Files
Netcatty/components/terminal/autocomplete/terminalAutocompleteLayout.ts
T
cc5ad3be16 perf: isolate Terminal hot props, cut memory/jank, and repay architecture debt (#2790)
* refactor: migrate architecture-debt hooks into application/state

Move SFTP Wave A stores/hooks and related vault/AI/terminal/systemManager
hooks out of components into application/state, update importers, and keep
thin deprecated re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* refactor(sftp): align local bookmarks store API with global bookmarks

Export subscribe/get/set/rehydrate helpers from localSftpBookmarks to match
the globalSftpBookmarks external-store pattern.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(electron): reduce baseline memory via spellcheck/GPU/prewarm guards

Disable spellcheck on BrowserWindows and the default session, drop spare
renderers, gate aggressive GPU switches behind NETCATTY_COMPAT_GPU, and make
settings prewarm opt-in via NETCATTY_PREWARM_SETTINGS.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* Isolate notes and customAccent from TerminalLayer hot props

Route vault notes through notesStore (shellHistoryStore pattern) and
app accent through appearanceChromeStore so note edits and accent-drag
ticks no longer rebuild TerminalLayer. Notes/AI slots and Terminal leaves
subscribe locally; VaultView and open-note callbacks stay unchanged.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ui): cut unnecessary AppView/VaultView/settings re-renders

Stabilize TopTabs close handler, memo AppHostTreeLayer, exclude accent from
settingsVersion, ignore connectionLogs off the logs section, share lastConnected
host refs, and keep rename dialog drafts local so chrome domain stays stable.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* chore: package size, dead code, and consolidation cleanup

Remove unused direct deps, exclude Vite-bundled renderer packages from
electron-builder, delete high-confidence dead code/no-op transfer warm
wiring, consolidate cloud provider IDs and KnownHost/SFTP helpers, and
land UI/AGENTS quick wins (rAF text batching, notes draft debounce,
streaming plain text, tempDirBridge, diagnostics adapter, External MCP
setters).

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: stabilize rAF text batching and diagnostics tests

Polyfill requestAnimationFrame for Node, flush pending text before
steer buffering, bypass rAF while steer is in flight, and stub
global localStorage for AI panel diagnostics adapter tests.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: correct import paths after application/state hook migrations

Migrated vault/AI/system hooks still used components/-relative imports;
point them at repo-root domain/components/types/lib instead.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: address Bugbot/Codex regressions from perf cleanup

- Keep blank Enter from closing RenameDraftDialog; only reset rename state after a non-empty submit
- Flush note drafts before vault mutations so pending title/body edits are not overwritten
- Re-apply appearanceChromeStore accent on appearanceTheme in Terminal, and keep layer themes unaccented

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): flush draft before markdown export paths

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep editor-close hotkey ref fresh during render

Assign handleRequestCloseEditorTabRef in render instead of useEffect so
Cmd/Ctrl+W never hits the App stub before the effect runs.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep accent in chrome themes without TerminalLayer thrash

Restore accent in globalAppearance for chrome/injection consumers.
Keep resolveFocusedAppearance identity stable across accent drag via
accent ref, while Terminal leaf still re-applies appearanceChromeStore.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep compose chrome accent live and merge note renames

Subscribe theme-panel focusedAppearance to appearanceChromeStore so
compose-bar chrome updates during color-picker drag even when
resolveFocusedAppearance identity stays stable. Tree renames now merge
title into the post-flush note instead of replacing from a stale row.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear terminal accent when switching back to theme mode

Re-resolve appearanceTheme by catalog id before applyCustomAccent so a
stale baked custom cursor/selection cannot stick after accentMode returns
to theme while TerminalLayer memo ignores accent props.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: register unsaved prompt singleton during render

AppView close handlers call promptUnsavedChanges outside the old
render-prop. Assign the singleton during render so Cmd/Ctrl+W and tab
close never hit the pre-effect null window that auto-cancels.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep vault import hooks UI-free and flush notes on teardown

Move ImportOptions into application/state and inject a notifier so
useVaultImportHandlers no longer imports components. Notes drafts also
flush on pagehide/beforeunload when Electron tears down without React
unmount.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move AI terminal session context builders into domain

buildAITerminalSessionInfo and AIPanelContext now live under domain/ so
application hooks no longer import TerminalLayerSupport and create a
UI → application → UI cycle.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: drop duplicate AIPanelContext type from TerminalLayerSupport

