Compare commits

..
104 changed files with 649 additions and 5028 deletions

No files matched your search

+2 -8
View File
@@ -25,7 +25,6 @@ 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();
@@ -62,10 +61,8 @@ function App() {
/**
* `AppLockGate` (index.tsx) owns `useSettingsState` / `useAppLockState` so the
* 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.
* lock overlay can render before app children mount, and it owns the
* splash-removal + rendererReady signal (deep links must wait for unlock).
* App forwards the gate's settings instance into SettingsPublisher so the
* runtime slot/context still publish a single settings runtime.
*/
@@ -81,9 +78,6 @@ 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}>
-2
View File
@@ -67,8 +67,6 @@
- 🔥 **Intelligent context awareness** — understands your server environment and provides tailored responses
- 🚀 **One-click complex operations** — set up clusters, deploy services, and more with simple instructions
To search the web with DeepSeek, open **Settings → AI → Web Search**, enable web search, select **DeepSeek**, and enter your DeepSeek API key. You can use it with your current chat model. [DeepSeek Search API and pricing](https://api-docs.deepseek.com/guides/search/)
### 🎬 AI in Action
#### 🔥 Single Host — Intelligent Server Diagnostics
-2
View File
@@ -640,8 +640,6 @@ export const enAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} messages',
'ai.chat.managerDeleteTitle': 'Delete this chat?',
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
'ai.chat.justNow': 'Just now',
'ai.chat.minutesAgo': '{n}m ago',
'ai.chat.hoursAgo': '{n}h ago',
-3
View File
@@ -1001,9 +1001,6 @@ 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',
-2
View File
@@ -640,8 +640,6 @@ export const esAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} mensajes',
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.justNow': 'Ahora mismo',
'ai.chat.minutesAgo': 'hace {n} min',
'ai.chat.hoursAgo': 'hace {n} h',
-3
View File
@@ -1001,9 +1001,6 @@ 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',
-2
View File
@@ -639,8 +639,6 @@ export const ruAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} сообщений',
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.justNow': 'Только что',
'ai.chat.minutesAgo': '{n}м назад',
'ai.chat.hoursAgo': '{n}ч назад',
-3
View File
@@ -986,9 +986,6 @@ 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,20 +304,3 @@ 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`);
}
}
}
});
-2
View File
@@ -640,8 +640,6 @@ export const zhCNAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} 条消息',
'ai.chat.managerDeleteTitle': '删除此会话?',
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.justNow': '刚刚',
'ai.chat.minutesAgo': '{n}分钟前',
'ai.chat.hoursAgo': '{n}小时前',
@@ -574,9 +574,6 @@ 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':
-2
View File
@@ -639,8 +639,6 @@ export const zhTWAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} 則訊息',
'ai.chat.managerDeleteTitle': '刪除此會話?',
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.justNow': '剛剛',
'ai.chat.minutesAgo': '{n}分鐘前',
'ai.chat.hoursAgo': '{n}小時前',
@@ -574,9 +574,6 @@ 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':
+12 -24
View File
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { useAppLockChrome } from './appRuntimeBridge';
import { resolvePluginViewWindowScope } from './pluginViewScopes';
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -8,17 +7,15 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
subscribeHidden(listener: () => void): () => void; unavailable(): void;
}) {
const { locked } = useAppLockChrome();
const effectiveActive = active && !locked;
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const scopeId = typeof window !== 'undefined'
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
: '';
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
@@ -32,7 +29,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
useEffect(() => {
if (!effectiveActive) {
if (!active) {
setHidden(false);
return;
}
@@ -41,31 +38,22 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
const activeHandle = { key, send: session.send, image: session.image };
sessionRef.current = activeHandle;
sessionRef.current = { key, send: session.send, image: session.image };
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden((nextHidden = true) => {
if (nextHidden) {
sessionRef.current = null;
setHidden(true);
} else {
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
setHidden(false);
}
});
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
} catch { unavailableRef.current(); }
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
const fallbackLoadImage = useCallback((path: string) => {
const session = sessionRef.current;
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [effectiveActive, key]);
const hasCurrentState = effectiveActive
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
@@ -77,9 +65,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
? state.image
: (cachedSession?.image ?? fallbackLoadImage);
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
}, [effectiveActive, key]);
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
// A newly selected plugin must never receive values from the previous tree,
// even during the render before effect cleanup and the next activation.
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
}
+10 -40
View File
@@ -73,31 +73,15 @@ export function usePluginHostActions() {
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
}, [getVault]);
const clearReview = useCallback((entry: Review) => {
if (current.current !== entry) return;
current.current = null;
responding.current = false;
setReview(null);
setRemember(false);
setBusy(false);
setError(false);
}, []);
const fail = useCallback(async (entry: Review) => {
if (current.current !== entry) return;
setError(true);
try {
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
await netcattyBridge.get()?.respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
});
if (accepted === false) {
clearReview(entry);
}
} catch {
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
clearReview(entry);
}
}, [clearReview]);
} catch { /* A stopped runtime or closed window already invalidates it. */ }
}, []);
const execute = useCallback(async (entry: Review) => {
const bridge = netcattyBridge.get();
@@ -156,8 +140,7 @@ export function usePluginHostActions() {
entry.claimed = true;
assertCurrent(entry);
await openHostSession(entry.host);
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
return;
}
let action: PluginHostAction;
@@ -178,16 +161,9 @@ export function usePluginHostActions() {
},
connect: openHostSession,
});
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
} catch { await fail(entry); }
finally {
if (current.current === entry) {
responding.current = false;
setBusy(false);
}
}
}, [assertCurrent, clearReview, fail, getVault]);
}, [assertCurrent, fail, getVault]);
useEffect(() => {
const bridge = netcattyBridge.get();
@@ -306,7 +282,7 @@ export function usePluginHostActions() {
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
try {
if (action !== 'cancel') assertCurrent(entry);
assertCurrent(entry);
const request = entry.prompt.request;
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
const revision = entry.candidateRevisions.get(id);
@@ -320,24 +296,18 @@ export function usePluginHostActions() {
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
if (accepted === false) {
clearReview(entry);
}
} catch {
if (action === 'cancel') clearReview(entry);
else await fail(entry);
}
} catch { await fail(entry); }
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
}, [assertCurrent, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
if (current.current?.requestId !== event.requestId) return;
current.current = null; setPrompt(null);
} else {
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
current.current = event as UiPrompt;
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
setPrompt(null);
+2 -7
View File
@@ -149,12 +149,7 @@ export function usePluginViewLifecycle({
}, [contributions.loading, contributions.snapshot.plugins]);
useEffect(() => {
if (!requested || viewContributions.loading) return;
if (!resolvedActiveView) {
setRequested(null);
return;
}
if (activeView?.view.location !== 'tab') return;
if (!requested || activeView?.view.location !== 'tab') return;
pluginViewTabStore.open({
pluginId: activeView.plugin.id,
pluginName: activeView.plugin.displayName,
@@ -164,7 +159,7 @@ export function usePluginViewLifecycle({
context: requested.context,
});
setRequested(null);
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
}, [activeView, requested]);
useEffect(() => {
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
+2 -3
View File
@@ -766,14 +766,13 @@ 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,
@@ -1,96 +0,0 @@
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', 'autocompleteShowSnippets',
'autocompleteHistoryScope',
] as const;
export const SYNCABLE_SETTING_STORAGE_KEYS = [
+4 -49
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import type { AISession } from '../infrastructure/ai/types';
import { useI18n } from '../application/i18n/I18nProvider';
import { cn } from '../lib/utils';
@@ -9,7 +9,6 @@ import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
// -------------------------------------------------------------------
@@ -53,7 +52,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
const { t } = useI18n();
const [view, setView] = useState<'scoped' | 'global'>('scoped');
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
const [searchQuery, setSearchQuery] = useState('');
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
@@ -72,22 +70,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
setRenderCount(SESSION_RENDER_BATCH);
}, [sessions, searchQuery]);
useEffect(() => {
if (view !== 'global' || !globalManager) {
setGlobalSelectionMode(false);
}
}, [view, globalManager]);
const selectionContextValue = useMemo(
() => ({
selectionMode: globalSelectionMode,
setSelectionMode: setGlobalSelectionMode,
}),
[globalSelectionMode],
);
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
const displayedSessions = filteredSessions.slice(0, renderCount);
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
@@ -150,7 +132,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
</div>
<div className="flex items-center gap-2">
{hasHeaderMenu && (
{(onImportSessions || onExportSessions) && (
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
<DropdownTrigger asChild>
<button
@@ -162,31 +144,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</button>
</DropdownTrigger>
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
{canSelectGlobalChats && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setHeaderMenuOpen(false);
setGlobalSelectionMode((prev) => !prev);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<CheckSquare
size={12}
className={cn(
'shrink-0',
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
)}
/>
<span>{t('ai.chat.managerToggleSelection')}</span>
</button>
{(onImportSessions || onExportSessions) && (
<div className="my-1 h-px bg-border/50" />
)}
</>
)}
{onImportSessions && (
<button
type="button"
@@ -227,9 +184,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</div>
</div>
{view === 'global' && globalManager ? (
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
{globalManager}
</GlobalSessionSelectionContext.Provider>
globalManager
) : (
<>
<div className="px-3 py-2 shrink-0 border-b border-border/30">
+1 -283
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 { ReportRendererReady, createAppLockGate } from "./AppLockGate.tsx";
import { createAppLockGate } from "./AppLockGate.tsx";
import { APP_LOCK_AUTO_PROMPT_DELAY_MS } from "./AppLockOverlay.tsx";
import { createAppLockBridgeHarness } from "./test-support/createAppLockBridgeHarness.ts";
import {
@@ -1024,285 +1024,3 @@ 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,7 +5,6 @@ import {
shouldDeferExternalActionWhileAppLocked,
shouldNotifyAppLockGateRendererReady,
shouldRenderAppLockGateChildren,
shouldReportAppLockGateRendererReady,
} from "./AppLockGate.tsx";
test("shouldRenderAppLockGateChildren withholds startup-locked route children until unlock", () => {
@@ -141,44 +140,6 @@ 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);
+22 -74
View File
@@ -1,4 +1,4 @@
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { I18nProvider } from '../application/i18n/I18nProvider';
import { useAppLockBridge } from '../application/state/useAppLockBridge';
@@ -67,33 +67,6 @@ 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;
@@ -115,8 +88,6 @@ 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,
@@ -128,31 +99,10 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
if (renderChildren) {
hasRenderedChildrenRef.current = true;
}
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]);
const shouldNotifyRendererReady = shouldNotifyAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
});
useEffect(() => {
try {
@@ -161,14 +111,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
}
}, []);
useEffect(() => {
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
}, [notifyAppLockRendererReady, shouldNotifyRendererReady]);
useEffect(() => {
const unsubscribe = onAppLockReopen(() => {
@@ -199,20 +149,18 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
<I18nProvider locale={settings.uiLanguage}>
<ToastProvider>
<TooltipProvider delayDuration={300}>
<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>
{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}
<AppLockOverlay
locked={appLock.locked}
reason={appLock.lockReason}
-10
View File
@@ -31,13 +31,3 @@ 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*\/>/);
});
+6 -3
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 { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
import 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 { closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
const { notifyRendererReady, 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,6 +359,10 @@ 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";
@@ -753,7 +757,6 @@ export default function SettingsPage({
<I18nProvider locale={settings.uiLanguage}>
<SettingsFocusProvider>
<SettingsPageContent settings={settings} appLock={appLock} />
<ReportRendererReady />
</SettingsFocusProvider>
</I18nProvider>
);
+1 -2
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 { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
import type { AppLockGateRenderContext } from "./AppLockGate";
const StatusDot: React.FC<{ status: "success" | "warning" | "error" | "neutral"; spinning?: boolean }> = ({
status,
@@ -505,7 +505,6 @@ const TrayPanel: React.FC<{ settings: SettingsState }> = ({ settings }) => {
return (
<I18nProvider locale={settings.uiLanguage}>
<TrayPanelContent />
<ReportRendererReady />
</I18nProvider>
);
};
+12 -130
View File
@@ -566,16 +566,9 @@ test("subtitle styling keeps agent label emphasized and message count normal whe
}
});
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
test("selection mode batches delete and title regeneration without activating rows", async () => {
const dom = installDomEnvironment();
const restoreGlobals = installRadixGlobals(dom);
try {
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const renderer = await createDomRenderer(dom.document);
const props = baseProps();
props.sessions = [
makeSession({ id: "s-a", title: "A" }),
@@ -588,141 +581,30 @@ test("selection mode is triggered from the drawer overflow menu, confirms bulk d
props.onRegenerateTitle = (id) => regenerated.push(id);
props.onSelect = (id) => activated.push(id);
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<SessionHistoryDrawer
sessions={props.sessions}
activeSessionId="s-a"
onSelect={() => {}}
onDelete={() => {}}
onExportSessions={() => {}}
onClose={() => {}}
globalManager={<GlobalAIChatSessionManager {...props} />}
/>
</TooltipProvider>
</I18nProvider>,
const renderer = await renderManager(dom, props);
const toggle = renderer.container.querySelector<HTMLElement>(
`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`,
);
assert.ok(toggle, "selection toggle present");
await dispatchDomEvent(toggle, new dom.window.MouseEvent("click", { bubbles: true }));
const openHeaderMenu = async () => {
const trigger = renderer.container.querySelector<HTMLButtonElement>(
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
);
assert.ok(trigger, "drawer overflow trigger present");
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
};
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
await openHeaderMenu();
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
// Close header menu before switching tabs.
await openHeaderMenu();
// Switch to the "All chats" tab.
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
// Search/filter bar must not contain an inline selection toggle button.
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
null,
"no standalone selection button in filter bar",
);
// Trigger selection mode from the drawer's top-right overflow menu.
await openHeaderMenu();
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.ok(selectItem, "Select chats menu item present on All chats tab");
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection action bar opens",
);
// Clicking Cancel exits selection mode cleanly.
const cancelBtn = Array.from(
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.trim() === t("common.cancel"));
assert.ok(cancelBtn, "Cancel button present in selection bar");
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Cancel exits selection mode",
);
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
await openHeaderMenu();
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Escape exits selection mode",
);
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
await openHeaderMenu();
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection bar open before tab switch",
);
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"switching away from All chats resets selection mode",
);
await openHeaderMenu();
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
// Clicking rows toggles selection instead of opening the chat.
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(activated, []);
const bulkRegen = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
const bulkRegen = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
assert.ok(bulkRegen, "bulk regenerate button present");
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
// Bulk delete is confirm-gated.
const bulkDelete = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("common.delete")));
const bulkDelete = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.includes(t("common.delete")));
assert.ok(bulkDelete, "bulk delete button present");
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"selection mode exits after confirmed bulk delete",
);
} finally {
restoreGlobals();
dom.cleanup();
}
});
+86 -161
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
import { useI18n } from '../../application/i18n/I18nProvider';
@@ -15,7 +15,6 @@ import {
} from '../ui/select';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
import {
buildGlobalManagerRows,
@@ -61,9 +60,6 @@ interface GlobalAIChatSessionManagerProps {
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
onRegenerateTitle?: (sessionId: string) => void;
onExport: (sessionId: string) => void;
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
selectionMode?: boolean;
onSelectionModeChange?: (active: boolean) => void;
}
const MANAGER_RENDER_BATCH = 80;
@@ -88,41 +84,20 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
onDeleteMany,
onRegenerateTitle,
onExport,
selectionMode: controlledSelectionMode,
onSelectionModeChange,
}) => {
const { t } = useI18n();
const selectionContext = useContext(GlobalSessionSelectionContext);
const [searchQuery, setSearchQuery] = useState('');
const [agentFilter, setAgentFilter] = useState<string>('all');
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
const [moveSession, setMoveSession] = useState<AISession | null>(null);
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
const [selectionMode, setSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [renameDraft, setRenameDraft] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
const selectionMode =
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
const setSelectionMode = useCallback(
(active: boolean) => {
if (controlledSelectionMode !== undefined) {
onSelectionModeChange?.(active);
} else if (selectionContext) {
selectionContext.setSelectionMode(active);
onSelectionModeChange?.(active);
} else {
setUncontrolledSelectionMode(active);
onSelectionModeChange?.(active);
}
},
[controlledSelectionMode, onSelectionModeChange, selectionContext],
);
const rows = useMemo(
() => buildGlobalManagerRows({
sessions,
@@ -161,26 +136,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
if (renamingSessionId) renameInputRef.current?.focus();
}, [renamingSessionId]);
useEffect(() => {
if (!selectionMode) {
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}
}, [selectionMode]);
const rowSessionIds = useMemo(
() => new Set(rows.map((row) => row.session.id)),
[rows],
);
const activeSelectedIds = useMemo(() => {
if (selectedIds.size === 0) return selectedIds;
const next = new Set<string>();
selectedIds.forEach((id) => {
if (rowSessionIds.has(id)) next.add(id);
});
return next;
}, [selectedIds, rowSessionIds]);
const displayedRows = filteredRows.slice(0, renderCount);
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
@@ -211,24 +166,10 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
return next;
});
};
const exitSelectionMode = useCallback(() => {
const exitSelectionMode = () => {
setSelectionMode(false);
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}, [setSelectionMode]);
useEffect(() => {
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
exitSelectionMode();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
};
const toggleSelectAll = () => {
const visibleIds = displayedRows.map((row) => row.session.id);
setSelectedIds((prev) => {
@@ -237,15 +178,15 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
});
};
const commitBulkDelete = () => {
if (activeSelectedIds.size === 0) return;
const ids = [...activeSelectedIds];
if (selectedIds.size === 0) return;
const ids = [...selectedIds];
if (onDeleteMany) onDeleteMany(ids);
else ids.forEach((id) => onDelete(id));
exitSelectionMode();
};
const commitBulkRegenerate = () => {
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
if (!onRegenerateTitle || selectedIds.size === 0) return;
selectedIds.forEach((id) => onRegenerateTitle(id));
};
const getOtherMoveTargets = (session: AISession) =>
@@ -311,6 +252,18 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
)}
</div>
<button
type="button"
aria-label={t('ai.chat.managerToggleSelection')}
title={t('ai.chat.managerToggleSelection')}
onClick={() => (selectionMode ? exitSelectionMode() : setSelectionMode(true))}
className={cn(
'h-8 w-8 shrink-0 grid place-items-center rounded-md transition-colors cursor-pointer',
selectionMode ? 'bg-primary/15 text-primary' : 'text-muted-foreground/60 hover:text-foreground hover:bg-muted',
)}
>
<CheckSquare size={14} />
</button>
{showAgentMeta && (
<Select value={effectiveAgentFilter} onValueChange={setAgentFilter}>
<SelectTrigger
@@ -333,29 +286,24 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
)}
</div>
{selectionMode && (
<div
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
data-section="ai-global-session-selection-bar"
>
<div className="px-3 py-1.5 shrink-0 border-b border-border/30 flex items-center gap-2 text-[12px]">
<button
type="button"
onClick={toggleSelectAll}
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer"
>
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
{displayedRows.length > 0 && displayedRows.every((row) => selectedIds.has(row.session.id))
? <CheckSquare size={13} /> : <Square size={13} />}
{t('ai.chat.managerSelectAll')}
</button>
<span className="text-muted-foreground/60 whitespace-nowrap">
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
</span>
<div className="ml-auto flex items-center gap-1">
<span className="text-muted-foreground/60">{t('ai.chat.managerSelectedCount', { n: String(selectedIds.size) })}</span>
<div className="ml-auto flex items-center gap-2">
{onRegenerateTitle && (
<button
type="button"
disabled={activeSelectedIds.size === 0}
disabled={selectedIds.size === 0}
onClick={commitBulkRegenerate}
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 cursor-pointer"
>
<RefreshCw size={12} />
{t('ai.chat.managerRegenerateTitle')}
@@ -363,20 +311,13 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
)}
<button
type="button"
disabled={activeSelectedIds.size === 0}
onClick={() => setBulkDeleteConfirmOpen(true)}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
disabled={selectedIds.size === 0}
onClick={commitBulkDelete}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 cursor-pointer"
>
<Trash2 size={12} />
{t('common.delete')}
</button>
<button
type="button"
onClick={exitSelectionMode}
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
>
{t('common.cancel')}
</button>
</div>
</div>
)}
@@ -421,7 +362,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
<React.Fragment key={row.session.id}>
<div
role="button"
tabIndex={selectionMode || row.canActivate ? 0 : -1}
tabIndex={row.canActivate ? 0 : -1}
onClick={() => {
if (selectionMode) {
toggleSelected(row.session.id);
@@ -448,91 +389,87 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
row.isCurrentActive
? 'text-foreground'
: 'text-foreground/75 hover:text-foreground',
!selectionMode && !row.canActivate && 'cursor-default',
!row.canActivate && 'cursor-default',
)}
data-session-id={row.session.id}
data-scope-state={row.scopeState}
>
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
<div className="min-w-0">
{selectionMode && (
<button
type="button"
aria-label={t('ai.chat.managerSelectRow')}
aria-pressed={activeSelectedIds.has(row.session.id)}
onClick={(e) => {
e.stopPropagation();
toggleSelected(row.session.id);
}}
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
className="float-left mr-2 mt-0.5 text-muted-foreground/60 hover:text-primary cursor-pointer"
>
{activeSelectedIds.has(row.session.id)
{selectedIds.has(row.session.id)
? <CheckSquare size={14} className="text-primary" />
: <Square size={14} />}
</button>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
)}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
/>
) : (
row.title
)}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
</span>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
{formatRelativeTime(new Date(row.session.updatedAt), t)}
</span>
{!selectionMode && (
<Dropdown
open={isMenuOpen}
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
@@ -625,7 +562,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
</DropdownContent>
</Dropdown>
)}
</div>
</div>
{moveSession?.id === row.session.id && (
@@ -686,17 +622,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
}}
onConfirm={commitDelete}
/>
<ConfirmDialog
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
confirmLabel={t('common.delete')}
destructive
onOpenChange={(open) => {
if (!open) setBulkDeleteConfirmOpen(false);
}}
onConfirm={commitBulkDelete}
/>
</div>
);
};
@@ -1,9 +0,0 @@
import { createContext } from 'react';
export interface GlobalSessionSelectionContextValue {
selectionMode: boolean;
setSelectionMode: (active: boolean) => void;
}
export const GlobalSessionSelectionContext =
createContext<GlobalSessionSelectionContextValue | null>(null);
@@ -337,27 +337,22 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<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),
})}
</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 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>
) : null}
</div>
{restoreAllowed && (
<Button
@@ -448,27 +443,22 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<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),
})}
</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 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>
) : null}
</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
+3 -6
View File
@@ -58,12 +58,9 @@ export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSessi
showHeader?: boolean;
}) {
const { t } = useI18n();
const subscribeHidden = useMemo(() => (onVisibilityChange: (hidden?: boolean) => void) => {
const sync = (tab = activeTabStore.getActiveTabId()) => {
onVisibilityChange(tab !== tabId || getSession() !== sessionId);
};
const stopTab = activeTabStore.subscribeSync((id) => sync(id));
const stopSession = subscribeSidePanelLiveSnapshot(true, () => sync());
const subscribeHidden = useMemo(() => (hide: () => void) => {
const stopTab = activeTabStore.subscribeSync((id) => { if (id !== tabId) hide(); });
const stopSession = subscribeSidePanelLiveSnapshot(true, () => { if (getSession() !== sessionId) hide(); });
return () => { stopTab(); stopSession(); };
}, [getSession, sessionId, tabId]);
return <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label={`${page.title} — ${page.pluginName}`} data-plugin-terminal-sidebar>
+1 -2
View File
@@ -15,8 +15,7 @@ import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDraw
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
type VaultPages = ReturnType<typeof usePluginVaultPages>;
const subscribeHidden = (onVisibilityChange: (hidden?: boolean) => void) =>
activeTabStore.subscribeSync((id) => { onVisibilityChange(id !== 'vault'); });
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
let nextPluginPromptId = 1;
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
@@ -1603,17 +1603,6 @@ 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")} />
@@ -10,7 +10,6 @@ const SEARCH_ICON_PATHS: Record<WebSearchProviderId, string> = {
tavily: "/ai/search/tavily.svg",
exa: "/ai/search/exa.png",
bocha: "/ai/search/bocha.webp",
deepseek: "/ai/providers/deepseek.svg",
zhipu: "/ai/search/zhipu.png",
searxng: "/ai/search/searxng.svg",
};
+1 -2
View File
@@ -129,14 +129,13 @@ 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, settings?.showSnippets, status, workspaceId]);
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
const autocomplete = useTerminalAutocomplete({
termRef,
containerRef,
@@ -210,8 +210,6 @@ 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;
/**
@@ -378,7 +376,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.showSnippets !== false && options.snippets && options.snippets.length > 0) {
if (options.snippets && options.snippets.length > 0) {
const atCommandPosition = ctx.wordIndex === 0;
const argumentNeedle = normalizeHistoryPathPrefix(ctx.currentWord);
const snippetArgumentMatch = !atCommandPosition
@@ -10,7 +10,6 @@ type TerminalAutocompleteSettingFields = {
autocompleteMinChars?: number;
autocompleteMaxSuggestions?: number;
autocompleteHistoryScope?: AutocompleteHistoryScope;
autocompleteShowSnippets?: boolean;
shiftEnterNewlineEnabled?: boolean;
};
@@ -37,7 +36,6 @@ export function resolveTerminalAutocompleteSettings(input: {
minChars: terminalSettings?.autocompleteMinChars ?? 1,
maxSuggestions: terminalSettings?.autocompleteMaxSuggestions ?? 50,
historyScope: terminalSettings?.autocompleteHistoryScope ?? "host",
showSnippets: terminalSettings?.autocompleteShowSnippets !== false,
shiftEnterNewlineEnabled: terminalSettings?.shiftEnterNewlineEnabled ?? true,
};
}
@@ -60,7 +58,6 @@ 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,16 +159,3 @@ 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,8 +17,6 @@ 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;
@@ -75,8 +73,7 @@ export async function provideTerminalCompletions(
protocol: request.session.protocol,
cwd: request.session.cwd,
cwdSource: request.cwdSource,
snippets: request.showSnippets === false ? undefined : request.snippets,
showSnippets: request.showSnippets,
snippets: request.snippets,
historyScope: request.historyScope,
onLatePathSuggestions: request.onLatePathSuggestions,
locale: request.locale,
@@ -68,8 +68,6 @@ 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 = {
@@ -84,7 +82,6 @@ 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). */
@@ -305,7 +302,6 @@ export function useTerminalAutocomplete(
const settings: AutocompleteSettings = {
...rawSettings,
showGhostText: rawSettings.showPopupMenu ? false : rawSettings.showGhostText,
showSnippets: rawSettings.showSnippets !== false,
livePreview: shouldWriteAutocompleteLivePreview(rawSettings.livePreview, isNetworkDevice),
};
@@ -491,16 +487,6 @@ 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
@@ -1179,8 +1165,7 @@ export function useTerminalAutocomplete(
skipPathCompletion: isNetworkDeviceRef.current,
cwd: cwdResolution.cwd,
cwdSource: cwdResolution.source,
snippets: settingsRef.current.showSnippets ? snippetsRef.current : undefined,
showSnippets: settingsRef.current.showSnippets,
snippets: snippetsRef.current,
promptText: prompt.promptText,
allowExternalProviders,
signal: completionController.signal,
@@ -1203,9 +1188,6 @@ 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),
@@ -1,115 +0,0 @@
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);
}
}
});
+2 -10
View File
@@ -33,17 +33,9 @@ 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?: {
hasRenderer?: () => boolean;
dimensions?: { css?: { cell?: CellDimensions } };
} };
_core?: { _renderService?: { dimensions?: { css?: { cell?: CellDimensions } } } };
};
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;
const coreDims = coreAccess._core?._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,7 +3,6 @@ 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";
@@ -116,83 +115,3 @@ 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,8 +1936,6 @@ 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 &&
@@ -2052,8 +2050,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const armImeTextInputDeferral = (event: KeyboardEvent) => {
clearImeTextInputDeferral();
clearBroadcastLegacyDataPending();
// Wait for insertText before keyup; keyup/blur flushes the original glyph
// when the IME did not remap the key.
// Wait for insertText (full-width) before keyup; keyup/blur flushes ASCII
// when the IME did not remap the key (English punctuation mode).
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.
@@ -2757,10 +2755,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
return false;
}
// 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.
// 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).
if (shouldDeferKeyDownForImeTextInput(e)) {
armImeTextInputDeferral(e);
return false;
@@ -43,32 +43,27 @@ 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", () => {
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));
}
}
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,
);
});
test("shouldBlockKeyPressForImeTextInput only while a deferral is armed", () => {
@@ -396,22 +391,9 @@ test("shouldCommitDeferredImeTextInput accepts insertText payloads while deferre
);
});
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", () => {
test("isUnchangedDeferredImeTextInput detects English punctuation flush", () => {
assert.equal(isUnchangedDeferredImeTextInput(",", ","), true);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(null, ","), false);
});
@@ -4,11 +4,9 @@
* 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 key is flushed. Composition (keyCode 229 /
* keyup/blur, the original ASCII 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
@@ -34,9 +32,6 @@ 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);
}
@@ -47,8 +42,7 @@ 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) ||
(event.key.charCodeAt(0) > 0x7f && UNICODE_PUNCTUATION_RE.test(event.key));
return isAsciiPunctuationKey(event.key);
}
/** Key releases that carry no keystroke of their own. */
@@ -192,5 +186,5 @@ export function isUnchangedDeferredImeTextInput(
deferredKey: string | null | undefined,
text: string,
): boolean {
return deferredKey != null && isAsciiPunctuationKey(deferredKey) && text === deferredKey;
return deferredKey != null && text === deferredKey;
}
@@ -257,79 +257,19 @@ test("does not arm when the hint cannot be shown (overlay unavailable)", () => {
assert.deepEqual(writes, []);
});
test("a bare Password prompt does not hint until a su or sudo command is submitted", () => {
test("a bare Password prompt does not hint until a su command is submitted", () => {
const { autofill, hints } = make();
autofill.handleOutput("Password: ");
assert.deepEqual(hints, []);
// macOS / Synology sudo uses the same bare prompt as su (#4628).
// sudo-armed bare Password: is too generic (mysql/ssh); su-armed is expected
autofill.armForCommand("sudo whoami");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, [true]);
assert.deepEqual(hints, []);
autofill.armForCommand("su -");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, [true, false, true]);
assert.deepEqual(hints, [true]);
});
for (const command of ["sudo ping 192.168.30.4", "sudo su"]) {
for (const prompt of ["Password:", "密码:"]) {
test(`${command} shows only the host-password hint for ${prompt} (#4628)`, () => {
const hints: boolean[] = [];
const writes: string[] = [];
const autofill = createSudoPasswordAutofill({
mode: "picker",
password: "host-secret",
candidates: [{ id: "other", label: "Other", password: "other-secret" }],
write: (data) => writes.push(data),
onHint: (active) => {
hints.push(active);
return true;
},
onPicker: () => assert.fail("sudo must not open the full keychain picker"),
});
autofill.armForCommand(command);
autofill.handleOutput(prompt);
assert.deepEqual(hints, [true]);
assert.deepEqual(writes, []);
assert.equal(autofill.isPromptPending(), true);
assert.equal(autofill.isPickerPending(), false);
autofill.confirmFill();
assert.deepEqual(writes, ["host-secret\n"]);
});
}
}
test("sudo arms still reject child and remote password prompts (#4628)", () => {
for (const prompt of ["Enter password:", "Password for user postgres:", "user@host's password:"]) {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput(prompt);
assert.deepEqual(hints, [], prompt);
assert.equal(autofill.isPromptPending(), false, prompt);
autofill.confirmFill();
assert.deepEqual(writes, [], prompt);
}
});
for (const { output, retry } of [
{ output: "\r\nPassword:", retry: false },
{ output: "\r\nSorry, try again.\r\nPassword:", retry: true },
{ output: "\r\n[sudo] password for alice:", retry: true },
]) {
test(`sudo bare prompt after confirmFill requires auth retry evidence: ${JSON.stringify(output)} (#4628)`, () => {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput("Password:");
assert.equal(autofill.isPromptPending(), true);
autofill.confirmFill();
assert.deepEqual(writes, ["secret\n"]);
autofill.handleOutput(output);
assert.equal(autofill.isPromptPending(), retry);
assert.deepEqual(hints, retry ? [true, false, true] : [true, false]);
autofill.confirmFill();
assert.deepEqual(writes, retry ? ["secret\n", "secret\n"] : ["secret\n"]);
});
}
test("an explicit [sudo] prompt hints without a recorded sudo command", () => {
// The [sudo] tag is sudo-specific, so we hint even when arming didn't fire —
// manual typing's recordedCommand is flaky (#1281/#1284), and the hint only
@@ -350,10 +350,9 @@ export const createSudoPasswordAutofill = (_options: {
if (!armActive) return false;
// su always prompts with a bare Password: line (not Enter password / DB).
if (armedKind === "su") return isSuBarePasswordPrompt(line);
// macOS / Synology / BSD sudo uses the same short bare Password: as su (#4628).
if (armedKind === "sudo") {
return isSudoScopedBarePasswordPrompt(line) || isSuBarePasswordPrompt(line);
}
// sudo: only sudo-scoped prompts, never generic "Enter password:" from
// child programs when sudo credentials are already cached.
if (armedKind === "sudo") return isSudoScopedBarePasswordPrompt(line);
return false;
};
@@ -443,8 +442,8 @@ export const createSudoPasswordAutofill = (_options: {
dismissedWhileArmed = false;
armedKind = null;
}
// Explicit "[sudo] …" always; su/sudo arms accept short bare Password:;
// sudo also accepts scoped prompts (not generic Enter password from mysql).
// Explicit "[sudo] …" always; su arm accepts bare Password:; sudo arm only
// accepts sudo-scoped bare prompts (not generic Enter password from mysql).
const isPrompt = isArmedPromptLine(lastLine, armActive);
if (pending) {
// The prompt moved on: a new line arrived and the latest line is no
@@ -30,7 +30,6 @@ function createContext(input: string) {
fastTypingThresholdMs: 40,
shiftEnterNewlineEnabled: true,
historyScope: "host",
showSnippets: true,
};
const context = {
settingsRef: ref(settings),
@@ -28,7 +28,6 @@ test("keeps autocomplete enabled for shell-like terminal protocols", () => {
minChars: 2,
maxSuggestions: 6,
historyScope: "global",
showSnippets: true,
shiftEnterNewlineEnabled: false,
},
);
@@ -58,7 +57,6 @@ test("keeps network-device autocomplete popup but disables live preview (#1193)"
minChars: 1,
maxSuggestions: 8,
historyScope: "host",
showSnippets: true,
shiftEnterNewlineEnabled: true,
},
);
@@ -111,7 +109,6 @@ 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,
@@ -157,33 +154,3 @@ 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,17 +99,3 @@ 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,8 +269,6 @@ 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),
@@ -482,7 +480,6 @@ 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,
@@ -666,7 +663,6 @@ 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,22 +359,3 @@ 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");
}
}
});
+1 -9
View File
@@ -931,14 +931,6 @@ 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",
@@ -1299,7 +1291,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "ai.webSearch.enable",
descriptionKey: "ai.webSearch.enable.description",
sectionKey: "ai.webSearch.title",
keywords: ["tavily", "brave", "deepseek", "web search"],
keywords: ["tavily", "brave", "web search"],
},
{
id: "ai-web-search-provider",
-25
View File
@@ -106,31 +106,6 @@ 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();
-20
View File
@@ -116,26 +116,6 @@ test("ssh_config import maps ForwardX11 no to disabled host X11 forwarding", ()
assert.equal(result.hosts[0].x11Forwarding, false);
});
test("ssh_config import merges an alias declared in several Host blocks", () => {
const result = importVaultHostsFromText("ssh_config", [
"Host hd-edu-web1",
" HostName 10.147.28.11",
" User root",
"",
"Host hd-edu-web1",
" IdentityFile ~/.ssh/id_rsa",
" IdentitiesOnly yes",
].join("\n"));
assert.equal(result.hosts.length, 1);
const [host] = result.hosts;
assert.equal(host.label, "hd-edu-web1");
assert.equal(host.hostname, "10.147.28.11");
assert.equal(host.username, "root");
assert.deepEqual(host.identityFilePaths, ["~/.ssh/id_rsa"]);
assert.equal(host.identitiesOnly, true);
});
test("ssh_config import enables agent login for the macOS Keychain pattern", () => {
const result = importVaultHostsFromText("ssh_config", [
"Host aws-sg",
+55 -96
View File
@@ -1105,111 +1105,70 @@ const importFromSshConfig = (text: string): VaultImportResult => {
const makeHostKey = (hostname: string, port?: number) =>
`${hostname.toLowerCase()}:${port ?? 22}`;
// OpenSSH applies every Host block whose pattern matches an alias and keeps
// the first obtained value, so one alias may be declared in several blocks
// (for example HostName/User in one block and IdentityFile in another).
// Resolve options per literal pattern; treating every block as its own host
// imported such an alias twice, and the second copy kept the alias itself as
// its hostname with no username.
const orderedPatterns: string[] = [];
const blockByPattern = new Map<string, Block>();
const inheritOption = <K extends keyof Block>(target: Block, source: Block, key: K) => {
if (target[key] === undefined && source[key] !== undefined) target[key] = source[key];
};
for (const block of blocks) {
for (const pattern of block.patterns) {
if (!pattern || isWildcardPattern(pattern)) continue;
const merged = blockByPattern.get(pattern);
if (!merged) {
blockByPattern.set(pattern, {
...block,
patterns: [pattern],
identityFiles: block.identityFiles ? [...block.identityFiles] : undefined,
const patterns = block.patterns.filter((p) => p && !isWildcardPattern(p));
if (patterns.length === 0) continue;
for (const pat of patterns) {
parsed++;
const hostname = block.hostname ?? pat;
if (!looksLikeHostnameToken(hostname)) {
skipped++;
issues.push({
level: "warning",
message: `ssh_config: skipped host "${pat}" (invalid hostname).`,
});
orderedPatterns.push(pattern);
continue;
}
inheritOption(merged, block, "hostname");
inheritOption(merged, block, "username");
inheritOption(merged, block, "port");
inheritOption(merged, block, "proxyJump");
inheritOption(merged, block, "identityAgent");
inheritOption(merged, block, "identitiesOnly");
inheritOption(merged, block, "addKeysToAgent");
inheritOption(merged, block, "useKeychain");
inheritOption(merged, block, "forwardX11");
if (block.identityFiles?.length) {
const seen = new Set(merged.identityFiles ?? []);
for (const identityFile of block.identityFiles) {
if (seen.has(identityFile)) continue;
seen.add(identityFile);
(merged.identityFiles ??= []).push(identityFile);
}
}
}
}
for (const pattern of orderedPatterns) {
const block = blockByPattern.get(pattern)!;
parsed++;
const hostname = block.hostname ?? pattern;
if (!looksLikeHostnameToken(hostname)) {
skipped++;
issues.push({
level: "warning",
message: `ssh_config: skipped host "${pattern}" (invalid hostname).`,
const host = createHost({
label: pat,
hostname,
username: block.username,
port: block.port,
protocol: "ssh",
});
continue;
}
const host = createHost({
label: pattern,
hostname,
username: block.username,
port: block.port,
protocol: "ssh",
});
// Attach IdentityFile paths if present
if (block.identityFiles && block.identityFiles.length > 0) {
host.identityFilePaths = [...block.identityFiles];
}
if (block.identityAgent !== undefined) {
host.identityAgent = block.identityAgent;
}
if (block.identitiesOnly !== undefined) {
host.identitiesOnly = block.identitiesOnly;
}
if (block.addKeysToAgent !== undefined) {
host.addKeysToAgent = block.addKeysToAgent;
}
if (block.useKeychain !== undefined) {
host.useKeychain = block.useKeychain;
}
const identityAgentEnabled = block.identityAgent !== undefined
&& block.identityAgent.toLowerCase() !== "none";
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
// declaring IdentityAgent. Treat that pair as an agent-backed login so
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
host.useSshAgent = true;
} else if (identityAgentDisabled) {
host.useSshAgent = false;
}
if (block.forwardX11 !== undefined) {
host.x11Forwarding = block.forwardX11;
}
// Attach IdentityFile paths if present
if (block.identityFiles && block.identityFiles.length > 0) {
host.identityFilePaths = [...block.identityFiles];
}
if (block.identityAgent !== undefined) {
host.identityAgent = block.identityAgent;
}
if (block.identitiesOnly !== undefined) {
host.identitiesOnly = block.identitiesOnly;
}
if (block.addKeysToAgent !== undefined) {
host.addKeysToAgent = block.addKeysToAgent;
}
if (block.useKeychain !== undefined) {
host.useKeychain = block.useKeychain;
}
const identityAgentEnabled = block.identityAgent !== undefined
&& block.identityAgent.toLowerCase() !== "none";
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
// declaring IdentityAgent. Treat that pair as an agent-backed login so
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
host.useSshAgent = true;
} else if (identityAgentDisabled) {
host.useSshAgent = false;
}
if (block.forwardX11 !== undefined) {
host.x11Forwarding = block.forwardX11;
}
parsedHosts.push(host);
parsedHosts.push(host);
// Store ProxyJump using hostname key (survives deduplication)
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
const hostKey = makeHostKey(hostname, block.port);
hostProxyJumpMap.set(hostKey, block.proxyJump);
// Store ProxyJump using hostname key (survives deduplication)
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
const hostKey = makeHostKey(hostname, block.port);
hostProxyJumpMap.set(hostKey, block.proxyJump);
}
}
}
+6 -11
View File
@@ -174,7 +174,7 @@ function isDefaultCmdPromptLine(line) {
}
function stripLeadingDecorativeToken(line) {
// Optional short decorative tokens, stripped only for recognition (#4354).
// Optional short decorative token, stripped only for recognition (#4354).
return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, "");
}
@@ -183,11 +183,9 @@ function isDefaultPosixPromptLine(line) {
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
// before the shell prompt. Recognition only; callers still return the full
// prompt line so suffix matching sees the visible prefix (#3947).
let prompt = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
// Check each candidate before stripping again: a glyph such as the
// robbyrussell arrow may be part of the prompt itself (#4354).
while (true) {
if (
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some(
(prompt) => (
POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_PATH_POSIX_PROMPT_PATTERN.test(prompt) ||
@@ -198,11 +196,8 @@ function isDefaultPosixPromptLine(line) {
POWERLEVEL10K_PROMPT_PATTERN.test(prompt) ||
POWERLINE_PROMPT_PATTERN.test(prompt) ||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt)
) return true;
const stripped = stripLeadingDecorativeToken(prompt);
if (stripped === prompt) return false;
prompt = stripped;
}
),
);
}
function extractTrailingIdlePrompt(output) {
-31
View File
@@ -518,41 +518,10 @@ test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the f
}
});
test("stacked decorative prefixes preserve the full extracted and tracked prompt", () => {
for (const prompt of [
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u26A1 root@testhost:~# `,
`${status} \u26A1 root@testhost:~#`,
`${status} \u26A1 root@testhost \uE0B0 ~ \uE0B0 `,
`(venv) ${status} \u26A1 user@host:~# `,
`${status} \u279C netcatty`,
`${status} \u279C netcatty `,
`${status} \u279C ~ git:(main) \u2717`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 `,
]),
"\u2718 \u2714 \u26A1 root@testhost:~# ",
"\u2718 \u2714 \u279C netcatty ",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
const session = {};
trackSessionIdlePrompt(session, `welcome\r\n${prompt}`);
assert.equal(session.lastIdlePrompt, prompt, prompt);
assert.equal(getFreshIdlePrompt(session), prompt, prompt);
}
});
test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => {
for (const line of [
"\u26A1 root@testhost:~# echo hi",
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
"\u2718 \u26A1 root@testhost:~# echo hi",
"\u2718 \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u279C netcatty ls`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 ls`,
]),
"\u2718 \u2714 \u279C netcatty ls",
"OK root@testhost:~# ",
"yes root@testhost:~# ",
"git:(main) root@testhost:~# ",
@@ -199,7 +199,6 @@ function registerProviderHandlers(ctx) {
"api.tavily.com",
"api.exa.ai",
"api.bochaai.com",
"api.deepseek.com",
"open.bigmodel.cn",
]);
// Dynamically populated from configured provider baseURLs
@@ -685,121 +685,3 @@ test("stop by rule id reports cleanup failures and keeps the tunnel retryable",
cancelled: true,
});
});
test("startPortForward settles pendingDialCoordination when custom bindChannels succeeds without publishing a transport", async (t) => {
resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 });
t.after(() => resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 }));
const ssh2 = require("ssh2");
const originalConnect = ssh2.Client.prototype.connect;
const originalEnd = ssh2.Client.prototype.end;
let connectCount = 0;
ssh2.Client.prototype.connect = function fakeConnect() {
connectCount += 1;
this._remoteVer = "SSH-2.0-OpenSSH_9.6";
this._sock = { destroyed: false, writableEnded: false, setTimeout() {} };
setImmediate(() => this.emit("ready"));
return this;
};
ssh2.Client.prototype.end = function fakeEnd() {
setImmediate(() => this.emit("close"));
return this;
};
t.after(() => {
ssh2.Client.prototype.connect = originalConnect;
ssh2.Client.prototype.end = originalEnd;
});
const event = { sender: createSender() };
const basePayload = {
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
hostname: "custom-bind.example",
hostId: "host-custom-bind",
port: 22,
username: "root",
password: "secret",
verifyHostKeys: false,
useSshAgent: false,
reuseTransport: true,
};
const customHooks = {
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
tunnelState.status = "active";
return { success: true };
},
};
const first = await startPortForward(event, { ...basePayload, tunnelId: "pf-custom-bind-1" }, customHooks);
assert.equal(first.success, true);
assert.equal(connectCount, 1);
assert.equal(
getTransportStats().pendingDials,
0,
"custom bindChannels must not leave an unsettled pendingDialCoordination in sshConnectionPool",
);
await stopPortForward(event, { tunnelId: "pf-custom-bind-1" });
// Before the fix, the second dial joined the leaked leader coordination and hung forever.
const second = await startPortForward(event, { ...basePayload, tunnelId: "pf-custom-bind-2" }, customHooks);
assert.equal(second.success, true);
assert.equal(connectCount, 2, "second dial must establish a fresh SSH connection instead of deadlocking");
assert.equal(getTransportStats().pendingDials, 0);
await stopPortForward(event, { tunnelId: "pf-custom-bind-2" });
});
test("startPortForward settles pendingDialCoordination for single-channel SSH peers", async (t) => {
resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 });
t.after(() => resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 }));
const ssh2 = require("ssh2");
const originalConnect = ssh2.Client.prototype.connect;
const originalEnd = ssh2.Client.prototype.end;
ssh2.Client.prototype.connect = function fakeSingleChannelConnect() {
this._remoteVer = "SSH-2.0-BHostSSH_7.0";
this._sock = { destroyed: false, writableEnded: false, setTimeout() {} };
setImmediate(() => this.emit("ready"));
return this;
};
ssh2.Client.prototype.end = function fakeEnd() {
setImmediate(() => this.emit("close"));
return this;
};
t.after(() => {
ssh2.Client.prototype.connect = originalConnect;
ssh2.Client.prototype.end = originalEnd;
});
const event = { sender: createSender() };
const result = await startPortForward(event, {
tunnelId: "pf-single-channel-1",
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 80,
hostname: "single-channel.example",
hostId: "host-single-channel",
port: 22,
username: "root",
password: "secret",
verifyHostKeys: false,
useSshAgent: false,
reuseTransport: true,
});
assert.equal(result.success, true);
assert.equal(
getTransportStats().pendingDials,
0,
"single-channel peer skipping transport registration must still clear pendingDialCoordination",
);
await stopPortForward(event, { tunnelId: "pf-single-channel-1" });
});
+9 -28
View File
@@ -1322,6 +1322,10 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
sendStatus('error', error?.message || String(error));
throw error;
}
if (isTunnelCancelled(tunnelState)) {
portForwardingTunnels.delete(tunnelId);
return { tunnelId, success: false, cancelled: true };
}
const abandonPendingDial = (reason) => {
if (!pendingDialCoordination) return;
failTransportDial(
@@ -1329,11 +1333,6 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
reason instanceof Error ? reason : new Error(String(reason || "Port forward connection cancelled")),
);
};
if (isTunnelCancelled(tunnelState)) {
portForwardingTunnels.delete(tunnelId);
abandonPendingDial("Port forward connection cancelled");
return { tunnelId, success: false, cancelled: true };
}
// Prefer an already-authenticated transport (live terminal or idle park).
if (existingTransport?.conn) {
@@ -1745,7 +1744,7 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
console.log(`[PortForward] SSH connection ready for tunnel ${tunnelId}`);
const peerSingleChannelSsh = remoteSoftwareRequiresSingleChannel(conn._remoteVer);
Promise.resolve().then(() => bindChannels({
bindChannels({
type,
conn,
tunnelId,
@@ -1763,17 +1762,9 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
: reuseEndpoint,
registerTransport: allowTransportReuse && !peerSingleChannelSsh,
dialCoordination: pendingDialCoordination,
})).then((result) => {
if (pendingDialCoordination) {
// No-op when bindChannels already settled the leader via completeTransportDial().
// Guarantees custom bindChannels hooks or single-channel peers never leave an
// unsettled leader record in sshConnectionPool for later dials to hang on.
const reason = !result?.success
? new Error("Port forward cancelled before activation")
: peerSingleChannelSsh
? new Error("SSH server does not support shared transport reuse")
: new Error("Port forward did not publish a reusable SSH transport");
failTransportDial(pendingDialCoordination, reason);
}).then((result) => {
if (!result?.success && pendingDialCoordination) {
failTransportDial(pendingDialCoordination, new Error("Port forward cancelled before activation"));
}
settled = true;
resolve(result);
@@ -1851,17 +1842,7 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
conn.end();
});
try {
conn.connect(connectOpts);
} catch (connectErr) {
clearAuthReadyTimer();
if (pendingDialCoordination) failTransportDial(pendingDialCoordination, connectErr);
sendStatus('error', connectErr?.message || String(connectErr));
cleanupChainConnections(chainConnections);
portForwardingTunnels.delete(tunnelId);
settled = true;
reject(connectErr);
}
conn.connect(connectOpts);
});
}
+2 -22
View File
@@ -92,18 +92,6 @@ function hostname(value) {
));
}
function dottedPortLength(value, dotIndex, { requireSingleDigitDelimiter = false } = {}) {
if (value[dotIndex] !== ".") return 0;
const match = /^\.(0|[1-9]\d{0,4})(?![A-Za-z0-9_.])/.exec(value.slice(dotIndex, dotIndex + 7));
if (!match || Number(match[1]) > 65535) return 0;
// Require a tcpdump-like delimiter after single-digit ports on IPv4 so 5-part IDs (e.g. 1.2.3.4.5) stay intact.
if (requireSingleDigitDelimiter && match[1].length === 1
&& !/[\s>:]/.test(value[dotIndex + match[0].length] || "")) {
return 0;
}
return match[0].length;
}
function addSubnet(block, cidr) {
const { address, prefix, family } = parseCidr(cidr);
block.addSubnet(address, prefix, family);
@@ -261,9 +249,8 @@ function createRedactionSession(input, { passthroughUnknownTokens = false } = {}
for (const match of value.matchAll(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g)) {
const start = match.index;
const end = start + match[0].length;
const validTrailing = !/[A-Za-z0-9_.]/.test(value[end] || "")
|| dottedPortLength(value, end, { requireSingleDigitDelimiter: true }) > 0;
if (!/[A-Za-z0-9_.]/.test(value[start - 1] || "") && validTrailing && shouldMaskIp(match[0])) {
if (!/[A-Za-z0-9_.]/.test(value[start - 1] || "")
&& !/[A-Za-z0-9_.]/.test(value[end] || "") && shouldMaskIp(match[0])) {
add(start, end, "IP");
}
}
@@ -272,13 +259,6 @@ function createRedactionSession(input, { passthroughUnknownTokens = false } = {}
if (!address.includes(":")) continue;
// Full stops/colons can be sentence punctuation following an address.
while (address && !isIP(address) && /[.:]$/.test(address)) address = address.slice(0, -1);
if (isIP(address) !== 6) {
const dot = address.lastIndexOf(".");
if (dot > 0 && dot + dottedPortLength(value, match.index + dot) === address.length) {
const candidate = address.slice(0, dot);
if (isIP(candidate) === 6) address = candidate;
}
}
if (isIP(address) === 6 && shouldMaskIp(address)) {
add(match.index, match.index + address.length, "IP");
}
@@ -122,65 +122,6 @@ test("public IPv4 and IPv6 are hidden, including bracketed addresses and IPv4-ma
assert.equal(session.redact("invalid 999.999.999.999 and 1.2.3.4.5"), "invalid 999.999.999.999 and 1.2.3.4.5");
});
test("tcpdump dotted ip.port and ss colon ip:port forms mask addresses while preserving ports and negatives", () => {
const session = enabledSession();
const cases = [
["203.0.113.10.58326", /^\[NC_[a-f0-9]{12}_IP_\d+\]\.58326$/],
["2001:db8::1.443", /^\[NC_[a-f0-9]{12}_IP_\d+\]\.443$/],
["2001:db8::2.443:", /^\[NC_[a-f0-9]{12}_IP_\d+\]\.443:$/],
["::ffff:203.0.113.10.443", /^\[NC_[a-f0-9]{12}_IP_\d+\]\.443$/],
[
"IP 203.0.113.10.58326 > 198.51.100.20.443: Flags [S]",
/^IP \[NC_[a-f0-9]{12}_IP_\d+\]\.58326 > \[NC_[a-f0-9]{12}_IP_\d+\]\.443: Flags \[S\]$/,
],
[
"IP 203.0.113.10.7 > 198.51.100.20.9: Flags [S]",
/^IP \[NC_[a-f0-9]{12}_IP_\d+\]\.7 > \[NC_[a-f0-9]{12}_IP_\d+\]\.9: Flags \[S\]$/,
],
[
"IP6 2001:db8::1.54321 > 2001:db8::2.443: Flags [S]",
/^IP6 \[NC_[a-f0-9]{12}_IP_\d+\]\.54321 > \[NC_[a-f0-9]{12}_IP_\d+\]\.443: Flags \[S\]$/,
],
["203.0.113.10:8443", /^\[NC_[a-f0-9]{12}_IP_\d+\]:8443$/],
["[2001:db8::5]:8443", /^\[\[NC_[a-f0-9]{12}_IP_\d+\]\]:8443$/],
[
"LISTEN 0 128 203.0.113.10:443 0.0.0.0:*",
/^LISTEN 0 128 \[NC_[a-f0-9]{12}_IP_\d+\]:443 0\.0\.0\.0:\*$/,
],
["203.0.113.0/24", /^\[NC_[a-f0-9]{12}_IP_\d+\]\/24$/],
];
for (const [input, expected] of cases) {
const masked = session.redact(input);
assert.match(masked, expected, input);
assert.equal(session.restore(masked), input, input);
}
for (const unchanged of [
"Linux 6.12.111+deb13-amd64",
"10.0.0.0/8",
"203.0.113.10.example.com",
"203.0.113.10.443.example.com",
"203.0.113.10.65536",
"203.0.113.10.0080",
"2001:db8::1.65536",
"2001:db8::1.443.5",
"2001:db8::1.443.test",
"2001:db8::1.443x",
"1.2.3.4.5",
"1.2.3.4.5.6",
"1.2.3.4.5.6.7",
"1.2.3.4.5.6.7.8",
"999.999.999.999.443",
"IP 10.0.0.1.58326 > 192.168.1.2.443: Flags [S]",
]) {
assert.equal(session.redact(unchanged), unchanged, unchanged);
}
const all = enabledSession({ redactPrivateIps: true });
const privLine = "IP 10.0.0.1.58326 > 192.168.1.2.443: Flags [S]";
const maskedPriv = all.redact(privLine);
assert.match(maskedPriv, /^IP \[NC_[a-f0-9]{12}_IP_\d+\]\.58326 > \[NC_[a-f0-9]{12}_IP_\d+\]\.443: Flags \[S\]$/);
assert.equal(all.restore(maskedPriv), privLine);
});
test("private, loopback, link-local, CGNAT, and mapped private addresses are preserved by default", () => {
const session = enabledSession();
for (const address of [
+30 -68
View File
@@ -215,20 +215,9 @@ class BrowserPluginRuntime {
port1.on("close", () => this.#handleExit(new Error("Plugin message port closed")));
port1.start();
let resolvePreloadReady;
let rejectPreloadReady;
const preloadReady = new Promise((resolve, reject) => {
resolvePreloadReady = resolve;
rejectPreloadReady = reject;
});
preloadReady.catch(() => {});
const preloadReady = new Promise((resolve) => { resolvePreloadReady = resolve; });
let resolveRuntimeConnected;
let rejectRuntimeConnected;
const runtimeConnected = new Promise((resolve, reject) => {
resolveRuntimeConnected = resolve;
rejectRuntimeConnected = reject;
});
runtimeConnected.catch(() => {});
this.startupRejecters = [rejectPreloadReady, rejectRuntimeConnected];
const runtimeConnected = new Promise((resolve) => { resolveRuntimeConnected = resolve; });
const onPreloadMessage = (_event, channel) => {
if (channel === "netcatty-plugin:preload-ready") {
void this.logger.write("debug", "Plugin browser preload ready");
@@ -240,7 +229,6 @@ class BrowserPluginRuntime {
}
};
contents.on("ipc-message", onPreloadMessage);
let port2Transferred = false;
const loading = contents.loadURL(this.registration.url);
let preloadTimer;
const preloadDeadline = new Promise((_, reject) => {
@@ -250,41 +238,32 @@ class BrowserPluginRuntime {
);
});
try {
try {
await Promise.race([
preloadReady,
preloadDeadline,
loading.then(() => preloadReady),
]);
} finally {
clearTimeout(preloadTimer);
}
this.#assertStarting(signal);
port2Transferred = true;
contents.postMessage("netcatty-plugin:connect", null, [port2]);
let connectionTimer;
const connectionDeadline = new Promise((_, reject) => {
connectionTimer = setTimeout(
() => reject(new Error("Plugin browser runtime did not accept its message port")),
PLUGIN_ACTIVATION_TIMEOUT_MS,
);
});
try {
await Promise.all([
loading,
Promise.race([runtimeConnected, connectionDeadline]),
]);
} finally {
clearTimeout(connectionTimer);
}
await Promise.race([
preloadReady,
preloadDeadline,
loading.then(() => preloadReady),
]);
} finally {
this.startupRejecters = null;
clearTimeout(preloadTimer);
}
this.#assertStarting(signal);
contents.postMessage("netcatty-plugin:connect", null, [port2]);
let connectionTimer;
const connectionDeadline = new Promise((_, reject) => {
connectionTimer = setTimeout(
() => reject(new Error("Plugin browser runtime did not accept its message port")),
PLUGIN_ACTIVATION_TIMEOUT_MS,
);
});
try {
await Promise.all([
loading,
Promise.race([runtimeConnected, connectionDeadline]),
]);
} finally {
clearTimeout(connectionTimer);
contents.removeListener("ipc-message", onPreloadMessage);
if (!port2Transferred) {
try { port2.close(); } catch {}
}
}
this.connected = true;
this.#assertStarting(signal);
const initialized = await this.router.request("plugin.initialize", {
netcattyVersion: config.netcattyVersion,
@@ -302,28 +281,16 @@ class BrowserPluginRuntime {
return initialized;
}
stop() {
this.stopPromise ??= this.#stop();
return this.stopPromise;
}
async #stop() {
async stop() {
if (this.stopping) return;
this.stopping = true;
if (this.startupRejecters) {
const stopErr = new Error("Plugin browser runtime stopped");
for (const reject of this.startupRejecters) reject(stopErr);
this.startupRejecters = null;
}
try {
if (this.connected) {
await this.router?.request("plugin.deactivate", {}, {
timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS,
});
}
await this.router?.request("plugin.deactivate", {}, {
timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS,
});
} finally {
const router = this.router;
this.router = null;
this.connected = false;
router?.close();
this.port?.close();
this.registration?.dispose();
@@ -353,14 +320,9 @@ class BrowserPluginRuntime {
}
#handleExit(error) {
if (this.startupRejecters) {
for (const reject of this.startupRejecters) reject(error);
this.startupRejecters = null;
}
if (!this.router) return;
const router = this.router;
this.router = null;
this.connected = false;
router.close(error);
this.port?.close();
this.registration?.dispose();
+2 -4
View File
@@ -156,7 +156,7 @@ class PluginByteStreamBroker {
reason: String(socket.authorizationError || "UNTRUSTED_CERT").slice(0, 256),
});
const decision = await raceWithAbort(
Promise.resolve(this.confirmTlsCert(certInfo, state, { ...context, signal: state.controller.signal })),
Promise.resolve(this.confirmTlsCert(certInfo, state, context)),
state.controller.signal,
);
await this.active(state, context);
@@ -216,7 +216,6 @@ class PluginByteStreamBroker {
await this.active(state, context);
state.connectTimer = setTimeout(() => this.finish(state,
failure("deadlineExceeded", "Byte stream connect timeout")), state.limits.connectMs);
state.connectTimer.unref?.();
let socket;
const effectiveServername = servername ?? (net.isIP(target.host) ? undefined : target.host);
if (hostTransport) {
@@ -271,8 +270,6 @@ class PluginByteStreamBroker {
if (!hostTransport) await raceWithAbort(new Promise((resolve) => socket.once(
target.transport === "tls" ? "secureConnect" : "connect", resolve,
)), state.controller.signal);
clearTimeout(state.connectTimer);
state.connectTimer = null;
await this.active(state, context);
if (target.transport === "tls" && !socket.authorized) {
if (!allowSelfSigned) {
@@ -280,6 +277,7 @@ class PluginByteStreamBroker {
}
await this.#verifyUntrustedTlsSocket(socket, state, context, effectiveServername);
}
clearTimeout(state.connectTimer);
state.lifetimeTimer = setTimeout(() => this.finish(state,
failure("deadlineExceeded", "Byte stream lifetime exceeded")), state.limits.lifetimeMs);
state.lifetimeTimer.unref?.();
+1 -18
View File
@@ -323,27 +323,11 @@ class PluginByteStreamService {
registry.registerRequest("network.stream.upgradeTls", async ({ handleId, servername, allowSelfSigned, caPem }, caller) => {
const context = await this.authenticate(caller);
const record = this.get(handleId, context);
const signals = [context.signal, record.context.signal].filter(Boolean);
const combinedSignal = signals.length > 1
? AbortSignal.any(signals)
: signals[0];
const upgradeContext = {
...record.context,
signal: combinedSignal,
assertActive: async () => {
await context.assertActive();
await record.context.assertActive();
},
assertCommit: () => {
context.assertCommit?.();
record.context.assertCommit?.();
},
};
return this.broker.upgradeTls(handleId, {
...(servername === undefined ? {} : { servername }),
allowSelfSigned: allowSelfSigned === true,
...(caPem === undefined ? {} : { caPem }),
}, upgradeContext);
}, record.context);
}, { validateParams: validator("ByteStreamUpgradeTlsRequest"), metadata: { capability: "network.stream", mutating: true, public: true } });
registry.registerRequest("network.stream.attach", async ({ handleId }, caller) => {
@@ -378,7 +362,6 @@ class PluginByteStreamService {
const record = [...this.records.values()].find((item) => item.inputStreamId === stream.streamId);
if (!record) return false;
const context = await this.authenticate(caller);
if (record.closing || this.records.get(record.handleId) !== record) return false;
this.get(record.handleId, context);
if (record.input || stream.windowBytes !== LIMITS.bufferBytes) throw denied();
record.input = stream;
+3 -31
View File
@@ -53,12 +53,6 @@ function probeTcpReachability({ host, port, timeoutMs, signal }) {
socket.once("timeout", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
socket.once("end", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
socket.once("close", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
});
socket.once("timeout", onConnectTimeout);
socket.once("error", (err) => finish({ reachable: false, protocol: "ssh", port, rttMs: null, bannerVerified: false, error: String(err?.message || "Connection failed").slice(0, 256) }));
@@ -278,12 +272,7 @@ class PluginHostCapabilitiesService {
for (const op of ["start", "stop", "delete"]) {
registry.registerRequest(`portForward.${op}`, async (params, context) => {
await context.assertActive();
return this.vaultDataBridge.request(
`portForward.${op}`,
{ ruleId: params.ruleId },
context.signal,
op === "start" ? { timeoutMs: 30_000 } : undefined,
);
return this.vaultDataBridge.request(`portForward.${op}`, { ruleId: params.ruleId }, context.signal);
}, {
metadata: { capability: "portForward", mutating: true },
validateParams: (params) => this.#validate("PortForwardRuleIdParams", params),
@@ -492,19 +481,11 @@ class PluginHostCapabilitiesService {
port: configuredPort,
securityMode: target.rdpSecurityMode || "auto",
mode: "heartbeat",
connectTimeoutMs: timeoutMs,
tcpTimeoutMs: timeoutMs,
handshakeTimeoutMs: Math.min(timeoutMs, 3_000),
},
{ signal: controller.signal },
);
if (this.closed || this.isLocked()) {
throw fail("unavailable", "Host probe is unavailable");
}
if (controller.signal.aborted) {
throw controller.signal.reason instanceof PluginRpcError
? controller.signal.reason
: fail("cancelled", "Host probe cancelled");
}
return {
reachable: Boolean(res?.ok || res?.reachable),
protocol,
@@ -517,16 +498,7 @@ class PluginHostCapabilitiesService {
};
}
const tcpRes = await this.probeTcp({ host: target.hostname, port: configuredPort, timeoutMs, signal: controller.signal });
if (this.closed || this.isLocked()) {
throw fail("unavailable", "Host probe is unavailable");
}
if (controller.signal.aborted) {
throw controller.signal.reason instanceof PluginRpcError
? controller.signal.reason
: fail("cancelled", "Host probe cancelled");
}
return tcpRes;
return await this.probeTcp({ host: target.hostname, port: configuredPort, timeoutMs, signal: controller.signal });
} finally {
context.signal?.removeEventListener("abort", onAbort);
this.activeProbes.delete(lease);
+5 -20
View File
@@ -630,10 +630,6 @@ class PluginHostInteractionService {
await fs.unlink(stagingPath).catch(() => {});
throw error;
}
if (this.fileHandles.get(handle.id) !== handle) {
await fs.unlink(stagingPath).catch(() => {});
throw fail("unavailable", "File handle was closed during write");
}
handle.stagingPath = stagingPath;
handle.stagingBytes = buf.byteLength;
} else {
@@ -653,11 +649,11 @@ class PluginHostInteractionService {
}
const totalSize = handle.stagingBytes;
if (commit) {
await context.assertActive();
const temp = handle.stagingPath;
handle.stagingPath = null;
handle.stagingBytes = 0;
try {
await context.assertActive();
await fs.rename(temp, handle.filePath);
} catch (error) {
await fs.unlink(temp).catch(() => {});
@@ -691,7 +687,7 @@ class PluginHostInteractionService {
setReady(sender, ready) {
const window = this.getWindow();
if (!sender || !window || window.isDestroyed?.() || window.webContents !== sender || sender.isDestroyed?.()) {
if (!sender || window?.webContents !== sender || sender.isDestroyed?.()) {
throw fail("permissionDenied", "Host interaction window is not the owner");
}
if (typeof ready !== "boolean") throw fail("invalidArgument", "Host interaction readiness is invalid");
@@ -730,7 +726,7 @@ class PluginHostInteractionService {
#assertWindow(sender = this.owner) {
const window = this.getWindow();
if (this.closed || this.isLocked() || !sender || sender !== this.owner
|| !window || window.isDestroyed?.() || window.webContents !== sender
|| window?.webContents !== sender || window.isDestroyed?.()
|| sender.isDestroyed?.() || window.isVisible?.() === false || window.isFocused?.() !== true) {
throw fail("unavailable", "Host interactions require the focused unlocked main window");
}
@@ -824,8 +820,8 @@ class PluginHostInteractionService {
throw fail("cancelled", "Host interaction admission was revoked");
}
const window = this.getWindow();
if (this.closed || this.isLocked() || !window || window.isDestroyed?.() || window.webContents !== admission.sender
|| admission.sender.isDestroyed?.() || window.isVisible?.() === false) {
if (this.closed || this.isLocked() || window?.webContents !== admission.sender
|| window.isDestroyed?.() || admission.sender.isDestroyed?.() || window.isVisible?.() === false) {
throw fail("unavailable", "Host interaction owner is unavailable");
}
if (window.isFocused?.() === true) break;
@@ -939,14 +935,6 @@ class PluginHostInteractionService {
});
}
if (this.vaultService?.isRequest(entry.params)) {
const hostStreamConnectMs = schema.$defs.HostByteStreamLimits?.const?.connectMs ?? 120_000;
if (entry.params.kind === "network.stream.connectViaHost" && response.action === "commit") {
const extendedMs = Math.max(this.timeoutMs, hostStreamConnectMs);
if (entry.timer) clearTimeout(entry.timer);
entry.expiresAt = this.clock() + extendedMs;
entry.timer = setTimeout(() => this.#finish(entry, null, fail("deadlineExceeded", "Host interaction expired")), extendedMs);
entry.timer.unref?.();
}
const outcome = await this.vaultService.respond(entry, response, nativeOptions);
await entry.context.assertActive();
this.#assertWindow(sender);
@@ -984,9 +972,6 @@ class PluginHostInteractionService {
let rawText;
try { rawText = await this.clipboard.readText(); }
catch { throw fail("unavailable", "Host clipboard text is unavailable"); }
await entry.context.assertActive();
this.#assertWindow(sender);
if (this.pending.get(entry.id) !== entry) return false;
const text = assertTextBytes(rawText, LIMITS.clipboardBytes);
this.quotaManager.chargeBytes(entry.context.runtimeId, "clipboard", Buffer.byteLength(text));
entry.previewText = text;
+122 -484
View File
@@ -12,18 +12,6 @@ const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
const DEFAULT_IDLE_TTL_MS = 120_000;
const DEFAULT_MAX_CONCURRENT_PER_RUNTIME = 16;
const DEFAULT_MAX_CONCURRENT_TOTAL = 64;
// Tighter than interactive SSH defaults (20s TCP / 120s auth) so background
// plugin dials fail with a clear timeout before the ~30s plugin RPC deadline
// (interactive prompts such as host-key/passphrase/2FA still share that RPC budget).
const DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS = 8_000;
const DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS = 8_000;
const DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS = 18_000;
// resolveSshConnectionTimeouts() ignores values below 1000ms and falls back to 20s/120s.
const MIN_SSH_CONNECT_STAGE_TIMEOUT_MS = 1_000;
function positiveMs(value, fallback) {
return Number.isFinite(value) && value > 0 ? Math.round(value) : fallback;
}
let vendorDetectorPromise = null;
function loadVendorDetector() {
@@ -37,9 +25,8 @@ function loadVendorDetector() {
* Host-owned pooled SSH exec transport for sandboxed plugins.
*
* - Reuses Netcatty's main-process SSH dialer (`portForwardingBridge.startPortForward`
* with `reuseTransport: false` and `bindChannels`), inheriting jump hosts, proxies,
* passphrase prompts, FIDO2, and host-key verification while keeping plugin
* connections isolated in this transport's own `(runtimeId, hostId)` pool.
* with `reuseTransport: true` and `bindChannels`), inheriting jump hosts, proxies,
* passphrase prompts, FIDO2, and host-key verification.
* - Caches live authenticated `ssh2` transports per `(runtimeId, hostId)` with idle
* eviction so periodic monitoring polls execute in ~5-30ms without new SSH handshakes
* or renderer IPC roundtrips.
@@ -54,25 +41,13 @@ class PluginHostSshExecTransport {
this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
this.maxConcurrentPerRuntime = options.maxConcurrentPerRuntime ?? DEFAULT_MAX_CONCURRENT_PER_RUNTIME;
this.maxConcurrentTotal = options.maxConcurrentTotal ?? DEFAULT_MAX_CONCURRENT_TOTAL;
this.sshTcpConnectTimeoutMs = positiveMs(
options.sshTcpConnectTimeoutMs,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
);
this.sshAuthReadyTimeoutMs = positiveMs(
options.sshAuthReadyTimeoutMs,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
);
this.sshDialEnvelopeMs = positiveMs(
options.sshDialEnvelopeMs,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
);
this.clock = options.clock ?? Date.now;
this.isLocked = options.isLocked ?? (() => false);
this.getSender = options.getSender ?? (() => null);
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> pooled entry */
this.connections = new Map();
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> in-flight dial record */
/** @type {Map<string, Promise<object>>} `${runtimeId}\0${hostId}` -> in-flight dial */
this.pendingDials = new Map();
/** @type {Set<{ controller: AbortController, runtimeId: string, pluginId: string, hostId: string }>} */
this.activeExecs = new Set();
@@ -94,165 +69,10 @@ class PluginHostSshExecTransport {
#isEntryHealthy(entry) {
if (!entry || entry.closed || !entry.conn) return false;
const sock = entry.conn._sock;
if (sock && (
sock.destroyed
|| sock.writableEnded
|| sock.readableEnded
|| sock.writableFinished
|| sock.writable === false
|| sock.readyState === "closed"
|| sock.readyState === "readOnly"
)) {
return false;
}
if (sock && (sock.destroyed || sock.writableEnded)) return false;
return true;
}
#isDeadlineAbort(signal) {
if (!signal?.aborted) return false;
const reason = signal.reason;
if (!reason) return false;
if (reason.code === RPC_ERRORS.deadlineExceeded) return true;
const message = typeof reason === "string" ? reason : String(reason?.message ?? "");
return /plugin (?:request|notification) deadline exceeded/i.test(message);
}
#isConnectTimeoutError(err) {
if (!err) return false;
if (err?.code === "ETIMEDOUT" || err?.code === RPC_ERRORS.deadlineExceeded) return true;
const message = typeof err === "string" ? err : String(err?.message ?? "");
return /\btimed?\s*out\b|\btimeout\b/i.test(message);
}
#callerAbortError(signal, fallbackMessage = "SSH connection was cancelled") {
if (signal?.reason instanceof PluginRpcError) return signal.reason;
if (this.#isDeadlineAbort(signal)) {
return fail("deadlineExceeded", "Plugin request deadline exceeded");
}
return fail("cancelled", fallbackMessage);
}
#dialAbortError(dialRecord) {
if (dialRecord.timedOut) {
return fail("deadlineExceeded", "SSH connection timed out");
}
const reason = dialRecord.controller.signal.reason;
if (reason instanceof PluginRpcError) return reason;
if (dialRecord.cancelledByWaiters) {
return fail("cancelled", "SSH connection was cancelled");
}
return fail("unavailable", "Host SSH execution is unavailable");
}
#isStopConfirmed(result) {
return result?.success === true;
}
#clearStopRetryTimer(dialRecord) {
if (dialRecord?.stopRetryTimer) {
clearTimeout(dialRecord.stopRetryTimer);
dialRecord.stopRetryTimer = null;
}
}
#scheduleStopRetry(dialRecord) {
if (
!dialRecord
|| !dialRecord.tunnelId
|| !dialRecord.stopRequested
|| dialRecord.stopConfirmed
|| dialRecord.dialDone
|| dialRecord.settled
|| dialRecord.stopRetryTimer
) {
return;
}
const maxAttempts = Math.min(200, Math.max(25, Math.ceil(this.sshDialEnvelopeMs / 100)));
const attempt = dialRecord.stopRetryAttempts ?? 0;
if (attempt >= maxAttempts) {
return;
}
const delayMs = Math.min(100, 10 * (2 ** Math.min(attempt, 4)));
dialRecord.stopRetryAttempts = attempt + 1;
dialRecord.stopRetryTimer = setTimeout(() => {
dialRecord.stopRetryTimer = null;
if (
!dialRecord.stopRequested
|| dialRecord.stopConfirmed
|| dialRecord.dialDone
|| dialRecord.settled
) {
return;
}
void this.#stopDialTunnel(dialRecord);
}, delayMs);
dialRecord.stopRetryTimer.unref?.();
}
async #stopDialTunnel(dialRecord, { afterDialReturn = false } = {}) {
if (!dialRecord?.tunnelId) return false;
dialRecord.stopRequested = true;
this.#clearStopRetryTimer(dialRecord);
if (dialRecord.stopConfirmed) return true;
if (dialRecord.stopInFlight) {
if (!afterDialReturn) {
return dialRecord.stopInFlight;
}
while (dialRecord.stopInFlight) {
await dialRecord.stopInFlight;
}
if (dialRecord.stopConfirmed) return true;
}
const { tunnelId, sender } = dialRecord;
const stopPromise = (async () => {
try {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
} catch { /* ignore */ }
let result = null;
try {
result = await this.#bridge().stopPortForward({ sender }, { tunnelId });
} catch {
result = null;
}
if (this.#isStopConfirmed(result)) {
dialRecord.stopConfirmed = true;
this.#clearStopRetryTimer(dialRecord);
return true;
}
if (!dialRecord.dialDone && !dialRecord.settled && dialRecord.stopRequested) {
this.#scheduleStopRetry(dialRecord);
}
return false;
})();
const tracked = stopPromise.finally(() => {
if (dialRecord.stopInFlight === tracked) {
dialRecord.stopInFlight = null;
}
});
dialRecord.stopInFlight = tracked;
return tracked;
}
#cancelPendingDial(dialRecord, reason) {
if (!dialRecord) return;
dialRecord.stopRequested = true;
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(dialRecord.key) === dialRecord) {
this.pendingDials.delete(dialRecord.key);
}
if (!dialRecord.settled && dialRecord.tunnelId) {
void this.#stopDialTunnel(dialRecord);
}
if (!dialRecord.controller.signal.aborted) {
dialRecord.controller.abort(reason);
}
}
#touchIdleTimer(entry) {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
if (entry.closed || this.idleTtlMs <= 0) return;
@@ -282,9 +102,6 @@ class PluginHostSshExecTransport {
}
async #dialEntry({ runtimeId, pluginId, hostId, prepareConnection, signal }) {
if (signal?.aborted) {
throw this.#callerAbortError(signal);
}
const key = this.#key(runtimeId, hostId);
const existing = this.connections.get(key);
if (this.#isEntryHealthy(existing)) {
@@ -294,280 +111,126 @@ class PluginHostSshExecTransport {
void this.#closeEntry(existing);
}
const attachWaiter = (dialRecord) => {
if (signal?.aborted) {
return Promise.reject(this.#callerAbortError(signal));
}
if (dialRecord.controller.signal.aborted && !dialRecord.settled) {
return Promise.reject(this.#dialAbortError(dialRecord));
}
dialRecord.waiterCount += 1;
let released = false;
const releaseWaiter = (abortedByCaller) => {
if (released) return;
released = true;
dialRecord.waiterCount = Math.max(0, dialRecord.waiterCount - 1);
// Tear down the shared dial only when the last waiter leaves while
// still in flight so retries do not hitchhike on a wedged handshake.
// Keep dialing when another waiter remains, and never stop a settled entry.
if (abortedByCaller && dialRecord.waiterCount === 0 && !dialRecord.settled) {
dialRecord.cancelledByWaiters = true;
this.#cancelPendingDial(dialRecord, fail("cancelled", "SSH connection was cancelled"));
}
};
const raceCallerSignal = (promise) => {
if (!signal) return promise;
if (signal.aborted) return Promise.reject(fail("cancelled", "SSH connection was cancelled"));
return new Promise((resolve, reject) => {
const dialSignal = dialRecord.controller.signal;
const cleanup = () => {
signal?.removeEventListener("abort", onCallerAbort);
dialSignal.removeEventListener("abort", onDialAbort);
};
const onCallerAbort = () => {
cleanup();
releaseWaiter(true);
reject(this.#callerAbortError(signal));
};
const onDialAbort = () => {
cleanup();
releaseWaiter(false);
reject(this.#dialAbortError(dialRecord));
};
signal?.addEventListener("abort", onCallerAbort, { once: true });
dialSignal.addEventListener("abort", onDialAbort, { once: true });
dialRecord.promise.then(
(val) => {
cleanup();
releaseWaiter(false);
resolve(val);
},
(err) => {
cleanup();
releaseWaiter(false);
reject(err);
},
const onAbort = () => reject(fail("cancelled", "SSH connection was cancelled"));
signal.addEventListener("abort", onAbort, { once: true });
promise.then(
(val) => { signal.removeEventListener("abort", onAbort); resolve(val); },
(err) => { signal.removeEventListener("abort", onAbort); reject(err); },
);
});
};
const inflight = this.pendingDials.get(key);
if (inflight) {
return attachWaiter(inflight);
return raceCallerSignal(inflight.promise);
}
const dialStartedAt = this.clock();
const envelopeMs = this.sshDialEnvelopeMs;
const dialController = new AbortController();
const dialRecord = {
key,
controller: dialController,
promise: null,
runtimeId,
pluginId,
hostId,
waiterCount: 0,
settled: false,
cancelledByWaiters: false,
timedOut: false,
tunnelId: null,
sender: null,
stopRequested: false,
stopConfirmed: false,
stopInFlight: null,
stopRetryTimer: null,
stopRetryAttempts: 0,
dialDone: false,
envelopeTimer: null,
};
this.pendingDials.set(key, dialRecord);
dialRecord.envelopeTimer = setTimeout(() => {
dialRecord.envelopeTimer = null;
if (dialRecord.settled) return;
dialRecord.timedOut = true;
this.#cancelPendingDial(dialRecord, fail("deadlineExceeded", "SSH connection timed out"));
}, envelopeMs);
dialRecord.envelopeTimer.unref?.();
const dialPromise = (async () => {
try {
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
let connectionOptions;
try {
connectionOptions = await prepareConnection(hostId, dialController.signal);
} catch (err) {
if (dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
throw err;
}
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
if (!connectionOptions || typeof connectionOptions !== "object") {
throw fail("unavailable", "Could not prepare SSH connection for host");
}
if (connectionOptions.singleChannelSsh) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
const detectVendor = await loadVendorDetector();
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
const elapsedMs = Math.max(0, this.clock() - dialStartedAt);
const remainingMs = envelopeMs - elapsedMs;
if (remainingMs <= 0) {
dialRecord.timedOut = true;
throw fail("deadlineExceeded", "SSH connection timed out");
}
const minStageMs = Math.min(
MIN_SSH_CONNECT_STAGE_TIMEOUT_MS,
this.sshTcpConnectTimeoutMs,
this.sshAuthReadyTimeoutMs,
);
const stageBudgetMs = Math.max(minStageMs, Math.round(remainingMs));
const sshTcpConnectTimeoutMs = Math.min(this.sshTcpConnectTimeoutMs, stageBudgetMs);
const sshAuthReadyTimeoutMs = Math.min(this.sshAuthReadyTimeoutMs, stageBudgetMs);
const sender = this.getSender();
const bridge = this.#bridge();
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
throw this.#dialAbortError(dialRecord);
}
const tunnelId = `plugin-exec-${randomUUID()}`;
const event = { sender };
dialRecord.tunnelId = tunnelId;
dialRecord.sender = sender;
let liveConn = null;
let rejectedUnsupported = false;
let result;
try {
result = await bridge.startPortForward(
event,
{
...connectionOptions,
tunnelId,
ruleId: undefined,
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
reuseTransport: false,
sshTcpConnectTimeoutMs,
sshAuthReadyTimeoutMs,
},
{
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
rejectedUnsupported = true;
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
}
liveConn = conn;
tunnelState.status = "active";
return { success: true };
},
},
);
} catch (err) {
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
if (rejectedUnsupported) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
if (this.#isConnectTimeoutError(err)) {
throw fail("deadlineExceeded", "SSH connection timed out");
}
if (err instanceof PluginRpcError) throw err;
throw fail("unavailable", "Could not connect to the selected SSH server");
}
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
if (rejectedUnsupported) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
throw this.#dialAbortError(dialRecord);
}
if (!result?.success || !liveConn) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
if (result?.cancelled) {
throw fail("cancelled", "SSH connection was cancelled");
}
if (this.#isConnectTimeoutError(result?.error)) {
throw fail("deadlineExceeded", "SSH connection timed out");
}
throw fail("unavailable", "Could not connect to the selected SSH server");
}
const entry = {
key,
runtimeId,
pluginId,
hostId,
tunnelId,
sender,
conn: liveConn,
closed: false,
activeCount: 0,
idleTimer: null,
};
const onConnDead = () => {
void this.#closeEntry(entry);
};
liveConn.once?.("close", onConnDead);
liveConn.once?.("end", onConnDead);
liveConn.once?.("error", onConnDead);
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
await this.#closeEntry(entry);
throw this.#dialAbortError(dialRecord);
}
// Publish and mark settled synchronously before resolving so a waiter
// abort in the settlement microtask cannot tear down the pooled entry.
dialRecord.settled = true;
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
this.connections.set(key, entry);
this.#touchIdleTimer(entry);
return entry;
} finally {
dialRecord.settled = true;
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw fail("unavailable", "Host SSH execution is unavailable");
}
const connectionOptions = await prepareConnection(hostId, dialController.signal);
if (!connectionOptions || typeof connectionOptions !== "object") {
throw fail("unavailable", "Could not prepare SSH connection for host");
}
if (connectionOptions.singleChannelSsh) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw fail("unavailable", "Host SSH execution is unavailable");
}
const sender = this.getSender();
const tunnelId = `plugin-exec-${randomUUID()}`;
const event = { sender };
let liveConn = null;
let rejectedUnsupported = false;
const detectVendor = await loadVendorDetector();
const result = await this.#bridge().startPortForward(
event,
{
...connectionOptions,
tunnelId,
ruleId: undefined,
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
reuseTransport: true,
},
{
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
rejectedUnsupported = true;
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
}
liveConn = conn;
tunnelState.status = "active";
return { success: true };
},
},
);
if (rejectedUnsupported) {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (!result?.success || !liveConn) {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
throw fail("unavailable", "Could not connect to the selected SSH server");
}
const entry = {
key,
runtimeId,
pluginId,
hostId,
tunnelId,
sender,
conn: liveConn,
closed: false,
activeCount: 0,
idleTimer: null,
};
const onConnDead = () => {
void this.#closeEntry(entry);
};
liveConn.once?.("close", onConnDead);
liveConn.once?.("end", onConnDead);
liveConn.once?.("error", onConnDead);
if (this.closed || this.isLocked() || dialController.signal.aborted) {
await this.#closeEntry(entry);
throw fail("unavailable", "Host SSH execution is unavailable");
}
this.connections.set(key, entry);
this.#touchIdleTimer(entry);
return entry;
})();
dialRecord.promise = dialPromise;
dialPromise.catch(() => {});
return attachWaiter(dialRecord);
const dialRecord = { controller: dialController, promise: dialPromise, runtimeId, pluginId, hostId };
this.pendingDials.set(key, dialRecord);
const cleanupPending = () => {
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
};
dialPromise.then(cleanupPending, cleanupPending);
return raceCallerSignal(dialPromise);
}
/**
@@ -586,19 +249,15 @@ class PluginHostSshExecTransport {
const controller = new AbortController();
const lease = { controller, runtimeId, pluginId, hostId };
this.activeExecs.add(lease);
let entry = null;
let acquired = false;
const onCallerAbort = () => {
controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
if (entry && acquired && this.#isDeadlineAbort(controller.signal)) {
void this.#closeEntry(entry);
}
};
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
if (signal?.aborted) {
this.activeExecs.delete(lease);
throw this.#callerAbortError(signal, "SSH operation was cancelled");
throw fail("cancelled", "SSH operation was cancelled");
}
signal?.addEventListener("abort", onCallerAbort, { once: true });
let entry = null;
let acquired = false;
try {
await assertActive?.();
controller.signal.throwIfAborted();
@@ -611,10 +270,6 @@ class PluginHostSshExecTransport {
});
await assertActive?.();
controller.signal.throwIfAborted();
if (!this.#isEntryHealthy(entry)) {
void this.#closeEntry(entry);
throw fail("unavailable", "Host SSH connection closed before acquisition");
}
entry.activeCount += 1;
acquired = true;
if (entry.idleTimer) {
@@ -675,7 +330,7 @@ class PluginHostSshExecTransport {
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH command was cancelled"));
if (signal?.aborted) {
this.activeExecs.delete(lease);
throw this.#callerAbortError(signal, "SSH command was cancelled");
throw fail("cancelled", "SSH command was cancelled");
}
signal?.addEventListener("abort", onCallerAbort, { once: true });
@@ -696,10 +351,6 @@ class PluginHostSshExecTransport {
await assertActive?.();
controller.signal.throwIfAborted();
if (!this.#isEntryHealthy(entry)) {
void this.#closeEntry(entry);
throw fail("unavailable", "Host SSH connection closed before execution");
}
entry.activeCount += 1;
acquired = true;
@@ -720,20 +371,10 @@ class PluginHostSshExecTransport {
runTimeoutMs: timeoutMs,
maxOutputBytes,
signal: controller.signal,
// Leave transport teardown to this plugin transport so a healthy
// user cancel preserves the pool while open-timeout/deadline evicts.
invalidateTransportOnAbort: false,
});
} catch (err) {
const isDeadlineAbort = this.#isDeadlineAbort(controller.signal);
if (
!this.#isEntryHealthy(entry)
|| err?.code === "ECONNRESET"
|| err?.code === "EPIPE"
|| err?.code === "SSH_EXEC_OPEN_TIMEOUT"
|| err?.code === "SSH_EXEC_OPEN_PENDING"
|| isDeadlineAbort
) {
if (!this.#isEntryHealthy(entry) || err?.code === "ECONNRESET" || err?.code === "EPIPE") {
void this.#closeEntry(entry);
}
if (err instanceof PluginRpcError) throw err;
@@ -741,7 +382,7 @@ class PluginHostSshExecTransport {
throw fail("resourceExhausted", "SSH command output exceeded the configured byte limit");
}
if (controller.signal.aborted) {
throw this.#callerAbortError(controller.signal, "SSH command was cancelled");
throw fail("cancelled", "SSH command was cancelled");
}
if (/timed out/i.test(String(err?.message ?? ""))) {
throw fail("deadlineExceeded", "SSH command timed out");
@@ -781,7 +422,7 @@ class PluginHostSshExecTransport {
releaseHost(pluginId, hostId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.pluginId === pluginId && dial.hostId === hostId) {
this.#cancelPendingDial(dial, fail("permissionDenied", "Host binding was revoked"));
dial.controller.abort(fail("permissionDenied", "Host binding was revoked"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -799,7 +440,7 @@ class PluginHostSshExecTransport {
releaseRuntime(runtimeId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.runtimeId === runtimeId) {
this.#cancelPendingDial(dial, fail("cancelled", "Plugin runtime stopped"));
dial.controller.abort(fail("cancelled", "Plugin runtime stopped"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -817,7 +458,7 @@ class PluginHostSshExecTransport {
releasePlugin(pluginId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.pluginId === pluginId) {
this.#cancelPendingDial(dial, fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
dial.controller.abort(fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -834,7 +475,7 @@ class PluginHostSshExecTransport {
closeAll(reason = "Host SSH execution unavailable") {
for (const dial of [...this.pendingDials.values()]) {
this.#cancelPendingDial(dial, fail("unavailable", reason));
dial.controller.abort(fail("unavailable", reason));
}
for (const lease of [...this.activeExecs]) {
lease.controller.abort(fail("unavailable", reason));
@@ -857,7 +498,4 @@ module.exports = {
DEFAULT_IDLE_TTL_MS,
DEFAULT_MAX_CONCURRENT_PER_RUNTIME,
DEFAULT_MAX_CONCURRENT_TOTAL,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
};
@@ -1,803 +0,0 @@
"use strict";
const assert = require("node:assert/strict");
const EventEmitter = require("node:events");
const test = require("node:test");
const {
PluginHostSshExecTransport,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
} = require("./hostSshExecTransport.cjs");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
function createFakeConn(sockOverrides = {}) {
const conn = new EventEmitter();
conn._remoteVer = "SSH-2.0-OpenSSH_9.6";
if (sockOverrides !== null) {
conn._sock = {
destroyed: false,
writableEnded: false,
readableEnded: false,
writableFinished: false,
writable: true,
readyState: "open",
...sockOverrides,
};
}
return conn;
}
function defaultPrepareConnection(hostId) {
return Promise.resolve({
hostId,
hostname: "10.0.0.10",
port: 22,
username: "ubuntu",
});
}
function createBaseExecArgs(overrides = {}) {
return {
runtimeId: "rt-1",
pluginId: "com.example.monitor",
hostId: "host-1",
command: "uptime",
timeoutMs: 10_000,
maxOutputBytes: 64 * 1024,
prepareConnection: defaultPrepareConnection,
...overrides,
};
}
test("last-waiter abort during in-flight dial stops tunnel, clears pendingDials, and allows fresh retry", async () => {
const sender = { id: 1 };
let dialCount = 0;
const stoppedTunnels = [];
const inflightStops = new Map();
const portForwardingBridge = {
startPortForward(_event, opts, hooks) {
dialCount += 1;
const attempt = dialCount;
if (attempt === 1) {
// First dial hangs until stopPortForward tears it down.
return new Promise((resolve) => {
inflightStops.set(opts.tunnelId, () => {
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
}
const conn = createFakeConn();
return hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
}).then(() => ({ success: true }));
},
async stopPortForward(event, { tunnelId }) {
stoppedTunnels.push({ sender: event?.sender, tunnelId });
const cancel = inflightStops.get(tunnelId);
if (cancel) {
inflightStops.delete(tunnelId);
cancel();
}
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => sender,
});
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
// Wait until startPortForward has been entered for attempt 1.
while (dialCount < 1) await new Promise((r) => setTimeout(r, 5));
assert.equal(transport.pendingDials.size, 1);
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(stoppedTunnels.length, 1, "last waiter abort must call stopPortForward");
assert.equal(stoppedTunnels[0].sender, sender);
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
assert.equal(inflightStops.size, 0, "hung startPortForward must be torn down");
// A subsequent retry must dial fresh and succeed instead of hitchhiking.
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
assert.equal(res2.stdout, "ok:retry");
assert.equal(dialCount, 2, "retry must start a new startPortForward dial");
// Completing normally must NOT stop the live pooled tunnel.
assert.equal(stoppedTunnels.length, 1);
assert.equal(transport.connections.size, 1);
transport.shutdown();
});
test("non-last waiter cancel keeps shared dial alive for remaining waiter, while cancelling all stops tunnel", async () => {
let dialCount = 0;
let stopCount = 0;
let finishDial = null;
let dialEntered = false;
const portForwardingBridge = {
startPortForward(_event, opts, hooks) {
dialCount += 1;
dialEntered = true;
return new Promise((resolve) => {
finishDial = async (cancelled = false) => {
if (cancelled) {
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
return;
}
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
resolve({ success: true });
};
});
},
async stopPortForward() {
stopCount += 1;
finishDial?.(true);
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 7,
getSender: () => ({ id: 1 }),
});
const abortA = new AbortController();
const pA = transport.exec(createBaseExecArgs({ command: "a", signal: abortA.signal }));
const pB = transport.exec(createBaseExecArgs({ command: "b" }));
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
assert.equal(dialCount, 1);
abortA.abort();
await assert.rejects(pA, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0, "aborting one of two waiters must not stop shared tunnel");
assert.equal(transport.pendingDials.size, 1);
await finishDial(false);
const resB = await pB;
assert.equal(resB.stdout, "ok:b");
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
// Now verify that cancelling ALL waiters (A then B) on a fresh host tears down the dial.
dialEntered = false;
const abortC = new AbortController();
const abortD = new AbortController();
const pC = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "c", signal: abortC.signal }));
const pD = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "d", signal: abortD.signal }));
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
assert.equal(dialCount, 2);
abortC.abort();
await assert.rejects(pC, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0);
abortD.abort();
await assert.rejects(pD, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 1, "cancelling the final remaining waiter must stop the tunnel");
assert.equal(transport.pendingDials.size, 0);
transport.shutdown();
});
test("releaseRuntime and releasePlugin stop in-flight dial tunnels", async () => {
const stopped = [];
let entered = 0;
const portForwardingBridge = {
startPortForward(_event, opts) {
entered += 1;
return new Promise(() => {
// intentionally never resolves on its own
void opts;
});
},
async stopPortForward(_event, { tunnelId }) {
stopped.push(tunnelId);
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "", stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => ({ id: 1 }),
});
const p1 = transport.exec(createBaseExecArgs({ runtimeId: "rt-1", hostId: "host-1" }));
while (entered < 1) await new Promise((r) => setTimeout(r, 5));
transport.releaseRuntime("rt-1");
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopped.length, 1);
assert.equal(transport.pendingDials.size, 0);
const p2 = transport.exec(createBaseExecArgs({ runtimeId: "rt-2", pluginId: "p-2", hostId: "host-2" }));
while (entered < 2) await new Promise((r) => setTimeout(r, 5));
transport.releasePlugin("p-2");
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.permissionDenied);
assert.equal(stopped.length, 2);
assert.equal(transport.pendingDials.size, 0);
transport.shutdown();
});
test("passes tightened SSH dial timeouts and maps connect timeout / envelope expiry to deadlineExceeded", async () => {
assert.equal(DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS, 8_000);
assert.equal(DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS, 8_000);
assert.ok(DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS >= 15_000 && DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS <= 20_000);
const seenOpts = [];
let now = 1_000;
let bridgeBehavior = "timeout-error";
let stopCount = 0;
const hungStops = new Map();
const portForwardingBridge = {
async startPortForward(_event, opts) {
seenOpts.push(opts);
if (bridgeBehavior === "timeout-error") {
throw new Error("Connection timeout to 10.0.0.10");
}
// Simulate an open hung socket handle that is torn down by stopPortForward.
return new Promise((resolve) => {
const socketHandle = setTimeout(() => {}, 10_000);
hungStops.set(opts.tunnelId, () => {
clearTimeout(socketHandle);
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
},
async stopPortForward(_event, { tunnelId }) {
stopCount += 1;
const cancel = hungStops.get(tunnelId);
if (cancel) {
hungStops.delete(tunnelId);
cancel();
}
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 5,
clock: () => now,
getSender: () => ({ id: 1 }),
});
// 1) Default connect budgets passed to startPortForward + timeout error mapping.
await assert.rejects(
transport.exec(createBaseExecArgs()),
(err) => err instanceof PluginRpcError
&& err.code === RPC_ERRORS.deadlineExceeded
&& err.message === "SSH connection timed out",
);
assert.equal(seenOpts.length, 1);
assert.equal(seenOpts[0].sshTcpConnectTimeoutMs, DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS);
assert.equal(seenOpts[0].sshAuthReadyTimeoutMs, DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS);
assert.ok(seenOpts[0].sshTcpConnectTimeoutMs < 30_000);
assert.ok(seenOpts[0].sshAuthReadyTimeoutMs < 30_000);
// 2) Slow prepareConnection shrinks remaining stage budgets (clamped >= 1000ms).
await assert.rejects(
transport.exec(createBaseExecArgs({
prepareConnection: async (hostId) => {
now += DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS - 3_500;
return defaultPrepareConnection(hostId);
},
})),
(err) => err.code === RPC_ERRORS.deadlineExceeded && err.message === "SSH connection timed out",
);
assert.equal(seenOpts.length, 2);
assert.equal(seenOpts[1].sshTcpConnectTimeoutMs, 3_500);
assert.equal(seenOpts[1].sshAuthReadyTimeoutMs, 3_500);
transport.shutdown();
// 3) Connect envelope actively aborts a hung dial before 30s and tears down the tunnel.
bridgeBehavior = "hang";
stopCount = 0;
const envelopeTransport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 5,
sshDialEnvelopeMs: 40,
getSender: () => ({ id: 1 }),
});
const startedAt = Date.now();
await assert.rejects(
envelopeTransport.exec(createBaseExecArgs()),
(err) => err instanceof PluginRpcError
&& err.code === RPC_ERRORS.deadlineExceeded
&& err.message === "SSH connection timed out",
);
const elapsed = Date.now() - startedAt;
assert.ok(elapsed < 2_000, `envelope abort should be fast, took ${elapsed}ms`);
assert.equal(stopCount, 1, "envelope abort must stop the in-flight tunnel");
assert.equal(envelopeTransport.pendingDials.size, 0);
envelopeTransport.shutdown();
});
test("health check reuses healthy sockets and re-dials half-open or closed sockets", async () => {
let dialCount = 0;
let stopCount = 0;
let currentConn = null;
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
currentConn = createFakeConn();
await hooks.bindChannels({
conn: currentConn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward() {
stopCount += 1;
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 3,
getSender: () => ({ id: 1 }),
});
// Healthy socket is reused across consecutive execs.
await transport.exec(createBaseExecArgs());
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
const unhealthyMutations = [
["writableEnded", (sock) => { sock.writableEnded = true; }],
["readableEnded", (sock) => { sock.readableEnded = true; }],
["destroyed", (sock) => { sock.destroyed = true; }],
["writableFinished", (sock) => { sock.writableFinished = true; }],
["writable=false", (sock) => { sock.writable = false; }],
["readyState=closed", (sock) => { sock.readyState = "closed"; }],
["readyState=readOnly", (sock) => { sock.readyState = "readOnly"; }],
];
let expectedDials = 1;
let expectedStops = 0;
for (const [label, mutate] of unhealthyMutations) {
mutate(currentConn._sock);
await transport.exec(createBaseExecArgs());
expectedDials += 1;
expectedStops += 1;
assert.equal(dialCount, expectedDials, `expected redial when socket has ${label}`);
assert.equal(stopCount, expectedStops, `expected eviction when socket has ${label}`);
}
// Omitting _sock completely remains healthy (backward-compatible with minimal fakes).
delete currentConn._sock;
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, expectedDials, "missing _sock must still reuse pooled entry");
transport.shutdown();
});
test("evicts pooled entry on SSH_EXEC_OPEN_TIMEOUT and RPC deadline abort, but keeps it on user cancel", async () => {
let dialCount = 0;
let stopCount = 0;
let execHandler = async () => ({ stdout: "ok", stderr: "", code: 0 });
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward() {
stopCount += 1;
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: (conn, cmd, opts) => execHandler(conn, cmd, opts),
measurePing: async () => 4,
getSender: () => ({ id: 1 }),
});
// Prime the pool.
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
// 1) User cancel (RPC_ERRORS.cancelled) of a healthy running exec must NOT evict.
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
});
const userAbort = new AbortController();
const userCancelPromise = transport.exec(createBaseExecArgs({ signal: userAbort.signal }));
setTimeout(() => userAbort.abort(new PluginRpcError(RPC_ERRORS.cancelled, "User cancelled")), 10);
await assert.rejects(userCancelPromise, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0, "user cancel of healthy exec must not evict pooled entry");
execHandler = async () => ({ stdout: "reused", stderr: "", code: 0 });
const reused = await transport.exec(createBaseExecArgs());
assert.equal(reused.stdout, "reused");
assert.equal(dialCount, 1, "pooled connection must be reused after healthy user cancel");
// 2) SSH_EXEC_OPEN_TIMEOUT must evict so next exec dials fresh.
execHandler = async () => {
const err = new Error("SSH exec channel open timed out after 10000 ms");
err.code = "SSH_EXEC_OPEN_TIMEOUT";
throw err;
};
await assert.rejects(
transport.exec(createBaseExecArgs()),
(err) => err.code === RPC_ERRORS.deadlineExceeded,
);
assert.equal(stopCount, 1, "SSH_EXEC_OPEN_TIMEOUT must evict pooled entry");
execHandler = async () => ({ stdout: "fresh-after-open-timeout", stderr: "", code: 0 });
const afterOpenTimeout = await transport.exec(createBaseExecArgs());
assert.equal(afterOpenTimeout.stdout, "fresh-after-open-timeout");
assert.equal(dialCount, 2, "next exec after SSH_EXEC_OPEN_TIMEOUT must re-dial");
// 3) RPC deadline abort after connection acquisition must evict so next exec dials fresh.
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
});
const deadlineAbort = new AbortController();
const deadlinePromise = transport.exec(createBaseExecArgs({ signal: deadlineAbort.signal }));
setTimeout(() => {
deadlineAbort.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
}, 10);
await assert.rejects(deadlinePromise, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(stopCount, 2, "RPC deadline abort must evict pooled entry");
execHandler = async () => ({ stdout: "fresh-after-deadline", stderr: "", code: 0 });
const afterDeadline = await transport.exec(createBaseExecArgs());
assert.equal(afterDeadline.stdout, "fresh-after-deadline");
assert.equal(dialCount, 3, "next exec after RPC deadline abort must re-dial");
transport.shutdown();
});
test("premature stop before startPortForward registers retries after registration, cancels hung dial, and allows fresh retry", async () => {
const sender = { id: 7 };
let dialCount = 0;
let firstTunnelId = null;
const stopCalls = [];
const registeredTunnels = new Map();
let resolveDialAtGate;
const dialAtGate = new Promise((resolve) => { resolveDialAtGate = resolve; });
let releaseRegistrationGate;
const registrationGate = new Promise((resolve) => { releaseRegistrationGate = resolve; });
let resolveFirstDialCancelled;
const firstDialCancelled = new Promise((resolve) => { resolveFirstDialCancelled = resolve; });
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
if (dialCount === 1) {
firstTunnelId = opts.tunnelId;
resolveDialAtGate();
// Simulate preemption/delay before portForwardingTunnels.set(tunnelId, ...).
await registrationGate;
// Now register the tunnel and hang until stopPortForward cancels it.
return new Promise((resolve) => {
registeredTunnels.set(opts.tunnelId, () => {
resolveFirstDialCancelled();
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
}
const conn = createFakeConn();
registeredTunnels.set(opts.tunnelId, () => {});
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(event, { tunnelId }) {
const cancel = registeredTunnels.get(tunnelId);
stopCalls.push({ sender: event?.sender, tunnelId, found: Boolean(cancel) });
if (!cancel) {
return { tunnelId, success: false, error: "Tunnel not found" };
}
registeredTunnels.delete(tunnelId);
cancel();
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => sender,
});
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
await dialAtGate;
assert.ok(firstTunnelId, "tunnelId must be assigned before gate");
assert.equal(registeredTunnels.size, 0, "tunnel must not be registered yet");
assert.equal(transport.pendingDials.size, 1);
// Last waiter aborts BEFORE startPortForward registers the tunnel.
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
assert.ok(stopCalls.length >= 1, "initial stop attempt must have fired");
assert.equal(stopCalls[0].tunnelId, firstTunnelId);
assert.equal(stopCalls[0].sender, sender);
assert.equal(stopCalls[0].found, false, "initial stop before registration must report Tunnel not found");
// Allow startPortForward to register and begin the hung handshake.
releaseRegistrationGate();
// Wait for the retry stop to cancel the newly registered hung dial.
await Promise.race([
firstDialCancelled,
new Promise((_, reject) => setTimeout(() => reject(new Error("Hung dial was not cancelled after registration")), 2_000)),
]);
// Give settlement microtasks / any stale timer a moment to confirm no double-close.
await new Promise((r) => setTimeout(r, 40));
const confirmedStopsForFirst = stopCalls.filter((c) => c.tunnelId === firstTunnelId && c.found);
assert.equal(confirmedStopsForFirst.length, 1, "stopPortForward must succeed once after registration without double-closing");
assert.equal(registeredTunnels.size, 0, "no zombie tunnel may remain registered");
assert.equal(transport.pendingDials.size, 0);
// A later retry must start a fresh dial and succeed without being stopped.
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
assert.equal(res2.stdout, "ok:retry");
assert.equal(dialCount, 2, "retry must start a fresh dial");
assert.equal(transport.connections.size, 1);
assert.equal(registeredTunnels.size, 1, "live retry tunnel must remain active");
transport.shutdown();
});
test("post-return abort stops tunnel after early Tunnel not found on both success and throw", async () => {
const stopCalls = [];
const registeredTunnels = new Map();
let dialCount = 0;
let resolveGateReached;
let gateReached;
let releaseGate;
let gate;
let resolveRegistered;
let registered;
let mode = "succeed";
const resetGate = () => {
gateReached = new Promise((resolve) => { resolveGateReached = resolve; });
gate = new Promise((resolve) => { releaseGate = resolve; });
registered = new Promise((resolve) => { resolveRegistered = resolve; });
};
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
if (mode === "succeed" || mode === "throw") {
resolveGateReached(opts.tunnelId);
await gate;
registeredTunnels.set(opts.tunnelId, () => {});
resolveRegistered();
if (mode === "throw") {
throw new Error("late dial failure");
}
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
}
const conn = createFakeConn();
registeredTunnels.set(opts.tunnelId, () => {});
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(_event, { tunnelId }) {
const found = registeredTunnels.has(tunnelId);
stopCalls.push({ tunnelId, found });
if (!found) {
return { tunnelId, success: false, error: "Tunnel not found" };
}
registeredTunnels.delete(tunnelId);
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 3,
getSender: () => ({ id: 2 }),
});
// 1) startPortForward resolves { success: true } immediately after an early Tunnel not found.
resetGate();
mode = "succeed";
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ hostId: "host-a", signal: abort1.signal }));
const tunnelId1 = await gateReached;
abort1.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && !c.found).length, 1);
releaseGate();
await registered;
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId1); i += 1) {
await new Promise((r) => setTimeout(r, 5));
}
assert.equal(registeredTunnels.has(tunnelId1), false, "post-return abort must stop tunnel that succeeded after early not-found");
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && c.found).length, 1);
assert.equal(transport.connections.size, 0);
assert.equal(transport.pendingDials.size, 0);
// 2) startPortForward throws after an early Tunnel not found.
resetGate();
mode = "throw";
const abort2 = new AbortController();
const p2 = transport.exec(createBaseExecArgs({ hostId: "host-b", signal: abort2.signal }));
const tunnelId2 = await gateReached;
abort2.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && !c.found).length, 1);
releaseGate();
await registered;
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId2); i += 1) {
await new Promise((r) => setTimeout(r, 5));
}
assert.equal(registeredTunnels.has(tunnelId2), false, "post-throw abort must stop tunnel after early not-found");
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && c.found).length, 1);
assert.equal(transport.pendingDials.size, 0);
// 3) Later retry succeeds fresh.
mode = "normal";
const res = await transport.exec(createBaseExecArgs({ hostId: "host-a", command: "after-cleanup" }));
assert.equal(res.stdout, "ok:after-cleanup");
assert.equal(dialCount, 3);
assert.equal(transport.connections.size, 1);
transport.shutdown();
});
test("PluginHostSshExecTransport dials with reuseTransport: false and reconnects cleanly after idle eviction", async () => {
const observedReuseFlags = [];
let dialCount = 0;
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
observedReuseFlags.push(opts.reuseTransport);
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(_event, { tunnelId }) {
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 4,
getSender: () => ({ id: 3 }),
idleTtlMs: 25,
});
const first = await transport.exec(createBaseExecArgs({ command: "poll-1" }));
assert.equal(first.stdout, "ok:poll-1");
assert.equal(dialCount, 1);
// Wait for idle eviction to tear down the pooled connection.
for (let i = 0; i < 40 && transport.connections.size > 0; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal(transport.connections.size, 0, "idle entry should be evicted");
const second = await transport.exec(createBaseExecArgs({ command: "poll-2" }));
assert.equal(second.stdout, "ok:poll-2");
assert.equal(dialCount, 2);
assert.deepEqual(observedReuseFlags, [false, false]);
transport.shutdown();
});
test("SSH_EXEC_OPEN_PENDING evicts the wedged pooled connection so the next retry dials fresh", async () => {
let dialCount = 0;
let execCalls = 0;
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(_event, { tunnelId }) {
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => {
execCalls += 1;
if (execCalls === 1) {
const err = new Error("SSH exec channel open still pending on this connection");
err.code = "SSH_EXEC_OPEN_PENDING";
throw err;
}
return { stdout: `ok:${command}`, stderr: "", code: 0 };
},
measurePing: async () => 2,
getSender: () => ({ id: 4 }),
});
await assert.rejects(
transport.exec(createBaseExecArgs({ command: "stuck" })),
(err) => err.code === RPC_ERRORS.unavailable,
);
assert.equal(transport.connections.size, 0, "wedged connection must be evicted on SSH_EXEC_OPEN_PENDING");
const recovered = await transport.exec(createBaseExecArgs({ command: "recovered" }));
assert.equal(recovered.stdout, "ok:recovered");
assert.equal(dialCount, 2, "next retry must dial a fresh SSH connection");
transport.shutdown();
});
+9 -39
View File
@@ -4,11 +4,7 @@ const posixPath = require("node:path").posix;
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const schema = require("./generated/plugin-contract.schema.json");
const fail = (code, message, cause) => {
const err = new PluginRpcError(RPC_ERRORS[code], message);
if (cause !== undefined) err.cause = cause;
return err;
};
const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
const SFTP_LIMITS = schema.$defs.VaultHostSftpLimits.const;
const S_IFMT = 0o170000;
@@ -131,7 +127,7 @@ class PluginHostSshSftpTransport {
}
settled = true;
if (err || !sftp) {
reject(fail("unavailable", err?.message || "Failed to open SFTP subsystem", err));
reject(fail("unavailable", err?.message || "Failed to open SFTP subsystem"));
return;
}
const evict = () => {
@@ -151,33 +147,15 @@ class PluginHostSshSftpTransport {
return raceWithCallerSignal(opening, callerSignal);
}
#evictSftp(conn) {
const cached = this.sftpByConn.get(conn);
if (!cached) return;
this.sftpByConn.delete(conn);
void cached.then((sftp) => {
try { sftp?.end?.(); } catch { /* ignore */ }
}).catch(() => {});
}
async #withSftp(ctx, operation) {
const lease = await this.sshExecTransport.acquireConnection(ctx);
try {
const sftp = await this.#openSftp(lease.conn, lease.signal);
return await runWithOperationSignal(lease.signal, SFTP_LIMITS.timeoutMs, (opSignal) => operation(sftp, opSignal));
} catch (err) {
const rawCode = err?.cause?.code ?? err?.code;
const isTransportBroken =
rawCode === "ECONNRESET"
|| rawCode === "EPIPE"
|| rawCode === "ETIMEDOUT"
|| err?.code === RPC_ERRORS.deadlineExceeded;
if (isTransportBroken) {
this.#evictSftp(lease.conn);
lease.invalidate();
}
if (err instanceof PluginRpcError) throw err;
if (lease.signal.aborted) throw fail("cancelled", "SFTP operation was cancelled");
if (err?.code === "ECONNRESET" || err?.code === "EPIPE") lease.invalidate();
throw fail("unavailable", err?.message ? String(err.message).slice(0, 256) : "SFTP operation failed");
} finally {
lease.release();
@@ -189,7 +167,7 @@ class PluginHostSshSftpTransport {
return this.#withSftp(ctx, (sftp) => new Promise((resolve, reject) => {
sftp.readdir(p, (err, list) => {
if (err) {
reject(fail(err.code === 2 ? "notFound" : "unavailable", err.message || "Failed to list directory", err));
reject(fail(err.code === 2 ? "notFound" : "unavailable", err.message || "Failed to list directory"));
return;
}
const items = Array.isArray(list) ? list : [];
@@ -215,7 +193,7 @@ class PluginHostSshSftpTransport {
resolve({ exists: false });
return;
}
reject(fail("unavailable", err.message || "Failed to stat remote path", err));
reject(fail("unavailable", err.message || "Failed to stat remote path"));
return;
}
resolve({
@@ -237,7 +215,6 @@ class PluginHostSshSftpTransport {
const chunks = [];
let total = 0;
let truncated = false;
let ended = false;
const onAbort = () => {
try { stream.destroy(); } catch { /* ignore */ }
};
@@ -267,17 +244,11 @@ class PluginHostSshSftpTransport {
});
return;
}
const rpcErr = fail(err?.code === 2 ? "notFound" : "unavailable", err?.message || "Failed to read remote file");
rpcErr.cause = err;
reject(rpcErr);
reject(fail(err?.code === 2 ? "notFound" : "unavailable", err?.message || "Failed to read remote file"));
});
stream.once("close", () => {
signal.removeEventListener("abort", onAbort);
if (ended) return;
if (!truncated) {
reject(fail("unavailable", "Remote SFTP read closed before completion"));
return;
}
if (!truncated) return;
const combined = Buffer.concat(chunks, total);
resolve({
data: encoding === "base64" ? combined.toString("base64") : combined.toString("utf8"),
@@ -287,7 +258,6 @@ class PluginHostSshSftpTransport {
});
});
stream.once("end", () => {
ended = true;
signal.removeEventListener("abort", onAbort);
const combined = Buffer.concat(chunks, total);
resolve({
@@ -318,7 +288,7 @@ class PluginHostSshSftpTransport {
});
stream.once("error", (err) => {
signal.removeEventListener("abort", onAbort);
reject(fail("unavailable", err?.message || "Failed to write remote file", err));
reject(fail("unavailable", err?.message || "Failed to write remote file"));
});
stream.once("close", () => {
signal.removeEventListener("abort", onAbort);
@@ -337,7 +307,7 @@ class PluginHostSshSftpTransport {
return this.#withSftp(ctx, (sftp) => new Promise((resolve, reject) => {
sftp.mkdir(p, (err) => {
if (err) {
reject(fail("unavailable", err.message || "Failed to create remote directory", err));
reject(fail("unavailable", err.message || "Failed to create remote directory"));
return;
}
resolve({ created: true });
+2 -5
View File
@@ -103,7 +103,7 @@ class PluginHostVaultDataBridge {
return true;
}
request(kind, payload, signal, options = {}) {
request(kind, payload, signal) {
if (!ALLOWED_KINDS.has(kind)) {
return Promise.reject(fail("invalidArgument", "Unsupported Vault data request"));
}
@@ -119,9 +119,6 @@ class PluginHostVaultDataBridge {
if (this.pending.size >= MAX_PENDING) {
return Promise.reject(fail("resourceExhausted", "Too many pending Vault data requests"));
}
const requestTimeoutMs = Number.isFinite(options?.timeoutMs) && options.timeoutMs > 0
? Math.min(Math.round(options.timeoutMs), 30_000)
: this.timeoutMs;
const requestId = randomUUID();
const actionToken = randomBytes(24).toString("base64url");
return new Promise((resolve, reject) => {
@@ -146,7 +143,7 @@ class PluginHostVaultDataBridge {
signal?.addEventListener("abort", entry.onAbort, { once: true });
entry.timer = setTimeout(() => {
finish(fail("deadlineExceeded", "Vault data request timed out"));
}, requestTimeoutMs);
}, this.timeoutMs);
entry.timer.unref?.();
this.pending.set(requestId, entry);
try {
+5 -6
View File
@@ -20,7 +20,7 @@ class PluginPermissionDecisionHost {
setReady(sender, ready) {
if (this.closed) throw permissionDenied("Permission UI is closed");
const window = this.getWindows().find((candidate) => candidate && !candidate.isDestroyed?.() && candidate.webContents === sender);
const window = this.getWindows().find((candidate) => candidate?.webContents === sender);
if (!window || window.isDestroyed?.() || sender.isDestroyed?.() || typeof ready !== "boolean") {
throw permissionDenied("Permission UI sender is invalid");
}
@@ -42,15 +42,14 @@ class PluginPermissionDecisionHost {
}
get owner() {
const win = this.getWindows().find((window) => window && !window.isDestroyed?.()
&& this.owners.has(window.webContents) && window.isFocused?.() && window.isVisible?.());
return win ? win.webContents : null;
return this.getWindows().find((window) => this.owners.has(window?.webContents)
&& !window.isDestroyed?.() && window.isFocused?.() && window.isVisible?.())?.webContents ?? null;
}
assertOwner(sender = this.owner) {
const window = this.owners.get(sender)?.window;
if (this.closed || !sender || !window || window.isDestroyed?.() || !this.getWindows().includes(window) || window.webContents !== sender || sender.isDestroyed?.()
|| !window.isFocused?.() || !window.isVisible?.() || this.isLocked()) {
if (this.closed || !sender || !window || !this.getWindows().includes(window) || window.webContents !== sender || sender.isDestroyed?.()
|| window.isDestroyed?.() || !window.isFocused?.() || !window.isVisible?.() || this.isLocked()) {
throw permissionDenied("Permission UI requires a focused unlocked app window");
}
}
+1 -7
View File
@@ -387,12 +387,6 @@ class PluginAISidebarService {
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin runtime supervisor is unavailable");
}
const rawDeadline = Number.isSafeInteger(options.deadlineMs)
? options.deadlineMs
: Number.isSafeInteger(options.timeoutMs)
? options.timeoutMs
: TOOL_INVOKE_DEADLINE_MS;
const timeoutMs = Math.max(1, Math.min(300_000, rawDeadline));
const rawResult = await this.runtimeSupervisor.request(
pluginId,
"plugin.ai.invokeTool",
@@ -403,7 +397,7 @@ class PluginAISidebarService {
...(chatSessionId ? { chatSessionId } : {}),
},
{
timeoutMs,
deadlineMs: Number.isSafeInteger(options.deadlineMs) ? options.deadlineMs : TOOL_INVOKE_DEADLINE_MS,
signal: options.signal,
},
);
@@ -275,37 +275,3 @@ test("ai.openSidebar enforces active ai.invoke approval for autoSend: true while
/disabled|denied/i,
);
});
test("PluginAISidebarService.invokeTool forwards timeoutMs to runtimeSupervisor.request", async () => {
const captured = [];
const supervisor = {
async request(pluginId, method, params, options) {
captured.push({ pluginId, method, params, options });
return { ok: true };
},
};
const service = new PluginAISidebarService({
runtimeSupervisor: supervisor,
});
service.registerTools({
viewId: "com.example.db.workbench",
tools: [{ name: "query_schema", description: "Inspect schema", inputSchema: { type: "object", properties: {} }, risk: "read" }],
}, ctx());
await service.invokeTool({
pluginId: manifest.id,
toolName: "query_schema",
args: {},
});
assert.equal(captured.length, 1);
assert.equal(captured[0].options.timeoutMs, 45_000);
await service.invokeTool({
pluginId: manifest.id,
toolName: "query_schema",
args: {},
}, {
deadlineMs: 60_000,
});
assert.equal(captured[1].options.timeoutMs, 60_000);
});
+29 -54
View File
@@ -237,24 +237,6 @@ function createTrustedPluginBridgeSender(options = {}) {
function registerPluginBridge(ipcMain, options) {
const manager = options.manager;
const observeSenderReset = (sender, onReset) => {
const run = () => {
try { onReset(); } catch { /* ignore */ }
};
const onNavigate = (details, _url, isInPlace, isMainFrame) => {
const main = details?.isMainFrame ?? isMainFrame;
const sameDocument = details?.isSameDocument ?? isInPlace;
if (main !== false && sameDocument !== true) run();
};
const onDestroyed = () => {
sender.removeListener?.("render-process-gone", run);
sender.removeListener?.("did-start-navigation", onNavigate);
run();
};
sender.once?.("destroyed", onDestroyed);
sender.on?.("render-process-gone", run);
sender.on?.("did-start-navigation", onNavigate);
};
let githubService;
const githubOwners = new WeakSet();
const githubFor = (activeManager, event) => {
@@ -262,7 +244,7 @@ function registerPluginBridge(ipcMain, options) {
githubService ??= new GitHubInstallService({ manager: activeManager });
if (!githubOwners.has(event.sender)) {
githubOwners.add(event.sender);
observeSenderReset(event.sender, () => { void githubService.discard(event.sender).catch(() => {}); });
event.sender.once?.("destroyed", () => { void githubService.discard(event.sender).catch(() => {}); });
}
return githubService;
};
@@ -367,7 +349,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedTerminalRequestSenders.has(sender)) {
observedTerminalRequestSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
for (const controller of requests.values()) controller.abort();
requests.clear();
});
@@ -383,7 +365,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedExtensionRequestSenders.has(sender)) {
observedExtensionRequestSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
for (const controller of requests.values()) controller.abort();
requests.clear();
});
@@ -419,7 +401,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedConnectionSenders.has(sender)) {
observedConnectionSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
const monitors = connectionMonitorsBySender.get(sender);
for (const monitor of monitors?.values?.() ?? []) monitor.controller.abort();
monitors?.clear?.();
@@ -459,7 +441,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedAuthenticationSenders.has(sender)) {
observedAuthenticationSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
for (const pending of challenges.values()) pending.reject(new Error("Plugin authentication window closed"));
challenges.clear();
});
@@ -618,7 +600,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedImporterSelectionSenders.has(sender)) {
observedImporterSelectionSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
for (const selection of selections.values()) closeImporterSelection(selection);
selections.clear();
});
@@ -641,7 +623,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedSyncTransferSenders.has(sender)) {
observedSyncTransferSenders.add(sender);
observeSenderReset(sender, () => {
sender.once?.("destroyed", () => {
for (const [transferId, transfer] of [...transfers.entries()]) {
try {
transfer.controller?.abort();
@@ -1013,9 +995,6 @@ function registerPluginBridge(ipcMain, options) {
const result = await extensionProviderService.readSyncObject(payload ?? {}, {
signal: controller.signal,
});
if (controller.signal.aborted) {
throw controller.signal.reason ?? new DOMException("Sync object read cancelled", "AbortError");
}
if (!result?.found || !result.bytes) {
extensionRequestMap(event.sender).delete(requestId);
return { found: false, key: payload?.key, data: null };
@@ -1481,7 +1460,6 @@ function registerPluginBridge(ipcMain, options) {
),
onClose: async () => {
acceptProviderOutput = false;
closedDuringStart = true;
if (sessions.get(sessionId) === sessionOwner) sessions.delete(sessionId);
if (monitors.get(sessionId)?.sessionOwner === sessionOwner) monitors.delete(sessionId);
connectionController.abort(new DOMException("Terminal session closed", "AbortError"));
@@ -1555,33 +1533,30 @@ function registerPluginBridge(ipcMain, options) {
},
});
providerOpened = true;
if (closedDuringStart || connectionController.signal.aborted) {
try { await extensionProviderService.control(opened.sessionId, "close", {}, { sessionOwner }); }
catch { extensionProviderService.closeSessionLocal(opened.sessionId, undefined, sessionOwner); }
return opened;
}
sessions.set(opened.sessionId, sessionOwner);
monitors.set(opened.sessionId, { sessionOwner, controller: connectionController });
if (opened.status === "connected") {
// The terminal renderer treats the first delivery as the connection
// readiness boundary. Preserve that boundary for silent protocols
// whose Provider completes open before producing terminal bytes.
await terminalWorkerManager.pushExternalOutput(
opened.sessionId,
"",
pluginConnectionReadyMeta,
if (!closedDuringStart) {
sessions.set(opened.sessionId, sessionOwner);
monitors.set(opened.sessionId, { sessionOwner, controller: connectionController });
if (opened.status === "connected") {
// The terminal renderer treats the first delivery as the connection
// readiness boundary. Preserve that boundary for silent protocols
// whose Provider completes open before producing terminal bytes.
await terminalWorkerManager.pushExternalOutput(
opened.sessionId,
"",
pluginConnectionReadyMeta,
sessionOwner,
);
}
void monitorPluginConnection({
sessionId: opened.sessionId,
sessionOwner,
);
sessions,
monitors,
controller: connectionController,
terminalWorkerManager,
readyPublished: opened.status === "connected",
});
}
void monitorPluginConnection({
sessionId: opened.sessionId,
sessionOwner,
sessions,
monitors,
controller: connectionController,
terminalWorkerManager,
readyPublished: opened.status === "connected",
});
return opened;
} catch (error) {
acceptProviderOutput = false;
+1 -5
View File
@@ -37,11 +37,7 @@ class PluginManager {
#mutate(operation) {
if (this.shuttingDown) return Promise.reject(new Error("Plugin manager is shutting down"));
const guarded = () => {
if (this.shuttingDown) return Promise.reject(new Error("Plugin manager is shutting down"));
return operation();
};
const result = this.mutationTail.then(guarded, guarded);
const result = this.mutationTail.then(operation, operation);
this.mutationTail = result.then(() => undefined, () => undefined);
return result;
}
-10
View File
@@ -318,16 +318,6 @@ class PluginRpcRouter {
signal: controller.signal,
notification: true,
})), controller.signal);
} catch (error) {
// Non-protocol application/authorization errors on a fire-and-forget
// notification (e.g. denied permission or App Lock) must not escalate
// to a fatal protocol violation that terminates and quarantines the plugin.
if (!(error instanceof PluginRpcError)
|| error.code === RPC_ERRORS.parseError
|| error.code === RPC_ERRORS.invalidRequest
|| error.code === RPC_ERRORS.invalidParams) {
throw error;
}
} finally {
clearTimeout(timer);
this.inflightNotifications.delete(controller);
-17
View File
@@ -425,20 +425,3 @@ test("oversized control messages close the peer before dispatch", async () => {
assert.equal(fixture.router.closed, true);
assert.match(fixture.protocolErrors[0].message, /exceeds/);
});
test("notification permission denial does not escalate to a protocol error or close the peer", async () => {
const fixture = createRouter({
notificationHandlers: {
"views.postMessage": async () => {
throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Plugin permission is disabled");
},
},
});
await fixture.router.accept({
jsonrpc: "2.0",
method: "views.postMessage",
params: { viewId: "com.example.demo.view", message: { ok: true } },
});
assert.equal(fixture.protocolErrors.length, 0);
assert.equal(fixture.router.closed, false);
});
+4 -26
View File
@@ -4,11 +4,7 @@ import { PLUGIN_BYTE_STREAM_FEATURE } from "@netcatty/plugin-contract";
export async function connectByteStream({ client, streams, subscriptions, enabledFeatures }, request, cancellationToken, viaHost = false) {
if (!enabledFeatures.includes(PLUGIN_BYTE_STREAM_FEATURE)) throw new PluginError("unsupported", "Byte stream feature is unavailable");
if (viaHost && !enabledFeatures.includes("network.host-byte-streams")) throw new PluginError("unsupported", "Host byte stream feature is unavailable");
const descriptor = await client.request(
viaHost ? "network.stream.connectViaHost" : "network.stream.connect",
request,
{ cancellationToken, deadlineMs: 120_000 },
);
const descriptor = await client.request(viaHost ? "network.stream.connectViaHost" : "network.stream.connect", request, { cancellationToken, ...(viaHost ? { deadlineMs: 120_000 } : {}) });
if (descriptor.cancelled) throw new PluginError("cancelled", "Host connection cancelled");
let readable;
let writable;
@@ -16,18 +12,12 @@ export async function connectByteStream({ client, streams, subscriptions, enable
let closing;
let cancellation;
let connection;
const detachLocal = () => {
cancellation?.dispose();
cancellation = undefined;
if (connection) subscriptions.delete(connection);
};
const close = () => {
closing ??= client.request("network.stream.close", { handleId: descriptor.handleId })
.finally(() => {
detachLocal();
try { readable?.cancel(); } catch {}
try { writable?.cancel(); } catch {}
cancellation?.dispose();
streams.rejectReadable(descriptor.outputStreamId);
if (connection) subscriptions.delete(connection);
});
return closing;
};
@@ -55,19 +45,7 @@ export async function connectByteStream({ client, streams, subscriptions, enable
endpoint: descriptor.endpoint,
...(descriptor.hostBindingToken ? { hostBindingToken: descriptor.hostBindingToken } : {}),
readable: Object.freeze({
id: readable.id,
read: () => readable.read().then(
(chunk) => {
if (chunk === null) detachLocal();
return chunk;
},
(error) => {
detachLocal();
throw error;
},
),
cancel,
dispose: cancel,
id: readable.id, read: () => readable.read(), cancel, dispose: cancel,
}),
writable: Object.freeze({
id: writable.id, write: (bytes) => writable.write(bytes), end: () => writable.end(),
@@ -41,24 +41,11 @@ function closedError(streamId) {
return new PluginError("unavailable", `Plugin stream is closed: ${streamId}`);
}
const MAX_RETIRED_STREAM_IDS = 512;
function rememberRetiredStreamId(set, streamId) {
set.delete(streamId);
set.add(streamId);
while (set.size > MAX_RETIRED_STREAM_IDS) {
const oldest = set.values().next().value;
set.delete(oldest);
}
}
export function createPluginStreamEndpoint(transport, options = {}) {
const maxStreams = options.maxStreams ?? 128;
const incoming = new Map();
const outgoing = new Map();
const pendingIncoming = new Map();
const retiredIncoming = new Set();
const retiredOutgoing = new Set();
let closed = false;
const sendEnvelope = (frame, transfer) => {
@@ -100,22 +87,10 @@ export function createPluginStreamEndpoint(transport, options = {}) {
}
function closeIncoming(state, error, notify = false, refundCancelledCredit = false) {
if (state.closed) {
// Peer already sent "end", but consumer cancelled/disposed before reading
// EOF null or draining buffered chunks. Refund remaining credit so the
// host can retire its outgoing stream slot.
if (notify && !state.error && (state.currentCreditBytes > 0 || state.queue.length > 0)) {
state.currentCreditBytes += state.queue.reduce((sum, chunk) => sum + chunk.creditBytes, 0);
state.queue.length = 0;
try { releaseCurrent(state); } catch {}
state.currentCreditBytes = 0;
}
return;
}
if (state.closed) return;
state.closed = true;
state.error = error ?? null;
incoming.delete(state.streamId);
if (notify) rememberRetiredStreamId(retiredIncoming, state.streamId);
if (error) {
// Discard unread bytes on cancellation/failure and settle their credit
// now. A later read must surface the error without sending more credit.
@@ -241,7 +216,6 @@ export function createPluginStreamEndpoint(transport, options = {}) {
state.terminal = "error";
state.closed = true;
outgoing.delete(state.streamId);
rememberRetiredStreamId(retiredOutgoing, state.streamId);
const failure = new PluginError("data_loss", String(error?.message ?? "Plugin stream failed"));
for (const pending of state.queue.splice(0)) pending.reject(failure);
state.queuedBytes = 0;
@@ -257,7 +231,7 @@ export function createPluginStreamEndpoint(transport, options = {}) {
});
},
cancel() {
if (state.closed || state.terminalSent) return;
if (state.closed) return;
state.closed = true;
state.terminal = "cancel";
const error = new PluginError("cancelled", "Plugin stream was cancelled");
@@ -272,10 +246,7 @@ export function createPluginStreamEndpoint(transport, options = {}) {
});
state.terminalSent = true;
} finally {
if (!state.terminalSent || state.availableBytes === state.windowBytes) {
outgoing.delete(state.streamId);
if (state.terminalSent) rememberRetiredStreamId(retiredOutgoing, state.streamId);
}
if (!state.terminalSent || state.availableBytes === state.windowBytes) outgoing.delete(state.streamId);
}
},
dispose() { this.cancel(); },
@@ -321,7 +292,6 @@ export function createPluginStreamEndpoint(transport, options = {}) {
if (output.terminalSent && output.availableBytes === output.windowBytes) {
output.closed = true;
outgoing.delete(frame.streamId);
rememberRetiredStreamId(retiredOutgoing, frame.streamId);
} else flushOutgoing(output);
return true;
}
@@ -334,18 +304,8 @@ export function createPluginStreamEndpoint(transport, options = {}) {
output.endReject?.(error);
return true;
}
if ((frame.kind === "windowUpdate" || frame.kind === "cancel") && retiredOutgoing.has(frame.streamId)) {
if (frame.kind === "cancel") retiredOutgoing.delete(frame.streamId);
return true;
}
const input = incoming.get(frame.streamId);
if (!input || input.closed) {
if (retiredIncoming.has(frame.streamId)) {
if (frame.kind !== "chunk") retiredIncoming.delete(frame.streamId);
return true;
}
throw new PluginError("data_loss", `Unknown Plugin stream: ${frame.streamId}`);
}
if (!input || input.closed) throw new PluginError("data_loss", `Unknown Plugin stream: ${frame.streamId}`);
if (frame.sequence !== input.nextSequence) {
throw new PluginError("data_loss", `Plugin stream frame is out of order: ${frame.streamId}`);
}
+31 -87
View File
@@ -291,24 +291,17 @@ function createHostClient(transport) {
return new Promise((resolve, reject) => {
const cancellationId = options.cancellationToken ? `browser-${id}` : undefined;
const pendingRequest = { resolve, reject };
const pendingKey = `${typeof id}:${String(id)}`;
pending.set(pendingKey, pendingRequest);
try {
transport.post({
jsonrpc: "2.0",
id,
method,
...(sanitizedParams === undefined ? {} : { params: sanitizedParams }),
...(cancellationId === undefined ? {} : { cancellationId }),
...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
});
} catch (error) {
pending.delete(pendingKey);
reject(new PluginError("unavailable", error instanceof Error ? error.message : "Plugin host transport failed"));
return;
}
pending.set(`${typeof id}:${String(id)}`, pendingRequest);
transport.post({
jsonrpc: "2.0",
id,
method,
...(sanitizedParams === undefined ? {} : { params: sanitizedParams }),
...(cancellationId === undefined ? {} : { cancellationId }),
...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
});
pendingRequest.cancellation = options.cancellationToken?.onCancellationRequested(() => {
try { notify("$/cancelRequest", { cancellationId }); } catch {}
notify("$/cancelRequest", { cancellationId });
});
});
}
@@ -798,7 +791,7 @@ function createPluginContext(config, client, runtimeApi) {
}),
};
const aiBase = Object.fromEntries(["openChat", "startTurn", "readTurn", "stopTurn", "closeChat"].map((operation) => [
operation, (params) => client.request(`ai.${operation}`, params, { deadlineMs: 65_000 }),
operation, (params) => client.request(`ai.${operation}`, params, operation === "readTurn" ? { deadlineMs: 65_000 } : {}),
]));
const ai = {
...aiBase,
@@ -828,50 +821,24 @@ function createPluginContext(config, client, runtimeApi) {
...(toolViewId ? { viewId: toolViewId } : {}),
};
});
await client.request("ai.registerTools", {
...(viewId ? { viewId } : {}),
tools: normalizedTools,
});
const prevBucket = runtimeApi.aiToolBuckets.get(scopeKey);
const prevExecutors = new Map();
if (prevBucket) {
for (const name of prevBucket.names) {
const existing = runtimeApi.aiToolExecutors.get(name);
if (existing?.scopeKey === scopeKey) {
prevExecutors.set(name, existing);
if (runtimeApi.aiToolExecutors.get(name)?.scopeKey === scopeKey) {
runtimeApi.aiToolExecutors.delete(name);
}
}
}
const names = normalizedTools.map((toolDef) => toolDef.name);
const token = Symbol("aiToolRegistration");
const displacedExecutors = new Map();
runtimeApi.aiToolBuckets.set(scopeKey, { token, names });
for (const name of names) {
if (runtimeApi.aiToolExecutors.has(name)) {
displacedExecutors.set(name, runtimeApi.aiToolExecutors.get(name));
}
runtimeApi.aiToolExecutors.set(name, { scopeKey, token, executor });
}
try {
await client.request("ai.registerTools", {
...(viewId ? { viewId } : {}),
tools: normalizedTools,
});
} catch (error) {
if (runtimeApi.aiToolBuckets.get(scopeKey)?.token === token) {
if (prevBucket) runtimeApi.aiToolBuckets.set(scopeKey, prevBucket);
else runtimeApi.aiToolBuckets.delete(scopeKey);
for (const name of names) {
if (runtimeApi.aiToolExecutors.get(name)?.token === token) {
runtimeApi.aiToolExecutors.delete(name);
}
}
for (const [name, entry] of displacedExecutors) {
if (!runtimeApi.aiToolExecutors.has(name)) runtimeApi.aiToolExecutors.set(name, entry);
}
for (const [name, entry] of prevExecutors) {
if (!runtimeApi.aiToolExecutors.has(name)) runtimeApi.aiToolExecutors.set(name, entry);
}
}
throw error;
}
let disposed = false;
return Object.freeze({
dispose() {
@@ -941,7 +908,7 @@ function createPluginContext(config, client, runtimeApi) {
read: (params) => client.request("context.selected.read", params),
};
const agent = Object.fromEntries(["listBackends", "selectTargets", "listChats", "openChat", "send", "read", "history", "stop", "closeChat"].map((operation) => [
operation, (params) => client.request(`agent.${operation}`, params, { deadlineMs: 65_000 }),
operation, (params) => client.request(`agent.${operation}`, params, operation === "read" ? { deadlineMs: 65_000 } : {}),
]));
const filesystem = {
readFile: (filePath, options = {}) => client.request("filesystem.readFile", {
@@ -1286,11 +1253,8 @@ export async function startPluginRuntime({
if (message.method === "plugin.deactivate") {
if (!deactivated) {
deactivated = true;
try {
await plugin.deactivate?.();
} finally {
context?.subscriptions.dispose();
}
await plugin.deactivate?.();
context?.subscriptions.dispose();
}
return null;
}
@@ -1616,33 +1580,19 @@ export async function startPluginRuntime({
const cancellationId = message.cancellationId;
const source = new CancellationTokenSource();
if (cancellationId) cancellation.set(cancellationId, source);
const sendRpcFailure = (error) => {
const rpcError = normalizeError(error);
try {
transport.post(makeRpcFailure(message.id, rpcError.code, rpcError.message, rpcError.data));
} catch {}
};
void handleRequest(message, source.token, ports).then(
(result) => {
let safeResult;
try {
safeResult = result === undefined ? null : sanitizeOutboundJsonValue(result, 1);
} catch (error) {
sendRpcFailure(new PluginError(
"internal",
error instanceof Error ? error.message : "Plugin RPC result must be a JSON value",
));
return;
}
try {
transport.post({
jsonrpc: "2.0",
id: message.id,
result: safeResult,
});
} catch {}
const safeResult = result === undefined ? null : sanitizeOutboundJsonValue(result, 1);
transport.post({
jsonrpc: "2.0",
id: message.id,
result: safeResult,
});
},
(error) => {
const rpcError = normalizeError(error);
transport.post(makeRpcFailure(message.id, rpcError.code, rpcError.message, rpcError.data));
},
sendRpcFailure,
).finally(() => {
if (cancellationId) cancellation.delete(cancellationId);
source.dispose();
@@ -1656,8 +1606,6 @@ export async function startPluginRuntime({
for (const source of cancellation.values()) source.cancel();
runtimeApi.commandHandlers.clear();
runtimeApi.providerHandlers.clear();
runtimeApi.aiToolBuckets.clear();
runtimeApi.aiToolExecutors.clear();
runtimeApi.settingsChanged.clear();
runtimeApi.environmentChanged.clear();
runtimeApi.terminalEvents.clear();
@@ -1667,12 +1615,8 @@ export async function startPluginRuntime({
for (const emitter of runtimeApi.viewMessages.values()) emitter.clear();
cancellation.clear();
if (!deactivated) {
deactivated = true;
try {
await plugin.deactivate?.();
} finally {
context?.subscriptions.dispose();
}
await plugin.deactivate?.();
context?.subscriptions.dispose();
}
transport.close();
},
+5 -25
View File
@@ -113,7 +113,6 @@ class RuntimeSupervisor {
this.starting = new Map();
this.startControllers = new Map();
this.stopping = new Map();
this.exitCleanups = new Map();
this.runtimeListeners = new Set();
this.progressListeners = new Set();
this.uncontainedPlugins = new Set();
@@ -233,8 +232,6 @@ class RuntimeSupervisor {
}
const stopping = this.stopping.get(pluginId);
if (stopping) await stopping;
const exitCleanup = this.exitCleanups.get(pluginId);
if (exitCleanup) await exitCleanup;
if (this.shuttingDown) throw new Error("Plugin runtime supervisor is shutting down");
if (this.starting.has(pluginId)) return this.starting.get(pluginId);
if (this.runtimes.has(pluginId)) {
@@ -328,13 +325,7 @@ class RuntimeSupervisor {
});
logger = this.logService?.createLogger(identity, plugin) ?? new PluginLogger();
const routes = this.rpcRegistry.createRoutes(identity);
const onExit = (details) => {
const cleanup = this.#handleExit(pluginId, runtime, identity, details).catch(() => {});
this.exitCleanups.set(pluginId, cleanup);
void cleanup.finally(() => {
if (this.exitCleanups.get(pluginId) === cleanup) this.exitCleanups.delete(pluginId);
});
};
const onExit = (details) => { void this.#handleExit(pluginId, runtime, identity, details); };
const onProtocolError = (error) => {
logger.audit({ operation: "runtime.protocol", authorization: "not-reached", result: "error", errorCode: error?.code });
return logger.write("error", "Plugin protocol violation", { error: error?.message });
@@ -491,19 +482,14 @@ class RuntimeSupervisor {
this.#recordContainmentFailure(identity, error);
return;
}
if (this.shuttingDown) {
try { this.#setRuntimeState(identity, "stopped"); } catch {}
return;
}
if (details.containmentFailed) {
this.#recordContainmentFailure(identity, details.error);
return;
}
if (details.expected) {
if (details.expected || this.shuttingDown) {
this.#setRuntimeState(identity, "stopped");
return;
}
if (this.runtimes.has(pluginId)) return;
await this.#recordFailure(identity, details.error);
}
@@ -552,16 +538,11 @@ class RuntimeSupervisor {
if (starting) {
try { await starting; } catch {}
}
const exitCleanup = this.exitCleanups.get(pluginId);
if (exitCleanup) {
try { await exitCleanup; } catch {}
}
const latestPlugin = this.database.getActivePlugin(pluginId);
if (latestPlugin && latestPlugin.runtime.quarantinedAt == null && latestPlugin.runtime.status !== "stopped" && latestPlugin.runtime.status !== "error") {
if (plugin && plugin.runtime.quarantinedAt == null && plugin.runtime.status !== "stopped") {
this.#setRuntimeState(identity, "stopped", {
pluginId,
pluginVersion: latestPlugin.activeVersion,
kind: latestPlugin.runtime.kind,
pluginVersion: plugin.activeVersion,
kind: plugin.runtime.kind,
});
}
return;
@@ -765,7 +746,6 @@ class RuntimeSupervisor {
await Promise.allSettled([...this.runtimes.keys()].map((pluginId) => this.stop(pluginId)));
await Promise.allSettled([...this.starting.values()]);
await Promise.allSettled([...this.stopping.values()]);
await Promise.allSettled([...this.exitCleanups.values()]);
for (const identity of this.runtimeIdentities.values()) this.#releaseRuntimeResources(identity);
this.resourceMonitors.clear();
this.runtimeListeners.clear();
+2 -7
View File
@@ -8,12 +8,11 @@ const {
const shutdownHandlers = new Set();
let shutdownPromise = null;
let shutdownInFlight = false;
function registerPluginShutdown(handler) {
if (typeof handler !== "function") throw new TypeError("Plugin shutdown handler must be a function");
shutdownHandlers.add(handler);
if (!shutdownInFlight) shutdownPromise = null;
shutdownPromise = null;
return () => {
shutdownHandlers.delete(handler);
};
@@ -31,7 +30,6 @@ function runPluginShutdown(options = {}) {
const timeout = new Promise((resolve) => {
timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
});
shutdownInFlight = true;
shutdownPromise = Promise.race([
Promise.allSettled([...shutdownHandlers].map((handler) => Promise.resolve().then(handler)))
.then((results) => {
@@ -40,10 +38,7 @@ function runPluginShutdown(options = {}) {
return { timedOut: false };
}),
timeout,
]).finally(() => {
clearTimeout(timer);
shutdownInFlight = false;
});
]).finally(() => clearTimeout(timer));
return shutdownPromise;
}
+4 -36
View File
@@ -54,25 +54,12 @@ function raceWithSignal(operation, signal) {
});
}
const MAX_RETIRED_STREAM_IDS = 512;
function rememberRetiredStreamId(set, streamId) {
set.delete(streamId);
set.add(streamId);
while (set.size > MAX_RETIRED_STREAM_IDS) {
const oldest = set.values().next().value;
set.delete(oldest);
}
}
class PluginStreamRouter {
constructor(options) {
this.send = options.send;
this.onIncomingStream = options.onIncomingStream ?? (() => false);
this.incoming = new Map();
this.outgoing = new Map();
this.retiredIncoming = new Set();
this.retiredOutgoing = new Set();
this.maxStreams = options.maxStreams ?? PLUGIN_RPC_MAX_PENDING;
this.openTimeoutMs = options.openTimeoutMs ?? PLUGIN_RPC_DEFAULT_TIMEOUT_MS;
this.closed = false;
@@ -106,7 +93,6 @@ class PluginStreamRouter {
openController: new AbortController(),
closed: false,
};
this.retiredIncoming.delete(frame.streamId);
this.incoming.set(frame.streamId, state);
let accepted;
let openTimedOut = false;
@@ -157,7 +143,6 @@ class PluginStreamRouter {
if (outgoing.terminalKind === "end" || outgoing.terminalKind === "cancel") {
if (outgoing.availableBytes === outgoing.maxCreditBytes) {
this.outgoing.delete(frame.streamId);
rememberRetiredStreamId(this.retiredOutgoing, frame.streamId);
}
return;
}
@@ -178,20 +163,8 @@ class PluginStreamRouter {
this.#notifyOutgoingClosed(outgoing, "cancel");
return;
}
if (frame.kind === "cancel" && this.retiredOutgoing.has(frame.streamId)) {
// Peer cancelled while our terminal end/cancel frame was already in flight.
this.retiredOutgoing.delete(frame.streamId);
return;
}
const state = this.incoming.get(frame.streamId);
if (!state || state.closed) {
if (this.retiredIncoming.has(frame.streamId)) {
// Producer had in-flight frames when host cancelled this incoming stream.
if (frame.kind !== "chunk") this.retiredIncoming.delete(frame.streamId);
return;
}
throw new Error(`Unknown incoming plugin stream: ${frame.streamId}`);
}
if (!state || state.closed) throw new Error(`Unknown incoming plugin stream: ${frame.streamId}`);
if (frame.sequence !== state.nextSequence) {
throw new Error(`Out-of-order plugin stream frame: ${frame.streamId}`);
}
@@ -245,9 +218,9 @@ class PluginStreamRouter {
: new Error(`Plugin stream ${frame.kind}: ${frame.streamId}`);
state.openController.abort(abortReason);
try {
if ((frame.kind === "cancel" || frame.kind === "end") && state.availableBytes < state.windowBytes) {
// The producer has stopped. Return unreturned credit once so it can
// retire its terminal state without leaking an outgoing stream slot.
if (frame.kind === "cancel" && state.availableBytes < state.windowBytes) {
// The producer has stopped. Return discarded credit once so it can
// retire its terminal state, without releasing more queued writes.
state.updateSequence += 1;
this.send({ frame: {
streamId: state.streamId, sequence: state.updateSequence,
@@ -311,7 +284,6 @@ class PluginStreamRouter {
terminalKind: null,
onClose: options.onClose,
};
this.retiredOutgoing.delete(streamId);
this.outgoing.set(streamId, state);
try {
this.send(envelope);
@@ -421,7 +393,6 @@ class PluginStreamRouter {
|| state.availableBytes === state.maxCreditBytes
) {
this.outgoing.delete(state.streamId);
if (terminalSent) rememberRetiredStreamId(this.retiredOutgoing, state.streamId);
}
this.#notifyOutgoingClosed(state, kind);
}
@@ -440,7 +411,6 @@ class PluginStreamRouter {
if (state.closed) return;
state.closed = true;
this.incoming.delete(state.streamId);
rememberRetiredStreamId(this.retiredIncoming, state.streamId);
state.openController.abort(reason);
state.updateSequence = Math.max(1, state.updateSequence + 1);
let sendError;
@@ -477,8 +447,6 @@ class PluginStreamRouter {
} catch {}
}
this.incoming.clear();
this.retiredIncoming.clear();
this.retiredOutgoing.clear();
}
}
-46
View File
@@ -496,49 +496,3 @@ test("oversized binary writes fail before consuming stream credit", async () =>
assert.equal(sent.length, 1);
assert.equal(router.outgoing.get("oversized").availableBytes, contract.PLUGIN_STREAM_MAX_WINDOW_BYTES);
});
test("crossing cancel/end frames on retired streams do not throw protocol errors and end refunds remaining credit", async () => {
const sent = [];
const contract = await import("@netcatty/plugin-contract");
let incomingHandle;
const router = new PluginStreamRouter({
send(message) { sent.push(message); },
onIncomingStream(stream) {
incomingHandle = stream;
stream.bind({ onChunk: async () => {}, onClose: () => {} });
return true;
},
});
// 1. Host cancels incoming while producer has in-flight chunk + end frames.
await router.accept({
frame: { streamId: "race-in", sequence: 0, kind: "open", windowBytes: 4096 },
});
await incomingHandle.cancel();
await router.accept({
frame: { streamId: "race-in", sequence: 1, kind: "chunk", data: contract.createJsonStreamChunk({ ok: true }) },
});
await router.accept({
frame: { streamId: "race-in", sequence: 2, kind: "end" },
});
// 2. Host ends outgoing at full credit while peer has an in-flight cancel frame.
const out = await router.openOutgoing("race-out", 4096);
out.end();
await router.accept({
frame: { streamId: "race-out", sequence: 1, kind: "cancel" },
});
// 3. Producer ends incoming stream before consumer calls release() -> host refunds unreturned credit.
sent.length = 0;
await router.accept({
frame: { streamId: "refund-end", sequence: 0, kind: "open", windowBytes: 4096 },
});
await router.accept({
frame: { streamId: "refund-end", sequence: 1, kind: "chunk", data: contract.createJsonStreamChunk({ hello: "world" }) },
});
await router.accept({
frame: { streamId: "refund-end", sequence: 2, kind: "end" },
});
assert.equal(sent.some((msg) => msg.frame?.streamId === "refund-end" && msg.frame?.kind === "windowUpdate"), true);
});
+1 -5
View File
@@ -164,7 +164,6 @@ class UtilityPluginRuntime {
const ready = waitForUtilityReady(this.child, PLUGIN_ACTIVATION_TIMEOUT_MS);
this.child.postMessage({ type: "netcatty-plugin:bootstrap", config });
await ready;
this.connected = true;
this.#assertStarting(signal);
const initialized = await this.router.request("plugin.initialize", {
netcattyVersion: config.netcattyVersion,
@@ -190,13 +189,10 @@ class UtilityPluginRuntime {
async #stop() {
this.stopping = true;
try {
if (this.connected) {
await this.router?.request("plugin.deactivate", {}, { timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS });
}
await this.router?.request("plugin.deactivate", {}, { timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS });
} finally {
const router = this.router;
this.router = null;
this.connected = false;
router?.close();
await this.#terminateAndWait();
}
+3 -32
View File
@@ -39,16 +39,6 @@ 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();
@@ -1596,28 +1586,9 @@ function createPreloadApi(ctx) {
return () => ipcRenderer.removeListener("netcatty:openTerminalPath", handler);
},
onColdStartIntentsSettled: (callback) => {
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);
};
const handler = () => callback();
ipcRenderer.on("netcatty:startup:coldStartIntentsSettled", handler);
return () => ipcRenderer.removeListener("netcatty:startup:coldStartIntentsSettled", handler);
},
setSshDeepLinkEnabled: (enabled) =>
ipcRenderer.invoke("netcatty:deepLink:ssh:setEnabled", { enabled }),
-59
View File
@@ -215,62 +215,3 @@ 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();
});
@@ -1,50 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { isWebSearchReady, type WebSearchConfig } from '../types';
import { executeWebSearch } from './toolExecutors';
const config: WebSearchConfig = { providerId: 'deepseek', enabled: true, apiKey: 'encrypted-test-key' };
function createDeps(aiFetch: (...args: unknown[]) => Promise<unknown>, apiHost?: string) {
return {
bridge: { aiExec: async () => ({ ok: true }), aiFetch },
context: { sessions: [] },
permissionMode: 'observer' as const,
webSearchConfig: { ...config, apiHost },
};
}
test('DeepSeek web search uses the bridge key and returns ranked summaries to the agent', async (t) => {
assert.equal(isWebSearchReady({ ...config, apiKey: undefined }), false);
assert.equal(isWebSearchReady(config), true);
const results = [
{ title: 'First', url: 'https://example.com/a', summary: 'Long summary', snippet: 'Short summary' },
{ title: 'Second', url: 'https://example.com/b', summary: '', snippet: 'Snippet only' },
];
const aiFetch = t.mock.fn(async () => ({ ok: true, data: JSON.stringify({ results }) }));
const query = 'site:example.com "release notes"';
const response = await executeWebSearch(createDeps(aiFetch), { query, maxResults: 2 });
assert.deepEqual(aiFetch.mock.calls.map(call => call.arguments), [[
'https://api.deepseek.com/v1/tools/search', 'POST',
{ 'Content-Type': 'application/json', Authorization: 'Bearer __WEB_SEARCH_KEY__' },
JSON.stringify({ query, count: 2 }),
]]);
assert.deepEqual(response, { ok: true, data: { results: [
{ title: 'First', url: 'https://example.com/a', content: 'Long summary' },
{ title: 'Second', url: 'https://example.com/b', content: 'Snippet only' },
] } });
});
test('DeepSeek accepts 128 Unicode code points and a versioned proxy URL', async (t) => {
const aiFetch = t.mock.fn(async () => ({ ok: true, data: '{"results":[]}' }));
const deps = createDeps(aiFetch, 'https://proxy.example.com/deepseek/v1/');
const query = '🌐'.repeat(128);
assert.deepEqual(await executeWebSearch(deps, { query }), { ok: true, data: { results: [] } });
for (const invalid of [' ', query + 'a']) {
const response = await executeWebSearch(deps, { query: invalid });
assert.equal(response.ok, false);
assert.match(response.error, /1 to 128 Unicode characters/);
}
assert.equal(aiFetch.mock.callCount(), 1);
assert.equal(aiFetch.mock.calls[0].arguments.at(0), 'https://proxy.example.com/deepseek/v1/tools/search');
});
@@ -130,37 +130,6 @@ async function searchBocha(
}));
}
// ---------------------------------------------------------------------------
// DeepSeek
// ---------------------------------------------------------------------------
async function searchDeepSeek(
bridge: NetcattyBridge,
config: WebSearchConfig,
query: string,
maxResults: number,
): Promise<WebSearchResult[]> {
const searchQuery = query.trim();
if (!searchQuery || Array.from(searchQuery).length > 128) {
throw new Error('DeepSeek search queries must contain 1 to 128 Unicode characters.');
}
const host = resolveApiHost(config).replace(/\/+$/, '');
const base = host.endsWith('/v1') ? host : `${host}/v1`;
const data = await fetchJson(bridge, `${base}/tools/search`, 'POST', {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.apiKey}`,
}, JSON.stringify({ query: searchQuery, count: Math.trunc(maxResults) })) as {
results: Array<{ title: string; url: string; summary: string; snippet: string }>;
};
return data.results.map(r => ({
title: r.title,
url: r.url,
content: r.summary || r.snippet,
}));
}
// ---------------------------------------------------------------------------
// Zhipu
// ---------------------------------------------------------------------------
@@ -219,7 +188,6 @@ const PROVIDER_SEARCH_FNS: Record<string, typeof searchTavily> = {
tavily: searchTavily,
exa: searchExa,
bocha: searchBocha,
deepseek: searchDeepSeek,
zhipu: searchZhipu,
searxng: searchSearxng,
};
+1 -2
View File
@@ -399,7 +399,7 @@ export interface DiscoveredAgent {
}
// Web Search types
export type WebSearchProviderId = 'tavily' | 'exa' | 'bocha' | 'deepseek' | 'zhipu' | 'searxng';
export type WebSearchProviderId = 'tavily' | 'exa' | 'bocha' | 'zhipu' | 'searxng';
export interface WebSearchConfig {
providerId: WebSearchProviderId;
@@ -413,7 +413,6 @@ export const WEB_SEARCH_PROVIDER_PRESETS: Record<WebSearchProviderId, { name: st
tavily: { name: 'Tavily', defaultApiHost: 'https://api.tavily.com', requiresApiKey: true },
exa: { name: 'Exa', defaultApiHost: 'https://api.exa.ai', requiresApiKey: true },
bocha: { name: 'Bocha', defaultApiHost: 'https://api.bochaai.com', requiresApiKey: true },
deepseek: { name: 'DeepSeek', defaultApiHost: 'https://api.deepseek.com', requiresApiKey: true },
zhipu: { name: 'Zhipu', defaultApiHost: 'https://open.bigmodel.cn/api/paas/v4', requiresApiKey: true },
searxng: { name: 'SearXNG', defaultApiHost: '', requiresApiKey: false },
};
+1 -1
View File
@@ -1028,7 +1028,7 @@ export class CloudSyncManager {
return reencryptSyncStorageImpl.call(this, oldKey, newKey, newConfig);
}
private clearSyncBase(): Promise<void> {
private clearSyncBase(): void {
return clearSyncBaseImpl.call(this);
}
@@ -28,16 +28,13 @@ import {
registerPluginProviderIdImpl,
unregisterPluginProviderIdImpl,
} from './stateAndSecurityMethods';
import { deleteSyncBlobsFromIdb } from './syncBlobIdbStorage';
const SYNC_REMOTE_ANCHOR_STORAGE_KEY = 'netcatty_sync_remote_anchor_v1';
export function clearProviderMergeStateImpl(this: any, provider: CloudProvider): Promise<void> {
const baseKey = this.syncBaseKey(provider);
this.removeFromStorage(baseKey);
export function clearProviderMergeStateImpl(this: any, provider: CloudProvider): void {
this.removeFromStorage(this.syncBaseKey(provider));
this.removeFromStorage(this.convergentProviderBaselineKey(provider));
this.clearSyncAnchor(provider);
return deleteSyncBlobsFromIdb([baseKey]);
}
export async function startProviderAuthImpl(this: any,
@@ -160,7 +157,7 @@ export async function completeGitHubAuthImpl(this: any,
const previousId = this.loadProviderAccountId('github') ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
await clearProviderMergeStateImpl.call(this, 'github');
clearProviderMergeStateImpl.call(this, 'github');
}
if (newId) {
this.saveProviderAccountId('github', newId);
@@ -258,7 +255,7 @@ export async function completePKCEAuthImpl(this: any,
const previousId = this.loadProviderAccountId(provider) ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
await clearProviderMergeStateImpl.call(this, provider);
clearProviderMergeStateImpl.call(this, provider);
}
if (newId) {
this.saveProviderAccountId(provider, newId);
@@ -306,7 +303,7 @@ export async function connectConfigProviderImpl(this: any,
await this.saveProviderConnection(provider, this.state.providers[provider]);
// Clear all trusted merge state when changing endpoint or bucket.
await clearProviderMergeStateImpl.call(this, provider);
clearProviderMergeStateImpl.call(this, provider);
this.emit({
type: 'AUTH_COMPLETED',
provider,
@@ -439,7 +436,7 @@ export async function connectPluginProviderImpl(
|| previousConfigFp !== nextConfigFp
|| previousCredentialFp !== nextCredentialFp
) {
await clearProviderMergeStateImpl.call(this, providerId);
clearProviderMergeStateImpl.call(this, providerId);
}
this.emit({
type: 'AUTH_COMPLETED',
@@ -540,7 +537,7 @@ export async function disconnectProviderImpl(this: any,provider: CloudProvider):
unregisterPluginProviderIdImpl.call(this, provider);
// Clear all trusted merge state so a later account/resource cannot reuse
// an unrelated snapshot or convergent baseline.
await clearProviderMergeStateImpl.call(this, provider);
clearProviderMergeStateImpl.call(this, provider);
this.removeFromStorage(this.providerAccountIdKey(provider));
const adapter = this.adapters.get(provider);
if (adapter) {
@@ -16,12 +16,6 @@ import {
decryptLocalStorageValue,
encryptLocalStorageValue,
} from './encryptedLocalStorage';
import {
idbDeleteSyncBlobs,
idbGetSyncBlob,
idbPutSyncBlob,
isSyncBlobIdbAvailable,
} from './syncBlobIdbStorage';
/** Built-ins plus any dynamic plugin providers currently in manager state. */
function listedProviders(manager: any): CloudProvider[] {
@@ -123,29 +117,15 @@ export function clearConvergentSyncStorageImpl(this: any, confirmed: boolean): v
}
}
function syncBlobStorageKeys(manager: any): string[] {
const keys = new Set<string>([manager.syncBaseKey()]);
if (typeof manager.syncSnapshotsKey === 'function') {
keys.add(manager.syncSnapshotsKey());
}
const providers = new Set<CloudProvider>(listedProviders(manager));
if (typeof manager?.listRegisteredPluginProviderIds === 'function') {
for (const id of manager.listRegisteredPluginProviderIds()) {
providers.add(id as CloudProvider);
}
}
for (const provider of providers) {
keys.add(manager.syncBaseKey(provider));
if (typeof manager.syncSnapshotsKey === 'function') {
keys.add(manager.syncSnapshotsKey(provider));
}
}
return [...keys];
}
function localOnlyEncryptedSyncKeys(manager: any): string[] {
const keys = new Set<string>([SYNC_STORAGE_KEYS.CONVERGENT_REPLICA]);
function encryptedSyncStorageKeys(manager: any): string[] {
const keys = new Set<string>([
manager.syncBaseKey(),
manager.syncSnapshotsKey(),
SYNC_STORAGE_KEYS.CONVERGENT_REPLICA,
]);
for (const provider of listedProviders(manager)) {
keys.add(manager.syncBaseKey(provider));
keys.add(manager.syncSnapshotsKey(provider));
keys.add(manager.convergentProviderBaselineKey(provider));
}
return [...keys];
@@ -163,127 +143,54 @@ export async function reencryptSyncStorageImpl(
newKey: CryptoKey,
newConfig: MasterKeyConfig,
): Promise<void> {
const localOnlyKeys = localOnlyEncryptedSyncKeys(this);
const idbBlobKeys = syncBlobStorageKeys(this);
const idbAvailable = isSyncBlobIdbAvailable();
const keys = encryptedSyncStorageKeys(this);
const previousConfig = (
this.loadFromStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG)
?? this.state.masterKeyConfig
) as MasterKeyConfig | null;
const localOriginals = new Map<string, unknown>();
const localReplacements = new Map<string, string>();
const idbOriginals = new Map<string, string | null>();
const idbReplacements = new Map<string, string>();
const legacyKeysToRemove: string[] = [];
for (const key of localOnlyKeys) {
const originals = new Map<string, string | null>();
const replacements = new Map<string, string>();
for (const key of keys) {
const encoded = this.loadFromStorage(key) as unknown;
if (encoded == null) {
localOriginals.set(key, null);
originals.set(key, null);
continue;
}
if (typeof encoded !== 'string') throw new Error(`Encrypted sync record ${key} is invalid`);
localOriginals.set(key, encoded);
originals.set(key, encoded);
const value = await decryptLocalStorageValue<unknown>(encoded, oldKey);
localReplacements.set(key, await encryptLocalStorageValue(value, newKey));
replacements.set(key, await encryptLocalStorageValue(value, newKey));
}
for (const key of idbBlobKeys) {
const legacyEncoded = this.loadFromStorage(key) as unknown;
const idbEncoded = idbAvailable ? await idbGetSyncBlob(key) : null;
localOriginals.set(key, legacyEncoded ?? null);
if (idbAvailable) {
idbOriginals.set(key, idbEncoded);
}
if (idbEncoded !== null) {
const value = await decryptLocalStorageValue<unknown>(idbEncoded, oldKey);
idbReplacements.set(key, await encryptLocalStorageValue(value, newKey));
if (legacyEncoded != null) {
legacyKeysToRemove.push(key);
}
continue;
}
if (legacyEncoded == null) continue;
if (typeof legacyEncoded !== 'string') throw new Error(`Encrypted sync record ${key} is invalid`);
const value = await decryptLocalStorageValue<unknown>(legacyEncoded, oldKey);
const reencrypted = await encryptLocalStorageValue(value, newKey);
if (idbAvailable) {
idbReplacements.set(key, reencrypted);
legacyKeysToRemove.push(key);
} else {
localReplacements.set(key, reencrypted);
}
}
for (const [key, original] of localOriginals) {
for (const [key, original] of originals) {
const current = this.loadFromStorage(key) as unknown;
if ((current ?? null) !== original) {
throw new Error('Sync data changed while the master key was being rotated');
}
}
if (idbAvailable) {
for (const [key, original] of idbOriginals) {
const current = await idbGetSyncBlob(key);
if ((current ?? null) !== original) {
throw new Error('Sync data changed while the master key was being rotated');
}
}
}
const currentConfig = this.loadFromStorage(
SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG,
) as MasterKeyConfig | null;
if (JSON.stringify(currentConfig) !== JSON.stringify(previousConfig)) {
throw new Error('Master key configuration changed while it was being rotated');
}
const committedLocal: string[] = [];
const committedIdb: string[] = [];
const committed: string[] = [];
try {
for (const [key, replacement] of localReplacements) {
for (const [key, replacement] of replacements) {
if (this.saveToStorage(key, replacement) === false) {
throw new Error(`Unable to persist re-encrypted sync record: ${key}`);
}
committedLocal.push(key);
}
for (const [key, replacement] of idbReplacements) {
await idbPutSyncBlob(key, replacement, {
errorLabel: `re-encrypted sync record (${key})`,
});
committedIdb.push(key);
committed.push(key);
}
if (this.saveToStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG, newConfig) === false) {
throw new Error('Unable to persist the new master key configuration');
}
} catch (error) {
for (const key of committedIdb.reverse()) {
const original = idbOriginals.get(key) ?? null;
try {
if (original !== null) {
await idbPutSyncBlob(key, original);
} else {
await idbDeleteSyncBlobs([key]);
}
} catch (rollbackError) {
console.warn(`[CloudSyncManager] Failed to roll back IndexedDB sync record ${key}`, rollbackError);
}
}
for (const key of committedLocal.reverse()) {
const original = localOriginals.get(key);
if (original !== undefined && original !== null) this.saveToStorage(key, original);
for (const key of committed.reverse()) {
const original = originals.get(key);
if (original !== undefined) this.saveToStorage(key, original);
}
if (previousConfig) this.saveToStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG, previousConfig);
else this.removeFromStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG);
throw error;
}
for (const key of legacyKeysToRemove) {
try {
this.removeFromStorage(key);
} catch (removeError) {
console.warn(`[CloudSyncManager] Failed to remove migrated legacy sync record ${key}`, removeError);
}
}
}
@@ -41,7 +41,6 @@ import {
import type { CloudAdapter } from '../adapters';
import type { SyncManagerState } from '../CloudSyncManager';
import { getConvergentSyncLocalConfig } from '../convergentSyncConfig';
import { deleteSyncBlobsFromIdb } from './syncBlobIdbStorage';
const SYNC_HISTORY_STORAGE_KEY = 'netcatty_sync_history_v1';
@@ -744,9 +743,7 @@ export function handleStorageEventImpl(this: any, event: StorageEvent): void {
// config/resource changes do on the connect path (authMethods).
if (credentialChanged) {
try {
const baseKey = this.syncBaseKey(provider);
this.removeFromStorage(baseKey);
void deleteSyncBlobsFromIdb([baseKey]);
this.removeFromStorage(this.syncBaseKey(provider));
this.removeFromStorage(this.convergentProviderBaselineKey(provider));
this.clearSyncAnchor(provider);
} catch {
@@ -27,11 +27,6 @@ import type {
} from "../../../domain/sync.ts";
import { setConvergentSyncLocalConfig } from "../convergentSyncConfig.ts";
import { saveProviderConnectionImpl } from "./stateAndSecurityMethods.ts";
import {
SYNC_BLOB_IDB_STORE_NAME,
resetSyncBlobIdbForTests,
} from "./syncBlobIdbStorage.ts";
import { installFakeIndexedDb } from "../../../application/state/testSupport/fakeIndexedDb.ts";
function payload(hostId: string): SyncPayload {
return payloadWithHosts([hostId]);
@@ -685,8 +680,6 @@ test("commitRemoteInspection does not advance the remote anchor when saving the
test("saveSyncBase reports storage failures so callers do not advance anchors", async () => {
const originalWarn = console.warn;
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb({ failOpen: true });
const manager = {
state: {
unlockedKey: {
@@ -698,25 +691,24 @@ test("saveSyncBase reports storage failures so callers do not advance anchors",
},
},
syncBaseKey: () => "sync-base",
saveToStorage: () => {
throw new Error("storage full");
},
};
console.warn = () => {};
try {
await assert.rejects(
() => saveSyncBaseImpl.call(manager, payload("cloud"), "github"),
/Unable to persist local sync baseline in IndexedDB/,
/storage full/,
);
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test("guarded provider saves cannot recreate state cleared during an await", async () => {
const stored = new Map<string, unknown>();
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"],
);
@@ -734,9 +726,6 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
stored.set(storageKey, value);
return true;
},
removeFromStorage: (storageKey: string) => {
stored.delete(storageKey);
},
createSyncedFileSignature: () => new Promise<string>((resolve) => {
setImmediate(() => resolve("signature"));
}),
@@ -750,14 +739,10 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
providerChanged = true;
stored.delete("base:github");
stored.delete("snapshots:github");
const idbStore = fakeIdb.db.getOrCreateStore(SYNC_BLOB_IDB_STORE_NAME);
idbStore.delete("base:github");
idbStore.delete("snapshots:github");
});
await assert.rejects(baseSave, /provider changed/);
assert.equal(stored.has("base:github"), false);
assert.equal(stored.has("snapshots:github"), false);
assert.deepEqual(fakeIdb.db.dumpStore(SYNC_BLOB_IDB_STORE_NAME), []);
providerChanged = false;
const anchorSave = saveSyncAnchorImpl.call(
@@ -807,8 +792,6 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
assert.equal(savedConnection.tokens.accessToken, "fresh");
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
@@ -827,8 +810,6 @@ test("saveSyncBase reports a missing local encryption key", async () => {
test("saveSyncBase keeps a bounded encrypted snapshot history before replacing the base", async () => {
const stored = new Map<string, string>();
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
@@ -840,27 +821,20 @@ test("saveSyncBase keeps a bounded encrypted snapshot history before replacing t
syncSnapshotsKey: (provider?: CloudProvider) => `snapshots-${provider ?? "default"}`,
saveToStorage: (storageKey: string, value: string) => stored.set(storageKey, value),
loadFromStorage: (storageKey: string) => stored.get(storageKey),
removeFromStorage: (storageKey: string) => stored.delete(storageKey),
};
try {
await saveSyncBaseImpl.call(manager, payload("base-0"), "github");
for (let i = 1; i <= 7; i += 1) {
await saveSyncBaseImpl.call(manager, payload(`base-${i}`), "github");
}
const snapshots = await loadSyncSnapshotsImpl.call(manager, "github");
assert.equal(snapshots.length, 5);
assert.deepEqual(
snapshots.map((snapshot) => snapshot.payload.hosts[0]?.id),
["base-6", "base-5", "base-4", "base-3", "base-2"],
);
assert.equal(stored.size, 0);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
await saveSyncBaseImpl.call(manager, payload("base-0"), "github");
for (let i = 1; i <= 7; i += 1) {
await saveSyncBaseImpl.call(manager, payload(`base-${i}`), "github");
}
const snapshots = await loadSyncSnapshotsImpl.call(manager, "github");
assert.equal(snapshots.length, 5);
assert.deepEqual(
snapshots.map((snapshot) => snapshot.payload.hosts[0]?.id),
["base-6", "base-5", "base-4", "base-3", "base-2"],
);
});
test("syncAllProviders builds provider-specific sync metadata from each provider base", async () => {
@@ -41,13 +41,6 @@ import {
decryptLocalStorageValue,
encryptLocalStorageValue,
} from './encryptedLocalStorage';
import {
deleteSyncBlobsFromIdb,
idbGetSyncBlob,
idbPutSyncBlob,
idbPutSyncBlobIfAbsent,
isSyncBlobIdbAvailable,
} from './syncBlobIdbStorage';
function getSyncSecurityGeneration(manager: any): number | undefined {
return typeof manager.getSyncSecurityGeneration === 'function'
@@ -142,77 +135,12 @@ function persistedProviderIdentity(provider: CloudProvider, connection: Provider
async function loadRawSyncBase(this: any, provider?: CloudProvider): Promise<SyncPayload | null> {
const key = this.state.unlockedKey?.derivedKey;
if (!key) return null;
const storageKey = this.syncBaseKey(provider);
let encoded: unknown = null;
if (isSyncBlobIdbAvailable()) {
try {
encoded = await idbGetSyncBlob(storageKey);
} catch {
encoded = null;
}
}
if (!encoded && typeof this.loadFromStorage === 'function') {
encoded = this.loadFromStorage(storageKey);
}
if (!key || typeof this.loadFromStorage !== 'function') return null;
const encoded = this.loadFromStorage(this.syncBaseKey(provider));
if (!encoded || typeof encoded !== 'string') return null;
return decryptLocalStorageValue<SyncPayload>(encoded, key);
}
async function loadEncryptedSyncBlobWithMigration<T>(
manager: any,
storageKey: string,
key: CryptoKey,
isValid?: (value: T) => boolean,
): Promise<T | null> {
let idbEncoded: string | null = null;
let idbReadable = false;
if (isSyncBlobIdbAvailable()) {
try {
idbEncoded = await idbGetSyncBlob(storageKey);
idbReadable = true;
} catch (error) {
console.warn(
`[CloudSyncManager] Failed to read ${storageKey} from IndexedDB; falling back to legacy localStorage`,
error,
);
}
}
if (idbEncoded !== null) {
const value = await decryptLocalStorageValue<T>(idbEncoded, key);
if (isValid && !isValid(value)) return null;
return value;
}
const legacyEncoded = typeof manager.loadFromStorage === 'function'
? (manager.loadFromStorage(storageKey) as unknown)
: null;
if (!legacyEncoded || typeof legacyEncoded !== 'string') return null;
const decrypted = await decryptLocalStorageValue<T>(legacyEncoded, key);
if (isValid && !isValid(decrypted)) return null;
if (idbReadable) {
try {
await idbPutSyncBlobIfAbsent(storageKey, legacyEncoded);
try {
manager.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove migrated legacy sync key ${storageKey}`,
removeError,
);
}
} catch (migrateError) {
console.warn(
`[CloudSyncManager] Failed to migrate ${storageKey} to IndexedDB; keeping legacy localStorage copy`,
migrateError,
);
}
}
return decrypted;
}
async function rememberCurrentSyncBaseSnapshot(this: any,
provider?: CloudProvider,
assertCanPersist?: () => void,
@@ -1276,18 +1204,8 @@ export async function saveSyncBaseImpl(this: any,
}
const encrypted = await encryptLocalStorageValue(payload, key);
assertCanPersist?.();
const storageKey = this.syncBaseKey(provider);
await idbPutSyncBlob(storageKey, encrypted, {
assertCanWrite: assertCanPersist,
errorLabel: 'sync baseline',
});
try {
this.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove legacy sync base key ${storageKey}`,
removeError,
);
if (this.saveToStorage(this.syncBaseKey(provider), encrypted) === false) {
throw new Error('Unable to persist sync base');
}
} catch (error) {
console.warn('[CloudSyncManager] Failed to save sync base', error);
@@ -1299,11 +1217,9 @@ export async function loadSyncBaseImpl(this: any,provider?: CloudProvider): Prom
const key = this.state.unlockedKey?.derivedKey;
if (!key) return null;
try {
return await loadEncryptedSyncBlobWithMigration<SyncPayload>(
this,
this.syncBaseKey(provider),
key,
);
const encoded = this.loadFromStorage(this.syncBaseKey(provider)) as unknown;
if (!encoded || typeof encoded !== 'string') return null;
return decryptLocalStorageValue<SyncPayload>(encoded, key);
} catch {
return null;
}
@@ -1318,13 +1234,10 @@ export async function loadSyncSnapshotsImpl(this: any,provider?: CloudProvider):
const key = this.state.unlockedKey?.derivedKey;
if (!key) return [];
try {
const snapshots = await loadEncryptedSyncBlobWithMigration<SyncSnapshotEntry[]>(
this,
this.syncSnapshotsKey(provider),
key,
(value) => Array.isArray(value),
);
return snapshots ?? [];
const encoded = this.loadFromStorage(this.syncSnapshotsKey(provider)) as unknown;
if (!encoded || typeof encoded !== 'string') return [];
const snapshots = await decryptLocalStorageValue<SyncSnapshotEntry[]>(encoded, key);
return Array.isArray(snapshots) ? snapshots : [];
} catch {
return [];
}
@@ -1341,40 +1254,15 @@ export async function saveSyncSnapshotsImpl(this: any,
}
const encrypted = await encryptLocalStorageValue(snapshots.slice(0, SYNC_SNAPSHOT_LIMIT), key);
assertCanPersist?.();
const storageKey = this.syncSnapshotsKey(provider);
await idbPutSyncBlob(storageKey, encrypted, {
assertCanWrite: assertCanPersist,
errorLabel: 'sync snapshots',
});
try {
this.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove legacy sync snapshots key ${storageKey}`,
removeError,
);
if (this.saveToStorage(this.syncSnapshotsKey(provider), encrypted) === false) {
throw new Error('Unable to persist sync snapshots');
}
}
export function clearSyncBaseImpl(this: any): Promise<void> {
const idbKeys = new Set<string>([
SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD,
SYNC_SNAPSHOTS_STORAGE_KEY,
]);
export function clearSyncBaseImpl(this: any): void {
this.removeFromStorage(SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD);
if (typeof this.syncBaseKey === 'function') {
const defaultBaseKey = this.syncBaseKey();
if (defaultBaseKey) {
idbKeys.add(defaultBaseKey);
if (defaultBaseKey !== SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD) {
this.removeFromStorage(defaultBaseKey);
}
}
}
if (typeof this.syncSnapshotsKey === 'function') {
const defaultSnapshotsKey = this.syncSnapshotsKey();
idbKeys.add(defaultSnapshotsKey);
this.removeFromStorage(defaultSnapshotsKey);
this.removeFromStorage(this.syncSnapshotsKey());
}
const providers = new Set<CloudProvider>([
'github', 'google', 'onedrive', 'webdav', 's3',
@@ -1388,18 +1276,13 @@ export function clearSyncBaseImpl(this: any): Promise<void> {
}
}
for (const p of providers) {
const baseKey = this.syncBaseKey(p);
idbKeys.add(baseKey);
this.removeFromStorage(baseKey);
this.removeFromStorage(this.syncBaseKey(p));
this.removeFromStorage(this.convergentProviderBaselineKey(p));
if (typeof this.syncSnapshotsKey === 'function') {
const snapshotsKey = this.syncSnapshotsKey(p);
idbKeys.add(snapshotsKey);
this.removeFromStorage(snapshotsKey);
this.removeFromStorage(this.syncSnapshotsKey(p));
}
}
this.clearSyncAnchor();
return deleteSyncBlobsFromIdb([...idbKeys]);
}
export function addSyncHistoryEntryImpl(this: any,entry: Omit<SyncHistoryEntry, 'id'>): void {
@@ -1420,7 +1303,7 @@ export function resetLocalVersionImpl(this: any): void {
this.state.syncHistory = [];
this.saveSyncConfig();
this.saveToStorage(SYNC_HISTORY_STORAGE_KEY, []);
void this.clearSyncBase();
this.clearSyncBase();
this.clearSyncAnchor();
this.notifyStateChange();
}
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more