|
| 1 | +import { useRef, useEffect, useState } from "react"; |
| 2 | +import { Terminal, FitAddon } from "ghostty-web"; |
| 3 | +import { useTerminalSession } from "@/hooks/useTerminalSession"; |
| 4 | + |
| 5 | +interface TerminalViewProps { |
| 6 | + workspaceId: string; |
| 7 | + sessionId?: string; |
| 8 | + visible: boolean; |
| 9 | +} |
| 10 | + |
| 11 | +export function TerminalView({ workspaceId, sessionId, visible }: TerminalViewProps) { |
| 12 | + const containerRef = useRef<HTMLDivElement>(null); |
| 13 | + const termRef = useRef<Terminal | null>(null); |
| 14 | + const fitAddonRef = useRef<FitAddon | null>(null); |
| 15 | + const [terminalError, setTerminalError] = useState<string | null>(null); |
| 16 | + const [terminalReady, setTerminalReady] = useState(false); |
| 17 | + const [terminalSize, setTerminalSize] = useState<{ cols: number; rows: number } | null>(null); |
| 18 | + |
| 19 | + // Handler for terminal output |
| 20 | + const handleOutput = (data: string) => { |
| 21 | + const term = termRef.current; |
| 22 | + if (term) { |
| 23 | + term.write(data); |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + // Handler for terminal exit |
| 28 | + const handleExit = (exitCode: number) => { |
| 29 | + const term = termRef.current; |
| 30 | + if (term) { |
| 31 | + term.write(`\r\n[Process exited with code ${exitCode}]\r\n`); |
| 32 | + } |
| 33 | + }; |
| 34 | + |
| 35 | + const { |
| 36 | + sendInput, |
| 37 | + resize, |
| 38 | + error: sessionError, |
| 39 | + } = useTerminalSession(workspaceId, sessionId, visible, terminalSize, handleOutput, handleExit); |
| 40 | + |
| 41 | + // Keep refs to latest functions so callbacks always use current version |
| 42 | + const sendInputRef = useRef(sendInput); |
| 43 | + const resizeRef = useRef(resize); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + sendInputRef.current = sendInput; |
| 47 | + resizeRef.current = resize; |
| 48 | + }, [sendInput, resize]); |
| 49 | + |
| 50 | + // Initialize terminal when visible |
| 51 | + useEffect(() => { |
| 52 | + if (!containerRef.current || !visible) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + let terminal: Terminal | null = null; |
| 57 | + |
| 58 | + const initTerminal = async () => { |
| 59 | + try { |
| 60 | + terminal = new Terminal({ |
| 61 | + fontSize: 13, |
| 62 | + fontFamily: "Monaco, Menlo, 'Courier New', monospace", |
| 63 | + cursorBlink: true, |
| 64 | + theme: { |
| 65 | + background: "#1e1e1e", |
| 66 | + foreground: "#d4d4d4", |
| 67 | + cursor: "#d4d4d4", |
| 68 | + cursorAccent: "#1e1e1e", |
| 69 | + selectionBackground: "#264f78", |
| 70 | + black: "#000000", |
| 71 | + red: "#cd3131", |
| 72 | + green: "#0dbc79", |
| 73 | + yellow: "#e5e510", |
| 74 | + blue: "#2472c8", |
| 75 | + magenta: "#bc3fbc", |
| 76 | + cyan: "#11a8cd", |
| 77 | + white: "#e5e5e5", |
| 78 | + brightBlack: "#666666", |
| 79 | + brightRed: "#f14c4c", |
| 80 | + brightGreen: "#23d18b", |
| 81 | + brightYellow: "#f5f543", |
| 82 | + brightBlue: "#3b8eea", |
| 83 | + brightMagenta: "#d670d6", |
| 84 | + brightCyan: "#29b8db", |
| 85 | + brightWhite: "#ffffff", |
| 86 | + }, |
| 87 | + }); |
| 88 | + |
| 89 | + const fitAddon = new FitAddon(); |
| 90 | + terminal.loadAddon(fitAddon); |
| 91 | + |
| 92 | + await terminal.open(containerRef.current!); |
| 93 | + fitAddon.fit(); |
| 94 | + |
| 95 | + const { cols, rows } = terminal; |
| 96 | + |
| 97 | + // Set terminal size so PTY session can be created with matching dimensions |
| 98 | + // Use stable object reference to prevent unnecessary effect re-runs |
| 99 | + setTerminalSize((prev) => { |
| 100 | + if (prev?.cols === cols && prev?.rows === rows) { |
| 101 | + return prev; |
| 102 | + } |
| 103 | + return { cols, rows }; |
| 104 | + }); |
| 105 | + |
| 106 | + // User input → IPC (use ref to always get latest sendInput) |
| 107 | + terminal.onData((data: string) => { |
| 108 | + sendInputRef.current(data); |
| 109 | + }); |
| 110 | + |
| 111 | + termRef.current = terminal; |
| 112 | + fitAddonRef.current = fitAddon; |
| 113 | + setTerminalReady(true); |
| 114 | + } catch (err) { |
| 115 | + console.error("Failed to initialize terminal:", err); |
| 116 | + setTerminalError(err instanceof Error ? err.message : "Failed to initialize terminal"); |
| 117 | + } |
| 118 | + }; |
| 119 | + |
| 120 | + void initTerminal(); |
| 121 | + |
| 122 | + return () => { |
| 123 | + if (terminal) { |
| 124 | + terminal.dispose(); |
| 125 | + } |
| 126 | + termRef.current = null; |
| 127 | + fitAddonRef.current = null; |
| 128 | + setTerminalReady(false); |
| 129 | + setTerminalSize(null); |
| 130 | + }; |
| 131 | + // Note: sendInput and resize are intentionally not in deps |
| 132 | + // They're used in callbacks, not during effect execution |
| 133 | + }, [visible, workspaceId]); |
| 134 | + |
| 135 | + // Resize on container size change |
| 136 | + useEffect(() => { |
| 137 | + if (!visible || !fitAddonRef.current || !containerRef.current || !termRef.current) { |
| 138 | + return; |
| 139 | + } |
| 140 | + |
| 141 | + let lastCols = 0; |
| 142 | + let lastRows = 0; |
| 143 | + let resizeTimeoutId: ReturnType<typeof setTimeout> | null = null; |
| 144 | + let pendingResize: { cols: number; rows: number } | null = null; |
| 145 | + |
| 146 | + // Use both ResizeObserver (for container changes) and window resize (as backup) |
| 147 | + const handleResize = () => { |
| 148 | + if (fitAddonRef.current && termRef.current) { |
| 149 | + try { |
| 150 | + // Resize terminal UI to fit container immediately for responsive UX |
| 151 | + fitAddonRef.current.fit(); |
| 152 | + |
| 153 | + // Get new dimensions |
| 154 | + const { cols, rows } = termRef.current; |
| 155 | + |
| 156 | + // Only process if dimensions actually changed |
| 157 | + if (cols === lastCols && rows === lastRows) { |
| 158 | + return; |
| 159 | + } |
| 160 | + |
| 161 | + lastCols = cols; |
| 162 | + lastRows = rows; |
| 163 | + |
| 164 | + // Update state (with stable reference to prevent unnecessary re-renders) |
| 165 | + setTerminalSize((prev) => { |
| 166 | + if (prev?.cols === cols && prev?.rows === rows) { |
| 167 | + return prev; |
| 168 | + } |
| 169 | + return { cols, rows }; |
| 170 | + }); |
| 171 | + |
| 172 | + // Store pending resize |
| 173 | + pendingResize = { cols, rows }; |
| 174 | + |
| 175 | + // Always debounce PTY resize to prevent vim corruption |
| 176 | + // Clear any pending timeout and set a new one |
| 177 | + if (resizeTimeoutId !== null) { |
| 178 | + clearTimeout(resizeTimeoutId); |
| 179 | + } |
| 180 | + |
| 181 | + resizeTimeoutId = setTimeout(() => { |
| 182 | + if (pendingResize) { |
| 183 | + console.log( |
| 184 | + `[TerminalView] Sending resize to PTY: ${pendingResize.cols}x${pendingResize.rows}` |
| 185 | + ); |
| 186 | + // Double requestAnimationFrame to ensure vim is ready |
| 187 | + requestAnimationFrame(() => { |
| 188 | + requestAnimationFrame(() => { |
| 189 | + if (pendingResize) { |
| 190 | + resizeRef.current(pendingResize.cols, pendingResize.rows); |
| 191 | + pendingResize = null; |
| 192 | + } |
| 193 | + }); |
| 194 | + }); |
| 195 | + } |
| 196 | + resizeTimeoutId = null; |
| 197 | + }, 300); // 300ms debounce - enough time for vim to stabilize |
| 198 | + } catch (err) { |
| 199 | + console.error("[TerminalView] Error fitting terminal:", err); |
| 200 | + } |
| 201 | + } |
| 202 | + }; |
| 203 | + |
| 204 | + const resizeObserver = new ResizeObserver(handleResize); |
| 205 | + resizeObserver.observe(containerRef.current); |
| 206 | + |
| 207 | + // Also listen to window resize as backup |
| 208 | + window.addEventListener("resize", handleResize); |
| 209 | + |
| 210 | + return () => { |
| 211 | + if (resizeTimeoutId !== null) { |
| 212 | + clearTimeout(resizeTimeoutId); |
| 213 | + } |
| 214 | + resizeObserver.disconnect(); |
| 215 | + window.removeEventListener("resize", handleResize); |
| 216 | + }; |
| 217 | + }, [visible, terminalReady]); // terminalReady ensures ResizeObserver is set up after terminal is initialized |
| 218 | + |
| 219 | + if (!visible) return null; |
| 220 | + |
| 221 | + const errorMessage = terminalError ?? sessionError; |
| 222 | + |
| 223 | + return ( |
| 224 | + <div |
| 225 | + className="terminal-view" |
| 226 | + style={{ |
| 227 | + width: "100%", |
| 228 | + height: "100%", |
| 229 | + backgroundColor: "#1e1e1e", |
| 230 | + }} |
| 231 | + > |
| 232 | + {errorMessage && ( |
| 233 | + <div className="border-b border-red-900/30 bg-red-900/20 p-2 text-sm text-red-400"> |
| 234 | + Terminal Error: {errorMessage} |
| 235 | + </div> |
| 236 | + )} |
| 237 | + <div |
| 238 | + ref={containerRef} |
| 239 | + className="terminal-container" |
| 240 | + style={{ |
| 241 | + width: "100%", |
| 242 | + height: "100%", |
| 243 | + overflow: "hidden", |
| 244 | + }} |
| 245 | + /> |
| 246 | + </div> |
| 247 | + ); |
| 248 | +} |
0 commit comments