The type is re-exported from domain; the local definition conflicted.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep migrated state hooks free of UI-layer imports

Move aiChatStreamingSupport into infrastructure/ai and poll list helpers
into domain/systemManager so useAIChatStreaming / useSystemManager no
longer import from components. Leave thin re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move remaining migrated-hook deps out of components

Host-key verification types/helpers now live in domain/, and SFTP column
layout types live in application/state/sftp/columnLayout. Application
hooks no longer import those definitions from the UI layer.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear lint blockers and flush notes when panels hide

Move AI panel diagnostics persistence into application/state so
components stop importing localStorageAdapter. Flush note drafts when
retained NotesManager mounts become inactive, and silence related lint
warnings in theme/host-key helpers.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): publish notesStore sync on vault note updates

updateNotes/updateNoteGroups now publishNotesSnapshot immediately so
AI/notes consumers do not briefly read a stale catalog after a hide
flush. Flush inactive drafts in useLayoutEffect before paint.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-08-07 14:40:38 +08:00

449 lines
16 KiB
TypeScript

import type { Terminal as XTerm } from "@xterm/xterm";
import type { CompletionSuggestion } from "./completionEngine";
import type { PromptDetectionResult } from "./promptDetector";
import type { SubDirPanel } from "./useTerminalAutocomplete";
import { getXTermCellDimensions } from "./xtermUtils";
export function resolveAutocompleteCwd(
promptText: string,
currentWord: string,
fallbackCwd: string | undefined,
os: "linux" | "windows" | "macos",
): string | undefined {
return resolveAutocompleteCwdWithSource(promptText, currentWord, fallbackCwd, os).cwd;
}
export type AutocompleteCwdSource = "prompt" | "fallback" | "none";
export function resolveAutocompleteCwdWithSource(
promptText: string,
currentWord: string,
fallbackCwd: string | undefined,
os: "linux" | "windows" | "macos",
): { cwd: string | undefined; source: AutocompleteCwdSource } {
if (os === "windows") return { cwd: fallbackCwd, source: fallbackCwd ? "fallback" : "none" };
const normalizedWord = currentWord.trim().replace(/^['"]/, "");
// Absolute or home-relative paths don't depend on cwd
if (normalizedWord.startsWith("/") || normalizedWord.startsWith("~/")) {
return { cwd: fallbackCwd, source: fallbackCwd ? "fallback" : "none" };
}
// For empty word (e.g. "cd ") and relative paths, try prompt-based cwd
// extraction which reflects the current visible prompt — more up-to-date
// than fallbackCwd when OSC 7 is not supported.
const promptCwd = extractPosixCwdFromPrompt(promptText);
return chooseAutocompleteCwdWithSource(promptCwd, fallbackCwd);
}
function chooseAutocompleteCwdWithSource(
promptCwd: string | undefined,
fallbackCwd: string | undefined,
): { cwd: string | undefined; source: AutocompleteCwdSource } {
if (!promptCwd) return { cwd: fallbackCwd, source: fallbackCwd ? "fallback" : "none" };
if (!fallbackCwd) return { cwd: promptCwd, source: "prompt" };
// Prompt cwd is extracted from the currently visible prompt, so it tracks
// directory changes even when OSC 7 is not supported. Prefer it over
// fallbackCwd (which may be stale from initial connection) whenever it
// looks like a usable path.
if (promptCwd.startsWith("/") || promptCwd === "~" || promptCwd.startsWith("~/")) {
return { cwd: promptCwd, source: "prompt" };
}
// Bare directory name (e.g. "xunlong") can't be used as a path — fallback
return { cwd: fallbackCwd, source: fallbackCwd ? "fallback" : "none" };
}
function extractPosixCwdFromPrompt(promptText: string): string | undefined {
const trimmed = promptText.trimEnd().replace(/[#$%>]\s*$/, "");
if (!trimmed) return undefined;
const patterns = [
/:(\/[^\s\]]*|~(?:\/[^\s\]]*)?)$/,
/\s(\/[^\s\]]*|~(?:\/[^\s\]]*)?)\]$/,
/(^|[\s:])(\/[^\s\]]*|~(?:\/[^\s\]]*)?)$/,
];
for (const pattern of patterns) {
const match = trimmed.match(pattern);
if (!match) continue;
const candidate = match[match.length - 1];
if (candidate === "/" || candidate.startsWith("/") || candidate === "~" || candidate.startsWith("~/")) {
return candidate;
}
}
const fallbackTokens = trimmed
.split(/\s+/)
.map((token) => token.replace(/^[([{:]+/, "").replace(/[\])}:]+$/, ""));
for (let index = fallbackTokens.length - 1; index >= 0; index--) {
const candidate = fallbackTokens[index];
if (candidate === "/" || candidate.startsWith("/") || candidate === "~" || candidate.startsWith("~/")) {
return candidate;
}
}
return undefined;
}
export function areSuggestionsEqual(
left: CompletionSuggestion[],
right: CompletionSuggestion[],
): boolean {
if (left.length !== right.length) return false;
for (let i = 0; i < left.length; i++) {
const a = left[i];
const b = right[i];
if (
a.text !== b.text ||
a.displayText !== b.displayText ||
a.description !== b.description ||
a.source !== b.source ||
a.score !== b.score ||
a.frequency !== b.frequency ||
a.fileType !== b.fileType
) {
return false;
}
}
return true;
}
export function areSubDirPanelsEqual(left: SubDirPanel[], right: SubDirPanel[]): boolean {
if (left.length !== right.length) return false;
for (let i = 0; i < left.length; i++) {
const a = left[i];
const b = right[i];
if (a.dirPath !== b.dirPath || a.selectedIndex !== b.selectedIndex) return false;
if (a.entries.length !== b.entries.length) return false;
for (let j = 0; j < a.entries.length; j++) {
if (a.entries[j].name !== b.entries[j].name || a.entries[j].type !== b.entries[j].type) {
return false;
}
}
}
return true;
}
export interface PopupClampViewport {
left: number;
top: number;
width: number;
height: number;
}
export interface PopupPlacementInput {
/** Anchor (current input line) top edge, in viewport coordinates. */
anchorTop: number;
/** Anchor (current input line) bottom edge, in viewport coordinates. */
anchorBottom: number;
/** Desired left edge (cursor column), in viewport coordinates. */
anchorLeft: number;
viewportWidth: number;
viewportHeight: number;
/**
* Optional clamp region in viewport coordinates. Defaults to the rectangle
* `(0, 0, viewportWidth, viewportHeight)`.
*/
clampViewport?: PopupClampViewport;
/** Natural height the popup wants if unconstrained (main list or detail). */
desiredHeight: number;
/**
* Total horizontal extent of the popup including any cascading sub-directory
* panels and the detail tooltip — used so the whole assembly is clamped
* inside the viewport, not just the main list.
*/
totalWidth: number;
/**
* Width budget for horizontal clamping. Defaults to `totalWidth`. The detail
* tooltip is rendered beside the list and can extend left on its own, so
* callers may pass a smaller width to keep the primary list near the cursor.
*/
clampWidth?: number;
/** Hard cap on rendered height (matches the list's maxHeight prop). */
maxHeight: number;
/** Gap between the anchor line and the popup. */
anchorGap: number;
/** Minimum distance to keep from the viewport edges. */
viewportPadding: number;
/**
* Direction hint from the cursor-cell based calculation. Only used to break
* ties when neither side can fully fit the desired height.
*/
expandUpwardHint: boolean;
}
export interface PopupPlacement {
/** Whether the popup renders above the anchor line (flipped up). */
renderUpward: boolean;
/** Final top edge, in viewport coordinates (already clamped). */
top: number;
/** Final left edge, in viewport coordinates (already clamped). */
left: number;
/** Height budget for the rendered content (drives scrolling). */
maxHeight: number;
}
export interface PopupGeometryClampInput {
left: number;
top: number;
width: number;
height: number;
clampViewport: PopupClampViewport;
viewportPadding: number;
}
export interface PopupGeometry {
top: number;
left: number;
}
function clampCoordinate(value: number, min: number, max: number): number {
if (max <= min) return min;
return Math.max(min, Math.min(value, max));
}
/**
* Final guardrail using the rendered popup's actual DOM size. The placement
* pass uses estimated list/detail/panel sizes so it can decide before render;
* this pass prevents any estimate mismatch or delayed xterm cursor refresh
* from letting the fixed-position portal escape the terminal/app bounds.
*/
export function clampAutocompletePopupGeometry(
input: PopupGeometryClampInput,
): PopupGeometry {
const { left, top, width, height, clampViewport, viewportPadding } = input;
const safeWidth = Number.isFinite(width) ? Math.max(0, width) : 0;
const safeHeight = Number.isFinite(height) ? Math.max(0, height) : 0;
const minLeft = clampViewport.left + viewportPadding;
const minTop = clampViewport.top + viewportPadding;
const maxLeft = clampViewport.left + clampViewport.width - viewportPadding - safeWidth;
const maxTop = clampViewport.top + clampViewport.height - viewportPadding - safeHeight;
return {
left: clampCoordinate(left, minLeft, Math.max(minLeft, maxLeft)),
top: clampCoordinate(top, minTop, Math.max(minTop, maxTop)),
};
}
/**
* Decide where to place the autocomplete popup so it never spills past the
* viewport edges. Pure and deterministic so the boundary math is unit-tested
* independently of React/DOM.
*
* Vertical: prefer downward, but flip upward when the space below the input
* line can't fit the desired height and the space above is a better fit. The
* height is then clamped to whatever the chosen side actually offers so the
* list scrolls instead of overflowing.
*
* Horizontal: clamp the left edge using the popup's *total* width (main list +
* cascading sub-dir panels + detail tooltip), not just the main list, so wide
* assemblies near the right edge slide left instead of overflowing. When the
* assembly is wider than the viewport it pins to the left padding so the
* primary list stays visible.
*/
export function computeAutocompletePopupPlacement(
input: PopupPlacementInput,
): PopupPlacement {
const {
anchorTop,
anchorBottom,
anchorLeft,
viewportWidth,
viewportHeight,
desiredHeight,
totalWidth,
maxHeight,
anchorGap,
viewportPadding,
expandUpwardHint,
clampViewport,
clampWidth,
} = input;
const bounds: PopupClampViewport = clampViewport ?? {
left: 0,
top: 0,
width: viewportWidth,
height: viewportHeight,
};
const boundsRight = bounds.left + bounds.width;
const boundsBottom = bounds.top + bounds.height;
const horizontalClampWidth = clampWidth ?? totalWidth;
const cappedDesiredHeight = Math.min(maxHeight, Math.max(0, desiredHeight));
const spaceAbove = Math.max(0, anchorTop - bounds.top - viewportPadding - anchorGap);
const spaceBelow = Math.max(0, boundsBottom - anchorBottom - viewportPadding - anchorGap);
const canFullyRenderAbove = spaceAbove >= cappedDesiredHeight;
const canFullyRenderBelow = spaceBelow >= cappedDesiredHeight;
const renderUpward = canFullyRenderBelow
? false
: canFullyRenderAbove
? true
: expandUpwardHint
? spaceAbove >= Math.min(spaceBelow, 80)
: spaceAbove > spaceBelow;
const availableVerticalSpace = renderUpward ? spaceAbove : spaceBelow;
const availableViewportHeight = Math.max(0, bounds.height - viewportPadding * 2);
const effectiveMaxHeight = Math.max(
0,
Math.min(maxHeight, availableVerticalSpace, availableViewportHeight),
);
const contentHeightForPlacement = Math.min(effectiveMaxHeight, cappedDesiredHeight);
const unclampedTop = renderUpward
? Math.max(bounds.top + viewportPadding, anchorTop - anchorGap - contentHeightForPlacement)
: Math.min(
anchorBottom + anchorGap,
boundsBottom - viewportPadding - contentHeightForPlacement,
);
const minTop = bounds.top + viewportPadding;
const maxTop = Math.max(minTop, boundsBottom - viewportPadding - contentHeightForPlacement);
const top = Math.max(minTop, Math.min(unclampedTop, maxTop));
// Right edge that keeps the clamped assembly inside the bounds. When the
// assembly is wider than the available room this goes below the left padding,
// so the final clamp pins the popup to the left padding (primary list wins).
const maxLeft = boundsRight - viewportPadding - Math.max(0, horizontalClampWidth);
const left = Math.max(bounds.left + viewportPadding, Math.min(anchorLeft, maxLeft));
return { renderUpward, top, left, maxHeight: effectiveMaxHeight };
}
export interface AutocompleteViewportAnchor {
anchorLeft: number;
anchorTop: number;
anchorBottom: number;
expandUpward: boolean;
}
const ESTIMATED_ROW_HEIGHT_PX = 28;
const POPUP_CHROME_PADDING_PX = 8;
function estimatePopupHeight(itemCount: number): number {
return itemCount * ESTIMATED_ROW_HEIGHT_PX + POPUP_CHROME_PADDING_PX;
}
function shouldExpandAutocompleteUpward(
cursorY: number,
spaceBelowPx: number,
spaceAbovePx: number,
estimatedPopupHeight: number,
): boolean {
if (spaceBelowPx >= estimatedPopupHeight) return false;
if (spaceAbovePx >= estimatedPopupHeight) return true;
return cursorY > 2 && spaceAbovePx >= spaceBelowPx;
}
/**
* Best-effort cursor column for popup anchoring. xterm's helper textarea and
* buffer.cursorX can lag behind the keystroke that triggered completion, so
* derive the column from the aligned prompt when the command still fits on one
* row.
*/
export function resolveAutocompleteCursorColumn(
term: XTerm,
prompt: Pick<PromptDetectionResult, "promptText" | "userInput">,
): number {
const buffer = term.buffer.active;
const absY = buffer.cursorY + buffer.baseY;
const line = buffer.getLine(absY);
if (line?.isWrapped) {
return buffer.cursorX;
}
let fromLine = buffer.cursorX;
if (line) {
const lineText = line.translateToString(false);
const tail = lineText.substring(buffer.cursorX).trimEnd();
if (tail.length === 0) {
fromLine = Math.max(buffer.cursorX, lineText.trimEnd().length);
}
}
const fromPrompt = prompt.promptText.length + prompt.userInput.length;
return Math.max(fromLine, fromPrompt);
}
/** Clamp autocomplete popups to the active terminal screen in split workspaces.
*
* Uses the visible `.xterm-screen` rect as the clamp boundary so the popup
* never overflows the *actual* rendered terminal grid. The `.xterm-container`
* can be a few pixels taller than the screen (rounding/padding), so falling
* back to its rect produced a false positive `spaceBelow` at the bottom row
* and caused short suggestion lists to flip downward below the visible area
* (see issue #1710).
*/
export function resolveAutocompleteClampViewport(container: HTMLElement | null): PopupClampViewport {
const pane = container?.closest<HTMLElement>('[data-section="terminal-split-pane"]');
const screen = container?.querySelector<HTMLElement>(".xterm-screen")
?? null;
// Clamp to the rendered screen so the popup cannot spill past the visible
// terminal rows. If the screen is not mounted yet, fall back to the split
// pane/container rect or the full viewport.
const rect = screen?.getBoundingClientRect()
?? pane?.getBoundingClientRect()
?? container?.getBoundingClientRect();
if (rect && rect.width > 0 && rect.height > 0) {
return {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
};
}
return {
left: 0,
top: 0,
width: typeof window !== "undefined" ? window.innerWidth : 1200,
height: typeof window !== "undefined" ? window.innerHeight : 800,
};
}
/**
* Resolve the autocomplete anchor in viewport coordinates so split panes and
* padded xterm screens stay aligned with the real cursor.
*/
export function resolveAutocompleteAnchorInViewport(
term: XTerm,
container: HTMLElement | null,
itemCount: number,
cursorColumn = term.buffer.active.cursorX,
): AutocompleteViewportAnchor {
const empty: AutocompleteViewportAnchor = {
anchorLeft: 0,
anchorTop: 0,
anchorBottom: 0,
expandUpward: false,
};
if (!container || !term.element) return empty;
const buffer = term.buffer.active;
const cursorY = buffer.cursorY;
const rows = Math.max(1, term.rows);
const estimatedPopupHeight = estimatePopupHeight(itemCount);
const dims = getXTermCellDimensions(term);
const screen =
container.querySelector<HTMLElement>(".xterm-screen")
?? term.element.querySelector<HTMLElement>(".xterm-screen")
?? container;
const screenRect = screen.getBoundingClientRect();
const anchorLeft = screenRect.left + cursorColumn * dims.width;
const anchorTop = screenRect.top + cursorY * dims.height;
const anchorBottom = screenRect.top + (cursorY + 1) * dims.height;
const spaceBelow = Math.max(0, (rows - cursorY - 1) * dims.height);
const spaceAbove = Math.max(0, cursorY * dims.height);
return {
anchorLeft,
anchorTop,
anchorBottom,
expandUpward: shouldExpandAutocompleteUpward(cursorY, spaceBelow, spaceAbove, estimatedPopupHeight),
};
}