"use client"; import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore, type CSSProperties, } from "react"; import { ArrowDown, ArrowUp, Columns2, Rows2, Maximize2, Minimize2, Plus, Search, X, } from "lucide-react"; import { Terminal as WTermTerminal, useTerminal } from "@wterm/react"; import type { SearchState, TerminalCore, WTerm, ShellIntegrationState, } from "@wterm/dom"; import { OutputReader } from "./output-reader"; import { ClipboardRequest, type ClipboardWriteRequest, } from "./clipboard-request"; import { TerminalConnection } from "../lib/terminal-connection"; import { SessionRecovery, RECOVERY_KEY, decodeOutput, } from "../lib/session-recovery"; import "@wterm/react/css"; import { MAX_PANES, adjacentPane, measureLayout, minimumSize, workspaceReducer, visibleSessions, shellLabel, type Session, type SessionStatus, } from "../lib/workspace-layout"; import { PaneDivider } from "./pane-divider"; import { AppearanceSettings, useAppearance } from "./appearance-settings"; import { TERMINAL_COLORS } from "../lib/appearance"; import { ShortcutSettings, useShortcuts } from "./shortcut-settings"; import { ariaShortcuts, matchCommand, shortcutTitle, type Shortcuts, } from "../lib/shortcuts"; function cwdLabel(cwd: string | null): string { if (!cwd) return "Starting…"; return cwd.replace(/[/\\]+$/, "") || "/"; } function disposeCore(core: TerminalCore): void { const disposable = core as TerminalCore & { dispose?: () => void }; disposable.dispose?.(); } function terminalPixelSize(terminal: WTerm): { width: number; height: number } { const rect = terminal.element.getBoundingClientRect(); return { width: Math.max(1, Math.round(rect.width)), height: Math.max(1, Math.round(rect.height)), }; } interface SessionTerminalProps { recovery: SessionRecovery; shortcuts: Shortcuts; registerFind: (id: string, open: () => void) => () => void; registerPrompt: ( id: string, navigate: (direction: -1 | 1) => void, ) => () => void; theme: "dark" | "light"; fontSize: number; session: Session; active: boolean; visible: boolean; debugEnabled: boolean; wasmUrl?: string; maxImageWidth?: number; maxImageHeight?: number; coreLoader?: () => Promise; onStatus: (id: string, status: SessionStatus) => void; onCwd: (id: string, cwd: string) => void; onDirectory: (id: string, uri: string) => void; onShell: (id: string, state: ShellIntegrationState) => void; } function SessionTerminal({ recovery, shortcuts, registerFind, registerPrompt, theme, fontSize, session, active, visible, debugEnabled, wasmUrl, maxImageWidth, maxImageHeight, coreLoader, onStatus, onCwd, onDirectory, onShell, }: SessionTerminalProps) { const [ready, setReady] = useState(false); const replaying = useRef(false); const attached = useRef(false); const leaving = useRef(false); const [log] = useState(() => recovery.get(session.id)); const [recoveryFailed, setRecoveryFailed] = useState(log.failed); const themeRef = useRef(theme); useLayoutEffect(() => { themeRef.current = theme; }, [theme]); const focusedRequest = useRef(0); const [core, setCore] = useState(null); const { ref, write } = useTerminal(); const wsRef = useRef(null); const terminalRef = useRef(null); const connectFrameRef = useRef(null); const disposedRef = useRef(false); const [findOpen, setFindOpen] = useState(false); const [connectionMessage, setConnectionMessage] = useState( null, ); const [reconnected, setReconnected] = useState(false); const [lostInput, setLostInput] = useState(false); const [announceOutput, setAnnounceOutput] = useState(false); const [query, setQuery] = useState(""); const [caseSensitive, setCaseSensitive] = useState(false); const [searchState, setSearchState] = useState(null); const findInputRef = useRef(null); useLayoutEffect(() => { if (replaying.current) return; terminalRef.current?.setThemeColors(TERMINAL_COLORS[theme]); log.append({ type: "theme", theme }); log.checkpoint(); setRecoveryFailed(log.failed); }, [theme, ready]); const openFind = useCallback(() => { setFindOpen(true); findInputRef.current?.focus(); findInputRef.current?.select(); }, []); const closeFind = () => { setFindOpen(false); terminalRef.current?.clearSearch(); terminalRef.current?.focus(); }; useLayoutEffect( () => registerFind(session.id, openFind), [registerFind, session.id, openFind], ); const navigatePrompt = useCallback((direction: -1 | 1) => { terminalRef.current?.scrollToPrompt(direction); }, []); useLayoutEffect( () => registerPrompt(session.id, navigatePrompt), [registerPrompt, session.id, navigatePrompt], ); useEffect(() => { if (findOpen) terminalRef.current?.search(query, { caseSensitive }); }, [query, caseSensitive, findOpen]); useEffect(() => { disposedRef.current = false; const pagehide = () => { leaving.current = true; wsRef.current?.detach(); }; window.addEventListener("pagehide", pagehide); return () => { window.removeEventListener("pagehide", pagehide); disposedRef.current = true; if (connectFrameRef.current !== null) { cancelAnimationFrame(connectFrameRef.current); connectFrameRef.current = null; } wsRef.current?.close(); wsRef.current = null; terminalRef.current = null; }; }, [recovery, session.id]); useEffect(() => { if (!coreLoader) return; let cancelled = false; onStatus(session.id, "loading"); coreLoader() .then((loadedCore) => { if (cancelled) { disposeCore(loadedCore); } else { setCore(loadedCore); } }) .catch(() => { if (!cancelled) onStatus(session.id, "closed"); }); return () => { cancelled = true; }; }, [coreLoader, onStatus, session.id]); useEffect(() => { return () => { if (core) disposeCore(core); }; }, [core]); useEffect(() => { if (!ready || focusedRequest.current === session.focusRequest) return; focusedRequest.current = session.focusRequest; if (!active || document.querySelector("dialog[open]")) return; terminalRef.current?.element.closest('[role="tabpanel"]')?.scrollIntoView({ block: "nearest", inline: "nearest", }); if (findOpen) findInputRef.current?.focus(); else ref.current?.focus(); }, [active, findOpen, ready, ref, session.focusRequest]); useEffect(() => { if (findOpen) findInputRef.current?.focus(); }, [findOpen]); const handleReady = useCallback( async (wt: WTerm) => { if (disposedRef.current) return; setReady(false); // A new parser cannot resume from the previous parser's byte position. if (terminalRef.current && terminalRef.current !== wt) { if (connectFrameRef.current !== null) { cancelAnimationFrame(connectFrameRef.current); connectFrameRef.current = null; } // Strict Mode can replace the core even after its first attachment. wsRef.current?.detach(); wsRef.current = null; } terminalRef.current = wt; const replay = log; const head = replay.saved; const saved = head?.session ? head : null; if ((log.restore || attached.current) && !saved) { setConnectionMessage( "This session could not be restored. Open a new terminal to start another shell.", ); onStatus(session.id, "closed"); return; } if (saved) { replaying.current = true; wt.autoResize = false; wt.setRenderingPaused(true); wt.resize(saved.cols, saved.rows); wt.setThemeColors(TERMINAL_COLORS[saved.theme]); let bytes = 0; try { for (const event of replay.replay) { if ( disposedRef.current || leaving.current || terminalRef.current !== wt ) return; if (event.type === "output") { const data = decodeOutput(event.data); wt.write(data); bytes += data.length; } else if (event.type === "resize") wt.resize(event.cols, event.rows); else wt.setThemeColors(TERMINAL_COLORS[event.theme]); if (bytes >= 32 * 1024) { bytes = 0; await new Promise((resolve) => setTimeout(resolve, 0)); } } } catch { replay.invalidate(); setRecoveryFailed(true); setConnectionMessage( "This session could not be restored. Open a new terminal to start another shell.", ); onStatus(session.id, "closed"); return; } finally { if (terminalRef.current === wt) replaying.current = false; wt.autoResize = true; } if ( disposedRef.current || leaving.current || terminalRef.current !== wt ) return; wt.fit(); } else replay.start(wt.cols, wt.rows, themeRef.current); wt.setThemeColors(TERMINAL_COLORS[themeRef.current]); replay.append({ type: "theme", theme: themeRef.current }); replay.checkpoint(); setReady(true); wt.onSearchChange = setSearchState; if (wsRef.current) return; // Let the first ResizeObserver pass settle before spawning the shell. // Otherwise zsh starts at 80x24, then redraws its prompt when the // terminal immediately resizes to the viewport dimensions. connectFrameRef.current = requestAnimationFrame(() => { connectFrameRef.current = null; if (disposedRef.current || wsRef.current) return; const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; const wsUrl = `${proto}//${window.location.host}/api/terminal`; onStatus(session.id, "connecting"); let restoredConnection = !!saved; const connection = new TerminalConnection( () => new WebSocket(wsUrl), { open: (resumed, inputLost) => { attached.current = true; const terminal = terminalRef.current; if (!terminal) return; const { width, height } = terminalPixelSize(terminal); setConnectionMessage(null); setReconnected(resumed && !restoredConnection); // `restoredConnection` belongs to this connection attempt, not render state; // oxlint's react/immutability misreads it. // oxlint-disable-next-line react/immutability restoredConnection = false; setLostInput((previous) => inputLost || (resumed && previous)); onStatus(session.id, "connected"); connection.resize(terminal.cols, terminal.rows, width, height); }, reconnecting: () => { setReconnected(false); setConnectionMessage( "Reconnecting… Input is paused until the session returns.", ); onStatus(session.id, "reconnecting"); }, write: (data) => { write(data); replay.write(data); }, cwd: (path) => onCwd(session.id, path), end: (message) => { if (disposedRef.current || wsRef.current !== connection) return; replay.invalidate(); setConnectionMessage(message); setReconnected(false); wsRef.current = null; onStatus(session.id, "closed"); }, inputError: setConnectionMessage, checkpoint: (state) => { replay.checkpoint(state); setRecoveryFailed(replay.failed); }, }, saved ?? undefined, ); wsRef.current = connection; }); }, [onCwd, onStatus, session.id, write], ); const handleData = useCallback((data: string) => { wsRef.current?.input(data); }, []); const [clipboardRequest, setClipboardRequest] = useState(null); const handleClipboardWrite = useCallback((text: string) => { if (replaying.current) return; setClipboardRequest({ text }); }, []); const handleResize = useCallback((cols: number, rows: number) => { if (replaying.current) return; const terminal = terminalRef.current; if (!terminal) return; log.append({ type: "resize", cols, rows }); log.checkpoint(); const { width, height } = terminalPixelSize(terminal); wsRef.current?.resize(cols, rows, width, height); }, []); if (coreLoader && !core) { return (
Loading terminal…
); } return (
{recoveryFailed && session.status !== "closed" && (

Refresh recovery is unavailable for this session. Keep this page open to continue using it.

)}
{session.shell && session.shell.phase !== "unknown" && (
{([-1, 1] as const).map((direction) => { const command = direction < 0 ? "previousPrompt" : "nextPrompt"; const label = direction < 0 ? "Previous prompt" : "Next prompt"; const Icon = direction < 0 ? ArrowUp : ArrowDown; return ( ); })}
)} {findOpen ? (
{ if (event.nativeEvent.isComposing) return; if (event.key === "Escape") { event.preventDefault(); closeFind(); } if (event.key === "Enter") { event.preventDefault(); if (event.shiftKey) terminalRef.current?.findPrevious(); else terminalRef.current?.findNext(); } }} > setQuery(event.target.value)} className="min-w-0 flex-1 rounded border border-[var(--workspace-border)] bg-[var(--workspace-bg)] px-2 py-1 outline-none focus:border-[var(--workspace-focus)]" /> {!query ? "" : searchState?.searching ? "Searching…" : searchState?.count ? `${searchState.activeIndex + 1} of ${searchState.count}${searchState.limited ? "+" : ""}` : "No matches"}
) : ( )}
{(reconnected || lostInput) && (
{reconnected && "Reconnected."} {lostInput && " Some input did not reach the shell and was not resent. Check the command line before continuing."}
)} {connectionMessage && (

{connectionMessage}

)} setClipboardRequest((current) => current === request ? null : current, ) } terminal={terminalRef} name={session.name} active={visible} />
onShell(session.id, state)} onWorkingDirectory={(uri) => onDirectory(session.id, uri)} onClipboardWrite={handleClipboardWrite} onResize={handleResize} aria-label={session.name} tabIndex={visible ? 0 : -1} className="local-terminal h-full w-full" style={ { borderRadius: 0, boxShadow: "none", padding: 0, "--term-font-size": `${fontSize}px`, "--term-row-height": `${Math.ceil(fontSize * 1.2)}px`, } as CSSProperties } />
); } interface SessionWorkspaceProps { wasmUrl?: string; maxImageWidth?: number; maxImageHeight?: number; coreLoader?: () => Promise; } const subscribeRecovery = () => () => {}; const serverRecovery = () => null; export function SessionWorkspace(props: SessionWorkspaceProps) { const [getRecovery] = useState(() => { let recovery: SessionRecovery | null = null; return () => { if (!recovery) { let storage: Storage | null = null; try { storage = window.sessionStorage; } catch {} const navigation = performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming | undefined; // `recovery` is created once inside the useState initializer, not during render; // oxlint's react/immutability misreads it. // oxlint-disable-next-line react/immutability recovery = new SessionRecovery( storage, `${RECOVERY_KEY}:${location.pathname}`, navigation?.type === "reload" || navigation?.type === "back_forward", ); } return recovery; }; }); const recovery = useSyncExternalStore( subscribeRecovery, getRecovery, serverRecovery, ); useEffect(() => { const restored = (event: PageTransitionEvent) => { if (event.persisted) location.reload(); }; window.addEventListener("pageshow", restored); return () => window.removeEventListener("pageshow", restored); }, []); return recovery ? : null; } function ReadyWorkspace({ recovery, wasmUrl, maxImageWidth, maxImageHeight, coreLoader, }: SessionWorkspaceProps & { recovery: SessionRecovery }) { const [workspace, dispatch] = useReducer(workspaceReducer, recovery.initial); const layoutSaved = useSyncExternalStore( recovery.subscribeLayoutSaved, recovery.getLayoutSaved, recovery.getLayoutSaved, ); useLayoutEffect(() => { recovery.saveLayout(workspace); }, [recovery, workspace]); const { shortcuts, saved: shortcutsSaved, update: updateShortcuts, } = useShortcuts(); const findHandlers = useRef(new Map void>()); const registerFind = useCallback((id: string, open: () => void) => { findHandlers.current.set(id, open); return () => { findHandlers.current.delete(id); }; }, []); const promptHandlers = useRef(new Map void>()); const registerPrompt = useCallback( (id: string, navigate: (direction: -1 | 1) => void) => { promptHandlers.current.set(id, navigate); return () => { promptHandlers.current.delete(id); }; }, [], ); const composing = useRef(false); const consumedKeys = useRef(new Set()); const newSessionButton = useRef(null); useEffect(() => { const blur = () => { composing.current = false; consumedKeys.current.clear(); }; window.addEventListener("blur", blur); return () => window.removeEventListener("blur", blur); }, []); useEffect(() => { if (!workspace.sessions.length) newSessionButton.current?.focus(); }, [workspace.sessions.length]); const { appearance, theme, ready: appearanceReady, saved, update, } = useAppearance(); const [debugEnabled] = useState( () => typeof window !== "undefined" && new URLSearchParams(window.location.search).has("debug"), ); const viewportRef = useRef(null); const [size, setSize] = useState({ width: 0, height: 0 }); useLayoutEffect(() => { const viewport = viewportRef.current!; const measure = () => { const width = viewport.clientWidth; const height = viewport.clientHeight; setSize((previous) => previous.width === width && previous.height === height ? previous : { width, height }, ); }; measure(); const observer = new ResizeObserver(measure); observer.observe(viewport); return () => observer.disconnect(); }, []); const displayLayout = workspace.zoomed && workspace.activeId ? { kind: "pane" as const, session: workspace.activeId } : workspace.layout; const minimum = minimumSize(displayLayout); const width = Math.max(size.width, minimum.width); const height = Math.max(size.height, minimum.height); const { panes, dividers } = measureLayout(displayLayout, width, height); const paneCount = Object.keys(panes).length; const layoutPaneCount = visibleSessions(workspace.layout).length; const handleStatus = useCallback((id: string, status: SessionStatus) => { dispatch({ type: "status", id, status }); }, []); const handleCwd = useCallback((id: string, cwd: string) => { dispatch({ type: "cwd", id, cwd }); }, []); const handleDirectory = useCallback((id: string, uri: string) => { dispatch({ type: "directory", id, uri }); }, []); const handleShell = useCallback( (id: string, shell: ShellIntegrationState) => { dispatch({ type: "shell", id, shell }); }, [], ); return (
{ composing.current = true; }} onCompositionEndCapture={() => { composing.current = false; }} onKeyUpCapture={(event) => { if (consumedKeys.current.delete(event.code)) { event.preventDefault(); event.stopPropagation(); } }} onKeyDownCapture={(event) => { if (event.repeat && consumedKeys.current.has(event.code)) { event.preventDefault(); event.stopPropagation(); return; } if (!event.repeat) consumedKeys.current.delete(event.code); if ( event.repeat || composing.current || event.defaultPrevented || !(event.target instanceof Element) || document.querySelector("dialog[open]") ) return; const command = matchCommand(shortcuts, event.nativeEvent); if (!command) return; const terminalInput = !!event.target.closest(".local-terminal"); const editing = !!event.target.closest( 'input, textarea, select, [contenteditable]:not([contenteditable="false"])', ); if ( !terminalInput && (editing || (command !== "find" && command !== "new")) ) return; const id = workspace.activeId; if (command !== "new" && !id) return; event.preventDefault(); event.stopPropagation(); consumedKeys.current.add(event.code); switch (command) { case "new": dispatch({ type: "add" }); break; case "close": recovery.remove(id!); dispatch({ type: "close", id: id! }); break; case "splitRight": case "splitDown": dispatch({ type: "split", id: id!, direction: command === "splitRight" ? "right" : "down", }); break; case "zoom": if (layoutPaneCount > 1) dispatch({ type: "zoom", id: id! }); break; case "find": findHandlers.current.get(id!)?.(); break; case "previousPrompt": case "nextPrompt": promptHandlers.current.get(id!)?.( command === "previousPrompt" ? -1 : 1, ); break; default: { const direction = { left: "ArrowLeft", right: "ArrowRight", up: "ArrowUp", down: "ArrowDown", } as const; const next = adjacentPane(panes, id!, direction[command]); if (next) dispatch({ type: "select", id: next }); } } }} >
{workspace.sessions.map((session) => { const active = session.id === workspace.activeId; const rect = panes[session.id]; const visible = !!rect; return (
1 ? (active ? "border-[var(--workspace-focus)]" : "border-[var(--workspace-border)]") : "border-transparent"}`} style={{ ...(rect ?? { left: 0, top: 0, width, height }), visibility: visible ? "visible" : "hidden", }} aria-hidden={!visible} inert={!visible} role="tabpanel" aria-label={session.name} onFocusCapture={() => dispatch({ type: "focus", id: session.id }) } onPointerDownCapture={() => dispatch({ type: "focus", id: session.id }) } >
{shellLabel(session) && ( {shellLabel(session)} )} {layoutPaneCount > 1 && ( )}
{appearanceReady && ( )}
); })} {dividers.map((divider) => ( dispatch({ type: "resize", id, ratio }) } /> ))} {workspace.sessions.length === 0 && (
)}
); }