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 "@xterm/xterm/css/xterm.css"; import { Cpu, Copy, HardDrive, Maximize2, MemoryStick, Radio, ArrowDownToLine, ArrowUpFromLine } from "lucide-react"; import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import ReactDOM from "react-dom"; import { useI18n } from "../application/i18n/I18nProvider"; import { logger } from "../lib/logger"; import { cn, normalizeLineEndings, wrapBracketedPaste } from "../lib/utils"; import { Host, Identity, KnownHost, SerialConfig, SSHKey, Snippet, TerminalSession, TerminalTheme, TerminalSettings, KeyBinding, } from "../types"; import { shouldEnableNativeUserInputAutoScroll, shouldScrollOnTerminalInput, } from "../domain/terminalScroll"; import { applyCustomAccentToTerminalTheme, resolveHostTerminalThemeId, } from "../domain/terminalAppearance"; import { classifyDistroId } from "../domain/host"; import { resolveHostAuth } from "../domain/sshAuth"; import { useTerminalBackend } from "../application/state/useTerminalBackend"; // SFTPModal removed - SFTP is now handled by SftpSidePanel in TerminalLayer import { Button } from "./ui/button"; import { HoverCard, HoverCardContent, HoverCardTrigger } from "./ui/hover-card"; import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip"; import { toast } from "./ui/toast"; import { useAvailableFonts } from "../application/state/fontStore"; import { composeFontFamilyStack, type SupportedPlatform } from "../infrastructure/config/cjkFonts"; import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes"; import { useCustomThemes } from "../application/state/customThemeStore"; import { TerminalConnectionDialog } from "./terminal/TerminalConnectionDialog"; import { HostKeyInfo } from "./terminal/TerminalHostKeyVerification"; import { createKnownHostFromHostKeyInfo, toHostKeyInfo } from "./terminal/hostKeyVerification"; import { TerminalToolbar } from "./terminal/TerminalToolbar"; import { TerminalComposeBar } from "./terminal/TerminalComposeBar"; import { TerminalContextMenu } from "./terminal/TerminalContextMenu"; import { TerminalSearchBar } from "./terminal/TerminalSearchBar"; import { ZmodemProgressIndicator } from "./terminal/ZmodemProgressIndicator"; import { createReplaySafeTerminalLogSanitizer } from "./terminal/replaySafeTerminalLog"; import { useZmodemTransfer } from "./terminal/hooks/useZmodemTransfer"; import { createTerminalSessionStarters, type PendingAuth } from "./terminal/runtime/createTerminalSessionStarters"; import { createXTermRuntime, primaryFontFamily, type XTermRuntime } from "./terminal/runtime/createXTermRuntime"; import { applyUserCursorPreference } from "./terminal/runtime/cursorPreference"; import { shouldPreserveTerminalFocusOnMouseDown } from "./terminal/toolbarFocus"; import { preserveTerminalViewportInScrollback } from "./terminal/clearTerminalViewport"; 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"; import { useServerStats } from "./terminal/hooks/useServerStats"; import { extractDropEntries, getPathForFile, DropEntry } from "../lib/sftpFileUtils"; import { useTerminalAutocomplete, AutocompletePopup } from "./terminal/autocomplete"; const MAX_CONNECTION_LOG_DATA_CHARS = 1_000_000; /** * Extract unique root paths from drop entries for local terminal path insertion. * For nested files, extracts the root folder path; for single files, uses the full path. * Paths with spaces are quoted. */ function extractRootPathsFromDropEntries(dropEntries: DropEntry[]): string[] { const paths: string[] = []; const seenPaths = new Set(); for (const entry of dropEntries) { if (!entry.file) continue; const fullPath = getPathForFile(entry.file); if (!fullPath) continue; const pathParts = entry.relativePath.split('/'); if (pathParts.length > 1) { // Nested file in a folder - extract the root folder path const rootFolderName = pathParts[0]; const separator = fullPath.includes('\\') ? '\\' : '/'; // Find the position of the root folder name in the full path const rootFolderIndex = fullPath.lastIndexOf(separator + rootFolderName + separator); const altRootFolderIndex = fullPath.lastIndexOf(separator + rootFolderName); const folderStartIndex = rootFolderIndex !== -1 ? rootFolderIndex + 1 : (altRootFolderIndex !== -1 ? altRootFolderIndex + 1 : -1); if (folderStartIndex !== -1) { const folderEndIndex = folderStartIndex + rootFolderName.length; const folderPath = fullPath.substring(0, folderEndIndex); if (!seenPaths.has(folderPath)) { paths.push(folderPath.includes(' ') ? `"${folderPath}"` : folderPath); seenPaths.add(folderPath); } } } else { // Single file (not in a folder) if (!seenPaths.has(fullPath)) { paths.push(fullPath.includes(' ') ? `"${fullPath}"` : fullPath); seenPaths.add(fullPath); } } } return paths; } interface TerminalProps { host: Host; keys: SSHKey[]; identities: Identity[]; snippets: Snippet[]; chainHosts?: Host[]; themePreviewId?: string; knownHosts?: KnownHost[]; isVisible: boolean; inWorkspace?: boolean; isResizing?: boolean; isFocusMode?: boolean; isFocused?: boolean; fontFamilyId: string; fontSize: number; terminalTheme: TerminalTheme; followAppTerminalTheme?: boolean; accentMode?: "theme" | "custom"; customAccent?: string; terminalSettings?: TerminalSettings; sessionId: string; startupCommand?: string; noAutoRun?: boolean; serialConfig?: SerialConfig; hotkeyScheme?: "disabled" | "mac" | "pc"; keyBindings?: KeyBinding[]; onHotkeyAction?: (action: string, event: KeyboardEvent) => void; onStatusChange?: (sessionId: string, status: TerminalSession["status"]) => void; onSessionExit?: (sessionId: string, evt: { exitCode?: number; signal?: number; error?: string; reason?: "exited" | "error" | "timeout" | "closed" }) => void; onTerminalDataCapture?: (sessionId: string, data: string) => void; onOsDetected?: (hostId: string, distro: string) => void; onCloseSession?: (sessionId: string) => void; onUpdateHost?: (host: Host) => void; onAddKnownHost?: (knownHost: KnownHost) => void; onExpandToFocus?: () => void; onCommandExecuted?: ( command: string, hostId: string, hostLabel: string, sessionId: string, ) => void; onSplitHorizontal?: () => void; onSplitVertical?: () => void; onOpenSftp?: ( host: Host, initialPath?: string, pendingUploadEntries?: DropEntry[], sourceSessionId?: string, ) => void; onOpenScripts?: () => void; onOpenTheme?: () => void; isBroadcastEnabled?: boolean; onToggleBroadcast?: () => void; onToggleComposeBar?: () => void; isWorkspaceComposeBarOpen?: boolean; onBroadcastInput?: (data: string, sourceSessionId: string) => void; onSnippetExecutorChange?: ( sessionId: string, executor: ((command: string, noAutoRun?: boolean) => void) | null, ) => void; // Session log configuration for real-time streaming sessionLog?: { enabled: boolean; directory: string; format: string }; } // Helper function to format network speed (bytes/sec) to human-readable format function formatNetSpeed(bytesPerSec: number): string { if (bytesPerSec < 1024) { return `${bytesPerSec}B/s`; } else if (bytesPerSec < 1024 * 1024) { return `${(bytesPerSec / 1024).toFixed(1)}K/s`; } else if (bytesPerSec < 1024 * 1024 * 1024) { return `${(bytesPerSec / (1024 * 1024)).toFixed(1)}M/s`; } else { return `${(bytesPerSec / (1024 * 1024 * 1024)).toFixed(1)}G/s`; } } type XTermWithPrivateRenderService = XTerm & { _core?: { _renderService?: { _renderRows?: (start: number, end: number) => void; }; }; }; function forceSyncRenderAfterResize(term: XTerm): void { const renderService = (term as XTermWithPrivateRenderService)._core?._renderService; const renderRows = renderService?._renderRows; if (typeof renderRows !== "function") return; const endRow = term.rows - 1; if (endRow < 0) return; try { renderRows.call(renderService, 0, endRow); } catch (err) { logger.warn("Sync render after resize failed", err); } } const TerminalComponent: React.FC = ({ host, keys, identities, snippets, chainHosts = [], themePreviewId, knownHosts = [], isVisible, inWorkspace, isResizing, isFocusMode, isFocused, fontFamilyId, fontSize, terminalTheme, followAppTerminalTheme = false, accentMode = "theme", customAccent = "", terminalSettings, sessionId, startupCommand, noAutoRun, serialConfig, hotkeyScheme = "disabled", keyBindings = [], onHotkeyAction, onStatusChange, onSessionExit, onTerminalDataCapture, onOsDetected, onCloseSession, onUpdateHost, onAddKnownHost, onExpandToFocus, onCommandExecuted, onSplitHorizontal, onSplitVertical, onOpenSftp, onOpenScripts, onOpenTheme, isBroadcastEnabled, onToggleBroadcast, onToggleComposeBar, isWorkspaceComposeBarOpen, onBroadcastInput, onSnippetExecutorChange, sessionLog, }) => { // Timeout for connection - increased to 120s to allow time for keyboard-interactive (2FA) authentication const CONNECTION_TIMEOUT = 120000; const { t } = useI18n(); const availableFonts = useAvailableFonts(); const containerRef = useRef(null); const termRef = useRef(null); const fitAddonRef = useRef(null); const serializeAddonRef = useRef(null); const searchAddonRef = useRef(null); const xtermRuntimeRef = useRef(null); const knownCwdRef = useRef(undefined); const disposeDataRef = useRef<(() => void) | null>(null); const disposeExitRef = useRef<(() => void) | null>(null); const sessionRef = useRef(null); const hasConnectedRef = useRef(false); const hasRunStartupCommandRef = useRef(false); // Token for an in-flight retry chain. handleRetry sets this to a fresh // symbol; any cancel/close/teardown/subsequent-retry invalidates it. The // chained xterm.write callbacks verify the token before proceeding so a // cancelled retry can't fire a startNewSession after the fact. const retryTokenRef = useRef(null); const terminalDataCapturedRef = useRef(false); const terminalLogDataRef = useRef(""); const terminalLogSanitizerRef = useRef(createReplaySafeTerminalLogSanitizer()); const onTerminalDataCaptureRef = useRef(onTerminalDataCapture); const commandBufferRef = useRef(""); const [hasMouseTracking, setHasMouseTracking] = useState(false); const mouseTrackingRef = useRef(false); const serialLineBufferRef = useRef(""); const terminalSettingsRef = useRef(terminalSettings); terminalSettingsRef.current = terminalSettings; onTerminalDataCaptureRef.current = onTerminalDataCapture; const isVisibleRef = useRef(isVisible); isVisibleRef.current = isVisible; const pendingOutputScrollRef = useRef(false); const lastFittedSizeRef = useRef<{ width: number; height: number } | null>(null); const fontWeightFixupDoneRef = useRef(false); const captureTerminalLogData = useCallback((data: string) => { const replaySafeData = terminalLogSanitizerRef.current.append(data); if (!replaySafeData) return; terminalLogDataRef.current += replaySafeData; if (terminalLogDataRef.current.length > MAX_CONNECTION_LOG_DATA_CHARS) { terminalLogDataRef.current = terminalLogDataRef.current.slice(-MAX_CONNECTION_LOG_DATA_CHARS); } }, []); const finalizeTerminalLogData = useCallback(() => { const replaySafeData = terminalLogSanitizerRef.current.finish(); if (replaySafeData) { terminalLogDataRef.current += replaySafeData; if (terminalLogDataRef.current.length > MAX_CONNECTION_LOG_DATA_CHARS) { terminalLogDataRef.current = terminalLogDataRef.current.slice(-MAX_CONNECTION_LOG_DATA_CHARS); } } return terminalLogDataRef.current; }, []); const writeLocalTerminalData = useCallback((data: string) => { if (!data) return; captureTerminalLogData(data); termRef.current?.write(data); }, [captureTerminalLogData]); useEffect(() => { if (xtermRuntimeRef.current) { // Merge global rules with host-level rules const globalRules = terminalSettings?.keywordHighlightRules ?? []; const hostRules = host?.keywordHighlightRules ?? []; const globalEnabled = terminalSettings?.keywordHighlightEnabled ?? false; // Host-level toggle: undefined = inherit global, true/false = explicit override const hostEnabled = host?.keywordHighlightEnabled; // Global and host-level highlights are independent: // global toggle controls global rules, host toggle controls host-specific rules const effectiveGlobalEnabled = globalEnabled; const effectiveHostEnabled = hostEnabled ?? false; const mergedRules = [ ...(effectiveGlobalEnabled ? globalRules : []), ...(effectiveHostEnabled ? hostRules : []) ]; const isEnabled = effectiveGlobalEnabled || effectiveHostEnabled; xtermRuntimeRef.current.keywordHighlighter.setRules(mergedRules, isEnabled); } }, [ terminalSettings?.keywordHighlightEnabled, terminalSettings?.keywordHighlightRules, host?.keywordHighlightEnabled, host?.keywordHighlightRules ]); const hotkeySchemeRef = useRef(hotkeyScheme); const keyBindingsRef = useRef(keyBindings); const onHotkeyActionRef = useRef(onHotkeyAction); hotkeySchemeRef.current = hotkeyScheme; keyBindingsRef.current = keyBindings; onHotkeyActionRef.current = onHotkeyAction; const isBroadcastEnabledRef = useRef(isBroadcastEnabled); const onBroadcastInputRef = useRef(onBroadcastInput); isBroadcastEnabledRef.current = isBroadcastEnabled; onBroadcastInputRef.current = onBroadcastInput; // Snippets ref for shortkey support in terminal const snippetsRef = useRef(snippets); snippetsRef.current = snippets; // Autocomplete handler refs (set after hook initialization) const autocompleteKeyEventRef = useRef<((e: KeyboardEvent) => boolean) | undefined>(undefined); const autocompleteInputRef = useRef<((data: string) => void) | undefined>(undefined); const autocompleteRepositionRef = useRef<(() => void) | undefined>(undefined); const terminalBackend = useTerminalBackend(); const { resizeSession, setSessionEncoding } = terminalBackend; // isScriptsOpen state removed - scripts now handled by side panel const [status, setStatus] = useState("connecting"); const [error, setError] = useState(null); const lastToastedErrorRef = useRef(null); const [showLogs, setShowLogs] = useState(false); const [progressLogs, setProgressLogs] = useState([]); const [timeLeft, setTimeLeft] = useState(CONNECTION_TIMEOUT / 1000); const [isCancelling, setIsCancelling] = useState(false); const [showSFTP, setShowSFTP] = useState(false); const [progressValue, setProgressValue] = useState(15); const [hasSelection, setHasSelection] = useState(false); const [isDisconnectedDialogDismissed, setIsDisconnectedDialogDismissed] = useState(false); const statusRef = useRef(status); statusRef.current = status; // Work around xterm.js WebGL renderer bug: glyphs rendered via the constructor // look different from dynamically-set ones. After text appears on screen (status // becomes "connected"), do a fontWeight round-trip to normalize the rendering. useEffect(() => { if (status !== 'connected' || fontWeightFixupDoneRef.current || !termRef.current) return; fontWeightFixupDoneRef.current = true; const timer = setTimeout(() => { if (!termRef.current) return; // Re-read the current weight at fire time to avoid stale closures const w = termRef.current.options.fontWeight; if (w === 'normal' || w === 400) return; termRef.current.options.fontWeight = 'normal'; termRef.current.options.fontWeight = w; }, 200); return () => clearTimeout(timer); }, [status]); const [chainProgress, setChainProgress] = useState<{ currentHop: number; totalHops: number; currentHostLabel: string; } | null>(null); // Drag and drop state const [isDraggingOver, setIsDraggingOver] = useState(false); const dragCounterRef = useRef(0); // pendingUploadEntries removed - drag-drop uploads now handled by SftpSidePanel const [isComposeBarOpen, setIsComposeBarOpen] = useState(false); const [terminalEncoding, setTerminalEncoding] = useState<'utf-8' | 'gb18030'>(() => { if (host?.charset && /^gb/i.test(String(host.charset).trim())) return 'gb18030'; return 'utf-8'; }); const terminalEncodingRef = useRef(terminalEncoding); terminalEncodingRef.current = terminalEncoding; // True only after the user actively picks an encoding from the toolbar. // onSessionAttached uses this to decide whether to override the backend's // initial charset for telnet/serial reconnects — on a first attach we // must not overwrite arbitrary host.charset values (latin1/shift_jis/...) // that the UI's two-value state can't represent. const userPickedEncodingRef = useRef(false); const terminalSearch = useTerminalSearch({ searchAddonRef, termRef }); const { isSearchOpen, setIsSearchOpen, searchMatchCount, handleToggleSearch, handleSearch, handleFindNext, handleFindPrevious, handleCloseSearch, } = terminalSearch; // Terminal autocomplete — onAcceptText writes directly to session (no CustomEvent) const autocompleteAcceptTextRef = useRef<((text: string) => void) | undefined>(undefined); autocompleteAcceptTextRef.current = (text: string) => { const id = sessionRef.current; if (id && text) { // Serial line mode: buffer text and handle local echo instead of direct send if (host.protocol === "serial" && serialConfig?.lineMode) { for (const ch of text) { if (ch === "\r") { const line = serialLineBufferRef.current + "\r"; terminalBackend.writeToSession(id, line); serialLineBufferRef.current = ""; if (serialConfig?.localEcho) writeLocalTerminalData("\r\n"); } else if (ch === "\x15") { if (serialConfig?.localEcho && serialLineBufferRef.current.length > 0) { writeLocalTerminalData("\b \b".repeat(serialLineBufferRef.current.length)); } serialLineBufferRef.current = ""; } else if (ch === "\b" || ch === "\x7f") { if (serialLineBufferRef.current.length > 0) { serialLineBufferRef.current = serialLineBufferRef.current.slice(0, -1); if (serialConfig?.localEcho) writeLocalTerminalData("\b \b"); } } else if (ch.charCodeAt(0) >= 32) { serialLineBufferRef.current += ch; if (serialConfig?.localEcho) writeLocalTerminalData(ch); } } // Still update commandBuffer and broadcast for serial line mode // (fall through to shared bookkeeping below — don't return early) } else if (host.protocol === "serial" && serialConfig?.localEcho) { // Serial character mode with local echo: echo accepted text locally terminalBackend.writeToSession(id, text); for (const ch of text) { if (ch === "\r") { writeLocalTerminalData("\r\n"); } else if (ch.charCodeAt(0) >= 32) { writeLocalTerminalData(ch); } } } else { terminalBackend.writeToSession(id, text); } // Broadcast to other sessions if broadcast mode is enabled if (isBroadcastEnabledRef.current && onBroadcastInputRef.current) { onBroadcastInputRef.current(text, sessionId); } // Update command buffer for onCommandExecuted tracking for (const ch of text) { if (ch === "\r" || ch === "\n") { const cmd = commandBufferRef.current.trim(); if (cmd && onCommandExecuted) onCommandExecuted(cmd, host.id, host.label, sessionId); commandBufferRef.current = ""; } else if (ch === "\x15") { // Ctrl+U: clear line — reset command buffer (fuzzy match sends this) commandBufferRef.current = ""; } else if (ch === "\b" || ch === "\x7f") { // Backspace: remove last character (Windows fuzzy replacement uses \b) commandBufferRef.current = commandBufferRef.current.slice(0, -1); } else if (ch.charCodeAt(0) >= 32) { commandBufferRef.current += ch; } } } }; const autocomplete = useTerminalAutocomplete({ termRef, sessionId, hostId: host.id, hostOs: host.os || (host.protocol === "local" ? (navigator.platform?.startsWith("Win") ? "windows" : navigator.platform?.startsWith("Mac") ? "macos" : "linux") : "linux"), settings: terminalSettings ? { enabled: terminalSettings.autocompleteEnabled ?? true, showGhostText: terminalSettings.autocompleteGhostText ?? true, showPopupMenu: terminalSettings.autocompletePopupMenu ?? true, debounceMs: terminalSettings.autocompleteDebounceMs ?? 100, minChars: terminalSettings.autocompleteMinChars ?? 1, maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 8, } : undefined, onAcceptText: (text) => autocompleteAcceptTextRef.current?.(text), protocol: host.protocol, getCwd: () => knownCwdRef.current ?? xtermRuntimeRef.current?.currentCwd, }); // Wire up autocomplete handler refs so createXTermRuntime can use them autocompleteKeyEventRef.current = autocomplete.handleKeyEvent; autocompleteInputRef.current = autocomplete.handleInput; autocompleteRepositionRef.current = autocomplete.repositionPopup; const autocompleteClosePopup = autocomplete.closePopup; useEffect(() => { knownCwdRef.current = undefined; }, [sessionId, host.id]); useEffect(() => { if (host.protocol === "local" || host.protocol === "serial" || host.protocol === "telnet") { return; } if (status !== "connected" || !sessionRef.current || knownCwdRef.current) return; let cancelled = false; const timer = setTimeout(async () => { if (!sessionRef.current) return; try { const result = await terminalBackend.getSessionPwd(sessionRef.current); if (!cancelled && result.success && result.cwd) { knownCwdRef.current = result.cwd; } } catch { // Best effort only. } }, 150); return () => { cancelled = true; clearTimeout(timer); }; }, [host.protocol, status, terminalBackend]); useEffect(() => { if (!isVisible) { autocompleteClosePopup(); } }, [isVisible, autocompleteClosePopup]); // Check if this is a local or serial connection (doesn't need connection dialog during connecting) const isLocalConnection = host.protocol === "local"; const isSerialConnection = host.protocol === "serial"; // Server stats (CPU, Memory, Disk) — only for Linux/macOS, and never // for hosts classified as network devices (either via explicit // deviceType='network' or via SSH banner detection that populated // host.distro with a network-vendor ID). See #674: polling the stats // command on Cisco / Huawei / Juniper etc. generates one AAA session // log entry per poll because each exec channel is counted as a new // session on those devices. // // IMPORTANT: this gating must NOT go through getEffectiveHostDistro() // because that honors the manual distro override (`distroMode: 'manual'` // + `manualDistro`) which is purely a cosmetic icon choice. A user who // pinned an "ubuntu" icon on what is actually a Cisco host would // otherwise silently re-enable the polling loop and re-introduce the // AAA log flood this patch is meant to eliminate. The display icon can // still be overridden (see DistroAvatar) — gating uses the raw detected // `host.distro` and the explicit `host.deviceType` only. const detectedDeviceClass = classifyDistroId(host.distro); const isNetworkDevice = host.deviceType === 'network' || detectedDeviceClass === 'network-device'; const isSupportedOs = !isNetworkDevice && (host.os === 'linux' || host.os === 'macos' || detectedDeviceClass === 'linux-like'); const { stats: serverStats } = useServerStats({ sessionId, enabled: terminalSettings?.showServerStats ?? true, refreshInterval: terminalSettings?.serverStatsRefreshInterval ?? 5, isSupportedOs, isConnected: status === 'connected', isVisible, }); const zmodem = useZmodemTransfer(sessionId); const zmodemToastedRef = useRef(false); useEffect(() => { if (zmodem.active) { zmodemToastedRef.current = false; return; } if (zmodemToastedRef.current) return; if (zmodem.error) { zmodemToastedRef.current = true; toast.error(zmodem.error, 'ZMODEM'); } else if (zmodem.filename) { zmodemToastedRef.current = true; toast.success( `${zmodem.transferType === 'upload' ? 'Uploaded' : 'Downloaded'}: ${zmodem.filename}`, 'ZMODEM', ); } }, [zmodem.active, zmodem.error, zmodem.filename, zmodem.transferType]); useEffect(() => { if (!error) { lastToastedErrorRef.current = null; return; } if (lastToastedErrorRef.current === error) return; lastToastedErrorRef.current = error; toast.error(error, t("terminal.connectionErrorTitle")); }, [error, t]); const pendingAuthRef = useRef(null); const sessionStartersRef = useRef | null>(null); const auth = useTerminalAuthState({ host, pendingAuthRef, termRef, onUpdateHost, onStartSession: (term) => { const starters = sessionStartersRef.current; if (!starters) return; if (host.moshEnabled) { starters.startMosh(term); return; } starters.startSSH(term); }, setStatus: (next) => setStatus(next), setProgressLogs, }); const [needsHostKeyVerification, setNeedsHostKeyVerification] = useState(false); const [pendingHostKeyInfo, setPendingHostKeyInfo] = useState(null); const [pendingHostKeyRequestId, setPendingHostKeyRequestId] = useState(null); const pendingConnectionRef = useRef<(() => void) | null>(null); // OSC-52 clipboard read prompt const [osc52ReadPromptVisible, setOsc52ReadPromptVisible] = useState(false); const osc52ReadResolverRef = useRef<((allowed: boolean) => void) | null>(null); const handleOsc52ReadRequest = useCallback((): Promise => { // Reject if terminal is not visible (background tab) — user can't see the prompt if (!isVisibleRef.current) return Promise.resolve(false); // Reject if another prompt is already pending (avoid resolver overwrite) if (osc52ReadResolverRef.current) return Promise.resolve(false); return new Promise((resolve) => { osc52ReadResolverRef.current = resolve; setOsc52ReadPromptVisible(true); }); }, []); const handleOsc52ReadResponse = useCallback((allowed: boolean) => { setOsc52ReadPromptVisible(false); osc52ReadResolverRef.current?.(allowed); osc52ReadResolverRef.current = null; // Restore focus to terminal termRef.current?.focus(); }, []); useEffect(() => { const dispose = terminalBackend.onHostKeyVerification?.((request) => { if (request.sessionId !== sessionId) return; setPendingHostKeyRequestId(request.requestId); setPendingHostKeyInfo(toHostKeyInfo(request)); setNeedsHostKeyVerification(true); setError(null); setProgressLogs((prev) => [ ...prev, request.status === 'changed' ? `Host key changed for ${request.hostname}. Waiting for confirmation...` : `Host key verification required for ${request.hostname}.`, ]); }); return () => { dispose?.(); }; }, [sessionId, terminalBackend]); const handleTopOverlayMouseDownCapture = useCallback((e: React.MouseEvent) => { if (e.button !== 0) return; if (!shouldPreserveTerminalFocusOnMouseDown(e.target)) return; e.preventDefault(); }, []); // Subscribe to custom theme changes so editing triggers re-render const customThemes = useCustomThemes(); const hasFontSizeOverride = host.fontSizeOverride === true || (host.fontSizeOverride === undefined && host.fontSize != null); const hasFontFamilyOverride = host.fontFamilyOverride === true || (host.fontFamilyOverride === undefined && !!host.fontFamily); const hasFontWeightOverride = host.fontWeightOverride === true || (host.fontWeightOverride === undefined && host.fontWeight != null); const effectiveFontSize = useMemo( () => (hasFontSizeOverride && host.fontSize != null ? host.fontSize : fontSize), [fontSize, hasFontSizeOverride, host.fontSize], ); const effectiveFontWeight = useMemo( () => (hasFontWeightOverride && host.fontWeight != null ? host.fontWeight : (terminalSettings?.fontWeight ?? 400)), [terminalSettings?.fontWeight, hasFontWeightOverride, host.fontWeight], ); const resolvedFontFamily = useMemo(() => { const hostFontId = hasFontFamilyOverride && host.fontFamily ? host.fontFamily : fontFamilyId; const resolvedFontId = hostFontId || "menlo"; const selectedFont = availableFonts.find((f) => f.id === resolvedFontId) || availableFonts[0]; const platform: SupportedPlatform = typeof navigator !== "undefined" && /Mac/i.test(navigator.platform) ? "darwin" : typeof navigator !== "undefined" && /Win/i.test(navigator.platform) ? "win32" : "linux"; return composeFontFamilyStack({ primaryFamily: selectedFont.family, userFallback: terminalSettings?.fallbackFont ?? "", latinFontId: resolvedFontId, platform, }); }, [availableFonts, fontFamilyId, hasFontFamilyOverride, host.fontFamily, terminalSettings?.fallbackFont]); const effectiveTheme = useMemo(() => { // When "Follow Application Theme" is on and there's no active // preview, skip per-host overrides — all terminals should use the // UI-matched theme passed via terminalTheme prop. if (followAppTerminalTheme && !themePreviewId) { return applyCustomAccentToTerminalTheme(terminalTheme, accentMode, customAccent); } const themeId = themePreviewId ?? resolveHostTerminalThemeId( { theme: host.theme, themeOverride: host.themeOverride } as Pick, terminalTheme.id, ); let baseTheme = terminalTheme; if (themeId) { const hostTheme = TERMINAL_THEMES.find((t) => t.id === themeId) || customThemes.find((t) => t.id === themeId); if (hostTheme) baseTheme = hostTheme; } return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent); }, [accentMode, customAccent, customThemes, followAppTerminalTheme, host.theme, host.themeOverride, terminalTheme, themePreviewId]); const resolvedChainHosts = chainHosts; const updateStatus = (next: TerminalSession["status"]) => { setStatus(next); hasConnectedRef.current = next === "connected"; onStatusChange?.(sessionId, next); }; const handleTerminalDataCaptureOnce = useCallback((capturedSessionId: string, data: string) => { const captureHandler = onTerminalDataCaptureRef.current; if (!captureHandler || terminalDataCapturedRef.current) return; terminalDataCapturedRef.current = true; const replaySafeLogData = finalizeTerminalLogData(); const capturedData = replaySafeLogData || data; captureHandler(capturedSessionId, capturedData); }, [finalizeTerminalLogData]); const cleanupSession = () => { disposeDataRef.current?.(); disposeDataRef.current = null; disposeExitRef.current?.(); disposeExitRef.current = null; if (sessionRef.current) { try { terminalBackend.closeSession(sessionRef.current); } catch (err) { logger.warn("Failed to close SSH session", err); } } sessionRef.current = null; }; const teardown = () => { retryTokenRef.current = null; cleanupSession(); xtermRuntimeRef.current?.dispose(); xtermRuntimeRef.current = null; termRef.current = null; fitAddonRef.current = null; serializeAddonRef.current = null; searchAddonRef.current = null; }; const sessionStarters = createTerminalSessionStarters({ host, keys, identities, knownHosts, resolvedChainHosts, sessionId, startupCommand, noAutoRun, terminalSettings, terminalSettingsRef, terminalBackend, serialConfig, isVisibleRef, pendingOutputScrollRef, sessionRef, hasConnectedRef, hasRunStartupCommandRef, disposeDataRef, disposeExitRef, fitAddonRef, serializeAddonRef, pendingAuthRef, updateStatus, setStatus, setError, setNeedsAuth: auth.setNeedsAuth, setAuthRetryMessage: auth.setAuthRetryMessage, setAuthPassword: auth.setAuthPassword, setProgressLogs, setProgressValue, setChainProgress, t, onSessionAttached: (id: string) => { // SSH: always sync. Its backend starts in utf-8 regardless of // host.charset, so the push is what keeps the UI state aligned // across reconnects — including localhost SSH targets, hence // hostname isn't in the gate. const isLocal = host.protocol === 'local' || host.id?.startsWith('local-'); const isSerial = host.protocol === 'serial' || host.id?.startsWith('serial-'); const isTelnet = host.protocol === 'telnet'; const isMosh = host.protocol === 'mosh' || host.moshEnabled; const isSSH = !isLocal && !isSerial && !isTelnet && !isMosh; if (isSSH) { setSessionEncoding(id, terminalEncodingRef.current); return; } // Telnet / serial: the backend already applied host.charset // (including arbitrary iconv labels like latin1 / shift_jis that // the UI's two-value state can't represent) through start*Session // options, so don't clobber it on first attach. Only re-sync once // the user has explicitly picked from the toolbar menu — that's // the signal they want the UI choice to win on reconnect. if ((isTelnet || isSerial) && userPickedEncodingRef.current) { setSessionEncoding(id, terminalEncodingRef.current); } }, onSessionExit, onTerminalDataCapture: handleTerminalDataCaptureOnce, onTerminalLogData: captureTerminalLogData, onOsDetected, onCommandExecuted, sessionLog, }); sessionStartersRef.current = sessionStarters; useEffect(() => { let disposed = false; terminalDataCapturedRef.current = false; terminalLogDataRef.current = ""; terminalLogSanitizerRef.current = createReplaySafeTerminalLogSanitizer(); setError(null); hasConnectedRef.current = false; pendingOutputScrollRef.current = false; setProgressLogs([]); setShowLogs(false); setIsCancelling(false); setIsDisconnectedDialogDismissed(false); const boot = async () => { try { if (disposed || !containerRef.current) return; const runtime = createXTermRuntime({ container: containerRef.current, host, fontFamilyId, fontSize, terminalTheme: effectiveTheme, terminalSettingsRef, terminalBackend, sessionRef, hotkeySchemeRef, keyBindingsRef, onHotkeyActionRef, isBroadcastEnabledRef, onBroadcastInputRef, snippetsRef, sessionId, statusRef, onCommandExecuted, commandBufferRef, setIsSearchOpen, // Serial-specific options serialLocalEcho: serialConfig?.localEcho, serialLineMode: serialConfig?.lineMode, serialLineBufferRef, onTerminalLogData: captureTerminalLogData, onCwdChange: (cwd: string) => { knownCwdRef.current = cwd; }, onOsc52ReadRequest: handleOsc52ReadRequest, // Autocomplete integration onAutocompleteKeyEvent: (e: KeyboardEvent) => autocompleteKeyEventRef.current?.(e) ?? true, onAutocompleteInput: (data: string) => autocompleteInputRef.current?.(data), isRestoringSelectionRef, }); xtermRuntimeRef.current = runtime; termRef.current = runtime.term; fitAddonRef.current = runtime.fitAddon; serializeAddonRef.current = runtime.serializeAddon; searchAddonRef.current = runtime.searchAddon; // Apply merged keyword highlight rules immediately after runtime creation // This fixes a timing issue where the useEffect for keyword highlighting // runs before the runtime is created, causing host-level rules to be missed const globalRules = terminalSettingsRef.current?.keywordHighlightRules ?? []; const hostRules = host?.keywordHighlightRules ?? []; const globalEnabled = terminalSettingsRef.current?.keywordHighlightEnabled ?? false; const hostEnabled = host?.keywordHighlightEnabled; const effectiveGlobalEnabled = globalEnabled; const effectiveHostEnabled = hostEnabled ?? false; const mergedRules = [ ...(effectiveGlobalEnabled ? globalRules : []), ...(effectiveHostEnabled ? hostRules : []) ]; const isEnabled = effectiveGlobalEnabled || effectiveHostEnabled; runtime.keywordHighlighter.setRules(mergedRules, isEnabled); const term = runtime.term; if (host.protocol === "serial") { setStatus("connecting"); setProgressLogs(["Initializing serial connection..."]); await sessionStarters.startSerial(term); } else if (host.protocol === "local" || host.hostname === "localhost") { setStatus("connecting"); setProgressLogs(["Initializing local shell..."]); await sessionStarters.startLocal(term); } else if (host.protocol === "telnet") { setStatus("connecting"); setProgressLogs(["Initializing Telnet connection..."]); await sessionStarters.startTelnet(term); } else if (host.moshEnabled) { setStatus("connecting"); setProgressLogs(["Initializing Mosh connection..."]); await sessionStarters.startMosh(term); } else { const resolvedAuth = resolveHostAuth({ host, keys, identities }); const hasPassword = !!resolvedAuth.password; const hasKey = !!resolvedAuth.keyId; const hasPendingAuth = pendingAuthRef.current; if ( !hasPassword && !hasKey && !hasPendingAuth && !resolvedAuth.username ) { auth.setNeedsAuth(true); setStatus("disconnected"); return; } setStatus("connecting"); setProgressLogs(["Initializing secure channel..."]); await sessionStarters.startSSH(term); } } catch (err) { logger.error("Failed to initialize terminal", err); setError(err instanceof Error ? err.message : String(err)); updateStatus("disconnected"); } }; boot(); return () => { disposed = true; if (!terminalDataCapturedRef.current && serializeAddonRef.current) { try { const terminalData = serializeAddonRef.current.serialize(); logger.info("[Terminal] Capturing data on unmount", { sessionId, dataLength: terminalData.length }); handleTerminalDataCaptureOnce(sessionId, terminalData); } catch (err) { logger.warn("Failed to serialize terminal data on unmount:", err); } } teardown(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- Effect only runs on host.id/sessionId change, internal functions are stable }, [handleTerminalDataCaptureOnce, host.id, sessionId]); // Connection timeline and timeout visuals useEffect(() => { if (status !== "connecting" || auth.needsAuth) return; // Local terminal and serial connections don't need timeout/progress UI if (isLocalConnection || isSerialConnection) return; setTimeLeft(CONNECTION_TIMEOUT / 1000); const countdown = setInterval(() => { setTimeLeft((prev) => (prev > 0 ? prev - 1 : 0)); }, 1000); const timeout = setTimeout(() => { setError("Connection timed out. Please try again."); updateStatus("disconnected"); setProgressLogs((prev) => [...prev, "Connection timed out."]); }, CONNECTION_TIMEOUT); setProgressValue(5); const prog = setInterval(() => { setProgressValue((prev) => { if (prev >= 95) return prev; const remaining = 95 - prev; const increment = Math.max(1, remaining * 0.15); return Math.min(95, prev + increment); }); }, 200); return () => { clearInterval(countdown); clearTimeout(timeout); clearInterval(prog); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- updateStatus is a stable internal helper }, [status, auth.needsAuth, host.protocol, host.hostname]); useEffect(() => { if (status === "connecting") { setIsDisconnectedDialogDismissed(false); } }, [status]); const safeFit = (options?: { force?: boolean; requireVisible?: boolean }) => { const fitAddon = fitAddonRef.current; if (!fitAddon) return; if (options?.requireVisible && !isVisibleRef.current) return; const container = containerRef.current; if (!container) return; const width = container.clientWidth; const height = container.clientHeight; if (width <= 0 || height <= 0) { // Terminal is hidden — invalidate the cached size so that when it // becomes visible again, a non-forced fit won't be suppressed by a // stale size match (e.g. after font metrics changed while hidden). lastFittedSizeRef.current = null; return; } if (!options?.force) { const lastSize = lastFittedSizeRef.current; if (lastSize && lastSize.width === width && lastSize.height === height) { autocompleteRepositionRef.current?.(); return; } } const runFit = () => { try { const term = termRef.current; if (!term) return; const dimensions = fitAddon.proposeDimensions(); if (!dimensions || Number.isNaN(dimensions.cols) || Number.isNaN(dimensions.rows)) return; lastFittedSizeRef.current = { width, height }; // addon-fit 0.11 clears the renderer before resizing, which can show // as a one-frame WebGL blink during layout changes. Resize directly // using the proposed dimensions to preserve the existing behavior // without forcing a blank intermediate frame. if (term.cols !== dimensions.cols || term.rows !== dimensions.rows) { term.resize(dimensions.cols, dimensions.rows); forceSyncRenderAfterResize(term); } if (typeof requestAnimationFrame === "function") { requestAnimationFrame(() => { autocompleteRepositionRef.current?.(); }); } else { autocompleteRepositionRef.current?.(); } } catch (err) { logger.warn("Fit failed", err); } }; if ( XTERM_PERFORMANCE_CONFIG.resize.useRAF && typeof requestAnimationFrame === "function" ) { requestAnimationFrame(runFit); } else { runFit(); } }; // Sync xterm theme before browser paint so canvas + DOM CSS vars update in the same frame useLayoutEffect(() => { if (termRef.current) { termRef.current.options.theme = { ...effectiveTheme.colors, selectionBackground: effectiveTheme.colors.selection, scrollbarSliderBackground: effectiveTheme.colors.foreground + '33', scrollbarSliderHoverBackground: effectiveTheme.colors.foreground + '66', scrollbarSliderActiveBackground: effectiveTheme.colors.foreground + '80', }; } }, [effectiveTheme]); useEffect(() => { if (termRef.current) { termRef.current.options.fontSize = effectiveFontSize; termRef.current.options.fontFamily = resolvedFontFamily; if (terminalSettings) { applyUserCursorPreference(termRef.current, terminalSettings); termRef.current.options.scrollback = terminalSettings.scrollback === 0 ? 999999 : terminalSettings.scrollback; termRef.current.options.fontWeight = effectiveFontWeight as | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; const resolvedFontWeightBold = (() => { const fontFamily = termRef.current?.options.fontFamily || ""; if (typeof document === "undefined" || !document.fonts?.check) { return terminalSettings.fontWeightBold; } const weightSpec = `${terminalSettings.fontWeightBold} ${effectiveFontSize}px ${primaryFontFamily(fontFamily)}`; return document.fonts.check(weightSpec) ? terminalSettings.fontWeightBold : effectiveFontWeight; })(); termRef.current.options.fontWeightBold = resolvedFontWeightBold as | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; termRef.current.options.lineHeight = 1 + terminalSettings.linePadding / 10; termRef.current.options.drawBoldTextInBrightColors = terminalSettings.drawBoldInBrightColors; termRef.current.options.minimumContrastRatio = terminalSettings.minimumContrastRatio; termRef.current.options.smoothScrollDuration = terminalSettings.smoothScrolling ? XTERM_PERFORMANCE_CONFIG.rendering.smoothScrollDuration : 0; termRef.current.options.scrollOnUserInput = shouldEnableNativeUserInputAutoScroll(terminalSettings); termRef.current.options.altClickMovesCursor = !terminalSettings.altAsMeta; termRef.current.options.wordSeparator = terminalSettings.wordSeparators; termRef.current.options.ignoreBracketedPasteMode = terminalSettings.disableBracketedPaste ?? false; } if (isVisibleRef.current) { setTimeout(() => safeFit({ force: true, requireVisible: true }), 50); } else { lastFittedSizeRef.current = null; } } }, [effectiveFontSize, effectiveFontWeight, resolvedFontFamily, terminalSettings]); useEffect(() => { if (!isVisible) return; const timer = setTimeout(() => { safeFit({ requireVisible: true }); if (pendingOutputScrollRef.current) { termRef.current?.scrollToBottom(); if (typeof requestAnimationFrame === "function") { requestAnimationFrame(() => { termRef.current?.scrollToBottom(); }); } pendingOutputScrollRef.current = false; } }, 50); return () => clearTimeout(timer); }, [isVisible]); useEffect(() => { let cancelled = false; const waitForFonts = async () => { try { const fontFaceSet = document.fonts as FontFaceSet | undefined; if (!fontFaceSet?.ready) return; await fontFaceSet.ready; if (cancelled) return; const term = termRef.current as { cols: number; rows: number; renderer?: { remeasureFont?: () => void }; } | null; const fitAddon = fitAddonRef.current; try { term?.renderer?.remeasureFont?.(); } catch (err) { logger.warn("Font remeasure failed", err); } try { fitAddon?.fit(); } catch (err) { logger.warn("Fit after fonts ready failed", err); } if (terminalSettings && termRef.current) { const fontFamily = termRef.current.options?.fontFamily || ""; if (typeof document !== "undefined" && document.fonts?.check) { const weightSpec = `${terminalSettings.fontWeightBold} ${effectiveFontSize}px ${primaryFontFamily(fontFamily)}`; const resolvedBold = document.fonts.check(weightSpec) ? terminalSettings.fontWeightBold : effectiveFontWeight; termRef.current.options.fontWeightBold = resolvedBold as | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; } } const id = sessionRef.current; if (id && term) { try { resizeSession(id, term.cols, term.rows); } catch (err) { logger.warn("Resize session after fonts ready failed", err); } } } catch (err) { logger.warn("Waiting for fonts failed", err); } }; waitForFonts(); return () => { cancelled = true; }; }, [effectiveFontSize, effectiveFontWeight, resizeSession, terminalSettings]); useEffect(() => { if (!isVisible || !containerRef.current || !fitAddonRef.current) return; let resizeTimeout: ReturnType | null = null; const observer = new ResizeObserver(() => { if (isResizing || !isVisibleRef.current) return; if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(() => { safeFit({ requireVisible: true }); }, 250); }); observer.observe(containerRef.current); return () => { if (resizeTimeout) clearTimeout(resizeTimeout); observer.disconnect(); }; }, [isVisible, isResizing]); const prevIsResizingRef = useRef(isResizing); useEffect(() => { if (prevIsResizingRef.current && !isResizing && isVisible) { const timer = setTimeout(() => { safeFit({ force: true, requireVisible: true }); }, 100); return () => clearTimeout(timer); } prevIsResizingRef.current = isResizing; }, [isResizing, isVisible]); useEffect(() => { if (!isVisible || !fitAddonRef.current) return; // Fit twice: once after initial layout (100ms) and again after layout settles // (350ms) to handle race conditions during split operations where the container // dimensions may not be final on the first pass. const timer1 = setTimeout(() => { safeFit({ requireVisible: true }); }, 100); const timer2 = setTimeout(() => { safeFit({ force: true, requireVisible: true }); }, 350); return () => { clearTimeout(timer1); clearTimeout(timer2); }; }, [inWorkspace, isVisible]); // When search bar opens/closes, re-fit terminal and maintain scroll position useEffect(() => { const term = termRef.current; if (!term || !fitAddonRef.current) return; const buffer = term.buffer.active; const wasAtBottom = buffer.viewportY >= buffer.baseY; const prevViewportY = buffer.viewportY; const timer = setTimeout(() => { safeFit({ force: true, requireVisible: true }); requestAnimationFrame(() => { if (wasAtBottom) { term.scrollToBottom(); } else { term.scrollToLine(prevViewportY); } }); }, 0); return () => clearTimeout(timer); }, [isSearchOpen]); useEffect(() => { const shouldAutoFocus = isVisible && termRef.current && (!inWorkspace || isFocusMode); if (shouldAutoFocus) { const timer = setTimeout(() => { termRef.current?.focus(); }, 50); return () => clearTimeout(timer); } }, [isVisible, inWorkspace, isFocusMode]); useEffect(() => { if (isFocused && termRef.current && isVisible) { const timer = setTimeout(() => { termRef.current?.focus(); }, 10); return () => clearTimeout(timer); } }, [isFocused, isVisible, sessionId]); useEffect(() => { const term = termRef.current; if (!term) return; const onSelectionChange = () => { const selection = term.getSelection(); const hasText = !!selection && selection.length > 0; setHasSelection(hasText); if (hasText && terminalSettings?.copyOnSelect && !isRestoringSelectionRef.current) { navigator.clipboard.writeText(selection).catch((err) => { logger.warn("Copy on select failed:", err); }); } }; const disposable = term.onSelectionChange(onSelectionChange); return () => disposable.dispose(); }, [terminalSettings?.copyOnSelect]); // Track whether the terminal application has enabled mouse tracking // (e.g. tmux with `set -g mouse on`, vim with `set mouse=a`). // When mouse tracking is active, disable Netcatty's context menu to avoid // conflicting with the application's own mouse handling. useEffect(() => { const term = termRef.current; if (!term) return; const disposable = term.onWriteParsed(() => { const tracking = term.modes.mouseTrackingMode !== 'none'; if (tracking !== mouseTrackingRef.current) { mouseTrackingRef.current = tracking; setHasMouseTracking(tracking); } }); // Set initial state const initial = term.modes.mouseTrackingMode !== 'none'; mouseTrackingRef.current = initial; setHasMouseTracking(initial); return () => disposable.dispose(); }, [sessionId]); // Prevent xterm.js's built-in rightClickHandler and right-button mouseup // from interfering with tmux/vim popup menus when mouse tracking is active. // - contextmenu: xterm.js calls textarea.select() which steals focus // - mouseup (button 2): tmux interprets the right-button release as a // dismiss action, closing the popup menu immediately after it appears // Both are intercepted at the capture phase before xterm.js's own listeners. useEffect(() => { const el = containerRef.current; if (!el) return; const handleContextMenuCapture = (e: MouseEvent) => { if (!mouseTrackingRef.current) return; e.preventDefault(); e.stopImmediatePropagation(); // stopImmediatePropagation blocks the event from reaching React's // bubble-phase root listener, so the onContextMenu handler in // TerminalContextMenu (which dispatches paste / select-word) never // fires inside a mouse-tracking TUI. Without dispatching the user's // chosen action here, right-click paste silently stops working in // opencode, tmux with `mouse on`, vim with `set mouse=a`, etc. (#941). // Middle-click still works because its auxclick listener lives in // createXTermRuntime and isn't gated by mouseTracking. const behavior = terminalSettingsRef.current?.rightClickBehavior; if (behavior === 'paste') { void terminalContextActionsRef.current?.onPaste?.(); } else if (behavior === 'select-word') { terminalContextActionsRef.current?.onSelectWord?.(); } // 'context-menu' is intentionally not handled — Radix opens the // menu via its own pointerdown listener, which our capture handler // does not intercept. }; const handleMouseUpCapture = (e: MouseEvent) => { if (e.button === 2 && mouseTrackingRef.current) { e.stopImmediatePropagation(); } }; el.addEventListener('contextmenu', handleContextMenuCapture, true); el.addEventListener('mouseup', handleMouseUpCapture, true); return () => { el.removeEventListener('contextmenu', handleContextMenuCapture, true); el.removeEventListener('mouseup', handleMouseUpCapture, true); }; }, [sessionId]); useEffect(() => { if (!isVisible) return; let resizeTimeout: ReturnType | null = null; const handler = () => { if (!isVisibleRef.current) return; if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(() => { safeFit({ requireVisible: true }); }, 250); }; window.addEventListener("resize", handler); return () => { if (resizeTimeout) clearTimeout(resizeTimeout); window.removeEventListener("resize", handler); }; }, [isVisible]); const disableBracketedPasteRef = useRef(terminalSettings?.disableBracketedPaste ?? false); disableBracketedPasteRef.current = terminalSettings?.disableBracketedPaste ?? false; // True only while createXTermRuntime is programmatically restoring the // selection right after a keystroke (preserveSelectionOnInput). Lets // copy-on-select skip a redundant clipboard write that would otherwise // clobber whatever the user copied elsewhere in the meantime. const isRestoringSelectionRef = useRef(false); const scrollOnPasteRef = useRef(terminalSettings?.scrollOnPaste ?? true); scrollOnPasteRef.current = terminalSettings?.scrollOnPaste ?? true; const scrollToBottomAfterProgrammaticInput = useCallback((data: string) => { if (termRef.current && shouldScrollOnTerminalInput(terminalSettingsRef.current, data)) { termRef.current.scrollToBottom(); } }, []); const executeSnippetCommand = useCallback((command: string, noAutoRun?: boolean) => { const term = termRef.current; const id = sessionRef.current; if (!term || !id) return; let data = normalizeLineEndings(command); const isMultiLine = data.includes('\n'); // Wrap in bracketed paste BEFORE appending \r so the Enter is sent // outside the paste markers — otherwise shells treat it as pasted text // instead of a submit action. if (isMultiLine && term.modes.bracketedPasteMode && !disableBracketedPasteRef.current) { data = wrapBracketedPaste(data); } if (!noAutoRun) data = `${data}\r`; terminalBackend.writeToSession(id, data); scrollToBottomAfterProgrammaticInput(data); term.focus(); }, [scrollToBottomAfterProgrammaticInput, terminalBackend]); // Only register the snippet executor once the terminal session is ready. // Before that, TerminalLayer falls back to raw writeToSession which is the // correct path for sessions that are still connecting. useEffect(() => { if (status !== "connected") { onSnippetExecutorChange?.(sessionId, null); return; } onSnippetExecutorChange?.(sessionId, executeSnippetCommand); return () => onSnippetExecutorChange?.(sessionId, null); }, [executeSnippetCommand, onSnippetExecutorChange, sessionId, status]); const terminalContextActions = useTerminalContextActions({ termRef, sessionRef, onHasSelectionChange: setHasSelection, scrollOnPasteRef, }); // Kept fresh on every render so the mouseTracking capture handler at // handleContextMenuCapture (which is bound once per sessionId) can // still invoke the latest paste / select-word callbacks without // re-binding on every action identity change. See #941. const terminalContextActionsRef = useRef(terminalContextActions); terminalContextActionsRef.current = terminalContextActions; const handleSetTerminalEncoding = (encoding: 'utf-8' | 'gb18030') => { setTerminalEncoding(encoding); userPickedEncodingRef.current = true; if (sessionRef.current) { setSessionEncoding(sessionRef.current, encoding); } }; const handleOpenSFTP = async () => { if (onOpenSftp) { // Delegate to parent (TerminalLayer) for shared SFTP side panel let initialPath: string | undefined = undefined; if (sessionRef.current) { try { const result = await terminalBackend.getSessionPwd(sessionRef.current); if (result.success && result.cwd) { initialPath = result.cwd; } } catch { // Silently fail } } onOpenSftp(host, initialPath, undefined, sessionId); return; } // Fallback: toggle internal SFTP state (shouldn't happen with new architecture) if (showSFTP) { setShowSFTP(false); return; } setShowSFTP(true); }; const handleCancelConnect = () => { if (pendingHostKeyRequestId) { void terminalBackend.respondHostKeyVerification(pendingHostKeyRequestId, false); } retryTokenRef.current = null; setIsCancelling(true); auth.setNeedsAuth(false); auth.setAuthRetryMessage(null); setNeedsHostKeyVerification(false); setPendingHostKeyInfo(null); setPendingHostKeyRequestId(null); setError("Connection cancelled"); setProgressLogs((prev) => [...prev, "Cancelled by user."]); cleanupSession(); updateStatus("disconnected"); setChainProgress(null); setTimeout(() => setIsCancelling(false), 600); onCloseSession?.(sessionId); }; const handleDismissDisconnectedDialog = () => { setIsDisconnectedDialogDismissed(true); }; const handleCloseDisconnectedSession = () => { retryTokenRef.current = null; onCloseSession?.(sessionId); }; const handleHostKeyClose = () => { setNeedsHostKeyVerification(false); setPendingHostKeyInfo(null); setPendingHostKeyRequestId(null); handleCancelConnect(); }; const handleHostKeyContinue = () => { if (pendingHostKeyRequestId) { void terminalBackend.respondHostKeyVerification(pendingHostKeyRequestId, true, false); } setNeedsHostKeyVerification(false); if (pendingConnectionRef.current) { pendingConnectionRef.current(); pendingConnectionRef.current = null; } setPendingHostKeyInfo(null); setPendingHostKeyRequestId(null); }; const handleHostKeyAddAndContinue = () => { if (pendingHostKeyInfo && onAddKnownHost) { onAddKnownHost(createKnownHostFromHostKeyInfo(pendingHostKeyInfo, host)); } if (pendingHostKeyRequestId) { void terminalBackend.respondHostKeyVerification(pendingHostKeyRequestId, true, true); } setNeedsHostKeyVerification(false); if (pendingConnectionRef.current) { pendingConnectionRef.current(); pendingConnectionRef.current = null; } setPendingHostKeyInfo(null); setPendingHostKeyRequestId(null); }; const handleRetry = () => { if (!termRef.current) return; cleanupSession(); const term = termRef.current; // Claim a fresh retry token. If the user cancels / closes / unmounts / // kicks off another retry while the chained writes below are still // queued, the token will be invalidated and our callbacks will abort // before opening a ghost backend session with no owning UI. const retryToken = Symbol("retry"); retryTokenRef.current = retryToken; const retryStillActive = () => retryTokenRef.current === retryToken && termRef.current === term; auth.resetForRetry(); terminalDataCapturedRef.current = false; hasRunStartupCommandRef.current = false; setIsDisconnectedDialogDismissed(false); setStatus("connecting"); setError(null); setProgressLogs(["Retrying secure channel..."]); setShowLogs(true); const startNewSession = () => { if (!retryStillActive()) return; if (host.protocol === "serial") { sessionStarters.startSerial(term); } else if (host.protocol === "local" || host.hostname === "localhost") { sessionStarters.startLocal(term); } else if (host.protocol === "telnet") { sessionStarters.startTelnet(term); } else if (host.moshEnabled) { sessionStarters.startMosh(term); } else { sessionStarters.startSSH(term); } }; // Chain the whole preparation through xterm.write callbacks so everything // lands in strict order — see #695. xterm.write is async, so without // chaining, a fast reconnect path (local/serial especially) can interleave // the new session's first bytes with our reset sequence, corrupting the // first screen. // // 1. Exit the alternate screen first. preserveTerminalViewportInScrollback // is a no-op on the alt buffer (disconnect while in vim/less/top), so // we must be on the normal buffer before preserving. term.write('\x1b[?1049l', () => { if (!retryStillActive()) return; // 2. Push the previous session's viewport into scrollback so the user // can still read it after reconnect. preserveTerminalViewportInScrollback(term); // 3. Soft terminal reset (DECSTR, \x1b[!p) resets VT220-era modes that // full-screen apps may have left on — DECCKM (otherwise arrow keys // emit SS3 and break readline history), keypad mode, SGR, // insert/replace, origin, cursor visibility — without clearing the // buffer. DECSTR does not cover xterm-specific extensions, so also // explicitly disable mouse tracking (1000/1002/1003/1006) and // bracketed paste (2004). Finally home the cursor. term.write( '\x1b[!p\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[H', // 4. Only now — after every prep byte has been applied to the // terminal — start the new session, so its first output can't // interleave with the reset sequence. startNewSession, ); }); }; const shouldShowConnectionDialog = status !== "connected" && !((isLocalConnection || isSerialConnection) && status === "connecting") && !(status === "disconnected" && isDisconnectedDialogDismissed); // Drag and drop handlers const handleDragEnter = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); dragCounterRef.current++; if (e.dataTransfer.types.includes('Files')) { setIsDraggingOver(true); } }; const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); if (e.dataTransfer.types.includes('Files')) { e.dataTransfer.dropEffect = 'copy'; } }; const handleDragLeave = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); dragCounterRef.current--; if (dragCounterRef.current === 0) { setIsDraggingOver(false); } }; const handleDrop = async (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); dragCounterRef.current = 0; setIsDraggingOver(false); if (!e.dataTransfer.types.includes('Files')) { return; } // Only handle drops on connected terminals if (status !== 'connected') { toast.error(t("terminal.dragDrop.notConnected"), t("terminal.dragDrop.errorTitle")); return; } try { const dropEntries = await extractDropEntries(e.dataTransfer); if (dropEntries.length === 0) { return; } if (isLocalConnection) { // Local terminal: Insert absolute paths const paths = extractRootPathsFromDropEntries(dropEntries); if (paths.length > 0 && termRef.current && sessionRef.current) { const pathsText = paths.join(' '); // Write the paths to the terminal terminalBackend.writeToSession(sessionRef.current, pathsText); scrollToBottomAfterProgrammaticInput(pathsText); termRef.current.focus(); } } else { // Remote terminal: Trigger SFTP upload via parent if (onOpenSftp) { let initialPath: string | undefined = undefined; if (sessionRef.current) { try { const result = await terminalBackend.getSessionPwd(sessionRef.current); if (result.success && result.cwd) { initialPath = result.cwd; } } catch { // Silently fail } } onOpenSftp(host, initialPath, dropEntries, sessionId); } } } catch (error) { logger.error("Failed to handle file drop", error); toast.error(t("terminal.dragDrop.errorMessage"), t("terminal.dragDrop.errorTitle")); } }; const renderControls = (opts?: { showClose?: boolean }) => ( {})} onOpenTheme={onOpenTheme ?? (() => {})} onUpdateHost={onUpdateHost} showClose={opts?.showClose} onClose={() => onCloseSession?.(sessionId)} isSearchOpen={isSearchOpen} onToggleSearch={handleToggleSearch} isComposeBarOpen={inWorkspace ? isWorkspaceComposeBarOpen : isComposeBarOpen} onToggleComposeBar={inWorkspace ? onToggleComposeBar : () => setIsComposeBarOpen(prev => !prev)} terminalEncoding={terminalEncoding} onSetTerminalEncoding={handleSetTerminalEncoding} /> ); const statusDotTone = status === "connected" ? "bg-emerald-400" : status === "connecting" ? "bg-amber-400" : "bg-rose-500"; const terminalPreviewVars = useMemo(() => ({ ['--terminal-ui-bg' as never]: `var(--terminal-preview-bg, ${effectiveTheme.colors.background})`, ['--terminal-ui-fg' as never]: `var(--terminal-preview-fg, ${effectiveTheme.colors.foreground})`, ['--terminal-ui-border' as never]: `var(--terminal-preview-border, color-mix(in srgb, ${effectiveTheme.colors.foreground} 8%, ${effectiveTheme.colors.background} 92%))`, ['--terminal-ui-toolbar-btn' as never]: `var(--terminal-preview-toolbar-btn, color-mix(in srgb, ${effectiveTheme.colors.background} 88%, ${effectiveTheme.colors.foreground} 12%))`, ['--terminal-ui-toolbar-btn-hover' as never]: `var(--terminal-preview-toolbar-btn-hover, color-mix(in srgb, ${effectiveTheme.colors.background} 78%, ${effectiveTheme.colors.foreground} 22%))`, ['--terminal-ui-toolbar-btn-active' as never]: `var(--terminal-preview-toolbar-btn-active, color-mix(in srgb, ${effectiveTheme.colors.cursor} 78%, ${effectiveTheme.colors.background} 22%))`, }), [effectiveTheme.colors.background, effectiveTheme.colors.cursor, effectiveTheme.colors.foreground]); return ( onCloseSession?.(sessionId) : undefined} >
{/* Drag and drop overlay */} {isDraggingOver && (
{isLocalConnection ? t("terminal.dragDrop.localTitle") : t("terminal.dragDrop.remoteTitle") }
{isLocalConnection ? t("terminal.dragDrop.localMessage") : t("terminal.dragDrop.remoteMessage") }
)}
{host.label} {host.protocol !== "local" && host.hostname && host.hostname !== "localhost" && ( {t("terminal.statusbar.copyHostname.tooltip", { hostname: host.hostname })} )}
{/* Server Stats Display */} {terminalSettings?.showServerStats && status === 'connected' && serverStats.lastUpdated && (
{/* CPU with HoverCard for per-core details */}
{t("terminal.serverStats.cpuCores")}
{serverStats.cpuPerCore.length > 0 ? (
{serverStats.cpuPerCore.map((usage, index) => (
Core {index}
= 90 ? "bg-red-500" : usage >= 70 ? "bg-amber-500" : "bg-emerald-500" )} style={{ width: `${usage}%` }} />
= 90 ? "text-red-400" : usage >= 70 ? "text-amber-400" : "text-emerald-400" )}> {usage}%
))}
) : serverStats.cpu !== null ? (
= 90 ? "bg-red-500" : serverStats.cpu >= 70 ? "bg-amber-500" : "bg-emerald-500" )} style={{ width: `${serverStats.cpu}%` }} />
= 90 ? "text-red-400" : serverStats.cpu >= 70 ? "text-amber-400" : "text-emerald-400" )}> {serverStats.cpu}% · {serverStats.cpuCores ?? '?'} cores
) : (
{t("terminal.serverStats.noData")}
)}
{/* Memory with HoverCard for htop-style bar and top processes */}
{t("terminal.serverStats.memoryDetails")}
{/* htop-style memory bar */} {serverStats.memTotal !== null && (
{/* Used (green) — exact value shown in legend below */} {serverStats.memUsed !== null && serverStats.memUsed > 0 && (
)} {/* Buffers (blue) */} {serverStats.memBuffers !== null && serverStats.memBuffers > 0 && (
)} {/* Cached (amber/orange) */} {serverStats.memCached !== null && serverStats.memCached > 0 && (
)}
{/* Legend */}
{t("terminal.serverStats.memUsed")}: {serverStats.memUsed !== null ? `${(serverStats.memUsed / 1024).toFixed(1)}G` : '--'}
{t("terminal.serverStats.memBuffers")}: {serverStats.memBuffers !== null ? `${(serverStats.memBuffers / 1024).toFixed(1)}G` : '--'}
{t("terminal.serverStats.memCached")}: {serverStats.memCached !== null ? `${(serverStats.memCached / 1024).toFixed(1)}G` : '--'}
{t("terminal.serverStats.memFree")}: {serverStats.memFree !== null ? `${(serverStats.memFree / 1024).toFixed(1)}G` : '--'}
)} {/* Swap bar */} {serverStats.swapTotal !== null && serverStats.swapTotal > 0 && (
{t("terminal.serverStats.swap")}
{serverStats.swapUsed !== null && serverStats.swapUsed > 0 && (
)}
{t("terminal.serverStats.swapUsed")}: {serverStats.swapUsed !== null ? `${(serverStats.swapUsed / 1024).toFixed(1)}G` : '--'}
{t("terminal.serverStats.swapFree")}: {serverStats.swapTotal !== null && serverStats.swapUsed !== null ? `${((serverStats.swapTotal - serverStats.swapUsed) / 1024).toFixed(1)}G` : '--'}
{t("terminal.serverStats.swapTotal")}: {`${(serverStats.swapTotal / 1024).toFixed(1)}G`}
)} {/* Top 10 processes */} {serverStats.topProcesses.length > 0 && (
{t("terminal.serverStats.topProcesses")}
{serverStats.topProcesses.map((proc, index) => (
{proc.memPercent.toFixed(1)}%
{proc.command.split('/').pop()?.split(' ')[0] || proc.command} {proc.command}
))}
)}
{/* Disk - with HoverCard for disk details */}
{t("terminal.serverStats.diskDetails")}
{serverStats.disks.length > 0 ? (
{serverStats.disks.map((disk, index) => (
{disk.mountPoint} {disk.mountPoint} = 90 ? "text-red-400" : disk.percent >= 80 ? "text-amber-400" : "text-emerald-400" )}> {disk.used}/{disk.total}G ({disk.percent}%)
= 90 ? "bg-red-500" : disk.percent >= 80 ? "bg-amber-500" : "bg-emerald-500" )} style={{ width: `${disk.percent}%` }} />
))}
) : (
{t("terminal.serverStats.noData")}
)}
{/* Network - with HoverCard for per-interface details */} {serverStats.netInterfaces.length > 0 && (
{t("terminal.serverStats.networkDetails")}
{serverStats.netInterfaces.map((iface, index) => (
{iface.name}
{formatNetSpeed(iface.rxSpeed)} {formatNetSpeed(iface.txSpeed)}
))}
)}
)}
{inWorkspace && onToggleBroadcast && ( {isBroadcastEnabled ? t("terminal.toolbar.broadcastDisable") : t("terminal.toolbar.broadcastEnable")} )} {inWorkspace && !isFocusMode && onExpandToFocus && ( {t("terminal.toolbar.focusMode")} )} {renderControls({ showClose: inWorkspace })}
{isSearchOpen && (
)}
{/* Autocomplete popup — rendered via Portal to escape overflow:hidden */} {isVisible && autocomplete.state.popupVisible && autocomplete.state.suggestions.length > 0 && ReactDOM.createPortal( , document.body, ) } {/* OSC-52 clipboard read prompt */} {osc52ReadPromptVisible && (
{ if (e.key === 'Escape') handleOsc52ReadResponse(false); }} >

{t("terminal.osc52.readPrompt.title")}

{t("terminal.osc52.readPrompt.desc")}

)} {/* Connection dialog: skip for local/serial during connecting phase, but show on error */} {shouldShowConnectionDialog && ( auth.submit(), onSubmitWithoutSave: () => auth.submit({ saveToHost: false }), onCancel: handleCancelConnect, isValid: auth.isValid, }} progressProps={{ timeLeft, isCancelling, progressLogs, onCancelConnect: handleCancelConnect, onCloseSession: handleCloseDisconnectedSession, onRetry: handleRetry, }} /> )} {/* ZMODEM transfer progress indicator */} {zmodem.active && (
)}
{/* Compose Bar (solo sessions only; workspace uses TerminalLayer's global bar) */} {isComposeBarOpen && !inWorkspace && ( { if (sessionRef.current) { const payload = text + '\r'; terminalBackend.writeToSession(sessionRef.current, payload); scrollToBottomAfterProgrammaticInput(payload); onBroadcastInput?.(payload, sessionRef.current); } }} onClose={() => { setIsComposeBarOpen(false); termRef.current?.focus(); }} isBroadcastEnabled={isBroadcastEnabled} themeColors={effectiveTheme.colors} /> )}
); }; const Terminal = memo(TerminalComponent); Terminal.displayName = "Terminal"; export default Terminal;