Compare commits

...
7 Commits
Author SHA1 Message Date
陈大猫 73ee6c0f31 fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps (#4655)
* fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps

Fixes #4653. macOS Pinyin halfwidth punctuation reports a fullwidth keydown before committing halfwidth insertText, the inverse of #2833. Defer non-ASCII punctuation and keep unchanged CJK glyphs on the literal/composition path rather than Kitty physical-key encoding.

Credit AiHyo for diagnosing the event sequence and root cause.

* fix(terminal): avoid control-character regex in IME punctuation deferral
2026-12-02 20:04:41 +08:00
陈大猫 905aed61ad fix(terminal): keep workspace sessions removed across queued updates (#4652) 2026-12-02 19:36:39 +08:00
GOUKI9999 13d05b0ea4 fix(cloud-sync): keep local backup AI/settings counts inline when width allows (#4645) 2026-12-02 17:16:44 +08:00
陈大猫 1045737c68 feat(terminal): add autocomplete setting to show or hide code snippets (#4641) 2026-12-02 17:16:00 +08:00
陈大猫 909d3e5ed2 fix(startup): open local terminal landing after lazy App mount (#4640) (#4646)
#4476 split App into a lazy chunk, so AppLockGate could send rendererReady
while Suspense still showed a fallback. The cold-start settled event then
fired before AppSideEffects subscribed, and the "open local terminal on
launch" landing never ran when tab restore was off.

Defer rendererReady until the lazy route reports it has mounted, and latch
the settled event in preload so late subscribers still receive it.
2026-12-02 17:00:35 +08:00
陈大猫 cb7e49c409 fix(terminal): prevent autocomplete crash from double-sending keys (#4539) (#4632) 2026-12-02 14:49:08 +08:00
Netcatty-Bot 02be8a2e0a Update Nix release metadata for v1.2.0 (#4631) 2026-12-02 13:38:39 +08:00
40 changed files with 1106 additions and 107 deletions

No files matched your search

+8 -2
View File
@@ -25,6 +25,7 @@ import { SessionPublisher } from './application/app/publishers/SessionPublisher'
import { SettingsPublisher } from './application/app/publishers/SettingsPublisher';
import { VaultPublisher } from './application/app/publishers/VaultPublisher';
import { AppLockRuntimePublisher } from './application/app/publishers/AppLockRuntimePublisher';
import { useReportRendererReady } from './components/AppLockGate';
// Initialize fonts eagerly at app startup
initializeFonts();
@@ -61,8 +62,10 @@ function App() {
/**
* `AppLockGate` (index.tsx) owns `useSettingsState` / `useAppLockState` so the
* lock overlay can render before app children mount, and it owns the
* splash-removal + rendererReady signal (deep links must wait for unlock).
* lock overlay can render before app children mount, and owns splash removal
* plus the lock-gated `rendererReady` policy. This lazy route reports ready
* after `AppSideEffects` and bridge listeners have mounted so cold-start
* intents and deep links never race a suspended chunk.
* App forwards the gate's settings instance into SettingsPublisher so the
* runtime slot/context still publish a single settings runtime.
*/
@@ -78,6 +81,9 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
}, []);
useExternalMcpGrantPersister();
// Signal rendererReady after child effects (AppSideEffects) and bridge setup
// have registered in this commit's effect flush.
useReportRendererReady();
return (
<SettingsPublisher settings={settings}>
+3
View File
@@ -1001,6 +1001,9 @@ Highlight the focused split pane:
'Choose whether autocomplete history suggestions come from the current host only, or from commands recorded on all hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Current host',
'settings.terminal.autocomplete.historyScope.global': 'All hosts',
'settings.terminal.autocomplete.showSnippets': 'Show code snippets',
'settings.terminal.autocomplete.showSnippets.desc':
'Include matching code snippets in the autocomplete list. Turn this off if snippets crowd out command and history suggestions.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Password prompt assist',
+3
View File
@@ -1001,6 +1001,9 @@ Resalta el panel dividido enfocado:
'Elige si las sugerencias de autocompletado del historial provienen solo del host actual o de los comandos registrados en todos los hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Host actual',
'settings.terminal.autocomplete.historyScope.global': 'Todos los hosts',
'settings.terminal.autocomplete.showSnippets': 'Mostrar fragmentos de código',
'settings.terminal.autocomplete.showSnippets.desc':
'Incluye fragmentos de código coincidentes en la lista de autocompletado. Desactiva esta opción si los fragmentos desplazan las sugerencias de comandos e historial.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Asistencia para solicitud de contraseña',
+3
View File
@@ -986,6 +986,9 @@ export const ruCoreMessages: Messages = {
'Выберите, брать ли подсказки истории автодополнения только с текущего хоста или со всех хостов.',
'settings.terminal.autocomplete.historyScope.host': 'Текущий хост',
'settings.terminal.autocomplete.historyScope.global': 'Все хосты',
'settings.terminal.autocomplete.showSnippets': 'Показывать сниппеты',
'settings.terminal.autocomplete.showSnippets.desc':
'Включать подходящие сниппеты в список автодополнения. Отключите, если сниппеты вытесняют подсказки команд и истории.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Подсказки пароля',
@@ -304,3 +304,20 @@ test("localized settings include SFTP tree folder double-click labels across all
}
}
});
test("localized settings include autocomplete show code snippets labels across all locales", () => {
const keys = [
"settings.terminal.autocomplete.showSnippets",
"settings.terminal.autocomplete.showSnippets.desc",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing autocomplete showSnippets labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
@@ -574,6 +574,9 @@ export const zhCNTerminalMessages: Messages = {
'选择自动补全的历史建议来自当前主机,还是所有主机上执行过的命令。',
'settings.terminal.autocomplete.historyScope.host': '当前主机',
'settings.terminal.autocomplete.historyScope.global': '全部主机',
'settings.terminal.autocomplete.showSnippets': '显示代码片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在补全列表中显示匹配的代码片段。若片段较多、排在列表前面,可关闭此项。',
'settings.terminal.section.passwordPromptAssist': '密码提示辅助',
'settings.terminal.passwordPromptAssist.mode': '辅助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
@@ -574,6 +574,9 @@ export const zhTWTerminalMessages: Messages = {
'選擇自動補全的歷史建議來自目前主機,還是所有主機上執行過的指令。',
'settings.terminal.autocomplete.historyScope.host': '目前主機',
'settings.terminal.autocomplete.historyScope.global': '全部主機',
'settings.terminal.autocomplete.showSnippets': '顯示程式碼片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在補全列表中顯示符合的程式碼片段。若片段較多、排在列表前面,可關閉此項。',
'settings.terminal.section.passwordPromptAssist': '密碼提示輔助',
'settings.terminal.passwordPromptAssist.mode': '輔助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
+3 -2
View File
@@ -766,13 +766,14 @@ export const useSessionState = ({
const preferredTabId = activeTabStore.getPreviousActiveTabId();
const tabOrderSnapshot = tabOrderRef.current;
const sessionsSnapshot = sessionsRef.current;
// Queue removal outside the workspace updater so React retains it when
// lower-priority session updates are rebased after this close.
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
setTabOrder(prevTabOrder => prevTabOrder.filter(id => id !== workspaceId));
setWorkspaces(prevWorkspaces => {
const remainingWorkspaces = prevWorkspaces.filter(w => w.id !== workspaceId);
const remainingSessions = sessionsSnapshot.filter(s => s.workspaceId !== workspaceId);
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
currentActiveTabId: activeTabStore.getActiveTabId(),
closedWorkspaceId: workspaceId,
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';
import { JSDOM } from 'jsdom';
import { activeTabStore } from './activeTabStore';
import { useSessionState } from './useSessionState';
import type { Host } from '../../domain/models';
const settle = (ms = 20) => new Promise<void>(resolve => setTimeout(resolve, ms));
test('workspace Close does not restore removed panes when a queued session update is rebased', async () => {
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of Object.entries({
window: dom.window, document: dom.window.document,
localStorage: dom.window.localStorage, CustomEvent: dom.window.CustomEvent,
Event: dom.window.Event,
})) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
const root = createRoot(document.getElementById('root')!);
let state!: ReturnType<typeof useSessionState>;
let closingId = '';
const mounts = new Map<string, number>();
function Pane({ id }: { id: string }) {
useEffect(() => { mounts.set(id, (mounts.get(id) ?? 0) + 1); }, [id]);
return null;
}
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return <>
<button onClick={() => state.closeWorkspace(closingId)}>Close</button>
{state.sessions.map(s => <Pane key={s.id} id={s.id} />)}
</>;
}
async function connect(name: string, count: number) {
const hosts = Array.from({ length: count }, (_, i) => ({
id: `${name}-${i}`, label: `${name}-${i}`, hostname: 'host.test',
username: 'alice', protocol: 'ssh',
} as Host));
flushSync(() => state.createWorkspaceWithHosts(name, hosts));
await settle();
const workspace = state.workspaces.at(-1)!;
flushSync(() => {
for (const s of state.sessions.filter(s => s.workspaceId === workspace.id)) {
state.updateSessionStatus(s.id, 'connected');
}
});
await settle();
return workspace;
}
async function close(id: string, queueCwd = false) {
closingId = id;
// A cwd observation without pendingInitialCwd queues a no-op update at
// default priority. The discrete Close runs first; React later rebases
// that queue. Wrapping this preparation in act would hide the schedule.
const session = state.sessions.find(s => s.workspaceId === id)!;
if (queueCwd) state.updateSessionRestoreCwd(session.id, '/home/alice');
document.querySelector('button')!.click();
await settle(100);
assert(!state.workspaces.some(w => w.id === id));
assert(!state.sessions.some(s => s.workspaceId === id), 'closed workspace sessions must stay removed after queued updates settle');
}
try {
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
flushSync(() => root.render(<Probe />));
const left = await connect('left', 2);
const target = await connect('target', 6);
const targetIds = state.sessions.filter(s => s.workspaceId === target.id).map(s => s.id);
// Keep the target mounted while other connected workspaces are used.
for (let i = 0; i < 3; i++) await close((await connect(`warm-${i}`, 2)).id);
const right = await connect('right', 2);
await close(right.id);
await close(left.id);
assert.deepEqual(state.sessions.map(s => s.id), targetIds);
assert(state.sessions.every(s => s.status === 'connected'));
assert.equal(activeTabStore.getActiveTabId(), target.id);
await close(target.id, true);
assert.equal(state.sessions.length, 0);
assert.equal(state.workspaces.length, 0);
assert.equal(activeTabStore.getActiveTabId(), 'vault');
assert([...mounts.values()].every(count => count === 1), 'Close must not remount any closed pane');
} finally {
flushSync(() => root.unmount());
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
await settle();
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+1 -1
View File
@@ -309,7 +309,7 @@ const SYNCABLE_TERMINAL_KEYS = [
'inlineImagesEnabled', 'inlineImageKittyEnabled', 'inlineImageSixelEnabled', 'inlineImageIipEnabled',
'autocompleteEnabled', 'autocompleteGhostText', 'autocompletePopupMenu',
'autocompleteDebounceMs', 'autocompleteMinChars', 'autocompleteMaxSuggestions',
'autocompleteHistoryScope',
'autocompleteHistoryScope', 'autocompleteShowSnippets',
] as const;
export const SYNCABLE_SETTING_STORAGE_KEYS = [
+283 -1
View File
@@ -4,7 +4,7 @@ import React from "react";
import { useAppLockBridge } from "../application/state/useAppLockBridge.ts";
import { useAppLockState } from "../application/state/useAppLockState.ts";
import { createAppLockGate } from "./AppLockGate.tsx";
import { ReportRendererReady, createAppLockGate } from "./AppLockGate.tsx";
import { APP_LOCK_AUTO_PROMPT_DELAY_MS } from "./AppLockOverlay.tsx";
import { createAppLockBridgeHarness } from "./test-support/createAppLockBridgeHarness.ts";
import {
@@ -1024,3 +1024,285 @@ test("reopen resync does not unlock a gate when runtime is still locked", async
dom.cleanup();
}
});
test("rendererReady waits for lazy route mount and runs after child effects", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const events: string[] = [];
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const baseBridge = bridgeHarness.bridge;
const wrappedBridge: NetcattyBridge = {
...baseBridge,
rendererReady: () => {
events.push("rendererReady");
baseBridge.rendererReady?.();
},
};
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const ChildSubscriber: React.FC = () => {
React.useEffect(() => {
events.push("childSubscribed");
}, []);
return React.createElement("div", { id: "lazy-route-content" }, "Mounted");
};
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = wrappedBridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Gate allowed children, but LazyRoute is still suspended -> must NOT signal ready.
assert.equal(dom.document.getElementById("lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
assert.deepEqual(events, []);
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement(ChildSubscriber),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("lazy-route-content")?.textContent, "Mounted");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
assert.deepEqual(events, ["childSubscribed", "rendererReady"]);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("startup-locked gate withholds rendererReady until unlock and lazy route mount", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: true,
reason: "startup",
version: 1,
lastLockedAt: 1_000,
lastUnlockedAt: null,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: true,
timeoutMinutes: 15,
passwordVerifier: {
version: 1,
algorithm: "PBKDF2-SHA256",
iterations: 210000,
salt: "AAAAAAAAAAAAAAAAAAAAAA==",
hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
},
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "locked-lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Locked first paint: children withheld, must not notify.
assert.equal(dom.document.getElementById("locked-lazy-fallback"), null);
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Unlock: children allowed, but LazyRoute still suspended -> still must not notify.
await runWithAct(async () => {
bridgeHarness.setRuntimeState({
locked: false,
reason: null,
lastUnlockedAt: 2_000,
lastActivityAt: 2_000,
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Resolve lazy chunk -> mounts real page and reports ready once.
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "locked-lazy-mounted" }, "Ready"),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-mounted")?.textContent, "Ready");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("notifyRendererReady=false suppresses ReportRendererReady signals", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: false,
children: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "opt-out-content" }, "OptOut"),
React.createElement(ReportRendererReady),
),
}),
);
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("opt-out-content")?.textContent, "OptOut");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
+39
View File
@@ -5,6 +5,7 @@ import {
shouldDeferExternalActionWhileAppLocked,
shouldNotifyAppLockGateRendererReady,
shouldRenderAppLockGateChildren,
shouldReportAppLockGateRendererReady,
} from "./AppLockGate.tsx";
test("shouldRenderAppLockGateChildren withholds startup-locked route children until unlock", () => {
@@ -140,6 +141,44 @@ test("shouldNotifyAppLockGateRendererReady waits until locked children can mount
);
});
test("shouldReportAppLockGateRendererReady requires gate permission and mounted content", () => {
// Gate allowing children (e.g. Suspense fallback) is not sufficient.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: false,
}),
false,
);
// Locked first paint must not notify even if contentMounted were true.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: false,
contentMounted: true,
}),
false,
);
// Routes that opt out (terminal-popup / editor-window) must not notify.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: false,
renderChildren: true,
contentMounted: true,
}),
false,
);
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: true,
}),
true,
);
});
test("shouldDeferExternalActionWhileAppLocked queues actions only while locked", () => {
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: true }), true);
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: false }), false);
+74 -22
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { I18nProvider } from '../application/i18n/I18nProvider';
import { useAppLockBridge } from '../application/state/useAppLockBridge';
@@ -67,6 +67,33 @@ export function shouldNotifyAppLockGateRendererReady(input: {
return input.notifyRendererReady && input.renderChildren;
}
/**
* Lazy route chunks suspend after AppLockGate allows children to render.
* Only emit rendererReady once the gate permits it and the lazy route's real
* content has mounted (so AppSideEffects / IPC listeners are registered).
*/
export function shouldReportAppLockGateRendererReady(input: {
notifyRendererReady: boolean;
renderChildren: boolean;
contentMounted: boolean;
}): boolean {
return shouldNotifyAppLockGateRendererReady(input) && input.contentMounted;
}
const RendererReadyContext = createContext<(() => void) | null>(null);
export function useReportRendererReady(): void {
const reportRendererReady = useContext(RendererReadyContext);
useEffect(() => {
reportRendererReady?.();
}, [reportRendererReady]);
}
export const ReportRendererReady: React.FC = () => {
useReportRendererReady();
return null;
};
/** Queue external actions (e.g. ssh:// deep links) while the app lock is held. */
export function shouldDeferExternalActionWhileAppLocked(input: {
locked: boolean;
@@ -88,6 +115,8 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
onAppLockReopen,
} = deps.useAppLockBridge();
const hasRenderedChildrenRef = useRef(false);
const contentMountedRef = useRef(false);
const hasNotifiedRendererReadyRef = useRef(false);
const [reopenSignal, setReopenSignal] = useState(0);
const renderChildren = shouldRenderAppLockGateChildren({
initialized: appLock.initialized,
@@ -99,10 +128,31 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
if (renderChildren) {
hasRenderedChildrenRef.current = true;
}
const shouldNotifyRendererReady = shouldNotifyAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
});
const emitRendererReadyIfAllowed = useCallback(() => {
if (hasNotifiedRendererReadyRef.current) return;
if (
!shouldReportAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
contentMounted: contentMountedRef.current,
})
) {
return;
}
hasNotifiedRendererReadyRef.current = true;
try {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
} catch {
// ignore
}
}, [notifyAppLockRendererReady, notifyRendererReady, renderChildren]);
const reportRendererReady = useCallback(() => {
contentMountedRef.current = true;
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
try {
@@ -111,14 +161,14 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
splash.classList.add('fade-out');
setTimeout(() => splash.remove(), 200);
}
if (shouldNotifyRendererReady) {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
}
} catch {
// ignore
}
}, [notifyAppLockRendererReady, shouldNotifyRendererReady]);
}, []);
useEffect(() => {
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
const unsubscribe = onAppLockReopen(() => {
@@ -149,18 +199,20 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
<I18nProvider locale={settings.uiLanguage}>
<ToastProvider>
<TooltipProvider delayDuration={300}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
<RendererReadyContext.Provider value={reportRendererReady}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
</RendererReadyContext.Provider>
<AppLockOverlay
locked={appLock.locked}
reason={appLock.lockReason}
+10
View File
@@ -31,3 +31,13 @@ test("terminal popups wait for app-lock initialization before starting a termina
/allowTerminalStart=\{appLock\.initialized\s*&&\s*!appLock\.locked\}/,
);
});
test("lazy routes gated by AppLockGate report rendererReady after mounting", () => {
const appSource = readComponentSource("../App.tsx");
const settingsPage = readComponentSource("./SettingsPage.tsx");
const trayPanel = readComponentSource("./TrayPanel.tsx");
assert.match(appSource, /\buseReportRendererReady\s*\(\)/);
assert.match(settingsPage, /<ReportRendererReady\s*\/>/);
assert.match(trayPanel, /<ReportRendererReady\s*\/>/);
});
+3 -6
View File
@@ -14,7 +14,7 @@ import { useWindowControls } from "../application/state/useWindowControls";
import { useUpdateCheck } from "../application/state/useUpdateCheck";
import { I18nProvider, useI18n } from "../application/i18n/I18nProvider";
import { sanitizePortForwardingRulesForSync } from "../application/syncPayload";
import type { AppLockGateRenderContext } from "./AppLockGate";
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
import { toast } from "./ui/toast";
import { SettingsTabContent } from "./settings/settings-ui";
import { SettingsFocusProvider, useSettingsFocus } from "./settings/SettingsFocusContext";
@@ -341,7 +341,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const pluginThemeTokens = useMemo(() => selectPluginThemeTokens(committedAppThemeStyle as Record<string, unknown>), [committedAppThemeStyle]);
const { t } = useI18n();
const { request, clearFocus, openSearch } = useSettingsFocus();
const { notifyRendererReady, closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
const { closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
const { updateState, checkNow, installUpdate, openReleasePage, startDownload, isUpdateDemoMode } = useUpdateCheck({
autoUpdateEnabled: settings.autoUpdateEnabled,
// Install blocked by unsaved editors in the main window — surface a toast
@@ -359,10 +359,6 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
}, [settings.hotkeyScheme, settings.keyBindings]);
const nativeCommandWClosesSettings = isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true);
useEffect(() => {
notifyRendererReady();
}, [notifyRendererReady]);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const isFind = (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f";
@@ -757,6 +753,7 @@ export default function SettingsPage({
<I18nProvider locale={settings.uiLanguage}>
<SettingsFocusProvider>
<SettingsPageContent settings={settings} appLock={appLock} />
<ReportRendererReady />
</SettingsFocusProvider>
</I18nProvider>
);
+2 -1
View File
@@ -16,7 +16,7 @@ import { getEffectiveKnownHosts } from "../infrastructure/syncHelpers";
import { PortForwardHostKeyTrayPrompt } from "./port-forwarding";
import { X, Maximize2, ChevronRight, ChevronDown, Power } from "lucide-react";
import { AppLogo } from "./AppLogo";
import type { AppLockGateRenderContext } from "./AppLockGate";
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
const StatusDot: React.FC<{ status: "success" | "warning" | "error" | "neutral"; spinning?: boolean }> = ({
status,
@@ -505,6 +505,7 @@ const TrayPanel: React.FC<{ settings: SettingsState }> = ({ settings }) => {
return (
<I18nProvider locale={settings.uiLanguage}>
<TrayPanelContent />
<ReportRendererReady />
</I18nProvider>
);
};
@@ -337,22 +337,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{t('cloudSync.localBackups.counts', {
hosts: String(backup.preview.hostCount),
keys: String(backup.preview.keyCount),
snippets: String(backup.preview.snippetCount),
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<div className="text-xs text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
<div className="text-xs text-muted-foreground mt-1 flex flex-wrap items-center gap-x-1.5">
<span>
{t('cloudSync.localBackups.counts', {
hosts: String(backup.preview.hostCount),
keys: String(backup.preview.keyCount),
snippets: String(backup.preview.snippetCount),
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
) : null}
</span>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
})}
</span>
</>
) : null}
</div>
</div>
{restoreAllowed && (
<Button
@@ -443,22 +448,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<div className="text-muted-foreground">
{t('cloudSync.localBackups.counts', {
hosts: String(pendingRestoreBackup.preview.hostCount),
keys: String(pendingRestoreBackup.preview.keyCount),
snippets: String(pendingRestoreBackup.preview.snippetCount),
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<div className="text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
<div className="text-muted-foreground flex flex-wrap items-center gap-x-1.5">
<span>
{t('cloudSync.localBackups.counts', {
hosts: String(pendingRestoreBackup.preview.hostCount),
keys: String(pendingRestoreBackup.preview.keyCount),
snippets: String(pendingRestoreBackup.preview.snippetCount),
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
) : null}
</span>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
})}
</span>
</>
) : null}
</div>
</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
@@ -1603,6 +1603,17 @@ function SettingsTerminalTab(props: {
disabled={!terminalSettings.autocompleteEnabled}
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-show-snippets"
label={t("settings.terminal.autocomplete.showSnippets")}
description={t("settings.terminal.autocomplete.showSnippets.desc")}
>
<Toggle
checked={terminalSettings.autocompleteShowSnippets !== false}
onChange={(v) => updateTerminalSetting("autocompleteShowSnippets", v)}
disabled={!terminalSettings.autocompleteEnabled}
/>
</SettingRow>
</div>
<SectionHeader title={t("settings.terminal.section.passwordPromptAssist")} />
+2 -1
View File
@@ -129,13 +129,14 @@ export function TerminalAutocomplete({
hostGroup,
cwdSource: options.cwdSource,
snippets: options.snippets,
showSnippets: options.showSnippets ?? settings?.showSnippets,
maximum: options.maxResults ?? 15,
historyScope: options.historyScope ?? settings?.historyScope,
signal: options.signal,
onLatePathSuggestions: options.onLatePathSuggestions,
locale: resolvedLocale,
});
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, settings?.showSnippets, status, workspaceId]);
const autocomplete = useTerminalAutocomplete({
termRef,
containerRef,
@@ -210,6 +210,8 @@ export async function getCompletions(
cwdSource?: AutocompleteCwdSource;
/** Custom snippets to surface at the command position */
snippets?: Snippet[];
/** Whether to include matching snippets in completions (default: true). */
showSnippets?: boolean;
/** Which history pool to query (default: current host only). */
historyScope?: AutocompleteHistoryScope;
/**
@@ -376,7 +378,7 @@ export async function getCompletions(
// Push without the early seen-text skip: snippets score above history, so if
// a snippet's label collides with an existing history entry's text, the
// score-sort + final dedup below keeps the snippet (the higher-scored one).
if (options.snippets && options.snippets.length > 0) {
if (options.showSnippets !== false && options.snippets && options.snippets.length > 0) {
const atCommandPosition = ctx.wordIndex === 0;
const argumentNeedle = normalizeHistoryPathPrefix(ctx.currentWord);
const snippetArgumentMatch = !atCommandPosition
@@ -10,6 +10,7 @@ type TerminalAutocompleteSettingFields = {
autocompleteMinChars?: number;
autocompleteMaxSuggestions?: number;
autocompleteHistoryScope?: AutocompleteHistoryScope;
autocompleteShowSnippets?: boolean;
shiftEnterNewlineEnabled?: boolean;
};
@@ -36,6 +37,7 @@ export function resolveTerminalAutocompleteSettings(input: {
minChars: terminalSettings?.autocompleteMinChars ?? 1,
maxSuggestions: terminalSettings?.autocompleteMaxSuggestions ?? 50,
historyScope: terminalSettings?.autocompleteHistoryScope ?? "host",
showSnippets: terminalSettings?.autocompleteShowSnippets !== false,
shiftEnterNewlineEnabled: terminalSettings?.shiftEnterNewlineEnabled ?? true,
};
}
@@ -58,6 +60,7 @@ export function resolveTerminalAutocompleteSettings(input: {
minChars: terminalSettings.autocompleteMinChars ?? 1,
maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 50,
historyScope: terminalSettings.autocompleteHistoryScope ?? "host",
showSnippets: terminalSettings.autocompleteShowSnippets !== false,
shiftEnterNewlineEnabled: terminalSettings.shiftEnterNewlineEnabled ?? true,
};
}
@@ -159,3 +159,16 @@ test('terminal completion adapter preserves built-in snippet metadata on duplica
assert.equal(duplicate?.snippet, snippet);
assert.equal(results.filter((item) => item.text === 'deploy').length, 1);
});
test('terminal completion adapter skips built-in snippets when showSnippets is false', async () => {
const snippet = { id: 'deploy', label: 'deploy', command: 'kubectl apply -f .' };
const results = await provideTerminalCompletions(null, {
input: 'dep',
session: { sessionId: 'session-1', protocol: 'ssh', status: 'connected' },
hostOs: 'linux',
snippets: [snippet],
showSnippets: false,
maximum: 8,
});
assert.equal(results.some((item) => item.source === 'snippet'), false);
});
@@ -17,6 +17,8 @@ export interface TerminalCompletionProviderRequest {
hostOs: 'linux' | 'windows' | 'macos';
cwdSource?: AutocompleteCwdSource;
snippets?: Snippet[];
/** Whether to include matching snippets in built-in completions (default: true). */
showSnippets?: boolean;
maximum: number;
/** Which history pool built-in suggestions draw from. */
historyScope?: AutocompleteHistoryScope;
@@ -73,7 +75,8 @@ export async function provideTerminalCompletions(
protocol: request.session.protocol,
cwd: request.session.cwd,
cwdSource: request.cwdSource,
snippets: request.snippets,
snippets: request.showSnippets === false ? undefined : request.snippets,
showSnippets: request.showSnippets,
historyScope: request.historyScope,
onLatePathSuggestions: request.onLatePathSuggestions,
locale: request.locale,
@@ -68,6 +68,8 @@ export interface AutocompleteSettings {
shiftEnterNewlineEnabled: boolean;
/** Which history pool suggestions draw from (current host vs all hosts). */
historyScope: "host" | "global";
/** Whether matching code snippets are included in autocomplete suggestions. */
showSnippets: boolean;
}
export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
@@ -82,6 +84,7 @@ export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
fastTypingThresholdMs: 40,
shiftEnterNewlineEnabled: true,
historyScope: "host",
showSnippets: true,
};
/** Max time to poll for shell echo after a pre-echo debounce cycle (#2813). */
@@ -302,6 +305,7 @@ export function useTerminalAutocomplete(
const settings: AutocompleteSettings = {
...rawSettings,
showGhostText: rawSettings.showPopupMenu ? false : rawSettings.showGhostText,
showSnippets: rawSettings.showSnippets !== false,
livePreview: shouldWriteAutocompleteLivePreview(rawSettings.livePreview, isNetworkDevice),
};
@@ -487,6 +491,16 @@ export function useTerminalAutocomplete(
);
}, []);
// Drop visible snippet suggestions if the user turns showSnippets off mid-session.
useEffect(() => {
if (
!settings.showSnippets
&& stateRef.current.suggestions.some((suggestion) => suggestion.source === "snippet")
) {
clearState();
}
}, [settings.showSnippets, clearState]);
/**
* Reconcile the visible popup with the newly edited input synchronously.
* The full provider refresh remains debounced, but rows from the previous
@@ -1165,7 +1179,8 @@ export function useTerminalAutocomplete(
skipPathCompletion: isNetworkDeviceRef.current,
cwd: cwdResolution.cwd,
cwdSource: cwdResolution.source,
snippets: snippetsRef.current,
snippets: settingsRef.current.showSnippets ? snippetsRef.current : undefined,
showSnippets: settingsRef.current.showSnippets,
promptText: prompt.promptText,
allowExternalProviders,
signal: completionController.signal,
@@ -1188,6 +1203,9 @@ export function useTerminalAutocomplete(
if (completionAbortRef.current === completionController) completionAbortRef.current = null;
}
if (completionController.signal.aborted) return;
if (!settingsRef.current.showSnippets) {
completions = completions.filter((completion) => completion.source !== "snippet");
}
if (!settingsRef.current.allowLineReplacement) {
completions = completions.filter((completion) =>
completion.source !== "snippet" && completion.text.startsWith(input),
@@ -0,0 +1,115 @@
import test from "node:test";
import assert from "node:assert/strict";
import { JSDOM } from "jsdom";
import type { Terminal as XTerm } from "@xterm/xterm";
import { GhostTextAddon } from "./GhostTextAddon.ts";
import { getXTermCellDimensions, invalidateCellDimensionCache } from "./xtermUtils.ts";
import {
keepImeCommittedTextThroughModifierKeyDowns,
keepLateImeTextInsert,
} from "../runtime/imeModifierKeyDownSeenGuard.ts";
test("autocomplete on a disposed renderer does not double-send a key (#4539)", async () => {
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost/",
pretendToBeVisual: true,
});
const win = dom.window;
win.matchMedia = () => ({
matches: false, media: "", onchange: null,
addEventListener() {}, removeEventListener() {},
addListener() {}, removeListener() {}, dispatchEvent: () => false,
});
win.HTMLCanvasElement.prototype.getContext = () => ({
font: "10px monospace", measureText: () => ({ width: 8 }),
}) as unknown as CanvasRenderingContext2D;
const globals = {
window: win, document: win.document, HTMLElement: win.HTMLElement,
HTMLTextAreaElement: win.HTMLTextAreaElement, Node: win.Node,
Element: win.Element, getComputedStyle: win.getComputedStyle.bind(win),
};
const previousGlobals = Object.fromEntries(
Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
);
Object.assign(globalThis, globals);
const errors: unknown[] = [];
win.addEventListener("error", (event) => {
errors.push(event.error);
event.preventDefault();
});
let oldTerm: XTerm | undefined;
let liveTerm: XTerm | undefined;
const ghost = new GhostTextAddon();
try {
const imported = await import("@xterm/xterm");
const Terminal = (imported as { default?: { Terminal: typeof imported.Terminal } }).default?.Terminal
?? imported.Terminal;
const openTerminal = () => {
const parent = win.document.createElement("div");
win.document.body.appendChild(parent);
const term = new Terminal({ cols: 80, rows: 24, cursorBlink: false });
keepImeCommittedTextThroughModifierKeyDowns(term);
keepLateImeTextInsert(term);
term.open(parent);
return term;
};
oldTerm = openTerminal();
ghost.activate(oldTerm);
// Runtime replacement leaves the separately activated autocomplete addon
// holding the old terminal, whose RenderService still exists after dispose.
oldTerm.dispose();
liveTerm = openTerminal();
const sent: string[] = [];
liveTerm.onData((data) => {
// Match createXTermRuntime: write first, then notify autocomplete.
sent.push(data);
ghost.applyKeystroke(data);
});
const textarea = liveTerm.textarea!;
const cancelled: boolean[] = [];
const typeKey = (key: string) => {
const keyCode = key.toUpperCase().charCodeAt(0);
const keydown = new win.KeyboardEvent("keydown", {
key, code: `Key${key.toUpperCase()}`, keyCode,
bubbles: true, cancelable: true,
});
textarea.dispatchEvent(keydown);
cancelled.push(keydown.defaultPrevented);
// JSDOM does not perform native keyboard default actions. Deliver the
// browser's keypress/input sequence only when keydown was not cancelled.
if (!keydown.defaultPrevented) {
textarea.dispatchEvent(new win.KeyboardEvent("keypress", {
key, charCode: key.charCodeAt(0), keyCode: key.charCodeAt(0),
bubbles: true, cancelable: true,
}));
for (const type of ["beforeinput", "input"]) {
textarea.dispatchEvent(new win.InputEvent(type, {
data: key, inputType: "insertText", composed: true, bubbles: true,
}));
}
}
textarea.dispatchEvent(new win.KeyboardEvent("keyup", { key, keyCode, bubbles: true }));
};
typeKey("a");
// The first suggestion arrives asynchronously, as in the reporter's trace.
await Promise.resolve().then(() => ghost.show("apt update -y", "a")).catch((error) => errors.push(error));
typeKey("p");
typeKey("t");
assert.equal(sent.join(""), "apt", "one PTY write per physical key");
assert.deepEqual(cancelled, [true, true, true]);
assert.deepEqual(errors, []);
// With no cached size, the absent renderer also reaches the DOM fallback.
invalidateCellDimensionCache();
assert.deepEqual(getXTermCellDimensions(oldTerm), { width: 8, height: 16 });
} finally {
ghost.dispose();
liveTerm?.dispose();
oldTerm?.dispose();
dom.window.close();
invalidateCellDimensionCache();
for (const [key, descriptor] of Object.entries(previousGlobals)) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+10 -2
View File
@@ -33,9 +33,17 @@ function getTermId(term: XTerm): number {
export function getXTermCellDimensions(term: XTerm): CellDimensions {
// Try xterm core renderer API (fast path)
const coreAccess = term as XTerm & {
_core?: { _renderService?: { dimensions?: { css?: { cell?: CellDimensions } } } };
_core?: { _renderService?: {
hasRenderer?: () => boolean;
dimensions?: { css?: { cell?: CellDimensions } };
} };
};
const coreDims = coreAccess._core?._renderService?.dimensions?.css?.cell;
const renderService = coreAccess._core?._renderService;
// The dimensions getter dereferences its renderer even after disposal.
// Avoid throwing through onData before xterm can prevent the key's default.
const coreDims = renderService?.hasRenderer?.() === false
? undefined
: renderService?.dimensions?.css?.cell;
if (coreDims && coreDims.width > 0 && coreDims.height > 0) {
// Update cache while we have a good value
const id = getTermId(term);
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { getCompletions } from "./autocomplete/completionEngine";
import { DEFAULT_AUTOCOMPLETE_SETTINGS } from "./autocomplete/useTerminalAutocomplete";
import { clearHistory, recordCommand } from "../../application/state/commandHistoryStore";
import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../domain/searchMatcher";
import type { Snippet } from "../../domain/models";
@@ -115,3 +116,83 @@ test("ASCII argument completion retains compact query prefixes", async () => {
const result = await getCompletions("git pull foo_bar", { snippets, skipPathCompletion: true });
assert.equal(result.find((suggestion) => suggestion.source === "snippet")?.snippet?.id, "compact");
});
test("getCompletions excludes snippet suggestions when showSnippets is false or snippets are omitted", async () => {
const chineseSnippet: Snippet = { id: "zh", label: "部署服务", command: "kubectl apply -f ." };
const dockerSnippet: Snippet = { id: "doc", label: "docker-deploy", command: "docker compose up -d" };
const library: Snippet[] = [deploySnippet, chineseSnippet, dockerSnippet];
// Baseline: when enabled, English and pinyin queries both surface snippet matches.
const enabledEn = await getCompletions("dep", { snippets: library, showSnippets: true });
assert.ok(enabledEn.some((suggestion) => suggestion.source === "snippet"));
const enabledPinyin = await getCompletions("bushu", { snippets: library, showSnippets: true });
assert.ok(enabledPinyin.some((suggestion) => suggestion.source === "snippet" && suggestion.snippet?.id === "zh"));
const enabledArg = await getCompletions("git pull dep", { snippets: library, showSnippets: true });
assert.ok(enabledArg.some((suggestion) => suggestion.source === "snippet"));
// Disabled via showSnippets: false — no snippet matches at command or argument positions,
// including English and pinyin queries, even though the snippet library is present.
for (const input of ["dep", "bushu", "git pull dep"]) {
const disabled = await getCompletions(input, {
snippets: library,
showSnippets: false,
skipPathCompletion: true,
});
assert.equal(
disabled.some((suggestion) => suggestion.source === "snippet"),
false,
`expected no snippet suggestions for ${JSON.stringify(input)} when showSnippets is false`,
);
}
// History suggestions still appear when snippets are hidden, while snippets are excluded.
const hostId = "host-snippet-toggle-test";
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const store = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
clear: () => store.clear(),
getItem: (key: string) => (store.has(key) ? store.get(key)! : null),
setItem: (key: string, value: string) => { store.set(key, String(value)); },
removeItem: (key: string) => { store.delete(key); },
},
});
try {
clearHistory(hostId);
recordCommand("docker ps -a", hostId, "linux");
const dockerWithSnippets = await getCompletions("doc", {
hostId,
snippets: library,
showSnippets: true,
skipPathCompletion: true,
});
assert.equal(dockerWithSnippets[0]?.source, "snippet");
assert.ok(
dockerWithSnippets.some((suggestion) => suggestion.source === "history" && suggestion.text === "docker ps -a"),
);
const dockerWithoutSnippets = await getCompletions("doc", {
hostId,
snippets: library,
showSnippets: false,
skipPathCompletion: true,
});
assert.equal(dockerWithoutSnippets.some((suggestion) => suggestion.source === "snippet"), false);
assert.equal(dockerWithoutSnippets[0]?.source, "history");
assert.equal(dockerWithoutSnippets[0]?.text, "docker ps -a");
} finally {
clearHistory(hostId);
if (previousLocalStorage) {
Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
} else {
delete (globalThis as Record<string, unknown>).localStorage;
}
}
// Disabled by omitting snippets (how useTerminalAutocomplete gates the option).
for (const snippets of [undefined, [] as Snippet[]]) {
const omitted = await getCompletions("dep", { snippets, skipPathCompletion: true });
assert.equal(omitted.some((suggestion) => suggestion.source === "snippet"), false);
}
});
@@ -1936,6 +1936,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
// Unchanged ASCII must keep the Kitty press/release path. Composition
// encoding under report-all emits unidentified CSI 0 u (or associated
// text without a physical key), so ordinary punctuation breaks in TUIs.
// Unchanged CJK glyphs use the literal/composition path below so Kitty
// cannot turn the physical key back into ASCII (#4653).
if (
isUnchangedDeferredImeTextInput(deferredKey, text) &&
deferredKittyEvent &&
@@ -2050,8 +2052,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const armImeTextInputDeferral = (event: KeyboardEvent) => {
clearImeTextInputDeferral();
clearBroadcastLegacyDataPending();
// Wait for insertText (full-width) before keyup; keyup/blur flushes ASCII
// when the IME did not remap the key (English punctuation mode).
// Wait for insertText before keyup; keyup/blur flushes the original glyph
// when the IME did not remap the key.
imeTextInputDeferredKey = event.key;
// Keep the physical key even when the source is not in Kitty mode so
// broadcast targets can still receive paired key events.
@@ -2755,10 +2757,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
return false;
}
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
// full-width "," arrives on insertText. Returning false (without
// preventDefault) stops xterm/Kitty from sending the half-width key so the
// input listener can commit the real glyph (#2833).
// Sogou/macOS reports ASCII "," before insertText commits "," (#2833);
// macOS Pinyin halfwidth mode reports the inverse (#4653). Returning false
// (without preventDefault) stops xterm/Kitty from sending the keydown glyph
// so the input listener can commit the real glyph.
if (shouldDeferKeyDownForImeTextInput(e)) {
armImeTextInputDeferral(e);
return false;
@@ -43,27 +43,32 @@ test("shouldDeferKeyDownForImeTextInput defers bare ASCII punctuation keydowns",
);
});
test("shouldDeferKeyDownForImeTextInput defers bare CJK punctuation keydowns", () => {
for (const key of [",", "。", ";", "?", "、", ":", "!", "「", "」"]) {
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), true, key);
}
});
test("shouldDeferKeyDownForImeTextInput leaves non-punctuation keys alone", () => {
for (const key of ["a", "Z", "0", " ", "Enter", "ArrowLeft", "中", "A", "1", " ", ",,"]) {
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), false, key);
}
});
test("shouldDeferKeyDownForImeTextInput leaves composition and modified keys alone", () => {
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", keyCode: 229 }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", isComposing: true }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", ctrlKey: true }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: "a", keyCode: 65 }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keypress", key: "," }),
false,
);
for (const key of [",", ","]) {
for (const event of [
{ type: "keydown", key, keyCode: 229 },
{ type: "keydown", key, isComposing: true },
{ type: "keydown", key, ctrlKey: true },
{ type: "keydown", key, altKey: true },
{ type: "keydown", key, metaKey: true },
{ type: "keypress", key },
{ type: "keyup", key },
]) {
assert.equal(shouldDeferKeyDownForImeTextInput(event), false, JSON.stringify(event));
}
}
});
test("shouldBlockKeyPressForImeTextInput only while a deferral is armed", () => {
@@ -391,9 +396,22 @@ test("shouldCommitDeferredImeTextInput accepts insertText payloads while deferre
);
});
test("isUnchangedDeferredImeTextInput detects English punctuation flush", () => {
test("macOS Pinyin halfwidth insertText can commit after a fullwidth keydown (#4653)", () => {
let deferredKey: string | null = null;
const keydown = { type: "keydown", key: ",", code: "Comma", keyCode: 188 };
if (shouldDeferKeyDownForImeTextInput(keydown)) deferredKey = keydown.key;
assert.equal(deferredKey, ",");
assert.equal(
shouldCommitDeferredImeTextInput(deferredKey, { inputType: "insertText", data: "," }),
true,
);
});
test("isUnchangedDeferredImeTextInput detects only ASCII punctuation flush", () => {
assert.equal(isUnchangedDeferredImeTextInput(",", ","), true);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(null, ","), false);
});
@@ -4,9 +4,11 @@
* an `input`/`insertText` event. xterm.js sends the keydown character and then
* drops the input event because `_keyDownSeen` is set — so the PTY receives
* "," instead of ",".
* macOS Pinyin halfwidth mode does the inverse: keydown reports "," but
* insertText commits "," (#4653).
*
* Defer those keydowns to the following insertText. If no remap arrives before
* keyup/blur, the original ASCII key is flushed. Composition (keyCode 229 /
* keyup/blur, the original key is flushed. Composition (keyCode 229 /
* isComposing) stays on xterm's CompositionHelper path.
*
* The deferral must never outlive the keystroke it was armed for: Windows IMEs
@@ -32,6 +34,9 @@ export type ImeTextInputEvent = Pick<InputEvent, "data" | "inputType">;
/** Printable ASCII punctuation IMEs commonly remap to full-width forms. */
const ASCII_PUNCTUATION_RE = /^[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]$/;
/** Single Unicode punctuation glyphs, including CJK and full-width forms. */
const UNICODE_PUNCTUATION_RE = /^\p{P}$/u;
export function isAsciiPunctuationKey(key: string): boolean {
return ASCII_PUNCTUATION_RE.test(key);
}
@@ -42,7 +47,8 @@ export function shouldDeferKeyDownForImeTextInput(
if (event.type !== undefined && event.type !== "keydown") return false;
if (event.isComposing === true || event.keyCode === 229) return false;
if (event.altKey || event.ctrlKey || event.metaKey) return false;
return isAsciiPunctuationKey(event.key);
return isAsciiPunctuationKey(event.key) ||
(event.key.charCodeAt(0) > 0x7f && UNICODE_PUNCTUATION_RE.test(event.key));
}
/** Key releases that carry no keystroke of their own. */
@@ -186,5 +192,5 @@ export function isUnchangedDeferredImeTextInput(
deferredKey: string | null | undefined,
text: string,
): boolean {
return deferredKey != null && text === deferredKey;
return deferredKey != null && isAsciiPunctuationKey(deferredKey) && text === deferredKey;
}
@@ -30,6 +30,7 @@ function createContext(input: string) {
fastTypingThresholdMs: 40,
shiftEnterNewlineEnabled: true,
historyScope: "host",
showSnippets: true,
};
const context = {
settingsRef: ref(settings),
@@ -28,6 +28,7 @@ test("keeps autocomplete enabled for shell-like terminal protocols", () => {
minChars: 2,
maxSuggestions: 6,
historyScope: "global",
showSnippets: true,
shiftEnterNewlineEnabled: false,
},
);
@@ -57,6 +58,7 @@ test("keeps network-device autocomplete popup but disables live preview (#1193)"
minChars: 1,
maxSuggestions: 8,
historyScope: "host",
showSnippets: true,
shiftEnterNewlineEnabled: true,
},
);
@@ -109,6 +111,7 @@ test("keeps serial autocomplete available but disables input-line preview and re
minChars: 1,
maxSuggestions: 8,
historyScope: "host",
showSnippets: true,
livePreview: false,
allowLineReplacement: false,
shiftEnterNewlineEnabled: true,
@@ -154,3 +157,33 @@ test('unknown systems do not rewrite the command line while retaining suggestion
assert.equal(settings?.allowLineReplacement, false);
}
});
test("defaults showSnippets to true and preserves explicit false across protocols", () => {
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "ssh",
terminalSettings: { autocompleteEnabled: true },
})?.showSnippets,
true,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "ssh",
terminalSettings: { autocompleteShowSnippets: false },
})?.showSnippets,
false,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "serial",
terminalSettings: { autocompleteShowSnippets: false },
})?.showSnippets,
false,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "serial",
})?.showSnippets,
true,
);
});
@@ -99,3 +99,17 @@ test("clearing command history restores the live-preview baseline (#3632)", () =
);
});
test("useTerminalAutocomplete excludes snippets when showSnippets is false", () => {
const source = readFileSync(
fileURLToPath(new URL("./autocomplete/useTerminalAutocomplete.ts", import.meta.url)),
"utf8",
);
assert.match(source, /showSnippets: true,/);
assert.match(source, /snippets: settingsRef\.current\.showSnippets \? snippetsRef\.current : undefined,/);
assert.match(source, /showSnippets: settingsRef\.current\.showSnippets,/);
assert.match(
source,
/if \(!settingsRef\.current\.showSnippets\) \{\s*completions = completions\.filter\(\(completion\) => completion\.source !== "snippet"\);/,
);
});
+4
View File
@@ -269,6 +269,8 @@ export interface TerminalSettings {
autocompleteMaxSuggestions: number; // Maximum suggestions in popup menu
/** Scope for history-backed autocomplete suggestions (host vs all hosts). */
autocompleteHistoryScope: AutocompleteHistoryScope;
/** Include matching code snippets in terminal autocomplete suggestions. */
autocompleteShowSnippets: boolean;
/**
* Assist for sudo/su password prompts: off, quick Enter-to-paste (hint),
@@ -480,6 +482,7 @@ export const normalizeTerminalSettings = (
autocompleteHistoryScope: isAutocompleteHistoryScope(settings?.autocompleteHistoryScope)
? settings.autocompleteHistoryScope
: DEFAULT_TERMINAL_SETTINGS.autocompleteHistoryScope,
autocompleteShowSnippets: settings?.autocompleteShowSnippets !== false,
oscNotifications: isOscNotificationMode(settings?.oscNotifications)
? settings.oscNotifications
: DEFAULT_TERMINAL_SETTINGS.oscNotifications,
@@ -663,6 +666,7 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = {
autocompleteMinChars: 1, // Start suggesting after 1 character
autocompleteMaxSuggestions: 50, // Show up to 50 suggestions (popup scrolls)
autocompleteHistoryScope: 'host', // Per-host history suggestions by default (#2595)
autocompleteShowSnippets: true, // Include matching code snippets in autocomplete by default
passwordPromptAssist: 'hint', // Historical sudo confirm-to-fill; picker is opt-in (#2156)
};
+19
View File
@@ -359,3 +359,22 @@ test("settings search finds the SFTP tree view folder double-click option from t
}
}
});
test("settings search finds the autocomplete show code snippets toggle across locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tTwReal = (key: string) => zhTW[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [t, queries] of [
[tZhReal, ["显示代码片段", "代码片段", "补全"]],
[tTwReal, ["顯示程式碼片段", "程式碼片段"]],
[tEnReal, ["show code snippets", "snippet", "snippets"]],
] as const) {
for (const query of queries) {
const hit = filterSettingsSearchCatalog(query, t).find(
(hit) => hit.entry.id === "terminal-autocomplete-show-snippets",
);
assert.ok(hit, `${query} should find terminal-autocomplete-show-snippets`);
assert.equal(hit.entry.tab, "terminal");
}
}
});
+8
View File
@@ -931,6 +931,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.autocomplete.historyScope.desc",
sectionKey: "settings.terminal.section.autocomplete",
},
{
id: "terminal-autocomplete-show-snippets",
tab: "terminal",
labelKey: "settings.terminal.autocomplete.showSnippets",
descriptionKey: "settings.terminal.autocomplete.showSnippets.desc",
sectionKey: "settings.terminal.section.autocomplete",
keywords: ["snippet", "snippets", "code snippets", "代码片段", "程式碼片段", "补全", "補全"],
},
{
id: "terminal-password-prompt-assist",
tab: "terminal",
+25
View File
@@ -106,6 +106,31 @@ test("normalizeTerminalSettings falls back for unsupported autocomplete history
);
});
test("normalizeTerminalSettings defaults autocompleteShowSnippets to true", () => {
assert.equal(normalizeTerminalSettings().autocompleteShowSnippets, true);
assert.equal(normalizeTerminalSettings({}).autocompleteShowSnippets, true);
});
test("normalizeTerminalSettings preserves explicit autocompleteShowSnippets values", () => {
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: false }).autocompleteShowSnippets,
false,
);
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: true }).autocompleteShowSnippets,
true,
);
});
test("normalizeTerminalSettings normalizes missing or non-boolean autocompleteShowSnippets to true", () => {
for (const invalid of [undefined, null, "false", 0, {}]) {
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: invalid as never }).autocompleteShowSnippets,
true,
);
}
});
test("normalizeTerminalSettings enables Shift+Enter newline by default", () => {
const settings = normalizeTerminalSettings();
+32 -3
View File
@@ -39,6 +39,16 @@ function createPreloadApi(ctx) {
}
for (const listener of hostBrowserPanelListeners) listener(request);
});
let coldStartIntentsSettled = false;
const coldStartIntentsSettledListeners = new Set();
// Main App mounts lazily; latch the cold-start settled signal so late
// subscribers still receive it once without racing live delivery.
ctx.ipcRenderer?.on?.("netcatty:startup:coldStartIntentsSettled", () => {
coldStartIntentsSettled = true;
for (const listener of [...coldStartIntentsSettledListeners]) {
listener();
}
});
// Lightweight test contexts may omit this map; default so closeSession never throws.
if (!ctx.moshSessionReadyListeners) {
ctx.moshSessionReadyListeners = new Map();
@@ -1586,9 +1596,28 @@ function createPreloadApi(ctx) {
return () => ipcRenderer.removeListener("netcatty:openTerminalPath", handler);
},
onColdStartIntentsSettled: (callback) => {
const handler = () => callback();
ipcRenderer.on("netcatty:startup:coldStartIntentsSettled", handler);
return () => ipcRenderer.removeListener("netcatty:startup:coldStartIntentsSettled", handler);
if (typeof callback !== "function") return () => {};
let active = true;
let delivered = false;
const deliver = () => {
if (!active || delivered) return;
delivered = true;
coldStartIntentsSettledListeners.delete(deliver);
try {
callback();
} catch (err) {
console.error("Cold-start intents settled callback failed", err);
}
};
if (coldStartIntentsSettled) {
queueMicrotask(deliver);
} else {
coldStartIntentsSettledListeners.add(deliver);
}
return () => {
active = false;
coldStartIntentsSettledListeners.delete(deliver);
};
},
setSshDeepLinkEnabled: (enabled) =>
ipcRenderer.invoke("netcatty:deepLink:ssh:setEnabled", { enabled }),
+59
View File
@@ -215,3 +215,62 @@ test("system theme subscription ignores malformed payloads", () => {
unsubscribe();
assert.deepEqual(calls, []);
});
test("coldStartIntentsSettled replays once when IPC fired before subscribe", async () => {
const { ipcRenderer } = createMockIpc();
const api = createPreloadApi({ ipcRenderer, webUtils: {} });
ipcRenderer.emit("netcatty:startup:coldStartIntentsSettled", {});
let calls = 0;
const off = api.onColdStartIntentsSettled(() => { calls += 1; });
// Duplicate live IPC racing the queued replay must not invoke the callback twice.
ipcRenderer.emit("netcatty:startup:coldStartIntentsSettled", {});
await Promise.resolve();
await Promise.resolve();
assert.equal(calls, 1);
off();
});
test("coldStartIntentsSettled invokes subscriber once when IPC fires after subscribe", async () => {
const { ipcRenderer } = createMockIpc();
const api = createPreloadApi({ ipcRenderer, webUtils: {} });
let calls = 0;
const off = api.onColdStartIntentsSettled(() => { calls += 1; });
assert.equal(calls, 0);
ipcRenderer.emit("netcatty:startup:coldStartIntentsSettled", {});
ipcRenderer.emit("netcatty:startup:coldStartIntentsSettled", {});
await Promise.resolve();
assert.equal(calls, 1);
off();
});
test("coldStartIntentsSettled unsubscribe prevents live delivery and cancels pending replay", async () => {
const { ipcRenderer } = createMockIpc();
const api = createPreloadApi({ ipcRenderer, webUtils: {} });
let liveCalls = 0;
const offLive = api.onColdStartIntentsSettled(() => { liveCalls += 1; });
offLive();
ipcRenderer.emit("netcatty:startup:coldStartIntentsSettled", {});
await Promise.resolve();
assert.equal(liveCalls, 0);
let replayCalls = 0;
const offReplay = api.onColdStartIntentsSettled(() => { replayCalls += 1; });
offReplay();
await Promise.resolve();
await Promise.resolve();
assert.equal(replayCalls, 0);
// Cancelling one subscriber must not clear the latch for a subsequent subscriber.
let laterCalls = 0;
const offLater = api.onColdStartIntentsSettled(() => { laterCalls += 1; });
await Promise.resolve();
assert.equal(laterCalls, 1);
offLater();
});
+3 -3
View File
@@ -1,14 +1,14 @@
{
version = "1.1.99";
version = "1.2.0";
sources = {
x86_64-linux = {
appImageArch = "x86_64";
hash = "sha256-1DL/6xfued2ZVT+DIZjlII6ATi4AXNCFrXGvWjBhCRg=";
hash = "sha256-75Mt9kDH4zlpLrngxBjOglrrDBgviuAoq5W2jJtXc+Q=";
};
aarch64-linux = {
appImageArch = "arm64";
hash = "sha256-O6HWgs4EuHZXgmyNf2VICsEODyRT536WWtcnnoxXuA0=";
hash = "sha256-ENQ8FTo3ATITTRFvBAvIhKzuGRKxbAKI5HXK3i+91qI=";
};
};
}