diff --git a/application/state/useAutoSync.monitorPanels.test.ts b/application/state/useAutoSync.monitorPanels.test.ts index bc935b229..0d7db555b 100644 --- a/application/state/useAutoSync.monitorPanels.test.ts +++ b/application/state/useAutoSync.monitorPanels.test.ts @@ -195,3 +195,82 @@ test("normal manual and debounced auto-sync upload panel creation, edits and del Object.assign(manager, originals); } }); + +test("pending-sync indication coalesces edit bursts without repeatedly collecting the vault", async () => { + const manager = getCloudSyncManager(); + const snapshot = { + ...manager.getState(), + securityState: "UNLOCKED" as const, + syncState: "IDLE" as const, + autoSyncEnabled: true, + providers: { + ...manager.getState().providers, + webdav: { provider: "webdav" as const, status: "connected" as const }, + }, + }; + const originals = { + getState: manager.getState, + loadSyncBase: manager.loadSyncBase, + inspectProviderRemote: manager.inspectProviderRemote, + setPendingLocalSync: manager.setPendingLocalSync, + setAvailablePluginSyncProviders: manager.setAvailablePluginSyncProviders, + }; + manager.getState = () => snapshot; + manager.loadSyncBase = async () => null; + manager.inspectProviderRemote = async () => ({ remoteFile: null, payload: null, remoteChanged: false }); + const pending: boolean[] = []; + manager.setPendingLocalSync = (value) => { pending.push(value); }; + manager.setAvailablePluginSyncProviders = () => {}; + let collects = 0; + let collectBarrier: Promise | undefined; + Object.defineProperty(window, "netcatty", { configurable: true, value: { + collectPluginSyncSidecars: async () => { collects++; await collectBarrier; return { version: 1, entries: [] }; }, + } }); + const apply = async () => {}; + const config = { hosts: [], keys: [], snippets: [], customGroups: ["fixture"], startupReady: true, + onApplyPayload: apply, onApplyConvergentPayload: apply }; + function Probe({ enabled = true }: { enabled?: boolean }) { useAutoSync({ ...config, enabled }); return null; } + let renderer: ReactTestRenderer | undefined; + const wait = async (ms: number) => { await act(async () => { await new Promise((resolve) => setTimeout(resolve, ms)); }); }; + try { + store.clear(); + writeMonitorPanels([{ id: "burst", name: "Before", description: "", hostIds: ["h"], view: "list", interval: 5, range: 15, sort: "manual" }]); + await act(async () => { renderer = create(React.createElement(Probe)); }); + await wait(500); + const initial = collects; + assert.ok(initial > 0, "startup still collects a real sync baseline"); + for (let i = 0; i < 10; i++) { + await act(async () => { + writeMonitorPanels([{ id: "burst", name: `Edit ${i}`, description: "", hostIds: ["h"], view: "list", interval: 5, range: 15, sort: "manual" }]); + await new Promise((resolve) => setTimeout(resolve, 5)); + }); + } + assert.equal(collects, initial, "editing must not repeatedly collect all sync data"); + await wait(350); + assert.equal(collects, initial + 1, "the final edit updates the pending indicator once"); + assert.equal(pending.at(-1), true); + writeMonitorPanels([]); + await wait(10); + await act(async () => { renderer!.update(React.createElement(Probe, { enabled: false })); }); + const disabled = collects; + await wait(350); + assert.equal(collects, disabled, "disabling sync cancels the pending collection"); + assert.equal(pending.at(-1), false); + await act(async () => { renderer!.update(React.createElement(Probe)); }); + await wait(350); + let releaseCollection!: () => void; + collectBarrier = new Promise((resolve) => { releaseCollection = resolve; }); + const beforeInflight = collects; + writeMonitorPanels([{ id: "burst", name: "New edit", description: "", hostIds: ["h"], view: "list", interval: 5, range: 15, sort: "manual" }]); + await wait(10); + await wait(350); + assert.equal(collects, beforeInflight + 1, "the pending collection has started"); + await act(async () => { renderer!.update(React.createElement(Probe, { enabled: false })); }); + await act(async () => { releaseCollection(); }); + assert.equal(pending.at(-1), false, "an old collection cannot re-enable the indicator after disabling sync"); + } finally { + await act(async () => renderer?.unmount()); + Reflect.deleteProperty(window, "netcatty"); + Object.assign(manager, originals); + } +}); diff --git a/application/state/useAutoSync.ts b/application/state/useAutoSync.ts index 7a838438f..322a51031 100644 --- a/application/state/useAutoSync.ts +++ b/application/state/useAutoSync.ts @@ -603,7 +603,7 @@ export const useAutoSync = (config: AutoSyncConfig) => { getDataHashRef.current = getDataHash; }, [getDataHash]); - const refreshPendingLocalSync = useCallback(async () => { + const refreshPendingLocalSync = useCallback(async (isCurrent = () => true) => { if ( !enabled || convergentSyncPaused @@ -618,6 +618,7 @@ export const useAutoSync = (config: AutoSyncConfig) => { } try { const currentHash = await getDataHashRef.current(); + if (!isCurrent()) return; const hashDecision = resolveAutoSyncHashDecision({ currentHash, lastSyncedHash: lastSyncedDataRef.current, @@ -1148,13 +1149,27 @@ export const useAutoSync = (config: AutoSyncConfig) => { // Reflect unsynced local edits in the top-bar cloud indicator. useEffect(() => { - void refreshPendingLocalSync(); + if (!enabled || convergentSyncPaused || !sync.hasAnyConnectedProvider || !sync.isUnlocked) { + manager.setPendingLocalSync(false); + return; + } + // Collecting the pending hash builds the same full payload as an upload. + // Let rapid edits settle before doing that work, even with auto-sync off. + let cancelled = false; + const timer = setTimeout(() => { + void refreshPendingLocalSync(() => !cancelled); + }, 200); + return () => { + cancelled = true; + clearTimeout(timer); + }; }, [ refreshPendingLocalSync, getDataHash, sync.hasAnyConnectedProvider, sync.isUnlocked, sync.isSyncing, + convergentSyncPaused, config.settingsVersion, enabled, bookmarksVersion, diff --git a/components/editor/EditorWindowPage.performance.test.ts b/components/editor/EditorWindowPage.performance.test.ts new file mode 100644 index 000000000..fc61fb196 --- /dev/null +++ b/components/editor/EditorWindowPage.performance.test.ts @@ -0,0 +1,150 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import test from 'node:test'; +import React from 'react'; +import { act, create, type ReactTestRenderer } from 'react-test-renderer'; +import ts from 'typescript'; + +import * as i18n from '../../application/i18n/I18nProvider'; +import * as editorTabs from '../../application/state/editorTabStore'; +import * as editorClient from '../../application/state/editorWindowClient'; +import * as editorRuntime from '../../application/state/useEditorWindow'; +import * as windowControls from '../../application/state/useWindowControls'; +import * as editorTabBar from './EditorWindowTabBar'; +import type { TextEditorPaneProps } from './TextEditorPane'; + +// Run the actual page, pane hosts, runtime and store. Only Monaco's visual +// surface and the unrelated confirmation/toast chrome are replaced here. +// Counting the memoized pane boundary catches content updates leaking through +// the page root into every inactive editor, rather than testing a hand-written +// approximation of the subscription graph. +function loadPage(pane: React.ComponentType) { + const source = readFileSync(new URL('./EditorWindowPage.tsx', import.meta.url), 'utf8'); + const compiled = ts.transpileModule(source, { compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + jsx: ts.JsxEmit.ReactJSX, + esModuleInterop: true, + } }).outputText; + const require = createRequire(import.meta.url); + const dependencies: Record = { + '../../application/i18n/I18nProvider': i18n, + '../../application/state/editorTabStore': editorTabs, + '../../application/state/editorWindowClient': editorClient, + '../../application/state/useEditorWindow': editorRuntime, + '../../application/state/useWindowControls': windowControls, + '../ui/toast': { toast: { success() {}, error() {}, warning() {} } }, + './UnsavedChangesDialog': { + UnsavedChangesProvider: ({ children }: { children: () => React.ReactNode }) => children(), + promptUnsavedChanges: async () => 'cancel', + }, + './EditorWindowTabBar': editorTabBar, + './TextEditorPane': { TextEditorPane: pane }, + }; + const module = { exports: {} as { default: React.ComponentType<{ settings: unknown }> } }; + new Function('require', 'module', 'exports', compiled)( + (id: string) => dependencies[id] ?? require(id), module, module.exports, + ); + return module.exports.default; +} + +const makeTab = (index: number): editorTabs.EditorTab => ({ + id: `performance-editor-${index}`, + kind: 'editor', + sessionId: 'fixture-session', + sftpTabId: 'fixture-sftp', + hostId: 'fixture-host', + remotePath: `/file-${index}.txt`, + fileName: `file-${index}.txt`, + languageId: 'text', + content: 'original', + baselineContent: 'original', + wordWrap: false, + viewState: null, + savingState: 'idle', + saveError: null, +}); + +test('detached editor typing and tab switches leave unrelated editor panes untouched', async () => { + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); + const previousAct = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + const panes = new Map(); + const renders = new Map(); + const titles: string[] = []; + const saves: unknown[] = []; + const docked: unknown[] = []; + let activate: ((payload: { editorId: string }) => void) | undefined; + let finishDock: ((result: { success: boolean }) => void) | undefined; + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true }); + Object.defineProperty(globalThis, 'window', { configurable: true, value: { + setTimeout, clearTimeout, addEventListener() {}, removeEventListener() {}, + netcatty: { + windowIsMaximized: async () => false, + setWindowTitle: async (title: string) => { titles.push(title); }, + onEditorWindowActivateTab: (callback: typeof activate) => { activate = callback; return () => { activate = undefined; }; }, + saveEditorWindowTab: async (snapshot: unknown) => { saves.push(snapshot); return { ok: true }; }, + dockEditorWindowTab: (snapshot: unknown) => { + docked.push(snapshot); + return new Promise<{ success: boolean }>((resolve) => { finishDock = resolve; }); + }, + }, + } }); + const Pane = React.memo((props: TextEditorPaneProps) => { + const name = props.fileName.replace(/ \*$/, ''); + renders.set(name, (renders.get(name) ?? 0) + 1); + panes.set(name, props); + return React.createElement('div', { 'data-editor': name }); + }); + const Page = loadPage(Pane); + const tabs = Array.from({ length: 10 }, (_, index) => makeTab(index)); + let renderer: ReactTestRenderer | undefined; + try { + await act(async () => { + for (const tab of tabs) editorTabs.editorTabStore._debugInsert(tab); + renderer = create(React.createElement(i18n.I18nProvider, { locale: 'en-US', children: React.createElement(Page, { settings: { hotkeyScheme: 'mac', keyBindings: [] } }) })); + }); + renders.clear(); + for (let index = 0; index < 20; index += 1) { + await act(async () => panes.get('file-9.txt')!.onContentChange(`updated ${index}`, null)); + } + assert.deepEqual(Object.fromEntries(renders), { 'file-9.txt': 20 }); + assert.equal(editorTabs.editorTabStore.getTab(tabs[9].id)?.content, 'updated 19'); + assert.equal(titles.at(-1), '* file-9.txt'); + + renders.clear(); + for (let index = 0; index < 10; index += 1) { + await act(async () => activate?.({ editorId: tabs[index].id })); + } + assert.equal([...renders.values()].reduce((sum, count) => sum + count, 0), 0); + assert.equal(editorTabs.editorTabStore.getTab(tabs[9].id)?.content, 'updated 19'); + assert.equal(titles.at(-1), '* file-9.txt'); + + await act(async () => { await panes.get('file-9.txt')!.onSave(); }); + assert.equal(saves.length, 1); + assert.equal(editorTabs.editorTabStore.isDirty(tabs[9].id), false); + assert.equal(titles.at(-1), 'file-9.txt'); + + // Dock completion must not steal focus from a tab selected while the + // acknowledgement was pending; stable callbacks read the latest selection. + await act(async () => { void panes.get('file-9.txt')!.onDockToMain?.(); }); + assert.equal(docked.length, 1); + await act(async () => activate?.({ editorId: tabs[0].id })); + await act(async () => finishDock?.({ success: true })); + assert.equal(editorTabs.editorTabStore.getTab(tabs[9].id), undefined); + assert.equal(titles.at(-1), 'file-0.txt'); + + await act(async () => panes.get('file-0.txt')!.onRequestClose?.()); + assert.equal(editorTabs.editorTabStore.getTab(tabs[0].id), undefined); + assert.equal(titles.at(-1), 'file-8.txt'); + } finally { + await act(async () => { + renderer?.unmount(); + for (const tab of tabs) editorTabs.editorTabStore.close(tab.id); + }); + if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow); + else Reflect.deleteProperty(globalThis, 'window'); + if (previousAct) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousAct); + else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + } +}); diff --git a/components/editor/EditorWindowPage.tsx b/components/editor/EditorWindowPage.tsx index a5a52a0ac..5c5940b99 100644 --- a/components/editor/EditorWindowPage.tsx +++ b/components/editor/EditorWindowPage.tsx @@ -84,7 +84,7 @@ function EditorWindowControls({ onClose }: { onClose: () => void }) { ); } -function EditorWindowPaneHost({ +const EditorWindowPaneHost = React.memo(function EditorWindowPaneHost({ tabId, isVisible, settings, @@ -130,6 +130,16 @@ function EditorWindowPaneHost({ } }, [tabId, t]); + const handleLanguageChange = useCallback((language: string) => { + editorTabStore.setLanguage(tabId, language); + }, [tabId]); + const handleToggleWordWrap = useCallback(() => { + const current = editorTabStore.getTab(tabId); + if (current) editorTabStore.setWordWrap(tabId, !current.wordWrap); + }, [tabId]); + const handleRequestClose = useCallback(() => onRequestClose(tabId), [onRequestClose, tabId]); + const handleDock = useCallback(() => onDock(tabId), [onDock, tabId]); + if (!tab) return null; const isDirty = tabIsDirty(tab); const hostLabel = tab.hostLabel || tab.hostId; @@ -151,18 +161,35 @@ function EditorWindowPaneHost({ hotkeyScheme={settings.hotkeyScheme} keyBindings={settings.keyBindings} onContentChange={handleContentChange} - onLanguageChange={(lang) => editorTabStore.setLanguage(tabId, lang)} - onToggleWordWrap={() => { - const current = editorTabStore.getTab(tabId); - if (current) editorTabStore.setWordWrap(tabId, !current.wordWrap); - }} - onSave={() => { void handleSave(); }} - onRequestClose={() => onRequestClose(tabId)} - onDockToMain={() => onDock(tabId)} + onLanguageChange={handleLanguageChange} + onToggleWordWrap={handleToggleWordWrap} + onSave={handleSave} + onRequestClose={handleRequestClose} + onDockToMain={handleDock} initialViewState={tab.viewState} /> ); +}); + +/** Keep content/dirty notifications out of the page and inactive editor panes. */ +function EditorWindowTitle({ + activeTabId, + setWindowTitle, +}: { + activeTabId: EditorTabId | null; + setWindowTitle: (title: string) => Promise; +}) { + const { t } = useI18n(); + const activeTab = useEditorTab(activeTabId ?? ""); + const activeDirty = useEditorTabDirty(activeTabId ?? ""); + useEffect(() => { + const name = activeTab?.fileName; + void setWindowTitle(name + ? `${activeDirty ? "* " : ""}${name}` + : t("sftp.editor.windowTitle")); + }, [activeDirty, activeTab?.fileName, setWindowTitle, t]); + return null; } function EditorWindowPageInner({ settings }: { settings: SettingsState }) { @@ -171,23 +198,12 @@ function EditorWindowPageInner({ settings }: { settings: SettingsState }) { const { onWindowCommandCloseRequested } = useWindowControls(); const tabs = useEditorTabChromeList(); const closeInFlightRef = useRef | null>(null); - const activeTab = useEditorTab(activeTabId ?? ""); - const activeDirty = useEditorTabDirty(activeTabId ?? ""); useEffect(() => { if (activeTabId && editorTabStore.getTab(activeTabId)) return; if (tabs.length > 0) setActiveTabId(tabs[tabs.length - 1].id); }, [activeTabId, setActiveTabId, tabs]); - useEffect(() => { - const name = activeTab?.fileName; - if (!name) { - void setWindowTitle(t("sftp.editor.windowTitle")); - return; - } - void setWindowTitle(`${activeDirty ? "* " : ""}${name}`); - }, [activeDirty, activeTab?.fileName, setWindowTitle, t]); - const saveTab = useCallback(async (tabId: EditorTabId): Promise => { const result = await saveDetachedEditorTab(tabId); if (result.ok) return true; @@ -221,16 +237,16 @@ function EditorWindowPageInner({ settings }: { settings: SettingsState }) { await closeWindow(); return true; } - if (activeTabId === tabId) { - setActiveTabId(remaining[remaining.length - 1]?.id ?? null); - } + setActiveTabId((current) => current === tabId + ? remaining[remaining.length - 1]?.id ?? null + : current); return true; })().finally(() => { closeInFlightRef.current = null; }); closeInFlightRef.current = task; return task; - }, [activeTabId, closeTab, closeWindow, setActiveTabId]); + }, [closeTab, closeWindow, setActiveTabId]); const handleDock = useCallback(async (tabId: EditorTabId) => { const result = await dockDetachedEditorTab(tabId); @@ -244,10 +260,14 @@ function EditorWindowPageInner({ settings }: { settings: SettingsState }) { await closeWindow(); return; } - if (activeTabId === tabId) { - setActiveTabId(remaining[remaining.length - 1]?.id ?? null); - } - }, [activeTabId, closeWindow, setActiveTabId, t]); + setActiveTabId((current) => current === tabId + ? remaining[remaining.length - 1]?.id ?? null + : current); + }, [closeWindow, setActiveTabId, t]); + + const handleRequestClose = useCallback((tabId: EditorTabId) => { + void closeTabAndMaybeWindow(tabId); + }, [closeTabAndMaybeWindow]); const handleWindowClose = useCallback(async () => { // Native close owns confirmation and blocks new transfers until it settles. @@ -296,6 +316,7 @@ function EditorWindowPageInner({ settings }: { settings: SettingsState }) { return (
+
{isMac ?
: null}
@@ -321,8 +342,8 @@ function EditorWindowPageInner({ settings }: { settings: SettingsState }) { tabId={tab.id} isVisible={tab.id === activeTabId} settings={settings} - onRequestClose={(id) => { void closeTabAndMaybeWindow(id); }} - onDock={(id) => { void handleDock(id); }} + onRequestClose={handleRequestClose} + onDock={handleDock} /> )) )} diff --git a/components/terminal/completionEngineSnippets.test.ts b/components/terminal/completionEngineSnippets.test.ts index 253fbdd0e..5af1bc054 100644 --- a/components/terminal/completionEngineSnippets.test.ts +++ b/components/terminal/completionEngineSnippets.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { getCompletions } from "./autocomplete/completionEngine"; import { DEFAULT_AUTOCOMPLETE_SETTINGS } from "./autocomplete/useTerminalAutocomplete"; +import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../lib/searchMatcher"; import type { Snippet } from "../../domain/models"; const deploySnippet: Snippet = { id: "d", label: "deploy", command: "kubectl apply -f ." }; @@ -83,3 +84,34 @@ test("getCompletions returns more than 8 snippet matches when default maxSuggest ); assert.equal(snippetMatches.length, 20); }); + + +test("argument completion skips ASCII transliteration in a large snippet library", async () => { + const snippets: Snippet[] = Array.from({ length: 5000 }, (_, index) => ({ + id: `snippet-${index}`, + label: `deploy-service-${index}`, + command: `kubectl --namespace production rollout restart deployment service-${index}`, + })); + snippets.push({ id: "mail", label: "邮箱", command: "user@example.com" }); + resetPinyinCacheForTests(); + try { + for (const input of ["git pull zz", "git pull zzq", "git pull zzqx"]) { + assert.deepEqual(await getCompletions(input, { snippets, skipPathCompletion: true }), []); + } + assert.deepEqual( + getPinyinCacheStatsForTests().keys, + ["邮箱"], + "ASCII command tokens cannot produce a new pinyin prefix and must not enter its cache", + ); + const result = await getCompletions("git pull yx", { snippets, skipPathCompletion: true }); + assert.equal(result.find((suggestion) => suggestion.source === "snippet")?.snippet?.id, "mail"); + } finally { + resetPinyinCacheForTests(); + } +}); + +test("ASCII argument completion retains compact query prefixes", async () => { + const snippets: Snippet[] = [{ id: "compact", label: "production-foobar", command: "echo ready" }]; + const result = await getCompletions("git pull foo_bar", { snippets, skipPathCompletion: true }); + assert.equal(result.find((suggestion) => suggestion.source === "snippet")?.snippet?.id, "compact"); +}); diff --git a/docs/research/sync-pending-indicator-performance.md b/docs/research/sync-pending-indicator-performance.md new file mode 100644 index 000000000..541afc0e4 --- /dev/null +++ b/docs/research/sync-pending-indicator-performance.md @@ -0,0 +1,18 @@ +# Pending sync indicator performance + +The pending-local-sync indicator independently collected and serialized the full sync payload after every local edit. Upload debounce did not cover this path. New monitor panel and portable chat changes also trigger it. No competing open repair was found during the 2026-10-18 audit. + +A production React hook in an isolated Electron renderer, with 2,000 synthetic hosts and mocked cloud network edges, received 50 monitor-name edits spaced 5 ms apart: + +| Checkpoint | Before | After | +| --- | --- | --- | +| Collections during the edit burst | 50 | 0 | +| Collections for the settled indicator | 0 additional | 1 | +| Uploads after the existing upload debounce | 1 | 1 | +| Pending indicator after edits | true | true | + +The indicator now waits 200 ms after the latest change before collecting. Disabling, locking, losing the provider, pausing, or unmounting cancels pending work; stale in-flight indicator results are ignored. Startup baseline collection and explicit/manual sync keep their existing timing. The change does not alter cloud payloads or conflict/merge decisions. + +`application/state/useAutoSync.monitorPanels.test.ts` exercises the actual hook, adapter notifications, and sidecar collection boundary. It failed before the fix (13 collections vs 3 startup collections after ten edits), and passes after the fix. It also checks settled pending state, cancellation before collection, and cancellation while collection is in flight. Existing panel create/edit/delete upload and sync baseline tests continue to pass. + +Validation: 47 related tests passed, full lint has zero errors (eight existing warnings), and production build passed. Full-platform CI must be checked at the final PR head. The fixture does not claim to reproduce the Windows long-running terminal report or to benchmark a real cloud provider. diff --git a/docs/research/terminal-snippet-completion-performance.md b/docs/research/terminal-snippet-completion-performance.md new file mode 100644 index 000000000..ede9dddfa --- /dev/null +++ b/docs/research/terminal-snippet-completion-performance.md @@ -0,0 +1,29 @@ +# Terminal argument completion performance + +Issue: #3715. This follows #3623's argument-position matching for #3622; it does not resolve #3622's remaining interactive-email UX request. + +`matchesWordPrefixQuery` tried pinyin for every word after a failed literal prefix comparison. A large snippet library therefore repeated transliteration/cache work for ordinary ASCII command words on each completion query. Printable ASCII words cannot gain another pinyin prefix, so they now return a miss immediately after the literal check. Chinese and other non-ASCII words keep the existing path. + +## Verification + +The regression exercises the actual `getCompletions` argument path with 5,000 snippets. Before the fix, it fails because the pinyin cache contains 5,011 entries, including ASCII commands and numbers. Afterward, only the Chinese label is cached and its initials still find the snippet. Additional cases cover empty queries, case, fullwidth normalization, word boundaries, Chinese full pinyin/initials, and mixed ASCII/Chinese words. + +Run the real Electron renderer measurement: + +```sh +node_modules/.bin/electron scripts/terminal-snippet-completion-performance.live.test.cjs +``` + +This uses isolated application data and synthetic snippets, calls the production completion engine, measures completion time and a queued input timer, and checks that ASCII words bypass pinyin while Chinese initials still work. It prints timings; the regression gate is the unnecessary-work assertion, avoiding a machine-specific timing threshold. + +On the audit machine, an initial fixture with Chinese labels and ASCII commands measured: + +| Library | Before | After | +| --- | --- | --- | +| 100 snippets | 0.4–2.4 ms | 0.1–1.3 ms | +| 1,000 snippets | 4.2–7.0 ms | 1.7–2.3 ms | +| 5,000 snippets | 52.9–86.0 ms | 8.8–9.9 ms | + +The corresponding 5,000-entry queued input delay fell from 53.1–86.1 ms to 8.8–9.9 ms. The committed fixture uses ASCII labels plus one Chinese label; the final three rounds measured 6.5–11.0 ms. These are local completion/render-thread measurements, not network or terminal throughput measurements. + +An isolated real Electron window also mounted production `TerminalAutocomplete` with real xterm and 5,001 snippets. Typing `git pull yx` displayed the Chinese mailbox snippet; clicking it selected the correct snippet. No connected SSH server, personal snippets, or user settings were used. diff --git a/domain/searchMatcher.test.ts b/domain/searchMatcher.test.ts index 934dfbbae..1d1a0580b 100644 --- a/domain/searchMatcher.test.ts +++ b/domain/searchMatcher.test.ts @@ -8,6 +8,7 @@ import { getHostSearchMatch, matchesHostSearchQuery, matchesSearchQuery, + matchesWordPrefixQuery, matchesWorkspaceHostPickerQuery, resetPinyinCacheForTests, } from "../lib/searchMatcher.ts"; @@ -321,3 +322,19 @@ test("host ASCII bypass preserves strict source selection, IP isolation, and pin details: [{ segment: "apibu", field: "label", method: "pinyinFull", phase: "loose" }], }); }); + + +test("word prefixes retain literal, normalized, and non-ASCII matching", () => { + assert.equal(matchesWordPrefixQuery("", "deploy"), true); + assert.equal(matchesWordPrefixQuery("DEP", "deploy-service"), true); + assert.equal(matchesWordPrefixQuery("ser", "deploy-service"), true); + assert.equal(matchesWordPrefixQuery("123", "item-1234"), true); + assert.equal(matchesWordPrefixQuery("dep", "DEPLOY"), true); + assert.equal(matchesWordPrefixQuery("caf", "café"), true); + assert.equal(matchesWordPrefixQuery("mail", "gmail"), false); + assert.equal(matchesWordPrefixQuery("zz", "deploy-service"), false); + assert.equal(matchesWordPrefixQuery("--de", "deploy-service"), false); + assert.equal(matchesWordPrefixQuery("bushu", "部署服务"), true); + assert.equal(matchesWordPrefixQuery("bsfw", "部署服务"), true); + assert.equal(matchesWordPrefixQuery("apibu", "API部署"), true); +}); diff --git a/lib/searchMatcher.ts b/lib/searchMatcher.ts index 7bb3081a5..318c7c7a4 100644 --- a/lib/searchMatcher.ts +++ b/lib/searchMatcher.ts @@ -334,6 +334,9 @@ export function matchesWordPrefixQuery( return words.some((word) => { if (word.startsWith(normalizedQuery)) return true; if (!compactQuery) return false; + // ASCII command words cannot gain a different pinyin prefix. Avoid the + // transliteration/cache work for every token in large snippet libraries. + if (/^[\x20-\x7E]+$/.test(word)) return word.startsWith(compactQuery); const { full, initials } = getPinyinVariants(word); return ( (full !== "" && full.startsWith(compactQuery)) diff --git a/scripts/terminal-snippet-completion-performance.live.test.cjs b/scripts/terminal-snippet-completion-performance.live.test.cjs new file mode 100644 index 000000000..ef811fb77 --- /dev/null +++ b/scripts/terminal-snippet-completion-performance.live.test.cjs @@ -0,0 +1,82 @@ +"use strict"; +/* global process, __dirname, console */ + +if (!process.versions.electron) { + require("node:test")("large snippet libraries keep argument completion responsive", { + skip: "run with Electron to measure the actual renderer completion path", + }, () => {}); +} else { + const assert = require("node:assert/strict"); + const fs = require("node:fs"); + const path = require("node:path"); + const { app, BrowserWindow } = require("electron"); + const esbuild = require("esbuild"); + const temp = require("../electron/bridges/tempDirBridge.cjs"); + const userData = fs.mkdtempSync(`${temp.getTempFilePath("snippet-completion-perf")}-`); + app.setPath("userData", userData); + app.on("window-all-closed", () => {}); + let window; + const cleanup = (code) => { + window?.destroy(); + fs.rmSync(userData, { recursive: true, force: true }); + app.exit(code); + }; + + void app.whenReady().then(async () => { + const root = path.resolve(__dirname, ".."); + const bundle = esbuild.buildSync({ + stdin: { + contents: [ + 'export { getCompletions } from "./components/terminal/autocomplete/completionEngine";', + 'export { resetPinyinCacheForTests, getPinyinCacheStatsForTests } from "./lib/searchMatcher";', + ].join("\n"), + resolveDir: root, + loader: "ts", + }, + bundle: true, + format: "cjs", + platform: "browser", + write: false, + define: { "import.meta.env.DEV": "false", "import.meta.env.PROD": "true", "import.meta": "{}" }, + }).outputFiles[0].text; + window = new BrowserWindow({ + show: false, + webPreferences: { nodeIntegration: true, contextIsolation: false, sandbox: false, backgroundThrottling: false }, + }); + await window.loadURL("data:text/html,"); + const result = await window.webContents.executeJavaScript(`(async () => { + const loaded = { exports: {} }; + ((module, exports) => { ${bundle} })(loaded, loaded.exports); + const { getCompletions, resetPinyinCacheForTests, getPinyinCacheStatsForTests } = loaded.exports; + const snippets = Array.from({ length: 5000 }, (_, index) => ({ + id: String(index), label: 'deploy-service-' + index, + command: 'kubectl --namespace production rollout restart deployment service-' + index, + })); + snippets.push({ id: 'mail', label: '邮箱', command: 'user@example.com' }); + await getCompletions('git pull zz', { snippets: [] }); + resetPinyinCacheForTests(); + const rows = []; + for (let round = 0; round < 3; round++) { + for (const input of ['git pull zz', 'git pull zzq', 'git pull zzqx']) { + const started = performance.now(); + let resolveInput; + const inputTurn = new Promise(resolve => { resolveInput = resolve; }); + setTimeout(() => resolveInput(performance.now() - started), 0); + const suggestions = await getCompletions(input, { snippets, skipPathCompletion: true }); + const completionMs = performance.now() - started; + rows.push({ round, input, completionMs, inputDelayMs: await inputTurn, matches: suggestions.length }); + } + } + const pinyinKeys = getPinyinCacheStatsForTests().keys; + const chinese = await getCompletions('git pull yx', { snippets, skipPathCompletion: true }); + return { rows, pinyinKeys, chineseSnippetId: chinese.find(item => item.source === 'snippet')?.snippet?.id }; + })()`); + assert.ok(result.rows.every(row => row.matches === 0)); + assert.deepEqual(result.pinyinKeys, ["邮箱"], "ASCII command words must bypass transliteration"); + assert.equal(result.chineseSnippetId, "mail", "Chinese initials must still reach the snippet"); + // Report timings without a machine-dependent threshold. The cache-work + // assertion above is the deterministic regression gate on this real path. + console.log("TERMINAL_SNIPPET_COMPLETION_PERFORMANCE_OK", JSON.stringify(result)); + cleanup(0); + }).catch(error => { console.error(error); cleanup(1); }); +}