/* eslint-disable @typescript-eslint/no-explicit-any */ import React, { memo, useCallback, useEffect, useRef, useState } from 'react'; import { ChevronsLeft, GripVertical, X as XIcon } from 'lucide-react'; import { shouldKeepTerminalBackgroundWorkActive } from '../../domain/terminalHibernate'; import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol'; import { classifyDistroId } from '../../domain/host'; import { OSC7_SETUP_TARGETS } from './osc7Setup'; import PasswordCredentialPicker from './PasswordCredentialPicker'; import { TerminalServerStats } from './TerminalServerStats'; import { TerminalTimestampGutter, resolveTerminalTimestampGutterColor, resolveTerminalTimestampGutterWidth, } from './TerminalTimestampGutter'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '../ui/dialog'; type TerminalViewContext = Record; type HostLineTimestampToggle = { id: string; showLineTimestamps?: boolean; }; export function getLineTimestampToggleHostUpdate( host: T, ): Pick & { showLineTimestamps: boolean } { return { id: host.id, showLineTimestamps: host.showLineTimestamps !== true, }; } export function shouldShowLineTimestampToolbarToggle( lineTimestampsAvailable: boolean | undefined, onUpdateHost: unknown, ): boolean { return lineTimestampsAvailable !== false && Boolean(onUpdateHost); } export function shouldEnableYmodemAction({ isSerialConnection, status, handleSendYmodem, handleReceiveYmodem, }: { isSerialConnection?: boolean; status?: string; handleSendYmodem?: () => void; handleReceiveYmodem?: () => void; }): boolean { return Boolean(isSerialConnection && status === "connected" && (handleSendYmodem || handleReceiveYmodem)); } export function shouldShowSelectionAIOverlay({ hasSelection, selectionOverlayPosition, onAddSelectionToAI, showSelectionAIAction, }: { hasSelection: boolean; selectionOverlayPosition?: { left: number; top: number } | null; onAddSelectionToAI?: unknown; showSelectionAIAction?: boolean; }): boolean { return Boolean( showSelectionAIAction !== false && hasSelection && selectionOverlayPosition && onAddSelectionToAI, ); } export function shouldReconnectTerminalOnEnterKey({ key, status, hasRetryHandler, isSearchOpen, isComposeBarOpen, needsAuth, needsHostKeyVerification, hasBlockingOverlay, altKey, ctrlKey, metaKey, shiftKey, isComposing, }: { key: string; status?: string; hasRetryHandler: boolean; isSearchOpen: boolean; isComposeBarOpen: boolean; needsAuth: boolean; needsHostKeyVerification: boolean; hasBlockingOverlay: boolean; altKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean; isComposing?: boolean; }): boolean { return key === "Enter" && status === "disconnected" && hasRetryHandler && !isSearchOpen && !isComposeBarOpen && !needsAuth && !needsHostKeyVerification && !hasBlockingOverlay && !altKey && !ctrlKey && !metaKey && !shiftKey && !isComposing; } export function shouldBlockTerminalReconnectForTarget({ isWithinXterm, hasInteractiveAncestor, }: { isWithinXterm: boolean; hasInteractiveAncestor: boolean; }): boolean { return !isWithinXterm && hasInteractiveAncestor; } function isTerminalReconnectControlTarget(target: EventTarget | null): boolean { if (typeof HTMLElement === "undefined" || !(target instanceof HTMLElement)) return false; return shouldBlockTerminalReconnectForTarget({ isWithinXterm: target.classList.contains("xterm-helper-textarea") || Boolean(target.closest(".xterm")), hasInteractiveAncestor: Boolean(target.closest("button, a, input, textarea, select, [contenteditable='true'], [role='button'], [role='menuitem'], [role='textbox']")), }); } type TerminalTitleAddressHost = { id?: string; protocol?: string; username?: string; hostname?: string; port?: number; }; export function formatTerminalTitleConnectionAddress(host?: TerminalTitleAddressHost): string | null { if (!host || host.protocol === 'local' || host.id?.startsWith('local-') || !host.hostname || host.hostname === 'localhost') { return null; } const isSerial = host.protocol === 'serial' || host.id?.startsWith('serial-'); const username = !isSerial && host.username ? `${host.username}@` : ''; const port = !isSerial && host.port ? `:${host.port}` : ''; return `${username}${host.hostname}${port}`; } export function resolveTerminalTopOffsets({ showHostInfoBar, isSearchOpen, terminalBodyInset = 4, }: { showHostInfoBar: boolean; isSearchOpen: boolean; terminalBodyInset?: number; }): { toolbarOffset: number; contentTop: string } { const toolbarOffset = isSearchOpen ? 64 : showHostInfoBar ? 30 : 0; return { toolbarOffset, contentTop: `${toolbarOffset + terminalBodyInset}px`, }; } export function resolveTerminalRightInset({ showHostInfoBar: _showHostInfoBar, isSearchOpen: _isSearchOpen, terminalBodyInset = 4, }: { showHostInfoBar: boolean; isSearchOpen: boolean; terminalBodyInset?: number; }): number { // Compact speed-dial floats over the terminal (z-30 overlay). Do not reserve // a right gutter for it — that pushes the xterm scrollbar left and leaves a // dead strip next to the circular toggle. void _showHostInfoBar; void _isSearchOpen; return terminalBodyInset; } /** * Shallow-compare every ctx value. rebuilds the ctx object on every * render, but many re-renders (layout/fit/visibility-of-other-panes, suppress * toggles) don't actually change any value passed to the view — notably * `paneLayoutKey`/`isResizing` are consumed by Terminal's hooks and are NOT in * this ctx. Without this memo, every Terminal re-render re-rendered the whole * (expensive) TerminalView. This only skips when EVERY value is referentially * equal, so it can never render stale UI. */ function terminalViewCtxEqual( prev: { ctx: TerminalViewContext }, next: { ctx: TerminalViewContext }, ): boolean { const a = prev.ctx; const b = next.ctx; if (a === b) return true; const aKeys = Object.keys(a); if (aKeys.length !== Object.keys(b).length) return false; for (const key of aKeys) { if (a[key] !== b[key]) return false; } return true; } function TerminalViewInner({ ctx }: { ctx: TerminalViewContext }) { const { Activity, Button, Clock3, Copy, Maximize2, Radio, Sparkles, SquareArrowOutUpRight, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTerminalProtocol, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOsc52ReadResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, hasSelection, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, isCancelling, isComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, knownCwdRef, needsHostKeyVerification, onCloseSession, onDetach, onDetachPointerDown, onExpandToFocus, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onToggleBroadcast, onUpdateHost, osc52ReadPromptVisible, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scriptExecutionOverlay, searchMatchCount, searchFocusToken, selectionOverlayPosition, sessionDisplayName, sessionId, workspaceId, sessionRef, setIsComposeBarOpen, setShowLogs, shouldShowConnectionDialog, showLogs, showSelectionAIAction, snippets, status, sudoHintRef, sudoHintText, passwordPickerState, onPasswordPickerSelect, passwordPickerTitle, passwordPickerEmptyText, t, termRef, terminalContextActions, terminalCwdTracker, terminalPreviewVars, terminalSettings, timeLeft, toast, zmodem } = ctx; const isNetworkDevice = host.deviceType === 'network' || classifyDistroId(host.distro) === 'network-device'; const ymodemActionEnabled = shouldEnableYmodemAction({ isSerialConnection, status, handleSendYmodem, handleReceiveYmodem, }); const terminalBodyInset = 4; const showHostInfoBar = terminalSettings?.showHostInfoBar !== false; const [compactActionsOpen, setCompactActionsOpen] = useState(false); const compactActionsRef = useRef(null); const compactActionsButtonRef = useRef(null); useEffect(() => { if (!compactActionsOpen) return; const handlePointerDown = (event: PointerEvent) => { if (compactActionsRef.current?.contains(event.target as Node)) return; if ( event.target instanceof Element && event.target.closest('[data-radix-popper-content-wrapper]') ) return; setCompactActionsOpen(false); }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape") return; setCompactActionsOpen(false); compactActionsButtonRef.current?.focus(); }; document.addEventListener("pointerdown", handlePointerDown); document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("pointerdown", handlePointerDown); document.removeEventListener("keydown", handleKeyDown); }; }, [compactActionsOpen]); const { toolbarOffset: terminalToolbarOffset, contentTop: terminalContentTop } = resolveTerminalTopOffsets({ showHostInfoBar, isSearchOpen, terminalBodyInset, }); const terminalRightInset = resolveTerminalRightInset({ showHostInfoBar, isSearchOpen, terminalBodyInset, }); const showLineTimestampGutter = lineTimestampsAvailable !== false && host.showLineTimestamps === true; const lineTimestampColor = resolveTerminalTimestampGutterColor(effectiveTheme.colors); const [lineTimestampGutterWidth, setLineTimestampGutterWidth] = useState(() => ( resolveTerminalTimestampGutterWidth({ fontSize: effectiveFontSize }) )); useEffect(() => { if (showLineTimestampGutter) return; setLineTimestampGutterWidth(resolveTerminalTimestampGutterWidth({ fontSize: effectiveFontSize })); }, [effectiveFontSize, effectiveFontWeight, resolvedFontFamily, sessionId, showLineTimestampGutter]); const handleLineTimestampGutterWidthChange = useCallback((width: number) => { setLineTimestampGutterWidth((current) => (current === width ? current : width)); }, []); const activeLineTimestampGutterWidth = showLineTimestampGutter ? lineTimestampGutterWidth : 0; const lineTimestampToggleLabel = showLineTimestampGutter ? t("terminal.toolbar.timestampsDisable") : t("terminal.toolbar.timestampsEnable"); const titleConnectionAddress = formatTerminalTitleConnectionAddress(host); const hasBlockingReconnectOverlay = Boolean(osc52ReadPromptVisible || osc7SetupOpen || scriptExecutionOverlay || zmodem.active || zmodem.overwriteRequest); const showEnterReconnectHint = shouldReconnectTerminalOnEnterKey({ key: "Enter", status, hasRetryHandler: Boolean(handleRetry), isSearchOpen, isComposeBarOpen, needsAuth: Boolean(auth.needsAuth), needsHostKeyVerification: Boolean(needsHostKeyVerification), hasBlockingOverlay: hasBlockingReconnectOverlay, }); const handleTerminalKeyDownCapture = useCallback((event: React.KeyboardEvent) => { if (!shouldReconnectTerminalOnEnterKey({ key: event.key, status, hasRetryHandler: Boolean(handleRetry), isSearchOpen, isComposeBarOpen, needsAuth: Boolean(auth.needsAuth), needsHostKeyVerification: Boolean(needsHostKeyVerification), hasBlockingOverlay: hasBlockingReconnectOverlay, altKey: event.altKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, shiftKey: event.shiftKey, isComposing: event.nativeEvent.isComposing, })) { return; } if (isTerminalReconnectControlTarget(event.target)) return; event.preventDefault(); event.stopPropagation(); handleRetry(); }, [ auth.needsAuth, handleRetry, hasBlockingReconnectOverlay, isComposeBarOpen, isSearchOpen, needsHostKeyVerification, status, ]); return ( onCloseSession?.(sessionId) : undefined} onAddSelectionToAI={ctx.onAddSelectionToAI ? handleAddSelectionToAI : undefined} onRename={onRename} onDetach={inWorkspace ? onDetach : undefined} >
{/* Drag and drop overlay */} {isDraggingOver && (
{isLocalConnection ? t("terminal.dragDrop.localTitle") : t("terminal.dragDrop.remoteTitle") }
{isLocalConnection ? t("terminal.dragDrop.localMessage") : remoteDragDropUsesZmodem ? t("terminal.dragDrop.remoteZmodemMessage") : t("terminal.dragDrop.remoteSftpMessage") }
)}
{(() => { const isCompactActionsMode = !showHostInfoBar && !isSearchOpen; const toolbarSurfaceStyle = { backgroundColor: 'var(--terminal-ui-bg)', color: 'var(--terminal-ui-fg)', borderColor: 'var(--terminal-ui-border)', ['--terminal-toolbar-fg' as never]: 'var(--terminal-ui-fg)', ['--terminal-toolbar-bg' as never]: 'var(--terminal-ui-bg)', ['--terminal-toolbar-btn' as never]: 'var(--terminal-ui-toolbar-btn)', ['--terminal-toolbar-btn-hover' as never]: 'var(--terminal-ui-toolbar-btn-hover)', ['--terminal-toolbar-btn-active' as never]: 'var(--terminal-ui-toolbar-btn-active)', } as React.CSSProperties; const terminalActionsBody = ( <>
{!showHostInfoBar && inWorkspace && onDetachPointerDown && (
)} {showHostInfoBar &&
{titleConnectionAddress || sessionDisplayName || host.label}
} {host.protocol !== "local" && host.hostname && host.hostname !== "localhost" && ( {t("terminal.statusbar.copyHostname.tooltip", { hostname: host.hostname })} )} {shouldShowLineTimestampToolbarToggle(lineTimestampsAvailable, onUpdateHost) && ( {lineTimestampToggleLabel} )} {isSystemSidebarEligible && ( {t("terminal.layer.system")} )}
{showHostInfoBar && !compactToolbar && ( )} {showHostInfoBar &&
}
{inWorkspace && onToggleBroadcast && ( {isBroadcastEnabled ? t("terminal.toolbar.broadcastDisable") : t("terminal.toolbar.broadcastEnable")} )} {inWorkspace && onDetach && ( {t('terminal.toolbar.detach')} )} {inWorkspace && !isFocusMode && onExpandToFocus && ( {t("terminal.toolbar.focusMode")} )} {renderControls({ showClose: inWorkspace })}
); if (isCompactActionsMode) { // Speed-dial: circular toggle; full action strip springs out to the left. // Do NOT use `.terminal-topbar` here — it sets container-type:inline-size, // which size-contains the inline axis and collapses width to 0 when we // animate max-width / rely on content sizing (buttons never appear). // Shared h-7 keeps the toggle and the action pill the same height as the // inner h-6 icon buttons + vertical padding. // No box-shadow: the 0fr→1fr expand clip always slices shadows and // looks worse than a clean border-only chrome. const compactChromeClass = "h-7 rounded-full border backdrop-blur-md"; return (
{t("terminal.toolbar.showActions")}
{terminalActionsBody}
); } return (
{terminalActionsBody}
); })()} {isSearchOpen && (
)}
{shouldShowSelectionAIOverlay({ hasSelection, selectionOverlayPosition, onAddSelectionToAI: ctx.onAddSelectionToAI, showSelectionAIAction, }) && handleAddSelectionToAI && (
{t("terminal.selection.addToAIDesc")}
)} {/* Autocomplete — owns the hook + popup in its own component so suggestion/selection updates don't re-render Terminal. Mounted unconditionally; it gates the popup on `visible` internally. */} terminalCwdTracker.getRendererCwd() ?? knownCwdRef.current} onAcceptText={(text) => autocompleteAcceptTextRef.current?.(text)} snippets={snippets} onAcceptSnippet={(snippet) => void executeSnippet(snippet)} themeColors={effectiveTheme.colors} containerRef={containerRef} searchBarOffset={terminalToolbarOffset + terminalBodyInset} keyEventRef={autocompleteKeyEventRef} inputRef={autocompleteInputRef} repositionRef={autocompleteRepositionRef} closeRef={autocompleteCloseRef} sudoHintRef={sudoHintRef} sudoHintText={sudoHintText} isPluginCompletionProviderAvailable={() => ( isPluginTerminalProviderAvailable('terminal.completion') )} sensitiveInputActiveRef={passwordPromptActiveRef} allowHostStyleGreaterThanPrompt={isNetworkDevice} /> onPasswordPickerSelect?.(id)} title={passwordPickerTitle ?? "Saved passwords"} emptyText={passwordPickerEmptyText ?? "No saved passwords"} themeColors={effectiveTheme.colors} termRef={termRef} containerRef={containerRef} /> {scriptExecutionOverlay} {/* OSC-52 clipboard read prompt */} {osc52ReadPromptVisible && (
{ if (e.key === 'Escape') handleOsc52ReadResponse(false); }} >

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

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

)} {t("terminal.osc7Setup.title")} {t("terminal.osc7Setup.desc")}

{t("terminal.osc7Setup.targets")}

{OSC7_SETUP_TARGETS.map((target) => ( {target} ))}
{/* 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, isAwaitingUserInput: Boolean(isConnectionAwaitingUserInput), isCancelling, progressLogs, onCancelConnect: handleCancelConnect, onCloseSession: handleCloseDisconnectedSession, onRetry: handleRetry, }} /> )} {/* ZMODEM transfer progress indicator */} {zmodem.active && (
)} {/* ZMODEM overwrite conflict dialog */} {zmodem.overwriteRequest && ( )}
{/* Compose Bar (solo sessions only; workspace uses TerminalLayer's global bar) */} {isComposeBarOpen && !inWorkspace && ( { if (sessionRef.current) { executeSnippetCommand(text, false); } }} onSnippetClick={(snippet) => void executeSnippet(snippet)} snippets={snippets} onClose={() => { setIsComposeBarOpen(false); termRef.current?.focus(); }} isBroadcastEnabled={isBroadcastEnabled} themeColors={effectiveTheme.colors} /> )}
); } export const TerminalView = memo(TerminalViewInner, terminalViewCtxEqual); TerminalView.displayName = 'TerminalView';