/* eslint-disable @typescript-eslint/no-explicit-any */ import React, { memo, useCallback, useEffect, useState } from 'react'; import { TerminalServerStats } from './TerminalServerStats'; import { TerminalTimestampGutter, resolveTerminalTimestampGutterColor, resolveTerminalTimestampGutterWidth, } from './TerminalTimestampGutter'; 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, ); } /** * 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, 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, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOsc52ReadResponse, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, hasSelection, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, isCancelling, isComposeBarOpen, isDraggingOver, isFocusMode, isLocalConnection, remoteDragDropUsesZmodem, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, knownCwdRef, needsHostKeyVerification, onCloseSession, onExpandToFocus, onOpenSystem, onSplitHorizontal, onSplitVertical, onToggleBroadcast, onUpdateHost, osc52ReadPromptVisible, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, searchMatchCount, selectionOverlayPosition, sessionId, sessionRef, setIsComposeBarOpen, setShowLogs, shouldShowConnectionDialog, showLogs, showSelectionAIAction, snippets, status, statusDotTone, sudoHintRef, sudoHintText, t, termRef, terminalContextActions, terminalCwdTracker, terminalPreviewVars, terminalSettings, timeLeft, toast, zmodem } = ctx; const ymodemActionEnabled = shouldEnableYmodemAction({ isSerialConnection, status, handleSendYmodem, handleReceiveYmodem, }); const terminalContentTop = isSearchOpen ? "64px" : "30px"; 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"); return ( onCloseSession?.(sessionId) : undefined} onAddSelectionToAI={ctx.onAddSelectionToAI ? handleAddSelectionToAI : 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") }
)}
{host.label} {shouldShowLineTimestampToolbarToggle(lineTimestampsAvailable, onUpdateHost) && ( {lineTimestampToggleLabel} )} {host.protocol !== "local" && host.hostname && host.hostname !== "localhost" && ( {t("terminal.statusbar.copyHostname.tooltip", { hostname: host.hostname })} )} {isSystemSidebarEligible && ( {t("terminal.layer.system")} )}
{!compactToolbar && ( )}
{inWorkspace && onToggleBroadcast && ( {isBroadcastEnabled ? t("terminal.toolbar.broadcastDisable") : t("terminal.toolbar.broadcastEnable")} )} {inWorkspace && !isFocusMode && onExpandToFocus && ( {t("terminal.toolbar.focusMode")} )} {renderControls({ showClose: inWorkspace })}
{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={isSearchOpen ? 64 : 30} keyEventRef={autocompleteKeyEventRef} inputRef={autocompleteInputRef} repositionRef={autocompleteRepositionRef} closeRef={autocompleteCloseRef} sudoHintRef={sudoHintRef} sudoHintText={sudoHintText} /> {/* 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 && (
)} {/* 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';