Compare commits

..
129 changed files with 549 additions and 5885 deletions

No files matched your search

+1 -1
View File
@@ -100,7 +100,7 @@ Placement rules (`resolveAgentKinds` in `toolSurfaces.cjs`):
| Vault bridge | `electron/bridges/aiBridge/vaultAgentBridge.cjs` + `infrastructure/ai/vaultAgentBridgeClient.ts` | Renderer vault state; **never** returns password/privateKey |
| AI context | `buildAITerminalSessionInfo` + `useTerminalAiContexts` | Per-session `hostChain` + `activePortForwards`; mirrored in `getContext` and Catty system prompt |
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes. `terminal_execute_bulk` (2–20 sessions, loaded via the `terminal_bulk` toolset) is all-or-nothing before sending and sets `policy.requiresFreshApproval`: remembered grants and external-client session approval never satisfy it. See `docs/features/terminal-execute-bulk.md`. `terminal_start_bulk` (same toolset) applies the same rules to background jobs and returns a `bulkId` for `terminal_poll_bulk` / `terminal_stop_bulk`; stop needs no approval. See `docs/features/terminal-bulk-jobs.md`.
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes. `terminal_execute_bulk` (2–20 sessions, loaded via the `terminal_bulk` toolset) is all-or-nothing before sending and sets `policy.requiresFreshApproval`: remembered grants and external-client session approval never satisfy it. See `docs/features/terminal-execute-bulk.md`.
**Handles:** `ToolOutputStore` persists across turns per chat session; cleared on chat session delete. Large `sftp.read` results spill to `tool_output_read`.
-20
View File
@@ -331,26 +331,6 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
if (binding.category === 'sftp') {
continue;
}
if (binding.action === 'commandPalette') {
const hasOpenHostModal = Array.from(
document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]:not([data-plugin-dialog])'),
).some((el) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (!hasOpenHostModal) {
const inPluginSurface = Boolean(target?.closest?.('[data-plugin-remote-surface]'));
const activeFullBleedSurface = inPluginSurface || Array.from(
document.querySelectorAll<HTMLElement>('[data-plugin-chrome="full-bleed"] [data-plugin-remote-surface]'),
).some((el) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (activeFullBleedSurface) {
return;
}
}
}
if (TERMINAL_PASSTHROUGH_ACTIONS.has(binding.action)) {
if (isTerminalElement) {
return;
+1 -2
View File
@@ -281,7 +281,7 @@ function AppViewInner({ domains }: AppViewProps) {
handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit,
handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect,
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions,
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
@@ -734,7 +734,6 @@ function AppViewInner({ domains }: AppViewProps) {
/>
<TerminalLayerMount
isVaultInitialized={isVaultInitialized}
hosts={terminalHosts}
portForwardingRules={portForwardingRules}
customGroups={customGroups}
-2
View File
@@ -55,7 +55,6 @@ export function VaultHost() {
hosts: vault.hosts,
identities: vault.identities,
importOrReuseKey: actions?.importOrReuseKey,
isVaultInitialized: vault.isVaultInitialized,
keys: vault.keys,
managedSources: vault.managedSources,
navigateToSection: local.navigateToSection,
@@ -91,7 +90,6 @@ export function VaultHost() {
vault.groupConfigs,
vault.hosts,
vault.identities,
vault.isVaultInitialized,
vault.keys,
vault.managedSources,
vault.proxyProfiles,
@@ -1,233 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import React, { useEffect, useLayoutEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import {
EMPTY_VAULT_SNAPSHOT,
publishVaultSnapshot,
useVaultSnapshot,
useVaultSnapshotField,
} from '../state/vaultSnapshotStore.ts';
import {
publishAppShellDomainSlice,
useAppShellProps,
} from './appShellPropsStore.ts';
import { registerAppHandlers } from './appHandlersBridge.ts';
import { resolveTerminalVaultInitialized } from '../../components/terminal/restoredSessionGate.ts';
import { terminalLayerAreEqual } from '../../components/terminalLayerMemo.ts';
import {
terminalLayerViewCtxEqual,
terminalLayerWorkspaceCtxEqual,
} from '../../components/terminalLayer/terminalLayerViewMemo.ts';
import type { Host, Identity, SSHKey } from '../../domain/models.ts';
const storageBacking = new Map<string, string>();
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (key: string) => storageBacking.get(key) ?? null,
setItem: (key: string, value: string) => {
storageBacking.set(key, value);
},
removeItem: (key: string) => {
storageBacking.delete(key);
},
clear: () => {
storageBacking.clear();
},
},
});
const { VaultHost } = await import('./hosts/VaultHost.tsx');
test('VaultHost keeps isVaultInitialized synchronized with hydrated hosts, keys, and identities for Terminal boot (#4428)', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
(globalThis as Record<string, unknown>).window = dom.window;
(globalThis as Record<string, unknown>).document = dom.window.document;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
const host: Host = {
id: 'host-1',
label: 'test-myhost',
hostname: '10.243.2.249',
port: 22,
username: 'user1',
authMethod: 'key',
identityFileId: 'key-1',
tags: [],
createdAt: 0,
};
const key: SSHKey = {
id: 'key-1',
label: 'Imported Key',
type: 'ED25519',
privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----',
publicKey: 'ssh-ed25519 AAAA test',
passphrase: 'secret',
source: 'imported',
category: 'key',
created: 0,
};
const identity: Identity = {
id: 'id-1',
label: 'User Identity',
username: 'user1',
authMethod: 'key',
keyId: 'key-1',
createdAt: 0,
};
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
registerAppHandlers({} as never);
// Mirror TerminalHost's layout-effect slice publication order (sibling after VaultHost).
function TerminalHostMirror() {
const vault = useVaultSnapshot();
useLayoutEffect(() => {
publishAppShellDomainSlice('terminal', { terminalHosts: vault.hosts });
}, [vault.hosts]);
return null;
}
const syncedBoots: Array<{
hostCount: number;
keyCount: number;
identityCount: number;
hasPrivateKey: boolean;
}> = [];
function SyncedTerminal({
vaultInitializedOverride,
hosts,
keys,
identities,
}: {
vaultInitializedOverride: boolean;
hosts: readonly Host[];
keys: readonly SSHKey[];
identities: readonly Identity[];
}) {
const sharedVaultInitialized = useVaultSnapshotField('isVaultInitialized');
const vaultInitialized = resolveTerminalVaultInitialized(
sharedVaultInitialized,
vaultInitializedOverride,
);
useEffect(() => {
if (!vaultInitialized) return;
syncedBoots.push({
hostCount: hosts.length,
keyCount: keys.length,
identityCount: identities.length,
hasPrivateKey: Boolean(keys[0]?.privateKey),
});
// Intentionally matches useTerminalEffects' boot effect dep shape (gated on vaultInitialized, not keys).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vaultInitialized]);
return null;
}
function ShellHarness() {
const { domains } = useAppShellProps();
const vaultDomain = domains?.vault as
| { isVaultInitialized?: boolean; keys?: readonly SSHKey[]; identities?: readonly Identity[] }
| undefined;
const terminalDomain = domains?.terminal as
| { terminalHosts?: readonly Host[] }
| undefined;
return React.createElement(
React.Fragment,
null,
React.createElement(VaultHost),
React.createElement(TerminalHostMirror),
vaultDomain && terminalDomain
? React.createElement(SyncedTerminal, {
vaultInitializedOverride: vaultDomain.isVaultInitialized ?? false,
hosts: terminalDomain.terminalHosts ?? [],
keys: vaultDomain.keys ?? [],
identities: vaultDomain.identities ?? [],
})
: null,
);
}
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await React.act(async () => {
root.render(React.createElement(ShellHarness));
});
assert.equal(syncedBoots.length, 0, 'restored terminal must not boot before vault hydration');
// Publish hydrated hosts, keys, identities, and isVaultInitialized together.
await React.act(async () => {
publishVaultSnapshot({
...EMPTY_VAULT_SNAPSHOT,
isVaultInitialized: true,
hosts: [host],
keys: [key],
identities: [identity],
});
});
assert.deepEqual(syncedBoots, [
{
hostCount: 1,
keyCount: 1,
identityCount: 1,
hasPrivateKey: true,
},
]);
} finally {
await React.act(async () => {
root.unmount();
});
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
registerAppHandlers(null);
(globalThis as Record<string, unknown>).window = prevWindow;
(globalThis as Record<string, unknown>).document = prevDocument;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
}
});
test('terminal layer memo comparators propagate isVaultInitialized changes', () => {
const baseLayerProps = {
isVaultInitialized: false,
hosts: [],
sessions: [],
};
assert.equal(
terminalLayerAreEqual(baseLayerProps, { ...baseLayerProps, isVaultInitialized: true }),
false,
);
assert.equal(
terminalLayerWorkspaceCtxEqual(
{ isVaultInitialized: false },
{ isVaultInitialized: true },
),
false,
);
assert.equal(
terminalLayerViewCtxEqual(
{ isVaultInitialized: false },
{ isVaultInitialized: true },
),
false,
);
const appViewSource = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8');
const supportSource = readFileSync(
new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url),
'utf8',
);
assert.match(appViewSource, /<TerminalLayerMount[\s\S]*?isVaultInitialized=\{isVaultInitialized\}/);
assert.match(supportSource, /vaultInitializedOverride=\{isVaultInitialized\}/);
});
-1
View File
@@ -98,7 +98,6 @@ export const enCoreMessages: Messages = {
'common.apply': 'Apply',
'common.use': 'Use',
'common.useGlobal': 'Use global',
'common.useGroup': 'Use group',
'common.saveChanges': 'Save Changes',
'common.advanced': 'Advanced',
'common.left': 'Left',
-1
View File
@@ -14,7 +14,6 @@ export const enTerminalMessages: Messages = {
'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.',
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
'terminal.directory.busy': 'Wait for an empty shell prompt.',
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
-4
View File
@@ -584,10 +584,6 @@ export const enVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Display files in a flat list for the current directory',
'settings.sftp.defaultViewMode.tree': 'Tree View',
'settings.sftp.defaultViewMode.treeDesc': 'Display files in a hierarchical tree structure',
'settings.sftp.treeFolderDoubleClick': 'Tree view folder double-click',
'settings.sftp.treeFolderDoubleClick.desc': 'Choose what happens when double-clicking a folder in SFTP Tree View. Clicking the chevron always expands or collapses in place.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Enter directory',
'settings.sftp.treeFolderDoubleClick.expand': 'Expand or collapse in place',
'sftp.autoSync.success': 'File synced to remote: {fileName}',
'sftp.autoSync.error': 'Failed to sync file: {error}',
-1
View File
@@ -98,7 +98,6 @@ export const esCoreMessages: Messages = {
'common.apply': 'Aplicar',
'common.use': 'Usar',
'common.useGlobal': 'Usar global',
'common.useGroup': 'Usar grupo',
'common.saveChanges': 'Guardar cambios',
'common.advanced': 'Avanzado',
'common.left': 'Izquierda',
-1
View File
@@ -14,7 +14,6 @@ export const esTerminalMessages: Messages = {
'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.',
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
-4
View File
@@ -584,10 +584,6 @@ export const esVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Muestra los archivos en una lista plana del directorio actual',
'settings.sftp.defaultViewMode.tree': 'Vista de árbol',
'settings.sftp.defaultViewMode.treeDesc': 'Muestra los archivos en una estructura de árbol jerárquica',
'settings.sftp.treeFolderDoubleClick': 'Doble clic en carpetas (vista de árbol)',
'settings.sftp.treeFolderDoubleClick.desc': 'Elige qué ocurre al hacer doble clic en una carpeta en la vista de árbol de SFTP. Hacer clic en la flecha siempre expande o contrae en su lugar.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Entrar en el directorio',
'settings.sftp.treeFolderDoubleClick.expand': 'Expandir o contraer en su lugar',
'sftp.autoSync.success': 'Archivo sincronizado con el remoto: {fileName}',
'sftp.autoSync.error': 'No se pudo sincronizar el archivo: {error}',
-1
View File
@@ -71,7 +71,6 @@ export const ruCoreMessages: Messages = {
'common.apply': 'Применить',
'common.use': 'Использовать',
'common.useGlobal': 'Использовать глобальное',
'common.useGroup': 'Использовать настройки группы',
'common.saveChanges': 'Сохранить изменения',
'common.advanced': 'Дополнительно',
'common.left': 'Слева',
-1
View File
@@ -14,7 +14,6 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.',
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
-4
View File
@@ -627,10 +627,6 @@ export const ruVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Показывать файлы в виде плоского списка для текущего каталога',
'settings.sftp.defaultViewMode.tree': 'Дерево',
'settings.sftp.defaultViewMode.treeDesc': 'Показывать файлы в иерархической древовидной структуре',
'settings.sftp.treeFolderDoubleClick': 'Двойной щелчок по папке в дереве',
'settings.sftp.treeFolderDoubleClick.desc': 'Выберите действие при двойном щелчке по папке в режиме дерева SFTP. Щелчок по стрелке всегда раскрывает или сворачивает папку на месте.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Перейти в каталог',
'settings.sftp.treeFolderDoubleClick.expand': 'Раскрыть или свернуть на месте',
'sftp.autoSync.success': 'Файл синхронизирован с удалённым сервером: {fileName}',
'sftp.autoSync.error': 'Не удалось синхронизировать файл: {error}',
@@ -285,22 +285,3 @@ test("localized vault messages include interactive authentication labels", () =>
assert.deepEqual(missing, [], `${locale.name} is missing interactive authentication labels`);
}
});
test("localized settings include SFTP tree folder double-click labels across all locales", () => {
const keys = [
"settings.sftp.treeFolderDoubleClick",
"settings.sftp.treeFolderDoubleClick.desc",
"settings.sftp.treeFolderDoubleClick.navigate",
"settings.sftp.treeFolderDoubleClick.expand",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing SFTP tree folder double-click labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
-1
View File
@@ -89,7 +89,6 @@ export const zhCNCoreMessages: Messages = {
'common.apply': '应用',
'common.use': '使用',
'common.useGlobal': '跟随全局',
'common.useGroup': '跟随分组',
'common.left': '左侧',
'common.right': '右侧',
'common.more': '更多',
@@ -14,7 +14,6 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.unavailable': '此会话暂不支持目录导航。',
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
@@ -191,10 +190,6 @@ export const zhCNTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表显示当前目录的文件',
'settings.sftp.defaultViewMode.tree': '树形视图',
'settings.sftp.defaultViewMode.treeDesc': '以层级树形结构显示文件',
'settings.sftp.treeFolderDoubleClick': '树形视图双击文件夹',
'settings.sftp.treeFolderDoubleClick.desc': '选择在 SFTP 树形视图中双击文件夹时的操作。点击左侧箭头始终在原处展开或折叠。',
'settings.sftp.treeFolderDoubleClick.navigate': '进入目录',
'settings.sftp.treeFolderDoubleClick.expand': '原地展开/折叠',
'sftp.autoSync.success': '文件已同步到远程:{fileName}',
'sftp.autoSync.error': '同步文件失败:{error}',
-1
View File
@@ -89,7 +89,6 @@ export const zhTWCoreMessages: Messages = {
'common.apply': '套用',
'common.use': '使用',
'common.useGlobal': '跟隨全域',
'common.useGroup': '跟隨群組',
'common.left': '左側',
'common.right': '右側',
'common.more': '更多',
@@ -14,7 +14,6 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。',
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -191,10 +190,6 @@ export const zhTWTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表顯示目前目錄的檔案',
'settings.sftp.defaultViewMode.tree': '樹形檢視',
'settings.sftp.defaultViewMode.treeDesc': '以層級樹形結構顯示檔案',
'settings.sftp.treeFolderDoubleClick': '樹形檢視雙擊資料夾',
'settings.sftp.treeFolderDoubleClick.desc': '選擇在 SFTP 樹形檢視中雙擊資料夾時的操作。點選左側箭頭始終在原地展開或摺疊。',
'settings.sftp.treeFolderDoubleClick.navigate': '進入目錄',
'settings.sftp.treeFolderDoubleClick.expand': '原地展開/摺疊',
'sftp.autoSync.success': '檔案已同步到遠端:{fileName}',
'sftp.autoSync.error': '同步檔案失敗:{error}',
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createPromptHostnameSessionSignalController } from './promptHostnameSessionSignalController.ts';
import { extractTerminalPromptHostname } from '../../domain/terminalPromptSecurity';
type Change = readonly [sessionId: string, hostname: string | null];
@@ -21,34 +20,10 @@ function createHarness() {
return { changes, controller };
}
test('prompt observations are independent of IP, alias, and matching connection addresses', () => {
const prompt = '[root@vm-prod ~]# ';
const observedHost = extractTerminalPromptHostname(prompt)!;
for (const hostname of ['203.0.113.10', 'alias.example.test', observedHost]) {
const changes: Change[] = [];
const controller = createPromptHostnameSessionSignalController({
getSession: () => ({ protocol: 'ssh', hostname }),
onChange: (sessionId, host) => changes.push([sessionId, host]),
});
controller.handleTerminalOutput('ssh-1', prompt);
assert.deepEqual(changes, [['ssh-1', observedHost]], hostname);
}
});
test('forgetting a session permits the first matching-host prompt to publish again', () => {
const { changes, controller } = createHarness();
const prompt = '[root@jump.example.com ~]# ';
const observedHost = extractTerminalPromptHostname(prompt)!;
controller.handleTerminalOutput('ssh-1', prompt);
controller.forgetSession('ssh-1');
controller.handleTerminalOutput('ssh-1', prompt);
assert.deepEqual(changes, [['ssh-1', observedHost], ['ssh-1', observedHost]]);
});
test('prompt host controller observes the initial jumpserver prompt', () => {
test('prompt host controller ignores the initial jumpserver prompt', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# ');
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname]]);
assert.deepEqual(changes, []);
});
test('prompt host controller publishes a nested target and de-duplicates it', () => {
@@ -56,18 +31,17 @@ test('prompt host controller publishes a nested target and de-duplicates it', ()
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# ');
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
});
test('prompt host controller observes the original host when returning from a target', () => {
test('prompt host controller clears the override when returning to the jumpserver', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
controller.handleTerminalOutput('ssh-1', 'exit\r\n[root@jump.example.com ~]# ');
assert.deepEqual(changes, [
['ssh-1', getSession('ssh-1').hostname],
['ssh-1', '10.1.64.1'],
['ssh-1', getSession('ssh-1').hostname],
['ssh-1', null],
]);
});
@@ -76,28 +50,26 @@ test('prompt host controller detects an identity split across output chunks', ()
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', 'ssh target\r\n[root@10.1.');
controller.handleTerminalOutput('ssh-1', '64.1 ~]# ');
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
});
test('prompt host controller ignores ambiguous, sensitive, and local output', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
const initialChanges = changes.slice();
controller.handleTerminalOutput('ssh-1', 'Password:\n# ');
controller.handleTerminalOutput('ssh-1', 'copied output\n# ');
controller.handleTerminalOutput('local-1', '[root@10.1.64.1 ~]# ');
assert.deepEqual(changes, initialChanges);
assert.deepEqual(changes, []);
});
test('prompt host controller ignores host-like text embedded in copied output', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
const initialChanges = changes.slice();
controller.handleTerminalOutput('ssh-1', 'see [root@prod] logs\n# ');
controller.handleTerminalOutput('ssh-1', '[root@prod] copied output\n# ');
controller.handleTerminalOutput('ssh-1', 'root@prod output\n# ');
controller.handleTerminalOutput('ssh-1', '[root@prod] version = 1.2\n# ');
assert.deepEqual(changes, initialChanges);
assert.deepEqual(changes, []);
});
test('prompt host controller publishes common zsh, Alpine, and macOS root prompt hosts', () => {
@@ -5,7 +5,7 @@ import {
} from '../../domain/terminalPromptSecurity';
type PromptHostnameSessionSignalOptions = {
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol'> | undefined;
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol' | 'hostname'> | undefined;
onChange: (sessionId: string, hostname: string | null) => void;
maxTailChars?: number;
};
@@ -22,18 +22,20 @@ export function createPromptHostnameSessionSignalController({
maxTailChars = DEFAULT_MAX_TAIL_CHARS,
}: PromptHostnameSessionSignalOptions) {
const tails = new Map<string, string>();
const baselines = new Map<string, string>();
const published = new Map<string, string>();
const tailLimit = Math.max(256, maxTailChars);
const forgetSession = (sessionId: string): void => {
tails.delete(sessionId);
baselines.delete(sessionId);
published.delete(sessionId);
};
return {
forgetSession,
pruneSessions(validSessionIds: ReadonlySet<string>): void {
for (const sessionId of [...tails.keys(), ...published.keys()]) {
for (const sessionId of [...tails.keys(), ...baselines.keys(), ...published.keys()]) {
if (!validSessionIds.has(sessionId)) {
forgetSession(sessionId);
}
@@ -63,8 +65,19 @@ export function createPromptHostnameSessionSignalController({
const detectedKey = normalizedHostname(detected);
if (!detectedKey) return;
// Observe the prompt, not whether its hostname matches an IP or DNS alias.
// The domain title policy decides if this presentation is shown.
let baseline = baselines.get(sessionId);
if (baseline === undefined) {
baseline = normalizedHostname(session.hostname) || detectedKey;
baselines.set(sessionId, baseline);
}
if (detectedKey === baseline) {
if (!published.has(sessionId)) return;
published.delete(sessionId);
onChange(sessionId, null);
return;
}
if (published.get(sessionId) === detectedKey) return;
published.set(sessionId, detectedKey);
onChange(sessionId, detected);
@@ -10,89 +10,6 @@ import { DirectoryPickerError, directoryChangeCommand } from '../../domain/direc
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
for (const home of [null, '/tmp'] as const) {
test(`command invalidation retains only the compose display (home=${home})`, async t => {
const id = 'hook-sticky-cwd-' + home;
let cwd = '/tmp/test_dir';
const writes: string[] = [];
const controller = createTerminalDirectoryController({
sessionId: id, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => cwd, home: async () => home, realpath: async path => path,
write: data => { writes.push(data); },
list: async () => ({ home, entries: [{ name: 'child', path: cwd + '/child', hidden: false }] }) },
publish: path => terminalCwdStore.setCwd(id, path, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, controller);
let model!: ReturnType<typeof useComposeDirectoryPicker>;
function Harness() { model = useComposeDirectoryPicker(id); return null; }
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness)); });
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); });
await act(async () => { model.setOpen(true); });
const label = home ? '~/test_dir' : cwd;
assert.equal(model.display?.label, label);
assert.equal(model.display?.title, cwd);
assert.equal(model.display?.ariaPath, label);
const revision = terminalCwdStore.getSessionRevision(id);
await act(async () => { terminalCwdStore.setCwd(id, null); });
assert.equal(model.cwd, null);
assert.equal(model.home, null);
assert.equal(terminalCwdStore.getCwd(id), null);
assert.equal(terminalCwdStore.getSource(id), undefined);
assert.ok(terminalCwdStore.getSessionRevision(id) > revision);
assert.equal(model.display?.label, label);
assert.equal(model.display?.title, cwd);
assert.equal(model.display?.ariaPath, label);
assert.equal(model.parent, null);
assert.deepEqual(model.entries, []);
await act(async () => { await model.change('/tmp'); });
assert.equal(model.error, 'unavailable');
await assert.rejects(controller.change('/tmp', new AbortController().signal, () => {}, cwd), { code: 'unavailable' });
assert.deepEqual(writes, []);
await act(async () => { await controller.refresh(); });
assert.equal(model.display?.label, label, 'restoring the same path preserves its home abbreviation');
await act(async () => { cwd = '/tmp/next'; await controller.refresh(); });
assert.equal(model.display?.label, home ? '~/next' : cwd);
assert.equal(model.display?.title, cwd);
});
}
for (const transition of ['session', 'controller', 'disconnect'] as const) {
test(`compose display never crosses a ${transition} boundary`, async t => {
const id = 'hook-display-boundary-' + transition;
const makeController = (sessionId: string, initial: boolean) => createTerminalDirectoryController({
sessionId, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => { if (!initial) throw new DirectoryPickerError('unknown'); return '/old/path'; },
home: async () => '/old', realpath: async path => path, write() {}, list: async () => ({ home: null, entries: [] }) },
publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, makeController(id, true));
let unregisterNext = () => {};
const renders: Array<ReturnType<typeof useComposeDirectoryPicker>['display']> = [];
let model!: ReturnType<typeof useComposeDirectoryPicker>;
function Harness({ session }: { session: string }) {
model = useComposeDirectoryPicker(session); renders.push(model.display); return null;
}
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness, { session: id })); });
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); unregisterNext(); });
assert.equal(model.display?.label, '~/path');
renders.length = 0;
await act(async () => {
if (transition === 'session') {
unregisterNext = registerTerminalDirectory(id + '-next', makeController(id + '-next', false));
root.update(React.createElement(Harness, { session: id + '-next' }));
} else if (transition === 'controller') {
// Leave the old backend value in the store: a new controller has not confirmed it.
unregisterNext = registerTerminalDirectory(id, makeController(id, false));
} else unregister();
});
assert.equal(model.cwd, null);
assert.equal(model.display, null);
assert.ok(renders.every(display => display === null), 'even the first render must discard the old display');
});
}
for (const outcome of ['complete', 'close', 'switch', 'repeated-reports'] as const) {
test(`unchanged OSC 7 during directory loading retries within the active menu (${outcome})`, async t => {
const id = 'hook-list-revision-' + outcome;
@@ -172,11 +89,9 @@ test('PowerShell non-filesystem reports clear an open menu and recover after ret
assert.equal(model.pathFlavor, 'win32');
assert.equal(model.parent, 'C:\\');
assert.equal(model.entries.length, 1);
assert.equal(model.display?.title, 'C:\\base');
await act(async () => { filesystem = false; await controller.refresh().catch(() => {}); });
assert.equal(model.cwd, null);
assert.equal(model.home, null);
assert.equal(model.display, null, 'native provider failures must not retain a filesystem label');
assert.equal(model.error, 'nonFilesystem');
assert.deepEqual(model.entries, []);
await act(async () => { filesystem = true; await controller.refresh(); });
+11 -22
View File
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
import { terminalCwdStore } from './terminalCwdStore';
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
@@ -8,8 +7,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const [confirmed, setConfirmed] = useState(false);
const observedCwd = terminalCwdStore.getCwd(sessionId);
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
@@ -18,15 +16,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
const [query, setQuery] = useState('');
const [showHidden, setShowHidden] = useState(false);
const [entries, setEntries] = useState<DirectoryEntry[]>([]);
const [homeResult, setHomeResult] = useState<{ sessionId: string; controller: typeof controller; value: string | null } | null>(null);
const home = homeResult?.sessionId === sessionId && homeResult.controller === controller ? homeResult.value : null;
const setHome = useCallback((value: string | null) => setHomeResult({ sessionId, controller, value }), [sessionId, controller]);
// Controller identity scopes the display to one connected shell generation.
const displayCache = useRef<{ sessionId: string; controller: typeof controller; value: ComposeDirectoryDisplay | null } | null>(null);
const previousDisplay = displayCache.current?.sessionId === sessionId && displayCache.current.controller === controller
? displayCache.current.value : null;
const display = resolveComposeDirectoryDisplay(previousDisplay, cwd, home, pathFlavor);
useEffect(() => { displayCache.current = { sessionId, controller, value: display }; }, [sessionId, controller, display]);
const [home, setHome] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [pending, setPending] = useState(false);
const listingBase = useRef<string | null>(null);
@@ -45,25 +35,25 @@ export function useComposeDirectoryPicker(sessionId: string) {
const stopObserving = observeTerminalDirectory(sessionId);
lifetime.current = new AbortController();
sending.current = false;
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
setConfirmed(false); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
listingBase.current = null;
listingRevision.current = null;
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
if (generation.current === id) { setConfirmed(true); setHome(nextHome); }
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
return () => {
generation.current = id + 1;
lifetime.current.abort(); read.current?.abort(); stopObserving();
};
}, [sessionId, controller, report, setHome]);
}, [sessionId, controller, report]);
const refresh = useCallback(async () => {
if (!controller) { setError('unavailable'); return; }
const id = generation.current;
setError(null);
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
try { await controller.refresh(); if (generation.current === id) setConfirmed(true); }
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
}, [controller, report, sessionId]);
}, [controller, report]);
const load = useCallback(async () => {
if (!controller || !cwd) return;
@@ -86,7 +76,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
} catch (failure) {
if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed');
} finally { if (!task.signal.aborted && id === generation.current) setLoading(false); }
}, [controller, cwd, report, sessionId, setHome]);
}, [controller, cwd, report, sessionId]);
useEffect(() => {
if (!cwd) {
@@ -97,7 +87,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
}
if (open) { setQuery(''); void load(); }
return () => { read.current?.abort(); };
}, [open, load, cwd, setHome]);
}, [open, load, cwd]);
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
@@ -119,9 +109,8 @@ export function useComposeDirectoryPicker(sessionId: string) {
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
@@ -1,125 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import {
resetModelCatalogWarningDismissals,
useModelCatalogWarningDismissal,
type ModelCatalogWarningDismissalState,
} from './useModelCatalogWarningDismissal.ts';
import { isModelCatalogWarningVisible } from '../../components/AIChatSidePanelHelpers.ts';
test('useModelCatalogWarningDismissal dismisses per cacheKey, survives remounts, and rearms on clean catalog', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
(globalThis as Record<string, unknown>).window = dom.window;
(globalThis as Record<string, unknown>).document = dom.window.document;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
resetModelCatalogWarningDismissals();
let latest!: ModelCatalogWarningDismissalState;
const Probe: React.FC = () => {
latest = useModelCatalogWarningDismissal();
return null;
};
const container = dom.window.document.getElementById('root')!;
let root = createRoot(container);
try {
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.size, 0);
const warningK1 = { cacheKey: 'k1', message: 'Catalog unavailable' };
const warningK2 = { cacheKey: 'k2', message: 'Other catalog unavailable' };
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Dismissing k1 hides only k1, leaving k2 visible.
await React.act(async () => {
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
assert.equal(
isModelCatalogWarningVisible(warningK2, 'k2', latest.dismissedKeys),
'Other catalog unavailable',
);
// Unmounting and remounting (e.g., empty panel hidden on tab/tool switch)
// must keep the dismissed cacheKey hidden until a clean catalog arrives.
await React.act(async () => {
root.unmount();
});
root = createRoot(container);
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
// Undefined and duplicate dismissals are no-ops that keep state identity.
const setBeforeNoop = latest.dismissedKeys;
await React.act(async () => {
latest.dismissWarning(undefined);
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys, setBeforeNoop);
// A clean catalog for k1 re-arms k1 so future failures surface again.
await React.act(async () => {
latest.rearmWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), false);
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Rearming a non-dismissed or undefined key is a no-op.
const setAfterRearm = latest.dismissedKeys;
await React.act(async () => {
latest.rearmWarning('k1');
latest.rearmWarning(undefined);
});
assert.equal(latest.dismissedKeys, setAfterRearm);
} finally {
await React.act(async () => {
root.unmount();
});
resetModelCatalogWarningDismissals();
(globalThis as Record<string, unknown>).window = prevWindow;
(globalThis as Record<string, unknown>).document = prevDocument;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
}
});
test('AIChatPanelContent keeps raw modelCatalogWarning for ChatInput when banner is dismissed', () => {
const panelSource = readFileSync(new URL('../../components/AIChatPanelContent.tsx', import.meta.url), 'utf8');
const sidePanelSource = readFileSync(new URL('../../components/AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(
panelSource,
/modelCatalogWarning && !modelCatalogWarningDismissed \?/,
'banner visibility must check modelCatalogWarningDismissed separately from raw modelCatalogWarning',
);
assert.match(
panelSource,
/<ChatInput[\s\S]*?modelCatalogWarning=\{modelCatalogWarning\}/,
'ChatInput must still receive the raw modelCatalogWarning so ComposerModelPicker keeps its refresh action',
);
assert.match(
sidePanelSource,
/useModelCatalogWarningDismissal\(\)/,
'AIChatSidePanel must consume the application/state dismissal hook rather than owning inline dismissal state',
);
});
@@ -1,70 +0,0 @@
import { useSyncExternalStore } from 'react';
export interface ModelCatalogWarningDismissalState {
dismissedKeys: ReadonlySet<string>;
dismissWarning: (cacheKey: string | undefined) => void;
rearmWarning: (cacheKey: string | undefined) => void;
}
type Listener = () => void;
let dismissedKeysSnapshot: ReadonlySet<string> = new Set();
const listeners = new Set<Listener>();
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function subscribe(listener: Listener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
function getSnapshot(): ReadonlySet<string> {
return dismissedKeysSnapshot;
}
export function dismissModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.add(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function rearmModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || !dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.delete(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function resetModelCatalogWarningDismissals(): void {
if (dismissedKeysSnapshot.size === 0) return;
dismissedKeysSnapshot = new Set();
emitChange();
}
/**
* Tracks SDK model catalog cache keys whose composer warning banner was
* dismissed by the user.
*
* Stored at module scope so dismissals survive empty-panel unmounts during
* normal tab/tool navigation and stay consistent with the shared
* `sdkRuntimeModelCache`. Dismissals remain scoped by cacheKey so switching
* agents or config re-arms the banner, and a clean catalog load clears that
* key so a later failure warns again.
*/
export function useModelCatalogWarningDismissal(): ModelCatalogWarningDismissalState {
const dismissedKeys = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return {
dismissedKeys,
dismissWarning: dismissModelCatalogWarningKey,
rearmWarning: rearmModelCatalogWarningKey,
};
}
+12 -6
View File
@@ -11,7 +11,7 @@ import {
publishTerminalSettingsSnapshot,
registerTerminalSettingsActions,
} from './terminalSettingsStore';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import {
normalizeAppLockTimeoutMinutes,
type AppLockSettings,
@@ -97,7 +97,6 @@ import {
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding as updateCustomKeyBindingRecord,
@@ -1940,10 +1939,17 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
}, []);
// Get merged key bindings (defaults + custom overrides)
const keyBindings = useMemo(
() => resolveKeyBindings(DEFAULT_KEY_BINDINGS, customKeyBindings),
[customKeyBindings],
);
const keyBindings = useMemo((): KeyBinding[] => {
return DEFAULT_KEY_BINDINGS.map(binding => {
const custom = customKeyBindings[binding.id];
if (!custom) return binding;
return {
...binding,
mac: custom.mac ?? binding.mac,
pc: custom.pc ?? binding.pc,
};
});
}, [customKeyBindings]);
// Update a single key binding
const updateKeyBinding = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => {
@@ -5,9 +5,8 @@ import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { createTerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { createTerminalDirectoryController } from './terminalDirectoryController';
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell.cjs';
export function useTerminalDirectorySession(options: {
sessionId: string;
@@ -34,7 +33,7 @@ export function useTerminalDirectorySession(options: {
let active = true;
const isCurrent = () => active && live.current.status === 'connected' && live.current.getBackendId() === backendId;
let unregister = () => {};
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
const register = (pathFlavor: DirectoryPathFlavor = 'posix') => {
if (!isCurrent()) return;
const controller = createTerminalDirectoryController({
sessionId,
@@ -42,11 +41,11 @@ export function useTerminalDirectorySession(options: {
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
encoding: host.sftpEncoding,
pathFlavor,
windowsShell: integration,
windowsShell,
}, isCurrent),
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
buildChangeCommand: path => directoryChangeCommand(path, windowsShell ?? 'posix', pathFlavor),
isCurrent,
isReady: () => live.current.isReady(),
publish: cwd => live.current.publish(cwd),
@@ -54,18 +53,13 @@ export function useTerminalDirectorySession(options: {
unregister = registerTerminalDirectory(sessionId, controller);
};
if (local) {
void bridge.getAppInfo?.().then(async info => {
// POSIX wrappers on Windows still use win32 PTYs. Neither their cwd nor
// their path namespace is supported by readLocalSessionCwd/local FS.
void bridge.getAppInfo?.().then(info => {
if ((info.platform === 'darwin' || info.platform === 'linux') && !windowsShell) register();
if (info.platform !== 'win32' || !isCurrent()) return;
if (windowsShell) register('win32', windowsShell);
else if (shellType === 'posix' && host.localShell) {
const shells = await bridge.discoverShells?.();
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
}
}
else if (info.platform === 'win32' && windowsShell) register('win32');
}).catch(() => {});
} else register();
return () => { active = false; unregister(); };
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, host.localShell, shellType, windowsShell]);
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, windowsShell]);
}
-32
View File
@@ -2291,38 +2291,6 @@ test("legacy and invalid packed download settings preserve the local preference"
}
});
test("tree folder double-click preference round-trips in sync payloads and preserves local value on missing or invalid input", async () => {
const key = storageKeys.STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR;
assert.ok((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key));
for (const behavior of ["navigate", "expand"] as const) {
localStorage.clear();
localStorage.setItem(key, behavior);
const payload = buildSyncPayload(vault());
assert.equal(payload.settings?.sftpTreeDoubleClickBehavior, behavior);
localStorage.clear();
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), behavior);
}
localStorage.clear();
const emptyPayload = buildSyncPayload(vault());
assert.equal(emptyPayload.settings?.sftpTreeDoubleClickBehavior, undefined);
localStorage.setItem(key, "expand");
await applySyncPayload(emptyPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
for (const invalid of ["open", "transfer", 1, null]) {
await applySyncPayload({
...emptyPayload,
settings: { sftpTreeDoubleClickBehavior: invalid },
} as unknown as SyncPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
}
});
test("old bottom tab preference is ignored by settings export and import", async () => {
localStorage.clear();
const legacyKey = "netcatty_tab_bar_position_v1";
-11
View File
@@ -109,7 +109,6 @@ import {
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_CUSTOM_THEMES,
STORAGE_KEY_SHOW_RECENT_HOSTS,
@@ -150,7 +149,6 @@ import {
import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge';
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
import { normalizeAiToolOutputMaxChars } from '../domain/aiToolOutputLimit';
import { isSftpTreeFolderDoubleClickBehavior } from '../domain/sftpTreeFolderDoubleClick';
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
// ---------------------------------------------------------------------------
@@ -347,7 +345,6 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_SHOW_RECENT_HOSTS,
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
@@ -579,8 +576,6 @@ export function collectSyncableSettings(): SyncPayload['settings'] {
if (followTerminalCwd === 'true' || followTerminalCwd === 'false') settings.sftpFollowTerminalCwd = followTerminalCwd === 'true';
const defaultViewMode = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE);
if (defaultViewMode === 'list' || defaultViewMode === 'tree') settings.sftpDefaultViewMode = defaultViewMode;
const treeDblClick = localStorageAdapter.readString(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR);
if (isSftpTreeFolderDoubleClickBehavior(treeDblClick)) settings.sftpTreeDoubleClickBehavior = treeDblClick;
// SFTP Bookmarks (global only - local bookmarks are device-specific)
const globalBookmarks = localStorageAdapter.read<SftpBookmark[]>(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS);
@@ -900,12 +895,6 @@ async function applySyncableSettings(
if (settings.sftpDefaultViewMode != null) {
localStorageAdapter.writeString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, settings.sftpDefaultViewMode);
}
if (isSftpTreeFolderDoubleClickBehavior(settings.sftpTreeDoubleClickBehavior)) {
localStorageAdapter.writeString(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
settings.sftpTreeDoubleClickBehavior,
);
}
// SFTP Bookmarks (global only)
if (settings.sftpGlobalBookmarks != null) localStorageAdapter.write(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS, settings.sftpGlobalBookmarks);
+2 -19
View File
@@ -1,5 +1,5 @@
import React, { type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Undo2, X } from 'lucide-react';
import { History, Plus, Undo2 } from 'lucide-react';
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
import type { Host, VaultNote } from '../types';
import type { UserSkillOption } from './ai/userSkillsState';
@@ -87,8 +87,6 @@ interface AIChatPanelContentProps {
providerDisplayName?: string;
modelDisplayName?: string;
modelCatalogWarning?: string;
/** Whether the composer warning banner itself was dismissed (picker still sees raw warning). */
modelCatalogWarningDismissed?: boolean;
/** Live SDK model catalog is loading (no built-in presets to show yet). */
modelCatalogLoading?: boolean;
/** Provenance of the active model list, rendered as the picker status chip. */
@@ -97,8 +95,6 @@ interface AIChatPanelContentProps {
modelCatalogFetchedAt?: string;
/** Retry a failed SDK model catalog load from the warning banner. */
handleModelCatalogRetry?: () => void;
/** Dismiss the warning banner for this agent config until a clean catalog re-arms it. */
handleModelCatalogDismiss?: () => void;
handleModelPickerOpen?: () => void;
agentModelPresets: AgentModelPreset[];
/** Suppress the composer picker's "use custom model" action (locked model). */
@@ -178,7 +174,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
handleSteer,
handleStop,
handleModelCatalogRetry,
handleModelCatalogDismiss,
handleModelPickerOpen,
canSteer,
isSteering,
@@ -188,7 +183,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
providerDisplayName,
modelDisplayName,
modelCatalogWarning,
modelCatalogWarningDismissed = false,
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
@@ -427,7 +421,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<div role="status" className="mx-3 mb-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
{steerWarning}
</div>
) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
) : modelCatalogWarning ? (
<div role="status" className="mx-3 mb-1.5 flex items-center gap-2 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
<span className="min-w-0 flex-1">{modelCatalogWarning}</span>
{handleModelCatalogRetry && (
@@ -438,17 +432,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
{t('ai.chat.modelCatalogRetry')}
</button>
)}
{handleModelCatalogDismiss && (
<button
type="button"
aria-label={t('common.close')}
title={t('common.close')}
onClick={handleModelCatalogDismiss}
className="shrink-0 rounded p-0.5 text-amber-600/70 transition-colors hover:bg-amber-500/10 hover:text-amber-600 cursor-pointer dark:text-amber-400/70 dark:hover:text-amber-300"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</button>
)}
</div>
) : modelCatalogLoading ? (
<div role="status" className="mx-3 mb-1.5 rounded-md bg-muted/40 px-2.5 py-1.5 text-[11px] leading-4 text-muted-foreground/70">
+1 -36
View File
@@ -85,14 +85,12 @@ import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime
import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState';
import { useConversationExport } from './ai/hooks/useConversationExport';
import { useAgentContextUsage } from '../application/state/useAgentCompactionUi';
import { useModelCatalogWarningDismissal } from '../application/state/useModelCatalogWarningDismissal';
import type { AIChatSidePanelProps } from './AIChatSidePanel.types';
import {
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
sdkRuntimeModelCache,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
retainStoredModelPresetForCatalog,
toSdkRuntimeModelCatalog,
generateId,
@@ -363,11 +361,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false);
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, { cacheKey: string; models: AgentModelPreset[]; catalogUnavailable: boolean }>>({});
const [runtimeModelWarnings, setRuntimeModelWarnings] = useState<Record<string, { cacheKey: string; message: string }>>({});
const {
dismissedKeys: dismissedModelCatalogKeys,
dismissWarning: dismissModelCatalogWarning,
rearmWarning: rearmModelCatalogWarning,
} = useModelCatalogWarningDismissal();
// Tracks SDK runtime model catalogs currently loading (per agent scope);
// the composer shows the loading row alongside the build-time presets and
// the live catalog replaces them when it arrives.
@@ -1359,11 +1352,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
t('ai.chat.modelCatalogWarning'),
);
});
// A clean catalog re-arms a banner the user previously dismissed, so a
// later failure for the same config is visible again.
if (catalog && !catalog.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
return catalog;
}).catch((err) => {
setRuntimeModelWarnings((current) => {
@@ -1379,7 +1367,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}
return null;
});
}, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]);
}, [t, buildExternalAgentRuntimeModelTarget]);
useEffect(() => {
if (!isVisible) return;
@@ -1402,9 +1390,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
Boolean(cached.warning),
t('ai.chat.modelCatalogWarning'),
));
if (!cached.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
}
// Respect renderer TTL / in-flight coalescing for all SDK agents including
@@ -1485,7 +1470,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
rearmModelCatalogWarning,
t,
]);
@@ -1641,14 +1625,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
applySdkRuntimeModelCatalog,
]);
// Hide the composer warning banner for this config until a clean catalog
// re-arms it. The underlying warning stays active so the model picker keeps
// its manual refresh action.
const handleDismissModelCatalogWarning = useCallback(() => {
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
dismissModelCatalogWarning(target?.cacheKey);
}, [currentAgentConfig, buildExternalAgentRuntimeModelTarget, dismissModelCatalogWarning]);
const selectedCattyThinking = agentThinkingMap.catty;
const handleCattyThinkingSelect = useCallback((level: string) => {
setAgentThinking('catty', level);
@@ -2540,17 +2516,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
? runtimeModelWarnings[currentAgentId].message
: undefined}
modelCatalogWarningDismissed={!hasCodexCustomConfig
&& Boolean(
runtimeModelWarnings[currentAgentId]
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
&& !isModelCatalogWarningVisible(
runtimeModelWarnings[currentAgentId],
buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey,
dismissedModelCatalogKeys,
),
)}
handleModelCatalogDismiss={handleDismissModelCatalogWarning}
modelCatalogLoading={
!hasCodexCustomConfig
&& Boolean(runtimeModelLoading[currentAgentId])
@@ -17,7 +17,6 @@ import {
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
toSdkRuntimeModelCatalog,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
@@ -686,26 +685,6 @@ test('reconcileRuntimeModelWarning clears only the banner that belongs to this c
assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current);
});
test('isModelCatalogWarningVisible shows a matching, non-dismissed banner', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k1', new Set()), 'cannot load models');
});
test('isModelCatalogWarningVisible hides a dismissed cache key but re-arms on a new key', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
const dismissed = new Set(['k1']);
assert.equal(isModelCatalogWarningVisible(warning, 'k1', dismissed), undefined);
// A config/agent switch produces a different cache key, which is not dismissed.
assert.equal(isModelCatalogWarningVisible({ cacheKey: 'k2', message: 'again' }, 'k2', dismissed), 'again');
});
test('isModelCatalogWarningVisible never shows a warning for another cache key or without a target', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k2', new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(warning, undefined, new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(undefined, 'k1', new Set()), undefined);
});
test('cacheOnly hydration in AIChatSidePanel reconciles cached refresh warnings before applying persisted models', () => {
const source = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(
-19
View File
@@ -293,25 +293,6 @@ export const sdkRuntimeModelCache = createSdkRuntimeModelCache();
export type RuntimeModelWarnings = Record<string, { cacheKey: string; message: string }>;
/**
* Whether a per-agent catalog warning should surface in the composer banner.
*
* A warning the user explicitly dismissed stays hidden for its cache key until
* a clean catalog is observed (the caller then drops the key from
* `dismissedKeys`). A warning belonging to a different cache key is never
* shown — config/agent switches must not inherit a stale dismissal.
*/
export function isModelCatalogWarningVisible(
warning: { cacheKey: string; message: string } | undefined,
cacheKey: string | undefined,
dismissedKeys: ReadonlySet<string>,
): string | undefined {
if (!warning || !cacheKey) return undefined;
if (warning.cacheKey !== cacheKey) return undefined;
if (dismissedKeys.has(cacheKey)) return undefined;
return warning.message;
}
/**
* Make the per-agent catalog warning banner match a catalog result. Used both
* for cache reads and after a refresh settles: a refresh that coalesced onto
+24 -63
View File
@@ -24,13 +24,10 @@ import {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type HostDetailsAdvancedSectionsProps = Record<string, any>;
const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void; inheritance?: React.ReactNode }> = ({ label, hint, enabled, disabled, onToggle, inheritance }) => {
const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void }> = ({ label, hint, enabled, disabled, onToggle }) => {
return (
<HostDetailsSettingRow label={label} hint={hint}>
<div className="flex items-center gap-2">
{inheritance}
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
</div>
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
</HostDetailsSettingRow>
);
};
@@ -52,7 +49,6 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
setShowAlgorithmOverrides,
chainedHosts,
hostChainInherited = false,
canRestoreHostChain = false,
setActiveSubPanel,
clearHostChain,
proxySummaryType,
@@ -63,29 +59,6 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
}) => {
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
const effectiveEtEnabled = form.etEnabled ?? effectiveGroupDefaults?.etEnabled;
const inheritedBackspaceBehavior = effectiveGroupDefaults?.backspaceBehavior;
const groupSettingControl = (key: "moshEnabled" | "etEnabled" | "deviceType" | "backspaceBehavior") => {
if (effectiveGroupDefaults?.[key] === undefined) return null;
return form[key] === undefined ? (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("vault.groups.details.inherited")}
</Badge>
) : (
<HostDetailsOverrideReset size="sm" label={t("common.useGroup")} onClick={() => {
if ((key === "moshEnabled" || key === "etEnabled") && effectiveGroupDefaults[key] === true) {
setForm(prev => ({
...prev,
[key]: undefined,
[key === "moshEnabled" ? "etEnabled" : "moshEnabled"]: false,
}));
} else {
update(key, undefined);
}
}} />
);
};
const inheritedStartupCommandRunMode = effectiveGroupDefaults?.startupCommandRunMode ?? "paste";
const effectiveStartupCommandRunMode = form.startupCommandRunMode ?? inheritedStartupCommandRunMode;
const systemSshAgentSupported = effectiveAuthMethod === "auto" || effectiveAuthMethod === "key";
@@ -224,10 +197,9 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="Mosh"
enabled={!!effectiveMoshEnabled}
inheritance={groupSettingControl("moshEnabled")}
enabled={!!form.moshEnabled}
onToggle={() => {
const enabling = !effectiveMoshEnabled;
const enabling = !form.moshEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -248,10 +220,9 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="EternalTerminal"
enabled={!!effectiveEtEnabled}
inheritance={groupSettingControl("etEnabled")}
enabled={!!form.etEnabled}
onToggle={() => {
const enabling = !effectiveEtEnabled;
const enabling = !form.etEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -264,7 +235,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
}
}}
/>
{effectiveEtEnabled && (
{form.etEnabled && (
<>
<HostDetailsSettingRow label={t("hostDetails.et.port")} hint={t("hostDetails.et.port.desc")}>
<Input
@@ -396,12 +367,11 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
icon={<Router size={14} className="text-muted-foreground" />}
title={t("hostDetails.section.deviceType")}
>
{(!form.protocol || form.protocol === 'ssh') && !effectiveMoshEnabled && !effectiveEtEnabled && (<>
{(!form.protocol || form.protocol === 'ssh') && !form.moshEnabled && !form.etEnabled && (<>
<ToggleRow
label={t("hostDetails.deviceType")}
hint={t("hostDetails.deviceType.desc")}
enabled={effectiveDeviceType === 'network'}
inheritance={groupSettingControl("deviceType")}
onToggle={() => update("deviceType", effectiveDeviceType === 'network' ? 'general' : 'network')}
/>
{effectiveDeviceType === 'network' && (
@@ -515,7 +485,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{(form.protocol === undefined || form.protocol === "ssh") && !effectiveMoshEnabled && !effectiveEtEnabled && (
{(form.protocol === undefined || form.protocol === "ssh") && !form.moshEnabled && !form.etEnabled && (
<>
<ToggleRow
label={t("hostDetails.sshInputCompatibility")}
@@ -529,23 +499,19 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</>
)}
<HostDetailsSettingRow label={t("hostDetails.backspaceBehavior")}>
<div className="flex items-center gap-2">
{form.backspaceBehavior !== undefined && groupSettingControl("backspaceBehavior")}
<Select
value={form.backspaceBehavior ?? inheritedBackspaceBehavior ?? "default"}
onValueChange={(v) => update("backspaceBehavior", v === "default" && inheritedBackspaceBehavior === undefined ? undefined : v)}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">{inheritedBackspaceBehavior !== undefined ? t("serial.backspace.default") : t("hostDetails.backspaceBehavior.default")}</SelectItem>
<SelectItem value="ctrl-h">^H (0x08)</SelectItem>
</SelectContent>
</Select>
</div>
<Select
value={form.backspaceBehavior ?? "default"}
onValueChange={(v) => update("backspaceBehavior", v === "default" ? undefined : v)}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">{t("hostDetails.backspaceBehavior.default")}</SelectItem>
<SelectItem value="ctrl-h">^H (0x08)</SelectItem>
</SelectContent>
</Select>
</HostDetailsSettingRow>
{form.backspaceBehavior === undefined && groupSettingControl("backspaceBehavior")}
</HostDetailsSection>
{/* Per-host keepalive override */}
@@ -668,14 +634,9 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
</div>
) : (
<div className="flex items-center gap-1">
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
</Badge>
{canRestoreHostChain && (
<HostDetailsOverrideReset size="sm" label={t("common.useGroup")} onClick={clearHostChain} />
)}
</div>
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
</Badge>
)
}
>
+1 -1
View File
@@ -225,7 +225,7 @@ export const nextFormAfterClearHostChain = (
groupDefaults
&& applyGroupDefaults({ ...prev, hostChain: undefined }, groupDefaults).hostChain?.hostIds?.length,
);
if (prev.hostChain === undefined || (groupWouldRestore && prev.hostChain.hostIds?.length)) {
if (prev.hostChain === undefined || groupWouldRestore) {
return { ...prev, hostChain: { hostIds: [] } };
}
const { hostChain: _hostChain, ...rest } = prev;
@@ -1,222 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider";
import { applyGroupDefaults } from "../domain/groupConfig";
import type { GroupConfig, Host } from "../domain/models";
import { resolveEffectiveTerminalProtocol } from "../domain/terminalProtocol";
import HostDetailsPanel from "./HostDetailsPanel";
import { ChainPanel } from "./host-details/ChainPanel";
import { HostDetailsOverrideReset } from "./host-details/HostDetailsOverrideReset";
import { HostDetailsSection, HostDetailsSettingRow } from "./host-details/HostDetailsSection";
import { mapTerminalBackspaceInput } from "./terminal/runtime/terminalBackspaceInput";
import { installDomEnvironment } from "./test-support/renderReactDom";
import { AsidePanelFooter } from "./ui/aside-panel";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Select } from "./ui/select";
import { Switch } from "./ui/switch";
import { TooltipProvider } from "./ui/tooltip";
const host: Host = {
id: "host-1", label: "Host", hostname: "example.com", username: "root",
password: "password", authMethod: "password", tags: [], os: "linux",
protocol: "ssh", group: "network",
};
const panelProps = (groupDefaults: Partial<GroupConfig>, initialData = host) => ({
initialData, availableKeys: [], identities: [], proxyProfiles: [],
groups: ["network"], groupConfigs: [{ path: "network", ...groupDefaults }],
allHosts: [{ ...host, id: "jump-1", label: "Jump", hostname: "jump.example.com" }],
terminalThemeId: "default", terminalFontSize: 14, layout: "inline" as const,
onSave: (_value: Host) => {}, onCancel: () => {},
});
async function withPanel(
groupDefaults: Partial<GroupConfig>,
run: (editor: { root: ReactTestInstance; save: () => Promise<Host> }) => Promise<void>,
initialData = host,
) {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let saved: Host | undefined;
try {
await act(async () => {
renderer = create(<I18nProvider locale="en"><TooltipProvider>
<HostDetailsPanel {...panelProps(groupDefaults, initialData)} onSave={(value) => { saved = value; }} />
</TooltipProvider></I18nProvider>);
});
await run({
root: renderer!.root,
save: async () => {
saved = undefined;
await act(async () => {
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
await buttons[buttons.length - 1].props.onClick();
});
assert.ok(saved, "the actual panel save handler must emit a host");
return saved;
},
});
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
}
function setting(root: ReactTestInstance, label: string) {
const row = root.findAllByType(HostDetailsSettingRow).find((node) => node.props.label === label);
assert.ok(row, `expected setting ${label}`);
return row;
}
function assertInherited(row: ReactTestInstance) {
assert.ok(row.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
assert.equal(row.findAllByType(HostDetailsOverrideReset).length, 0);
}
for (const [key, label] of [["moshEnabled", "Mosh"], ["etEnabled", "EternalTerminal"]] as const) {
test(`Host Details shows inherited ${label}, saves Off, and resets to the group`, async () => {
const group = { [key]: true };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, label);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "Network Device Mode"), false);
if (key === "etEnabled") setting(root, "ET server port");
await act(async () => { row().findByType(Switch).props.onCheckedChange(false); });
const off = await save();
assert.equal(off[key], false);
assert.equal(applyGroupDefaults(off, group)[key], false);
assert.equal(row().findByType(Switch).props.checked, false);
assert.equal(row().findAllByType(Badge).length, 0);
if (key === "etEnabled") {
assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "ET server port"), false);
}
const reset = row().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited[key], undefined);
assert.equal(applyGroupDefaults(inherited, group)[key], true);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
});
});
test(`Host Details restores inherited ${label} and disables the competing transport`, async () => {
const competingKey = key === "moshEnabled" ? "etEnabled" : "moshEnabled";
const competingLabel = key === "moshEnabled" ? "EternalTerminal" : "Mosh";
const group = { [key]: true };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, label);
assert.equal(row().findByType(Switch).props.checked, false);
assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, true);
const reset = row().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited[key], undefined);
assert.equal(inherited[competingKey], false);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, false);
const effective = applyGroupDefaults(inherited, group);
assert.equal(effective[key], true);
assert.equal(effective[competingKey], false);
assert.equal(resolveEffectiveTerminalProtocol(effective), key === "moshEnabled" ? "mosh" : "et");
}, { ...host, [key]: false, [competingKey]: true });
});
}
test("Host Details device type override can return to the group", async () => {
const group = { deviceType: "network" as const };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, "Network Device Mode");
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
await act(async () => { row().findByType(Switch).props.onCheckedChange(false); });
assert.equal((await save()).deviceType, "general");
assert.equal(row().findByType(Switch).props.checked, false);
await act(async () => { row().findByType(HostDetailsOverrideReset).props.onClick(); });
const inherited = await save();
assert.equal(inherited.deviceType, undefined);
assert.equal(applyGroupDefaults(inherited, group).deviceType, "network");
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
});
});
test("Host Details backspace shows inherited Ctrl-H and saves explicit DEL or Ctrl-H or inherit", async () => {
const group = { backspaceBehavior: "ctrl-h" as const };
await withPanel(group, async ({ root, save }) => {
const select = () => setting(root, "Backspace Behavior").findByType(Select);
assert.equal(select().props.value, "ctrl-h");
assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
await act(async () => { select().props.onValueChange("default"); });
const del = await save();
assert.equal(del.backspaceBehavior, "default");
const reloaded: Host = JSON.parse(JSON.stringify(del));
assert.equal(mapTerminalBackspaceInput("\x7f", applyGroupDefaults(reloaded, group).backspaceBehavior), "\x7f");
assert.equal(select().props.value, "default");
await act(async () => { select().props.onValueChange("ctrl-h"); });
assert.equal((await save()).backspaceBehavior, "ctrl-h");
await act(async () => { setting(root, "Backspace Behavior").findByType(HostDetailsOverrideReset).props.onClick(); });
const inherited = await save();
assert.equal(inherited.backspaceBehavior, undefined);
assert.equal(applyGroupDefaults(inherited, group).backspaceBehavior, "ctrl-h");
assert.equal(select().props.value, "ctrl-h");
assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
});
});
test("Host Details keeps no-group toggle and Default backspace behavior", async () => {
await withPanel({}, async ({ root, save }) => {
const mosh = setting(root, "Mosh");
assert.equal(mosh.findByType(Switch).props.checked, false);
assert.equal(mosh.findAllByType(HostDetailsOverrideReset).length, 0);
await act(async () => { mosh.findByType(Switch).props.onCheckedChange(true); });
assert.equal((await save()).moshEnabled, true);
await act(async () => { setting(root, "Mosh").findByType(Switch).props.onCheckedChange(false); });
assert.equal((await save()).moshEnabled, false);
assert.equal(setting(root, "Mosh").findAllByType(HostDetailsOverrideReset).length, 0);
const select = () => setting(root, "Backspace Behavior").findByType(Select);
await act(async () => { select().props.onValueChange("ctrl-h"); });
assert.equal((await save()).backspaceBehavior, "ctrl-h");
await act(async () => { select().props.onValueChange("default"); });
assert.equal((await save()).backspaceBehavior, undefined);
});
});
test("Host Details can restore group jump hosts from the empty-override Direct row", async () => {
const group = { hostChain: { hostIds: ["jump-1"] } };
await withPanel(group, async ({ root, save }) => {
const section = () => root.findAllByType(HostDetailsSection).find((node) => node.props.title === "Proxy via Hosts")!;
await act(async () => { section().findAllByType("button").find((node) => node.props.className?.includes("cursor-pointer"))!.props.onClick(); });
await act(async () => { root.findByType(ChainPanel).props.onClearChain(); });
await act(async () => { root.findByType(ChainPanel).props.onBack(); });
const direct = await save();
assert.deepEqual(direct.hostChain, { hostIds: [] });
assert.deepEqual(applyGroupDefaults(direct, group).hostChain, { hostIds: [] });
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Direct"));
const reset = section().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited.hostChain, undefined);
assert.deepEqual(applyGroupDefaults(inherited, group).hostChain, group.hostChain);
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
});
});
@@ -4,10 +4,9 @@ import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { Host, Identity, ProxyProfile } from "../types.ts";
import type { Host, Identity } from "../types.ts";
import HostDetailsPanel, { parseOptionalPortInput } from "./HostDetailsPanel.tsx";
import { applyGroupDefaults } from "../domain/groupConfig.ts";
import { getActiveGlobalDefaultProxyProfileId, publishActiveGlobalDefaultProxyProfileId } from "../domain/globalDefaultProxy.ts";
import {
mapProxySaveErrorKey,
prepareProxyConfigForSave,
@@ -38,7 +37,7 @@ const hostWithMissingProxyProfile: Host = {
const renderHostDetails = (
initialData: Host = hostWithMissingProxyProfile,
options: { identities?: Identity[]; proxyProfiles?: ProxyProfile[] } = {},
options: { identities?: Identity[] } = {},
) =>
renderToStaticMarkup(
React.createElement(
@@ -51,7 +50,7 @@ const renderHostDetails = (
initialData,
availableKeys: [],
identities: options.identities ?? [],
proxyProfiles: options.proxyProfiles ?? [],
proxyProfiles: [],
groups: [],
managedSources: [],
allTags: [],
@@ -102,31 +101,6 @@ test("HostDetailsPanel labels command proxy summaries consistently", () => {
assert.doesNotMatch(markup, /--token secret/);
});
test("HostDetailsPanel displays the inherited global default proxy without a group proxy", () => {
const previous = getActiveGlobalDefaultProxyProfileId();
try {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
const markup = renderHostDetails({ ...hostWithMissingProxyProfile, proxyProfileId: undefined }, {
proxyProfiles: [{
id: "global-proxy",
label: "Global Office Proxy",
config: { type: "http", host: "global-proxy.example.com", port: 8080 },
createdAt: 1,
}],
});
assert.match(markup, /Global Office Proxy/);
assert.match(markup, /Inherited from group/);
assert.doesNotMatch(markup, /Configure proxy/);
const direct = renderHostDetails({ ...hostWithMissingProxyProfile, proxyProfileId: undefined, directProxy: true });
assert.match(direct, /Direct \(no proxy\)/);
assert.doesNotMatch(direct, /Global Office Proxy|Inherited from group/);
} finally {
publishActiveGlobalDefaultProxyProfileId(previous);
}
});
test("HostDetailsPanel keeps explicitly cleared telnet credentials empty", () => {
const markup = renderHostDetails({
...hostWithMissingProxyProfile,
@@ -724,19 +698,6 @@ test("clearing an inherited-only chain keeps an empty override instead of restor
assert.deepEqual(applyGroupDefaults(cleared, group).hostChain, { hostIds: [] });
});
test("clearing an empty host-chain override restores group hops on the second clear", () => {
const group = { hostChain: { hostIds: ["jump-1", "jump-host"] } };
for (const hostChain of [undefined, { hostIds: ["jump-host"] }]) {
const cleared = nextFormAfterClearHostChain({ ...networkSshHost, hostChain }, group);
assert.deepEqual(cleared.hostChain, { hostIds: [] });
const restored = nextFormAfterClearHostChain(cleared, group);
assert.equal(restored.hostChain, undefined);
assert.equal(Object.hasOwn(restored, "hostChain"), false);
assert.deepEqual(applyGroupDefaults(restored, group).hostChain, group.hostChain);
}
});
test("HostDetailsPanel custom proxy draft hides the inherited saved proxy", () => {
const markup = renderToStaticMarkup(
React.createElement(
@@ -788,7 +749,6 @@ test("HostDetailsPanel empty jump-host override hides the inherited group chain"
assert.doesNotMatch(markup, /bastion\.example\.com/);
assert.doesNotMatch(markup, /edge\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
assert.match(markup, /aria-label="Use group"/);
});
test("mapProxySaveErrorKey maps every proxy save validation error to its i18n key", () => {
+2 -6
View File
@@ -378,7 +378,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [defaultGroup, form.group, groupConfigs, groupDefaults]);
const effectiveAuthHost = useMemo(
() => applyGroupDefaults(form, effectiveGroupDefaults ?? {}),
() => effectiveGroupDefaults ? applyGroupDefaults(form, effectiveGroupDefaults) : form,
[effectiveGroupDefaults, form],
);
@@ -449,7 +449,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
);
) && Boolean(effectiveGroupDefaults?.proxyProfileId || effectiveGroupDefaults?.proxyConfig);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || displayProxyConfig) || "HTTP";
@@ -794,9 +794,6 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
[effectiveAuthHost.hostChain?.hostIds, form.hostChain],
);
const hostChainInherited = form.hostChain === undefined && displayHostChainIds.length > 0;
const canRestoreHostChain = form.hostChain !== undefined
&& !form.hostChain.hostIds?.length
&& resolveFormHostChainIds({ ...form, hostChain: undefined }, effectiveGroupDefaults).length > 0;
const availableHostsForChain = useMemo(() => {
const chainedIds = new Set(displayHostChainIds);
@@ -1265,7 +1262,6 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setShowAlgorithmOverrides={setShowAlgorithmOverrides}
chainedHosts={chainedHosts}
hostChainInherited={hostChainInherited}
canRestoreHostChain={canRestoreHostChain}
setActiveSubPanel={setActiveSubPanel}
clearHostChain={clearHostChain}
proxySummaryType={proxySummaryType}
-2
View File
@@ -192,7 +192,6 @@ function buildScriptSessionMeta(
}
const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
isVaultInitialized,
hosts,
portForwardingRules = [],
customGroups,
@@ -2803,7 +2802,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onToggleGlobalComposeSendTarget,
canUseGlobalBroadcast,
isComposeBarOpen,
isVaultInitialized,
keyBindings,
keys,
knownHosts,
+2 -26
View File
@@ -80,7 +80,7 @@ test("host tree tab gutter style animates only when host tree transitions and yi
});
});
test("workspace tabs resolve generated labels from live prompt hosts in all mode", () => {
test("workspace tabs resolve generated labels from live prompt hosts", () => {
const sessions = [
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
topTabSession("s2", "h2", { customName: "", promptHostname: "" }),
@@ -95,7 +95,7 @@ test("workspace tabs resolve generated labels from live prompt hosts in all mode
publishSessionPromptHost("s1", "target-a");
publishSessionPromptHost("s2", "target-b");
assert.equal(
resolveWorkspaceTopTabLabel(workspace, sessions, "all"),
resolveWorkspaceTopTabLabel(workspace, sessions),
"target-a/target-b",
);
@@ -103,30 +103,6 @@ test("workspace tabs resolve generated labels from live prompt hosts in all mode
sessionPresentationStore.clearSession("s2");
});
test("generated workspace tabs keep saved names in disabled and agent-only modes", (t) => {
const sessions = [
topTabSession("mode-s1", "h1", { hostLabel: "Production" }),
topTabSession("mode-s2", "h2", { hostLabel: "Database" }),
];
t.after(() => sessions.forEach((session) => sessionPresentationStore.clearSession(session.id)));
const savedTitle = sessions.map((session) => session.hostLabel).join("/");
const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: "mode-s1" };
publishSessionPromptHost("mode-s1", "vm-prod");
publishSessionPromptHost("mode-s2", "db-prod");
for (const mode of [undefined, "off", "agent"] as const) {
assert.equal(resolveWorkspaceTopTabLabel(workspace, sessions, mode), savedTitle, String(mode));
}
});
test("auto workspace tabs apply presentation with the current mode", (t) => {
const session = topTabSession("auto-mode", "h1", { hostLabel: "Production" });
t.after(() => sessionPresentationStore.clearSession(session.id));
const workspace = { title: "Workspace", autoTitle: true, focusedSessionId: session.id };
publishSessionPromptHost(session.id, "vm-prod");
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "off"), session.hostLabel);
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "all"), "vm-prod");
});
test("workspace tabs keep explicit names ahead of live prompt hosts", () => {
const sessions = [
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
@@ -470,180 +470,3 @@ test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, curs
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid FK jump, hiddenColumns, keyboard shortcuts, and PluginErCanvas double-click + SVG export', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [
{ name: 'id', type: 'int4', primaryKey: true },
{ name: 'customer_id', type: 'int4', foreignKey: { table: 'customers', column: 'id', schema: 'public' } },
{ name: 'secret_col', type: 'text' },
],
hiddenColumns: ['secret_col'],
rows: [[10, 42, 'hidden-val']],
editable: true,
};
const roGridProps = {
columns: [{ name: 'id', type: 'int4' }],
rows: [{ id: 99 }],
editable: false,
};
const erProps = {
tables: [
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'created_at', type: 'timestamp with time zone' }] },
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
],
relations: [{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
};
const tree = {
children: [
{ id: 'surface-btn', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'sbt', type: 3, data: 'Btn' }] },
{ id: 'grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) }, children: [] },
{ id: 'ro-grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(roGridProps) }, children: [] },
{ id: 'er', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) }, children: [] },
],
};
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={tree} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
// Shadow surface prevents default on Cmd+K / Cmd+S
const btn = shadows[0].querySelector('button')!;
const modK = new dom.window.KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true, cancelable: true });
await act(async () => { btn.dispatchEvent(modK); });
assert.equal(modK.defaultPrevented, true, 'Cmd+K inside shadow surface must preventDefault');
// DataGrid: hiddenColumns excludes secret_col while preserving values
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
assert.equal(gridHost.querySelector('[data-col-name="secret_col"]'), null, 'hidden column must not render');
const fkCell = gridHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="customer_id"]') as HTMLElement;
assert.ok(fkCell, 'customer_id FK cell rendered');
const jumpBtn = fkCell.querySelector('[data-fk-jump]') as HTMLButtonElement;
assert.ok(jumpBtn, 'FK jump button rendered');
await act(async () => { jumpBtn.click(); });
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'fkJump'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'customer_id', value: 42, targetTable: 'customers', targetColumn: 'id', targetSchema: 'public' } },
);
// Select FK cell then press Cmd+C -> cellCopy, Delete -> cellEdit NULL, Cmd+Z -> shortcut mod+z
await act(async () => { fkCell.click(); });
const gridRoot = gridHost.querySelector('[data-plugin-data-grid]') as HTMLElement;
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'c', metaKey: true, bubbles: true, cancelable: true }));
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true }));
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'z', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellCopy'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellCopy', detail: { text: '42', rowIndex: 0, colName: 'customer_id', rowIndices: [0] } },
);
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'customer_id', value: null, isNull: true } },
);
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } },
);
// Non-editable grid double-click emits cellDoubleClick
const roHost = document.querySelector('[data-plugin-widget-node="ro-grid"]') as HTMLElement;
const roCell = roHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="id"]') as HTMLElement;
await act(async () => { roCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
assert.deepEqual(
events.find((e) => e.nodeId === 'ro-grid' && e.widgetEvent === 'cellDoubleClick'),
{ nodeId: 'ro-grid', type: 'widget', widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 99 } },
);
// ER Canvas: abbreviated type, tableDoubleClick, Export SVG
const erHost = document.querySelector('[data-plugin-widget-node="er"]') as HTMLElement;
assert.ok(erHost.textContent?.includes('timestamptz'), 'verbose PG timestamp abbreviated to timestamptz');
const ordersCard = erHost.querySelector('[data-er-table="orders"]') as Element;
await act(async () => { ordersCard.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
assert.deepEqual(
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableDoubleClick'),
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableDoubleClick', detail: { table: 'orders', schema: 'public' } },
);
const exportBtn = erHost.querySelector('[data-er-export-svg]') as HTMLButtonElement;
await act(async () => { exportBtn.click(); });
const exportEvt = events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'exportSvg');
assert.ok(exportEvt, 'exportSvg event emitted');
assert.match(String((exportEvt!.detail as { svg: string }).svg), /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
// Host global hotkey handler yields Cmd+K (commandPalette) to active plugin surface while keeping Cmd+J (quickSwitch)
const { handleGlobalHotkeyKeyDownImpl } = await import('../../application/app/AppHandlers');
const { matchesKeyBinding } = await import('../../domain/models');
const { DEFAULT_KEY_BINDINGS } = await import('../../domain/models/keyBindings');
const hostActions: string[] = [];
const onGlobalKey = (event: KeyboardEvent) => handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '⌘ + W',
hotkeyScheme: 'mac',
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
executeHotkeyAction: (action: string) => hostActions.push(action),
}), event);
dom.window.addEventListener('keydown', onGlobalKey as unknown as EventListener, true);
try {
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'k', code: 'KeyK', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(hostActions, [], 'host commandPalette must not hijack Cmd+K inside plugin surface');
assert.ok(
events.some((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut' && (e.detail as { shortcut?: string })?.shortcut === 'mod+k'),
'Cmd+K reaches plugin DataGrid as mod+k shortcut',
);
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'j', code: 'KeyJ', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(hostActions, ['quickSwitch'], 'Cmd+J still opens Netcatty Quick Switcher');
} finally {
dom.window.removeEventListener('keydown', onGlobalKey as unknown as EventListener, true);
}
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+2 -52
View File
@@ -3,7 +3,6 @@ import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
import { PluginViewPopover } from './PluginViewPopover';
import { PluginSplitPane } from './primitives/PluginSplitPane';
import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer';
import { matchWorkbenchShortcut } from './primitives/shortcuts';
import type { PluginSplitPaneWidgetProps } from './primitives/types';
import { createPortal } from 'react-dom';
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
@@ -408,15 +407,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
if (event.type === 'submit') event.preventDefault();
if (event.type === 'contextmenu') event.preventDefault();
if (event.type === 'keydown' && event instanceof view.KeyboardEvent) {
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (sc === 'mod+k' || sc === 'mod+s') {
event.preventDefault();
}
}
const nodeId = target.dataset.netcattyRemoteNode
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
const nodeId = target.dataset.netcattyRemoteNode;
if (!nodeId) return;
if (event.type === 'scroll') {
@@ -472,55 +464,13 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
};
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
// into the plugin so its Command Palette and Save shortcuts work reliably.
const view = shadow.ownerDocument.defaultView;
const onWindowKeyDown = (event: KeyboardEvent) => {
if (depth !== 0 || event.defaultPrevented) return;
const surfaceEl = surfaceRef.current;
if (!surfaceEl || !surfaceEl.closest('[data-plugin-chrome="full-bleed"]')) return;
const rect = surfaceEl.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
const doc = surfaceEl.ownerDocument;
const hasHostModal = [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
const r = dialog.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (hasHostModal) return;
const active = doc.activeElement;
const focusInsideHostChrome = active
&& active !== doc.body
&& active !== doc.documentElement
&& !surfaceEl.contains(active)
&& !active.closest?.('[data-plugin-view-slot]');
if (focusInsideHostChrome) return;
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (sc !== 'mod+k' && sc !== 'mod+s') return;
const rootNodeId = (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode;
if (!rootNodeId) return;
event.preventDefault();
onEventRef.current({
nodeId: rootNodeId,
type: 'keydown',
key: event.key,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
altKey: event.altKey,
shiftKey: event.shiftKey,
});
};
view?.addEventListener('keydown', onWindowKeyDown, false);
return () => {
view?.removeEventListener('keydown', onWindowKeyDown, false);
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true);
};
}, [shadow, depth]);
}, [shadow]);
return (
<SurfaceContext.Provider value={surfaceContextValue}>
@@ -8,7 +8,6 @@ import {
readClipboardTextWithFallbacks,
} from '@/infrastructure/monaco/monacoClipboardPaste';
import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme';
import { matchWorkbenchShortcut } from './shortcuts';
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
import type {
PluginCodeEditorCompletionSchema,
@@ -63,10 +62,8 @@ export default function PluginCodeEditorInner({
const editorId = useId();
const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`;
const wrapperRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<Parameters<OnMount>[0] | null>(null);
const monacoRef = useRef<Monaco | null>(null);
const handledKeyEventsRef = useRef<WeakSet<Event>>(new WeakSet());
const disposablesRef = useRef<Array<{ dispose(): void }>>([]);
const onWidgetEventRef = useRef(onWidgetEvent);
onWidgetEventRef.current = onWidgetEvent;
@@ -319,26 +316,6 @@ export default function PluginCodeEditorInner({
],
run: emitFormat,
}),
editor.onKeyDown((monacoKeyEvent) => {
const nativeEvent = monacoKeyEvent.browserEvent;
if (handledKeyEventsRef.current.has(nativeEvent)) return;
const shortcut = matchWorkbenchShortcut(nativeEvent, { includeUndoRedo: false });
if (!shortcut) return;
if (shortcut === 'escape') {
const target = nativeEvent.target as Element | null;
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
handledKeyEventsRef.current.add(nativeEvent);
onWidgetEventRef.current('shortcut', { shortcut });
return;
}
handledKeyEventsRef.current.add(nativeEvent);
monacoKeyEvent.preventDefault();
monacoKeyEvent.stopPropagation();
nativeEvent.preventDefault();
nativeEvent.stopImmediatePropagation?.();
nativeEvent.stopPropagation();
onWidgetEventRef.current('shortcut', { shortcut });
}),
editor.addAction({
id: 'netcatty.pluginCodeEditor.paste',
label: 'Paste',
@@ -377,38 +354,10 @@ export default function PluginCodeEditorInner({
}, 80);
}, []);
// Native capture listener runs BEFORE Monaco's textarea / chord-prefix handler
// so Cmd/Ctrl+K never enters Monaco's chord state and always reaches the plugin once.
useEffect(() => {
const el = wrapperRef.current;
if (!el) return;
const onNativeKeyDownCapture = (event: KeyboardEvent) => {
if (handledKeyEventsRef.current.has(event)) return;
// Keep Monaco's native Cmd/Ctrl+Z undo/redo intact while forwarding global workbench shortcuts.
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (!shortcut) return;
if (shortcut === 'escape') {
const target = event.target as Element | null;
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
handledKeyEventsRef.current.add(event);
onWidgetEventRef.current('shortcut', { shortcut });
return;
}
handledKeyEventsRef.current.add(event);
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
onWidgetEventRef.current('shortcut', { shortcut });
};
el.addEventListener('keydown', onNativeKeyDownCapture, true);
return () => el.removeEventListener('keydown', onNativeKeyDownCapture, true);
}, []);
const resolvedHeight = typeof height === 'number' ? `${height}px` : height;
return (
<div
ref={wrapperRef}
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background"
style={resolvedHeight !== '100%' ? { height: resolvedHeight } : undefined}
data-plugin-code-editor=""
+39 -181
View File
@@ -1,7 +1,6 @@
import { useVirtualizer } from '@tanstack/react-virtual';
import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, KeyRound, Link2, Loader2 } from 'lucide-react';
import { ArrowDown, ArrowUp, ArrowUpDown, KeyRound, Loader2 } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
PluginDataGridColumn,
PluginDataGridRow,
@@ -46,7 +45,6 @@ function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean {
export function PluginDataGrid({
columns = [],
rows = [],
hiddenColumns,
dirtyCells,
deletedRowIndices,
insertedRows = [],
@@ -72,11 +70,6 @@ export function PluginDataGrid({
const deletedSet = useMemo(() => new Set(deletedRowIndices ?? []), [deletedRowIndices]);
const selectedSet = useMemo(() => new Set(selectedRowIndices ?? []), [selectedRowIndices]);
const hiddenSet = useMemo(() => new Set(hiddenColumns ?? []), [hiddenColumns]);
const visibleCols = useMemo(
() => columns.map((col, origIndex) => ({ col, origIndex })).filter(({ col }) => !hiddenSet.has(col.name)),
[columns, hiddenSet],
);
const totalRows = rows.length + insertedRows.length;
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
@@ -98,16 +91,16 @@ export function PluginDataGrid({
const colVirtualizer = useVirtualizer({
horizontal: true,
count: visibleCols.length,
count: columns.length,
getScrollElement: () => scrollRef.current,
estimateSize: (index) => (visibleCols[index] ? getColWidth(visibleCols[index].col) : DEFAULT_COL_WIDTH),
estimateSize: (index) => (columns[index] ? getColWidth(columns[index]) : DEFAULT_COL_WIDTH),
overscan: 4,
initialRect: { width: 960, height: 420 },
});
useEffect(() => {
colVirtualizer.measure();
}, [colWidths, visibleCols, colVirtualizer]);
}, [colWidths, columns, colVirtualizer]);
useEffect(() => {
if (editingCell) {
@@ -132,11 +125,11 @@ export function PluginDataGrid({
return null;
}, [rows, insertedRows]);
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, origColIndex: number) => {
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, colIndex: number) => {
const dirtyKey = `${rowIndex}:${col.name}`;
const isDirty = Boolean(dirtyCells && Object.prototype.hasOwnProperty.call(dirtyCells, dirtyKey));
const entry = getRowAt(rowIndex);
const rawValue = entry ? readCellValue(entry.row, col, origColIndex) : undefined;
const rawValue = entry ? readCellValue(entry.row, col, colIndex) : undefined;
return {
value: isDirty ? dirtyCells![dirtyKey] : rawValue,
isDirty,
@@ -154,19 +147,19 @@ export function PluginDataGrid({
});
}, [onWidgetEvent]);
const beginEdit = useCallback((rowIndex: number, visibleColIndex: number) => {
const beginEdit = useCallback((rowIndex: number, colIndex: number) => {
if (!editable || deletedSet.has(rowIndex)) return;
const entry = visibleCols[visibleColIndex];
if (!entry) return;
const { value } = getEffectiveValue(rowIndex, entry.col, entry.origIndex);
setActiveCell({ rowIndex, colIndex: visibleColIndex });
const col = columns[colIndex];
if (!col) return;
const { value } = getEffectiveValue(rowIndex, col, colIndex);
setActiveCell({ rowIndex, colIndex });
setEditingCell({
rowIndex,
colIndex: visibleColIndex,
colName: entry.col.name,
colIndex,
colName: col.name,
draft: value === null || value === undefined ? '' : formatCellDisplay(value),
});
}, [editable, deletedSet, visibleCols, getEffectiveValue]);
}, [editable, deletedSet, columns, getEffectiveValue]);
const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => {
const next = new Set(selectedSet);
@@ -232,78 +225,9 @@ export function PluginDataGrid({
onWidgetEvent('cellContextMenu', { rowIndex, colName, x, y });
}, [onWidgetEvent]);
const copySelectionOrActiveCell = useCallback(() => {
const selectedIndices = [...selectedSet].sort((a, b) => a - b);
if (selectedIndices.length > 0 && visibleCols.length > 0) {
const text = selectedIndices
.map((rowIdx) => visibleCols.map(({ col, origIndex }) => {
const { value } = getEffectiveValue(rowIdx, col, origIndex);
return value === null || value === undefined ? 'NULL' : formatCellDisplay(value);
}).join('\t'))
.join('\n');
try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {}
onWidgetEvent('cellCopy', {
text,
rowIndex: activeCell?.rowIndex ?? selectedIndices[0],
colName: activeCell ? visibleCols[activeCell.colIndex]?.col.name ?? null : null,
rowIndices: selectedIndices,
});
return true;
}
if (activeCell) {
const entry = visibleCols[activeCell.colIndex];
if (!entry) return false;
const { value } = getEffectiveValue(activeCell.rowIndex, entry.col, entry.origIndex);
const text = value === null || value === undefined ? 'NULL' : formatCellDisplay(value);
try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {}
onWidgetEvent('cellCopy', {
text,
rowIndex: activeCell.rowIndex,
colName: entry.col.name,
rowIndices: [activeCell.rowIndex],
});
return true;
}
return false;
}, [selectedSet, visibleCols, activeCell, getEffectiveValue, onWidgetEvent]);
const handleGridKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
const mod = event.metaKey || event.ctrlKey;
// While editing an inline cell input, only forward Cmd/Ctrl+K and Cmd/Ctrl+S.
if (editingCell) {
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (shortcut === 'mod+k' || shortcut === 'mod+s') {
event.preventDefault();
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
}
return;
}
// Global workbench shortcuts + grid Undo/Redo
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
if (shortcut) {
if (shortcut !== 'escape') {
event.preventDefault();
}
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
return;
}
// Cmd/Ctrl+C copies active cell or selected rows
if (mod && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'c') {
if (copySelectionOrActiveCell()) {
event.preventDefault();
event.stopPropagation();
}
return;
}
if (!activeCell || visibleCols.length === 0 || totalRows === 0) return;
if (editingCell || !activeCell || columns.length === 0 || totalRows === 0) return;
const { rowIndex, colIndex } = activeCell;
if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) {
event.preventDefault();
setActiveCell({ rowIndex: rowIndex + 1, colIndex });
@@ -312,7 +236,7 @@ export function PluginDataGrid({
event.preventDefault();
setActiveCell({ rowIndex: rowIndex - 1, colIndex });
rowVirtualizer.scrollToIndex(rowIndex - 1);
} else if (event.key === 'ArrowRight' && colIndex + 1 < visibleCols.length) {
} else if (event.key === 'ArrowRight' && colIndex + 1 < columns.length) {
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex + 1 });
colVirtualizer.scrollToIndex(colIndex + 1);
@@ -320,34 +244,11 @@ export function PluginDataGrid({
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex - 1 });
colVirtualizer.scrollToIndex(colIndex - 1);
} else if ((event.key === 'Enter' || event.key === 'F2') && editable) {
} else if (event.key === 'Enter' && editable) {
event.preventDefault();
beginEdit(rowIndex, colIndex);
} else if ((event.key === 'Delete' || event.key === 'Backspace') && editable && !deletedSet.has(rowIndex)) {
const entry = visibleCols[colIndex];
if (entry && entry.col.nullable !== false) {
event.preventDefault();
onWidgetEvent('cellEdit', {
rowIndex,
colName: entry.col.name,
value: null,
isNull: true,
});
}
}
}, [
editingCell,
activeCell,
visibleCols,
totalRows,
rowVirtualizer,
colVirtualizer,
editable,
deletedSet,
beginEdit,
copySelectionOrActiveCell,
onWidgetEvent,
]);
}, [editingCell, activeCell, columns.length, totalRows, rowVirtualizer, colVirtualizer, editable, beginEdit]);
const virtualRows = rowVirtualizer.getVirtualItems();
const virtualCols = colVirtualizer.getVirtualItems();
@@ -371,8 +272,11 @@ export function PluginDataGrid({
</div>
)}
<div ref={scrollRef} className="relative h-full w-full min-h-0 flex-1 overflow-auto">
{visibleCols.length === 0 ? (
<div
ref={scrollRef}
className="relative h-full w-full min-h-0 flex-1 overflow-auto [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-muted-foreground/20 hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/40"
>
{columns.length === 0 ? (
<div className="flex h-full w-full items-center justify-center p-6 text-xs text-muted-foreground">
{emptyMessage}
</div>
@@ -400,9 +304,8 @@ export function PluginDataGrid({
<div className="relative flex-1" style={{ height: HEADER_HEIGHT }}>
{virtualCols.map((vCol) => {
const colEntry = visibleCols[vCol.index];
if (!colEntry) return null;
const { col } = colEntry;
const col = columns[vCol.index];
if (!col) return null;
const isSorted = sort?.column === col.name;
const sortable = col.sortable !== false;
return (
@@ -421,16 +324,11 @@ export function PluginDataGrid({
disabled={!sortable}
onClick={() => handleSortClick(col)}
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
title={col.foreignKey
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
: col.type ? `${col.name} (${col.type})` : col.name}
title={col.type ? `${col.name} (${col.type})` : col.name}
>
{col.primaryKey && (
<KeyRound size={11} className="shrink-0 text-amber-500" aria-label="Primary key" />
)}
{col.foreignKey && (
<Link2 size={11} className="shrink-0 text-blue-500" aria-label="Foreign key" />
)}
<span className="truncate font-medium">{col.name}</span>
{col.type && (
<span className="truncate font-mono text-[10px] font-normal text-muted-foreground">
@@ -501,7 +399,7 @@ export function PluginDataGrid({
<div
className="sticky left-0 z-10 flex shrink-0 items-center justify-between border-r border-border/70 bg-background px-2 font-mono text-[10px] tabular-nums text-muted-foreground"
style={{ width: GUTTER_WIDTH, height: ROW_HEIGHT }}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, visibleCols[0]?.col.name ?? '')}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, columns[0]?.name ?? '')}
>
<input
type="checkbox"
@@ -522,16 +420,14 @@ export function PluginDataGrid({
{/* Virtualized Cells */}
<div className="relative z-0 flex-1 overflow-hidden" style={{ height: ROW_HEIGHT }}>
{virtualCols.map((vCol) => {
const visibleColIndex = vCol.index;
const colEntry = visibleCols[visibleColIndex];
if (!colEntry) return null;
const { col, origIndex } = colEntry;
const { value, isDirty } = getEffectiveValue(rowIndex, col, origIndex);
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === visibleColIndex;
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === visibleColIndex;
const colIndex = vCol.index;
const col = columns[colIndex];
if (!col) return null;
const { value, isDirty } = getEffectiveValue(rowIndex, col, colIndex);
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === colIndex;
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === colIndex;
const isNull = value === null || value === undefined;
const numeric = !isNull && isNumericColumn(col, value);
const fk = col.foreignKey;
return (
<div
@@ -540,31 +436,21 @@ export function PluginDataGrid({
data-row-index={rowIndex}
data-col-name={col.name}
data-dirty={isDirty ? 'true' : undefined}
className={`group/cell absolute top-0 bottom-0 flex items-center gap-1 border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
className={`absolute top-0 bottom-0 flex items-center border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
isDirty ? 'bg-amber-500/15 ring-1 ring-inset ring-amber-500/50' : ''
} ${isActive ? 'ring-2 ring-inset ring-primary z-[5]' : ''} ${
numeric ? 'justify-end' : 'justify-start'
}`}
style={{ left: vCol.start, width: vCol.size }}
onClick={() => {
setActiveCell({ rowIndex, colIndex: visibleColIndex });
setActiveCell({ rowIndex, colIndex });
onWidgetEvent('cellSelect', {
rowIndex,
colName: col.name,
value: value === undefined ? null : value,
});
}}
onDoubleClick={() => {
if (editable && !isDeleted) {
beginEdit(rowIndex, visibleColIndex);
} else {
onWidgetEvent('cellDoubleClick', {
rowIndex,
colName: col.name,
value: value === undefined ? null : value,
});
}
}}
onDoubleClick={() => beginEdit(rowIndex, colIndex)}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)}
>
{isEditing ? (
@@ -579,13 +465,6 @@ export function PluginDataGrid({
value={editingCell.draft}
onChange={(e) => setEditingCell({ ...editingCell, draft: e.target.value })}
onKeyDown={(e) => {
const sc = matchWorkbenchShortcut(e, { includeUndoRedo: false });
if (sc === 'mod+k' || sc === 'mod+s') {
e.preventDefault();
e.stopPropagation();
onWidgetEvent('shortcut', { shortcut: sc });
return;
}
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
@@ -596,13 +475,14 @@ export function PluginDataGrid({
} else if (e.key === 'Tab') {
e.preventDefault();
commitEdit(editingCell, false);
const nextCol = e.shiftKey ? visibleColIndex - 1 : visibleColIndex + 1;
if (nextCol >= 0 && nextCol < visibleCols.length) {
const nextCol = e.shiftKey ? colIndex - 1 : colIndex + 1;
if (nextCol >= 0 && nextCol < columns.length) {
beginEdit(rowIndex, nextCol);
}
}
}}
onBlur={() => {
// Delay slightly so clicking the inline NULL button wins over blur.
const snapshot = editingCell;
setTimeout(() => {
setEditingCell((curr) => {
@@ -654,28 +534,6 @@ export function PluginDataGrid({
{formatCellDisplay(value)}
</span>
)}
{!isEditing && !isNull && fk && (
<button
type="button"
data-fk-jump=""
aria-label={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column}`}
title={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column} = ${formatCellDisplay(value)}`}
onClick={(e) => {
e.stopPropagation();
onWidgetEvent('fkJump', {
rowIndex,
colName: col.name,
value,
targetTable: fk.table,
targetColumn: fk.column,
...(fk.schema ? { targetSchema: fk.schema } : {}),
});
}}
className="ml-auto shrink-0 inline-flex h-4 w-4 items-center justify-center rounded text-blue-500 opacity-0 transition-opacity hover:bg-blue-500/15 group-hover/cell:opacity-100 focus:opacity-100"
>
<ArrowUpRight size={11} />
</button>
)}
</div>
);
})}
+63 -142
View File
@@ -1,22 +1,16 @@
import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
abbreviateSqlType,
buildStandaloneErSvg,
ER_CARD_HEADER_HEIGHT,
ER_CARD_ROW_HEIGHT,
ER_CARD_WIDTH,
erCardHeight,
erTableKey,
} from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
PluginErCanvasWidgetProps,
PluginErTable,
PluginWidgetEventCallback,
} from './types';
const GRID_GAP_X = 80;
const CARD_WIDTH = 236;
const CARD_HEADER_HEIGHT = 34;
const CARD_ROW_HEIGHT = 24;
const CARD_FOOTER_PADDING = 8;
const GRID_GAP_X = 76;
const GRID_GAP_Y = 56;
const MIN_ZOOM = 0.25;
const MAX_ZOOM = 2.5;
@@ -25,45 +19,35 @@ export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
function tableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
return table.schema ? `${table.schema}.${table.name}` : table.name;
}
function cardHeight(table: PluginErTable): number {
return CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * CARD_ROW_HEIGHT + CARD_FOOTER_PADDING;
}
function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: number; y: number }> {
const result: Record<string, { x: number; y: number }> = {};
const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1))));
const colY = Array.from({ length: colsPerRow }, () => 40);
tables.forEach((table, index) => {
const key = erTableKey(table);
const key = tableKey(table);
if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) {
result[key] = { x: table.x, y: table.y };
return;
}
const colIdx = index % colsPerRow;
const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X);
const x = 40 + colIdx * (CARD_WIDTH + GRID_GAP_X);
const y = colY[colIdx];
result[key] = { x, y };
colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y;
colY[colIdx] = y + cardHeight(table) + GRID_GAP_Y;
});
return result;
}
function resolveCanvasPalette(el: HTMLElement | null) {
const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
const readVar = (name: string, fallback: string) => {
if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return fallback;
const val = window.getComputedStyle(el).getPropertyValue(name).trim();
return val ? `hsl(${val})` : fallback;
};
return {
background: readVar('--background', isDark ? '#0f1117' : '#ffffff'),
card: readVar('--card', isDark ? '#161922' : '#ffffff'),
cardForeground: readVar('--card-foreground', isDark ? '#f1f5f9' : '#0f172a'),
muted: readVar('--muted', isDark ? '#1e2230' : '#f1f5f9'),
mutedForeground: readVar('--muted-foreground', isDark ? '#94a3b8' : '#64748b'),
border: readVar('--border', isDark ? '#2a3040' : '#e2e8f0'),
primary: readVar('--primary', isDark ? '#38bdf8' : '#2563eb'),
};
}
export function PluginErCanvas({
tables = [],
relations = [],
@@ -77,7 +61,7 @@ export function PluginErCanvas({
const [panning, setPanning] = useState(false);
const tableSignature = useMemo(
() => tables.map((t) => `${erTableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
() => tables.map((t) => `${tableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
[tables],
);
@@ -86,7 +70,7 @@ export function PluginErCanvas({
const defaults = computeInitialPositions(tables);
const next: Record<string, { x: number; y: number }> = {};
for (const tbl of tables) {
const key = erTableKey(tbl);
const key = tableKey(tbl);
next[key] = prev[key] ?? defaults[key];
}
return next;
@@ -97,7 +81,7 @@ export function PluginErCanvas({
const byKey = new Map<string, PluginErTable>();
const byName = new Map<string, PluginErTable>();
for (const tbl of tables) {
byKey.set(erTableKey(tbl), tbl);
byKey.set(tableKey(tbl), tbl);
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
}
return { byKey, byName };
@@ -120,11 +104,11 @@ export function PluginErCanvas({
let maxX = -Infinity;
let maxY = -Infinity;
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
const pos = positions[tableKey(tbl)] ?? { x: 0, y: 0 };
minX = Math.min(minX, pos.x);
minY = Math.min(minY, pos.y);
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
maxX = Math.max(maxX, pos.x + CARD_WIDTH);
maxY = Math.max(maxY, pos.y + cardHeight(tbl));
}
const contentW = Math.max(1, maxX - minX);
const contentH = Math.max(1, maxY - minY);
@@ -170,7 +154,6 @@ export function PluginErCanvas({
if (event.button !== 0) return;
if ((event.target as Element).closest?.('[data-er-table]')) return;
event.preventDefault();
containerRef.current?.focus();
const startX = event.clientX;
const startY = event.clientY;
const initialX = viewport.x;
@@ -197,8 +180,7 @@ export function PluginErCanvas({
const startCardDrag = useCallback((event: React.PointerEvent<SVGGElement>, table: PluginErTable) => {
if (event.button !== 0) return;
event.stopPropagation();
containerRef.current?.focus();
const key = erTableKey(table);
const key = tableKey(table);
const startX = event.clientX;
const startY = event.clientY;
const origin = positions[key] ?? { x: 0, y: 0 };
@@ -234,14 +216,6 @@ export function PluginErCanvas({
window.addEventListener('pointercancel', onUp);
}, [positions, viewport.zoom, onWidgetEvent]);
const handleCardDoubleClick = useCallback((event: React.MouseEvent<SVGGElement>, table: PluginErTable) => {
event.stopPropagation();
onWidgetEvent('tableDoubleClick', {
table: table.name,
...(table.schema ? { schema: table.schema } : {}),
});
}, [onWidgetEvent]);
const zoomBy = useCallback((factor: number) => {
const el = containerRef.current;
const rect = el?.getBoundingClientRect();
@@ -260,35 +234,15 @@ export function PluginErCanvas({
const resetLayout = useCallback(() => {
setPositions(computeInitialPositions(tables));
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(fitToView);
} else {
fitToView();
}
requestAnimationFrame(fitToView);
}, [tables, fitToView]);
const handleExportSvg = useCallback(() => {
const palette = resolveCanvasPalette(containerRef.current);
const svg = buildStandaloneErSvg(tables, relations, positions, palette);
onWidgetEvent('exportSvg', { svg });
}, [tables, relations, positions, onWidgetEvent]);
const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
if (!shortcut) return;
if (shortcut !== 'escape') event.preventDefault();
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
}, [onWidgetEvent]);
return (
<div
ref={containerRef}
data-plugin-er-canvas=""
tabIndex={0}
onWheel={handleWheel}
onKeyDown={handleKeyDown}
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none outline-none"
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none"
>
{/* Floating Canvas Controls */}
<div className="absolute right-3 top-3 z-20 flex items-center gap-1 rounded-lg border border-border bg-background/95 p-1 shadow-sm backdrop-blur-sm">
@@ -297,7 +251,7 @@ export function PluginErCanvas({
onClick={() => zoomBy(1.2)}
aria-label="Zoom in"
title="Zoom in"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
>
<ZoomIn size={13} />
</button>
@@ -309,7 +263,7 @@ export function PluginErCanvas({
onClick={() => zoomBy(1 / 1.2)}
aria-label="Zoom out"
title="Zoom out"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
>
<ZoomOut size={13} />
</button>
@@ -319,7 +273,7 @@ export function PluginErCanvas({
onClick={fitToView}
aria-label="Fit to view"
title="Fit to view"
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
<Maximize2 size={12} />
Fit
@@ -329,22 +283,10 @@ export function PluginErCanvas({
onClick={resetLayout}
aria-label="Reset layout"
title="Reset layout"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
>
<RotateCcw size={12} />
</button>
<div className="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
data-er-export-svg=""
onClick={handleExportSvg}
aria-label="Export SVG"
title="Export SVG"
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
>
<Download size={12} />
Export SVG
</button>
</div>
{tables.length === 0 ? (
@@ -372,34 +314,28 @@ export function PluginErCanvas({
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) return null;
const fromKey = erTableKey(fromTable);
const toKey = erTableKey(toTable);
const fromKey = tableKey(fromTable);
const toKey = tableKey(toTable);
const fromPos = positions[fromKey] ?? { x: 0, y: 0 };
const toPos = positions[toKey] ?? { x: 0, y: 0 };
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const fromCenter = fromPos.x + ER_CARD_WIDTH / 2;
const toCenter = toPos.x + ER_CARD_WIDTH / 2;
const y1 = fromPos.y + CARD_HEADER_HEIGHT + fromColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
const y2 = toPos.y + CARD_HEADER_HEIGHT + toColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
const fromCenter = fromPos.x + CARD_WIDTH / 2;
const toCenter = toPos.x + CARD_WIDTH / 2;
const goRight = toCenter >= fromCenter;
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
const x1 = goRight ? fromPos.x + CARD_WIDTH : fromPos.x;
const x2 = goRight ? toPos.x : toPos.x + CARD_WIDTH;
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
const c1x = goRight ? x1 + dx : x1 - dx;
const c2x = goRight ? x2 - dx : x2 + dx;
const isHovered = hoveredRelation === idx;
const highlighted = isHovered || selectedTable === fromKey || selectedTable === toKey;
const highlighted = hoveredRelation === idx || selectedTable === fromKey || selectedTable === toKey;
const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))';
const midX = (x1 + x2) / 2;
const midY = (y1 + y2) / 2;
const edgeLabel = `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`;
const labelWidth = Math.min(260, Math.max(72, edgeLabel.length * 6.2 + 14));
return (
<g
key={rel.name ?? `${fromKey}.${rel.fromColumn}->${toKey}.${rel.toColumn}:${idx}`}
data-er-relation={`${rel.fromTable}.${rel.fromColumn}->${rel.toTable}.${rel.toColumn}`}
onPointerEnter={() => setHoveredRelation(idx)}
onPointerLeave={() => setHoveredRelation(null)}
>
@@ -407,7 +343,7 @@ export function PluginErCanvas({
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
fill="none"
stroke="transparent"
strokeWidth={14}
strokeWidth={12}
/>
<path
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
@@ -418,27 +354,17 @@ export function PluginErCanvas({
/>
<circle cx={x1} cy={y1} r={3.5} fill={stroke} />
<circle cx={x2} cy={y2} r={3.5} fill="hsl(var(--background))" stroke={stroke} strokeWidth={1.8} />
{isHovered && (
<g transform={`translate(${midX - labelWidth / 2}, ${midY - 12})`}>
<rect
width={labelWidth}
height={18}
rx={4}
fill="hsl(var(--popover))"
stroke="hsl(var(--primary))"
strokeWidth={1}
/>
<text
x={labelWidth / 2}
y={12}
textAnchor="middle"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--popover-foreground))"
>
{edgeLabel}
</text>
</g>
{rel.name && highlighted && (
<text
x={(x1 + x2) / 2}
y={(y1 + y2) / 2 - 6}
textAnchor="middle"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--primary))"
>
{rel.name}
</text>
)}
</g>
);
@@ -446,9 +372,9 @@ export function PluginErCanvas({
{/* Table Cards */}
{tables.map((table) => {
const key = erTableKey(table);
const key = tableKey(table);
const pos = positions[key] ?? { x: 0, y: 0 };
const height = erCardHeight(table);
const height = cardHeight(table);
const isSelected = selectedTable === key;
return (
@@ -457,12 +383,11 @@ export function PluginErCanvas({
data-er-table={table.name}
transform={`translate(${pos.x}, ${pos.y})`}
onPointerDown={(e) => startCardDrag(e, table)}
onDoubleClick={(e) => handleCardDoubleClick(e, table)}
className="cursor-pointer"
filter="url(#nc-er-shadow)"
>
<rect
width={ER_CARD_WIDTH}
width={CARD_WIDTH}
height={height}
rx={8}
fill="hsl(var(--card))"
@@ -471,14 +396,14 @@ export function PluginErCanvas({
/>
{/* Header band */}
<path
d={`M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z`}
d={`M 0 8 Q 0 0 8 0 L ${CARD_WIDTH - 8} 0 Q ${CARD_WIDTH} 0 ${CARD_WIDTH} 8 L ${CARD_WIDTH} ${CARD_HEADER_HEIGHT} L 0 ${CARD_HEADER_HEIGHT} Z`}
fill="hsl(var(--muted))"
/>
<line
x1={0}
y1={ER_CARD_HEADER_HEIGHT}
x2={ER_CARD_WIDTH}
y2={ER_CARD_HEADER_HEIGHT}
y1={CARD_HEADER_HEIGHT}
x2={CARD_WIDTH}
y2={CARD_HEADER_HEIGHT}
stroke="hsl(var(--border))"
strokeWidth={1}
/>
@@ -495,19 +420,15 @@ export function PluginErCanvas({
{/* Columns */}
{table.columns.map((col, colIdx) => {
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
const rowY = CARD_HEADER_HEIGHT + colIdx * CARD_ROW_HEIGHT;
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
const maxNameChars = badgeOffset >= 52 ? 12 : badgeOffset >= 26 ? 15 : 19;
const displayName = col.name.length > maxNameChars ? `${col.name.slice(0, maxNameChars - 1)}…` : col.name;
const displayType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
return (
<g key={col.name} transform={`translate(0, ${rowY})`}>
<title>{`${col.name}: ${col.type}${col.nullable ? ' NULL' : ' NOT NULL'}`}</title>
{colIdx > 0 && (
<line
x1={8}
y1={0}
x2={ER_CARD_WIDTH - 8}
x2={CARD_WIDTH - 8}
y2={0}
stroke="hsl(var(--border))"
strokeOpacity={0.45}
@@ -537,17 +458,17 @@ export function PluginErCanvas({
fontFamily="var(--font-mono)"
fill="hsl(var(--card-foreground))"
>
{displayName}
{col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name}
</text>
<text
x={ER_CARD_WIDTH - 10}
x={CARD_WIDTH - 10}
y={16}
textAnchor="end"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--muted-foreground))"
>
{displayType}
{`${col.type}${col.nullable ? '?' : ''}`.slice(0, 14)}
</text>
</g>
);
@@ -1,55 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => {
assert.equal(abbreviateSqlType('character varying(180)'), 'varchar(180)');
assert.equal(abbreviateSqlType('timestamp with time zone'), 'timestamptz');
assert.equal(abbreviateSqlType('timestamp without time zone'), 'timestamp');
assert.equal(abbreviateSqlType('double precision'), 'float8');
assert.equal(abbreviateSqlType('integer'), 'int4');
assert.equal(abbreviateSqlType('boolean'), 'bool');
assert.equal(abbreviateSqlType('numeric(10,2)'), 'numeric(10,2)');
});
test('buildStandaloneErSvg generates valid self-contained SVG markup with tables, PK/FK pills, and Bezier relations', () => {
const svg = buildStandaloneErSvg(
[
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'email', type: 'character varying(180)', nullable: false }] },
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
],
[{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
{ 'public.customers': { x: 40, y: 40 }, 'public.orders': { x: 380, y: 40 } },
{
background: '#0f1117',
card: '#161922',
cardForeground: '#f1f5f9',
muted: '#1e2230',
mutedForeground: '#94a3b8',
border: '#2a3040',
primary: '#38bdf8',
},
);
assert.match(svg, /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
assert.match(svg, /<\/svg>$/);
assert.match(svg, /public\.customers/);
assert.match(svg, /varchar\(180\)/);
assert.match(svg, />PK</);
assert.match(svg, />FK</);
assert.match(svg, /<path d="M /);
});
test('matchWorkbenchShortcut normalizes mod+k/s/t/w/z/shift+z and escape while respecting includeUndoRedo', () => {
assert.equal(matchWorkbenchShortcut({ key: 'k', metaKey: true }), 'mod+k');
assert.equal(matchWorkbenchShortcut({ key: 'K', ctrlKey: true }), 'mod+k');
assert.equal(matchWorkbenchShortcut({ key: 's', metaKey: true }), 'mod+s');
assert.equal(matchWorkbenchShortcut({ key: 't', ctrlKey: true }), 'mod+t');
assert.equal(matchWorkbenchShortcut({ key: 'w', metaKey: true }), 'mod+w');
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }), 'mod+z');
assert.equal(matchWorkbenchShortcut({ key: 'Z', metaKey: true, shiftKey: true }), 'mod+shift+z');
assert.equal(matchWorkbenchShortcut({ key: 'y', ctrlKey: true }), 'mod+shift+z');
assert.equal(matchWorkbenchShortcut({ key: 'Escape' }), 'escape');
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }, { includeUndoRedo: false }), null);
assert.equal(matchWorkbenchShortcut({ key: 'c', metaKey: true }), null);
});
-155
View File
@@ -1,155 +0,0 @@
import type { PluginErRelation, PluginErTable } from './types';
export const ER_CARD_WIDTH = 252;
export const ER_CARD_HEADER_HEIGHT = 34;
export const ER_CARD_ROW_HEIGHT = 24;
export const ER_CARD_FOOTER_PADDING = 8;
/** Abbreviate verbose SQL types (especially PostgreSQL catalog names) so ER cards never clip mid-word. */
export function abbreviateSqlType(rawType: string): string {
const trimmed = rawType.trim();
if (!trimmed) return '';
let out = trimmed
.replace(/\bcharacter\s+varying\b/gi, 'varchar')
.replace(/\bcharacter\b(?=\s*\()/gi, 'char')
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timestamptz')
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'timestamp')
.replace(/\btime\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timetz')
.replace(/\btime\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'time')
.replace(/\bdouble\s+precision\b/gi, 'float8')
.replace(/\bboolean\b/gi, 'bool')
.replace(/\binteger\b/gi, 'int4')
.replace(/\bsmallint\b/gi, 'int2')
.replace(/\bbigint\b/gi, 'int8')
.replace(/\s+/g, ' ');
if (out.length > 18) {
out = `${out.slice(0, 17)}…`;
}
return out;
}
export function erTableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
return table.schema ? `${table.schema}.${table.name}` : table.name;
}
export function erCardHeight(table: PluginErTable): number {
return ER_CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * ER_CARD_ROW_HEIGHT + ER_CARD_FOOTER_PADDING;
}
function escapeXml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
export interface ErSvgPalette {
background: string;
card: string;
cardForeground: string;
muted: string;
mutedForeground: string;
border: string;
primary: string;
}
export function buildStandaloneErSvg(
tables: PluginErTable[],
relations: PluginErRelation[],
positions: Record<string, { x: number; y: number }>,
palette: ErSvgPalette,
): string {
const byKey = new Map<string, PluginErTable>();
const byName = new Map<string, PluginErTable>();
for (const tbl of tables) {
byKey.set(erTableKey(tbl), tbl);
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
}
const resolveTable = (ref: string) => byKey.get(ref) ?? byName.get(ref);
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 40, y: 40 };
minX = Math.min(minX, pos.x);
minY = Math.min(minY, pos.y);
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
}
if (!Number.isFinite(minX)) {
minX = 0; minY = 0; maxX = 400; maxY = 240;
}
const pad = 40;
const vbX = Math.floor(minX - pad);
const vbY = Math.floor(minY - pad);
const vbW = Math.max(200, Math.ceil(maxX - minX + pad * 2));
const vbH = Math.max(160, Math.ceil(maxY - minY + pad * 2));
const lines: string[] = [
`<svg xmlns="http://www.w3.org/2000/svg" width="${vbW}" height="${vbH}" viewBox="${vbX} ${vbY} ${vbW} ${vbH}">`,
`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="${escapeXml(palette.background)}" />`,
];
for (const rel of relations) {
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) continue;
const fromPos = positions[erTableKey(fromTable)] ?? { x: 0, y: 0 };
const toPos = positions[erTableKey(toTable)] ?? { x: 0, y: 0 };
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const goRight = (toPos.x + ER_CARD_WIDTH / 2) >= (fromPos.x + ER_CARD_WIDTH / 2);
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
const c1x = goRight ? x1 + dx : x1 - dx;
const c2x = goRight ? x2 - dx : x2 + dx;
lines.push(
`<path d="M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}" fill="none" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.5" stroke-opacity="0.75" />`,
`<circle cx="${x1}" cy="${y1}" r="3.5" fill="${escapeXml(palette.mutedForeground)}" />`,
`<circle cx="${x2}" cy="${y2}" r="3.5" fill="${escapeXml(palette.background)}" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.8" />`,
);
}
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
const h = erCardHeight(tbl);
const title = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
lines.push(`<g transform="translate(${pos.x}, ${pos.y})">`);
lines.push(`<rect width="${ER_CARD_WIDTH}" height="${h}" rx="8" fill="${escapeXml(palette.card)}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
lines.push(`<path d="M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z" fill="${escapeXml(palette.muted)}" />`);
lines.push(`<line x1="0" y1="${ER_CARD_HEADER_HEIGHT}" x2="${ER_CARD_WIDTH}" y2="${ER_CARD_HEADER_HEIGHT}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
lines.push(`<text x="12" y="21" font-size="12" font-weight="600" font-family="system-ui, -apple-system, sans-serif" fill="${escapeXml(palette.cardForeground)}">${escapeXml(title)}</text>`);
tbl.columns.forEach((col, colIdx) => {
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
const shortType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
const colLabel = col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name;
lines.push(`<g transform="translate(0, ${rowY})">`);
if (colIdx > 0) {
lines.push(`<line x1="8" y1="0" x2="${ER_CARD_WIDTH - 8}" y2="0" stroke="${escapeXml(palette.border)}" stroke-opacity="0.45" stroke-width="0.75" />`);
}
if (col.isPk) {
lines.push(`<rect x="8" y="5" width="22" height="14" rx="3" fill="#f59e0b" fill-opacity="0.2" /><text x="19" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#d97706">PK</text>`);
}
if (col.isFk) {
const fkX = col.isPk ? 34 : 8;
lines.push(`<rect x="${fkX}" y="5" width="22" height="14" rx="3" fill="#3b82f6" fill-opacity="0.2" /><text x="${fkX + 11}" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#2563eb">FK</text>`);
}
lines.push(`<text x="${10 + badgeOffset}" y="16" font-size="11" font-family="ui-monospace, monospace" fill="${escapeXml(palette.cardForeground)}">${escapeXml(colLabel)}</text>`);
lines.push(`<text x="${ER_CARD_WIDTH - 10}" y="16" text-anchor="end" font-size="10" font-family="ui-monospace, monospace" fill="${escapeXml(palette.mutedForeground)}">${escapeXml(shortType)}</text>`);
lines.push('</g>');
});
lines.push('</g>');
}
lines.push('</svg>');
return lines.join('\n');
}
@@ -1,36 +0,0 @@
import type { PluginWorkbenchShortcut } from './types';
export interface KeyboardShortcutLike {
key: string;
metaKey?: boolean;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
}
/**
* Normalize global workbench shortcuts pressed inside plugin views/widgets.
* Returns null for unrecognized key combinations.
*/
export function matchWorkbenchShortcut(
event: KeyboardShortcutLike,
options?: { includeUndoRedo?: boolean },
): PluginWorkbenchShortcut | null {
const includeUndoRedo = options?.includeUndoRedo ?? true;
if (event.key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) {
return 'escape';
}
const mod = Boolean(event.metaKey || event.ctrlKey);
if (!mod || event.altKey) return null;
const key = event.key.toLowerCase();
if (key === 'k' && !event.shiftKey) return 'mod+k';
if (key === 's' && !event.shiftKey) return 'mod+s';
if (key === 't' && !event.shiftKey) return 'mod+t';
if (key === 'w' && !event.shiftKey) return 'mod+w';
if (includeUndoRedo) {
if (key === 'z' && event.shiftKey) return 'mod+shift+z';
if (key === 'z' && !event.shiftKey) return 'mod+z';
if (key === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z';
}
return null;
}
-19
View File
@@ -3,15 +3,6 @@ export type PluginWidgetEventCallback = (
detail?: Record<string, unknown>,
) => void;
export type PluginWorkbenchShortcut =
| 'mod+k'
| 'mod+s'
| 'mod+t'
| 'mod+w'
| 'mod+z'
| 'mod+shift+z'
| 'escape';
export interface PluginCodeEditorCompletionColumn {
name: string;
type?: string;
@@ -57,12 +48,6 @@ export interface PluginCodeEditorWidgetProps {
height?: number | string;
}
export interface PluginDataGridForeignKey {
table: string;
column: string;
schema?: string;
}
export interface PluginDataGridColumn {
name: string;
type?: string;
@@ -70,7 +55,6 @@ export interface PluginDataGridColumn {
nullable?: boolean;
width?: number;
sortable?: boolean;
foreignKey?: PluginDataGridForeignKey;
}
export interface PluginDataGridSort {
@@ -83,7 +67,6 @@ export type PluginDataGridRow = Record<string, unknown> | unknown[];
export interface PluginDataGridWidgetProps {
columns?: PluginDataGridColumn[];
rows?: PluginDataGridRow[];
hiddenColumns?: string[];
rowKeyField?: string;
dirtyCells?: Record<string, unknown>;
deletedRowIndices?: number[];
@@ -126,8 +109,6 @@ export interface PluginErRelation {
toTable: string;
toColumn: string;
name?: string;
onDelete?: string;
onUpdate?: string;
}
export interface PluginErCanvasWidgetProps {
@@ -9,18 +9,12 @@ import { useSettingsState } from "../../../application/state/useSettingsState";
import { useStoredString } from "../../../application/state/useStoredString";
import {
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD,
} from "../../../infrastructure/config/storageKeys";
import {
buildSftpDownloadDialogDirectoryOptions,
normalizeSftpDefaultDownloadDirectory,
} from "../../../domain/sftpDownloadLocation";
import {
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
type SftpTreeFolderDoubleClickBehavior,
} from "../../../domain/sftpTreeFolderDoubleClick";
import type { FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { Button } from "../../ui/button";
@@ -53,11 +47,6 @@ export default function SettingsFileAssociationsTab() {
const { t } = useI18n();
const [packedDownload, setPackedDownload] = useStoredString<string>(STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD, "true");
const [storedDownloadDir, setStoredDownloadDir] = useStoredString<string>(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR, "");
const [sftpTreeFolderDoubleClick, setSftpTreeFolderDoubleClick] = useStoredString<SftpTreeFolderDoubleClickBehavior>(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
);
const defaultDownloadDir = normalizeSftpDefaultDownloadDirectory(storedDownloadDir);
const [isSelectingDownloadDir, setIsSelectingDownloadDir] = useState(false);
const { getAllAssociations, removeAssociation, setOpenerForExtension, getDefaultOpener, setDefaultOpener, removeDefaultOpener } = useSftpFileAssociations();
@@ -198,24 +187,6 @@ export default function SettingsFileAssociationsTab() {
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.treeFolderDoubleClick')} />
<SettingCard>
<SettingRow
anchorId="sftp-tree-folder-double-click"
description={t('settings.sftp.treeFolderDoubleClick.desc')}
>
<Select
value={sftpTreeFolderDoubleClick}
options={[
{ value: 'navigate', label: t('settings.sftp.treeFolderDoubleClick.navigate') },
{ value: 'expand', label: t('settings.sftp.treeFolderDoubleClick.expand') },
]}
onChange={(value) => setSftpTreeFolderDoubleClick(value as SftpTreeFolderDoubleClickBehavior)}
className="w-56"
/>
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.showHiddenFiles')} />
<SettingCard>
<SettingRow
+1 -184
View File
@@ -10,7 +10,6 @@ import type { SftpFileEntry } from "../../types";
import { createEmptyPane } from "../../application/state/sftp/types";
import { sftpTreeSelectionStore } from "../../application/state/sftp/sftpTreeSelectionStore";
import { installDomEnvironment, createDomRenderer } from "../test-support/renderReactDom";
import { STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR } from "../../infrastructure/config/storageKeys";
const entry = (name: string, type: SftpFileEntry["type"]): SftpFileEntry => ({
name,
@@ -21,21 +20,10 @@ const entry = (name: string, type: SftpFileEntry["type"]): SftpFileEntry => ({
lastModifiedFormatted: "--",
});
test("tree activation resolves directory double-click action per preference while keeping parent and file actions separate", () => {
const dirLink: SftpFileEntry = { ...entry("linked-docs", "symlink"), linkTarget: "directory" };
const fileLink: SftpFileEntry = { ...entry("linked-file", "symlink"), linkTarget: "file" };
test("tree activation enters directories and keeps file opening separate", () => {
assert.equal(getSftpTreeEntryOpenAction(entry("..", "directory")), "up");
assert.equal(getSftpTreeEntryOpenAction(entry("docs", "directory")), "navigate");
assert.equal(getSftpTreeEntryOpenAction(dirLink), "navigate");
assert.equal(getSftpTreeEntryOpenAction(entry("notes.txt", "file")), "open");
assert.equal(getSftpTreeEntryOpenAction(fileLink), "open");
assert.equal(getSftpTreeEntryOpenAction(entry("..", "directory"), "expand"), "up");
assert.equal(getSftpTreeEntryOpenAction(entry("docs", "directory"), "expand"), "expand");
assert.equal(getSftpTreeEntryOpenAction(dirLink, "expand"), "expand");
assert.equal(getSftpTreeEntryOpenAction(entry("notes.txt", "file"), "expand"), "open");
assert.equal(getSftpTreeEntryOpenAction(fileLink, "expand"), "open");
});
test("tree double clicks open entries while the chevron only toggles expansion", async () => {
@@ -209,174 +197,3 @@ test("tree view routes double clicks to navigation and preserves selection, expa
dom.cleanup();
}
});
test("tree view expands and collapses folders in place on double-click when configured and reacts to live setting updates", async () => {
const dom = installDomEnvironment();
const previousObserver = Object.getOwnPropertyDescriptor(globalThis, "ResizeObserver");
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const eventTargetKeys = ["addEventListener", "removeEventListener", "dispatchEvent"] as const;
const previousEventTarget = eventTargetKeys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);
for (const key of eventTargetKeys) {
Object.defineProperty(globalThis, key, {
configurable: true,
value: dom.window[key].bind(dom.window),
});
}
const backing = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
get length() { return backing.size; },
clear() { backing.clear(); },
getItem(key: string) { return backing.get(key) ?? null; },
key(index: number) { return Array.from(backing.keys())[index] ?? null; },
removeItem(key: string) { backing.delete(key); },
setItem(key: string, value: string) { backing.set(key, value); },
} satisfies Storage,
});
Object.defineProperty(globalThis, "ResizeObserver", {
configurable: true,
value: class { observe() {} disconnect() {} },
});
dom.window.requestAnimationFrame = callback => dom.window.setTimeout(() => callback(0), 0);
dom.window.cancelAnimationFrame = id => dom.window.clearTimeout(id);
const renderer = await createDomRenderer(dom.document);
const noop = () => {};
const calls: string[] = [];
const paneId = "tree-activation-expand";
const directoryLink: SftpFileEntry = { ...entry("linked-docs", "symlink"), linkTarget: "directory" };
const fileLink: SftpFileEntry = { ...entry("linked-file", "symlink"), linkTarget: "file" };
const files = [entry("docs", "directory"), entry("src", "directory"), entry("notes.txt", "file"), directoryLink, fileLink];
const childrenByPath: Record<string, SftpFileEntry[]> = {
"/root/docs": [entry("nested", "directory")],
"/root/docs/nested": [entry("leaf.txt", "file")],
"/root/src": [entry("index.ts", "file")],
"/root/linked-docs": [entry("guide.md", "file")],
};
const props: React.ComponentProps<typeof SftpPaneTreeView> = {
pane: {
...createEmptyPane(paneId),
files,
connection: { id: "conn", hostId: "host", hostLabel: "Host", isLocal: false, status: "connected", currentPath: "/root" },
},
side: "left",
onPrepareSelection: noop,
onLoadChildren: async path => {
calls.push(`load:${path}`);
return childrenByPath[path] ?? [];
},
onMoveEntriesToPath: async () => {},
onNavigateUp: () => calls.push("up"),
onNavigateTo: path => calls.push(`navigate:${path}`),
onOpenEntry: (_item, path) => { calls.push(`open:${path}`); },
onRefresh: noop,
onDragStart: noop,
onDragEnd: noop,
openRenameDialog: noop,
openDeleteConfirm: noop,
onCopyToOtherPane: noop,
onReceiveFromOtherPane: noop,
draggedFiles: null,
openNewFolderDialog: noop,
openNewFileDialog: noop,
sorting: {
sortField: "name",
sortOrder: "asc",
directoriesFirst: true,
columnWidths: { name: 50, modified: 24, size: 7, type: 9, owner: 10 },
visibleColumns: { name: true, modified: false, size: false, type: false, owner: false },
handleSort: noop,
handleResizeStart: noop,
toggleColumnVisibility: noop,
toggleDirectoriesFirst: noop,
},
reloadRequest: { token: 0 },
};
const row = (name: string) => {
const element = renderer.container.querySelector(`[data-entry-name="${name}"]`);
assert.ok(element, `missing row ${name}`);
return element;
};
const click = async (target: Element, type = "click", detail = 1) => {
await act(async () => { target.dispatchEvent(new dom.window.MouseEvent(type, { bubbles: true, detail })); });
};
const doubleClick = async (target: Element) => {
await click(target);
await click(target, "click", 2);
await click(target, "dblclick", 2);
};
try {
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "expand");
await renderer.render(React.createElement(SftpPaneTreeView, props));
// Double-clicking folders expands them in place while keeping other expanded branches.
await doubleClick(row("docs").querySelector("span.truncate")!);
assert.deepEqual(calls.splice(0), ["load:/root/docs"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
row("nested");
await doubleClick(row("src").querySelector("span.truncate")!);
assert.deepEqual(calls.splice(0), ["load:/root/src"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
assert.equal(row("src").getAttribute("data-expanded"), "true");
row("index.ts");
await doubleClick(row("nested"));
assert.deepEqual(calls.splice(0), ["load:/root/docs/nested"]);
assert.equal(row("nested").getAttribute("data-expanded"), "true");
row("leaf.txt");
// Double-clicking an expanded folder collapses it in place without navigating.
await doubleClick(row("nested"));
assert.deepEqual(calls, []);
assert.equal(row("nested").getAttribute("data-expanded"), "false");
assert.equal(renderer.container.querySelector('[data-entry-name="leaf.txt"]'), null);
assert.equal(row("src").getAttribute("data-expanded"), "true");
// Directory symlinks also expand/collapse in place; files, file symlinks and ".." keep their actions.
await doubleClick(row("linked-docs"));
assert.deepEqual(calls.splice(0), ["load:/root/linked-docs"]);
assert.equal(row("linked-docs").getAttribute("data-expanded"), "true");
row("guide.md");
for (const [name, action] of [["notes.txt", "open:/root/notes.txt"], ["linked-file", "open:/root/linked-file"], ["..", "up"]]) {
await doubleClick(row(name));
assert.deepEqual(calls.splice(0), [action]);
}
// Switching the setting back to "navigate" takes effect immediately on the mounted tree.
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "navigate");
await act(async () => {
dom.window.dispatchEvent(new dom.window.CustomEvent("netcatty:local-storage-adapter-changed", {
detail: { key: STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR },
}));
});
await doubleClick(row("docs"));
assert.deepEqual(calls.splice(0), ["navigate:/root/docs"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
// Cross-window storage events also update the mounted tree live.
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "expand");
await act(async () => {
dom.window.dispatchEvent(new dom.window.StorageEvent("storage", {
key: STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
newValue: "expand",
}));
});
await doubleClick(row("docs"));
assert.deepEqual(calls, []);
assert.equal(row("docs").getAttribute("data-expanded"), "false");
} finally {
await renderer.unmount();
sftpTreeSelectionStore.clearPane(paneId);
for (const [key, descriptor] of previousEventTarget) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
if (previousObserver) Object.defineProperty(globalThis, "ResizeObserver", previousObserver);
else Reflect.deleteProperty(globalThis, "ResizeObserver");
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
dom.cleanup();
}
});
+4 -27
View File
@@ -22,13 +22,6 @@ import {
shouldShowSftpUploadFolderMenu,
shouldShowSftpUploadFilesMenu,
} from './sftpUploadMenu';
import { useStoredString } from '../../application/state/useStoredString';
import {
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
type SftpTreeFolderDoubleClickBehavior,
} from '../../domain/sftpTreeFolderDoubleClick';
import { STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR } from '../../infrastructure/config/storageKeys';
interface ContextTarget {
entry: SftpFileEntry;
entryPath: string;
@@ -36,12 +29,9 @@ interface ContextTarget {
export const getSftpTreeEntryOpenAction = (
entry: SftpFileEntry,
folderDoubleClickBehavior: SftpTreeFolderDoubleClickBehavior = DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
): 'up' | 'navigate' | 'expand' | 'open' => {
): 'up' | 'navigate' | 'open' => {
if (entry.name === '..') return 'up';
if (isNavigableDirectory(entry)) {
return folderDoubleClickBehavior === 'expand' ? 'expand' : 'navigate';
}
if (isNavigableDirectory(entry)) return 'navigate';
return 'open';
};
@@ -80,7 +70,6 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
onCdInTerminal,
sorting,
reloadRequest,
folderDoubleClickBehavior,
}) => {
const {
columnWidths,
@@ -436,30 +425,18 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
}
lastClickedPathRef.current = entryPath;
}, [focusTreeContainer, pane.id]);
const [storedFolderDoubleClickBehavior] = useStoredString<SftpTreeFolderDoubleClickBehavior>(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
);
const effectiveFolderDoubleClickBehavior = folderDoubleClickBehavior ?? storedFolderDoubleClickBehavior;
const folderDoubleClickBehaviorRef = useRef(effectiveFolderDoubleClickBehavior);
folderDoubleClickBehaviorRef.current = effectiveFolderDoubleClickBehavior;
const openTreeEntry = useCallback((entry: SftpFileEntry, entryPath: string) => {
const action = getSftpTreeEntryOpenAction(entry, folderDoubleClickBehaviorRef.current);
const action = getSftpTreeEntryOpenAction(entry);
if (action === 'up') {
onNavigateUpRef.current();
return;
}
if (action === 'expand') {
void toggleExpand(entry, entryPath);
return;
}
if (action === 'navigate') {
onNavigateToRef.current(entryPath);
return;
}
onOpenEntryRef.current(entry, entryPath);
}, [toggleExpand]);
}, []);
const stableOnRefresh = useCallback(() => onRefreshRef.current(), []);
const handleTreeContainerKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
@@ -2,7 +2,6 @@ import type { SftpFileEntry } from '../../types';
import type { SftpPane } from '../../application/state/sftp/types';
import type { SftpTransferSource } from './SftpContext';
import type { UseSftpPaneSortingResult } from '../../application/state/sftp/useSftpPaneSorting';
import type { SftpTreeFolderDoubleClickBehavior } from '../../domain/sftpTreeFolderDoubleClick';
export interface SftpPaneTreeViewProps {
pane: SftpPane;
@@ -39,5 +38,4 @@ export interface SftpPaneTreeViewProps {
onCdInTerminal?: (dirPath: string) => void;
sorting: UseSftpPaneSortingResult;
reloadRequest: { token: number; paths?: string[]; full?: boolean };
folderDoubleClickBehavior?: SftpTreeFolderDoubleClickBehavior;
}
@@ -1,53 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { I18nProvider } from '../../application/i18n/I18nProvider';
import { loadLocaleMessages } from '../../application/i18n/messages';
import { terminalCwdStore } from '../../application/state/terminalCwdStore';
import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController';
import { registerTerminalDirectory } from '../../application/state/terminalDirectoryRegistry';
import { ComposeDirectoryPicker } from './ComposeDirectoryPicker';
import type { ComposeBarTheme } from './TerminalComposeBar';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
for (const home of [null, '/tmp'] as const) {
test(`chip text, title and ARIA retain the confirmed display during a null cwd (home=${home})`, async t => {
await loadLocaleMessages('zh-CN');
const sessionId = 'chip-display-' + home;
const cwd = '/tmp/test_dir';
let root!: ReactTestRenderer;
let unregister = () => {};
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); });
await act(async () => {
root = create(<I18nProvider locale="zh-CN">
<ComposeDirectoryPicker sessionId={sessionId} theme={{} as ComposeBarTheme} onReturnFocus={() => {}} />
</I18nProvider>);
});
const chip = () => root.root.findByType('button');
const text = () => root.root.findByProps({ className: 'truncate' }).children.join('');
assert.equal(text(), '\u76ee\u5f55\u672a\u77e5');
assert.equal(chip().props.title, text());
assert.ok(chip().props['aria-label'].includes(text()));
await act(async () => {
unregister = registerTerminalDirectory(sessionId, createTerminalDirectoryController({
sessionId, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => cwd, home: async () => home, realpath: async path => path,
write() { assert.fail('display updates must not write to the terminal'); }, list: async () => ({ home, entries: [] }) },
publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'),
}));
});
const label = home ? '~/test_dir' : cwd;
assert.equal(text(), label);
const aria = chip().props['aria-label'];
assert.ok(aria.includes(label));
assert.equal(chip().props.title, cwd);
await act(async () => { terminalCwdStore.setCwd(sessionId, null); });
assert.equal(terminalCwdStore.getCwd(sessionId), null);
assert.equal(text(), label);
assert.equal(chip().props.title, cwd);
assert.equal(chip().props['aria-label'], aria);
});
}
@@ -2,7 +2,7 @@ import { ArrowUp, ChevronDown, Folder, LoaderCircle, RefreshCw } from 'lucide-re
import { memo, useEffect, useId, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useComposeDirectoryPicker } from '../../application/state/useComposeDirectoryPicker';
import { directoryDisplayName } from '../../domain/directoryPicker';
import { directoryDisplayName, directoryLabel } from '../../domain/directoryPicker';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import type { ComposeBarTheme } from './TerminalComposeBar';
@@ -51,8 +51,8 @@ export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ ses
<Popover open={model.open} onOpenChange={value => { if (value) outside.current = false; model.setOpen(value); }}>
<PopoverTrigger asChild>
<button type="button" disabled={model.pending}
aria-label={t('terminal.directory.open', { path: model.display?.ariaPath ?? t('terminal.directory.unknown') })}
title={model.display?.title ?? t('terminal.directory.unknown')}
aria-label={t('terminal.directory.open', { path: model.cwd ? directoryLabel(model.cwd, model.home, model.pathFlavor) : t('terminal.directory.unknown') })}
title={model.cwd ? directoryDisplayName(model.cwd) : t('terminal.directory.unknown')}
className="h-6 min-w-0 max-w-full flex items-center gap-1.5 rounded border px-2 text-[11px] font-mono transition-colors duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-60"
style={{ backgroundColor: theme.chipBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
onMouseEnter={(event) => {
@@ -63,7 +63,7 @@ export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ ses
}}
>
{model.pending ? <LoaderCircle size={12} className="shrink-0 animate-spin" /> : <Folder size={12} className="shrink-0" />}
<span className="truncate">{model.display?.label ?? t('terminal.directory.unknown')}</span>
<span className="truncate">{model.cwd ? directoryDisplayName(directoryLabel(model.cwd, model.home, model.pathFlavor)) : t('terminal.directory.unknown')}</span>
<ChevronDown size={10} className="shrink-0 opacity-60" />
</button>
</PopoverTrigger>
@@ -21,6 +21,5 @@ test("Ctrl-H mode makes Backspace delete on network-device serial consoles", ()
test("default mode preserves xterm Backspace and ordinary input", () => {
assert.equal(mapTerminalBackspaceInput("\x7f", undefined), "\x7f");
assert.equal(mapTerminalBackspaceInput("\x7f", "default"), "\x7f");
assert.equal(mapTerminalBackspaceInput("show version", "ctrl-h"), "show version");
});
@@ -1,5 +1,4 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { JSDOM } from 'jsdom';
@@ -20,35 +19,6 @@ import {
resolveSidePanelPortalTarget,
} from './terminalLayerSidePanelSlots.tsx';
test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it away', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const paneHost = source.slice(
source.indexOf('function SidePanelPaneHost'),
source.indexOf('function TerminalLayerSidePanelInner'),
);
assert.ok(paneHost.length > 0, 'SidePanelPaneHost source slice must exist');
// The close button is the only button in the pane header; it must not shrink
// when the pane label is truncated at narrow split widths.
const closeButton = paneHost.match(/<button[\s\S]*?aria-label=\{`\$\{closePaneLabel\}/);
assert.ok(closeButton, 'pane header close button must exist');
assert.match(
closeButton![0],
/className="[^"]*\bshrink-0\b[^"]*"/,
'pane header close button must carry shrink-0 so it stays visible at narrow widths',
);
});
test('magnified side panels use a continuous 1px inset outline in the side panel accent', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /outline: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(chromeSource, /outlineOffset: -1/);
assert.doesNotMatch(chromeSource, /\bborder(?:Color|Width|Style)?\b/);
});
test('AI side panel shell can be force-hidden for layout isolation', () => {
assert.equal(getTerminalSidePanelShellWidth({
activeSidePanelTab: 'ai',
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
const MemoizedSidePanelMountedContent = memo(
SidePanelMountedContent,
@@ -168,7 +168,7 @@ function SidePanelPaneHost({
<span className="text-[11px] font-medium truncate flex-1">{label}</span>
<button
type="button"
className="h-5 w-5 shrink-0 grid place-items-center rounded-sm opacity-70 hover:opacity-100 hover:bg-white/10"
className="h-5 w-5 grid place-items-center rounded-sm opacity-70 hover:opacity-100 hover:bg-white/10"
aria-label={`${closePaneLabel}: ${label}`}
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => {
@@ -1567,10 +1567,12 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
style={{
outline: `1px solid ${sidePanelTheme.accent}`,
outlineOffset: -1,
borderColor: sidePanelTheme.accent,
borderWidth: resolveMagnifiedChromeBorderWidth(
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
),
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
}}
@@ -53,6 +53,7 @@ import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePane
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
PANE_MAGNIFICATION_DURATION_MS,
resolveMagnifiedChromeBorderWidth,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
type PaneMagnificationController,
@@ -682,7 +683,6 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE
AIChatPanelsHost.displayName = 'AIChatPanelsHost';
export interface TerminalLayerProps {
isVaultInitialized?: boolean;
hosts: Host[];
portForwardingRules?: import('../../domain/models').PortForwardingRule[];
customGroups: string[];
@@ -822,7 +822,6 @@ interface TerminalPaneProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -962,7 +961,6 @@ const terminalPanePropsAreEqual = (
prev.splitHorizontalHandlersRef === next.splitHorizontalHandlersRef &&
prev.splitVerticalHandlersRef === next.splitVerticalHandlersRef &&
getPaneAppearanceThemeId(prev) === getPaneAppearanceThemeId(next) &&
prev.isVaultInitialized === next.isVaultInitialized &&
prev.keys === next.keys &&
prev.identities === next.identities &&
prev.snippets === next.snippets &&
@@ -1255,7 +1253,6 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -1646,14 +1643,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
"absolute bg-background",
inActiveWorkspace && "workspace-pane",
isVisible && "z-10",
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",
)}
style={{
...style,
outline: magnifiedSurfaceBounds
? `1px solid ${sessionAppearanceTheme.colors.cursor}`
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
borderWidth: isMagnified && magnifiedSurfaceBounds
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
: undefined,
outlineOffset: magnifiedSurfaceBounds ? -1 : undefined,
}}
tabIndex={-1}
onClick={handlePaneClick}
@@ -1683,7 +1680,6 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
sessionId={session.id}
workspaceId={session.workspaceId}
restoreState={session.restoreState}
vaultInitializedOverride={isVaultInitialized}
pendingInitialCwd={session.pendingInitialCwd}
shellType={session.shellType}
lastCwd={session.lastCwd}
@@ -1780,7 +1776,6 @@ interface TerminalPanesHostProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -1876,7 +1871,6 @@ const terminalPanesHostPropsAreEqual = (
if (prev.splitVerticalHandlersRef !== next.splitVerticalHandlersRef) return false;
if (prev.resolveSessionAppearance !== next.resolveSessionAppearance) return false;
if (prev.hostMap !== next.hostMap) return false;
if (prev.isVaultInitialized !== next.isVaultInitialized) return false;
if (prev.keys !== next.keys) return false;
if (prev.identities !== next.identities) return false;
if (prev.snippets !== next.snippets) return false;
@@ -9,41 +9,14 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("terminal pane chrome follows retained surface bounds through restore with a continuous 1px inset outline", () => {
test("magnified terminal panes use the resolved terminal accent for border chrome", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
assert.match(paneSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
assert.match(paneSource, /outline: magnifiedSurfaceBounds\s+\? `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`\s+: undefined/);
assert.match(paneSource, /outlineOffset: magnifiedSurfaceBounds \? -1 : undefined/);
assert.doesNotMatch(paneSource, /\bborder(?:Color|Width|Style)?\b/);
});
test("restoring terminal chrome keeps its 1px inset outline until surface bounds clear at any DPR", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
const styleSource = paneSource.match(/style=\{\{([\s\S]*?)\}\}/);
assert.ok(styleSource);
const resolveStyle = new Function(
"style", "isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme",
"magnifiedDevicePixelRatio",
`return ({${styleSource[1]}});`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStyle({}, true, bounds, theme, dpr);
const restoring = resolveStyle({}, false, bounds, theme, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.outline, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.outlineOffset, -1);
for (const isMagnified of [false, true]) {
const cleared = resolveStyle({}, isMagnified, null, theme, dpr);
assert.equal(cleared.outline, undefined);
assert.equal(cleared.outlineOffset, undefined);
}
}
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl"/);
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
@@ -62,7 +62,6 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -231,7 +230,6 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef={splitVerticalHandlersRef}
resolveSessionAppearance={resolveSessionAppearance}
hostMap={hostMap}
isVaultInitialized={isVaultInitialized}
keys={keys}
identities={identities}
snippets={snippets}
@@ -383,7 +383,6 @@ const WORKSPACE_CTX_KEYS = [
'splitVerticalHandlersRef',
'resolveSessionAppearance',
'hostMap',
'isVaultInitialized',
'keys',
'identities',
'snippets',
-1
View File
@@ -4,7 +4,6 @@ export const terminalLayerAreEqual = (
prev: Record<string, unknown>,
next: Record<string, unknown>,
): boolean => (
prev.isVaultInitialized === next.isVaultInitialized &&
prev.hosts === next.hosts &&
prev.customGroups === next.customGroups &&
prev.groupConfigs === next.groupConfigs &&
+16 -5
View File
@@ -26,6 +26,8 @@ import { resolveSessionCodingCliProvider } from '../../domain/codingCliProviderM
import type { CodingCliProvider } from '../../domain/codingCliProviders';
import { resolveCodingCliActivityPhase, type CodingCliActivityPhase } from '../../domain/codingCliTitleParse';
import {
buildMergedWorkspaceTitleFromSessions,
DEFAULT_WORKSPACE_TITLE,
resolveSessionTabTitle,
resolveWorkspaceTabLabel,
} from '../../domain/sessionTabTitle';
@@ -259,15 +261,24 @@ export const formatSessionTopTabLabel = (
type WorkspaceTopTabLabelWorkspace = Pick<
Workspace,
'title' | 'focusedSessionId' | 'autoTitle' | 'generatedTitle'
>;
'title' | 'focusedSessionId' | 'autoTitle'
> & {
generatedTitle?: boolean;
};
export const resolveWorkspaceTopTabLabel = (
workspace: WorkspaceTopTabLabelWorkspace,
sessions: readonly TerminalSession[],
dynamicTabTitleMode?: DynamicTabTitleMode,
): string => {
return resolveWorkspaceTabLabel(workspace, sessions.map(applySessionPresentation), dynamicTabTitleMode);
const presentedSessions = sessions.map(applySessionPresentation);
const resolvedWorkspace = workspace.generatedTitle
? {
...workspace,
title: buildMergedWorkspaceTitleFromSessions(presentedSessions) ?? DEFAULT_WORKSPACE_TITLE,
autoTitle: false,
}
: workspace;
return resolveWorkspaceTabLabel(resolvedWorkspace, presentedSessions);
};
export const createTopTabCopyDoubleClickHandler = (
@@ -1095,7 +1106,7 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
[onCopyWorkspace, workspace.id, tabDoubleClickBehavior],
);
const detachSessions = workspaceSessions ?? [];
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions, dynamicTabTitleMode);
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions);
return (
<ContextMenu>
-121
View File
@@ -1,121 +0,0 @@
# Long-running jobs on many sessions (`terminal_start_bulk`, `terminal_poll_bulk`, `terminal_stop_bulk`)
These tools start the same long-running command as a background job on 2–20 open
terminal sessions, then poll and stop those jobs together. They are the bulk versions
of `terminal_start`, `terminal_poll` and `terminal_stop`, for upgrades, builds, scans
or log checks across hosts. For short commands on many sessions use
`terminal_execute_bulk` (see [terminal-execute-bulk.md](terminal-execute-bulk.md)).
They are available to MCP clients only. Load them over MCP with `load_netcatty_tools`
and the `terminal_bulk` toolset.
## `terminal_start_bulk`
| Field | Type | Notes |
|---|---|---|
| `command` | string | Same rules as `terminal_start`. |
| `sessionIds` | string | JSON array of 2–20 unique session IDs. Resolve IDs with `get_environment`. |
Before anything starts, every target is checked with the rules `terminal_start` uses:
session scope, closing, already busy, connected, a shell-backed PTY (network devices,
serial sessions and sessions without a writable terminal are refused), and the command
safety policy for that session's shell. If **any** target fails, no job starts on any
host and the call fails, listing every bad target at once. Out-of-scope IDs are
reported without a label.
Approval works like `terminal_execute_bulk`: observer mode refuses, confirm mode asks
**once** with a card listing the command and every host, and that approval is never
satisfied by a remembered grant or by "allow for this session". In confirm mode no host
is contacted before you answer; the shell-kind probe and the shell-specific safety
patterns run right after approval, before any job starts. Sessions hosted by the
terminal worker are checked the same way, with a no-send `precheck` of the worker's
job start.
```json
{
"ok": true,
"bulkId": "bulk_m1x2y3_ab12cd34",
"hostCount": 3,
"counts": { "running": 3 },
"jobs": [
{ "sessionId": "s-web1", "label": "web1", "jobId": "job_…", "status": "running" },
{ "sessionId": "s-web2", "label": "web2", "jobId": "job_…", "status": "running" },
{ "sessionId": "s-db1", "label": "db1", "jobId": "job_…", "status": "running" }
],
"recommendedPollIntervalMs": 30000
}
```
- `running` means the job was **launched**. As with `terminal_start`, a terminal that is
not ready when the command is sent (a pager, a password prompt, a prompt that cannot
be recognized) shows up as `failed` on the first poll.
- A host whose job could not be started at all is listed with `status: "not_started"` and
an `error`; the other jobs keep running, because jobs already started are not undone.
If no job started, the call fails with `Error: No background job was started.`
- Each session stays busy until its job ends (at most 1 hour), so other commands on it
are refused meanwhile.
- Jobs keep running when the agent run is stopped. Stop them with `terminal_stop_bulk`.
- There is no way to answer prompts in a running job, so use non-interactive commands
(`-y`, `DEBIAN_FRONTEND=noninteractive`, `sudo -n`).
## `terminal_poll_bulk`
| Field | Type | Notes |
|---|---|---|
| `bulkId` | string, optional | From `terminal_start_bulk`. Pass this or `jobIds`. |
| `jobIds` | string, optional | JSON array of 1–20 job IDs, instead of a `bulkId`. |
| `offsets` | string, optional | JSON object `{ "<jobId>": <nextOffset> }` from the previous poll. Missing jobs start at 0. |
```json
{
"ok": true,
"bulkId": "bulk_m1x2y3_ab12cd34",
"jobCount": 3,
"allCompleted": false,
"counts": { "running": 1, "completed": 1, "failed": 1 },
"jobs": [
{ "jobId": "job_…", "sessionId": "s-web1", "label": "web1", "status": "running", "exitCode": null, "nextOffset": 5120, "output": "…" },
{ "jobId": "job_…", "sessionId": "s-web2", "label": "web2", "status": "completed", "exitCode": 0, "nextOffset": 9000, "output": "…" },
{ "jobId": "job_…", "sessionId": "s-db1", "label": "db1", "status": "failed", "exitCode": 100, "nextOffset": 300, "output": "…", "error": "…" }
],
"recommendedPollIntervalMs": 30000
}
```
- Each job returns at most 4 KB of new output, and all jobs together at most 32 KB.
The total is shared by need: jobs with little new output take only what they need,
and the rest goes to busy jobs (with 20 busy jobs, about 1.6 KB each). When a job has
more new output than its share, the **newest** output is returned and `skippedChars`
says how much was skipped. Output older than the job's kept window (the last 256 KB)
also counts as skipped. Use `terminal_poll` on one job for its full output.
- Pass each job's `nextOffset` back in `offsets` to get only new output next time.
Offsets count the raw output; progress redraws (`\r`) are collapsed to the latest frame.
- `allCompleted` is `true` when no job is `running` or `stopping`.
- A job that expired (10 minutes after it finished), is out of scope, or belongs to
another chat is reported per job with `status: "unavailable"`; the poll itself still
succeeds.
## `terminal_stop_bulk`
| Field | Type | Notes |
|---|---|---|
| `bulkId` | string, optional | From `terminal_start_bulk`. Pass this or `jobIds`. |
| `jobIds` | string, optional | JSON array of 1–20 job IDs, instead of a `bulkId`. |
Stops every job with the existing `terminal_stop` behavior: no approval, and it works
in observer mode, so a runaway rollout can always be stopped. Each job reports its
status (`stopping`, or its final status if it already ended); missing jobs are reported
per job as `unavailable`.
## `bulkId`
A `bulkId` names the jobs one `terminal_start_bulk` call started, so polling and
stopping need one ID instead of many. It belongs to the chat that created it, like each
job does, and expires after the jobs' lifetime (75 minutes). After that, poll or stop
the jobs by `jobIds`.
## Not included
The in-app agents (Catty and the global agent) do not get these tools yet, and plugin
agents cannot call them. Sending input to running jobs, targets by group or tag, and
opening missing sessions are not part of these tools.
+2 -4
View File
@@ -3,8 +3,7 @@
`terminal_execute_bulk` runs the same short command on 2–20 open terminal sessions and
waits for all of them. It is available to MCP clients only (the in-app agents do not get it yet). Load it
over MCP with `load_netcatty_tools` and the `terminal_bulk` toolset. For a single host use
`terminal_execute`; fewer than 2 sessions is rejected. For long-running commands on many sessions use
`terminal_start_bulk` (see [terminal-bulk-jobs.md](terminal-bulk-jobs.md)).
`terminal_execute`; fewer than 2 sessions is rejected.
## Input
@@ -107,8 +106,7 @@ are grouped, which keeps the response small on large fleets.
`cancelled`, `connection_lost`, `error`, or `not_sent`.
- `exitCode` is a number only for `completed`. A non-zero exit code is a normal result,
not a tool failure. Serial and network-device sessions have no exit code (`null`).
- `stderr` and `error` are omitted when empty. On interactive terminals stderr is part of stdout, so `stderr` usually
appears only for sessions that run the command over an SSH exec channel.
- `stderr` and `error` are omitted when empty.
- Output is grouped on the full, untruncated result, so two hosts that differ only in the
part that was cut off are never merged. `tailLines` and a per-group size cap are then
applied; a cut group has `outputTruncated: true` (also set when the exec layer had already dropped the beginning of a very large output) and, when lines were dropped,
@@ -8,7 +8,7 @@ Context Chips 位于终端撰写栏的快捷命令与输入区之间,为当前
| 功能 | 当前范围 | 文档 |
| --- | --- | --- |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD 和 Git Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Directory Picker | 目录展示、当前层搜索、父级/子目录导航;POSIX 与 Windows PowerShell 适配 | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Git Branch | 后续接入仓库识别、分支读取与切换 | [Git Branch](git-branch.md) |
| Git Changes | 后续接入变更统计与详情入口 | [Git Changes](git-changes.md) |
| Node Version | 后续接入当前 shell 的运行时与版本管理器 | [Node Version](node-version.md) |
@@ -10,7 +10,6 @@
| Unix SSH | 活动会话的严格查询/OSC 7 | 同一认证连接的 SFTP | 绑定原终端,按连接能力确认 |
| Windows PowerShell 5.1/7 | 原 runspace 的 FileSystem ProviderPath | Windows 本地 FS | Set-Location -LiteralPath,等待新位置报告 |
| Windows CMD | 会话 PROMPT 的 `$P` | Windows 本地 FS | `cd /d`,等待原 CMD 报告目标位置 |
| Git for Windows Bash | 原 Bash 的 MSYS `/proc/<pid>/cwd` | MSYS 映射的 Windows 盘符路径 | Bash 内建 `cd`,重新读取原进程 cwd |
## 路径与能力模型
@@ -61,12 +60,6 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根
目录列表遵循 Windows 访问权限。系统兼容链接拒绝枚举时,菜单显示权限原因,并保留父目录入口。等待原 CMD 会话报告位置时,菜单显示对应的 CMD 状态,收到有效报告后恢复目录导航。
## Git Bash 会话集成
根据 Git for Windows 的安装记录识别 Bash。定位启动器下的原 Bash 进程后,用同一安装的 MSYS 工具读取 `/proc/<pid>/cwd`,再通过 `cygpath` 映射为 Windows 盘符路径。菜单按 Windows 文件系统展示父级和子目录,原会话使用 Bash 内建 `cd` 切换,并由新一次读取确认结果。
启动参数、profile 和提示符沿用用户配置。存在子进程时暂缓目录操作,原 Bash 恢复后重新读取。共享路径和虚拟挂载留到各自的路径语义明确后扩展。
## 后续设计方向
- POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。
@@ -9,7 +9,6 @@
| A:路径与能力 | POSIX/Win32 路径模型;盘符/UNC 根;authority、cwd revision;独立 read/list/change/confirm 能力;可注入命令策略 | 将目标文件系统和 shell 语法分别建模,保持菜单可复用 |
| B:PowerShell | 5.1/7 会话级脚本;原 runspace ProviderPath;私有位置报告;本地 FS;LiteralPath 切换和实际结果确认 | 用原 shell 状态串联展示、读取和执行 |
| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 |
| D1:Git Bash | 绑定原 Git for Windows Bash,读取 MSYS cwd 并映射为 Windows 盘符路径 | 保留 Bash 启动行为,复用 Windows 文件系统和目录控制器 |
| 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
@@ -17,8 +16,6 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
## 后续阶段
Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库与 worktree 状态推进 [Git Changes](git-changes.md) 和 [Pull Request](pull-request.md)。[Node Version](node-version.md) 独立接入 shell 与版本管理器。目录兼容性按环境分别提交。
### PowerShell 覆盖扩展
继续补充主题/profile 组合、prompt 内位置变化、受限语言模式、大小写敏感目录和共享目录权限场景。每项先建立原生 ConPTY fixture,再完善能力状态和路径确认策略。
@@ -38,12 +35,12 @@ Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库
为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。
### D2/D3:WSL 与 Cygwin
### D:WSL、Git Bash 与 Cygwin
为每类环境定义文件系统 authority、cwd 来源、结构化目录 helper 与执行策略:
- WSL:绑定所选 distro,验证 Linux home、挂载盘及 wslpath/UNC 映射。
- Cygwin:验证 mount、驱动器、链接和编码转换。Git Bash 后续补充共享路径和虚拟挂载语义。
- MSYS/Cygwin:验证 mount、驱动器、链接和编码转换。
- helper:保留原始名称、类型和目录链接,提供输出边界、取消及权限状态。
交付目标是让目录读取与命令执行处于同一命名空间,并按 distro/mount 身份组织缓存。
-23
View File
@@ -1,23 +0,0 @@
import { directoryDisplayName, directoryLabel } from './directoryPicker';
import type { DirectoryPathFlavor } from './directoryPath';
export type ComposeDirectoryDisplay = {
home: string | null;
label: string;
title: string;
ariaPath: string;
};
/** Display only: a retained label must never be used as a live cwd. */
export function resolveComposeDirectoryDisplay(
previous: ComposeDirectoryDisplay | null,
cwd: string | null,
home: string | null,
flavor: DirectoryPathFlavor,
): ComposeDirectoryDisplay | null {
// Native Windows nulls can mean a non-filesystem provider or integration failure.
if (!cwd) return flavor === 'posix' ? previous : null;
const displayHome = home ?? previous?.home ?? null;
const ariaPath = directoryLabel(cwd, displayHome, flavor);
return { home: displayHome, label: directoryDisplayName(ariaPath), title: directoryDisplayName(cwd), ariaPath };
}
-120
View File
@@ -6,130 +6,10 @@ import {
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding,
} from './customKeyBindings.ts';
import { DEFAULT_KEY_BINDINGS, keyStringToKeyboardEvent } from './models/keyBindings.ts';
import { checkAppShortcut } from '../application/state/useGlobalHotkeys.ts';
function shortcut(key: string, bindings = DEFAULT_KEY_BINDINGS, isMac = false) {
const event = keyStringToKeyboardEvent(key);
assert.ok(event);
return checkAppShortcut(event, bindings, isMac)?.action ?? null;
}
test('resolving defaults preserves reopen, new tab, and local terminal shortcuts', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {});
assert.deepEqual(bindings, DEFAULT_KEY_BINDINGS);
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
assert.equal(shortcut('Ctrl + T', bindings), 'newTab');
assert.equal(shortcut('\u2318 + L', bindings, true), 'openLocal');
});
test('custom PC open-local evicts the conflicting reopen default only on PC', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'openLocal');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
});
test('custom macOS open-local evicts the conflicting reopen default only on macOS', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { mac: '\u2318 + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, '\u2318 + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.mac, 'Disabled');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'openLocal');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
});
test('unrelated custom shortcuts leave reopen defaults intact', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + L' },
});
assert.equal(shortcut('Ctrl + L', bindings), 'openLocal');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
});
for (const [id, key] of [['copy', 'C'], ['paste', 'V']]) {
test(`recording the terminal ${id} default preserves the SFTP default`, () => {
const chord = `\u2318 + ${key}`;
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
[id]: { mac: chord },
});
assert.equal(bindings.find(binding => binding.id === id)?.mac, chord);
assert.equal(bindings.find(binding => binding.id === `sftp-${id}`)?.mac, chord);
});
}
test('custom SFTP chords preserve conflicting app-level defaults on both schemes', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'sftp-copy': { mac: '\u2318 + Shift + T', pc: 'Ctrl + Shift + T' },
});
for (const id of ['sftp-copy', 'reopen-closed-tab']) {
assert.equal(bindings.find(binding => binding.id === id)?.mac, '\u2318 + Shift + T');
assert.equal(bindings.find(binding => binding.id === id)?.pc, 'Ctrl + Shift + T');
}
});
test('custom SFTP chords still evict conflicting defaults within SFTP', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'sftp-copy': { mac: '\u2318 + V', pc: 'Ctrl + V' },
});
assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.mac, '\u2318 + V');
assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.pc, 'Ctrl + V');
assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.mac, 'Disabled');
assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.pc, 'Disabled');
assert.equal(bindings.find(binding => binding.id === 'paste')?.mac, '\u2318 + V');
});
test('conflicting custom shortcuts remain while uncustomized defaults are evicted', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
'open-hosts': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'open-hosts')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
});
test('an explicitly customized reopen binding retains its conflicting chord', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
'reopen-closed-tab': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T');
});
test('resolving conflicts does not mutate defaults or custom overrides', () => {
const defaults = structuredClone(DEFAULT_KEY_BINDINGS);
const custom = { 'open-local': { pc: 'Ctrl + Shift + T', mac: 'Disabled' } };
const originalCustom = structuredClone(custom);
const bindings = resolveKeyBindings(defaults, custom);
assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, 'Disabled');
assert.deepEqual(defaults, DEFAULT_KEY_BINDINGS);
assert.deepEqual(custom, originalCustom);
});
test('parses legacy stored custom key bindings without sync metadata', () => {
const parsed = parseCustomKeyBindingsStorageRecord('{"open":{"mac":"Cmd+K"}}');
+1 -36
View File
@@ -1,39 +1,4 @@
import { CustomKeyBindings, KeyBinding } from './models';
export const resolveKeyBindings = (
defaults: readonly KeyBinding[],
customKeyBindings: CustomKeyBindings,
): KeyBinding[] => {
let merged = defaults.map(binding => {
const custom = customKeyBindings[binding.id];
if (!custom) return binding;
return {
...binding,
mac: custom.mac ?? binding.mac,
pc: custom.pc ?? binding.pc,
};
});
for (const scheme of ['mac', 'pc'] as const) {
const customChords = { sftp: new Set<string>(), app: new Set<string>() };
for (const binding of merged) {
if (customKeyBindings[binding.id]?.[scheme] != null && binding[scheme] !== 'Disabled') {
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(binding[scheme]);
}
}
// SFTP has its own input context; all other categories share the app-level handler.
// Custom shortcuts win over defaults in that context; custom conflicts remain unchanged.
merged = merged.map(binding => (
customKeyBindings[binding.id]?.[scheme] == null &&
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].has(binding[scheme])
? { ...binding, [scheme]: 'Disabled' }
: binding
));
}
return merged;
};
import { CustomKeyBindings } from './models';
const SYNC_VERSION_FIELD = '__netcattySyncVersion';
const SYNC_ORIGIN_FIELD = '__netcattySyncOrigin';
+2 -8
View File
@@ -3,8 +3,7 @@ import { resolveInteractiveTerminalCdIntent } from './sessionRestore';
import { isAbsoluteDirectoryPath, joinDirectoryPath, labelDirectoryPath, parentDirectoryPath, type DirectoryPathFlavor } from './directoryPath';
export type DirectoryEntry = { name: string; path: string; hidden: boolean };
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'nonFilesystem';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'nonFilesystem';
export class DirectoryPickerError extends Error {
constructor(public readonly code: DirectoryPickerErrorCode) { super(code); }
@@ -39,7 +38,7 @@ export const COMPLETE_DIRECTORY_CAPABILITIES: DirectoryCapabilities = Object.fre
});
/** A shell adapter constructs input for the original interactive shell. */
export function directoryChangeCommand(path: string, shell: 'posix' | WindowsDirectoryShell, flavor: DirectoryPathFlavor): string | null {
export function directoryChangeCommand(path: string, shell: 'posix' | 'powershell' | 'cmd', flavor: DirectoryPathFlavor): string | null {
if (!isDirectoryPath(path, flavor)) return null;
if (shell === 'cmd') {
if (flavor !== 'win32' || !/^[a-z]:[\\/]/i.test(path) || /[%!]/.test(path)) return null;
@@ -50,11 +49,6 @@ export function directoryChangeCommand(path: string, shell: 'posix' | WindowsDir
// PowerShell recognizes smart single quotes as delimiters too. Doubling
// only ASCII apostrophes would let a filename terminate the literal.
if (shell === 'powershell') return `Microsoft.PowerShell.Management\\Set-Location -LiteralPath '${path.replace(/['\u2018\u2019\u201a\u201b]/g, quote => quote + quote)}'`;
if (shell === 'git-bash') {
if (flavor !== 'win32' || !/^[a-z]:[\\/]/i.test(path)) return null;
const target = path.replace(/\\/g, '/').replace(/'/g, "'\\''");
return `\\builtin cd -- '${target}'`;
}
return flavor === 'posix' ? resolveInteractiveTerminalCdIntent(path)?.command ?? null : null;
}
-7
View File
@@ -63,13 +63,6 @@ test("applyGroupDefaults lets host device type override group device type", () =
assert.equal(result.deviceType, "general");
});
test("applyGroupDefaults preserves explicit DEL over group Ctrl-H after persistence", () => {
const groupDefaults: Partial<GroupConfig> = { backspaceBehavior: "ctrl-h" };
const saved: Host = JSON.parse(JSON.stringify(host({ backspaceBehavior: "default" })));
assert.equal(applyGroupDefaults(saved, groupDefaults).backspaceBehavior, "default");
assert.equal(applyGroupDefaults(host(), groupDefaults).backspaceBehavior, "ctrl-h");
});
test("applyGroupDefaults skips remote-only device type for local shell hosts", () => {
const result = applyGroupDefaults(host({ protocol: "local" }), { deviceType: "network" });
+2 -2
View File
@@ -314,8 +314,8 @@ export interface Host {
// Show local timestamps for this host beside terminal output rows.
// Kept per-host because timestamp visibility is usually a host/workflow preference.
showLineTimestamps?: boolean;
// Undefined inherits; 'default' sends DEL (0x7F), 'ctrl-h' sends ^H (0x08).
backspaceBehavior?: 'default' | 'ctrl-h';
// What the Backspace key sends: undefined = xterm default (no interception), 'ctrl-h' = ^H (0x08)
backspaceBehavior?: 'ctrl-h';
// When true, tab titles stay on the connection label instead of following the
// shell-reported window title (OSC 0/2). Useful when many hosts share one
// bastion profile name.
+10
View File
@@ -9,6 +9,7 @@ import {
resolvePaneMagnificationCandidate,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
resolveMagnifiedChromeBorderWidth,
resolveTwoPaneMagnificationStyle,
snapCssRectToDevicePixels,
type PaneMagnificationController,
@@ -100,6 +101,15 @@ test('magnification overlays the original layout without changing its rect', ()
});
});
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
});
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
// Integer CSS pixels at 1x stay unchanged (existing contract).
+4
View File
@@ -92,6 +92,10 @@ export function getPaneMagnificationShortcutLabel(
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
}
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
}
export function snapCssRectToDevicePixels(
left: number,
top: number,
+133 -244
View File
@@ -5,6 +5,7 @@ import {
buildMergedWorkspaceTitle,
buildMergedWorkspaceTitleFromSessions,
getSessionConnectionLabel,
isGenericLoopbackHostname,
resolveCodingCliProviderIconUpdate,
resolveSessionTabTitle,
resolveWorkspaceTabLabel,
@@ -22,68 +23,6 @@ test('getSessionConnectionLabel prefers customName over hostLabel', () => {
);
});
test('connection identity ignores live prompt hostnames', () => {
const session = { hostLabel: 'Production', promptHostname: 'vm-prod' };
assert.equal(getSessionConnectionLabel(session), session.hostLabel);
});
test('ordinary SSH prompt hostnames do not replace configured names by default', () => {
const session = { hostLabel: 'Production', promptHostname: 'vm-prod' };
for (const mode of [undefined, 'off', 'agent'] as const) {
assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel, String(mode));
}
});
test('agent mode does not use a prompt hostname when the agent has no title', () => {
const session = {
hostLabel: 'Production', promptHostname: 'vm-prod', codingCliProviderId: 'claude' as const,
};
assert.equal(resolveSessionTabTitle(session, 'agent'), session.hostLabel);
});
test('persisted merged workspace identities ignore live hostnames', () => {
const sessions = [
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
{ id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' },
];
assert.equal(
buildMergedWorkspaceTitleFromSessions(sessions),
buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel),
);
});
test('auto workspace labels honor disabled and agent-only modes', () => {
const session = { id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' };
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
for (const mode of [undefined, 'off', 'agent'] as const) {
assert.equal(resolveWorkspaceTabLabel(workspace, [session], mode), session.hostLabel, String(mode));
}
});
test('auto workspace labels use the same agent title policy as session tabs', () => {
const session = {
id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod',
dynamicTitle: 'claude: deploy', codingCliProviderId: 'claude' as const,
};
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
assert.equal(resolveWorkspaceTabLabel(workspace, [session], 'agent'), session.dynamicTitle);
});
test('generated workspace display titles honor mode without changing their saved identity', () => {
const sessions = [
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
{ id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' },
];
const savedTitle = buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel)!;
const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: 'a' };
assert.equal(resolveWorkspaceTabLabel(workspace, sessions, 'off'), savedTitle);
assert.equal(
resolveWorkspaceTabLabel(workspace, sessions, 'all'),
buildMergedWorkspaceTitle(sessions[0].promptHostname, sessions[1].promptHostname),
);
assert.equal(workspace.title, savedTitle);
});
test('resolveSessionTabTitle ignores dynamic title for non-agent sessions', () => {
assert.equal(
resolveSessionTabTitle(
@@ -147,12 +86,12 @@ test('resolveSessionTabTitle strips agent spinner prefixes from dynamic titles',
);
});
test('resolveSessionTabTitle uses a detected prompt host in all mode', () => {
test('resolveSessionTabTitle uses a detected prompt host ahead of hostLabel', () => {
assert.equal(
resolveSessionTabTitle({
hostLabel: 'jumpserver',
promptHostname: '10.1.64.1',
}, 'all'),
}),
'10.1.64.1',
);
});
@@ -191,6 +130,136 @@ test('resolveSessionTabTitle prefers the live prompt host over a generic shell t
);
});
test('isGenericLoopbackHostname matches only generic localhost and loopback names', () => {
for (const generic of [
'localhost',
'localhost.localdomain',
'localhost.local',
'127.0.0.1',
'::1',
'LocalHost',
' LOCALHOST.LOCALDOMAIN. ',
'localhost.',
]) {
assert.equal(isGenericLoopbackHostname(generic), true, generic);
}
for (const specific of ['', ' ', '.', 'localhost..', 'ubuntu', '10.1.64.1', '192.168.100.222']) {
assert.equal(isGenericLoopbackHostname(specific), false, specific);
}
});
test('resolveSessionTabTitle ignores generic localhost prompt hosts in default and agent modes', () => {
for (const promptHostname of [
'localhost',
'localhost.localdomain',
'localhost.local',
'127.0.0.1',
'::1',
'LocalHost',
'localhost.',
]) {
assert.equal(
resolveSessionTabTitle({
hostLabel: '192.168.100.222',
promptHostname,
}),
'192.168.100.222',
);
assert.equal(
resolveSessionTabTitle(
{
hostLabel: '192.168.100.222',
promptHostname,
dynamicTitle: 'root@localhost:~',
},
'agent',
),
'192.168.100.222',
);
}
});
test('resolveSessionTabTitle keeps distinct SSH hostLabels when both remotes report localhost', () => {
const sessionA = { hostLabel: '192.168.100.222', promptHostname: 'localhost' };
const sessionB = { hostLabel: '192.168.100.220', promptHostname: 'localhost' };
assert.equal(resolveSessionTabTitle(sessionA), '192.168.100.222');
assert.equal(resolveSessionTabTitle(sessionB), '192.168.100.220');
});
test('resolveSessionTabTitle keeps customName ahead of a generic prompt host', () => {
assert.equal(
resolveSessionTabTitle({
customName: 'LAN Node 1',
hostLabel: '192.168.100.222',
promptHostname: 'localhost',
}),
'LAN Node 1',
);
});
test('getSessionConnectionLabel skips generic promptHostname and keeps non-generic ones', () => {
assert.equal(
getSessionConnectionLabel({
hostLabel: '192.168.100.222',
promptHostname: 'localhost',
}),
'192.168.100.222',
);
assert.equal(
getSessionConnectionLabel({
hostLabel: '192.168.100.222',
promptHostname: 'localhost.localdomain',
}),
'192.168.100.222',
);
assert.equal(
getSessionConnectionLabel({
customName: 'Node 222',
hostLabel: '192.168.100.222',
promptHostname: 'localhost',
}),
'Node 222',
);
assert.equal(
getSessionConnectionLabel({
hostLabel: '192.168.100.222',
promptHostname: 'ubuntu',
}),
'ubuntu',
);
});
test('resolveSessionTabTitle keeps non-generic prompt host overrides across default, agent, and all modes', () => {
assert.equal(
resolveSessionTabTitle({
hostLabel: '192.168.100.222',
promptHostname: 'ubuntu',
}),
'ubuntu',
);
assert.equal(
resolveSessionTabTitle(
{
hostLabel: '192.168.100.222',
promptHostname: 'ubuntu',
},
'agent',
),
'ubuntu',
);
assert.equal(
resolveSessionTabTitle(
{
hostLabel: '192.168.100.222',
promptHostname: 'ubuntu',
dynamicTitle: 'root@ubuntu:~',
},
'all',
),
'ubuntu',
);
});
test('coding CLI icon updates stop without clearing the current icon when dynamic titles are off', () => {
assert.equal(shouldUpdateCodingCliTabIcon('off'), false);
assert.equal(shouldUpdateCodingCliTabIcon('agent'), true);
@@ -362,183 +431,3 @@ test('buildMergedWorkspaceTitleFromSessions recomputes from live membership', ()
'01/02',
);
});
// External review examples: the expected field is part of the contract, not
// computed by resolveSessionTabTitle or another display-title helper.
const reviewedAllTitleCases = [
{
name: 'same-host shell title retains username and cwd',
session: { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@web01: ~/app' },
expectedField: 'dynamicTitle',
},
{
name: 'old shell host gives way to the current prompt host',
session: { hostLabel: 'Database entry', promptHostname: 'db02', dynamicTitle: 'ubuntu@web01: ~/app' },
expectedField: 'promptHostname',
},
{
name: 'JumpServer transport title gives way to the target prompt host',
session: { hostLabel: 'Jump fleet', promptHostname: 'target-01', dynamicTitle: 'user@jumpssh:2222' },
expectedField: 'promptHostname',
},
{
name: 'program title retains its document context',
session: { hostLabel: 'Editor server', promptHostname: 'web01', dynamicTitle: 'vim README.md' },
expectedField: 'dynamicTitle',
},
] as const;
for (const { name, session, expectedField } of reviewedAllTitleCases) {
test(`all title policy review: ${name}`, () => {
assert.equal(resolveSessionTabTitle(session, 'all'), session[expectedField]);
});
}
test('all title policy compares shell hostnames case-insensitively without rewriting the title', () => {
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@WEB01: ~/app' };
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
});
test('all title policy ignores one FQDN trailing dot only when comparing host identity', () => {
for (const session of [
{ hostLabel: 'Production', promptHostname: 'WEB01.EXAMPLE.TEST', dynamicTitle: 'ubuntu@web01.example.test.: ~/app' },
{ hostLabel: 'Production', promptHostname: 'web01.example.test.', dynamicTitle: 'ubuntu@WEB01.EXAMPLE.TEST: /srv' },
]) {
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
}
});
test('all title policy equates bracketed IPv6 title hosts with the same literal prompt address', () => {
const session = {
hostLabel: 'IPv6 production', promptHostname: '2001:DB8::A', dynamicTitle: 'root@[2001:db8::a]: ~/app',
};
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
});
test('all title policy rejects a clearly different bracketed IPv6 title host', () => {
const session = {
hostLabel: 'IPv6 production', promptHostname: '2001:db8::b', dynamicTitle: 'root@[2001:db8::a]: /srv',
};
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
});
test('all title policy does not treat embedded email or URI text as a shell host report', () => {
for (const dynamicTitle of [
'vim maintainer@old.example.test:notes.txt',
'Issue for maintainer@old.example.test',
'https://maintainer@old.example.test/docs',
'mailto:maintainer@old.example.test',
]) {
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle };
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
}
});
test('reviewed shell and program titles remain disabled in default off and agent modes', () => {
for (const { session } of reviewedAllTitleCases) {
for (const mode of [undefined, 'off', 'agent'] as const) {
assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel);
}
}
});
test('manual names stay authoritative for every reviewed title and mode', () => {
for (const example of reviewedAllTitleCases) {
const session = { ...example.session, customName: 'Operator production tab' };
for (const mode of [undefined, 'off', 'agent', 'all'] as const) {
assert.equal(resolveSessionTabTitle(session, mode), session.customName);
}
}
});
test('active Agent titles retain priority over reviewed prompt identities only in enabled modes', () => {
for (const example of reviewedAllTitleCases) {
const session = { ...example.session, codingCliProviderId: 'claude' as const, dynamicTitle: 'claude: deploy' };
for (const mode of [undefined, 'agent', 'all'] as const) {
assert.equal(resolveSessionTabTitle(session, mode), session.dynamicTitle);
}
assert.equal(resolveSessionTabTitle(session, 'off'), session.hostLabel);
}
});
const reviewedWorkspaceSessions = reviewedAllTitleCases.map(({ session }, index) => ({
...session, id: `review-pane-${index}`, hostId: `review-host-${index}`,
}));
const reviewedWorkspaceLabels = reviewedAllTitleCases.map(({ session, expectedField }) => session[expectedField]);
test('auto workspace titles apply the reviewed all policy to the focused pane', () => {
for (let index = 0; index < reviewedWorkspaceSessions.length; index += 1) {
const session = reviewedWorkspaceSessions[index];
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
assert.equal(
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'),
`${reviewedWorkspaceLabels[index]} +${reviewedWorkspaceSessions.length - 1}`,
);
for (const mode of [undefined, 'off', 'agent'] as const) {
assert.equal(
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode),
`${session.hostLabel} +${reviewedWorkspaceSessions.length - 1}`,
);
}
}
});
test('generated workspace display titles apply the reviewed policy without changing stored names', () => {
const workspace = {
title: reviewedWorkspaceSessions.map(session => session.hostLabel).join('/'),
autoTitle: false, generatedTitle: true, focusedSessionId: reviewedWorkspaceSessions[0].id,
};
const storedTitle = workspace.title;
assert.equal(
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'),
reviewedWorkspaceLabels.join('/'),
);
for (const mode of [undefined, 'off', 'agent'] as const) {
assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), storedTitle);
}
assert.equal(workspace.title, storedTitle);
});
test('all title policy preserves bare emails and suffixes without shell or port evidence', () => {
for (const dynamicTitle of [
'maintainer@old.example.test',
'ubuntu@old.example.test: notes.txt',
'ubuntu@old.example.test:0',
'ubuntu@old.example.test:65536',
'ubuntu@old.example.test:999999',
'ubuntu@old.example.test:22garbage',
]) {
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle };
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
}
});
test('all title policy recognizes legal endpoint port boundaries', () => {
for (const port of [1, 65_535]) {
const session = { hostLabel: 'Jump fleet', promptHostname: 'target', dynamicTitle: `ubuntu@jump:${port}` };
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
}
});
test('all title policy does not infer short names or matching first labels as aliases', () => {
for (const reportedHost of ['web', 'web.dev.example']) {
const session = {
hostLabel: 'Production', promptHostname: 'web.prod.example', dynamicTitle: `root@${reportedHost}: /srv`,
};
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
}
});
test('all title policy preserves titles with invalid bracketed host addresses', () => {
for (const reportedHost of ['not-ip', '2001:db8:::1']) {
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: `root@[${reportedHost}]: ~/app` };
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
}
});
test('explicit workspace names ignore all reviewed live title shapes', () => {
const workspace = { title: 'Operator layout', autoTitle: false, generatedTitle: false };
for (const mode of [undefined, 'off', 'agent', 'all'] as const) {
assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), workspace.title);
}
});
+68 -75
View File
@@ -3,21 +3,28 @@ import type { CodingCliProviderId } from './codingCliProviders';
import { normalizeCodingCliTitle } from './codingCliTitleParse';
import type { DynamicTabTitleMode } from './models/terminal';
/** Configured connection label, independent of live terminal presentation. */
export const getSessionConnectionLabel = (
session: Pick<TerminalSession, 'customName' | 'hostLabel'>,
): string => {
return session.customName || session.hostLabel || '';
const GENERIC_LOOPBACK_HOSTNAMES = new Set([
'localhost',
'localhost.localdomain',
'localhost.local',
'127.0.0.1',
'::1',
]);
export const isGenericLoopbackHostname = (value: string): boolean => {
const trimmed = value.trim();
const normalized = (trimmed.endsWith('.') ? trimmed.slice(0, -1) : trimmed).toLowerCase();
return GENERIC_LOOPBACK_HOSTNAMES.has(normalized);
};
type SessionTabLabelSession = Pick<
TerminalSession,
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId'
>;
const joinWorkspaceLabels = (labels: readonly string[]): string | null => {
const uniqueLabels = [...new Set(labels.map((label) => label.trim()).filter(Boolean))];
return uniqueLabels.length > 0 ? uniqueLabels.join('/') : null;
/** Connection label: user rename, live prompt host, then configured host label. */
export const getSessionConnectionLabel = (
session: Pick<TerminalSession, 'customName' | 'hostLabel' | 'promptHostname'>,
): string => {
const promptHostname = session.promptHostname?.trim();
const effectivePromptHostname =
promptHostname && !isGenericLoopbackHostname(promptHostname) ? promptHostname : '';
return session.customName || effectivePromptHostname || session.hostLabel || '';
};
/**
@@ -41,10 +48,18 @@ export const buildMergedWorkspaceTitle = (
baseLabel: string,
joiningLabel: string,
): string | null => {
return joinWorkspaceLabels([baseLabel, joiningLabel]);
const base = baseLabel.trim();
const joining = joiningLabel.trim();
if (!base && !joining) return null;
if (!base) return joining;
if (!joining || joining === base) return base;
return `${base}/${joining}`;
};
type WorkspaceTabLabelSession = Pick<TerminalSession, 'id' | 'hostId'> & SessionTabLabelSession;
type WorkspaceTabLabelSession = Pick<
TerminalSession,
'id' | 'customName' | 'hostLabel' | 'hostId' | 'promptHostname'
>;
/**
* Recompute a merged workspace's composed title from its *current* member
@@ -59,7 +74,14 @@ type WorkspaceTabLabelSession = Pick<TerminalSession, 'id' | 'hostId'> & Session
export const buildMergedWorkspaceTitleFromSessions = (
sessions: readonly WorkspaceTabLabelSession[],
): string | null => {
return joinWorkspaceLabels(sessions.map(getSessionConnectionLabel));
const labels: string[] = [];
for (const session of sessions) {
const label = getSessionConnectionLabel(session).trim();
if (!label || labels.includes(label)) continue;
labels.push(label);
}
if (labels.length === 0) return null;
return labels.join('/');
};
/**
@@ -70,26 +92,17 @@ export const buildMergedWorkspaceTitleFromSessions = (
* workspace holds sessions for more than one distinct host, the focused host is
* shown with a "+N" suffix for the others.
*
* Presented sessions use the same title policy as individual tabs. Generated
* merge titles are display-only compositions; their persisted identity is built
* separately by buildMergedWorkspaceTitleFromSessions. Host counts always use
* hostId, never a dynamic title or per-pane rename.
* Uses the stable connection label (rename / host label) rather than the
* dynamic shell/agent title: those live titles are published only to the
* session presentation store (not the plain session records passed here), and
* they can differ per-pane on a single host — counting them would both go stale
* and produce a bogus "+N". The host identity is what this tab is about.
*/
export const resolveWorkspaceTabLabel = (
workspace: {
title?: string;
focusedSessionId?: string | null;
autoTitle?: boolean;
generatedTitle?: boolean;
},
workspace: { title?: string; focusedSessionId?: string | null; autoTitle?: boolean },
sessions: readonly WorkspaceTabLabelSession[],
dynamicTabTitleMode: DynamicTabTitleMode = 'agent',
): string => {
const title = workspace.title?.trim();
if (workspace.generatedTitle) {
return joinWorkspaceLabels(sessions.map((session) => resolveSessionTabTitle(session, dynamicTabTitleMode)))
?? DEFAULT_WORKSPACE_TITLE;
}
// Derive a host label only for an auto-titled workspace. The `autoTitle` flag
// is authoritative when present (so a workspace a user explicitly named
// "Workspace" is kept, not overwritten); legacy workspaces without the flag
@@ -102,7 +115,7 @@ export const resolveWorkspaceTabLabel = (
return title || DEFAULT_WORKSPACE_TITLE;
}
const focused = sessions.find((s) => s.id === workspace.focusedSessionId) ?? sessions[0];
const primary = resolveSessionTabTitle(focused, dynamicTabTitleMode);
const primary = getSessionConnectionLabel(focused);
// Count distinct HOSTS by hostId, the only stable host identity: a rename
// rewrites both customName and hostLabel (useSessionState.submitSessionRename),
// so neither is safe to count by — a renamed pane on the same host would add a
@@ -134,58 +147,38 @@ export const resolveCodingCliProviderIconUpdate = ({
return nextProviderId;
};
const shellTitleHostname = (title: string): string | undefined => {
// A title is not a prompt: require an anchored identity plus cwd/port evidence,
// so program titles, email addresses, and URIs do not become host reports.
const match = /^[a-z0-9_.+-]+@(\[[^\]\s]+\]|[a-z0-9][a-z0-9_.-]*):\s*(.*)$/iu.exec(title);
if (!match) return undefined;
const [, hostname, suffix] = match;
const isPath = /^(?:~(?:\/|$)|\/)/u.test(suffix);
const isPort = /^\d{1,5}$/u.test(suffix) && Number(suffix) > 0 && Number(suffix) <= 65_535;
if (!isPath && !isPort) return undefined;
if (hostname.startsWith('[')) {
try {
// Validate IPv6 brackets only; do not use URL canonicalization to infer
// aliases or compressed/expanded address equivalence.
new URL(`http://${hostname}/`);
} catch {
return undefined;
}
}
return hostname;
};
const titleHostnameKey = (hostname: string): string =>
hostname.replace(/^\[(.*)\]$/u, '$1').replace(/\.$/u, '').toLowerCase();
/**
* Resolve the label shown on session tabs and pane headers.
* Live prompt and Shell titles require all mode; agent mode permits Agent titles only.
* Uses the shell-reported title according to the global dynamic title mode.
*/
export const resolveSessionTabTitle = (
session: SessionTabLabelSession,
session: Pick<
TerminalSession,
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId'
>,
dynamicTabTitleMode: DynamicTabTitleMode = 'agent',
): string => {
const connectionLabel = getSessionConnectionLabel(session);
if (session.customName || dynamicTabTitleMode === 'off') {
return connectionLabel;
if (session.customName) {
return session.customName;
}
const rawTitle = session.dynamicTitle?.trim();
const dynamicTitle = rawTitle ? normalizeCodingCliTitle(rawTitle) || rawTitle : undefined;
if (session.codingCliProviderId && dynamicTitle) {
return dynamicTitle;
}
if (dynamicTabTitleMode !== 'all') {
return connectionLabel;
if (dynamicTabTitleMode !== 'off' && session.codingCliProviderId) {
const agentTitle = session.dynamicTitle?.trim();
if (agentTitle) return normalizeCodingCliTitle(agentTitle) || agentTitle;
}
const promptHostname = session.promptHostname?.trim();
if (!dynamicTitle) return promptHostname || connectionLabel;
if (promptHostname) {
const reportedHost = shellTitleHostname(dynamicTitle);
if (reportedHost && titleHostnameKey(reportedHost) !== titleHostnameKey(promptHostname)) {
return promptHostname;
}
if (promptHostname && !isGenericLoopbackHostname(promptHostname)) {
return promptHostname;
}
return dynamicTitle;
if (dynamicTabTitleMode === 'off') {
return connectionLabel;
}
if (dynamicTabTitleMode === 'agent' && !session.codingCliProviderId) {
return connectionLabel;
}
const dynamicTitle = session.dynamicTitle?.trim();
if (!dynamicTitle) {
return connectionLabel;
}
return normalizeCodingCliTitle(dynamicTitle) || dynamicTitle;
};
-17
View File
@@ -339,20 +339,3 @@ test("settings search finds the SFTP default download folder from the real local
}
}
});
test("settings search finds the SFTP tree view folder double-click option from the real 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, ["tree view folder double-click", "double click folder", "expand collapse"]],
] as const) {
for (const query of queries) {
const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === "sftp-tree-folder-double-click");
assert.ok(hit, `${query} should find sftp-tree-folder-double-click`);
assert.equal(hit.entry.tab, "file-associations");
}
}
});
-20
View File
@@ -990,26 +990,6 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "settings.sftp.defaultViewMode",
descriptionKey: "settings.sftp.defaultViewMode.desc",
},
{
id: "sftp-tree-folder-double-click",
tab: "file-associations",
labelKey: "settings.sftp.treeFolderDoubleClick",
descriptionKey: "settings.sftp.treeFolderDoubleClick.desc",
keywords: [
"tree view",
"double click folder",
"expand collapse",
"enter directory",
"树形视图",
"双击文件夹",
"原地展开",
"进入目录",
"樹形檢視",
"雙擊資料夾",
"原地展開",
"進入目錄",
],
},
{
id: "sftp-show-hidden-files",
tab: "file-associations",
-26
View File
@@ -1,26 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
parseSftpTreeFolderDoubleClickBehavior,
} from "./sftpTreeFolderDoubleClick.ts";
test("tree folder double-click defaults to navigate and validates allowed values", () => {
assert.equal(DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR, "navigate");
assert.equal(isSftpTreeFolderDoubleClickBehavior("navigate"), true);
assert.equal(isSftpTreeFolderDoubleClickBehavior("expand"), true);
assert.equal(isSftpTreeFolderDoubleClickBehavior("open"), false);
assert.equal(isSftpTreeFolderDoubleClickBehavior(""), false);
assert.equal(isSftpTreeFolderDoubleClickBehavior(null), false);
assert.equal(isSftpTreeFolderDoubleClickBehavior(undefined), false);
});
test("parseSftpTreeFolderDoubleClickBehavior falls back to default for invalid inputs", () => {
assert.equal(parseSftpTreeFolderDoubleClickBehavior("navigate"), "navigate");
assert.equal(parseSftpTreeFolderDoubleClickBehavior("expand"), "expand");
assert.equal(parseSftpTreeFolderDoubleClickBehavior("invalid"), "navigate");
assert.equal(parseSftpTreeFolderDoubleClickBehavior(null), "navigate");
assert.equal(parseSftpTreeFolderDoubleClickBehavior(undefined), "navigate");
});
-21
View File
@@ -1,21 +0,0 @@
export const SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIORS = ["navigate", "expand"] as const;
export type SftpTreeFolderDoubleClickBehavior =
(typeof SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIORS)[number];
export const DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR: SftpTreeFolderDoubleClickBehavior =
"navigate";
export function isSftpTreeFolderDoubleClickBehavior(
value: unknown,
): value is SftpTreeFolderDoubleClickBehavior {
return value === "navigate" || value === "expand";
}
export function parseSftpTreeFolderDoubleClickBehavior(
value: unknown,
): SftpTreeFolderDoubleClickBehavior {
return isSftpTreeFolderDoubleClickBehavior(value)
? value
: DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR;
}
-1
View File
@@ -350,7 +350,6 @@ export interface SyncPayload {
sftpAutoOpenSidebar?: boolean;
sftpFollowTerminalCwd?: boolean;
sftpDefaultViewMode?: 'list' | 'tree';
sftpTreeDoubleClickBehavior?: 'navigate' | 'expand';
sftpGlobalBookmarks?: import('./models').SftpBookmark[];
// Vault: show recently connected hosts
showRecentHosts?: boolean;
-22
View File
@@ -1,7 +1,6 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { Host, ManagedSource, ProxyProfile } from './models';
import { applyGroupDefaults, resolveGroupDefaults } from './groupConfig';
import { deleteGroup, upsertGroup } from './vaultGroupAgentOps';
const hosts: Host[] = [
@@ -26,27 +25,6 @@ describe('vaultGroupAgentOps', () => {
assert.equal(result.config?.username, 'deploy');
});
it('clearing a child group proxy lets the parent group proxy apply, like Group Details', () => {
const result = upsertGroup({
groups: ['prod', 'prod/web'],
configs: [
{ path: 'prod', proxyConfig: { type: 'http', host: 'parent-gw.test', port: 3128 } },
{ path: 'prod/web', proxyProfileId: 'proxy-1' },
],
hosts,
managedSources: [],
}, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles);
assert.equal(result.ok, true);
if (!result.ok) return;
assert.equal(result.config?.proxyProfileId, undefined);
assert.equal(result.config?.proxyConfig, undefined);
const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: '' };
const effective = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', result.state.configs, proxyOptions), proxyOptions,
);
assert.equal(effective.proxyConfig?.host, 'parent-gw.test');
});
it('rejects missing identities, proxy profiles, and jump hosts', () => {
const state = { groups: ['prod'], configs: [], hosts, managedSources: [] };
assert.equal(upsertGroup(state, 'prod', '{"identityId":"missing"}', [], proxyProfiles).ok, false);
+1 -3
View File
@@ -149,9 +149,7 @@ export function patchGroupConfig(
if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) {
return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` };
}
// Like Group Details: an empty value removes the group proxy so a parent
// group proxy (or the global default) applies, instead of blocking it.
next.proxyProfileId = proxyProfileId || undefined;
next.proxyProfileId = proxyProfileId;
next.proxyConfig = undefined;
}
if (Object.hasOwn(defaults, 'jumpHostIds')) {
+1 -44
View File
@@ -643,7 +643,7 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', ()
assert.equal(cleared.ok, true);
if (!cleared.ok) return;
assert.deepEqual(cleared.updatedHost.hostChain, { hostIds: [] });
assert.equal(cleared.updatedHost.proxyProfileId, undefined);
assert.equal(cleared.updatedHost.proxyProfileId, '');
assert.equal(cleared.updatedHost.startupCommand, '');
assert.equal(cleared.updatedHost.startupCommandRunMode, undefined);
assert.deepEqual(cleared.updatedHost.environmentVariables, []);
@@ -652,49 +652,6 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', ()
assert.equal(cleared.updatedHost.etEnabled, false);
});
const proxyUpdateProfile: ProxyProfile = {
id: 'proxy-1', label: 'proxy', config: { type: 'socks5', host: '127.0.0.1', port: 1080 }, createdAt: 1,
};
const proxyUpdateHost = (overrides: Partial<Host> = {}): Host => ({
id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux',
...overrides,
});
const updateProxy = (host: Host, patch: VaultHostUpdatePatch) => applyVaultHostUpdate(
[host], [], host.id, patch, { proxyProfiles: [proxyUpdateProfile] },
);
const proxyOptions = { validProxyProfileIds: new Set([proxyUpdateProfile.id]), globalProxyProfileId: '' };
test('applyVaultHostUpdate selecting a proxy profile replaces an explicit direct choice', () => {
const result = updateProxy(
proxyUpdateHost({ directProxy: true }),
{ proxyProfileId: proxyUpdateProfile.id },
);
assert.equal(result.ok, true);
if (!result.ok) return;
assert.equal(result.updatedHost.proxyProfileId, proxyUpdateProfile.id);
assert.equal(result.updatedHost.directProxy, undefined);
assert.equal(result.updatedHost.proxyConfig, undefined);
assert.equal(applyGroupDefaults(result.updatedHost, {}, proxyOptions).proxyProfileId, proxyUpdateProfile.id);
});
test('applyVaultHostUpdate clearing the proxy removes every host proxy setting so group proxies apply', () => {
const groupProxyConfig = { type: 'http' as const, host: 'group-proxy.example.com', port: 3128 };
for (const current of [
proxyUpdateHost({ proxyProfileId: proxyUpdateProfile.id }),
proxyUpdateHost({ proxyConfig: { type: 'http', host: 'host-proxy.example.com', port: 8080 } }),
proxyUpdateHost({ directProxy: true }),
]) {
const result = updateProxy(current, { proxyProfileId: '' });
assert.equal(result.ok, true, JSON.stringify(current));
if (!result.ok) continue;
assert.equal(result.updatedHost.proxyProfileId, undefined);
assert.equal(result.updatedHost.proxyConfig, undefined);
assert.equal(result.updatedHost.directProxy, undefined);
const effective = applyGroupDefaults(result.updatedHost, { proxyConfig: groupProxyConfig }, proxyOptions);
assert.deepEqual(effective.proxyConfig, groupProxyConfig);
}
});
test('applyVaultHostUpdate rejects malformed advanced connection settings', () => {
const host: Host = {
id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux',
+1 -5
View File
@@ -514,12 +514,8 @@ export function applyVaultHostUpdate(
if (nextProxyProfileId && !options.proxyProfiles?.some((profile) => profile.id === nextProxyProfileId)) {
return { ok: false, error: `Proxy profile "${nextProxyProfileId}" was not found.` };
}
// Mirror the Host Details proxy panel: a selected profile replaces any
// one-off proxy and the explicit direct choice; an empty value removes
// every host proxy setting so the group and global default apply again.
updated.proxyProfileId = nextProxyProfileId || undefined;
updated.proxyProfileId = nextProxyProfileId;
updated.proxyConfig = undefined;
updated.directProxy = undefined;
}
if (startupCommand.provided) {
if (typeof startupCommand.value !== 'string') return { ok: false, error: 'startupCommand must be a string.' };
+1 -2
View File
@@ -13,11 +13,10 @@ function drivePath(value) {
}
function readWindowsProcessTree(pid, callback, {
loadNative = () => require('@vscode/windows-process-tree'), execFileFn = execFile, readFallback,
loadNative = () => require('@vscode/windows-process-tree'), execFileFn = execFile,
} = {}) {
if (!Number.isSafeInteger(pid) || pid <= 0) return callback(null);
const fallback = () => {
if (readFallback) return readFallback(pid, callback);
const powershell = path.win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe');
const command = `$ErrorActionPreference = 'Stop'; `
@@ -1,101 +0,0 @@
const fs = require('node:fs');
const path = require('node:path');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const { isDiscoveredGitBash } = require('../../lib/localShell.cjs');
const { readWindowsProcessTree } = require('./cmdDirectoryIntegration.cjs');
const run = promisify(execFile);
const probeOptions = { encoding: 'utf8', windowsHide: true, timeout: 2000, maxBuffer: 128 * 1024 };
const unavailable = { success: false, error: 'Git Bash directory integration is not ready' };
// Git for Windows starts a launcher followed by its MSYS bash process.
function idleBashPid(tree, rootPid) {
if (tree?.pid !== rootPid || tree.name?.toLowerCase() !== 'bash.exe' || tree.children?.length !== 1) return null;
const [bash] = tree.children;
return bash.name?.toLowerCase() === 'bash.exe' && bash.children?.length === 0 ? bash.pid : null;
}
function readGitBashTreeFallback(pid, callback) {
const powershell = path.win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe');
const script = `$ErrorActionPreference = 'Stop'; `
+ `$processes = @(Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,Name); `
+ `$root = @($processes | Where-Object { $_.ProcessId -eq ${pid} -and $_.Name -eq 'bash.exe' }); `
+ `$children = @($processes | Where-Object { $_.ParentProcessId -eq ${pid} }); `
+ `if ($root.Count -eq 1 -and $children.Count -eq 1 -and $children[0].Name -eq 'bash.exe') { `
+ `$child = $children[0].ProcessId; if (-not ($processes | Where-Object { $_.ParentProcessId -eq $child })) { [Console]::WriteLine($child) } }`;
execFile(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
{ ...probeOptions, timeout: 3000 }, (error, stdout) => {
const child = error ? 0 : Number(stdout.trim());
callback(Number.isSafeInteger(child) && child > 0
? { pid, name: 'bash.exe', children: [{ pid: child, name: 'bash.exe', children: [] }] } : null);
});
}
function getShellTree(pid) {
return new Promise(resolve => {
const timer = setTimeout(() => resolve(null), 3200);
readWindowsProcessTree(pid, tree => { clearTimeout(timer); resolve(tree); }, { readFallback: readGitBashTreeFallback });
});
}
function findMsysPid(stdout, windowsPid) {
const rows = stdout.split(/\r?\n/).map(line => line.trim().split(/\s+/))
.filter(fields => fields.length >= 8 && /^[1-9]\d*$/.test(fields[0]));
const matches = rows.filter(fields => fields[3] === String(windowsPid) && fields[7] === '/usr/bin/bash');
if (matches.length !== 1) return null;
const [pid] = matches[0];
// MSYS maintains its own parentage across fork and exec.
return rows.some(fields => fields[1] === pid) ? null : pid;
}
async function probeDirectory(rootPid, bin, env, getTree) {
const options = { ...probeOptions, env };
const [tree, processes] = await Promise.all([
getTree(rootPid), run(path.win32.join(bin, 'ps.exe'), ['-e', '-l'], options),
]);
const windowsPid = idleBashPid(tree, rootPid);
const msysPid = windowsPid ? findMsysPid(processes.stdout, windowsPid) : null;
if (!msysPid) return null;
const { stdout: link } = await run(path.win32.join(bin, 'readlink.exe'), [`/proc/${msysPid}/cwd`], options);
const posixCwd = link.replace(/\r?\n$/, '');
if (!posixCwd.startsWith('/') || /[\x00-\x1f\x7f]/.test(posixCwd)
|| /^\/(?:dev|proc)(?:\/|$)/.test(posixCwd)) return null;
const { stdout } = await run(path.win32.join(bin, 'cygpath.exe'), ['-w', '--', posixCwd], options);
const cwd = stdout.replace(/\r?\n$/, '');
if (!/^[a-z]:\\/i.test(cwd) || /[\x00-\x1f\x7f<>"|?*]/.test(cwd) || cwd.length > 8192) return null;
return (await fs.promises.stat(cwd)).isDirectory() ? cwd : null;
}
function createGitBashDirectoryReader(probe) {
let pid;
let revision = 0;
let pending;
return {
setProcessId(value) { pid = value; pending = undefined; },
invalidate() { pending = undefined; },
read() {
if (!Number.isSafeInteger(pid) || pid <= 0) return Promise.resolve(unavailable);
if (pending) return pending;
const processId = pid;
const query = Promise.resolve().then(() => probe(processId)).then(cwd => {
if (!cwd || pending !== query) return unavailable;
return { success: true, cwd, directoryState: { cwd, home: null, provider: 'FileSystem',
revision: ++revision, shellKind: 'git-bash', pathFlavor: 'win32' } };
}).catch(() => unavailable).finally(() => { if (pending === query) pending = undefined; });
pending = query;
return query;
},
};
}
function prepareGitBashDirectoryIntegration(shell, args, env, discoveredCommand) {
if (process.platform !== 'win32' || !isDiscoveredGitBash(shell, discoveredCommand)
|| !args.every(arg => ['--login', '-l', '-i', '--noprofile', '--norc'].includes(arg))) return null;
const bin = path.win32.resolve(path.win32.dirname(shell), '..', 'usr', 'bin');
if (!['ps.exe', 'readlink.exe', 'cygpath.exe'].every(tool => fs.existsSync(path.win32.join(bin, tool)))) return null;
return { reader: createGitBashDirectoryReader(pid => probeDirectory(pid, bin, env, getShellTree)) };
}
module.exports = { createGitBashDirectoryReader, findMsysPid, idleBashPid, prepareGitBashDirectoryIntegration };
@@ -1,36 +0,0 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { createGitBashDirectoryReader, findMsysPid, idleBashPid } = require('./gitBashDirectoryIntegration.cjs');
const shell = (pid, children = [], name = 'bash.exe') => ({ pid, name, children });
test('a Git Bash probe follows just the launcher and original idle Bash', () => {
assert.equal(idleBashPid(shell(12, [shell(34)]), 12), 34);
assert.equal(idleBashPid(shell(12, [shell(34, [shell(56)])]), 12), null);
assert.equal(idleBashPid(shell(12, [shell(34, [], 'cmd.exe')]), 12), null);
assert.equal(idleBashPid(shell(12, [shell(34)]), 56), null);
const processes = 'PID PPID PGID WINPID TTY UID STIME COMMAND\n 812 1 812 34 cons0 197608 09:24:10 /usr/bin/bash\n';
assert.equal(findMsysPid(processes, 34), '812');
assert.equal(findMsysPid(processes + ' 999 812 999 54 cons0 197608 09:24:11 /usr/bin/bash\n', 34), null);
assert.equal(findMsysPid(processes, 12), null);
assert.equal(findMsysPid(processes.repeat(2), 34), null);
});
test('a pending probe is shared and a pre-write result cannot confirm navigation', async () => {
const probes = [];
const reader = createGitBashDirectoryReader(pid => new Promise(resolve => probes.push({ pid, resolve })));
reader.setProcessId(12);
const before = reader.read();
assert.equal(reader.read(), before);
await Promise.resolve();
reader.invalidate();
const after = reader.read();
await Promise.resolve();
assert.deepEqual(probes.map(probe => probe.pid), [12, 12]);
probes[1].resolve('C:\\new');
probes[0].resolve('C:\\old');
assert.equal((await before).success, false);
assert.deepEqual((await after).directoryState, {
cwd: 'C:\\new', home: null, provider: 'FileSystem', revision: 1, shellKind: 'git-bash', pathFlavor: 'win32',
});
});
-79
View File
@@ -1969,37 +1969,6 @@ function checkWorkerExecSafety(sessionId, command, chatSessionId) {
* the worker to run every other deterministic check (transport, shell kind, shell-aware
* blocklist, unsupported local shell, busy background job) without sending anything.
*/
/**
* No-send check that handleWorkerJobStart would accept this command, for
* terminal_start_bulk. Same main-side safety check as a real worker start, then the
* worker's job-start precheck (busy, local shell, network/serial, writable PTY,
* shell-aware blocklist) without creating a job.
*/
async function preflightWorkerJobStart(params = {}, { probe = true } = {}) {
const { sessionId, command, chatSessionId } = params;
if (!terminalWorkerManager?.request) return { ok: false, error: "Session not found" };
const blocked = checkWorkerExecSafety(sessionId, command, chatSessionId || null);
if (blocked) return { ok: false, error: blocked };
try {
const result = await terminalWorkerManager.request("netcatty:ai:jobStart", {
sessionId,
command,
chatSessionId: chatSessionId || null,
commandTimeoutMs,
sessionMeta: getSessionMeta(sessionId, chatSessionId || null) || {},
commandBlocklist,
precheck: true,
// Before approval the worker must not open any channel to the host.
...(probe ? {} : { probe: false }),
}, {});
return result && result.ok === false
? { ok: false, error: result.error || "Session does not support background execution" }
: { ok: true };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
}
}
async function preflightWorkerExec(params = {}, { probe = true } = {}) {
const { sessionId, command, chatSessionId } = params;
if (!terminalWorkerManager?.request) return { ok: false, error: "Session not found" };
@@ -2388,13 +2357,6 @@ function getBuiltinRpcHandlerRegistry() {
"terminal.start": handleJobStart,
"terminal.poll": handleJobPoll,
"terminal.stop": handleJobStop,
// terminal_start_bulk is intercepted in dispatchCore like terminal_execute_bulk.
"terminal.startBulk": () => ({
ok: false,
error: "terminal_start_bulk must be dispatched through the bulk job starter.",
}),
"terminal.pollBulk": (params) => jobBulkHandler.poll(params),
"terminal.stopBulk": (params) => jobBulkHandler.stop(params),
});
}
return builtinRpcHandlerRegistry;
@@ -2449,12 +2411,6 @@ async function dispatchCore(method, params, approvalContext = {}) {
return execBulkHandler.run(params, approvalContext, permission);
}
if (capability?.id === "terminal.startBulk" || capability?.id === "terminal.pollBulk" || capability?.id === "terminal.stopBulk") {
// Plugin-delegated agents never get fan-out execution.
if (delegated) return { ok: false, error: `${capability.surfaces?.builtin?.mcpTool || method} is not available to this client.` };
if (capability.id === "terminal.startBulk") return jobBulkHandler.start(params, approvalContext, permission);
}
// Validate session scope *first* so out-of-scope callers cannot infer the
// existence or activity of foreign sessions through busy-state error
// messages, and so requests fail fast without blocking the write lock.
@@ -2797,7 +2753,6 @@ const execHandlerApi = createExecHandlerApi({
const {
resolveExecContext,
preflightExec,
preflightJobStart,
handleExec,
handleJobStart,
getScopedJob,
@@ -2845,40 +2800,6 @@ const execBulkHandler = createExecBulkHandler({
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog,
});
// terminal_start_bulk / terminal_poll_bulk / terminal_stop_bulk: background jobs on many sessions.
const { createJobBulkHandler } = require("./mcpServerBridge/jobBulk.cjs");
const jobBulkHandler = createJobBulkHandler({
getSessions: () => sessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
isChatSessionCancelled,
preflightMainJobStart: preflightJobStart,
preflightWorkerJobStart,
// Mirrors dispatchCore: sessions not in the main-process map live in the terminal worker.
startJobOnSession: (params, beforeExecute) => (sessions?.get?.(params.sessionId)
? handleJobStart(params, { beforeExecute })
: handleWorkerJobStart(params, beforeExecute)),
pollJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobPoll(params)
: handleJobPoll(params)),
stopJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobStop(params)
: handleJobStop(params)),
requestApproval: requestApprovalFromRenderer,
sessionIdleManager,
getLivePermission: (params) => evaluateRpcPermission({
rpcMethod: "netcatty/jobStartBulk",
surface: CAPABILITY_SURFACES.BUILTIN,
permissionMode,
params,
context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId) },
}),
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
});
const { createConfigAndCleanupApi } = require("./mcpServerBridge/configAndCleanup.cjs");
const configAndCleanupApi = createConfigAndCleanupApi({
get authToken() { return authToken; },
@@ -653,38 +653,3 @@ test("collapseCarriageReturns handles 256KB CR-heavy progress output in linear t
assert.equal(collapsed, `header line\n${frames[frameCount - 1]}\nfinal frame`);
assert.ok(elapsedMs < 500, `expected linear collapseCarriageReturns on 256KB+ payload, took ${elapsedMs}ms`);
});
// ── terminal_start_bulk support: preflightJobStart ──
test("preflightJobStart accepts a shell PTY session without starting a job or typing", async () => {
const pty = new FakePty();
const backgroundJobs = new Map();
const ctx = createExecHandlerTestContext({ sessions: new Map([["pty", { protocol: "ssh", shellKind: "posix", stream: pty }]]), backgroundJobs });
ctx.checkCommandSafetyForShell = checkBlocklistForShell;
ctx.resolveSessionBlocklistShellKind = resolveSessionBlocklistShellKind;
const api = createExecHandlerApi(ctx);
assert.deepEqual(await api.preflightJobStart({ sessionId: "pty", command: "apt-get -y upgrade", chatSessionId: "chat" }), { ok: true });
assert.deepEqual(pty.writes, [], "preflight never types into the terminal");
assert.equal(backgroundJobs.size, 0, "preflight never creates a job");
assert.equal(ctx.activeSessionExecutions.size, 0, "preflight never reserves the session");
});
test("preflightJobStart reports the same refusals handleJobStart would give", async () => {
const sessions = new Map([
["blocked", { protocol: "ssh", shellKind: "posix", stream: new FakePty() }],
["channel-only", { protocol: "ssh", shellKind: "posix", conn: { exec() {} } }],
["serial", { protocol: "serial", stream: { write() {} }, serialPort: { write() {} } }],
["net", { protocol: "ssh", stream: new FakePty() }],
]);
const api = createBulkExecContext(sessions, {
getSessionMeta: (sessionId) => (sessionId === "net" ? { deviceType: "network" } : {}),
});
const call = (sessionId, command = "uptime") => api.preflightJobStart({ sessionId, command, chatSessionId: "chat" });
assert.match((await call("blocked", "rm -rf /")).error, /^Command blocked by safety policy\. Pattern: /);
// terminal_execute can fall back to an exec channel; background jobs cannot.
assert.match((await call("channel-only")).error, /requires a writable PTY-backed terminal session/);
assert.match((await call("serial")).error, /supports shell-backed PTY sessions only/);
assert.match((await call("net")).error, /supports shell-backed PTY sessions only/);
assert.deepEqual(await call("ghost"), { ok: false, error: "Session not found" });
});
@@ -1,229 +0,0 @@
"use strict";
require("./cliDiscoveryTestIsolation.cjs").isolateCliDiscoveryFile();
const assert = require("node:assert/strict");
const test = require("node:test");
const tick = () => new Promise((resolve) => setImmediate(resolve));
function loadFreshBridge() {
const bridgePath = require.resolve("./mcpServerBridge.cjs");
delete require.cache[bridgePath];
return require("./mcpServerBridge.cjs");
}
/**
* Bridge wired to a fake terminal worker that hosts the given sessions and runs
* background jobs for them.
*/
function createBridge({ sessionIds = ["ssh-1", "ssh-2", "ssh-3"], refuse, chat = "chat-1", mode = "auto" } = {}) {
const prechecks = [];
const starts = [];
const polls = [];
const stops = [];
const jobs = new Map();
let nextJob = 0;
const bridge = loadFreshBridge();
bridge.init({
sessions: new Map(),
electronModule: null,
terminalWorkerManager: {
send() {},
request(channel, payload) {
if (channel === "netcatty:ai:jobStart") {
if (payload.precheck === true) {
prechecks.push(payload);
const error = refuse?.(payload.sessionId, payload);
return Promise.resolve(error ? { ok: false, error } : { ok: true });
}
starts.push(payload);
const jobId = `wjob-${payload.sessionId}-${nextJob++}`;
jobs.set(jobId, { sessionId: payload.sessionId, status: "running", output: `started ${payload.command}\n` });
return Promise.resolve({ ok: true, jobId, sessionId: payload.sessionId, status: "running" });
}
if (channel === "netcatty:ai:jobPoll") {
polls.push(payload);
const job = jobs.get(payload.jobId);
if (!job) return Promise.resolve({ ok: false, error: "Background job not found" });
const total = job.output.length;
const from = Math.min(Math.max(0, Number(payload.offset) || 0), total);
return Promise.resolve({
ok: true, jobId: payload.jobId, sessionId: job.sessionId, status: job.status,
completed: job.status !== "running", exitCode: job.exitCode ?? null, error: null,
output: job.output.slice(from), nextOffset: total, totalOutputChars: total, outputBaseOffset: 0,
});
}
if (channel === "netcatty:ai:jobStop") {
stops.push(payload);
const job = jobs.get(payload.jobId);
if (!job) return Promise.resolve({ ok: false, error: "Background job not found" });
job.status = "stopping";
return Promise.resolve({ ok: true, jobId: payload.jobId, sessionId: job.sessionId, status: "stopping", exitCode: null });
}
return Promise.reject(new Error(`unexpected worker request: ${channel}`));
},
},
});
bridge.setPermissionMode(mode);
bridge.setCommandBlocklist([]);
bridge.setCommandTimeout(30);
bridge.updateSessionMetadata(
sessionIds.map((sessionId, index) => ({
sessionId,
hostname: `host${index + 1}.example`,
label: `web${index + 1}`,
protocol: "ssh",
connected: true,
})),
chat,
);
return { bridge, prechecks, starts, polls, stops, jobs, chat };
}
function captureApprovals(bridge) {
const requests = [];
bridge.setMainWindowGetter(() => ({
isDestroyed: () => false,
webContents: {
id: 1,
isDestroyed: () => false,
send(channel, payload) {
if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload);
},
},
}));
return requests;
}
const startParams = (chatSessionId, overrides = {}) => ({
command: "apt-get -y upgrade",
sessionIds: '["ssh-1","ssh-2","ssh-3"]',
chatSessionId,
...overrides,
});
test("netcatty/jobStartBulk prechecks every worker session, then starts one job per session", async () => {
const { bridge, prechecks, starts, chat } = createBridge();
const result = await bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
assert.equal(result.ok, true);
assert.equal(typeof result.bulkId, "string");
assert.deepEqual(result.counts, { running: 3 });
assert.deepEqual(result.jobs.map((job) => [job.sessionId, job.label, job.status]), [
["ssh-1", "web1", "running"], ["ssh-2", "web2", "running"], ["ssh-3", "web3", "running"],
]);
// Auto mode: the full precheck runs before anything starts, and every target passes it first.
assert.equal(prechecks.length, 6, "a precheck before and after the (absent) prompt for each target");
assert.ok(prechecks.every((payload) => payload.probe === undefined));
assert.equal(starts.length, 3);
assert.ok(starts.every((payload) => payload.precheck === undefined), "real starts are not prechecks");
});
test("any refused target starts nothing anywhere", async () => {
const { bridge, starts, chat } = createBridge({
refuse: (sessionId) => (sessionId === "ssh-2" ? "Background execution requires a writable PTY-backed terminal session." : null),
});
const result = await bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
assert.equal(result.ok, false);
assert.match(result.error, /nothing was sent\. 1 of 3 targets/);
assert.match(result.error, /- ssh-2 \(web2\): Background execution requires a writable PTY-backed terminal session\./);
assert.equal(starts.length, 0);
});
test("observer mode refuses a bulk start", async () => {
const { bridge, prechecks, starts, chat } = createBridge({ mode: "observer" });
const result = await bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
assert.equal(result.ok, false);
assert.match(result.error, /observer/);
assert.equal(prechecks.length + starts.length, 0);
});
test("confirm mode asks once with a fresh approval and probes no host before it", async () => {
const { bridge, prechecks, starts, chat } = createBridge({ mode: "confirm" });
const approvals = captureApprovals(bridge);
bridge.setPermissionGrants([
{ id: "g1", capabilityId: "terminal.startBulk", sessionPattern: "*", createdAt: Date.now() },
{ id: "g2", capabilityId: "terminal.start", sessionPattern: "*", createdAt: Date.now() },
]);
const pending = bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
await tick();
assert.equal(approvals.length, 1, "remembered grants never replace the prompt");
assert.equal(approvals[0].toolName, "netcatty/jobStartBulk");
assert.deepEqual(approvals[0].args, {
command: "apt-get -y upgrade",
sessions: ["ssh-1 (web1)", "ssh-2 (web2)", "ssh-3 (web3)"],
});
assert.equal(approvals[0].allowSession, false);
assert.ok(prechecks.every((payload) => payload.probe === false), "no probe before approval");
assert.equal(starts.length, 0);
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
const result = await pending;
assert.equal(result.ok, true);
assert.equal(starts.length, 3);
});
test("a denied bulk start starts nothing and frees the sessions", async () => {
const { bridge, starts, chat } = createBridge({ mode: "confirm" });
const approvals = captureApprovals(bridge);
const pending = bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
await tick();
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, false);
const result = await pending;
assert.equal(result.ok, false);
assert.match(result.error, /denied/i);
assert.equal(starts.length, 0);
bridge.setPermissionMode("auto");
const single = await bridge.dispatchBuiltinRpc("netcatty/jobStart", { sessionId: "ssh-1", command: "sleep 1", chatSessionId: chat });
assert.equal(single.ok, true, "claims were released");
});
test("poll and stop by bulkId reach every worker job, without approval", async () => {
const { bridge, polls, stops, jobs, chat } = createBridge({ mode: "confirm" });
const approvals = captureApprovals(bridge);
const pending = bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
await tick();
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
const started = await pending;
assert.equal(started.ok, true);
const [jobA, jobB] = started.jobs.map((job) => job.jobId);
jobs.get(jobB).status = "completed";
jobs.get(jobB).exitCode = 0;
const polled = await bridge.dispatchBuiltinRpc("netcatty/jobPollBulk", {
bulkId: started.bulkId,
chatSessionId: chat,
offsets: JSON.stringify({ [jobA]: 8 }),
});
assert.equal(polled.ok, true);
assert.equal(polled.allCompleted, false);
assert.deepEqual(polled.counts, { running: 2, completed: 1 });
assert.equal(polled.jobs[0].output, "apt-get -y upgrade\n", "only output after the offset");
assert.equal(polled.jobs[1].exitCode, 0);
assert.ok(polls.length >= 3);
const stopped = await bridge.dispatchBuiltinRpc("netcatty/jobStopBulk", { bulkId: started.bulkId, chatSessionId: chat });
assert.equal(stopped.ok, true);
assert.equal(stops.length, 3);
assert.equal(approvals.length, 1, "poll and stop never ask");
});
test("stop works in observer mode, poll is a read", async () => {
const { bridge, stops, chat } = createBridge();
const started = await bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
bridge.setPermissionMode("observer");
assert.equal((await bridge.dispatchBuiltinRpc("netcatty/jobPollBulk", { bulkId: started.bulkId, chatSessionId: chat })).ok, true);
assert.equal((await bridge.dispatchBuiltinRpc("netcatty/jobStopBulk", { bulkId: started.bulkId, chatSessionId: chat })).ok, true);
assert.equal(stops.length, 3);
});
test("another chat cannot use the bulkId", async () => {
const { bridge, chat } = createBridge();
const started = await bridge.dispatchBuiltinRpc("netcatty/jobStartBulk", startParams(chat));
const foreign = await bridge.dispatchBuiltinRpc("netcatty/jobPollBulk", { bulkId: started.bulkId, chatSessionId: "chat-2" });
assert.equal(foreign.ok, false);
assert.match(foreign.error, /was not found/);
});
@@ -30,9 +30,6 @@ const MCP_BRIDGE_BUILTIN_CAPABILITY_IDS = [
"terminal.start",
"terminal.poll",
"terminal.stop",
"terminal.startBulk",
"terminal.pollBulk",
"terminal.stopBulk",
];
test("buildBuiltinRpcHandlerRegistry maps catalog builtin rpcMethod to handlers", () => {
+24 -60
View File
@@ -37,7 +37,7 @@ function labelPart(sessionId, label) {
* @param {{ command?: unknown, sessionIds?: unknown, tailLines?: unknown }} params
* @returns {{ ok: true, command: string, sessionIds: string[], tailLines: number } | { ok: false, error: string }}
*/
function parseBulkExecParams(params = {}, { singleTool = "terminal_execute" } = {}) {
function parseBulkExecParams(params = {}) {
const command = params?.command;
if (typeof command !== "string" || !command.trim()) {
return { ok: false, error: "Invalid command" };
@@ -56,7 +56,7 @@ function parseBulkExecParams(params = {}, { singleTool = "terminal_execute" } =
return { ok: false, error: shapeError };
}
if (rawIds.length < MIN_BULK_TARGETS) {
return { ok: false, error: `${shapeError}. Use ${singleTool} to run a command on a single session` };
return { ok: false, error: `${shapeError}. Use terminal_execute to run a command on a single session` };
}
if (rawIds.length > MAX_BULK_TARGETS) {
return { ok: false, error: shapeError };
@@ -202,18 +202,6 @@ function tailText(text, tailLines, maxChars) {
return { text: kept, omittedLines, truncated };
}
/**
* Split one group's character budget between stdout and stderr. stderr keeps up to a
* quarter when it needs it; whatever one stream does not use goes to the other (on
* interactive terminals stderr is part of stdout, so stdout usually gets it all).
* @returns {{ stdoutChars: number, stderrChars: number }}
*/
function splitGroupBudget(stdoutLength, stderrLength, total) {
let stderrChars = Math.min(stderrLength, Math.floor(total * 0.25));
if (stdoutLength < total - stderrChars) stderrChars = Math.min(stderrLength, total - stdoutLength);
return { stdoutChars: total - stderrChars, stderrChars };
}
/**
* Group identical per-host results (compared on the full raw output, before
* truncation) and build the public payload.
@@ -252,15 +240,10 @@ function groupBulkResults(entries, options = {}) {
const groups = [];
for (const { normalized, hosts } of groupsByKey.values()) {
// One budget per group, shared by both streams, so the response stays under the cap.
// Apply tailLines first, so only text that can still be shown competes for the budget.
const outLines = tailText(normalized.stdout, tailLines, Infinity);
const errLines = tailText(normalized.stderr, tailLines, Infinity);
const { stdoutChars, stderrChars } = splitGroupBudget(outLines.text.length, errLines.text.length, perGroupChars);
const outCut = tailText(outLines.text, Infinity, stdoutChars);
const errCut = tailText(errLines.text, Infinity, stderrChars);
const out = { text: outCut.text, truncated: outLines.truncated || outCut.truncated };
const err = { text: errCut.text, truncated: errLines.truncated || errCut.truncated };
const omittedLines = outLines.omittedLines + outCut.omittedLines + errLines.omittedLines + errCut.omittedLines;
const stdoutChars = Math.floor(perGroupChars * 0.75);
const out = tailText(normalized.stdout, tailLines, stdoutChars);
const err = tailText(normalized.stderr, tailLines, perGroupChars - stdoutChars);
const omittedLines = out.omittedLines + err.omittedLines;
const group = {
hosts,
status: normalized.status,
@@ -285,11 +268,9 @@ function groupBulkResults(entries, options = {}) {
}
/**
* Local, side-effect-free target checks shared by the bulk tools, in the same order
* as a single command: scope, closing, busy, pending claim, existence, connected.
* @param {object} deps the same deps the bulk handlers receive
* @param {object} deps injected by mcpServerBridge (keeps this module testable)
*/
function createBulkTargetGuards(deps) {
function createExecBulkHandler(deps) {
const {
getSessions,
getSessionMeta,
@@ -297,6 +278,22 @@ function createBulkTargetGuards(deps) {
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
getActiveChatExecution,
beginChatExecution,
isChatSessionCancelled,
preflightMainExec,
preflightWorkerExec,
execOnSession,
requestApproval,
sessionIdleManager,
getCommandTimeoutMs,
getLivePermission,
cancelExecsForChat,
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog = () => {},
setTimeoutFn = setTimeout,
clearTimeoutFn = clearTimeout,
} = deps;
function resolveLabel(sessionId, chatSessionId) {
@@ -327,36 +324,6 @@ function createBulkTargetGuards(deps) {
return null;
}
return { resolveLabel, checkTargetSync };
}
/**
* @param {object} deps injected by mcpServerBridge (keeps this module testable)
*/
function createExecBulkHandler(deps) {
const {
getSessions,
pendingSessionWriteApprovals,
getActiveChatExecution,
beginChatExecution,
isChatSessionCancelled,
preflightMainExec,
preflightWorkerExec,
execOnSession,
requestApproval,
sessionIdleManager,
getCommandTimeoutMs,
getLivePermission,
cancelExecsForChat,
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog = () => {},
setTimeoutFn = setTimeout,
clearTimeoutFn = clearTimeout,
} = deps;
const { resolveLabel, checkTargetSync } = createBulkTargetGuards(deps);
/**
* Transport + command-safety checks. With probe:false nothing may touch the remote host
* (used before the approval prompt); with probe:true the shell kind may be probed over an
@@ -605,12 +572,9 @@ module.exports = {
MAX_TAIL_LINES,
MIN_BULK_TARGETS,
classifyHostResult,
createBulkTargetGuards,
createExecBulkHandler,
formatPreflightFailure,
groupBulkResults,
labelPart,
parseBulkExecParams,
splitGroupBudget,
tailText,
};
@@ -14,7 +14,6 @@ const {
formatPreflightFailure,
groupBulkResults,
parseBulkExecParams,
splitGroupBudget,
tailText,
} = require("./execBulk.cjs");
@@ -785,55 +784,3 @@ test("explicit no-send codes thrown by the exec layer, and closed streams, are c
assert.equal(classifyHostResult({ ok: false, thrown: true, error: "boom" }).status, "error");
assert.equal(classifyHostResult({ ok: false, thrown: true, code: "SHELL_PROMPT_PENDING", error: "x" }).status, "not_sent");
});
// ── stdout/stderr budget ──
test("splitGroupBudget gives a stream's unused share to the other", () => {
// No stderr (interactive terminals): stdout gets the whole budget.
assert.deepEqual(splitGroupBudget(30_000, 0, 32_000), { stdoutChars: 32_000, stderrChars: 0 });
// Small stderr keeps what it needs; stdout gets the rest.
assert.deepEqual(splitGroupBudget(30_000, 1_000, 32_000), { stdoutChars: 31_000, stderrChars: 1_000 });
// Small stdout leaves room for a large stderr.
assert.deepEqual(splitGroupBudget(1_000, 30_000, 32_000), { stdoutChars: 2_000, stderrChars: 30_000 });
// Both large: stderr keeps a quarter, as before.
assert.deepEqual(splitGroupBudget(50_000, 50_000, 32_000), { stdoutChars: 24_000, stderrChars: 8_000 });
for (const [out, err] of [[0, 0], [5, 5], [40_000, 3], [3, 40_000], [20_000, 20_000]]) {
const { stdoutChars, stderrChars } = splitGroupBudget(out, err, 32_000);
assert.ok(stdoutChars + stderrChars <= 32_000, `${out}/${err}`);
}
});
test("groupBulkResults keeps stdout beyond three quarters when stderr is empty", () => {
// One line per 100 chars, under the tailLines limit so only the character cap applies.
const line = `${"o".repeat(99)}\n`;
const stdout = line.repeat(300); // 30,000 chars, 300 lines
const payload = groupBulkResults([
{ sessionId: "a", label: "web1", result: { ok: true, stdout, stderr: "", exitCode: 0 } },
], { tailLines: 2000 });
assert.equal(payload.groups[0].stdout, stdout, "all 30,000 chars fit in the 32 KB group budget");
assert.equal(payload.groups[0].outputTruncated, undefined);
});
test("groupBulkResults applies tailLines before sharing the budget", () => {
const stdout = Array.from({ length: 500 }, (_, i) => `out-${i}`).join("\n");
const stderr = `${"e".repeat(99)}\n`.repeat(200); // 20,000 chars of stderr
const payload = groupBulkResults([
{ sessionId: "a", label: "web1", result: { ok: true, stdout, stderr, exitCode: 1 } },
], { tailLines: 10 });
const group = payload.groups[0];
// stdout is cut to 10 short lines, so stderr may use the space stdout does not need.
assert.equal(group.stdout.split("\n").length, 10);
assert.equal(group.stderr.split("\n").filter(Boolean).length, 10, "stderr also keeps its last 10 lines");
assert.equal(group.outputTruncated, true);
assert.equal(group.omittedLines, 490 + 190);
});
test("groupBulkResults never exceeds the per-group budget", () => {
const big = "x".repeat(100_000);
const payload = groupBulkResults([
{ sessionId: "a", label: "", result: { ok: true, stdout: big, stderr: big, exitCode: 0 } },
], { tailLines: 2000 });
const group = payload.groups[0];
assert.ok(group.stdout.length + (group.stderr || "").length <= 32 * 1024);
assert.equal(group.outputTruncated, true);
});
@@ -236,40 +236,35 @@ function createExecHandlerApi(ctx) {
* Mirrors handleExec's transport order; used by terminal_execute_bulk to
* validate every target before any command is sent.
*/
/**
* Shell-aware command safety for a preflight. With probe:false nothing may touch
* the remote host yet (no approval has been given): use the shell kind only if it
* is already known, otherwise the shell-independent patterns. The authoritative
* check re-runs after approval, and again when the command is sent.
*/
async function checkPreflightShellCommand({ session, sessionId, command, chatSessionId }, probe) {
let safety;
if (probe) {
const probed = await ensureSessionShellKindForExec(session, {
trackForCancellation: activePtyExecs,
chatSessionId,
});
if (!probed.ok) return probed;
safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
} else {
const knownKind = resolveSessionBlocklistShellKind(session);
safety = knownKind
? checkCommandSafetyForShell(command, knownKind)
: checkCommandSafetyCommonOnly(command);
}
if (safety.blocked) {
debugLog("preflight:blocklisted", { sessionId, matchedPattern: safety.matchedPattern });
return { ok: false, error: `Command blocked by safety policy. Pattern: ${safety.matchedPattern}` };
}
return { ok: true };
}
async function preflightExec(params, { probe = true } = {}) {
const resolved = resolveExecContext(params);
if (!resolved.ok) return resolved;
const { session, isNetworkDevice, sshClient, ptyStream } = resolved.context;
const { session, sessionId, command, chatSessionId, isNetworkDevice, sshClient, ptyStream } = resolved.context;
const hasWritablePty = Boolean(ptyStream && typeof ptyStream.write === "function");
const checkShellCommand = () => checkPreflightShellCommand(resolved.context, probe);
const checkShellCommand = async () => {
let safety;
if (probe) {
const probed = await ensureSessionShellKindForExec(session, {
trackForCancellation: activePtyExecs,
chatSessionId,
});
if (!probed.ok) return probed;
safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
} else {
// Nothing may touch the remote host yet (no approval has been given): use the
// shell kind only if it is already known, otherwise the shell-independent
// patterns. The authoritative check re-runs after approval, and again at exec.
const knownKind = resolveSessionBlocklistShellKind(session);
safety = knownKind
? checkCommandSafetyForShell(command, knownKind)
: checkCommandSafetyCommonOnly(command);
}
if (safety.blocked) {
debugLog("preflightExec:blocklisted", { sessionId, matchedPattern: safety.matchedPattern });
return { ok: false, error: `Command blocked by safety policy. Pattern: ${safety.matchedPattern}` };
}
return { ok: true };
};
if (isNetworkDevice && hasWritablePty) return { ok: true };
if (hasWritablePty) return checkShellCommand();
@@ -288,25 +283,6 @@ function createExecHandlerApi(ctx) {
return { ok: false, error: "Session does not support command execution" };
}
/**
* Side-effect-free (apart from the cached shell-kind probe handleJobStart also
* runs) check that handleJobStart would accept this command on this session.
* Mirrors handleJobStart's refusals; used by terminal_start_bulk to validate
* every target before any job is started.
*/
async function preflightJobStart(params, { probe = true } = {}) {
const resolved = resolveExecContext(params);
if (!resolved.ok) return resolved;
const { isNetworkDevice, sessionProtocol, ptyStream } = resolved.context;
if (isNetworkDevice || sessionProtocol === "serial") {
return { ok: false, error: "Background execution currently supports shell-backed PTY sessions only." };
}
if (!ptyStream || typeof ptyStream.write !== "function") {
return { ok: false, error: "Background execution requires a writable PTY-backed terminal session." };
}
return checkPreflightShellCommand(resolved.context, probe);
}
function handleJobStart(params, executionContext = {}) {
const resolved = resolveExecContext(params);
if (!resolved.ok) return resolved;
@@ -587,7 +563,6 @@ function createExecHandlerApi(ctx) {
return {
resolveExecContext,
preflightExec,
preflightJobStart,
handleExec,
handleJobStart,
getScopedJob,
@@ -1,514 +0,0 @@
"use strict";
/**
* terminal_start_bulk / terminal_poll_bulk / terminal_stop_bulk: background jobs
* on 2-20 terminal sessions.
*
* Contract (see docs/features/terminal-bulk-jobs.md):
* - start: all-or-nothing preflight (same rules as terminal_start), one fresh
* approval for the whole fan-out, then one background job per session. A
* `bulkId` names the set so poll/stop need one id instead of many.
* - poll: the existing per-job poll for each job, capped per job and in total.
* The total is shared by need, so quiet jobs leave room for busy ones. When a
* job has more new output than its share, the newest output is returned and
* `skippedChars` says how much was jumped over.
* - stop: the existing per-job stop for each job (no approval, like terminal_stop).
* Per-job problems (expired, out of scope, not found) never fail poll or stop.
*/
const {
MAX_BULK_TARGETS,
createBulkTargetGuards,
formatPreflightFailure,
labelPart,
parseBulkExecParams,
} = require("./execBulk.cjs");
const BULK_START_RPC_METHOD = "netcatty/jobStartBulk";
// Polls repeat, so keep them small: enough tail to see progress or an error.
// terminal_poll on one job returns its full kept output.
const MAX_POLL_CHARS_PER_JOB = 4 * 1024;
const MAX_POLL_TOTAL_CHARS = 32 * 1024;
const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
/** A job runs at most 1 hour and is kept 10 minutes after it ends; keep the handle a bit longer. */
const BULK_ENTRY_MAX_AGE_MS = (60 + 10 + 5) * 60 * 1000;
const MAX_BULK_ENTRIES = 100;
/** Poll offset past any real output: returns no output, only nextOffset. */
const PEEK_OFFSET = Number.MAX_SAFE_INTEGER;
const CLAIM_CONFLICT_ERROR = "Session already has another command request awaiting approval or startup. Wait for it to finish before starting a new command.";
function parseJsonValue(raw) {
if (typeof raw !== "string") return raw;
try {
return JSON.parse(raw);
} catch {
return undefined;
}
}
/**
* Resolve the jobs a poll/stop call targets: a bulkId from terminal_start_bulk, or an
* explicit list of 1-20 jobIds.
* @returns {{ ok: true, bulkId: string | null, jobIds: string[] } | { ok: false, error: string }}
*/
function parseJobTargets(params = {}) {
const bulkId = typeof params?.bulkId === "string" ? params.bulkId.trim() : "";
const hasJobIds = params?.jobIds !== undefined && params?.jobIds !== null && params?.jobIds !== "";
if (bulkId && hasJobIds) return { ok: false, error: "Pass either bulkId or jobIds, not both" };
if (bulkId) return { ok: true, bulkId, jobIds: [] };
if (!hasJobIds) return { ok: false, error: "bulkId or jobIds is required" };
const shapeError = `jobIds must be a JSON array of 1-${MAX_BULK_TARGETS} job ID strings`;
const raw = parseJsonValue(params.jobIds);
if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_BULK_TARGETS
|| raw.some((id) => typeof id !== "string" || !id.trim())) {
return { ok: false, error: shapeError };
}
return { ok: true, bulkId: null, jobIds: [...new Set(raw.map((id) => id.trim()))] };
}
/**
* @returns {{ ok: true, offsets: Map<string, number> } | { ok: false, error: string }}
*/
function parseOffsets(raw) {
if (raw === undefined || raw === null || raw === "") return { ok: true, offsets: new Map() };
const value = parseJsonValue(raw);
const shapeError = "offsets must be a JSON object mapping jobId to the nextOffset from a previous poll";
if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, error: shapeError };
const offsets = new Map();
for (const [jobId, offset] of Object.entries(value)) {
const numeric = Number(offset);
if (!Number.isFinite(numeric) || numeric < 0) return { ok: false, error: shapeError };
offsets.set(jobId, Math.floor(numeric));
}
return { ok: true, offsets };
}
/**
* Share `total` characters across jobs by need (water-filling): a job never gets
* more than it needs or `perJob`, and what quiet jobs leave is shared by the rest.
* @param {number[]} needs new raw characters available per job
* @returns {number[]} characters each job may return
*/
function allocatePollBudgets(needs, perJob, total) {
const budgets = needs.map(() => 0);
const order = needs
.map((need, index) => ({ index, want: Math.min(Math.max(0, need), perJob) }))
.filter((entry) => entry.want > 0)
.sort((a, b) => a.want - b.want);
let remaining = total;
for (let i = 0; i < order.length; i++) {
const share = Math.floor(remaining / (order.length - i));
if (order[i].want <= share) {
budgets[order[i].index] = order[i].want;
remaining -= order[i].want;
continue;
}
// Sorted by want, so every job left wants more than an equal share.
for (let j = i; j < order.length; j++) budgets[order[j].index] = share;
break;
}
return budgets;
}
function countStatuses(entries) {
const counts = {};
for (const entry of entries) counts[entry.status] = (counts[entry.status] || 0) + 1;
return counts;
}
/**
* @param {object} deps injected by mcpServerBridge (keeps this module testable)
*/
function createJobBulkHandler(deps) {
const {
getSessions,
pendingSessionWriteApprovals,
isChatSessionCancelled,
preflightMainJobStart,
preflightWorkerJobStart,
startJobOnSession,
pollJob,
stopJob,
requestApproval,
sessionIdleManager,
getLivePermission,
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
createBulkId = () => `bulk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`,
now = () => Date.now(),
} = deps;
const { resolveLabel, checkTargetSync } = createBulkTargetGuards(deps);
/** bulkId -> { chatSessionId, createdAt, jobs: [{ jobId, sessionId, label }] } */
const bulkEntries = new Map();
function pruneBulkEntries() {
const cutoff = now() - BULK_ENTRY_MAX_AGE_MS;
for (const [bulkId, entry] of bulkEntries) {
if (entry.createdAt < cutoff) bulkEntries.delete(bulkId);
}
// Oldest first (Map keeps insertion order).
while (bulkEntries.size > MAX_BULK_ENTRIES) {
bulkEntries.delete(bulkEntries.keys().next().value);
}
}
/** Same isolation as a single job: a bulkId is only visible to the chat that created it. */
function getBulkEntry(bulkId, chatSessionId) {
pruneBulkEntries();
const entry = bulkEntries.get(bulkId);
if (!entry) return null;
if (entry.chatSessionId && entry.chatSessionId !== (chatSessionId || null)) return null;
return entry;
}
async function checkTargetTransport(sessionId, label, ctx, { probe = true } = {}) {
const hasMainSession = Boolean(getSessions()?.get?.(sessionId));
const probeParams = {
sessionId,
command: ctx.command,
chatSessionId: ctx.chatSessionId,
scopedSessionIds: ctx.scopedSessionIds,
};
let outcome;
try {
outcome = hasMainSession
? await preflightMainJobStart(probeParams, { probe })
: await preflightWorkerJobStart(probeParams, { probe });
} catch (err) {
outcome = { ok: false, error: err?.message || String(err) };
}
if (outcome && outcome.ok === false) {
return { sessionId, label, error: outcome.error || "Session does not support background execution" };
}
return null;
}
async function preflightAll(ctx, { probe = true } = {}) {
const failures = new Array(ctx.sessionIds.length).fill(null);
const pending = [];
ctx.sessionIds.forEach((sessionId, index) => {
const syncFailure = checkTargetSync(sessionId, ctx, { includePendingWrite: true });
if (syncFailure) {
failures[index] = syncFailure;
return;
}
pending.push(checkTargetTransport(sessionId, resolveLabel(sessionId, ctx.chatSessionId), ctx, { probe })
.then((failure) => { failures[index] = failure; }));
});
await Promise.all(pending);
return failures.filter(Boolean);
}
function preflightFailureResult(failures, total) {
return { ok: false, code: "BULK_PREFLIGHT_FAILED", error: formatPreflightFailure(failures, total) };
}
/**
* @param {object} params RPC params (command, sessionIds, chatSessionId, scopedSessionIds)
* @param {object} approvalContext transport context (externalSocket, beforeExecute)
* @param {{ requiresApproval?: boolean }} permission result of the permission check
*/
async function start(params, approvalContext = {}, permission = {}) {
const parsed = parseBulkExecParams(params, { singleTool: "terminal_start" });
if (!parsed.ok) return { ok: false, error: parsed.error };
const { command, sessionIds } = parsed;
const chatSessionId = params?.chatSessionId || null;
const ctx = { command, sessionIds, chatSessionId, scopedSessionIds: params?.scopedSessionIds };
// Phase 1: preflight. Nothing is started. When a prompt is coming, nothing may touch
// the remote hosts before the user answers, so shell-kind probes wait until after approval.
const approvalRequired = permission.requiresApproval === true;
const failures = await preflightAll(ctx, { probe: !approvalRequired });
if (failures.length > 0) return preflightFailureResult(failures, sessionIds.length);
// Claim every target synchronously so no other command can slip in while the user decides.
const claimConflicts = sessionIds
.filter((sessionId) => pendingSessionWriteApprovals.has(sessionId))
.map((sessionId) => ({ sessionId, label: resolveLabel(sessionId, chatSessionId), error: CLAIM_CONFLICT_ERROR }));
if (claimConflicts.length > 0) return preflightFailureResult(claimConflicts, sessionIds.length);
for (const sessionId of sessionIds) pendingSessionWriteApprovals.set(sessionId, BULK_START_RPC_METHOD);
// Keep the sessions from idle auto-close until the jobs exist; a running job then does.
const activeSessionIds = sessionIds.filter((sessionId) => sessionIdleManager.beginActivity(chatSessionId, sessionId));
let approvalGranted = false;
try {
// Phase 2: one approval listing every host, never satisfied by grants or session approval.
if (approvalRequired) {
const approved = await requestApproval(
BULK_START_RPC_METHOD,
{
command,
sessions: sessionIds.map((sessionId) => labelPart(sessionId, resolveLabel(sessionId, chatSessionId))),
},
chatSessionId,
{ ...approvalContext, requireFreshApproval: true },
);
if (!approved) return { ok: false, error: USER_DENIED_MESSAGE };
approvalGranted = true;
}
// Phase 3: commit. Local guards first, so a call that is no longer authorized never
// causes a remote probe.
const localGuards = () => {
if (isChatSessionCancelled(chatSessionId)) return { ok: false, error: CHAT_SESSION_CANCELLED_MESSAGE };
const live = typeof getLivePermission === "function" ? getLivePermission(params) : null;
if (live) {
if (live.allowed === false) return { ok: false, error: live.error };
if (live.requiresApproval === true && !approvalGranted) {
return {
ok: false,
error: "The permission mode changed to confirm while this call was pending. Run it again to be asked for approval.",
};
}
}
const recheck = sessionIds
.map((sessionId) => checkTargetSync(sessionId, ctx, { includePendingWrite: false }))
.filter(Boolean);
if (recheck.length > 0) return preflightFailureResult(recheck, sessionIds.length);
try {
approvalContext.beforeExecute?.();
} catch (err) {
return { ok: false, error: err?.message || String(err) };
}
return null;
};
const staleBeforeProbe = localGuards();
if (staleBeforeProbe) return staleBeforeProbe;
const staleTransport = (await Promise.all(sessionIds.map((sessionId) => (
checkTargetTransport(sessionId, resolveLabel(sessionId, chatSessionId), ctx, { probe: true })
)))).filter(Boolean);
if (staleTransport.length > 0) return preflightFailureResult(staleTransport, sessionIds.length);
// That pass awaited, so check the local guards again; the start loop is synchronous.
const staleAfterProbe = localGuards();
if (staleAfterProbe) return staleAfterProbe;
const labels = new Map(sessionIds.map((sessionId) => [sessionId, resolveLabel(sessionId, chatSessionId)]));
const results = await Promise.all(sessionIds.map((sessionId) => {
let started;
try {
started = Promise.resolve(startJobOnSession(
{ sessionId, command, chatSessionId, scopedSessionIds: params?.scopedSessionIds },
approvalContext.beforeExecute,
));
} catch (err) {
started = Promise.resolve({ ok: false, error: err?.message || String(err) });
}
return started.catch((err) => ({ ok: false, error: err?.message || String(err) }));
}));
const jobs = sessionIds.map((sessionId, index) => {
const result = results[index] || {};
const label = labels.get(sessionId) || "";
if (result.ok && result.jobId) {
return { sessionId, label, jobId: result.jobId, status: result.status || "running" };
}
return { sessionId, label, status: "not_started", error: result.error || "Background job did not start" };
});
const startedJobs = jobs.filter((job) => job.jobId);
if (startedJobs.length === 0) {
const detail = jobs.map((job) => `- ${labelPart(job.sessionId, job.label)}: ${job.error}`).join("\n");
return { ok: false, code: "BULK_NOT_STARTED", error: `No background job was started.\n${detail}` };
}
pruneBulkEntries();
const bulkId = createBulkId();
bulkEntries.set(bulkId, {
chatSessionId,
createdAt: now(),
jobs: startedJobs.map(({ jobId, sessionId, label }) => ({ jobId, sessionId, label })),
});
pruneBulkEntries();
return {
ok: true,
bulkId,
hostCount: sessionIds.length,
counts: countStatuses(jobs),
jobs,
recommendedPollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
};
} finally {
for (const sessionId of activeSessionIds) sessionIdleManager.endActivity(chatSessionId, sessionId);
for (const sessionId of sessionIds) {
if (pendingSessionWriteApprovals.get(sessionId) === BULK_START_RPC_METHOD) {
pendingSessionWriteApprovals.delete(sessionId);
}
}
}
}
/** Jobs for a poll/stop call, each with the label recorded at start when known. */
function resolveTargetJobs(params) {
const targets = parseJobTargets(params);
if (!targets.ok) return targets;
const chatSessionId = params?.chatSessionId || null;
if (targets.bulkId) {
const entry = getBulkEntry(targets.bulkId, chatSessionId);
if (!entry) {
return {
ok: false,
error: `Bulk job set "${targets.bulkId}" was not found. It may have expired; poll or stop the jobs by jobIds instead.`,
};
}
return { ok: true, bulkId: targets.bulkId, jobs: entry.jobs };
}
return { ok: true, bulkId: null, jobs: targets.jobIds.map((jobId) => ({ jobId, sessionId: null, label: "" })) };
}
function jobScopeParams(params, jobId, offset) {
return {
jobId,
chatSessionId: params?.chatSessionId || null,
scopedSessionIds: params?.scopedSessionIds,
...(offset !== undefined ? { offset } : {}),
};
}
async function callSafely(fn, args) {
try {
return await fn(args);
} catch (err) {
return { ok: false, error: err?.message || String(err) };
}
}
function jobLabel(job, result, chatSessionId) {
if (job.label) return job.label;
return result?.sessionId ? resolveLabel(result.sessionId, chatSessionId) : "";
}
function unavailableEntry(job, result, fallback = null, chatSessionId = null) {
return {
jobId: job.jobId,
sessionId: job.sessionId || fallback?.sessionId || undefined,
label: (fallback ? jobLabel(job, fallback, chatSessionId) : job.label) || undefined,
status: "unavailable",
error: result?.error || "Background job not found",
};
}
/**
* Read one job's output, keeping at most `budget` characters of new output (the
* newest). The budget is applied by polling from a later offset, so the existing
* poll slices the raw buffer and collapses progress redraws itself and nextOffset
* stays exact.
*/
async function readJobOutput(params, job, peek, requestedOffset, budget) {
const chatSessionId = params?.chatSessionId || null;
const end = Number(peek.nextOffset) || 0;
const fromOffset = Math.max(requestedOffset, end - budget);
const result = fromOffset >= end
? peek
: await callSafely(pollJob, jobScopeParams(params, job.jobId, fromOffset));
if (!result || result.ok === false) return unavailableEntry(job, result, peek, chatSessionId);
let output = typeof result.output === "string" ? result.output : "";
// Output that arrived between the two polls can push past the budget; keep the newest.
let trimmed = 0;
if (output.length > budget) {
trimmed = output.length - budget;
output = output.slice(trimmed);
}
// Output older than the job's kept window is gone too.
const effectiveStart = Math.max(fromOffset, Number(result.outputBaseOffset) || 0);
const skippedChars = Math.max(0, effectiveStart - requestedOffset) + trimmed;
const entry = {
jobId: job.jobId,
sessionId: result.sessionId || job.sessionId,
label: jobLabel(job, result, chatSessionId),
status: result.status,
exitCode: result.exitCode ?? null,
nextOffset: result.nextOffset,
output,
};
if (result.error) entry.error = result.error;
if (skippedChars > 0) entry.skippedChars = skippedChars;
return entry;
}
async function poll(params = {}) {
const resolved = resolveTargetJobs(params);
if (!resolved.ok) return { ok: false, error: resolved.error };
const offsets = parseOffsets(params?.offsets);
if (!offsets.ok) return { ok: false, error: offsets.error };
const chatSessionId = params?.chatSessionId || null;
const requested = resolved.jobs.map((job) => offsets.offsets.get(job.jobId) || 0);
// Peek first: no output, just where each job ends, so the budget can follow need.
const peeks = await Promise.all(resolved.jobs.map((job) => (
callSafely(pollJob, jobScopeParams(params, job.jobId, PEEK_OFFSET))
)));
const needs = peeks.map((peek, index) => {
if (!peek || peek.ok === false) return 0;
const start = Math.max(requested[index], Number(peek.outputBaseOffset) || 0);
return Math.max(0, (Number(peek.nextOffset) || 0) - start);
});
const budgets = allocatePollBudgets(needs, MAX_POLL_CHARS_PER_JOB, MAX_POLL_TOTAL_CHARS);
const jobs = await Promise.all(resolved.jobs.map((job, index) => {
const peek = peeks[index];
if (!peek || peek.ok === false) return unavailableEntry(job, peek, null, chatSessionId);
return readJobOutput(params, job, peek, requested[index], budgets[index]);
}));
const counts = countStatuses(jobs);
const running = (counts.running || 0) + (counts.stopping || 0);
return {
ok: true,
...(resolved.bulkId ? { bulkId: resolved.bulkId } : {}),
jobCount: jobs.length,
allCompleted: running === 0,
counts,
jobs,
recommendedPollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
};
}
async function stop(params = {}) {
const resolved = resolveTargetJobs(params);
if (!resolved.ok) return { ok: false, error: resolved.error };
const chatSessionId = params?.chatSessionId || null;
const jobs = await Promise.all(resolved.jobs.map(async (job) => {
const result = await callSafely(stopJob, jobScopeParams(params, job.jobId));
if (!result || result.ok === false) {
return {
jobId: job.jobId,
sessionId: job.sessionId || undefined,
label: job.label || undefined,
status: "unavailable",
error: result?.error || "Background job not found",
};
}
const entry = {
jobId: job.jobId,
sessionId: result.sessionId || job.sessionId,
label: jobLabel(job, result, chatSessionId),
status: result.status,
exitCode: result.exitCode ?? null,
};
if (result.error) entry.error = result.error;
return entry;
}));
return {
ok: true,
...(resolved.bulkId ? { bulkId: resolved.bulkId } : {}),
jobCount: jobs.length,
counts: countStatuses(jobs),
jobs,
};
}
return { start, poll, stop, _bulkEntries: bulkEntries };
}
module.exports = {
BULK_ENTRY_MAX_AGE_MS,
BULK_START_RPC_METHOD,
MAX_BULK_ENTRIES,
MAX_POLL_CHARS_PER_JOB,
MAX_POLL_TOTAL_CHARS,
PEEK_OFFSET,
allocatePollBudgets,
createJobBulkHandler,
parseJobTargets,
parseOffsets,
};
@@ -1,492 +0,0 @@
"use strict";
const assert = require("node:assert/strict");
const test = require("node:test");
const {
BULK_ENTRY_MAX_AGE_MS,
BULK_START_RPC_METHOD,
MAX_BULK_ENTRIES,
MAX_POLL_CHARS_PER_JOB,
MAX_POLL_TOTAL_CHARS,
allocatePollBudgets,
createJobBulkHandler,
parseJobTargets,
parseOffsets,
} = require("./jobBulk.cjs");
const { serializeBackgroundJob } = require("../ai/backgroundJobOutput.cjs");
// ── input parsing ──
test("parseJobTargets accepts a bulkId or a JSON list of jobIds, not both", () => {
assert.deepEqual(parseJobTargets({ bulkId: " bulk-1 " }), { ok: true, bulkId: "bulk-1", jobIds: [] });
assert.deepEqual(parseJobTargets({ jobIds: '["j1","j2","j1"]' }), { ok: true, bulkId: null, jobIds: ["j1", "j2"] });
assert.deepEqual(parseJobTargets({ jobIds: ["j1"] }), { ok: true, bulkId: null, jobIds: ["j1"] });
for (const [params, pattern] of [
[{}, /bulkId or jobIds is required/],
[{ bulkId: "b", jobIds: '["j"]' }, /either bulkId or jobIds/],
[{ jobIds: "not json" }, /JSON array of 1-20/],
[{ jobIds: "[]" }, /JSON array of 1-20/],
[{ jobIds: '["a", 1]' }, /JSON array of 1-20/],
[{ jobIds: JSON.stringify(Array.from({ length: 21 }, (_, i) => `j${i}`)) }, /JSON array of 1-20/],
]) {
const result = parseJobTargets(params);
assert.equal(result.ok, false, JSON.stringify(params));
assert.match(result.error, pattern);
}
});
test("parseOffsets maps jobId to a non-negative offset", () => {
assert.deepEqual([...parseOffsets(undefined).offsets], []);
assert.deepEqual([...parseOffsets('{"j1":10,"j2":"5.9"}').offsets], [["j1", 10], ["j2", 5]]);
assert.deepEqual([...parseOffsets({ j1: 3 }).offsets], [["j1", 3]]);
for (const raw of ["[1]", '{"j":-1}', '{"j":"x"}', "nope"]) {
assert.equal(parseOffsets(raw).ok, false, raw);
}
});
test("allocatePollBudgets shares the total by need and never exceeds the caps", () => {
// Everyone fits: each gets what it needs.
assert.deepEqual(allocatePollBudgets([10, 0, 30], 100, 1000), [10, 0, 30]);
// Per-job cap.
assert.deepEqual(allocatePollBudgets([500, 5], 100, 1000), [100, 5]);
// Quiet jobs leave room for busy ones.
assert.deepEqual(allocatePollBudgets([1, 1, 1000, 1000], 100, 150), [1, 1, 74, 74]);
// All busy: an equal share, total never exceeded.
const even = allocatePollBudgets(Array(20).fill(50_000), 4096, 32 * 1024);
assert.ok(even.every((value) => value === 1638));
assert.ok(even.reduce((a, b) => a + b, 0) <= 32 * 1024);
assert.deepEqual(allocatePollBudgets([], 100, 100), []);
});
// ── harness ──
function createHarness(options = {}) {
const ids = options.ids || ["a", "b", "c"];
const inScope = new Set(options.inScope || ids);
const labels = options.labels || { a: "web1", b: "web2", c: "db1" };
const mainSessions = new Map((options.mainIds || ids).map((id) => [id, { label: labels[id] }]));
const busy = new Map();
const closing = new Map();
const pending = new Map();
const jobs = new Map(options.jobs || []);
const state = {
cancelled: false,
events: [],
approvals: [],
probes: [],
starts: [],
polls: [],
stops: [],
activity: { begun: [], ended: [] },
livePermission: null,
now: options.now ?? 1_000_000,
};
let nextBulk = 0;
let nextJob = 0;
const preflight = (where) => async ({ sessionId }, { probe }) => {
state.probes.push({ sessionId, where, probe });
const error = options.transportErrors?.[sessionId];
return error ? { ok: false, error } : { ok: true };
};
const deps = {
getSessions: () => mainSessions,
getSessionMeta: (id) => ({ label: labels[id] || "", connected: true }),
validateSessionScope: (id) => (inScope.has(id) ? null : `Session "${id}" is not in the current scope.`),
closingTerminalSessions: closing,
getSessionBusyError: (id) => (busy.has(id) ? { ok: false, error: busy.get(id) } : null),
pendingSessionWriteApprovals: pending,
isChatSessionCancelled: () => state.cancelled,
preflightMainJobStart: preflight("main"),
preflightWorkerJobStart: preflight("worker"),
startJobOnSession: (params, beforeExecute) => {
state.starts.push({ params, beforeExecute });
state.events.push(`start:${params.sessionId}`);
if (options.start) return options.start(params, state);
const jobId = `job-${params.sessionId}-${nextJob++}`;
jobs.set(jobId, { id: jobId, sessionId: params.sessionId, chatSessionId: params.chatSessionId, status: "running", stdout: "", outputBaseOffset: 0, totalOutputChars: 0 });
return Promise.resolve({ ok: true, jobId, sessionId: params.sessionId, status: "running" });
},
pollJob: (params) => {
state.polls.push(params);
const job = jobs.get(params.jobId);
if (!job || (job.chatSessionId && job.chatSessionId !== params.chatSessionId)) {
return { ok: false, error: "Background job not found" };
}
return serializeBackgroundJob(job, params.offset);
},
stopJob: (params) => {
state.stops.push(params);
const job = jobs.get(params.jobId);
if (!job) return { ok: false, error: "Background job not found" };
if (job.status === "running") job.status = "stopping";
return serializeBackgroundJob(job, 0);
},
requestApproval: async (...args) => {
state.approvals.push(args);
state.events.push("approval");
if (options.onApproval) await options.onApproval({ busy, closing, state, pending, inScope });
return options.approve !== false;
},
sessionIdleManager: {
beginActivity: (chat, id) => { state.activity.begun.push(id); return true; },
endActivity: (chat, id) => { state.activity.ended.push(id); return true; },
},
getLivePermission: () => state.livePermission,
USER_DENIED_MESSAGE: "Operation denied by user.",
CHAT_SESSION_CANCELLED_MESSAGE: "Operation cancelled: the SDK agent session was stopped.",
createBulkId: () => `bulk-${nextBulk++}`,
now: () => state.now,
};
const handler = createJobBulkHandler(deps);
const baseParams = { command: "apt-get -y upgrade", sessionIds: JSON.stringify(ids), chatSessionId: "chat-1" };
return { handler, state, busy, closing, pending, jobs, baseParams, deps, inScope };
}
// ── start ──
test("start launches one job per session after one fresh approval and returns a bulkId", async () => {
const harness = createHarness();
const result = await harness.handler.start(harness.baseParams, { beforeExecute: () => {} }, { requiresApproval: true });
assert.equal(result.ok, true);
assert.equal(result.bulkId, "bulk-0");
assert.equal(result.hostCount, 3);
assert.deepEqual(result.counts, { running: 3 });
assert.deepEqual(result.jobs.map((job) => [job.sessionId, job.label, job.status]), [
["a", "web1", "running"], ["b", "web2", "running"], ["c", "db1", "running"],
]);
assert.ok(result.jobs.every((job) => typeof job.jobId === "string"));
assert.equal(harness.state.approvals.length, 1, "one approval for the whole fan-out");
const [method, args, chatSessionId, context] = harness.state.approvals[0];
assert.equal(method, BULK_START_RPC_METHOD);
assert.deepEqual(args, { command: "apt-get -y upgrade", sessions: ["a (web1)", "b (web2)", "c (db1)"] });
assert.equal(chatSessionId, "chat-1");
assert.equal(context.requireFreshApproval, true);
// Every start runs after the approval.
assert.deepEqual(harness.state.events, ["approval", "start:a", "start:b", "start:c"]);
// Claims and idle protection are released once the jobs exist.
assert.equal(harness.pending.size, 0);
assert.deepEqual(harness.state.activity.ended, ["a", "b", "c"]);
});
test("start never probes a remote host before approval, and probes every target after it", async () => {
const harness = createHarness({ mainIds: ["a"], ids: ["a", "b"] });
await harness.handler.start({ ...harness.baseParams, sessionIds: '["a","b"]' }, {}, { requiresApproval: true });
const beforeApproval = harness.state.probes.slice(0, 2);
const afterApproval = harness.state.probes.slice(2);
assert.deepEqual(beforeApproval.map((p) => [p.sessionId, p.where, p.probe]), [["a", "main", false], ["b", "worker", false]]);
assert.deepEqual(afterApproval.map((p) => [p.sessionId, p.probe]), [["a", true], ["b", true]]);
});
test("start without a prompt runs the full check right away", async () => {
const harness = createHarness();
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(result.ok, true);
assert.equal(harness.state.approvals.length, 0);
assert.ok(harness.state.probes.every((p) => p.probe === true));
});
test("start is all-or-nothing: every bad target is listed and no job starts", async () => {
const harness = createHarness({
inScope: ["a", "b"],
transportErrors: { b: "Background execution currently supports shell-backed PTY sessions only." },
});
harness.busy.set("a", "Session already has a long-running command in progress.");
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: true });
assert.equal(result.ok, false);
assert.equal(result.code, "BULK_PREFLIGHT_FAILED");
assert.match(result.error, /^nothing was sent\. 3 of 3 targets cannot run this command:/);
assert.match(result.error, /- a \(web1\): Session already has a long-running command/);
assert.match(result.error, /- b \(web2\): Background execution currently supports shell-backed PTY sessions only\./);
// An out-of-scope id never reveals its label.
assert.match(result.error, /- c: Session "c" is not in the current scope\./);
assert.equal(harness.state.approvals.length, 0);
assert.equal(harness.state.starts.length, 0);
});
test("start rejects malformed input and points single sessions to terminal_start", async () => {
const harness = createHarness();
const single = await harness.handler.start({ ...harness.baseParams, sessionIds: '["a"]' });
assert.equal(single.ok, false);
assert.match(single.error, /Use terminal_start/);
assert.equal((await harness.handler.start({ ...harness.baseParams, command: " " })).ok, false);
assert.equal(harness.state.starts.length, 0);
});
test("a denied approval starts nothing and releases every claim", async () => {
const harness = createHarness({ approve: false });
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: true });
assert.deepEqual(result, { ok: false, error: "Operation denied by user." });
assert.equal(harness.state.starts.length, 0);
assert.equal(harness.pending.size, 0);
});
test("targets are claimed while the approval is open", async () => {
let claimedDuringApproval = null;
const harness = createHarness({
onApproval: ({ pending }) => { claimedDuringApproval = [...pending.entries()]; },
});
await harness.handler.start(harness.baseParams, {}, { requiresApproval: true });
assert.deepEqual(claimedDuringApproval, [["a", BULK_START_RPC_METHOD], ["b", BULK_START_RPC_METHOD], ["c", BULK_START_RPC_METHOD]]);
});
test("a target claimed by another request is refused before the prompt", async () => {
const harness = createHarness();
harness.pending.set("b", "netcatty/exec");
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: true });
assert.equal(result.code, "BULK_PREFLIGHT_FAILED");
assert.match(result.error, /- b \(web2\): Session already has another command request awaiting approval/);
assert.equal(harness.pending.get("b"), "netcatty/exec", "the other request keeps its claim");
});
test("state that changes while the prompt is open stops the whole start", async () => {
const cancelled = createHarness({ onApproval: ({ state }) => { state.cancelled = true; } });
assert.deepEqual(
await cancelled.handler.start(cancelled.baseParams, {}, { requiresApproval: true }),
{ ok: false, error: "Operation cancelled: the SDK agent session was stopped." },
);
assert.equal(cancelled.state.starts.length, 0);
const observer = createHarness({
onApproval: ({ state }) => { state.livePermission = { allowed: false, error: "observer mode" }; },
});
assert.deepEqual(await observer.handler.start(observer.baseParams, {}, { requiresApproval: true }), { ok: false, error: "observer mode" });
assert.equal(observer.state.starts.length, 0);
const closing = createHarness({ onApproval: ({ closing: map }) => { map.set("c", true); } });
const result = await closing.handler.start(closing.baseParams, {}, { requiresApproval: true });
assert.equal(result.code, "BULK_PREFLIGHT_FAILED");
assert.match(result.error, /- c \(db1\): Session "c" is closing\./);
assert.equal(closing.state.starts.length, 0);
assert.equal(closing.pending.size, 0);
});
test("switching to confirm mode during an unprompted start refuses it", async () => {
const harness = createHarness();
harness.state.livePermission = { allowed: true, requiresApproval: true };
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(result.ok, false);
assert.match(result.error, /permission mode changed to confirm/);
assert.equal(harness.state.starts.length, 0);
});
test("a privacy-policy change during approval stops the start", async () => {
const harness = createHarness();
let calls = 0;
const result = await harness.handler.start(harness.baseParams, {
beforeExecute: () => {
calls += 1;
throw new Error("External MCP privacy policy changed.");
},
}, { requiresApproval: true });
assert.deepEqual(result, { ok: false, error: "External MCP privacy policy changed." });
assert.equal(calls, 1);
assert.equal(harness.state.starts.length, 0);
});
test("a host that fails to start is reported per host; the others keep running", async () => {
const harness = createHarness({
start: (params) => (params.sessionId === "b"
? Promise.resolve({ ok: false, error: "Session is closing." })
: Promise.resolve({ ok: true, jobId: `job-${params.sessionId}`, status: "running" })),
});
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(result.ok, true);
assert.deepEqual(result.counts, { running: 2, not_started: 1 });
assert.deepEqual(result.jobs[1], { sessionId: "b", label: "web2", status: "not_started", error: "Session is closing." });
// The bulkId only names the jobs that exist.
assert.deepEqual(harness.handler._bulkEntries.get(result.bulkId).jobs.map((job) => job.jobId), ["job-a", "job-c"]);
});
test("when no job starts at all the call fails and no bulkId is created", async () => {
const harness = createHarness({
start: (params) => (params.sessionId === "a"
? Promise.reject(new Error("worker gone"))
: Promise.resolve({ ok: false, error: "Shell prompt is not ready; no command was sent" })),
});
const result = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(result.ok, false);
assert.equal(result.code, "BULK_NOT_STARTED");
assert.match(result.error, /^No background job was started\.\n- a \(web1\): worker gone\n- b \(web2\): Shell prompt is not ready/);
assert.equal(harness.handler._bulkEntries.size, 0);
assert.equal(harness.pending.size, 0);
});
// ── poll ──
async function startedHarness(options = {}) {
const harness = createHarness(options);
const started = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(started.ok, true);
const jobIds = started.jobs.map((job) => job.jobId);
return { ...harness, started, jobIds };
}
test("poll returns each job's status and new output since its offset", async () => {
const harness = await startedHarness();
const [jobA, jobB, jobC] = harness.jobIds;
Object.assign(harness.jobs.get(jobA), { stdout: "line1\nline2\n", totalOutputChars: 12 });
Object.assign(harness.jobs.get(jobB), { stdout: "done\n", totalOutputChars: 5, status: "completed", exitCode: 0 });
Object.assign(harness.jobs.get(jobC), { stdout: "E: failed\n", totalOutputChars: 10, status: "failed", exitCode: 100, error: "exit 100" });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1", offsets: JSON.stringify({ [jobA]: 6 }) });
assert.equal(result.ok, true);
assert.equal(result.bulkId, harness.started.bulkId);
assert.equal(result.allCompleted, false);
assert.deepEqual(result.counts, { running: 1, completed: 1, failed: 1 });
assert.deepEqual(result.jobs[0], { jobId: jobA, sessionId: "a", label: "web1", status: "running", exitCode: null, nextOffset: 12, output: "line2\n" });
assert.deepEqual(result.jobs[1], { jobId: jobB, sessionId: "b", label: "web2", status: "completed", exitCode: 0, nextOffset: 5, output: "done\n" });
assert.equal(result.jobs[2].error, "exit 100");
assert.equal(result.jobs[2].exitCode, 100);
});
test("poll keeps only the newest output per job and reports what it skipped", async () => {
const harness = await startedHarness();
const [jobA] = harness.jobIds;
const big = "x".repeat(40_000) + "TAIL";
Object.assign(harness.jobs.get(jobA), { stdout: big, totalOutputChars: big.length });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
const entry = result.jobs[0];
assert.equal(entry.output.length, MAX_POLL_CHARS_PER_JOB);
assert.ok(entry.output.endsWith("TAIL"));
assert.equal(entry.skippedChars, big.length - MAX_POLL_CHARS_PER_JOB);
assert.equal(entry.nextOffset, big.length, "nextOffset stays exact");
// The next poll from nextOffset has nothing new and skips nothing.
const again = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1", offsets: { [jobA]: entry.nextOffset } });
assert.equal(again.jobs[0].output, "");
assert.equal("skippedChars" in again.jobs[0], false);
});
test("poll counts output dropped from the job's kept window as skipped", async () => {
const harness = await startedHarness();
const [jobA] = harness.jobIds;
// The job kept only the last 100 chars of 1000 produced.
Object.assign(harness.jobs.get(jobA), { stdout: "y".repeat(100), outputBaseOffset: 900, totalOutputChars: 1000, outputTruncated: true });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1", offsets: { [jobA]: 400 } });
assert.equal(result.jobs[0].output, "y".repeat(100));
assert.equal(result.jobs[0].skippedChars, 500);
});
test("progress redraws are collapsed and offsets stay on the raw output", async () => {
const harness = await startedHarness();
const [jobA] = harness.jobIds;
const raw = "10%\r50%\r100%\ndone\n";
Object.assign(harness.jobs.get(jobA), { stdout: raw, totalOutputChars: raw.length });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
assert.equal(result.jobs[0].output, "100%\ndone\n");
assert.equal(result.jobs[0].nextOffset, raw.length);
});
test("the total poll budget is shared across jobs", async () => {
const ids = Array.from({ length: 20 }, (_, i) => `s${i}`);
const harness = await startedHarness({ ids, labels: {} });
for (const jobId of harness.jobIds) {
const out = "z".repeat(20_000);
Object.assign(harness.jobs.get(jobId), { stdout: out, totalOutputChars: out.length });
}
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
const perJob = Math.floor(MAX_POLL_TOTAL_CHARS / 20);
assert.ok(perJob < MAX_POLL_CHARS_PER_JOB);
assert.ok(result.jobs.every((job) => job.output.length === perJob));
const total = result.jobs.reduce((sum, job) => sum + job.output.length, 0);
assert.ok(total <= MAX_POLL_TOTAL_CHARS);
});
test("quiet jobs leave their share to busy jobs", async () => {
const ids = Array.from({ length: 20 }, (_, i) => `s${i}`);
const harness = await startedHarness({ ids, labels: {} });
harness.jobIds.forEach((jobId, index) => {
const out = index < 2 ? "b".repeat(50_000) : "q".repeat(100);
Object.assign(harness.jobs.get(jobId), { stdout: out, totalOutputChars: out.length });
});
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
// The two busy jobs get the full per-job cap, not 32 KB / 20.
assert.equal(result.jobs[0].output.length, MAX_POLL_CHARS_PER_JOB);
assert.equal(result.jobs[1].output.length, MAX_POLL_CHARS_PER_JOB);
assert.equal(result.jobs[0].skippedChars, 50_000 - MAX_POLL_CHARS_PER_JOB);
// Quiet jobs return all their new output and skip nothing.
assert.ok(result.jobs.slice(2).every((job) => job.output.length === 100 && !("skippedChars" in job)));
const total = result.jobs.reduce((sum, job) => sum + job.output.length, 0);
assert.ok(total <= MAX_POLL_TOTAL_CHARS);
});
test("per-job problems are reported per job and never fail the poll", async () => {
const harness = await startedHarness();
const [jobA, jobB] = harness.jobIds;
harness.jobs.delete(jobB);
Object.assign(harness.jobs.get(jobA), { status: "completed", exitCode: 0 });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
assert.equal(result.ok, true);
assert.deepEqual(result.jobs[1], { jobId: jobB, sessionId: "b", label: "web2", status: "unavailable", error: "Background job not found" });
assert.deepEqual(result.counts, { completed: 1, unavailable: 1, running: 1 });
});
test("allCompleted is true once no job is running or stopping", async () => {
const harness = await startedHarness();
for (const jobId of harness.jobIds) Object.assign(harness.jobs.get(jobId), { status: "completed", exitCode: 0 });
const result = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
assert.equal(result.allCompleted, true);
});
test("poll accepts explicit jobIds and resolves their labels", async () => {
const harness = await startedHarness();
const result = await harness.handler.poll({ jobIds: JSON.stringify(harness.jobIds.slice(0, 2)), chatSessionId: "chat-1" });
assert.equal(result.ok, true);
assert.equal("bulkId" in result, false);
assert.deepEqual(result.jobs.map((job) => job.label), ["web1", "web2"]);
});
test("a bulkId is only visible to the chat that created it", async () => {
const harness = await startedHarness();
const foreign = await harness.handler.poll({ bulkId: harness.started.bulkId, chatSessionId: "chat-2" });
assert.equal(foreign.ok, false);
assert.match(foreign.error, /was not found/);
const unknown = await harness.handler.stop({ bulkId: "bulk-nope", chatSessionId: "chat-1" });
assert.equal(unknown.ok, false);
assert.match(unknown.error, /was not found.*jobIds instead/);
// Explicit jobIds still go through each job's own ownership check.
const foreignJobs = await harness.handler.poll({ jobIds: JSON.stringify(harness.jobIds), chatSessionId: "chat-2" });
assert.ok(foreignJobs.jobs.every((job) => job.status === "unavailable"));
});
// ── stop ──
test("stop stops every job of a bulkId and reports each one", async () => {
const harness = await startedHarness();
const [, jobB] = harness.jobIds;
Object.assign(harness.jobs.get(jobB), { status: "completed", exitCode: 0 });
const result = await harness.handler.stop({ bulkId: harness.started.bulkId, chatSessionId: "chat-1" });
assert.equal(result.ok, true);
assert.deepEqual(result.counts, { stopping: 2, completed: 1 });
assert.equal(result.jobs[1].status, "completed");
assert.deepEqual(harness.state.stops.map((params) => [params.jobId, params.chatSessionId]), harness.jobIds.map((id) => [id, "chat-1"]));
});
test("stop reports missing jobs per job", async () => {
const harness = await startedHarness();
harness.jobs.clear();
const result = await harness.handler.stop({ jobIds: JSON.stringify(harness.jobIds), chatSessionId: "chat-1" });
assert.equal(result.ok, true);
assert.deepEqual(result.counts, { unavailable: 3 });
});
// ── bulkId registry ──
test("bulkIds expire after the jobs' lifetime and the registry stays bounded", async () => {
const harness = await startedHarness();
const { bulkId } = harness.started;
harness.state.now += BULK_ENTRY_MAX_AGE_MS + 1;
const expired = await harness.handler.poll({ bulkId, chatSessionId: "chat-1" });
assert.equal(expired.ok, false);
assert.match(expired.error, /expired/);
for (let i = 0; i < MAX_BULK_ENTRIES + 5; i++) {
const started = await harness.handler.start(harness.baseParams, {}, { requiresApproval: false });
assert.equal(started.ok, true);
}
assert.equal(harness.handler._bulkEntries.size, MAX_BULK_ENTRIES);
});
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more