diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 0d756f544..b959e0eec 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -2,11 +2,9 @@ import { Terminal as XTerm } from "@xterm/xterm"; import { FitAddon } from "@xterm/addon-fit"; import { SerializeAddon } from "@xterm/addon-serialize"; import { SearchAddon } from "@xterm/addon-search"; -import { WebglAddon } from "@xterm/addon-webgl"; -import { WebLinksAddon } from "@xterm/addon-web-links"; import "@xterm/xterm/css/xterm.css"; import { Maximize2, Radio } from "lucide-react"; -import React, { memo, useEffect, useMemo, useRef, useState, useCallback } from "react"; +import React, { memo, useEffect, useMemo, useRef, useState } from "react"; import { logger } from "../lib/logger"; import { cn } from "../lib/utils"; import { @@ -19,7 +17,6 @@ import { TerminalSettings, KeyBinding, } from "../types"; -import { checkAppShortcut, getAppLevelActions, getTerminalPassthroughActions } from "../application/state/useGlobalHotkeys"; import { useTerminalBackend } from "../application/state/useTerminalBackend"; import KnownHostConfirmDialog, { HostKeyInfo } from "./KnownHostConfirmDialog"; import SFTPModal from "./SFTPModal"; @@ -28,73 +25,64 @@ import { toast } from "./ui/toast"; import { TERMINAL_FONTS } from "../infrastructure/config/fonts"; import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes"; -// Import terminal sub-components import { TerminalConnectionDialog } from "./terminal/TerminalConnectionDialog"; import { TerminalToolbar } from "./terminal/TerminalToolbar"; import { TerminalContextMenu } from "./terminal/TerminalContextMenu"; import { TerminalSearchBar } from "./terminal/TerminalSearchBar"; import { createHighlightProcessor } from "./terminal/keywordHighlight"; -import { - XTERM_PERFORMANCE_CONFIG, - type XTermPlatform, - resolveXTermPerformanceConfig, -} from "../infrastructure/config/xtermPerformance"; +import { createTerminalSessionStarters, type PendingAuth } from "./terminal/runtime/createTerminalSessionStarters"; +import { createXTermRuntime, type XTermRuntime } from "./terminal/runtime/createXTermRuntime"; +import { XTERM_PERFORMANCE_CONFIG } from "../infrastructure/config/xtermPerformance"; +import { useTerminalSearch } from "./terminal/hooks/useTerminalSearch"; +import { useTerminalContextActions } from "./terminal/hooks/useTerminalContextActions"; +import { useTerminalAuthState } from "./terminal/hooks/useTerminalAuthState"; interface TerminalProps { host: Host; keys: SSHKey[]; snippets: Snippet[]; - allHosts?: Host[]; // All hosts for chain resolution - knownHosts?: KnownHost[]; // Known hosts for verification + allHosts?: Host[]; + knownHosts?: KnownHost[]; isVisible: boolean; inWorkspace?: boolean; isResizing?: boolean; - isFocusMode?: boolean; // Whether workspace is in focus mode - isFocused?: boolean; // Whether this terminal should have keyboard focus (for split views) + isFocusMode?: boolean; + isFocused?: boolean; fontSize: number; terminalTheme: TerminalTheme; - terminalSettings?: TerminalSettings; // Global terminal settings + terminalSettings?: TerminalSettings; sessionId: string; - startupCommand?: string; // Command to run after connection (for snippet runner) - // Hotkey configuration - hotkeyScheme?: 'disabled' | 'mac' | 'pc'; + startupCommand?: string; + hotkeyScheme?: "disabled" | "mac" | "pc"; keyBindings?: KeyBinding[]; - // Hotkey action callbacks onHotkeyAction?: (action: string, event: KeyboardEvent) => void; - onStatusChange?: ( - sessionId: string, - status: TerminalSession["status"], - ) => void; + onStatusChange?: (sessionId: string, status: TerminalSession["status"]) => void; onSessionExit?: (sessionId: string) => void; - onTerminalDataCapture?: (sessionId: string, data: string) => void; // Capture terminal data when session exits + onTerminalDataCapture?: (sessionId: string, data: string) => void; onOsDetected?: (hostId: string, distro: string) => void; onCloseSession?: (sessionId: string) => void; onUpdateHost?: (host: Host) => void; - onAddKnownHost?: (knownHost: KnownHost) => void; // Callback to add host to known hosts - onExpandToFocus?: () => void; // Callback to switch workspace to focus mode + onAddKnownHost?: (knownHost: KnownHost) => void; + onExpandToFocus?: () => void; onCommandExecuted?: ( command: string, hostId: string, hostLabel: string, sessionId: string, - ) => void; // Callback when a command is executed - // Split actions + ) => void; onSplitHorizontal?: () => void; onSplitVertical?: () => void; - // Broadcast mode isBroadcastEnabled?: boolean; onToggleBroadcast?: () => void; onBroadcastInput?: (data: string, sourceSessionId: string) => void; } -// xterm.js doesn't need async initialization like ghostty-web - const TerminalComponent: React.FC = ({ host, keys, snippets, allHosts = [], - knownHosts: _knownHosts = [], // Reserved for future host key verification UI + knownHosts: _knownHosts = [], isVisible, inWorkspace, isResizing, @@ -105,7 +93,7 @@ const TerminalComponent: React.FC = ({ terminalSettings, sessionId, startupCommand, - hotkeyScheme = 'disabled', + hotkeyScheme = "disabled", keyBindings = [], onHotkeyAction, onStatusChange, @@ -129,29 +117,25 @@ const TerminalComponent: React.FC = ({ const fitAddonRef = useRef(null); const serializeAddonRef = useRef(null); const searchAddonRef = useRef(null); + const xtermRuntimeRef = useRef(null); const disposeDataRef = useRef<(() => void) | null>(null); const disposeExitRef = useRef<(() => void) | null>(null); const sessionRef = useRef(null); const hasConnectedRef = useRef(false); - const hasRunStartupCommandRef = useRef(false); // Track if startup command has been executed - const commandBufferRef = useRef(""); // Buffer for tracking typed commands + const hasRunStartupCommandRef = useRef(false); + const commandBufferRef = useRef(""); - // Ref to store latest terminalSettings for use in boot function (avoids stale closure) const terminalSettingsRef = useRef(terminalSettings); terminalSettingsRef.current = terminalSettings; - // Keyword highlight processor - processes terminal output for keyword highlighting const highlightProcessorRef = useRef<(text: string) => string>((t) => t); - - // Update highlight processor when settings change useEffect(() => { highlightProcessorRef.current = createHighlightProcessor( terminalSettings?.keywordHighlightRules ?? [], - terminalSettings?.keywordHighlightEnabled ?? false + terminalSettings?.keywordHighlightEnabled ?? false, ); }, [terminalSettings?.keywordHighlightEnabled, terminalSettings?.keywordHighlightRules]); - // Refs to store latest hotkey config for use in keyboard handler const hotkeySchemeRef = useRef(hotkeyScheme); const keyBindingsRef = useRef(keyBindings); const onHotkeyActionRef = useRef(onHotkeyAction); @@ -159,7 +143,6 @@ const TerminalComponent: React.FC = ({ keyBindingsRef.current = keyBindings; onHotkeyActionRef.current = onHotkeyAction; - // Refs for broadcast mode (to avoid stale closures) const isBroadcastEnabledRef = useRef(isBroadcastEnabled); const onBroadcastInputRef = useRef(onBroadcastInput); isBroadcastEnabledRef.current = isBroadcastEnabled; @@ -180,31 +163,23 @@ const TerminalComponent: React.FC = ({ const [progressValue, setProgressValue] = useState(15); const [hasSelection, setHasSelection] = useState(false); - // Search state - const [isSearchOpen, setIsSearchOpen] = useState(false); - const [searchMatchCount, setSearchMatchCount] = useState<{ current: number; total: number } | null>(null); - const searchTermRef = useRef(''); // Store current search term for findNext/findPrevious - - // Chain connection progress state const [chainProgress, setChainProgress] = useState<{ currentHop: number; totalHops: number; currentHostLabel: string; } | null>(null); - // Auth dialog state for hosts without credentials - const [needsAuth, setNeedsAuth] = useState(false); - const [authRetryMessage, setAuthRetryMessage] = useState(null); // Error message for auth retry - const [authUsername, setAuthUsername] = useState(host.username || "root"); - const [authMethod, setAuthMethod] = useState< - "password" | "key" | "certificate" - >("password"); - const [authPassword, setAuthPassword] = useState(""); - const [authKeyId, setAuthKeyId] = useState(null); - const [authPassphrase, setAuthPassphrase] = useState(""); - const [showAuthPassword, setShowAuthPassword] = useState(false); - const [showAuthPassphrase, setShowAuthPassphrase] = useState(false); - const [saveCredentials, setSaveCredentials] = useState(true); + const terminalSearch = useTerminalSearch({ searchAddonRef, termRef }); + const { + isSearchOpen, + setIsSearchOpen, + searchMatchCount, + handleToggleSearch, + handleSearch, + handleFindNext, + handleFindPrevious, + handleCloseSearch, + } = terminalSearch; useEffect(() => { if (!error) { @@ -216,32 +191,32 @@ const TerminalComponent: React.FC = ({ toast.error(error, "Connection Error"); }, [error]); - // Pending connection credentials (set after auth dialog submit) - const pendingAuthRef = useRef<{ - authMethod: "password" | "key" | "certificate"; - username: string; - password?: string; - keyId?: string; - passphrase?: string; - } | null>(null); + const pendingAuthRef = useRef(null); + const sessionStartersRef = useRef | null>(null); + const auth = useTerminalAuthState({ + host, + pendingAuthRef, + termRef, + onUpdateHost, + onStartSsh: (term) => { + sessionStartersRef.current?.startSSH(term); + }, + setStatus: (next) => setStatus(next), + setProgressLogs, + }); - // Known host verification state - const [needsHostKeyVerification, setNeedsHostKeyVerification] = - useState(false); - const [pendingHostKeyInfo, setPendingHostKeyInfo] = - useState(null); + const [needsHostKeyVerification, setNeedsHostKeyVerification] = useState(false); + const [pendingHostKeyInfo, setPendingHostKeyInfo] = useState(null); const pendingConnectionRef = useRef<(() => void) | null>(null); - // Calculate effective theme: host-specific theme takes priority over global const effectiveTheme = useMemo(() => { if (host.theme) { - const hostTheme = TERMINAL_THEMES.find(t => t.id === host.theme); + const hostTheme = TERMINAL_THEMES.find((t) => t.id === host.theme); if (hostTheme) return hostTheme; } return terminalTheme; }, [host.theme, terminalTheme]); - // Resolve host chain to actual host objects const resolvedChainHosts = (host.hostChain?.hostIds ?.map((id) => allHosts.find((h) => h.id === id)) @@ -271,42 +246,49 @@ const TerminalComponent: React.FC = ({ const teardown = () => { cleanupSession(); - termRef.current?.dispose(); + xtermRuntimeRef.current?.dispose(); + xtermRuntimeRef.current = null; termRef.current = null; - fitAddonRef.current?.dispose(); fitAddonRef.current = null; - serializeAddonRef.current?.dispose(); serializeAddonRef.current = null; - searchAddonRef.current?.dispose(); searchAddonRef.current = null; }; - const runDistroDetection = async (key?: SSHKey) => { - if (!terminalBackend.execAvailable()) return; - try { - const res = await terminalBackend.execCommand({ - hostname: host.hostname, - username: host.username || "root", - port: host.port || 22, - password: host.password, // Always include for fallback - privateKey: key?.privateKey, - command: "cat /etc/os-release 2>/dev/null || uname -a", - timeout: 8000, - }); - const data = `${res.stdout || ""}\n${res.stderr || ""}`; - const idMatch = data.match(/ID=([\\w\\-]+)/i); - const distro = idMatch - ? idMatch[1].replace(/"/g, "") - : (data.split(/\\s+/)[0] || "").toLowerCase(); - if (distro) onOsDetected?.(host.id, distro); - } catch (err) { - logger.warn("OS probe failed", err); - } - }; + const sessionStarters = createTerminalSessionStarters({ + host, + keys, + resolvedChainHosts, + sessionId, + startupCommand, + terminalSettings, + terminalBackend, + sessionRef, + hasConnectedRef, + hasRunStartupCommandRef, + disposeDataRef, + disposeExitRef, + fitAddonRef, + serializeAddonRef, + highlightProcessorRef, + pendingAuthRef, + updateStatus, + setStatus, + setError, + setNeedsAuth: auth.setNeedsAuth, + setAuthRetryMessage: auth.setAuthRetryMessage, + setAuthPassword: auth.setAuthPassword, + setProgressLogs, + setProgressValue, + setChainProgress, + onSessionExit, + onTerminalDataCapture, + onOsDetected, + onCommandExecuted, + }); + sessionStartersRef.current = sessionStarters; useEffect(() => { let disposed = false; - // Don't set status yet - will determine after checking auth requirements setError(null); hasConnectedRef.current = false; setProgressLogs([]); @@ -317,410 +299,47 @@ const TerminalComponent: React.FC = ({ try { if (disposed || !containerRef.current) return; - const platform: XTermPlatform = (() => { - if ( - typeof process !== "undefined" && - (process.platform === "darwin" || - process.platform === "win32" || - process.platform === "linux") - ) { - return process.platform; - } - - if (typeof navigator !== "undefined") { - const ua = navigator.userAgent.toLowerCase(); - if (ua.includes("win")) return "win32"; - if (ua.includes("linux")) return "linux"; - } - - return "darwin"; - })(); - - const deviceMemoryGb = - typeof navigator !== "undefined" && - typeof (navigator as { deviceMemory?: number }).deviceMemory === "number" - ? (navigator as { deviceMemory?: number }).deviceMemory - : undefined; - - const performanceConfig = resolveXTermPerformanceConfig({ - platform, - deviceMemoryGb, + const runtime = createXTermRuntime({ + container: containerRef.current, + host, + fontSize, + terminalTheme, + terminalSettingsRef, + terminalBackend, + sessionRef, + hotkeySchemeRef, + keyBindingsRef, + onHotkeyActionRef, + isBroadcastEnabledRef, + onBroadcastInputRef, + sessionId, + status, + onCommandExecuted, + commandBufferRef, + setIsSearchOpen, }); - // Get font family from host config or use default fallback - const hostFontId = host.fontFamily || 'menlo'; - const fontObj = TERMINAL_FONTS.find(f => f.id === hostFontId) || TERMINAL_FONTS[0]; - const fontFamily = fontObj.family; + xtermRuntimeRef.current = runtime; + termRef.current = runtime.term; + fitAddonRef.current = runtime.fitAddon; + serializeAddonRef.current = runtime.serializeAddon; + searchAddonRef.current = runtime.searchAddon; - // Use host-specific font size if available, otherwise use the global fontSize prop - const effectiveFontSize = host.fontSize || fontSize; - - // Apply terminal settings with defaults (use ref to get latest values) - const settings = terminalSettingsRef.current; - const cursorStyle = settings?.cursorShape ?? 'block'; - const cursorBlink = settings?.cursorBlink ?? true; - const scrollback = settings?.scrollback ?? 10000; - const fontLigatures = settings?.fontLigatures ?? true; - const drawBoldTextInBrightColors = settings?.drawBoldInBrightColors ?? true; - const fontWeight = settings?.fontWeight ?? 400; - const fontWeightBold = settings?.fontWeightBold ?? 700; - // linePadding 0-10 maps to lineHeight 1.0-2.0 - const lineHeight = 1 + (settings?.linePadding ?? 0) / 10; - const minimumContrastRatio = settings?.minimumContrastRatio ?? 1; - const scrollOnUserInput = settings?.scrollOnInput ?? true; - const altIsMeta = settings?.altAsMeta ?? false; - const wordSeparator = settings?.wordSeparators ?? " ()[]{}'\""; - - const term = new XTerm({ - ...performanceConfig.options, - fontSize: effectiveFontSize, - fontFamily: fontFamily, - fontWeight: fontWeight as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'normal' | 'bold', - fontWeightBold: fontWeightBold as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'normal' | 'bold', - lineHeight, - cursorStyle, - cursorBlink, - scrollback, - allowProposedApi: fontLigatures, // Required for font ligatures - drawBoldTextInBrightColors, - minimumContrastRatio, - scrollOnUserInput, - altClickMovesCursor: !altIsMeta, // If altAsMeta is true, don't use alt for cursor movement - wordSeparator, - theme: { - ...terminalTheme.colors, - selectionBackground: terminalTheme.colors.selection, - }, - }); - - type MaybeRenderer = { - constructor?: { name?: string }; - type?: string; - }; - - type IntrospectableTerminal = XTerm & { - _core?: { - _renderService?: { - _renderer?: MaybeRenderer; - }; - }; - options?: { - rendererType?: string; - }; - }; - - const logRenderer = (attempt = 0) => { - // Peek into private renderer to tell if WebGL is active; stored on window for DevTools checks - const introspected = term as IntrospectableTerminal; - const renderer = introspected._core?._renderService?._renderer; - const candidates = [ - renderer?.type, - renderer?.constructor?.name, - introspected.options?.rendererType, - ]; - const rendererName = - candidates.find((value) => typeof value === "string" && value.length > 0) || - undefined; - const normalized = rendererName - ? rendererName.toLowerCase().includes("webgl") - ? "webgl" - : rendererName.toLowerCase().includes("canvas") - ? "canvas" - : rendererName - : "unknown"; - logger.info(`[XTerm] renderer=${normalized}`); - const scopedWindow = window as Window & { __xtermRenderer?: string }; - scopedWindow.__xtermRenderer = normalized; - if (normalized === "unknown" && attempt < 3) { - setTimeout(() => logRenderer(attempt + 1), 150); - } - }; - - const fitAddon = new FitAddon(); - term.loadAddon(fitAddon); - termRef.current = term; - fitAddonRef.current = fitAddon; - - const serializeAddon = new SerializeAddon(); - term.loadAddon(serializeAddon); - serializeAddonRef.current = serializeAddon; - - // Load search addon for terminal text search - const searchAddon = new SearchAddon(); - term.loadAddon(searchAddon); - searchAddonRef.current = searchAddon; - - try { - term.open(containerRef.current); - - // Load WebGL addon for GPU-accelerated rendering unless canvas is preferred for macOS/low-memory profiles - let webglLoaded = false; - const scopedWindow = window as Window & { - __xtermWebGLLoaded?: boolean; - __xtermRendererPreference?: string; - }; - - if (performanceConfig.useWebGLAddon) { - try { - // Try enabling the new glyph handler for faster glyph caching if supported by the addon version - const webglAddon = (() => { - const webglOptions: Record = { - useCustomGlyphHandler: true, - }; - try { - // xterm-addon-webgl >=0.18 supports this flag; older versions ignore/fail so we guard - const WebglCtor = WebglAddon as unknown as new ( - options?: unknown, - ) => WebglAddon; - return new WebglCtor(webglOptions); - } catch { - return new WebglAddon(); - } - })(); - webglAddon.onContextLoss(() => { - logger.warn("[XTerm] WebGL context loss detected, disposing addon"); - webglAddon.dispose(); - }); - term.loadAddon(webglAddon); - webglLoaded = true; - } catch (webglErr) { - logger.warn( - "[XTerm] WebGL addon failed, using canvas renderer. Error:", - webglErr instanceof Error ? webglErr.message : webglErr, - ); - // Canvas renderer will be used as fallback - it's actually faster on some Macs - } - } else { - logger.info( - "[XTerm] Skipping WebGL addon (canvas preferred for macOS profile or low-memory devices)", - ); - } - - // Store whether WebGL was successfully loaded for diagnostics - scopedWindow.__xtermWebGLLoaded = webglLoaded; - scopedWindow.__xtermRendererPreference = performanceConfig.preferCanvasRenderer ? "canvas" : "webgl"; - - // Load web links addon for clickable URLs - const webLinksAddon = new WebLinksAddon((event, uri) => { - // Check if the required modifier key is held (read from ref for real-time updates) - const currentLinkModifier = terminalSettingsRef.current?.linkModifier ?? 'none'; - let shouldOpen = false; - switch (currentLinkModifier) { - case 'none': - shouldOpen = true; - break; - case 'ctrl': - shouldOpen = event.ctrlKey; - break; - case 'alt': - shouldOpen = event.altKey; - break; - case 'meta': - shouldOpen = event.metaKey; - break; - } - if (shouldOpen) { - // Open URL in default browser - if (terminalBackend.openExternalAvailable()) { - void terminalBackend.openExternal(uri); - } else { - window.open(uri, '_blank'); - } - } - }); - term.loadAddon(webLinksAddon); - - logRenderer(); - - // Attach custom key event handler to intercept app-level shortcuts - // This allows keyboard shortcuts to work even when terminal is focused - // Always attach the handler - it will check the ref values dynamically - const appLevelActions = getAppLevelActions(); - const terminalActions = getTerminalPassthroughActions(); - - term.attachCustomKeyEventHandler((e: KeyboardEvent) => { - // Handle Ctrl+F / Cmd+F for search regardless of hotkey settings - if ((e.ctrlKey || e.metaKey) && e.key === 'f' && e.type === 'keydown') { - e.preventDefault(); - setIsSearchOpen(true); - return false; - } - - // Read current values from refs - const currentScheme = hotkeySchemeRef.current; - const currentBindings = keyBindingsRef.current; - const hotkeyCallback = onHotkeyActionRef.current; - - // Skip if hotkeys are disabled - if (currentScheme === 'disabled' || currentBindings.length === 0) { - return true; // Let xterm handle it - } - - const isMac = currentScheme === 'mac'; - - // Check if this matches any of our shortcuts - const matched = checkAppShortcut(e, currentBindings, isMac); - if (!matched) return true; // Let xterm handle it - - const { action } = matched; - - // App-level actions: call the callback directly and prevent xterm from handling - if (appLevelActions.has(action)) { - e.preventDefault(); - if (hotkeyCallback) { - hotkeyCallback(action, e); - } - return false; - } - - // Terminal-level actions: handle here - if (terminalActions.has(action)) { - e.preventDefault(); - switch (action) { - case 'copy': { - const selection = term.getSelection(); - if (selection) { - navigator.clipboard.writeText(selection); - } - break; - } - case 'paste': { - navigator.clipboard.readText().then((text) => { - const id = sessionRef.current; - if (id) terminalBackend.writeToSession(id, text); - }); - break; - } - case 'selectAll': { - term.selectAll(); - break; - } - case 'clearBuffer': { - term.clear(); - break; - } - case 'searchTerminal': { - // Open search UI - setIsSearchOpen(true); - break; - } - } - return false; - } - - return true; // Let xterm handle other keys - }); - - // Add middle-click paste support - const middleClickPaste = settings?.middleClickPaste ?? true; - if (middleClickPaste && containerRef.current) { - const handleMiddleClick = async (e: MouseEvent) => { - if (e.button === 1) { // Middle mouse button - e.preventDefault(); - try { - const text = await navigator.clipboard.readText(); - if (text && sessionRef.current) { - terminalBackend.writeToSession(sessionRef.current, text); - } - } catch (err) { - logger.warn('[Terminal] Failed to paste from clipboard:', err); - } - } - }; - containerRef.current.addEventListener('auxclick', handleMiddleClick); - // Store cleanup function - const container = containerRef.current; - const cleanup = () => container.removeEventListener('auxclick', handleMiddleClick); - // Add to disposal - we'll handle this in the main cleanup - const originalDispose = disposeDataRef.current; - disposeDataRef.current = () => { - cleanup(); - originalDispose?.(); - }; - } - - fitAddon.fit(); - term.focus(); - } catch (openErr) { - logger.error("[XTerm] Failed to open terminal:", openErr); - throw openErr; - } - - term.onData((data) => { - const id = sessionRef.current; - if (id) { - terminalBackend.writeToSession(id, data); - - // Broadcast input to other terminals in the same workspace - if (isBroadcastEnabledRef.current && onBroadcastInputRef.current) { - onBroadcastInputRef.current(data, sessionId); - } - - // Track command input for shell history - if (status === "connected" && onCommandExecuted) { - // Handle control characters - if (data === "\r" || data === "\n") { - // Enter pressed - command submitted - const cmd = commandBufferRef.current.trim(); - if (cmd) { - onCommandExecuted(cmd, host.id, host.label, sessionId); - } - commandBufferRef.current = ""; - } else if (data === "\x7f" || data === "\b") { - // Backspace - remove last character - commandBufferRef.current = commandBufferRef.current.slice( - 0, - -1, - ); - } else if (data === "\x03") { - // Ctrl+C - clear buffer - commandBufferRef.current = ""; - } else if (data === "\x15") { - // Ctrl+U - clear line - commandBufferRef.current = ""; - } else if (data.length === 1 && data.charCodeAt(0) >= 32) { - // Regular printable character - commandBufferRef.current += data; - } else if (data.length > 1 && !data.startsWith("\x1b")) { - // Pasted text (multiple chars, not escape sequence) - commandBufferRef.current += data; - } - } - } - }); - - // Add debouncing for resize events to prevent excessive calls on macOS - let resizeTimeout: NodeJS.Timeout | null = null; - const resizeDebounceMs = XTERM_PERFORMANCE_CONFIG.resize.debounceMs; - term.onResize(({ cols, rows }) => { - const id = sessionRef.current; - if (id) { - // Debounce resize to prevent rapid successive calls - if (resizeTimeout) { - clearTimeout(resizeTimeout); - } - resizeTimeout = setTimeout(() => { - terminalBackend.resizeSession(id, cols, rows); - resizeTimeout = null; - }, resizeDebounceMs); // Debounce for smooth resizing on macOS - } - }); + const term = runtime.term; if (host.protocol === "local" || host.hostname === "localhost") { setStatus("connecting"); setProgressLogs(["Initializing local shell..."]); - await startLocal(term); + await sessionStarters.startLocal(term); } else if (host.protocol === "telnet") { setStatus("connecting"); setProgressLogs(["Initializing Telnet connection..."]); - await startTelnet(term); + await sessionStarters.startTelnet(term); } else if (host.moshEnabled) { setStatus("connecting"); setProgressLogs(["Initializing Mosh connection..."]); - await startMosh(term); + await sessionStarters.startMosh(term); } else { - // SSH connection (default) - // Check if host needs authentication info const hasPassword = host.authMethod === "password" && host.password; const hasKey = (host.authMethod === "key" || host.authMethod === "certificate") && @@ -728,16 +347,14 @@ const TerminalComponent: React.FC = ({ const hasPendingAuth = pendingAuthRef.current; if (!hasPassword && !hasKey && !hasPendingAuth && !host.username) { - // No auth info available - show auth dialog without starting connection - setNeedsAuth(true); - // Keep status as disconnected - don't trigger timeout timer + auth.setNeedsAuth(true); setStatus("disconnected"); return; } setStatus("connecting"); setProgressLogs(["Initializing secure channel..."]); - await startSSH(term); + await sessionStarters.startSSH(term); } } catch (err) { logger.error("Failed to initialize terminal", err); @@ -750,7 +367,6 @@ const TerminalComponent: React.FC = ({ return () => { disposed = true; - // Capture terminal data before teardown if callback is provided if (onTerminalDataCapture && serializeAddonRef.current) { try { const terminalData = serializeAddonRef.current.serialize(); @@ -767,8 +383,7 @@ const TerminalComponent: React.FC = ({ // Connection timeline and timeout visuals useEffect(() => { - // Don't run timeout timer when showing auth dialog (user is entering credentials) - if (status !== "connecting" || needsAuth) return; + if (status !== "connecting" || auth.needsAuth) return; const scripted = [ "Resolving host and keys...", "Negotiating ciphers...", @@ -800,13 +415,11 @@ const TerminalComponent: React.FC = ({ const prog = setInterval(() => { setProgressValue((prev) => { if (prev >= 95) return prev; - // Smooth asymptotic approach - slows down as it gets higher const remaining = 95 - prev; - // Larger increment since we update less frequently (200ms instead of 100ms) const increment = Math.max(1, remaining * 0.15); return Math.min(95, prev + increment); }); - }, 200); // Reduced from 100ms to 200ms to cut re-renders in half + }, 200); return () => { clearInterval(stepTimer); @@ -815,7 +428,7 @@ const TerminalComponent: React.FC = ({ clearInterval(prog); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- updateStatus is a stable internal helper - }, [status, needsAuth]); + }, [status, auth.needsAuth]); const safeFit = () => { const fitAddon = fitAddonRef.current; @@ -829,93 +442,93 @@ const TerminalComponent: React.FC = ({ } }; - if (XTERM_PERFORMANCE_CONFIG.resize.useRAF && typeof requestAnimationFrame === "function") { + if ( + XTERM_PERFORMANCE_CONFIG.resize.useRAF && + typeof requestAnimationFrame === "function" + ) { requestAnimationFrame(runFit); } else { runFit(); } }; - // Effect for global fontSize/terminalTheme/terminalSettings changes (from Settings) useEffect(() => { if (termRef.current) { - // Only apply global settings if host doesn't have specific overrides const effectiveFontSize = host.fontSize || fontSize; termRef.current.options.fontSize = effectiveFontSize; - // Use effectiveTheme which respects host-specific theme override termRef.current.options.theme = { ...effectiveTheme.colors, selectionBackground: effectiveTheme.colors.selection, }; - // Apply all terminal settings for real-time updates if (terminalSettings) { - // Cursor settings termRef.current.options.cursorStyle = terminalSettings.cursorShape; termRef.current.options.cursorBlink = terminalSettings.cursorBlink; - - // Buffer settings termRef.current.options.scrollback = terminalSettings.scrollback; - - // Font settings - termRef.current.options.fontWeight = terminalSettings.fontWeight as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; - termRef.current.options.fontWeightBold = terminalSettings.fontWeightBold as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; + termRef.current.options.fontWeight = terminalSettings.fontWeight as + | 100 + | 200 + | 300 + | 400 + | 500 + | 600 + | 700 + | 800 + | 900; + termRef.current.options.fontWeightBold = terminalSettings.fontWeightBold as + | 100 + | 200 + | 300 + | 400 + | 500 + | 600 + | 700 + | 800 + | 900; termRef.current.options.lineHeight = 1 + terminalSettings.linePadding / 10; - termRef.current.options.drawBoldTextInBrightColors = terminalSettings.drawBoldInBrightColors; - - // Accessibility - termRef.current.options.minimumContrastRatio = terminalSettings.minimumContrastRatio; - - // Input behavior + termRef.current.options.drawBoldTextInBrightColors = + terminalSettings.drawBoldInBrightColors; + termRef.current.options.minimumContrastRatio = + terminalSettings.minimumContrastRatio; termRef.current.options.scrollOnUserInput = terminalSettings.scrollOnInput; termRef.current.options.altClickMovesCursor = !terminalSettings.altAsMeta; termRef.current.options.wordSeparator = terminalSettings.wordSeparators; } - // Refit after settings change (especially important for lineHeight changes) setTimeout(() => safeFit(), 50); } }, [fontSize, effectiveTheme, terminalSettings, host.fontSize]); - // Effect for host-specific font/theme changes (from ThemeCustomizeModal) useEffect(() => { if (termRef.current) { - // Apply host-specific font size const effectiveFontSize = host.fontSize || fontSize; termRef.current.options.fontSize = effectiveFontSize; - // Apply host-specific font family - const hostFontId = host.fontFamily || 'menlo'; - const fontObj = TERMINAL_FONTS.find(f => f.id === hostFontId) || TERMINAL_FONTS[0]; + const hostFontId = host.fontFamily || "menlo"; + const fontObj = TERMINAL_FONTS.find((f) => f.id === hostFontId) || TERMINAL_FONTS[0]; termRef.current.options.fontFamily = fontObj.family; - // Apply effective theme (host-specific or global) termRef.current.options.theme = { ...effectiveTheme.colors, selectionBackground: effectiveTheme.colors.selection, }; - // Refit after changes setTimeout(() => safeFit(), 50); } }, [host.fontSize, host.fontFamily, host.theme, fontSize, effectiveTheme]); - // Separate effect for visibility-triggered fit (less frequent) useEffect(() => { if (isVisible && fitAddonRef.current) { - // Small delay to ensure container is properly sized const timer = setTimeout(() => safeFit(), 50); return () => clearTimeout(timer); } }, [isVisible]); - // Re-fit once webfonts are ready so canvas sizing uses correct font metrics useEffect(() => { let cancelled = false; const waitForFonts = async () => { try { - // FontFaceSet is available in modern browsers const fontFaceSet = document.fonts as FontFaceSet | undefined; if (!fontFaceSet?.ready) return; await fontFaceSet.ready; @@ -958,21 +571,16 @@ const TerminalComponent: React.FC = ({ }; }, [host.id, sessionId, resizeSession]); - // Debounced fit for resize operations - only fit when not actively resizing useEffect(() => { if (!containerRef.current || !fitAddonRef.current) return; let resizeTimeout: ReturnType | null = null; const observer = new ResizeObserver(() => { - // Skip fit during active resize drag if (isResizing) return; - - // Clear previous timeout if (resizeTimeout) { clearTimeout(resizeTimeout); } - // Wait 250ms after last resize event before fitting (increased for performance) resizeTimeout = setTimeout(() => { safeFit(); }, 250); @@ -985,11 +593,9 @@ const TerminalComponent: React.FC = ({ }; }, [isVisible, isResizing]); - // Fit when resizing ends (isResizing changes from true to false) const prevIsResizingRef = useRef(isResizing); useEffect(() => { if (prevIsResizingRef.current && !isResizing && isVisible) { - // Resizing just ended, fit the terminal const timer = setTimeout(() => { safeFit(); }, 100); @@ -998,23 +604,17 @@ const TerminalComponent: React.FC = ({ prevIsResizingRef.current = isResizing; }, [isResizing, isVisible]); - // Re-fit when inWorkspace changes (terminal moves into/out of workspace) useEffect(() => { if (!isVisible || !fitAddonRef.current) return; - // Delay fit to allow layout changes to complete const timer = setTimeout(() => { safeFit(); }, 100); return () => clearTimeout(timer); }, [inWorkspace, isVisible]); - // Auto-focus terminal when tab becomes visible (only for solo tabs, not split views) useEffect(() => { - // In split view mode (inWorkspace && !isFocusMode), focus is controlled by isFocused prop - // Only auto-focus for solo tabs or focus mode const shouldAutoFocus = isVisible && termRef.current && (!inWorkspace || isFocusMode); if (shouldAutoFocus) { - // Small delay to ensure the tab switch animation completes const timer = setTimeout(() => { termRef.current?.focus(); }, 50); @@ -1022,10 +622,8 @@ const TerminalComponent: React.FC = ({ } }, [isVisible, inWorkspace, isFocusMode]); - // Focus terminal when isFocused prop becomes true (for split view navigation) useEffect(() => { if (isFocused && termRef.current && isVisible) { - // Small delay to ensure state updates complete const timer = setTimeout(() => { termRef.current?.focus(); }, 10); @@ -1033,7 +631,6 @@ const TerminalComponent: React.FC = ({ } }, [isFocused, isVisible, sessionId]); - // Track terminal selection for context menu and copyOnSelect useEffect(() => { const term = termRef.current; if (!term) return; @@ -1043,27 +640,23 @@ const TerminalComponent: React.FC = ({ const hasText = !!selection && selection.length > 0; setHasSelection(hasText); - // Copy on select if enabled if (hasText && terminalSettings?.copyOnSelect) { - navigator.clipboard.writeText(selection).catch(err => { - logger.warn('Copy on select failed:', err); + navigator.clipboard.writeText(selection).catch((err) => { + logger.warn("Copy on select failed:", err); }); } }; term.onSelectionChange(onSelectionChange); - // No need to return cleanup as xterm handles it when disposed }, [terminalSettings?.copyOnSelect]); useEffect(() => { let resizeTimeout: ReturnType | null = null; const handler = () => { - // Clear previous timeout if (resizeTimeout) { clearTimeout(resizeTimeout); } - // Wait 250ms after last resize event before fitting (increased for performance) resizeTimeout = setTimeout(() => { safeFit(); }, 250); @@ -1076,520 +669,12 @@ const TerminalComponent: React.FC = ({ }; }, []); - const startSSH = async (term: XTerm) => { - try { - term.clear?.(); - } catch (err) { - logger.warn("Failed to clear terminal before connect", err); - } - - if (!terminalBackend.backendAvailable()) { - setError("Native SSH bridge unavailable. Launch via Electron app."); - term.writeln( - "\r\n[netcatty SSH bridge unavailable. Please run the desktop build to connect.]", - ); - updateStatus("disconnected"); - return; - } - - // Use pending auth if available, otherwise use host config - const pendingAuth = pendingAuthRef.current; - const effectiveUsername = pendingAuth?.username || host.username || "root"; - // Always include password if available for fallback authentication - const effectivePassword = pendingAuth?.password || host.password; - const effectiveKeyId = pendingAuth?.keyId || host.identityFileId; - const effectivePassphrase = pendingAuth?.passphrase; - - const key = effectiveKeyId - ? keys.find((k) => k.id === effectiveKeyId) - : undefined; - - // Prepare proxy configuration if set - const proxyConfig = host.proxyConfig - ? { - type: host.proxyConfig.type, - host: host.proxyConfig.host, - port: host.proxyConfig.port, - username: host.proxyConfig.username, - password: host.proxyConfig.password, - } - : undefined; - - // Prepare jump host chain configuration - const jumpHosts = resolvedChainHosts.map((jumpHost) => { - const jumpKey = jumpHost.identityFileId - ? keys.find((k) => k.id === jumpHost.identityFileId) - : undefined; - return { - hostname: jumpHost.hostname, - port: jumpHost.port || 22, - username: jumpHost.username || "root", - password: jumpHost.password, // Always include for fallback - privateKey: jumpKey?.privateKey, - certificate: jumpKey?.certificate, - passphrase: jumpKey?.passphrase, - publicKey: jumpKey?.publicKey, - credentialId: jumpKey?.credentialId, - rpId: jumpKey?.rpId, - keyId: jumpKey?.id, - keySource: jumpKey?.source, - userVerification: - jumpKey?.source === "biometric" ? "required" : "preferred", - label: jumpHost.label, - }; - }); - - // Initialize chain progress if we have jump hosts - const totalHops = jumpHosts.length + 1; // jump hosts + target - let unsubscribeChainProgress: (() => void) | undefined; - - if (jumpHosts.length > 0) { - setChainProgress({ - currentHop: 1, - totalHops, - currentHostLabel: - jumpHosts[0]?.label || jumpHosts[0]?.hostname || host.hostname, - }); - setProgressLogs((prev) => [ - ...prev, - `Starting chain connection (${totalHops} hops)...`, - ]); - - // Subscribe to chain progress events from IPC - { - const unsub = terminalBackend.onChainProgress( - (hop, total, label, status) => { - setChainProgress({ - currentHop: hop, - totalHops: total, - currentHostLabel: label, - }); - setProgressLogs((prev) => [ - ...prev, - `Chain ${hop} of ${total}: ${label} - ${status}`, - ]); - // Update progress value based on chain hop - const hopProgress = (hop / total) * 80 + 10; - setProgressValue(Math.min(95, hopProgress)); - }, - ); - if (unsub) unsubscribeChainProgress = unsub; - } - } - - try { - // Build environment variables, including TERM from settings - const termEnv: Record = { - TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color', - }; - - // Add host-specific environment variables - if (host.environmentVariables) { - for (const { name, value } of host.environmentVariables) { - if (name) termEnv[name] = value; - } - } - - // DEBUG: Log key info for troubleshooting - console.log('[Terminal] Starting SSH session with key info:', { - keyId: key?.id, - keyLabel: key?.label, - keySource: key?.source, - hasCredentialId: !!key?.credentialId, - hasRpId: !!key?.rpId, - hasPublicKey: !!key?.publicKey, - hasPrivateKey: !!key?.privateKey, - }); - - const id = await terminalBackend.startSSHSession({ - sessionId, - hostname: host.hostname, - username: effectiveUsername, - port: host.port || 22, - password: effectivePassword, - privateKey: key?.privateKey, - certificate: key?.certificate, - publicKey: key?.publicKey, - credentialId: key?.credentialId, - rpId: key?.rpId, - keyId: key?.id, - keySource: key?.source, - userVerification: - key?.source === "biometric" ? "required" : "preferred", - passphrase: effectivePassphrase || key?.passphrase, - agentForwarding: host.agentForwarding, - cols: term.cols, - rows: term.rows, - charset: host.charset, - // Environment variables including TERM - env: termEnv, - // New: proxy and jump host configuration - proxy: proxyConfig, - jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined, - }); - - // Clean up chain progress listener after successful connection - if (unsubscribeChainProgress) { - unsubscribeChainProgress(); - } - - sessionRef.current = id; - - disposeDataRef.current = terminalBackend.onSessionData(id, (chunk) => { - // Apply keyword highlighting before writing to terminal - term.write(highlightProcessorRef.current(chunk)); - if (!hasConnectedRef.current) { - updateStatus("connected"); - setChainProgress(null); // Clear chain progress on connect - // Trigger fit after connection to ensure proper terminal size - setTimeout(() => { - if (fitAddonRef.current) { - try { - fitAddonRef.current.fit(); - // Send updated size to remote - if (sessionRef.current) { - terminalBackend.resizeSession(sessionRef.current, term.cols, term.rows); - } - } catch (err) { - logger.warn("Post-connect fit failed", err); - } - } - }, 100); - } - }); - - disposeExitRef.current = terminalBackend.onSessionExit(id, (evt) => { - updateStatus("disconnected"); - setChainProgress(null); // Clear chain progress on disconnect - term.writeln( - `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, - ); - // Capture terminal data before session exit - if (onTerminalDataCapture && serializeAddonRef.current) { - try { - const terminalData = serializeAddonRef.current.serialize(); - onTerminalDataCapture(sessionId, terminalData); - } catch (err) { - logger.warn("Failed to serialize terminal data:", err); - } - } - onSessionExit?.(sessionId); - }); - - // Run startup command from host config or snippet - const commandToRun = startupCommand || host.startupCommand; - if (commandToRun && !hasRunStartupCommandRef.current) { - hasRunStartupCommandRef.current = true; - setTimeout(() => { - if (sessionRef.current) { - terminalBackend.writeToSession(sessionRef.current, `${commandToRun}\r`); - // Track startup command execution in shell history - if (onCommandExecuted) { - onCommandExecuted(commandToRun, host.id, host.label, sessionId); - } - } - }, 600); - } - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - - // Check if this is an authentication failure - const isAuthError = - message.toLowerCase().includes("authentication") || - message.toLowerCase().includes("auth") || - message.toLowerCase().includes("password") || - message.toLowerCase().includes("permission denied"); - - if (isAuthError) { - // Show auth dialog for password retry - setError(null); // Clear error so we show auth dialog instead - setNeedsAuth(true); - setAuthRetryMessage( - "Authentication failed. Please check your credentials and try again.", - ); - setAuthPassword(""); // Clear password for re-entry - setProgressLogs((prev) => [ - ...prev, - "Authentication failed. Please try again.", - ]); - // Stay in connecting state to show auth dialog - setStatus("connecting"); - } else { - setError(message); - term.writeln(`\r\n[Failed to start SSH: ${message}]`); - updateStatus("disconnected"); - } - - setChainProgress(null); // Clear chain progress on error - // Clean up chain progress listener on error - if (unsubscribeChainProgress) { - unsubscribeChainProgress(); - } - } - - // Trigger distro detection once connected (hidden exec, no terminal output) - setTimeout(() => runDistroDetection(key), 600); - }; - - const startTelnet = async (term: XTerm) => { - try { - term.clear?.(); - } catch (err) { - logger.warn("Failed to clear terminal before connect", err); - } - - if (!terminalBackend.telnetAvailable()) { - setError("Telnet bridge unavailable. Please run the desktop build."); - term.writeln( - "\r\n[Telnet bridge unavailable. Please run the desktop build.]", - ); - updateStatus("disconnected"); - return; - } - - try { - // Build environment variables, including TERM from settings - const telnetEnv: Record = { - TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color', - }; - - // Add host-specific environment variables - if (host.environmentVariables) { - for (const { name, value } of host.environmentVariables) { - if (name) telnetEnv[name] = value; - } - } - - const id = await terminalBackend.startTelnetSession({ - sessionId, - hostname: host.hostname, - port: host.telnetPort || host.port || 23, - cols: term.cols, - rows: term.rows, - charset: host.charset, - env: telnetEnv, - }); - - sessionRef.current = id; - - disposeDataRef.current = terminalBackend.onSessionData(id, (chunk) => { - // Apply keyword highlighting before writing to terminal - term.write(highlightProcessorRef.current(chunk)); - if (!hasConnectedRef.current) { - updateStatus("connected"); - setTimeout(() => { - if (fitAddonRef.current) { - try { - fitAddonRef.current.fit(); - if (sessionRef.current) { - terminalBackend.resizeSession(sessionRef.current, term.cols, term.rows); - } - } catch (err) { - logger.warn("Post-connect fit failed", err); - } - } - }, 100); - } - }); - - disposeExitRef.current = terminalBackend.onSessionExit(id, (evt) => { - updateStatus("disconnected"); - term.writeln( - `\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, - ); - // Capture terminal data before session exit - if (onTerminalDataCapture && serializeAddonRef.current) { - try { - const terminalData = serializeAddonRef.current.serialize(); - onTerminalDataCapture(sessionId, terminalData); - } catch (err) { - logger.warn("Failed to serialize terminal data:", err); - } - } - onSessionExit?.(sessionId); - }); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - setError(message); - term.writeln(`\r\n[Failed to start Telnet: ${message}]`); - updateStatus("disconnected"); - } - }; - - const startMosh = async (term: XTerm) => { - try { - term.clear?.(); - } catch (err) { - logger.warn("Failed to clear terminal before connect", err); - } - - if (!terminalBackend.moshAvailable()) { - setError("Mosh bridge unavailable. Please run the desktop build."); - term.writeln( - "\r\n[Mosh bridge unavailable. Please run the desktop build.]", - ); - updateStatus("disconnected"); - return; - } - - try { - // Build environment variables, including TERM from settings - const moshEnv: Record = { - TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color', - }; - - // Add host-specific environment variables - if (host.environmentVariables) { - for (const { name, value } of host.environmentVariables) { - if (name) moshEnv[name] = value; - } - } - - const id = await terminalBackend.startMoshSession({ - sessionId, - hostname: host.hostname, - username: host.username || "root", - port: host.port || 22, - moshServerPath: host.moshServerPath, - agentForwarding: host.agentForwarding, - cols: term.cols, - rows: term.rows, - charset: host.charset, - env: moshEnv, - }); - - sessionRef.current = id; - - disposeDataRef.current = terminalBackend.onSessionData(id, (chunk) => { - // Apply keyword highlighting before writing to terminal - term.write(highlightProcessorRef.current(chunk)); - if (!hasConnectedRef.current) { - updateStatus("connected"); - setTimeout(() => { - if (fitAddonRef.current) { - try { - fitAddonRef.current.fit(); - if (sessionRef.current) { - terminalBackend.resizeSession(sessionRef.current, term.cols, term.rows); - } - } catch (err) { - logger.warn("Post-connect fit failed", err); - } - } - }, 100); - } - }); - - disposeExitRef.current = terminalBackend.onSessionExit(id, (evt) => { - updateStatus("disconnected"); - term.writeln( - `\r\n[Mosh session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, - ); - // Capture terminal data before session exit - if (onTerminalDataCapture && serializeAddonRef.current) { - try { - const terminalData = serializeAddonRef.current.serialize(); - onTerminalDataCapture(sessionId, terminalData); - } catch (err) { - logger.warn("Failed to serialize terminal data:", err); - } - } - onSessionExit?.(sessionId); - }); - - // Run startup command if specified - const commandToRun = startupCommand || host.startupCommand; - if (commandToRun && !hasRunStartupCommandRef.current) { - hasRunStartupCommandRef.current = true; - setTimeout(() => { - if (sessionRef.current) { - terminalBackend.writeToSession(sessionRef.current, `${commandToRun}\r`); - if (onCommandExecuted) { - onCommandExecuted(commandToRun, host.id, host.label, sessionId); - } - } - }, 600); - } - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - setError(message); - term.writeln(`\r\n[Failed to start Mosh: ${message}]`); - updateStatus("disconnected"); - } - }; - - const startLocal = async (term: XTerm) => { - try { - term.clear?.(); - } catch (err) { - logger.warn("Failed to clear terminal before connect", err); - } - - if (!terminalBackend.localAvailable()) { - setError("Local shell bridge unavailable. Please run the desktop build."); - term.writeln( - "\r\n[Local shell bridge unavailable. Please run the desktop build to spawn a local terminal.]", - ); - updateStatus("disconnected"); - return; - } - - try { - const id = await terminalBackend.startLocalSession({ - sessionId, - cols: term.cols, - rows: term.rows, - env: { - TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color', - }, - }); - sessionRef.current = id; - disposeDataRef.current = terminalBackend.onSessionData(id, (chunk) => { - // Apply keyword highlighting before writing to terminal - term.write(highlightProcessorRef.current(chunk)); - if (!hasConnectedRef.current) { - updateStatus("connected"); - // Trigger fit after connection to ensure proper terminal size - setTimeout(() => { - if (fitAddonRef.current) { - try { - fitAddonRef.current.fit(); - // Send updated size to remote - if (sessionRef.current) { - terminalBackend.resizeSession(sessionRef.current, term.cols, term.rows); - } - } catch (err) { - logger.warn("Post-connect fit failed", err); - } - } - }, 100); - } - }); - disposeExitRef.current = terminalBackend.onSessionExit(id, (evt) => { - updateStatus("disconnected"); - term.writeln( - `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, - ); - // Capture terminal data before session exit - logger.info("[Terminal] Session exit, capturing data", { sessionId, hasCallback: !!onTerminalDataCapture, hasSerializeAddon: !!serializeAddonRef.current }); - if (onTerminalDataCapture && serializeAddonRef.current) { - try { - const terminalData = serializeAddonRef.current.serialize(); - logger.info("[Terminal] Serialized terminal data", { sessionId, dataLength: terminalData.length }); - onTerminalDataCapture(sessionId, terminalData); - } catch (err) { - logger.warn("Failed to serialize terminal data:", err); - } - } - onSessionExit?.(sessionId); - }); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - setError(message); - term.writeln(`\r\n[Failed to start local shell: ${message}]`); - updateStatus("disconnected"); - } - }; + const terminalContextActions = useTerminalContextActions({ + termRef, + sessionRef, + terminalBackend, + onHasSelectionChange: setHasSelection, + }); const handleSnippetClick = (cmd: string) => { if (sessionRef.current) { @@ -1603,30 +688,27 @@ const TerminalComponent: React.FC = ({ const handleCancelConnect = () => { setIsCancelling(true); - setNeedsAuth(false); - setAuthRetryMessage(null); // Clear auth retry message + auth.setNeedsAuth(false); + auth.setAuthRetryMessage(null); setNeedsHostKeyVerification(false); setPendingHostKeyInfo(null); setError("Connection cancelled"); setProgressLogs((prev) => [...prev, "Cancelled by user."]); cleanupSession(); updateStatus("disconnected"); - setChainProgress(null); // Clear chain progress on cancel + setChainProgress(null); setTimeout(() => setIsCancelling(false), 600); onCloseSession?.(sessionId); }; - // Handle known host verification - Close (cancel) const handleHostKeyClose = () => { setNeedsHostKeyVerification(false); setPendingHostKeyInfo(null); handleCancelConnect(); }; - // Handle known host verification - Continue without adding const handleHostKeyContinue = () => { setNeedsHostKeyVerification(false); - // Resume connection without adding to known hosts if (pendingConnectionRef.current) { pendingConnectionRef.current(); pendingConnectionRef.current = null; @@ -1634,7 +716,6 @@ const TerminalComponent: React.FC = ({ setPendingHostKeyInfo(null); }; - // Handle known host verification - Add and continue const handleHostKeyAddAndContinue = () => { if (pendingHostKeyInfo && onAddKnownHost) { const newKnownHost: KnownHost = { @@ -1648,7 +729,6 @@ const TerminalComponent: React.FC = ({ onAddKnownHost(newKnownHost); } setNeedsHostKeyVerification(false); - // Resume connection if (pendingConnectionRef.current) { pendingConnectionRef.current(); pendingConnectionRef.current = null; @@ -1659,221 +739,18 @@ const TerminalComponent: React.FC = ({ const handleRetry = () => { if (!termRef.current) return; cleanupSession(); - setNeedsAuth(false); - setAuthRetryMessage(null); // Clear auth retry message - pendingAuthRef.current = null; + auth.resetForRetry(); setStatus("connecting"); setError(null); setProgressLogs(["Retrying secure channel..."]); setShowLogs(true); if (host.protocol === "local" || host.hostname === "localhost") { - startLocal(termRef.current); + sessionStarters.startLocal(termRef.current); } else { - startSSH(termRef.current); + sessionStarters.startSSH(termRef.current); } }; - const isAuthValid = () => { - if (!authUsername.trim()) return false; - if (authMethod === "password") return authPassword.trim().length > 0; - if (authMethod === "key" || authMethod === "certificate") return !!authKeyId; - return false; - }; - - const handleAuthSubmit = () => { - if (!isAuthValid()) return; - - // Set pending auth credentials - pendingAuthRef.current = { - authMethod, - username: authUsername, - password: authMethod === "password" ? authPassword : undefined, - keyId: - authMethod === "key" || authMethod === "certificate" - ? (authKeyId ?? undefined) - : undefined, - passphrase: - authMethod === "key" || authMethod === "certificate" - ? authPassphrase || undefined - : undefined, - }; - - // Save credentials to host if requested - if (saveCredentials && onUpdateHost) { - const updatedHost: Host = { - ...host, - username: authUsername, - authMethod: authMethod, - password: authMethod === "password" ? authPassword : undefined, - identityFileId: - authMethod === "key" || authMethod === "certificate" - ? (authKeyId ?? undefined) - : undefined, - }; - onUpdateHost(updatedHost); - } - - // Hide auth dialog and start connection - setNeedsAuth(false); - setAuthRetryMessage(null); // Clear any previous auth error message - setStatus("connecting"); - setProgressLogs(["Authenticating with provided credentials..."]); - - if (termRef.current) { - // Clear terminal before connecting - try { - termRef.current.clear?.(); - } catch (err) { - logger.warn("Failed to clear terminal", err); - } - startSSH(termRef.current); - } - }; - - // Context menu handlers - const handleContextCopy = () => { - const term = termRef.current; - if (!term) return; - const selection = term.getSelection(); - if (selection) { - navigator.clipboard.writeText(selection); - } - }; - - const handleContextPaste = async () => { - const term = termRef.current; - if (!term) return; - try { - const text = await navigator.clipboard.readText(); - if (text && sessionRef.current) terminalBackend.writeToSession(sessionRef.current, text); - } catch (err) { - logger.warn("Failed to paste from clipboard", err); - } - }; - - const handleContextSelectAll = () => { - const term = termRef.current; - if (!term) return; - term.selectAll(); - setHasSelection(true); - }; - - const handleContextClear = () => { - const term = termRef.current; - if (!term) return; - term.clear(); - }; - - const handleContextSelectWord = () => { - const term = termRef.current; - if (!term) return; - // xterm.js selectWord selects the word under cursor - // Since we don't have a cursor position from right-click, we can select all as fallback - // A proper implementation would require tracking the click position - term.selectAll(); - setHasSelection(true); - }; - - // Search handlers - const handleToggleSearch = useCallback(() => { - setIsSearchOpen((prev) => !prev); - // Clear match count when closing - if (isSearchOpen) { - setSearchMatchCount(null); - searchAddonRef.current?.clearDecorations(); - } - }, [isSearchOpen]); - - const handleSearch = useCallback((term: string): boolean => { - const searchAddon = searchAddonRef.current; - if (!searchAddon || !term) { - setSearchMatchCount(null); - return false; - } - - // Store the search term for findNext/findPrevious - searchTermRef.current = term; - - // Clear previous decorations - searchAddon.clearDecorations(); - - // Perform search (findNext from current position or start) - const found = searchAddon.findNext(term, { - regex: false, - caseSensitive: false, - wholeWord: false, - decorations: { - matchBackground: '#FFFF0044', - matchBorder: '#FFFF00', - matchOverviewRuler: '#FFFF00', - activeMatchBackground: '#FF880088', - activeMatchBorder: '#FF8800', - activeMatchColorOverviewRuler: '#FF8800', - }, - }); - - // Update match count after search - // Note: xterm search addon doesn't expose match count directly - // We'll track it by counting via findAll (if available) or estimate - if (found) { - // For now, we don't have exact count from the addon - // We'll show a basic indicator - setSearchMatchCount({ current: 1, total: 1 }); // Placeholder - } else { - setSearchMatchCount({ current: 0, total: 0 }); - } - - return found; - }, []); - - const handleFindNext = useCallback((): boolean => { - const searchAddon = searchAddonRef.current; - const term = searchTermRef.current; - if (!searchAddon || !term) return false; - const found = searchAddon.findNext(term, { - regex: false, - caseSensitive: false, - wholeWord: false, - decorations: { - matchBackground: '#FFFF0044', - matchBorder: '#FFFF00', - matchOverviewRuler: '#FFFF00', - activeMatchBackground: '#FF880088', - activeMatchBorder: '#FF8800', - activeMatchColorOverviewRuler: '#FF8800', - }, - }); - return found; - }, []); - - const handleFindPrevious = useCallback((): boolean => { - const searchAddon = searchAddonRef.current; - const term = searchTermRef.current; - if (!searchAddon || !term) return false; - const found = searchAddon.findPrevious(term, { - regex: false, - caseSensitive: false, - wholeWord: false, - decorations: { - matchBackground: '#FFFF0044', - matchBorder: '#FFFF00', - matchOverviewRuler: '#FFFF00', - activeMatchBackground: '#FF880088', - activeMatchBorder: '#FF8800', - activeMatchColorOverviewRuler: '#FF8800', - }, - }); - return found; - }, []); - - const handleCloseSearch = useCallback(() => { - setIsSearchOpen(false); - setSearchMatchCount(null); - searchAddonRef.current?.clearDecorations(); - // Refocus terminal after closing search - termRef.current?.focus(); - }, []); - const renderControls = (opts?: { showClose?: boolean }) => ( = ({ : status === "connecting" ? "bg-amber-400" : "bg-rose-500"; - // Reserved for future status indicator enhancements const _isConnecting = status === "connecting"; const _hasError = Boolean(error); @@ -1906,17 +782,16 @@ const TerminalComponent: React.FC = ({ hasSelection={hasSelection} hotkeyScheme={hotkeyScheme} rightClickBehavior={terminalSettings?.rightClickBehavior} - onCopy={handleContextCopy} - onPaste={handleContextPaste} - onSelectAll={handleContextSelectAll} - onClear={handleContextClear} - onSelectWord={handleContextSelectWord} + onCopy={terminalContextActions.onCopy} + onPaste={terminalContextActions.onPaste} + onSelectAll={terminalContextActions.onSelectAll} + onClear={terminalContextActions.onClear} + onSelectWord={terminalContextActions.onSelectWord} onSplitHorizontal={onSplitHorizontal} onSplitVertical={onSplitVertical} onClose={inWorkspace ? () => onCloseSession?.(sessionId) : undefined} >
- {/* Unified statusbar for both single host and workspace modes */}
@@ -1936,7 +811,6 @@ const TerminalComponent: React.FC = ({ />
- {/* Broadcast button - only show in workspace mode */} {inWorkspace && onToggleBroadcast && ( )} - {/* Expand to focus mode button - only show in workspace split view mode */} {inWorkspace && !isFocusMode && onExpandToFocus && (
- {/* Search bar - full width below status bar */} {isSearchOpen && (
= ({
- - {/* Known Host Verification Dialog */} {needsHostKeyVerification && pendingHostKeyInfo && (
= ({ error={error} progressValue={progressValue} chainProgress={chainProgress} - needsAuth={needsAuth} + needsAuth={auth.needsAuth} showLogs={showLogs} _setShowLogs={setShowLogs} keys={keys} authProps={{ - authMethod, - setAuthMethod, - authUsername, - setAuthUsername, - authPassword, - setAuthPassword, - authKeyId, - setAuthKeyId, - authPassphrase, - setAuthPassphrase, - showAuthPassphrase, - setShowAuthPassphrase, - showAuthPassword, - setShowAuthPassword, - authRetryMessage, - onSubmit: handleAuthSubmit, - onSubmitWithoutSave: () => { - setSaveCredentials(false); - handleAuthSubmit(); - }, + authMethod: auth.authMethod, + setAuthMethod: auth.setAuthMethod, + authUsername: auth.authUsername, + setAuthUsername: auth.setAuthUsername, + authPassword: auth.authPassword, + setAuthPassword: auth.setAuthPassword, + authKeyId: auth.authKeyId, + setAuthKeyId: auth.setAuthKeyId, + authPassphrase: auth.authPassphrase, + setAuthPassphrase: auth.setAuthPassphrase, + showAuthPassphrase: auth.showAuthPassphrase, + setShowAuthPassphrase: auth.setShowAuthPassphrase, + showAuthPassword: auth.showAuthPassword, + setShowAuthPassword: auth.setShowAuthPassword, + authRetryMessage: auth.authRetryMessage, + onSubmit: () => auth.submit(), + onSubmitWithoutSave: () => auth.submit({ saveToHost: false }), onCancel: handleCancelConnect, - isValid: isAuthValid(), + isValid: auth.isValid, }} progressProps={{ timeLeft, @@ -2053,14 +928,13 @@ const TerminalComponent: React.FC = ({ )}
- {/* SFTP Modal - rendered outside terminal container to avoid affecting terminal width */} k.id === host.identityFileId)?.privateKey : undefined, @@ -2084,8 +958,7 @@ const TerminalComponent: React.FC = ({ ? keys.find((k) => k.id === host.identityFileId)?.source : undefined, userVerification: host.identityFileId - ? keys.find((k) => k.id === host.identityFileId)?.source === - "biometric" + ? keys.find((k) => k.id === host.identityFileId)?.source === "biometric" ? "required" : "preferred" : undefined, @@ -2098,7 +971,6 @@ const TerminalComponent: React.FC = ({ ); }; -// Memoized Terminal - only re-renders when props change const Terminal = memo(TerminalComponent); Terminal.displayName = "Terminal"; diff --git a/components/terminal/hooks/useTerminalAuthState.ts b/components/terminal/hooks/useTerminalAuthState.ts new file mode 100644 index 000000000..1796c0d92 --- /dev/null +++ b/components/terminal/hooks/useTerminalAuthState.ts @@ -0,0 +1,154 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { MutableRefObject } from "react"; +import type { Host, TerminalSession } from "../../../types"; +import type { PendingAuth } from "../runtime/createTerminalSessionStarters"; +import type { TerminalAuthMethod } from "../TerminalAuthDialog"; +import { logger } from "../../../lib/logger"; + +export const useTerminalAuthState = ({ + host, + pendingAuthRef, + termRef, + onUpdateHost, + onStartSsh, + setStatus, + setProgressLogs, +}: { + host: Host; + pendingAuthRef: MutableRefObject; + termRef: MutableRefObject; + onUpdateHost?: (host: Host) => void; + onStartSsh: (term: XTerm) => void; + setStatus: (status: TerminalSession["status"]) => void; + setProgressLogs: (next: string[] | ((prev: string[]) => string[])) => void; +}) => { + const [needsAuth, setNeedsAuth] = useState(false); + const [authRetryMessage, setAuthRetryMessage] = useState(null); + const [authUsername, setAuthUsername] = useState(host.username || "root"); + const [authMethod, setAuthMethod] = useState("password"); + const [authPassword, setAuthPassword] = useState(""); + const [authKeyId, setAuthKeyId] = useState(null); + const [authPassphrase, setAuthPassphrase] = useState(""); + const [showAuthPassword, setShowAuthPassword] = useState(false); + const [showAuthPassphrase, setShowAuthPassphrase] = useState(false); + const [saveCredentials, setSaveCredentials] = useState(true); + + useEffect(() => { + setNeedsAuth(false); + setAuthRetryMessage(null); + setAuthUsername(host.username || "root"); + setAuthPassword(""); + setAuthKeyId(null); + setAuthPassphrase(""); + setShowAuthPassword(false); + setShowAuthPassphrase(false); + setSaveCredentials(true); + }, [host.id, host.username]); + + const isValid = useMemo(() => { + if (!authUsername.trim()) return false; + if (authMethod === "password") return authPassword.trim().length > 0; + if (authMethod === "key" || authMethod === "certificate") return !!authKeyId; + return false; + }, [authKeyId, authMethod, authPassword, authUsername]); + + const resetForRetry = useCallback(() => { + setNeedsAuth(false); + setAuthRetryMessage(null); + pendingAuthRef.current = null; + }, [pendingAuthRef]); + + const submit = useCallback( + (opts?: { saveToHost?: boolean }) => { + if (!isValid) return; + + pendingAuthRef.current = { + authMethod, + username: authUsername, + password: authMethod === "password" ? authPassword : undefined, + keyId: + authMethod === "key" || authMethod === "certificate" + ? (authKeyId ?? undefined) + : undefined, + passphrase: + authMethod === "key" || authMethod === "certificate" + ? authPassphrase || undefined + : undefined, + }; + + const shouldSave = opts?.saveToHost ?? saveCredentials; + if (shouldSave && onUpdateHost) { + const updatedHost: Host = { + ...host, + username: authUsername, + authMethod: authMethod, + password: authMethod === "password" ? authPassword : undefined, + identityFileId: + authMethod === "key" || authMethod === "certificate" + ? (authKeyId ?? undefined) + : undefined, + }; + onUpdateHost(updatedHost); + } + + setNeedsAuth(false); + setAuthRetryMessage(null); + setStatus("connecting"); + setProgressLogs(["Authenticating with provided credentials..."]); + + const term = termRef.current; + if (!term) return; + + try { + term.clear?.(); + } catch (err) { + logger.warn("Failed to clear terminal", err); + } + + onStartSsh(term); + }, + [ + authKeyId, + authMethod, + authPassphrase, + authPassword, + authUsername, + host, + isValid, + onStartSsh, + onUpdateHost, + pendingAuthRef, + saveCredentials, + setProgressLogs, + setStatus, + termRef, + ], + ); + + return { + needsAuth, + setNeedsAuth, + authRetryMessage, + setAuthRetryMessage, + authUsername, + setAuthUsername, + authMethod, + setAuthMethod, + authPassword, + setAuthPassword, + authKeyId, + setAuthKeyId, + authPassphrase, + setAuthPassphrase, + showAuthPassword, + setShowAuthPassword, + showAuthPassphrase, + setShowAuthPassphrase, + saveCredentials, + setSaveCredentials, + isValid, + resetForRetry, + submit, + }; +}; diff --git a/components/terminal/hooks/useTerminalContextActions.ts b/components/terminal/hooks/useTerminalContextActions.ts new file mode 100644 index 000000000..b39c4e7ef --- /dev/null +++ b/components/terminal/hooks/useTerminalContextActions.ts @@ -0,0 +1,63 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; +import { useCallback } from "react"; +import type { MutableRefObject } from "react"; +import { logger } from "../../../lib/logger"; + +type TerminalBackendWriteApi = { + writeToSession: (sessionId: string, data: string) => void; +}; + +export const useTerminalContextActions = ({ + termRef, + sessionRef, + terminalBackend, + onHasSelectionChange, +}: { + termRef: MutableRefObject; + sessionRef: MutableRefObject; + terminalBackend: TerminalBackendWriteApi; + onHasSelectionChange?: (hasSelection: boolean) => void; +}) => { + const onCopy = useCallback(() => { + const term = termRef.current; + if (!term) return; + const selection = term.getSelection(); + if (selection) { + navigator.clipboard.writeText(selection); + } + }, [termRef]); + + const onPaste = useCallback(async () => { + const term = termRef.current; + if (!term) return; + try { + const text = await navigator.clipboard.readText(); + if (text && sessionRef.current) terminalBackend.writeToSession(sessionRef.current, text); + } catch (err) { + logger.warn("Failed to paste from clipboard", err); + } + }, [sessionRef, termRef, terminalBackend]); + + const onSelectAll = useCallback(() => { + const term = termRef.current; + if (!term) return; + term.selectAll(); + onHasSelectionChange?.(true); + }, [onHasSelectionChange, termRef]); + + const onClear = useCallback(() => { + const term = termRef.current; + if (!term) return; + term.clear(); + }, [termRef]); + + const onSelectWord = useCallback(() => { + const term = termRef.current; + if (!term) return; + term.selectAll(); + onHasSelectionChange?.(true); + }, [onHasSelectionChange, termRef]); + + return { onCopy, onPaste, onSelectAll, onClear, onSelectWord }; +}; + diff --git a/components/terminal/hooks/useTerminalSearch.ts b/components/terminal/hooks/useTerminalSearch.ts new file mode 100644 index 000000000..feeb5041a --- /dev/null +++ b/components/terminal/hooks/useTerminalSearch.ts @@ -0,0 +1,123 @@ +import type { SearchAddon } from "@xterm/addon-search"; +import type { Terminal as XTerm } from "@xterm/xterm"; +import { useCallback, useRef, useState } from "react"; +import type { MutableRefObject } from "react"; + +type SearchMatchCount = { current: number; total: number } | null; + +export const useTerminalSearch = ({ + searchAddonRef, + termRef, +}: { + searchAddonRef: MutableRefObject; + termRef: MutableRefObject; +}) => { + const [isSearchOpen, setIsSearchOpen] = useState(false); + const [searchMatchCount, setSearchMatchCount] = useState(null); + const searchTermRef = useRef(""); + + const clearSearchDecorations = useCallback(() => { + searchAddonRef.current?.clearDecorations(); + }, [searchAddonRef]); + + const handleToggleSearch = useCallback(() => { + setIsSearchOpen((prev) => !prev); + if (isSearchOpen) { + setSearchMatchCount(null); + clearSearchDecorations(); + } + }, [clearSearchDecorations, isSearchOpen]); + + const handleSearch = useCallback( + (term: string): boolean => { + const searchAddon = searchAddonRef.current; + if (!searchAddon || !term) { + setSearchMatchCount(null); + return false; + } + + searchTermRef.current = term; + searchAddon.clearDecorations(); + + const found = searchAddon.findNext(term, { + regex: false, + caseSensitive: false, + wholeWord: false, + decorations: { + matchBackground: "#FFFF0044", + matchBorder: "#FFFF00", + matchOverviewRuler: "#FFFF00", + activeMatchBackground: "#FF880088", + activeMatchBorder: "#FF8800", + activeMatchColorOverviewRuler: "#FF8800", + }, + }); + + if (found) { + setSearchMatchCount({ current: 1, total: 1 }); + } else { + setSearchMatchCount({ current: 0, total: 0 }); + } + + return found; + }, + [searchAddonRef], + ); + + const handleFindNext = useCallback((): boolean => { + const searchAddon = searchAddonRef.current; + const term = searchTermRef.current; + if (!searchAddon || !term) return false; + return searchAddon.findNext(term, { + regex: false, + caseSensitive: false, + wholeWord: false, + decorations: { + matchBackground: "#FFFF0044", + matchBorder: "#FFFF00", + matchOverviewRuler: "#FFFF00", + activeMatchBackground: "#FF880088", + activeMatchBorder: "#FF8800", + activeMatchColorOverviewRuler: "#FF8800", + }, + }); + }, [searchAddonRef]); + + const handleFindPrevious = useCallback((): boolean => { + const searchAddon = searchAddonRef.current; + const term = searchTermRef.current; + if (!searchAddon || !term) return false; + return searchAddon.findPrevious(term, { + regex: false, + caseSensitive: false, + wholeWord: false, + decorations: { + matchBackground: "#FFFF0044", + matchBorder: "#FFFF00", + matchOverviewRuler: "#FFFF00", + activeMatchBackground: "#FF880088", + activeMatchBorder: "#FF8800", + activeMatchColorOverviewRuler: "#FF8800", + }, + }); + }, [searchAddonRef]); + + const handleCloseSearch = useCallback(() => { + setIsSearchOpen(false); + setSearchMatchCount(null); + clearSearchDecorations(); + termRef.current?.focus(); + }, [clearSearchDecorations, termRef]); + + return { + isSearchOpen, + setIsSearchOpen, + searchMatchCount, + handleToggleSearch, + handleSearch, + handleFindNext, + handleFindPrevious, + handleCloseSearch, + }; +}; + diff --git a/components/terminal/index.ts b/components/terminal/index.ts index e3cf02b78..fce35218b 100644 --- a/components/terminal/index.ts +++ b/components/terminal/index.ts @@ -22,3 +22,7 @@ export { TerminalSearchBar } from './TerminalSearchBar'; export type { TerminalSearchBarProps } from './TerminalSearchBar'; export { createHighlightProcessor, highlightKeywords, compileHighlightRules } from './keywordHighlight'; + +export { useTerminalSearch } from './hooks/useTerminalSearch'; +export { useTerminalContextActions } from './hooks/useTerminalContextActions'; +export { useTerminalAuthState } from './hooks/useTerminalAuthState'; diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts new file mode 100644 index 000000000..5dbb7ffa3 --- /dev/null +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -0,0 +1,530 @@ +import type { FitAddon } from "@xterm/addon-fit"; +import type { SerializeAddon } from "@xterm/addon-serialize"; +import type { Terminal as XTerm } from "@xterm/xterm"; +import type { Dispatch, MutableRefObject, SetStateAction } from "react"; +import { logger } from "../../../lib/logger"; +import type { Host, SSHKey, TerminalSession, TerminalSettings } from "../../../types"; + +type TerminalBackendApi = { + backendAvailable: () => boolean; + telnetAvailable: () => boolean; + moshAvailable: () => boolean; + localAvailable: () => boolean; + execAvailable: () => boolean; + startSSHSession: (options: NetcattySSHOptions) => Promise; + startTelnetSession: ( + options: Parameters>[0], + ) => Promise; + startMoshSession: ( + options: Parameters>[0], + ) => Promise; + startLocalSession: ( + options: Parameters>[0], + ) => Promise; + execCommand: (options: Parameters[0]) => Promise<{ + stdout?: string; + stderr?: string; + }>; + onSessionData: (sessionId: string, cb: (data: string) => void) => () => void; + onSessionExit: ( + sessionId: string, + cb: (evt: { exitCode?: number; signal?: number }) => void, + ) => () => void; + onChainProgress: ( + cb: (hop: number, total: number, label: string, status: string) => void, + ) => (() => void) | undefined; + writeToSession: (sessionId: string, data: string) => void; + resizeSession: (sessionId: string, cols: number, rows: number) => void; +}; + +export type PendingAuth = { + authMethod: "password" | "key" | "certificate"; + username: string; + password?: string; + keyId?: string; + passphrase?: string; +} | null; + +type ChainProgressState = { + currentHop: number; + totalHops: number; + currentHostLabel: string; +} | null; + +export type TerminalSessionStartersContext = { + host: Host; + keys: SSHKey[]; + resolvedChainHosts: Host[]; + sessionId: string; + startupCommand?: string; + terminalSettings?: TerminalSettings; + terminalBackend: TerminalBackendApi; + + sessionRef: MutableRefObject; + hasConnectedRef: MutableRefObject; + hasRunStartupCommandRef: MutableRefObject; + disposeDataRef: MutableRefObject<(() => void) | null>; + disposeExitRef: MutableRefObject<(() => void) | null>; + fitAddonRef: MutableRefObject; + serializeAddonRef: MutableRefObject; + highlightProcessorRef: MutableRefObject<(text: string) => string>; + pendingAuthRef: MutableRefObject; + + updateStatus: (next: TerminalSession["status"]) => void; + setStatus: Dispatch>; + setError: Dispatch>; + setNeedsAuth: Dispatch>; + setAuthRetryMessage: Dispatch>; + setAuthPassword: Dispatch>; + setProgressLogs: Dispatch>; + setProgressValue: Dispatch>; + setChainProgress: Dispatch>; + + onSessionExit?: (sessionId: string) => void; + onTerminalDataCapture?: (sessionId: string, data: string) => void; + onOsDetected?: (hostId: string, distro: string) => void; + onCommandExecuted?: ( + command: string, + hostId: string, + hostLabel: string, + sessionId: string, + ) => void; +}; + +const buildTermEnv = (host: Host, terminalSettings?: TerminalSettings) => { + const env: Record = { + TERM: terminalSettings?.terminalEmulationType ?? "xterm-256color", + }; + + if (host.environmentVariables) { + for (const { name, value } of host.environmentVariables) { + if (name) env[name] = value; + } + } + + return env; +}; + +const attachSessionToTerminal = ( + ctx: TerminalSessionStartersContext, + term: XTerm, + id: string, + opts?: { + onExitMessage?: (evt: { exitCode?: number; signal?: number }) => string; + onConnected?: () => void; + }, +) => { + ctx.sessionRef.current = id; + + ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => { + term.write(ctx.highlightProcessorRef.current(chunk)); + if (!ctx.hasConnectedRef.current) { + ctx.updateStatus("connected"); + opts?.onConnected?.(); + setTimeout(() => { + if (!ctx.fitAddonRef.current) return; + try { + ctx.fitAddonRef.current.fit(); + if (ctx.sessionRef.current) { + ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows); + } + } catch (err) { + logger.warn("Post-connect fit failed", err); + } + }, 100); + } + }); + + ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => { + ctx.updateStatus("disconnected"); + term.writeln(opts?.onExitMessage?.(evt) ?? "\r\n[session closed]"); + + if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) { + try { + const terminalData = ctx.serializeAddonRef.current.serialize(); + ctx.onTerminalDataCapture(ctx.sessionId, terminalData); + } catch (err) { + logger.warn("Failed to serialize terminal data:", err); + } + } + + ctx.onSessionExit?.(ctx.sessionId); + }); +}; + +const runDistroDetection = async (ctx: TerminalSessionStartersContext, key?: SSHKey) => { + if (!ctx.terminalBackend.execAvailable()) return; + try { + const res = await ctx.terminalBackend.execCommand({ + hostname: ctx.host.hostname, + username: ctx.host.username || "root", + port: ctx.host.port || 22, + password: ctx.host.password, + privateKey: key?.privateKey, + command: "cat /etc/os-release 2>/dev/null || uname -a", + timeout: 8000, + }); + const data = `${res.stdout || ""}\n${res.stderr || ""}`; + const idMatch = data.match(/ID=([\\w\\-]+)/i); + const distro = idMatch + ? idMatch[1].replace(/"/g, "") + : (data.split(/\s+/)[0] || "").toLowerCase(); + if (distro) ctx.onOsDetected?.(ctx.host.id, distro); + } catch (err) { + logger.warn("OS probe failed", err); + } +}; + +export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContext) => { + const startSSH = async (term: XTerm) => { + try { + term.clear?.(); + } catch (err) { + logger.warn("Failed to clear terminal before connect", err); + } + + if (!ctx.terminalBackend.backendAvailable()) { + ctx.setError("Native SSH bridge unavailable. Launch via Electron app."); + term.writeln( + "\r\n[netcatty SSH bridge unavailable. Please run the desktop build to connect.]", + ); + ctx.updateStatus("disconnected"); + return; + } + + const pendingAuth = ctx.pendingAuthRef.current; + const effectiveUsername = pendingAuth?.username || ctx.host.username || "root"; + const effectivePassword = pendingAuth?.password || ctx.host.password; + const effectiveKeyId = pendingAuth?.keyId || ctx.host.identityFileId; + const effectivePassphrase = pendingAuth?.passphrase; + + const key = effectiveKeyId + ? ctx.keys.find((k) => k.id === effectiveKeyId) + : undefined; + + const proxyConfig = ctx.host.proxyConfig + ? { + type: ctx.host.proxyConfig.type, + host: ctx.host.proxyConfig.host, + port: ctx.host.proxyConfig.port, + username: ctx.host.proxyConfig.username, + password: ctx.host.proxyConfig.password, + } + : undefined; + + const jumpHosts = ctx.resolvedChainHosts.map((jumpHost) => { + const jumpKey = jumpHost.identityFileId + ? ctx.keys.find((k) => k.id === jumpHost.identityFileId) + : undefined; + return { + hostname: jumpHost.hostname, + port: jumpHost.port || 22, + username: jumpHost.username || "root", + password: jumpHost.password, + privateKey: jumpKey?.privateKey, + certificate: jumpKey?.certificate, + passphrase: jumpKey?.passphrase, + publicKey: jumpKey?.publicKey, + credentialId: jumpKey?.credentialId, + rpId: jumpKey?.rpId, + keyId: jumpKey?.id, + keySource: jumpKey?.source, + userVerification: jumpKey?.source === "biometric" ? "required" : "preferred", + label: jumpHost.label, + }; + }); + + const totalHops = jumpHosts.length + 1; + let unsubscribeChainProgress: (() => void) | undefined; + + if (jumpHosts.length > 0) { + ctx.setChainProgress({ + currentHop: 1, + totalHops, + currentHostLabel: + jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname, + }); + ctx.setProgressLogs((prev) => [ + ...prev, + `Starting chain connection (${totalHops} hops)...`, + ]); + + const unsub = ctx.terminalBackend.onChainProgress((hop, total, label, status) => { + ctx.setChainProgress({ + currentHop: hop, + totalHops: total, + currentHostLabel: label, + }); + ctx.setProgressLogs((prev) => [ + ...prev, + `Chain ${hop} of ${total}: ${label} - ${status}`, + ]); + const hopProgress = (hop / total) * 80 + 10; + ctx.setProgressValue(Math.min(95, hopProgress)); + }); + if (unsub) unsubscribeChainProgress = unsub; + } + + try { + const termEnv = buildTermEnv(ctx.host, ctx.terminalSettings); + + // DEBUG: Log key info for troubleshooting + console.log("[Terminal] Starting SSH session with key info:", { + keyId: key?.id, + keyLabel: key?.label, + keySource: key?.source, + hasCredentialId: !!key?.credentialId, + hasRpId: !!key?.rpId, + hasPublicKey: !!key?.publicKey, + hasPrivateKey: !!key?.privateKey, + }); + + const id = await ctx.terminalBackend.startSSHSession({ + sessionId: ctx.sessionId, + hostname: ctx.host.hostname, + username: effectiveUsername, + port: ctx.host.port || 22, + password: effectivePassword, + privateKey: key?.privateKey, + certificate: key?.certificate, + publicKey: key?.publicKey, + credentialId: key?.credentialId, + rpId: key?.rpId, + keyId: key?.id, + keySource: key?.source, + userVerification: key?.source === "biometric" ? "required" : "preferred", + passphrase: effectivePassphrase || key?.passphrase, + agentForwarding: ctx.host.agentForwarding, + cols: term.cols, + rows: term.rows, + charset: ctx.host.charset, + env: termEnv, + proxy: proxyConfig, + jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined, + }); + + if (unsubscribeChainProgress) unsubscribeChainProgress(); + + attachSessionToTerminal(ctx, term, id, { + onConnected: () => ctx.setChainProgress(null), + onExitMessage: (evt) => + `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, + }); + + const commandToRun = ctx.startupCommand || ctx.host.startupCommand; + if (commandToRun && !ctx.hasRunStartupCommandRef.current) { + ctx.hasRunStartupCommandRef.current = true; + setTimeout(() => { + if (!ctx.sessionRef.current) return; + ctx.terminalBackend.writeToSession(ctx.sessionRef.current, `${commandToRun}\r`); + if (ctx.onCommandExecuted) { + ctx.onCommandExecuted(commandToRun, ctx.host.id, ctx.host.label, ctx.sessionId); + } + }, 600); + } + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + const isAuthError = + message.toLowerCase().includes("authentication") || + message.toLowerCase().includes("auth") || + message.toLowerCase().includes("password") || + message.toLowerCase().includes("permission denied"); + + if (isAuthError) { + ctx.setError(null); + ctx.setNeedsAuth(true); + ctx.setAuthRetryMessage( + "Authentication failed. Please check your credentials and try again.", + ); + ctx.setAuthPassword(""); + ctx.setProgressLogs((prev) => [ + ...prev, + "Authentication failed. Please try again.", + ]); + ctx.setStatus("connecting"); + } else { + ctx.setError(message); + term.writeln(`\r\n[Failed to start SSH: ${message}]`); + ctx.updateStatus("disconnected"); + } + + ctx.setChainProgress(null); + if (unsubscribeChainProgress) unsubscribeChainProgress(); + } + + setTimeout(() => void runDistroDetection(ctx, key), 600); + }; + + const startTelnet = async (term: XTerm) => { + try { + term.clear?.(); + } catch (err) { + logger.warn("Failed to clear terminal before connect", err); + } + + if (!ctx.terminalBackend.telnetAvailable()) { + ctx.setError("Telnet bridge unavailable. Please run the desktop build."); + term.writeln("\r\n[Telnet bridge unavailable. Please run the desktop build.]"); + ctx.updateStatus("disconnected"); + return; + } + + try { + const telnetEnv = buildTermEnv(ctx.host, ctx.terminalSettings); + const id = await ctx.terminalBackend.startTelnetSession({ + sessionId: ctx.sessionId, + hostname: ctx.host.hostname, + port: ctx.host.telnetPort || ctx.host.port || 23, + cols: term.cols, + rows: term.rows, + charset: ctx.host.charset, + env: telnetEnv, + }); + + attachSessionToTerminal(ctx, term, id, { + onExitMessage: (evt) => + `\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + ctx.setError(message); + term.writeln(`\r\n[Failed to start Telnet: ${message}]`); + ctx.updateStatus("disconnected"); + } + }; + + const startMosh = async (term: XTerm) => { + try { + term.clear?.(); + } catch (err) { + logger.warn("Failed to clear terminal before connect", err); + } + + if (!ctx.terminalBackend.moshAvailable()) { + ctx.setError("Mosh bridge unavailable. Please run the desktop build."); + term.writeln("\r\n[Mosh bridge unavailable. Please run the desktop build.]"); + ctx.updateStatus("disconnected"); + return; + } + + try { + const moshEnv = buildTermEnv(ctx.host, ctx.terminalSettings); + const id = await ctx.terminalBackend.startMoshSession({ + sessionId: ctx.sessionId, + hostname: ctx.host.hostname, + username: ctx.host.username || "root", + port: ctx.host.port || 22, + moshServerPath: ctx.host.moshServerPath, + agentForwarding: ctx.host.agentForwarding, + cols: term.cols, + rows: term.rows, + charset: ctx.host.charset, + env: moshEnv, + }); + + attachSessionToTerminal(ctx, term, id, { + onExitMessage: (evt) => + `\r\n[Mosh session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, + }); + + const commandToRun = ctx.startupCommand || ctx.host.startupCommand; + if (commandToRun && !ctx.hasRunStartupCommandRef.current) { + ctx.hasRunStartupCommandRef.current = true; + setTimeout(() => { + if (!ctx.sessionRef.current) return; + ctx.terminalBackend.writeToSession(ctx.sessionRef.current, `${commandToRun}\r`); + if (ctx.onCommandExecuted) { + ctx.onCommandExecuted(commandToRun, ctx.host.id, ctx.host.label, ctx.sessionId); + } + }, 600); + } + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + ctx.setError(message); + term.writeln(`\r\n[Failed to start Mosh: ${message}]`); + ctx.updateStatus("disconnected"); + } + }; + + const startLocal = async (term: XTerm) => { + try { + term.clear?.(); + } catch (err) { + logger.warn("Failed to clear terminal before connect", err); + } + + if (!ctx.terminalBackend.localAvailable()) { + ctx.setError("Local shell bridge unavailable. Please run the desktop build."); + term.writeln( + "\r\n[Local shell bridge unavailable. Please run the desktop build to spawn a local terminal.]", + ); + ctx.updateStatus("disconnected"); + return; + } + + try { + const id = await ctx.terminalBackend.startLocalSession({ + sessionId: ctx.sessionId, + cols: term.cols, + rows: term.rows, + env: { + TERM: ctx.terminalSettings?.terminalEmulationType ?? "xterm-256color", + }, + }); + + ctx.sessionRef.current = id; + ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => { + term.write(ctx.highlightProcessorRef.current(chunk)); + if (!ctx.hasConnectedRef.current) { + ctx.updateStatus("connected"); + setTimeout(() => { + if (!ctx.fitAddonRef.current) return; + try { + ctx.fitAddonRef.current.fit(); + if (ctx.sessionRef.current) { + ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows); + } + } catch (err) { + logger.warn("Post-connect fit failed", err); + } + }, 100); + } + }); + + ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => { + ctx.updateStatus("disconnected"); + term.writeln( + `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`, + ); + + logger.info("[Terminal] Session exit, capturing data", { + sessionId: ctx.sessionId, + hasCallback: !!ctx.onTerminalDataCapture, + hasSerializeAddon: !!ctx.serializeAddonRef.current, + }); + + if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) { + try { + const terminalData = ctx.serializeAddonRef.current.serialize(); + logger.info("[Terminal] Serialized terminal data", { + sessionId: ctx.sessionId, + dataLength: terminalData.length, + }); + ctx.onTerminalDataCapture(ctx.sessionId, terminalData); + } catch (err) { + logger.warn("Failed to serialize terminal data:", err); + } + } + + ctx.onSessionExit?.(ctx.sessionId); + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + ctx.setError(message); + term.writeln(`\r\n[Failed to start local shell: ${message}]`); + ctx.updateStatus("disconnected"); + } + }; + + return { startSSH, startTelnet, startMosh, startLocal }; +}; diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts new file mode 100644 index 000000000..117dbac20 --- /dev/null +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -0,0 +1,457 @@ +import { FitAddon } from "@xterm/addon-fit"; +import { SearchAddon } from "@xterm/addon-search"; +import { SerializeAddon } from "@xterm/addon-serialize"; +import { WebLinksAddon } from "@xterm/addon-web-links"; +import { WebglAddon } from "@xterm/addon-webgl"; +import { Terminal as XTerm } from "@xterm/xterm"; +import type { Dispatch, MutableRefObject, SetStateAction } from "react"; +import { + checkAppShortcut, + getAppLevelActions, + getTerminalPassthroughActions, +} from "../../../application/state/useGlobalHotkeys"; +import { TERMINAL_FONTS } from "../../../infrastructure/config/fonts"; +import { + XTERM_PERFORMANCE_CONFIG, + type XTermPlatform, + resolveXTermPerformanceConfig, +} from "../../../infrastructure/config/xtermPerformance"; +import { logger } from "../../../lib/logger"; +import type { + Host, + KeyBinding, + TerminalSession, + TerminalSettings, + TerminalTheme, +} from "../../../types"; + +type TerminalBackendApi = { + openExternalAvailable: () => boolean; + openExternal: (url: string) => Promise; + writeToSession: (sessionId: string, data: string) => void; + resizeSession: (sessionId: string, cols: number, rows: number) => void; +}; + +export type XTermRuntime = { + term: XTerm; + fitAddon: FitAddon; + serializeAddon: SerializeAddon; + searchAddon: SearchAddon; + dispose: () => void; +}; + +export type CreateXTermRuntimeContext = { + container: HTMLDivElement; + host: Host; + fontSize: number; + terminalTheme: TerminalTheme; + terminalSettingsRef: MutableRefObject; + terminalBackend: TerminalBackendApi; + sessionRef: MutableRefObject; + + hotkeySchemeRef: MutableRefObject<"disabled" | "mac" | "pc">; + keyBindingsRef: MutableRefObject; + onHotkeyActionRef: MutableRefObject< + ((action: string, event: KeyboardEvent) => void) | undefined + >; + + isBroadcastEnabledRef: MutableRefObject; + onBroadcastInputRef: MutableRefObject< + ((data: string, sourceSessionId: string) => void) | undefined + >; + + sessionId: string; + status: TerminalSession["status"]; + onCommandExecuted?: ( + command: string, + hostId: string, + hostLabel: string, + sessionId: string, + ) => void; + commandBufferRef: MutableRefObject; + setIsSearchOpen: Dispatch>; +}; + +const detectPlatform = (): XTermPlatform => { + if ( + typeof process !== "undefined" && + (process.platform === "darwin" || + process.platform === "win32" || + process.platform === "linux") + ) { + return process.platform; + } + + if (typeof navigator !== "undefined") { + const ua = navigator.userAgent.toLowerCase(); + if (ua.includes("win")) return "win32"; + if (ua.includes("linux")) return "linux"; + } + + return "darwin"; +}; + +export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime => { + const platform = detectPlatform(); + const deviceMemoryGb = + typeof navigator !== "undefined" && + typeof (navigator as { deviceMemory?: number }).deviceMemory === "number" + ? (navigator as { deviceMemory?: number }).deviceMemory + : undefined; + + const performanceConfig = resolveXTermPerformanceConfig({ + platform, + deviceMemoryGb, + }); + + const hostFontId = ctx.host.fontFamily || "menlo"; + const fontObj = TERMINAL_FONTS.find((f) => f.id === hostFontId) || TERMINAL_FONTS[0]; + const fontFamily = fontObj.family; + + const effectiveFontSize = ctx.host.fontSize || ctx.fontSize; + + const settings = ctx.terminalSettingsRef.current; + const cursorStyle = settings?.cursorShape ?? "block"; + const cursorBlink = settings?.cursorBlink ?? true; + const scrollback = settings?.scrollback ?? 10000; + const fontLigatures = settings?.fontLigatures ?? true; + const drawBoldTextInBrightColors = settings?.drawBoldInBrightColors ?? true; + const fontWeight = settings?.fontWeight ?? 400; + const fontWeightBold = settings?.fontWeightBold ?? 700; + const lineHeight = 1 + (settings?.linePadding ?? 0) / 10; + const minimumContrastRatio = settings?.minimumContrastRatio ?? 1; + const scrollOnUserInput = settings?.scrollOnInput ?? true; + const altIsMeta = settings?.altAsMeta ?? false; + const wordSeparator = settings?.wordSeparators ?? " ()[]{}'\""; + + const term = new XTerm({ + ...performanceConfig.options, + fontSize: effectiveFontSize, + fontFamily, + fontWeight: fontWeight as + | 100 + | 200 + | 300 + | 400 + | 500 + | 600 + | 700 + | 800 + | 900 + | "normal" + | "bold", + fontWeightBold: fontWeightBold as + | 100 + | 200 + | 300 + | 400 + | 500 + | 600 + | 700 + | 800 + | 900 + | "normal" + | "bold", + lineHeight, + cursorStyle, + cursorBlink, + scrollback, + allowProposedApi: fontLigatures, + drawBoldTextInBrightColors, + minimumContrastRatio, + scrollOnUserInput, + altClickMovesCursor: !altIsMeta, + wordSeparator, + theme: { + ...ctx.terminalTheme.colors, + selectionBackground: ctx.terminalTheme.colors.selection, + }, + }); + + type MaybeRenderer = { + constructor?: { name?: string }; + type?: string; + }; + + type IntrospectableTerminal = XTerm & { + _core?: { + _renderService?: { + _renderer?: MaybeRenderer; + }; + }; + options?: { + rendererType?: string; + }; + }; + + const logRenderer = (attempt = 0) => { + const introspected = term as IntrospectableTerminal; + const renderer = introspected._core?._renderService?._renderer; + const candidates = [ + renderer?.type, + renderer?.constructor?.name, + introspected.options?.rendererType, + ]; + const rendererName = + candidates.find((value) => typeof value === "string" && value.length > 0) || + undefined; + const normalized = rendererName + ? rendererName.toLowerCase().includes("webgl") + ? "webgl" + : rendererName.toLowerCase().includes("canvas") + ? "canvas" + : rendererName + : "unknown"; + logger.info(`[XTerm] renderer=${normalized}`); + const scopedWindow = window as Window & { __xtermRenderer?: string }; + scopedWindow.__xtermRenderer = normalized; + if (normalized === "unknown" && attempt < 3) { + setTimeout(() => logRenderer(attempt + 1), 150); + } + }; + + const fitAddon = new FitAddon(); + term.loadAddon(fitAddon); + + const serializeAddon = new SerializeAddon(); + term.loadAddon(serializeAddon); + + const searchAddon = new SearchAddon(); + term.loadAddon(searchAddon); + + term.open(ctx.container); + + let webglAddon: WebglAddon | null = null; + let webglLoaded = false; + const scopedWindow = window as Window & { + __xtermWebGLLoaded?: boolean; + __xtermRendererPreference?: string; + }; + + if (performanceConfig.useWebGLAddon) { + try { + webglAddon = (() => { + const webglOptions: Record = { useCustomGlyphHandler: true }; + try { + const WebglCtor = WebglAddon as unknown as new (options?: unknown) => WebglAddon; + return new WebglCtor(webglOptions); + } catch { + return new WebglAddon(); + } + })(); + webglAddon.onContextLoss(() => { + logger.warn("[XTerm] WebGL context loss detected, disposing addon"); + webglAddon?.dispose(); + }); + term.loadAddon(webglAddon); + webglLoaded = true; + } catch (webglErr) { + logger.warn( + "[XTerm] WebGL addon failed, using canvas renderer. Error:", + webglErr instanceof Error ? webglErr.message : webglErr, + ); + } + } else { + logger.info( + "[XTerm] Skipping WebGL addon (canvas preferred for macOS profile or low-memory devices)", + ); + } + + scopedWindow.__xtermWebGLLoaded = webglLoaded; + scopedWindow.__xtermRendererPreference = performanceConfig.preferCanvasRenderer + ? "canvas" + : "webgl"; + + const webLinksAddon = new WebLinksAddon((event, uri) => { + const currentLinkModifier = ctx.terminalSettingsRef.current?.linkModifier ?? "none"; + let shouldOpen = false; + switch (currentLinkModifier) { + case "none": + shouldOpen = true; + break; + case "ctrl": + shouldOpen = event.ctrlKey; + break; + case "alt": + shouldOpen = event.altKey; + break; + case "meta": + shouldOpen = event.metaKey; + break; + } + if (!shouldOpen) return; + + if (ctx.terminalBackend.openExternalAvailable()) { + void ctx.terminalBackend.openExternal(uri); + } else { + window.open(uri, "_blank"); + } + }); + term.loadAddon(webLinksAddon); + + logRenderer(); + + const appLevelActions = getAppLevelActions(); + const terminalActions = getTerminalPassthroughActions(); + + term.attachCustomKeyEventHandler((e: KeyboardEvent) => { + if ((e.ctrlKey || e.metaKey) && e.key === "f" && e.type === "keydown") { + e.preventDefault(); + ctx.setIsSearchOpen(true); + return false; + } + + const currentScheme = ctx.hotkeySchemeRef.current; + const currentBindings = ctx.keyBindingsRef.current; + const hotkeyCallback = ctx.onHotkeyActionRef.current; + + if (currentScheme === "disabled" || currentBindings.length === 0) { + return true; + } + + const isMac = currentScheme === "mac"; + const matched = checkAppShortcut(e, currentBindings, isMac); + if (!matched) return true; + + const { action } = matched; + + if (appLevelActions.has(action)) { + e.preventDefault(); + hotkeyCallback?.(action, e); + return false; + } + + if (terminalActions.has(action)) { + e.preventDefault(); + switch (action) { + case "copy": { + const selection = term.getSelection(); + if (selection) navigator.clipboard.writeText(selection); + break; + } + case "paste": { + navigator.clipboard.readText().then((text) => { + const id = ctx.sessionRef.current; + if (id) ctx.terminalBackend.writeToSession(id, text); + }); + break; + } + case "selectAll": { + term.selectAll(); + break; + } + case "clearBuffer": { + term.clear(); + break; + } + case "searchTerminal": { + ctx.setIsSearchOpen(true); + break; + } + } + return false; + } + + return true; + }); + + let cleanupMiddleClick: (() => void) | null = null; + const middleClickPaste = settings?.middleClickPaste ?? true; + if (middleClickPaste) { + const handleMiddleClick = async (e: MouseEvent) => { + if (e.button !== 1) return; + e.preventDefault(); + try { + const text = await navigator.clipboard.readText(); + if (text && ctx.sessionRef.current) { + ctx.terminalBackend.writeToSession(ctx.sessionRef.current, text); + } + } catch (err) { + logger.warn("[Terminal] Failed to paste from clipboard:", err); + } + }; + + ctx.container.addEventListener("auxclick", handleMiddleClick); + cleanupMiddleClick = () => + ctx.container.removeEventListener("auxclick", handleMiddleClick); + } + + fitAddon.fit(); + term.focus(); + + term.onData((data) => { + const id = ctx.sessionRef.current; + if (id) { + ctx.terminalBackend.writeToSession(id, data); + + if (ctx.isBroadcastEnabledRef.current && ctx.onBroadcastInputRef.current) { + ctx.onBroadcastInputRef.current(data, ctx.sessionId); + } + + if (ctx.status === "connected" && ctx.onCommandExecuted) { + if (data === "\r" || data === "\n") { + const cmd = ctx.commandBufferRef.current.trim(); + if (cmd) ctx.onCommandExecuted(cmd, ctx.host.id, ctx.host.label, ctx.sessionId); + ctx.commandBufferRef.current = ""; + } else if (data === "\x7f" || data === "\b") { + ctx.commandBufferRef.current = ctx.commandBufferRef.current.slice(0, -1); + } else if (data === "\x03") { + ctx.commandBufferRef.current = ""; + } else if (data === "\x15") { + ctx.commandBufferRef.current = ""; + } else if (data.length === 1 && data.charCodeAt(0) >= 32) { + ctx.commandBufferRef.current += data; + } else if (data.length > 1 && !data.startsWith("\x1b")) { + ctx.commandBufferRef.current += data; + } + } + } + }); + + let resizeTimeout: NodeJS.Timeout | null = null; + const resizeDebounceMs = XTERM_PERFORMANCE_CONFIG.resize.debounceMs; + term.onResize(({ cols, rows }) => { + const id = ctx.sessionRef.current; + if (!id) return; + if (resizeTimeout) clearTimeout(resizeTimeout); + resizeTimeout = setTimeout(() => { + ctx.terminalBackend.resizeSession(id, cols, rows); + resizeTimeout = null; + }, resizeDebounceMs); + }); + + return { + term, + fitAddon, + serializeAddon, + searchAddon, + dispose: () => { + cleanupMiddleClick?.(); + try { + term.dispose(); + } catch (err) { + logger.warn("[XTerm] dispose failed", err); + } + try { + fitAddon.dispose(); + } catch (err) { + logger.warn("[XTerm] fitAddon dispose failed", err); + } + try { + serializeAddon.dispose(); + } catch (err) { + logger.warn("[XTerm] serializeAddon dispose failed", err); + } + try { + searchAddon.dispose(); + } catch (err) { + logger.warn("[XTerm] searchAddon dispose failed", err); + } + try { + webglAddon?.dispose(); + } catch (err) { + logger.warn("[XTerm] webglAddon dispose failed", err); + } + }, + }; +};