Merge remote-tracking branch 'origin/main' into add_vnc_rdp_support

# Conflicts:
#	components/HostDetailsAdvancedSections.tsx
#	components/terminal/TerminalConnectionDialog.tsx
#	components/terminalLayer/TerminalLayerSidePanelSection.tsx
#	electron/capabilities/codegen/mcpToolRegistry.cjs
This commit is contained in:
bincxz committed 2026-11-26 23:46:16 +08:00
commit a3a24942e7
210 files changed
+15523 -794

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`.
**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`.
**Handles:** `ToolOutputStore` persists across turns per chat session; cleared on chat session delete. Large `sftp.read` results spill to `tool_output_read`.
+28
View File
@@ -357,6 +357,34 @@ 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 visibleFullBleedSurfaces = Array.from(
document.querySelectorAll<HTMLElement>('[data-plugin-chrome="full-bleed"] [data-plugin-remote-surface]'),
).filter((el) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
const active = document.activeElement;
const focusInsideHostChrome = Boolean(
active
&& active !== document.body
&& active !== document.documentElement
&& !visibleFullBleedSurfaces.some((el) => el.contains(active))
&& !active.closest?.('[data-plugin-view-slot]'),
);
if (inPluginSurface || (visibleFullBleedSurfaces.length > 0 && !focusInsideHostChrome)) {
return;
}
}
}
if (TERMINAL_PASSTHROUGH_ACTIONS.has(binding.action)) {
if (isTerminalElement) {
return;
+2 -1
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, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, 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,
@@ -738,6 +738,7 @@ function AppViewInner({ domains }: AppViewProps) {
/>
<TerminalLayerMount
isVaultInitialized={isVaultInitialized}
hosts={terminalHosts}
portForwardingRules={portForwardingRules}
customGroups={customGroups}
+2
View File
@@ -55,6 +55,7 @@ export function VaultHost() {
hosts: vault.hosts,
identities: vault.identities,
importOrReuseKey: actions?.importOrReuseKey,
isVaultInitialized: vault.isVaultInitialized,
keys: vault.keys,
managedSources: vault.managedSources,
navigateToSection: local.navigateToSection,
@@ -90,6 +91,7 @@ export function VaultHost() {
vault.groupConfigs,
vault.hosts,
vault.identities,
vault.isVaultInitialized,
vault.keys,
vault.managedSources,
vault.proxyProfiles,
@@ -0,0 +1,233 @@
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,6 +98,7 @@ 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',
@@ -214,6 +214,25 @@ export const enSystemManagerMessages: Messages = {
'systemManager.ports.unknownProcess': 'Unknown process',
'systemManager.ports.terminate': 'Terminate',
'systemManager.ports.confirmTerminate': 'Send SIGTERM to process {{pid}} that holds this port?',
'systemManager.ports.forwardedMeta': '{{count}} forwarded',
'systemManager.ports.forward': 'Forward to local port',
'systemManager.ports.stopForward': 'Stop port forwarding',
'systemManager.ports.forwardTitle': 'Forward port to local',
'systemManager.ports.forwardDesc': 'Create a local SSH port forward to this remote listener.',
'systemManager.ports.forwardDescWithHost': 'Forward this listener on {{host}} to a local port over SSH.',
'systemManager.ports.forwardLocalPort': 'Local port',
'systemManager.ports.forwardBindAddress': 'Bind address',
'systemManager.ports.forwardAction': 'Forward',
'systemManager.ports.forwarding': 'Forwarding…',
'systemManager.ports.forwardInvalidPort': 'Enter a valid port number between 1 and 65535.',
'systemManager.ports.forwardInvalidBindAddress': 'Enter a valid bind address (e.g. 127.0.0.1 or 0.0.0.0).',
'systemManager.ports.forwardPortInUse': 'Local port {{port}} is already used by "{{label}}".',
'systemManager.ports.forwardFailed': 'Failed to start port forwarding.',
'systemManager.ports.forwardStarted': 'Forwarding {{local}} → {{remote}}',
'systemManager.ports.forwardStopped': 'Stopped forwarding {{local}}',
'systemManager.ports.copiedEndpoint': 'Copied {{endpoint}}',
'systemManager.ports.copyEndpointAria': 'Copy local address {{endpoint}}',
'systemManager.ports.clickToCopy': 'Click to copy local address',
'systemManager.services.unavailable': 'systemctl is not available on this host.',
'systemManager.services.loading': 'Loading systemd services…',
+1
View File
@@ -14,6 +14,7 @@ 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.',
+1
View File
@@ -98,6 +98,7 @@ 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',
@@ -214,6 +214,25 @@ export const esSystemManagerMessages: Messages = {
'systemManager.ports.unknownProcess': 'Proceso desconocido',
'systemManager.ports.terminate': 'Terminar',
'systemManager.ports.confirmTerminate': '¿Enviar SIGTERM al proceso {{pid}} que ocupa este puerto?',
'systemManager.ports.forwardedMeta': '{{count}} reenviado(s)',
'systemManager.ports.forward': 'Reenviar a puerto local',
'systemManager.ports.stopForward': 'Detener reenvío de puerto',
'systemManager.ports.forwardTitle': 'Reenviar puerto a local',
'systemManager.ports.forwardDesc': 'Crea un reenvío local SSH hacia este puerto remoto en escucha.',
'systemManager.ports.forwardDescWithHost': 'Reenvía este puerto en escucha de {{host}} a un puerto local por SSH.',
'systemManager.ports.forwardLocalPort': 'Puerto local',
'systemManager.ports.forwardBindAddress': 'Dirección de enlace',
'systemManager.ports.forwardAction': 'Reenviar',
'systemManager.ports.forwarding': 'Reenviando…',
'systemManager.ports.forwardInvalidPort': 'Ingresa un número de puerto válido entre 1 y 65535.',
'systemManager.ports.forwardInvalidBindAddress': 'Ingresa una dirección de enlace válida (p. ej., 127.0.0.1 o 0.0.0.0).',
'systemManager.ports.forwardPortInUse': 'El puerto local {{port}} ya está en uso por «{{label}}».',
'systemManager.ports.forwardFailed': 'No se pudo iniciar el reenvío de puerto.',
'systemManager.ports.forwardStarted': 'Reenviando {{local}} → {{remote}}',
'systemManager.ports.forwardStopped': 'Reenvío detenido en {{local}}',
'systemManager.ports.copiedEndpoint': 'Copiado {{endpoint}}',
'systemManager.ports.copyEndpointAria': 'Copiar dirección local {{endpoint}}',
'systemManager.ports.clickToCopy': 'Haz clic para copiar la dirección local',
'systemManager.services.unavailable': 'systemctl no está disponible en este host.',
'systemManager.services.loading': 'Cargando servicios de systemd…',
+1
View File
@@ -14,6 +14,7 @@ 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.',
+1
View File
@@ -71,6 +71,7 @@ export const ruCoreMessages: Messages = {
'common.apply': 'Применить',
'common.use': 'Использовать',
'common.useGlobal': 'Использовать глобальное',
'common.useGroup': 'Использовать настройки группы',
'common.saveChanges': 'Сохранить изменения',
'common.advanced': 'Дополнительно',
'common.left': 'Слева',
@@ -197,6 +197,25 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.ports.unknownProcess': 'Неизвестный процесс',
'systemManager.ports.terminate': 'Завершить',
'systemManager.ports.confirmTerminate': 'Отправить SIGTERM процессу {{pid}}, занимающему этот порт?',
'systemManager.ports.forwardedMeta': 'проброшено: {{count}}',
'systemManager.ports.forward': 'Пробросить на локальный порт',
'systemManager.ports.stopForward': 'Остановить проброс порта',
'systemManager.ports.forwardTitle': 'Пробросить порт локально',
'systemManager.ports.forwardDesc': 'Создать локальный SSH-туннель к этому удалённому порту.',
'systemManager.ports.forwardDescWithHost': 'Пробросить этот порт на {{host}} на локальный порт через SSH.',
'systemManager.ports.forwardLocalPort': 'Локальный порт',
'systemManager.ports.forwardBindAddress': 'Адрес привязки',
'systemManager.ports.forwardAction': 'Пробросить',
'systemManager.ports.forwarding': 'Проброс…',
'systemManager.ports.forwardInvalidPort': 'Введите корректный номер порта от 1 до 65535.',
'systemManager.ports.forwardInvalidBindAddress': 'Введите корректный адрес привязки (например, 127.0.0.1 или 0.0.0.0).',
'systemManager.ports.forwardPortInUse': 'Локальный порт {{port}} уже занят правилом «{{label}}».',
'systemManager.ports.forwardFailed': 'Не удалось запустить проброс порта.',
'systemManager.ports.forwardStarted': 'Проброс {{local}} → {{remote}} запущен',
'systemManager.ports.forwardStopped': 'Проброс {{local}} остановлен',
'systemManager.ports.copiedEndpoint': 'Скопировано: {{endpoint}}',
'systemManager.ports.copyEndpointAria': 'Скопировать локальный адрес {{endpoint}}',
'systemManager.ports.clickToCopy': 'Нажмите, чтобы скопировать локальный адрес',
'systemManager.services.unavailable': 'systemctl недоступен на этом хосте.',
'systemManager.services.loading': 'Загрузка служб systemd…',
+1
View File
@@ -14,6 +14,7 @@ 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': 'Дождитесь пустой командной строки.',
+1
View File
@@ -89,6 +89,7 @@ export const zhCNCoreMessages: Messages = {
'common.apply': '应用',
'common.use': '使用',
'common.useGlobal': '跟随全局',
'common.useGroup': '跟随分组',
'common.left': '左侧',
'common.right': '右侧',
'common.more': '更多',
@@ -214,6 +214,25 @@ export const zhCnSystemManagerMessages: Messages = {
'systemManager.ports.unknownProcess': '未知进程',
'systemManager.ports.terminate': '结束进程',
'systemManager.ports.confirmTerminate': '向占用该端口的进程 {{pid}} 发送 SIGTERM?',
'systemManager.ports.forwardedMeta': '{{count}} 个已转发',
'systemManager.ports.forward': '转发到本地端口',
'systemManager.ports.stopForward': '停止端口转发',
'systemManager.ports.forwardTitle': '转发端口到本地',
'systemManager.ports.forwardDesc': '通过 SSH 将此远程监听端口转发到本地端口。',
'systemManager.ports.forwardDescWithHost': '通过 SSH 将 {{host}} 上的此监听端口转发到本地端口。',
'systemManager.ports.forwardLocalPort': '本地端口',
'systemManager.ports.forwardBindAddress': '绑定地址',
'systemManager.ports.forwardAction': '开始转发',
'systemManager.ports.forwarding': '转发中…',
'systemManager.ports.forwardInvalidPort': '请输入 1 到 65535 之间的有效端口号。',
'systemManager.ports.forwardInvalidBindAddress': '请输入有效的绑定地址(如 127.0.0.1 或 0.0.0.0)。',
'systemManager.ports.forwardPortInUse': '本地端口 {{port}} 已被「{{label}}」占用。',
'systemManager.ports.forwardFailed': '启动端口转发失败。',
'systemManager.ports.forwardStarted': '已开始转发 {{local}} → {{remote}}',
'systemManager.ports.forwardStopped': '已停止转发 {{local}}',
'systemManager.ports.copiedEndpoint': '已复制 {{endpoint}}',
'systemManager.ports.copyEndpointAria': '复制本地地址 {{endpoint}}',
'systemManager.ports.clickToCopy': '点击复制本地地址',
'systemManager.services.unavailable': '此主机未检测到 systemctl。',
'systemManager.services.loading': '正在加载 systemd 服务…',
@@ -14,6 +14,7 @@ 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': '请等待终端回到空命令提示符。',
+1
View File
@@ -89,6 +89,7 @@ export const zhTWCoreMessages: Messages = {
'common.apply': '套用',
'common.use': '使用',
'common.useGlobal': '跟隨全域',
'common.useGroup': '跟隨群組',
'common.left': '左側',
'common.right': '右側',
'common.more': '更多',
@@ -214,6 +214,25 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.ports.unknownProcess': '未知行程',
'systemManager.ports.terminate': '結束行程',
'systemManager.ports.confirmTerminate': '向佔用該連接埠的行程 {{pid}} 傳送 SIGTERM?',
'systemManager.ports.forwardedMeta': '{{count}} 個已轉發',
'systemManager.ports.forward': '轉發至本機連接埠',
'systemManager.ports.stopForward': '停止連接埠轉發',
'systemManager.ports.forwardTitle': '轉發連接埠至本機',
'systemManager.ports.forwardDesc': '透過 SSH 將此遠端監聽連接埠轉發至本機連接埠。',
'systemManager.ports.forwardDescWithHost': '透過 SSH 將 {{host}} 上的此監聽連接埠轉發至本機連接埠。',
'systemManager.ports.forwardLocalPort': '本機連接埠',
'systemManager.ports.forwardBindAddress': '繫結位址',
'systemManager.ports.forwardAction': '開始轉發',
'systemManager.ports.forwarding': '轉發中…',
'systemManager.ports.forwardInvalidPort': '請輸入 1 到 65535 之間的有效連接埠號碼。',
'systemManager.ports.forwardInvalidBindAddress': '請輸入有效的繫結位址(例如 127.0.0.1 或 0.0.0.0)。',
'systemManager.ports.forwardPortInUse': '本機連接埠 {{port}} 已被「{{label}}」佔用。',
'systemManager.ports.forwardFailed': '啟動連接埠轉發失敗。',
'systemManager.ports.forwardStarted': '已開始轉發 {{local}} → {{remote}}',
'systemManager.ports.forwardStopped': '已停止轉發 {{local}}',
'systemManager.ports.copiedEndpoint': '已複製 {{endpoint}}',
'systemManager.ports.copyEndpointAria': '複製本機位址 {{endpoint}}',
'systemManager.ports.clickToCopy': '點擊複製本機位址',
'systemManager.services.unavailable': '此主機未偵測到 systemctl。',
'systemManager.services.loading': '正在載入 systemd 服務…',
@@ -14,6 +14,7 @@ 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': '請等待終端回到空白命令提示字元。',
@@ -7,12 +7,20 @@ test('plugin theme tokens come from the themed app surface style', () => {
assert.deepEqual(selectPluginThemeTokens({
'--background': '220 10% 10%',
'--foreground': '0 0% 98%',
'--card': '220 10% 12%',
'--primary': '210 90% 55%',
'--destructive': '0 84% 60%',
'--radius': '0.5rem',
'--font-mono': '"JetBrains Mono", monospace',
colorScheme: 'dark',
'--unknown-plugin-token': 'ignored',
}), {
'--background': '220 10% 10%',
'--foreground': '0 0% 98%',
'--card': '220 10% 12%',
'--primary': '210 90% 55%',
'--destructive': '0 84% 60%',
'--radius': '0.5rem',
'--font-mono': '"JetBrains Mono", monospace',
});
});
@@ -1,11 +1,26 @@
export const PLUGIN_THEME_TOKEN_NAMES = Object.freeze([
'--background',
'--foreground',
'--muted',
'--muted-foreground',
'--border',
'--card',
'--card-foreground',
'--popover',
'--popover-foreground',
'--primary',
'--primary-foreground',
'--secondary',
'--secondary-foreground',
'--muted',
'--muted-foreground',
'--accent',
'--accent-foreground',
'--destructive',
'--destructive-foreground',
'--border',
'--input',
'--ring',
'--radius',
'--font-sans',
'--font-mono',
] as const);
export function selectPluginThemeTokens(
+14 -5
View File
@@ -38,14 +38,23 @@ export class PluginViewSessions {
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
}).catch(() => dispose(true));
const imageCache = new Map<string, Promise<string>>();
return {
viewId: request.viewId,
scope: request.scopeId,
image: async (path: string) => {
if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable');
const result = await bridge.getPluginViewResource({ instanceId: id, path });
if (disposed) throw new Error('Plugin view closed');
return result.url;
image: (path: string) => {
if (disposed || !bridge.getPluginViewResource) return Promise.reject(new Error('Plugin image unavailable'));
const existing = imageCache.get(path);
if (existing) return existing;
const pending = bridge.getPluginViewResource({ instanceId: id, path }).then((result) => {
if (disposed) throw new Error('Plugin view closed');
return result.url;
}).catch((error) => {
if (imageCache.get(path) === pending) imageCache.delete(path);
throw error;
});
imageCache.set(path, pending);
return pending;
},
get idle() { return users === 0; },
getSnapshot: () => state,
@@ -2,6 +2,7 @@ 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];
@@ -20,10 +21,34 @@ function createHarness() {
return { changes, controller };
}
test('prompt host controller ignores the initial jumpserver prompt', () => {
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', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# ');
assert.deepEqual(changes, []);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname]]);
});
test('prompt host controller publishes a nested target and de-duplicates it', () => {
@@ -31,17 +56,18 @@ 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', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
});
test('prompt host controller clears the override when returning to the jumpserver', () => {
test('prompt host controller observes the original host when returning from a target', () => {
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', null],
['ssh-1', getSession('ssh-1').hostname],
]);
});
@@ -50,26 +76,28 @@ 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', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['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, []);
assert.deepEqual(changes, initialChanges);
});
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, []);
assert.deepEqual(changes, initialChanges);
});
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' | 'hostname'> | undefined;
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol'> | undefined;
onChange: (sessionId: string, hostname: string | null) => void;
maxTailChars?: number;
};
@@ -22,20 +22,18 @@ 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(), ...baselines.keys(), ...published.keys()]) {
for (const sessionId of [...tails.keys(), ...published.keys()]) {
if (!validSessionIds.has(sessionId)) {
forgetSession(sessionId);
}
@@ -65,19 +63,8 @@ export function createPromptHostnameSessionSignalController({
const detectedKey = normalizedHostname(detected);
if (!detectedKey) return;
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;
}
// Observe the prompt, not whether its hostname matches an IP or DNS alias.
// The domain title policy decides if this presentation is shown.
if (published.get(sessionId) === detectedKey) return;
published.set(sessionId, detectedKey);
onChange(sessionId, detected);
@@ -10,6 +10,89 @@ 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;
@@ -89,9 +172,11 @@ 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(); });
+22 -11
View File
@@ -1,5 +1,6 @@
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';
@@ -7,7 +8,8 @@ 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 [confirmed, setConfirmed] = useState(false);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const observedCwd = terminalCwdStore.getCwd(sessionId);
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
@@ -16,7 +18,15 @@ export function useComposeDirectoryPicker(sessionId: string) {
const [query, setQuery] = useState('');
const [showHidden, setShowHidden] = useState(false);
const [entries, setEntries] = useState<DirectoryEntry[]>([]);
const [home, setHome] = useState<string | null>(null);
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 [loading, setLoading] = useState(false);
const [pending, setPending] = useState(false);
const listingBase = useRef<string | null>(null);
@@ -35,25 +45,25 @@ export function useComposeDirectoryPicker(sessionId: string) {
const stopObserving = observeTerminalDirectory(sessionId);
lifetime.current = new AbortController();
sending.current = false;
setConfirmed(false); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
setConfirmation(null); 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) { setConfirmed(true); setHome(nextHome); }
if (generation.current === id) { setConfirmation({ sessionId, controller }); 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]);
}, [sessionId, controller, report, setHome]);
const refresh = useCallback(async () => {
if (!controller) { setError('unavailable'); return; }
const id = generation.current;
setError(null);
try { await controller.refresh(); if (generation.current === id) setConfirmed(true); }
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
}, [controller, report]);
}, [controller, report, sessionId]);
const load = useCallback(async () => {
if (!controller || !cwd) return;
@@ -76,7 +86,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]);
}, [controller, cwd, report, sessionId, setHome]);
useEffect(() => {
if (!cwd) {
@@ -87,7 +97,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
}
if (open) { setQuery(''); void load(); }
return () => { read.current?.abort(); };
}, [open, load, cwd]);
}, [open, load, cwd, setHome]);
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
@@ -109,8 +119,9 @@ 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 === 'nonFilesystem';
return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
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,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
+4 -1
View File
@@ -23,6 +23,8 @@ export type ChainProgress = {
currentHop: number;
totalHops: number;
currentHostLabel: string;
/** host:port of the hop being connected; absent from older progress events. */
currentHostAddress?: string;
connectionPhase: string;
} | null;
@@ -139,13 +141,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
// Subscribe to chain progress for the active attempt.
useEffect(() => {
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError) => {
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError, address) => {
if (sessionId !== sessionIdRef.current) return;
if (total > 1) {
setChainProgress({
currentHop: hop,
totalHops: total,
currentHostLabel: label,
currentHostAddress: address,
connectionPhase: phase,
});
}
+9 -4
View File
@@ -11,7 +11,11 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
}) {
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const [state, setState] = useState<{ key: string; snapshot: PluginViewSnapshot }>({ key: '', snapshot: initial() });
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
image?: (path: string) => Promise<string>;
}>({ key: '', snapshot: initial() });
const [hidden, setHidden] = useState(false);
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
@@ -22,17 +26,18 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) });
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot }); if (snapshot.error) unavailableRef.current(); };
const stop = session.subscribe(update); update(); setHidden(false);
sessionRef.current = { key, send: session.send, image: session.image };
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
} catch { unavailableRef.current(); }
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
const loadImage = useCallback((path: string) => {
const fallbackLoadImage = useCallback((path: string) => {
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const loadImage = active && state.key === key && state.image ? state.image : fallbackLoadImage;
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
@@ -0,0 +1,125 @@
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',
);
});
@@ -0,0 +1,70 @@
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,
};
}
+68 -9
View File
@@ -24,9 +24,17 @@ type Review = {
completionToken?: string;
};
function isHostActionRequestKind(kind: string): boolean {
return kind.startsWith('vault.')
|| kind === 'network.stream.connectViaHost'
|| kind === 'network.stream.confirm'
|| kind === 'network.stream.tlsConfirm';
}
export function usePluginHostActions() {
const [review, setReview] = useState<Review | null>(null);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [remember, setRemember] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const current = useRef<Review | null>(null);
@@ -44,9 +52,19 @@ export function usePluginHostActions() {
const assertCurrent = useCallback((entry: Review) => {
if (current.current !== entry || Date.now() >= entry.prompt.expiresAt) throw new Error('Host action expired');
if (entry.prompt.request.kind === 'network.stream.confirm' || entry.prompt.request.kind === 'network.stream.tlsConfirm') {
const lock = getAppAppLockRuntime();
if (lock && lock.initialized && lock.locked) throw new Error('App is locked');
return;
}
const vault = getVault();
const target = entry.prompt.vaultTarget;
if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) throw new Error('Selected host changed');
if (entry.prompt.durableHostId) {
const liveHost = vault.hosts.find((candidate) => candidate.id === entry.prompt.durableHostId);
if (!liveHost || liveHost !== entry.host) throw new Error('Saved SSH host changed or was removed');
} else if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) {
throw new Error('Selected host changed');
}
if ((entry.prompt.request.kind === 'vault.requestConnect' || entry.prompt.request.kind === 'network.stream.connectViaHost') && (vault.groupConfigs !== entry.groups || vault.snippets !== entry.snippets)) {
throw new Error('Saved connection settings changed');
}
@@ -71,7 +89,7 @@ export function usePluginHostActions() {
assertCurrent(entry);
const request = entry.prompt.request;
const target = entry.prompt.vaultTarget;
if (request.kind === 'network.stream.connectViaHost' && target && entry.host) {
if (request.kind === 'network.stream.connectViaHost' && entry.host && (target || entry.prompt.durableHostId)) {
const vault = getVault();
const settings = getAppSettingsRuntime();
if (!settings || !bridge.openPluginHostStream) throw new Error('Host stream unavailable');
@@ -83,7 +101,15 @@ export function usePluginHostActions() {
|| latest.hosts !== vault.hosts || latest.knownHosts !== vault.knownHosts || getAppSettingsRuntime()?.terminalSettings !== settings.terminalSettings) throw new Error('Connection settings changed');
};
assertPrepared();
await executePluginHostAction({ kind: 'connect', target }, {
if (entry.prompt.durableHostId) {
entry.claimed = true;
await bridge.openPluginHostStream!({
response: { requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' },
connectionOptions,
});
return;
}
await executePluginHostAction({ kind: 'connect', target: target! }, {
getVault, resources: resources.current, assertCurrent: assertPrepared,
authorizeCommit: async () => { assertPrepared(); },
connect: async () => {
@@ -126,12 +152,35 @@ export function usePluginHostActions() {
const unsubscribe = bridge.onPluginInteraction((event) => {
if ('closed' in event) {
if (current.current?.prompt.requestId !== event.requestId) return;
current.current = null; setReview(null); setBusy(false); responding.current = false;
current.current = null; setReview(null); setRemember(false); setBusy(false); responding.current = false;
return;
}
if (!event.request.kind.startsWith('vault.') && event.request.kind !== 'network.stream.connectViaHost') return;
if (!isHostActionRequestKind(event.request.kind)) return;
const prompt = event as VaultHostPrompt;
try {
if (prompt.request.kind === 'network.stream.confirm' || prompt.request.kind === 'network.stream.tlsConfirm') {
const entry: Review = {
prompt, candidates: [], candidateRevisions: new Map(), customGroups: [],
groups: [], snippets: [], managedSources: [], scriptsRun: false, claimed: false,
};
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(false); setError(false); responding.current = false;
setReview(entry);
return;
}
if (prompt.phase === 'commit' && prompt.autoCommit && prompt.durableHostId && prompt.request.kind === 'network.stream.connectViaHost') {
const vault = getVault();
const host = vault.hosts.find((candidate) => candidate.id === prompt.durableHostId);
if (!host) throw new Error('Saved SSH host no longer exists');
const entry: Review = {
prompt, candidates: [], candidateRevisions: new Map(), customGroups: vault.customGroups,
host, groups: vault.groupConfigs, snippets: vault.snippets, managedSources: vault.managedSources,
scriptsRun: false, claimed: false,
};
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(true); setError(false); responding.current = false;
setReview(null);
void execute(entry);
return;
}
if (prompt.phase === 'commit') {
const entry = current.current;
if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable');
@@ -150,7 +199,10 @@ export function usePluginHostActions() {
scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false,
claimed: false,
};
current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
const defaultRemember = prompt.request.kind === 'network.stream.connectViaHost'
&& 'durable' in prompt.request
&& prompt.request.durable === true;
current.current = entry; setSelectedIds([]); setRemember(defaultRemember); setBusy(false); setError(false); responding.current = false;
if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') {
setReview(null);
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken,
@@ -168,7 +220,7 @@ export function usePluginHostActions() {
};
}, [execute, fail, getVault]);
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => {
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
const entry = current.current;
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
@@ -181,17 +233,24 @@ export function usePluginHostActions() {
resources.current.resolve(id, revision);
return resources.current.metadata(id);
}) : undefined;
const includeRemember = action === 'submit' && (
request.kind === 'network.stream.connectViaHost'
|| request.kind === 'network.stream.confirm'
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
} catch { await fail(entry); }
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, fail, selectedIds]);
}, [assertCurrent, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, busy, error, respond };
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
@@ -0,0 +1,317 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { act } from 'react';
import { create, type ReactTestRenderer } from 'react-test-renderer';
import { normalizeTerminalSettings } from '../../domain/models/terminal.ts';
import type { Host, PortForwardingRule } from '../../domain/models.ts';
import type { ListeningPortInfo } from '../../domain/systemManager/types.ts';
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys.ts';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge.ts';
import { stopAllPortForwards } from '../../infrastructure/services/portForwardingService.ts';
import type { TerminalSession } from '../../types.ts';
import { resetPortForwardingStateForTests } from './usePortForwardingState.ts';
import {
resetEphemeralQuickForwardsForTests,
useQuickPortForwarding,
type QuickPortForwardingContext,
} from './useQuickPortForwarding.ts';
function installDomGlobals() {
const previous = new Map<string, PropertyDescriptor | undefined>();
const setGlobal = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
const backing = new Map<string, string>();
const storage: Storage = {
get length() { return backing.size; },
clear() { backing.clear(); },
getItem(key) { return backing.get(key) ?? null; },
key(index) { return Array.from(backing.keys())[index] ?? null; },
removeItem(key) { backing.delete(key); },
setItem(key, value) { backing.set(key, value); },
};
setGlobal('IS_REACT_ACT_ENVIRONMENT', true);
setGlobal('localStorage', storage);
setGlobal('window', {
addEventListener() {},
removeEventListener() {},
dispatchEvent() { return true; },
});
setGlobal('document', {
visibilityState: 'visible',
hidden: false,
addEventListener() {},
removeEventListener() {},
});
return {
backing,
restore() {
for (const [key, desc] of previous.entries()) {
if (desc) Object.defineProperty(globalThis, key, desc);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
const savedHost: Host = {
id: 'host-saved',
label: 'Prod API',
hostname: '10.0.0.10',
port: 22,
username: 'ubuntu',
tags: [],
os: 'linux',
};
const sshSession: TerminalSession = {
id: 'session-1',
hostId: savedHost.id,
hostLabel: savedHost.label,
username: savedHost.username,
hostname: savedHost.hostname,
status: 'connected',
protocol: 'ssh',
};
const listeningPort: ListeningPortInfo = {
id: 'tcp|*|5432|100',
protocol: 'tcp',
address: '*',
port: 5432,
pid: 100,
processName: 'postgres',
};
function makeContext(overrides: Partial<QuickPortForwardingContext> = {}): QuickPortForwardingContext {
return {
session: sshSession,
sessionHost: savedHost,
vaultHosts: [savedHost],
effectiveHosts: [savedHost],
keys: [],
identities: [],
knownHosts: [],
terminalSettings: normalizeTerminalSettings(),
...overrides,
};
}
test('useQuickPortForwarding creates, reuses, stops, and rolls back failed new rules for saved hosts', async (t) => {
const env = installDomGlobals();
resetPortForwardingStateForTests();
resetEphemeralQuickForwardsForTests();
const statusHandlers = new Map<string, (status: PortForwardingRule['status'], error?: string | null) => void>();
let failNextStart: string | null = null;
const startedPayloads: Array<Record<string, unknown>> = [];
const stoppedRuleIds: string[] = [];
t.mock.method(netcattyBridge, 'get', () => ({
getPortForwardSnapshot: async () => ({ epoch: 'e1', revision: 0, records: [] }),
subscribePortForwardRuntime: async () => ({ epoch: 'e1', revision: 0, records: [] }),
onPortForwardRuntime: () => () => undefined,
unsubscribePortForwardRuntime: async () => undefined,
onPortForwardStatus: (tunnelId: string, cb: (status: PortForwardingRule['status'], error?: string | null) => void) => {
statusHandlers.set(tunnelId, cb);
return () => { statusHandlers.delete(tunnelId); };
},
startPortForward: async (options: Record<string, unknown>) => {
startedPayloads.push(options);
if (failNextStart) {
return { success: false, error: failNextStart };
}
const tunnelId = String(options.tunnelId);
statusHandlers.get(tunnelId)?.('active');
return { success: true, tunnelId, localPort: options.localPort };
},
stopPortForwardByRuleId: async (ruleId: string) => {
stoppedRuleIds.push(ruleId);
return { stopped: 1, failed: 0, errors: [] };
},
stopAllPortForwards: async () => ({ success: true }),
}));
let api!: ReturnType<typeof useQuickPortForwarding>;
const ctx = makeContext();
function Probe() {
api = useQuickPortForwarding(ctx);
return null;
}
let root: ReactTestRenderer | undefined;
try {
await act(async () => {
root = create(<Probe />);
});
assert.equal(api.canForward, true);
// 1. Failed start of a brand-new rule rolls it back so Vault stays clean.
failNextStart = 'listen EADDRINUSE: address already in use 127.0.0.1:5432';
let failedResult!: Awaited<ReturnType<typeof api.startQuickForward>>;
await act(async () => {
failedResult = await api.startQuickForward({
port: listeningPort,
localPort: 5432,
bindAddress: '127.0.0.1',
});
});
assert.equal(failedResult.success, false);
assert.match(failedResult.error ?? '', /EADDRINUSE/);
assert.equal(api.allRules.length, 0);
// 2. Successful start persists a local rule and marks it active.
failNextStart = null;
let startedResult!: Awaited<ReturnType<typeof api.startQuickForward>>;
await act(async () => {
startedResult = await api.startQuickForward({
port: listeningPort,
localPort: 15432,
bindAddress: '127.0.0.1',
});
});
assert.equal(startedResult.success, true);
assert.equal(api.allRules.length, 1);
const createdRuleId = startedResult.rule!.id;
assert.equal(api.allRules[0].status, 'active');
assert.equal(api.allRules[0].localPort, 15432);
assert.equal(api.allRules[0].remoteHost, '127.0.0.1');
assert.equal(api.allRules[0].remotePort, 5432);
assert.equal(startedPayloads[1]?.reuseTransport, true);
assert.ok(env.backing.get(STORAGE_KEY_PORT_FORWARDING)?.includes(createdRuleId));
// 3. Stop transitions rule back to inactive.
await act(async () => {
const stopRes = await api.stopQuickForward(api.allRules[0]);
assert.equal(stopRes.success, true);
});
assert.ok(stoppedRuleIds.includes(createdRuleId));
assert.equal(api.allRules[0].status, 'inactive');
// 4. Starting again with the same localPort + bindAddress reuses the rule without duplicates.
let restartedResult!: Awaited<ReturnType<typeof api.startQuickForward>>;
await act(async () => {
restartedResult = await api.startQuickForward({
port: listeningPort,
localPort: 15432,
bindAddress: '127.0.0.1',
});
});
assert.equal(restartedResult.success, true);
assert.equal(restartedResult.rule?.id, createdRuleId);
assert.equal(api.allRules.length, 1);
// 5. Failure on a reused pre-existing rule must NOT delete it.
await act(async () => {
await api.stopQuickForward(api.allRules[0]);
});
failNextStart = 'listen EADDRINUSE';
await act(async () => {
const res = await api.startQuickForward({
port: listeningPort,
localPort: 15432,
bindAddress: '127.0.0.1',
});
assert.equal(res.success, false);
});
assert.equal(api.allRules.length, 1);
assert.equal(api.allRules[0].id, createdRuleId);
} finally {
await stopAllPortForwards();
await act(async () => {
root?.unmount();
});
resetPortForwardingStateForTests();
resetEphemeralQuickForwardsForTests();
env.restore();
}
});
test('useQuickPortForwarding keeps unsaved quick-connect tunnels in memory without polluting localStorage', async (t) => {
const env = installDomGlobals();
resetPortForwardingStateForTests();
resetEphemeralQuickForwardsForTests();
const statusHandlers = new Map<string, (status: PortForwardingRule['status'], error?: string | null) => void>();
t.mock.method(netcattyBridge, 'get', () => ({
getPortForwardSnapshot: async () => ({ epoch: 'e1', revision: 0, records: [] }),
subscribePortForwardRuntime: async () => ({ epoch: 'e1', revision: 0, records: [] }),
onPortForwardRuntime: () => () => undefined,
unsubscribePortForwardRuntime: async () => undefined,
onPortForwardStatus: (tunnelId: string, cb: (status: PortForwardingRule['status'], error?: string | null) => void) => {
statusHandlers.set(tunnelId, cb);
return () => { statusHandlers.delete(tunnelId); };
},
startPortForward: async (options: Record<string, unknown>) => {
const tunnelId = String(options.tunnelId);
statusHandlers.get(tunnelId)?.('active');
return { success: true, tunnelId, localPort: options.localPort };
},
stopPortForwardByRuleId: async () => ({ stopped: 1, failed: 0, errors: [] }),
stopAllPortForwards: async () => ({ success: true }),
}));
const quickHost: Host = {
...savedHost,
id: 'quick-connect-1',
ephemeral: true,
};
const quickSession: TerminalSession = {
...sshSession,
hostId: quickHost.id,
};
let api!: ReturnType<typeof useQuickPortForwarding>;
const ctx = makeContext({
session: quickSession,
sessionHost: quickHost,
vaultHosts: [],
effectiveHosts: [],
});
function Probe() {
api = useQuickPortForwarding(ctx);
return null;
}
let root: ReactTestRenderer | undefined;
try {
await act(async () => {
root = create(<Probe />);
});
assert.equal(api.canForward, true);
await act(async () => {
const res = await api.startQuickForward({
port: listeningPort,
localPort: 25432,
bindAddress: '127.0.0.1',
});
assert.equal(res.success, true);
});
assert.equal(api.allRules.length, 1);
assert.equal(api.allRules[0].status, 'active');
assert.equal(env.backing.get(STORAGE_KEY_PORT_FORWARDING), undefined);
await act(async () => {
const stopRes = await api.stopQuickForward(api.allRules[0]);
assert.equal(stopRes.success, true);
});
assert.equal(api.allRules.length, 0);
} finally {
await stopAllPortForwards();
await act(async () => {
root?.unmount();
});
resetPortForwardingStateForTests();
resetEphemeralQuickForwardsForTests();
env.restore();
}
});
+303
View File
@@ -0,0 +1,303 @@
import { useCallback, useMemo, useState, useSyncExternalStore } from 'react';
import { isSavedVaultHost } from '../../domain/ephemeralHosts';
import type {
Host,
Identity,
KnownHost,
PortForwardingRule,
SSHKey,
TerminalSettings,
} from '../../domain/models';
import { isPortForwardingAutoReconnectEnabled } from '../../domain/portForwardingReconnect';
import {
buildQuickForwardRuleLabel,
canQuickForwardSession,
findExactReusableForwardRule,
resolveForwardRemoteHost,
} from '../../domain/systemManager/portForwardQuick';
import type { ListeningPortInfo } from '../../domain/systemManager/types';
import {
clearReconnectTimer,
startPortForward,
stopPortForward,
} from '../../infrastructure/services/portForwardingService';
import type { TerminalSession } from '../../types';
import { usePortForwardingState } from './usePortForwardingState';
export interface QuickPortForwardingContext {
session: TerminalSession | null;
sessionHost: Host | null;
/** Authenticated session host override (e.g. interactive password/user). */
authHost?: Host | null;
/** Saved vault hosts, used to determine if rules should be persisted to Vault. */
vaultHosts: Host[];
/** Materialized hosts (group defaults + proxy profiles) for jump-host resolution. */
effectiveHosts: Host[];
keys: SSHKey[];
identities: Identity[];
knownHosts: KnownHost[];
terminalSettings: TerminalSettings;
}
export interface StartQuickForwardParams {
port: ListeningPortInfo;
localPort: number;
bindAddress: string;
}
export interface StartQuickForwardResult {
success: boolean;
rule?: PortForwardingRule;
error?: string;
}
// In-memory store for quick-forwards launched from unsaved / ephemeral sessions
// so they never write dangling hostId references to localStorage or cloud sync.
const ephemeralRulesMap = new Map<string, PortForwardingRule>();
let ephemeralRulesSnapshot: PortForwardingRule[] = [];
const ephemeralListeners = new Set<() => void>();
function notifyEphemeralListeners(): void {
ephemeralRulesSnapshot = Array.from(ephemeralRulesMap.values());
ephemeralListeners.forEach((listener) => listener());
}
function subscribeEphemeralRules(listener: () => void): () => void {
ephemeralListeners.add(listener);
return () => {
ephemeralListeners.delete(listener);
};
}
function getEphemeralRulesSnapshot(): PortForwardingRule[] {
return ephemeralRulesSnapshot;
}
function upsertEphemeralRule(rule: PortForwardingRule): void {
ephemeralRulesMap.set(rule.id, rule);
notifyEphemeralListeners();
}
function updateEphemeralRuleStatus(
ruleId: string,
status: PortForwardingRule['status'],
error?: string,
): void {
const existing = ephemeralRulesMap.get(ruleId);
if (!existing) return;
if (status === 'inactive') {
ephemeralRulesMap.delete(ruleId);
} else {
ephemeralRulesMap.set(ruleId, {
...existing,
status,
error,
lastUsedAt: status === 'active' ? Date.now() : existing.lastUsedAt,
});
}
notifyEphemeralListeners();
}
function deleteEphemeralRule(ruleId: string): void {
if (!ephemeralRulesMap.delete(ruleId)) return;
notifyEphemeralListeners();
}
export function resetEphemeralQuickForwardsForTests(): void {
ephemeralRulesMap.clear();
ephemeralRulesSnapshot = [];
ephemeralListeners.clear();
}
export function useQuickPortForwarding(context?: QuickPortForwardingContext) {
const {
rules: persistedRules,
addRule,
deleteRule,
startTunnel,
stopTunnel,
} = usePortForwardingState();
const ephemeralRules = useSyncExternalStore(
subscribeEphemeralRules,
getEphemeralRulesSnapshot,
getEphemeralRulesSnapshot,
);
const [pendingRuleIds, setPendingRuleIds] = useState<ReadonlySet<string>>(() => new Set());
const targetHost = context?.authHost ?? context?.sessionHost ?? null;
const hostId = context?.sessionHost?.id;
const canForward = useMemo(
() => Boolean(context) && canQuickForwardSession(targetHost, context?.session),
[context, targetHost],
);
const canPersistRule = useMemo(() => {
if (!context?.sessionHost || !isSavedVaultHost(context.sessionHost)) return false;
return context.vaultHosts.some((candidate) => candidate.id === context.sessionHost!.id);
}, [context]);
const allRules = useMemo(
() => (ephemeralRules.length > 0 ? [...persistedRules, ...ephemeralRules] : persistedRules),
[ephemeralRules, persistedRules],
);
const markPending = useCallback((ruleId: string, pending: boolean) => {
setPendingRuleIds((prev) => {
const has = prev.has(ruleId);
if (pending === has) return prev;
const next = new Set(prev);
if (pending) next.add(ruleId);
else next.delete(ruleId);
return next;
});
}, []);
const startQuickForward = useCallback(
async ({
port,
localPort,
bindAddress,
}: StartQuickForwardParams): Promise<StartQuickForwardResult> => {
if (!context || !targetHost || !hostId || !canForward) {
return { success: false, error: 'Port forwarding is unavailable for this session.' };
}
const remoteHost = resolveForwardRemoteHost(port);
const label = buildQuickForwardRuleLabel(
context.sessionHost?.label || context.session?.hostLabel || targetHost.hostname,
port,
localPort,
remoteHost,
);
if (canPersistRule) {
const reusableRule = findExactReusableForwardRule(persistedRules, {
hostId,
remoteHost,
remotePort: port.port,
localPort,
bindAddress,
});
const rule = reusableRule ?? addRule({
label,
type: 'local',
localPort,
bindAddress,
remoteHost,
remotePort: port.port,
hostId,
autoStart: false,
});
const createdNewRule = !reusableRule;
markPending(rule.id, true);
try {
const result = await startTunnel(
rule,
targetHost,
context.effectiveHosts,
context.keys,
context.identities,
undefined,
isPortForwardingAutoReconnectEnabled(rule),
context.terminalSettings,
context.knownHosts,
);
if (!result.success) {
if (createdNewRule) {
deleteRule(rule.id);
}
return { success: false, error: result.error };
}
return { success: true, rule };
} finally {
markPending(rule.id, false);
}
}
// Ephemeral / unsaved quick-connect session: run tunnel in-memory without
// persisting a dangling hostId into Vault or cloud sync.
const ephemeralRule: PortForwardingRule = {
id: crypto.randomUUID(),
label,
type: 'local',
localPort,
bindAddress,
remoteHost,
remotePort: port.port,
hostId,
autoStart: false,
status: 'connecting',
createdAt: Date.now(),
};
upsertEphemeralRule(ephemeralRule);
markPending(ephemeralRule.id, true);
try {
const result = await startPortForward(
ephemeralRule,
targetHost,
context.effectiveHosts,
context.keys,
context.identities,
(status, error) => {
updateEphemeralRuleStatus(ephemeralRule.id, status, error);
},
false,
context.terminalSettings,
context.knownHosts,
);
if (!result.success) {
deleteEphemeralRule(ephemeralRule.id);
return { success: false, error: result.error };
}
return { success: true, rule: ephemeralRule };
} finally {
markPending(ephemeralRule.id, false);
}
},
[
addRule,
canForward,
canPersistRule,
context,
deleteRule,
hostId,
markPending,
persistedRules,
startTunnel,
targetHost,
],
);
const stopQuickForward = useCallback(
async (rule: PortForwardingRule): Promise<{ success: boolean; error?: string }> => {
markPending(rule.id, true);
try {
if (ephemeralRulesMap.has(rule.id)) {
clearReconnectTimer(rule.id);
const result = await stopPortForward(rule.id, (status, error) => {
updateEphemeralRuleStatus(rule.id, status, error);
});
if (result.success) {
deleteEphemeralRule(rule.id);
}
return result;
}
return await stopTunnel(rule.id);
} finally {
markPending(rule.id, false);
}
},
[markPending, stopTunnel],
);
return {
canForward,
hostId,
allRules,
pendingRuleIds,
startQuickForward,
stopQuickForward,
};
}
+6 -12
View File
@@ -11,7 +11,7 @@ import {
publishTerminalSettingsSnapshot,
registerTerminalSettingsActions,
} from './terminalSettingsStore';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import {
normalizeAppLockTimeoutMinutes,
type AppLockSettings,
@@ -102,6 +102,7 @@ import {
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding as updateCustomKeyBindingRecord,
@@ -2100,17 +2101,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
}, []);
// Get merged key bindings (defaults + custom overrides)
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]);
const keyBindings = useMemo(
() => resolveKeyBindings(DEFAULT_KEY_BINDINGS, customKeyBindings),
[customKeyBindings],
);
// Update a single key binding
const updateKeyBinding = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => {
+1 -1
View File
@@ -454,7 +454,7 @@ export const useTerminalBackend = () => {
return bridge.getTelnetEchoMode(sessionId);
}, []);
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void) => {
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void) => {
const bridge = netcattyBridge.get();
return bridge?.onChainProgress?.(cb);
}, []);
@@ -5,8 +5,9 @@ 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 } from '../../domain/directoryPicker';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell.cjs';
export function useTerminalDirectorySession(options: {
sessionId: string;
@@ -33,7 +34,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') => {
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
if (!isCurrent()) return;
const controller = createTerminalDirectoryController({
sessionId,
@@ -41,11 +42,11 @@ export function useTerminalDirectorySession(options: {
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
encoding: host.sftpEncoding,
pathFlavor,
windowsShell,
windowsShell: integration,
}, isCurrent),
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, windowsShell ?? 'posix', pathFlavor),
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
isReady: () => live.current.isReady(),
publish: cwd => live.current.publish(cwd),
@@ -53,13 +54,18 @@ export function useTerminalDirectorySession(options: {
unregister = registerTerminalDirectory(sessionId, controller);
};
if (local) {
// 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 => {
void bridge.getAppInfo?.().then(async info => {
if ((info.platform === 'darwin' || info.platform === 'linux') && !windowsShell) register();
else if (info.platform === 'win32' && windowsShell) register('win32');
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');
}
}
}).catch(() => {});
} else register();
return () => { active = false; unregister(); };
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, windowsShell]);
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, host.localShell, shellType, windowsShell]);
}
+19 -2
View File
@@ -1,5 +1,5 @@
import React, { type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Undo2 } from 'lucide-react';
import { History, Plus, Undo2, X } 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';
@@ -89,6 +89,8 @@ 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,6 +99,8 @@ 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). */
@@ -177,6 +181,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
handleSteer,
handleStop,
handleModelCatalogRetry,
handleModelCatalogDismiss,
handleModelPickerOpen,
canSteer,
isSteering,
@@ -186,6 +191,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
providerDisplayName,
modelDisplayName,
modelCatalogWarning,
modelCatalogWarningDismissed = false,
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
@@ -425,7 +431,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 ? (
) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
<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 && (
@@ -436,6 +442,17 @@ 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">
+36 -1
View File
@@ -85,12 +85,14 @@ 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,
@@ -361,6 +363,11 @@ 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.
@@ -1352,6 +1359,11 @@ 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) => {
@@ -1367,7 +1379,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}
return null;
});
}, [t, buildExternalAgentRuntimeModelTarget]);
}, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]);
useEffect(() => {
if (!isVisible) return;
@@ -1390,6 +1402,9 @@ 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
@@ -1470,6 +1485,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
rearmModelCatalogWarning,
t,
]);
@@ -1625,6 +1641,14 @@ 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);
@@ -2530,6 +2554,17 @@ 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,6 +17,7 @@ import {
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
toSdkRuntimeModelCatalog,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
@@ -685,6 +686,26 @@ 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,6 +293,25 @@ 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
+63 -24
View File
@@ -25,10 +25,13 @@ 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 }> = ({ label, hint, enabled, disabled, onToggle }) => {
const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void; inheritance?: React.ReactNode }> = ({ label, hint, enabled, disabled, onToggle, inheritance }) => {
return (
<HostDetailsSettingRow label={label} hint={hint}>
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
<div className="flex items-center gap-2">
{inheritance}
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
</div>
</HostDetailsSettingRow>
);
};
@@ -54,6 +57,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
setShowAlgorithmOverrides,
chainedHosts,
hostChainInherited = false,
canRestoreHostChain = false,
setActiveSubPanel,
clearHostChain,
proxySummaryType,
@@ -64,6 +68,29 @@ 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";
@@ -227,9 +254,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="Mosh"
enabled={!!form.moshEnabled}
enabled={!!effectiveMoshEnabled}
inheritance={groupSettingControl("moshEnabled")}
onToggle={() => {
const enabling = !form.moshEnabled;
const enabling = !effectiveMoshEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -250,9 +278,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="EternalTerminal"
enabled={!!form.etEnabled}
enabled={!!effectiveEtEnabled}
inheritance={groupSettingControl("etEnabled")}
onToggle={() => {
const enabling = !form.etEnabled;
const enabling = !effectiveEtEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -265,7 +294,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
}
}}
/>
{form.etEnabled && (
{effectiveEtEnabled && (
<>
<HostDetailsSettingRow label={t("hostDetails.et.port")} hint={t("hostDetails.et.port.desc")}>
<Input
@@ -399,11 +428,12 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
icon={<Router size={14} className="text-muted-foreground" />}
title={t("hostDetails.section.deviceType")}
>
{isSshView && !form.moshEnabled && !form.etEnabled && (<>
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (<>
<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' && (
@@ -519,7 +549,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{isSshView && !form.moshEnabled && !form.etEnabled && (
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
<>
<ToggleRow
label={t("hostDetails.sshInputCompatibility")}
@@ -533,19 +563,23 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</>
)}
<HostDetailsSettingRow label={t("hostDetails.backspaceBehavior")}>
<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>
<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>
</HostDetailsSettingRow>
{form.backspaceBehavior === undefined && groupSettingControl("backspaceBehavior")}
</HostDetailsSection>
{/* Per-host keepalive override */}
@@ -675,9 +709,14 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
</div>
) : (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
</Badge>
<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>
)
}
>
@@ -0,0 +1,160 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
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 type { Host } from '../domain/models';
import HostDetailsPanel from './HostDetailsPanel';
import { HostDetailsConnectionSections } from './HostDetailsConnectionSections';
import { LocalShellHostDetailsPanel } from './LocalShellHostDetailsPanel';
import { SerialHostDetailsPanel } from './SerialHostDetailsPanel';
import { installDomEnvironment } from './test-support/renderReactDom';
import { AsidePanelFooter } from './ui/aside-panel';
import { Button } from './ui/button';
import { Combobox } from './ui/combobox';
import { Input } from './ui/input';
import { TooltipProvider } from './ui/tooltip';
type PanelKind = 'ssh' | 'local' | 'serial';
const host: Host = {
id: 'existing', label: 'Web', hostname: 'web.example.com', username: 'root',
password: 'test-password', authMethod: 'password', tags: [], os: 'linux',
protocol: 'ssh', group: 'prod / web',
};
async function withPanel(
kind: PanelKind,
initialData: Host | undefined,
run: (editor: {
renderer: ReactTestRenderer;
save: () => Promise<Host>;
created: string[];
}) => Promise<void>,
groups: string[] = [],
) {
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;
const created: string[] = [];
const common = { onSave: (value: Host) => { saved = value; }, onCancel() {}, groups, layout: 'inline' as const };
try {
await act(async () => {
renderer = create(<I18nProvider locale="en"><TooltipProvider>
{kind === 'ssh' ? <HostDetailsPanel {...common} initialData={initialData}
availableKeys={[]} identities={[]} terminalThemeId="default" terminalFontSize={14}
onCreateGroup={(path) => created.push(path)} />
: kind === 'local' ? <LocalShellHostDetailsPanel {...common} initialData={initialData} />
: <SerialHostDetailsPanel {...common} initialData={initialData!} />}
</TooltipProvider></I18nProvider>);
});
await run({
renderer: renderer!, created,
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 panel must call onSave');
return saved;
},
});
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
}
function groupPicker(renderer: ReactTestRenderer, kind: PanelKind) {
return renderer.root.findAllByType(Combobox).find((picker) =>
kind === 'ssh' ? picker.props.createText === 'Create Group' : picker.props.placeholder === 'Select Group',
)!;
}
for (const kind of ['ssh', 'local', 'serial'] as const) {
const initialData = { ...host, protocol: kind, ...(kind === 'serial' ? { hostname: 'COM3' } : {}) };
test(`${kind} Host Details keeps the exact stored group on a label-only edit`, async () => {
for (const group of ['prod / web', ' prod / web ', ' prod/web ']) {
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
await act(async () => {
renderer.root.findAllByType(Input).find((input) => input.props.value === host.label)!
.props.onChange({ target: { value: 'Updated label' } });
});
const saved = await save();
assert.equal(saved.label, 'Updated label');
assert.equal(saved.group, group);
});
}
});
test(`${kind} Host Details normalizes an explicitly selected trimmed-equivalent group`, async () => {
for (const group of [' prod/web ', ' prod / web ']) {
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
await act(async () => { groupPicker(renderer, kind).props.onValueChange(group.trim()); });
assert.equal((await save()).group, 'prod/web');
}, [group.trim()]);
}
});
test(`${kind} Host Details normalizes a changed group and allows clearing it`, async () => {
await withPanel(kind, initialData, async ({ renderer, save }) => {
const picker = groupPicker(renderer, kind);
await act(async () => { picker.props.onValueChange(host.group); });
assert.equal((await save()).group, host.group, 'reselecting the original group preserves it');
for (const [value, expected] of [[' stage / / web ', 'stage/web'], ['', '']]) {
await act(async () => { picker.props.onValueChange(value); });
assert.equal((await save()).group, expected);
}
});
});
}
for (const kind of ['ssh', 'local'] as const) {
test(`${kind} Host Details normalizes a new host's group`, async () => {
await withPanel(kind, undefined, async ({ renderer, save }) => {
await act(async () => {
if (kind === 'ssh') {
const { update } = renderer.root.findByType(HostDetailsConnectionSections).props;
update('hostname', 'web.example.com');
update('password', 'test-password');
}
groupPicker(renderer, kind).props.onValueChange('prod / web');
});
assert.equal((await save()).group, 'prod/web');
});
});
}
test('Create Group normalizes paths before creation and selection, including the Combobox follow-up', async () => {
const values = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
for (const groups of [[], ['prod/web']]) {
await withPanel('ssh', host, async ({ renderer, save, created }) => {
for (const value of values) {
const picker = groupPicker(renderer, 'ssh');
await act(async () => { picker.props.onCreateNew(value); });
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
// Combobox calls both callbacks with the original input when creating.
await act(async () => { picker.props.onValueChange(value); });
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
assert.equal((await save()).group, 'prod/web');
}
assert.deepEqual(created, groups.length ? [] : values.map(() => 'prod/web'));
await act(async () => { groupPicker(renderer, 'ssh').props.onCreateNew(' / / \\ '); });
assert.equal(created.length, groups.length ? 0 : values.length);
}, groups);
}
});
test('new-group sub-panel passes both parent and name through the same creation handler', () => {
const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8');
assert.match(source, /createAndSelectGroup\(`\$\{newGroupParent\}\/\$\{newGroupName\}`\)/);
assert.match(source, /onSave=\{handleCreateGroup\}/);
assert.match(source, /onCreateNew=\{createAndSelectGroup\}/);
});
+1 -1
View File
@@ -244,7 +244,7 @@ export const nextFormAfterClearHostChain = (
groupDefaults
&& applyGroupDefaults({ ...prev, hostChain: undefined }, groupDefaults).hostChain?.hostIds?.length,
);
if (prev.hostChain === undefined || groupWouldRestore) {
if (prev.hostChain === undefined || (groupWouldRestore && prev.hostChain.hostIds?.length)) {
return { ...prev, hostChain: { hostIds: [] } };
}
const { hostChain: _hostChain, ...rest } = prev;
@@ -0,0 +1,222 @@
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,9 +4,10 @@ import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { Host, Identity } from "../types.ts";
import type { Host, Identity, ProxyProfile } 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 +39,7 @@ const hostWithMissingProxyProfile: Host = {
const renderHostDetails = (
initialData: Host = hostWithMissingProxyProfile,
options: { identities?: Identity[] } = {},
options: { identities?: Identity[]; proxyProfiles?: ProxyProfile[] } = {},
) =>
renderToStaticMarkup(
React.createElement(
@@ -51,7 +52,7 @@ const renderHostDetails = (
initialData,
availableKeys: [],
identities: options.identities ?? [],
proxyProfiles: [],
proxyProfiles: options.proxyProfiles ?? [],
groups: [],
managedSources: [],
allTags: [],
@@ -102,6 +103,31 @@ 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,
@@ -718,6 +744,19 @@ 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(
@@ -769,6 +808,7 @@ 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", () => {
+35 -16
View File
@@ -10,6 +10,7 @@ import React, { useEffect, useMemo, useState, useCallback, useRef } from "react"
import { useI18n } from "../application/i18n/I18nProvider";
import { useApplicationBackend, type SshAgentStatus } from "../application/state/useApplicationBackend";
import { applyGroupDefaults, resolveGroupDefaults, resolveGroupTerminalThemeId } from "../domain/groupConfig";
import { normalizeGroupTargetPath, resolveHostGroupForSave } from "../domain/hostGroupPathMutations";
import {
getEffectiveHostDistro,
normalizePrimaryTelnetState,
@@ -343,6 +344,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [form.agentForwarding, form.identityAgent, form.hostname, form.port, form.username, checkSshAgent]);
const [groupInputValue, setGroupInputValue] = useState(form.group || "");
const originalGroupRef = useRef(initialData ? initialData.group || "" : undefined);
const createdGroupInputRef = useRef<string | null>(null);
const initialHostId = initialData?.id;
@@ -377,6 +380,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [initialData, snippets]);
useEffect(() => {
originalGroupRef.current = initialData ? initialData.group || "" : undefined;
createdGroupInputRef.current = null;
if (!initialData) return;
const normalized = normalizePrimaryTelnetState(initialData);
setForm(
@@ -436,7 +441,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [defaultGroup, form.group, groupConfigs, groupDefaults]);
const effectiveAuthHost = useMemo(
() => effectiveGroupDefaults ? applyGroupDefaults(form, effectiveGroupDefaults) : form,
() => applyGroupDefaults(form, effectiveGroupDefaults ?? {}),
[effectiveGroupDefaults, form],
);
@@ -507,7 +512,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";
@@ -928,7 +933,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}
const normalizedProxyConfig = proxySave.normalizedProxyConfig;
let finalLabel = form.label?.trim() || hostname;
const finalGroup = groupInputValue.trim() || form.group || "";
const finalGroup = resolveHostGroupForSave(
groupInputValue.trim() || form.group || "",
originalGroupRef.current,
groupInputValue !== originalGroupRef.current,
);
const targetManagedSource = managedSources
.filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/"))
@@ -1204,14 +1213,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}
};
const handleCreateGroup = () => {
if (!newGroupName.trim()) return;
const fullPath = newGroupParent
? `${newGroupParent}/${newGroupName.trim()}`
: newGroupName.trim();
onCreateGroup?.(fullPath);
const createAndSelectGroup = (value: string) => {
const fullPath = normalizeGroupTargetPath(value);
if (!fullPath) return;
createdGroupInputRef.current = value;
if (!groups.includes(fullPath)) onCreateGroup?.(fullPath);
setGroupInputValue(fullPath);
update("group", fullPath);
};
const handleCreateGroup = () => {
if (!newGroupName.trim()) return;
createAndSelectGroup(`${newGroupParent}/${newGroupName}`);
setNewGroupName("");
setNewGroupParent("");
setActiveSubPanel("none");
@@ -1224,6 +1237,9 @@ 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);
@@ -1563,16 +1579,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
options={groupOptions}
value={form.group || ""}
onValueChange={(val) => {
update("group", val);
setGroupInputValue(val);
// Creation also calls onValueChange with the raw input. Keep that
// path normalized while preserving a reselected legacy group.
const groupPath = val === createdGroupInputRef.current
? normalizeGroupTargetPath(val)
: resolveHostGroupForSave(val, originalGroupRef.current, val !== originalGroupRef.current);
createdGroupInputRef.current = null;
update("group", groupPath);
setGroupInputValue(groupPath);
}}
placeholder={t("hostDetails.group.placeholder")}
allowCreate={true}
onCreateNew={(val) => {
onCreateGroup?.(val);
update("group", val);
setGroupInputValue(val);
}}
onCreateNew={createAndSelectGroup}
createText="Create Group"
triggerClassName="flex-1 h-10"
/>
@@ -1734,6 +1752,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setShowAlgorithmOverrides={setShowAlgorithmOverrides}
chainedHosts={chainedHosts}
hostChainInherited={hostChainInherited}
canRestoreHostChain={canRestoreHostChain}
setActiveSubPanel={setActiveSubPanel}
clearHostChain={clearHostChain}
proxySummaryType={proxySummaryType}
+6 -4
View File
@@ -5,12 +5,13 @@
* into vault groups next to their SSH hosts (issue #3615).
*/
import { Save, TerminalSquare, X } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import React, { useMemo, useRef, useState } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import { useDiscoveredShells } from '../lib/useDiscoveredShells';
import { detectLocalOs } from '../lib/localShell';
import type { Host } from '../domain/models';
import { createLocalShellHost } from '../domain/localShellHost';
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
import { Button } from './ui/button';
import { Combobox, ComboboxOption } from './ui/combobox';
@@ -68,6 +69,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
const [group, setGroup] = useState(
initialData ? initialData.group ?? '' : defaultGroup ?? '',
);
const originalGroupRef = useRef(initialData ? initialData.group ?? '' : undefined);
const matchedShell = useMemo(
() => discoveredShells.find((candidate) => candidate.id === shell),
@@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
shellIcon: shellMeta?.icon,
startDir,
startupCommand,
// Save the controlled value directly: '' means the user explicitly
// cleared the group, which persists at the vault root.
group: group,
group,
tags: initialData?.tags,
notes: initialData?.notes,
});
// Apply after the factory's outer trim to retain unchanged legacy paths exactly.
host.group = resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current);
// On edits, merge over the existing host so fields this form does not
// expose (pinned, lastConnectedAt, order, ...) and the original
// creation timestamp survive a save.
+4 -2
View File
@@ -3,9 +3,10 @@
* A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel)
*/
import { Eye, EyeOff, Save, Tag, X } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import React, { useMemo, useRef, useState } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import type { GroupConfig, Host, SerialConfig, SerialFlowControl, SerialParity } from '../domain/models';
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
import {
resolveSerialBackspaceFormValue,
resolveSerialBackspaceOverrideOnSave,
@@ -97,6 +98,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
const [charset, setCharset] = useState(initialData.charset || 'UTF-8');
const [tags, setTags] = useState<string[]>(initialData.tags || []);
const [group, setGroup] = useState(initialData.group || '');
const originalGroupRef = useRef(initialData.group || '');
const [notes, setNotes] = useState(initialData.notes ?? '');
const handleSave = () => {
@@ -136,7 +138,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
? (passwordCleared ? undefined : password)
: (initialData.password ?? undefined),
tags,
group,
group: resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current),
charset,
serialConfig: config,
backspaceBehavior: undefined,
+1
View File
@@ -1020,6 +1020,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
currentHop: number;
totalHops: number;
currentHostLabel: string;
currentHostAddress?: string;
connectionPhase: string;
} | null>(null);
const [isConnectionAwaitingUserInput, setIsConnectionAwaitingUserInput] = useState(false);
+2
View File
@@ -203,6 +203,7 @@ function buildScriptSessionMeta(
}
const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
isVaultInitialized,
hosts,
portForwardingRules = [],
customGroups,
@@ -2876,6 +2877,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onToggleGlobalComposeSendTarget,
canUseGlobalBroadcast,
isComposeBarOpen,
isVaultInitialized,
keyBindings,
keys,
knownHosts,
+26 -2
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", () => {
test("workspace tabs resolve generated labels from live prompt hosts in all mode", () => {
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", () => {
publishSessionPromptHost("s1", "target-a");
publishSessionPromptHost("s2", "target-b");
assert.equal(
resolveWorkspaceTopTabLabel(workspace, sessions),
resolveWorkspaceTopTabLabel(workspace, sessions, "all"),
"target-a/target-b",
);
@@ -103,6 +103,30 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => {
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: "" }),
+11 -3
View File
@@ -1,9 +1,17 @@
import React, { Suspense } from 'react';
import type { PluginHostDrawnPageProps } from './PluginHostDrawnPage';
const PluginHostDrawnPageImpl = React.lazy(() =>
import('./PluginHostDrawnPage').then((module) => ({ default: module.PluginHostDrawnPage })),
);
let preloadPromise: Promise<unknown> | null = null;
const loadPluginHostDrawnPage = () => {
preloadPromise ??= import('./PluginHostDrawnPage').then((module) => ({ default: module.PluginHostDrawnPage }));
return preloadPromise as Promise<{ default: typeof import('./PluginHostDrawnPage').PluginHostDrawnPage }>;
};
export function preloadPluginHostDrawnPage(): void {
void loadPluginHostDrawnPage().catch(() => { preloadPromise = null; });
}
const PluginHostDrawnPageImpl = React.lazy(loadPluginHostDrawnPage);
/**
* Lazy boundary for host-drawn plugin views so css-tree, mdn-data, and
@@ -3,18 +3,23 @@ import {
Box,
Code,
Command,
Database,
FileText,
Folder,
Globe,
HardDrive,
Key,
Layers,
LayoutPanelLeft,
List,
Network,
Palette,
Play,
Puzzle,
Server,
Settings,
Shield,
Sparkles,
Table,
Terminal,
Wrench,
@@ -30,17 +35,22 @@ const THEME_ICONS: Readonly<Record<string, LucideIcon>> = Object.freeze({
box: Box,
code: Code,
command: Command,
database: Database,
file: FileText,
folder: Folder,
globe: Globe,
'hard-drive': HardDrive,
key: Key,
layers: Layers,
'layout-panel': LayoutPanelLeft,
list: List,
network: Network,
palette: Palette,
play: Play,
server: Server,
settings: Settings,
shield: Shield,
sparkles: Sparkles,
table: Table,
terminal: Terminal,
wrench: Wrench,
+89 -3
View File
@@ -15,13 +15,27 @@ export function PluginHostActionHost() {
const request = entry.prompt.request;
const selection = request.kind === 'vault.selectHosts';
const stream = request.kind === 'network.stream.connectViaHost';
const directStreamConfirm = request.kind === 'network.stream.confirm';
const tlsConfirm = request.kind === 'network.stream.tlsConfirm';
const connection = request.kind === 'vault.requestConnect' || stream;
const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined;
const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined;
const dialogTitle = selection
? t('plugins.hostActions.select')
: directStreamConfirm
? 'Confirm Network Connection'
: tlsConfirm
? 'Verify TLS Certificate'
: connection
? t('plugins.hostActions.connect')
: entry.host
? t('plugins.hostActions.edit')
: t('plugins.hostActions.create');
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
<DialogContent className={selection ? 'max-w-md h-[min(85vh,640px)] flex flex-col p-0 gap-0 overflow-hidden' : 'sm:max-w-[560px] max-h-[85vh] overflow-y-auto'} hideCloseButton>
<DialogHeader className={selection ? 'px-4 pt-4 pb-2 shrink-0 border-b border-border/60' : undefined}>
<DialogTitle>{t(selection ? 'plugins.hostActions.select' : connection ? 'plugins.hostActions.connect' : entry.host ? 'plugins.hostActions.edit' : 'plugins.hostActions.create')}</DialogTitle>
<DialogTitle>{dialogTitle}</DialogTitle>
<DialogDescription className="break-all">{entry.prompt.pluginId} · {entry.prompt.pluginVersion}</DialogDescription>
</DialogHeader>
{selection ? <>
@@ -29,17 +43,89 @@ export function PluginHostActionHost() {
<p className="px-4 pt-2 text-sm font-medium break-words">{request.title}</p>
{state.selectedIds.length > 50 && <p role="alert" className="px-4 text-sm text-destructive">{t('plugins.hostActions.selectionLimit')}</p>}
<SelectHostPanelContent hosts={entry.candidates} customGroups={entry.customGroups} selectedHostIds={state.selectedIds} multiSelect className="flex-1 min-h-0" confirmDisabled={state.busy || state.selectedIds.length > 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} />
</> : connection && effective ? <>
</> : directStreamConfirm ? <div className="space-y-3">
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1">
<p className="text-xs text-muted-foreground">Destination Endpoint</p>
<p className="font-mono text-sm font-medium break-all">{request.endpoint}</p>
<p className="text-xs text-muted-foreground">
{request.transport.toUpperCase()} · {request.host}:{request.port}
{request.isLocal ? ' · Local / Private Network' : ''}
</p>
</div>
<p className="text-xs text-muted-foreground">
This plugin is requesting a direct {request.transport.toUpperCase()} connection to this endpoint. Netcatty&apos;s internal control ports remain blocked.
</p>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Remember for this endpoint</span>
</label>
</div> : tlsConfirm ? <div className="space-y-3">
<p className="text-sm text-amber-600 dark:text-amber-400 font-medium">
The server certificate could not be verified ({request.reason}).
</p>
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1.5 text-xs">
<div>
<span className="text-muted-foreground">Endpoint: </span>
<span className="font-mono break-all">{request.endpoint}</span>
</div>
{request.subject && <div>
<span className="text-muted-foreground">Subject: </span>
<span className="font-mono break-all">{request.subject}</span>
</div>}
{request.issuer && <div>
<span className="text-muted-foreground">Issuer: </span>
<span className="font-mono break-all">{request.issuer}</span>
</div>}
{request.validTo && <div>
<span className="text-muted-foreground">Valid Until: </span>
<span className="font-mono">{request.validTo}</span>
</div>}
<div>
<span className="text-muted-foreground">SHA-256 Fingerprint: </span>
<code className="block mt-1 font-mono text-[11px] break-all rounded bg-background/60 p-1.5 border border-border/40">
{request.fingerprint256}
</code>
</div>
</div>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Trust &amp; remember this certificate fingerprint</span>
</label>
</div> : connection && effective ? <>
<p className="break-all text-sm font-medium">{effective.label}</p>
<p className="break-all text-sm">{protocol !== 'local' && effective.username ? `${effective.username}@` : ''}{effective.hostname}{protocol !== 'local' && effective.port ? `:${effective.port}` : ''} ({protocol})</p>
{protocol === 'local' && <p className="text-sm font-medium" role="note">{t('plugins.hostActions.localExecution')}</p>}
{stream ? <><p className="text-sm font-medium break-all">{request.endpoint}</p><p className="text-sm">{t('plugins.hostActions.streamNote')}</p></> : <>
{stream ? <>
<p className="text-sm font-medium break-all">{request.endpoint}</p>
<p className="text-sm">{t('plugins.hostActions.streamNote')}</p>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer pt-1">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Remember this SSH tunnel binding</span>
</label>
</> : <>
<p className="text-sm" role="note">{t(entry.scriptsRun ? 'plugins.hostActions.scriptsRun' : 'plugins.hostActions.noScripts')}</p>
<p className="text-xs text-muted-foreground">{t('plugins.hostActions.connectionNote')}</p></>}
</> : request.kind === 'vault.requestHostDraft' ? <PluginHostDraftPreview key={entry.prompt.requestId} before={entry.host} draft={request.draft} managedSources={entry.managedSources} busy={state.busy} onConfirm={(draft) => void state.respond('submit', draft)} /> : null}
{state.error && <p role="alert" className="text-sm text-destructive">{t('plugins.hostActions.failed')}</p>}
<DialogFooter className={selection ? 'p-3 border-t' : undefined}>
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>{t('common.cancel')}</Button>
{directStreamConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
{tlsConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>Trust &amp; Continue</Button>}
{connection && <Button disabled={state.busy || (stream && protocol !== 'ssh')} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
</DialogFooter>
</DialogContent>
+29 -4
View File
@@ -7,14 +7,39 @@ export type PluginHostDrawnPageProps = Parameters<typeof useHostDrawnPluginView>
pluginId: string;
};
type MinimalTreeNode = {
type?: number;
attributes?: Record<string, string>;
children?: MinimalTreeNode[];
};
function hasFullBleedChrome(tree: unknown): boolean {
if (!tree || typeof tree !== 'object') return false;
const children = (tree as { children?: MinimalTreeNode[] }).children;
if (!Array.isArray(children)) return false;
// Check root and immediate child (hostDom wraps React trees in a mountRoot div).
const check = (nodes: MinimalTreeNode[], depth: number): boolean => {
for (const node of nodes) {
if (node?.type !== 1) continue;
if (node.attributes?.['data-plugin-chrome'] === 'full-bleed') return true;
if (depth < 2 && Array.isArray(node.children) && check(node.children, depth + 1)) return true;
}
return false;
};
return check(children, 0);
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const view = useHostDrawnPluginView(props);
if (!view.visible) return null;
if (view.loading) return <p data-plugin-view-slot={props.slot.split(':')[0]} role="status" className="p-4 text-sm text-muted-foreground">{props.loadingLabel}</p>;
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]}>
const fullBleed = hasFullBleedChrome(view.tree);
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
</div>
{!fullBleed && (
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
</div>
)}
</div>;
}
+451 -1
View File
@@ -31,7 +31,7 @@ test('plugin surface forwards its own input and contains malformed updates and r
assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]);
const input = captured!.querySelector('input')!; input.value = 'typed';
await act(async () => { input.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed' });
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed', selectionStart: 5, selectionEnd: 5 });
await act(async () => { document.getElementById('host')!.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
assert.equal(events.length, 2);
await act(async () => { root.render(<PluginRemoteSurface tree={tree} css="@import 'https://bad.example/x';" onEvent={() => {}} />); });
@@ -254,3 +254,453 @@ test('PluginRemoteSurface avoids JSON/form hook work on text and plain elements
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, cursor popover, and host-rendered widgets', 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', '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: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, 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: 'name', type: 'varchar', nullable: true },
],
rows: [
{ id: 1, name: 'Alice' },
{ id: 2, name: null },
],
dirtyCells: { '0:name': 'Alicia' },
editable: true,
};
const erProps = {
tables: [
{ name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] },
{ name: 'orders', columns: [{ name: 'id', type: 'int', isPk: true }, { name: 'user_id', type: 'int', isFk: true }] },
],
relations: [{ fromTable: 'orders', fromColumn: 'user_id', toTable: 'users', toColumn: 'id' }],
};
const tree = {
children: [
{
id: 'scroller',
type: 1,
element: 'div',
attributes: { class: 'list' },
children: [{ id: 'item', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'it', type: 3, data: 'Row' }] }],
},
{
id: 'ctx-popover',
type: 1,
element: 'div',
attributes: {
'data-plugin-popover': 'true',
'data-plugin-anchor-x': '120',
'data-plugin-anchor-y': '80',
'data-plugin-popover-width': '260',
'data-plugin-popover-max-height': '320',
open: '',
},
children: [{ id: 'pop-item', type: 1, element: 'span', attributes: {}, children: [{ id: 'pt', type: 3, data: 'Menu' }] }],
},
{
id: 'split',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'split-pane',
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 220, minSize: 120, maxSize: 400 }),
},
children: [
{ id: 'pane-a', type: 1, element: 'div', attributes: {}, children: [{ id: 'pa', type: 3, data: 'Left' }] },
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
],
},
{
id: 'grid',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
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>)} />);
});
const mainShadow = shadows[0];
assert.ok(mainShadow, 'main shadow mounted');
// 1. dblclick & contextmenu with surface-relative coordinates + preventDefault
const btn = mainShadow.querySelector('button')!;
const ctxEvent = new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 250, clientY: 170 });
await act(async () => {
btn.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, clientX: 180, clientY: 90 }));
btn.dispatchEvent(ctxEvent);
});
assert.equal(ctxEvent.defaultPrevented, true, 'contextmenu must call preventDefault');
assert.deepEqual(events[0], { nodeId: 'item', type: 'dblclick', x: 80, y: 40 });
assert.deepEqual(events[1], { nodeId: 'item', type: 'contextmenu', x: 150, y: 120 });
// 2. throttled scroll
const scroller = mainShadow.querySelector('.list') as HTMLElement;
scroller.scrollTop = 140;
scroller.scrollLeft = 20;
await act(async () => {
scroller.dispatchEvent(new dom.window.Event('scroll', { bubbles: false }));
await new Promise((resolve) => setTimeout(resolve, 90));
});
const scrollEvt = events.find((e) => e.type === 'scroll');
assert.ok(scrollEvt, 'scroll event emitted');
assert.equal(scrollEvt!.scrollTop, 140);
assert.equal(scrollEvt!.scrollLeft, 20);
// 3. cursor-anchored popover positioned within surface bounds with custom width & maxHeight
const popoverEl = document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
assert.ok(popoverEl, 'cursor-anchored popover rendered');
assert.equal(popoverEl!.style.width, '260px');
assert.equal(popoverEl!.style.maxHeight, '320px');
assert.equal(popoverEl!.style.left, '220px'); // surface.left (100) + anchorX (120)
// 4. SplitPane rendered inside shadow root with two panes and drag handle
const splitEl = mainShadow.querySelector('[data-plugin-widget="split-pane"]') as HTMLElement | null;
assert.ok(splitEl, 'split-pane rendered in shadow root');
assert.equal(splitEl!.querySelectorAll('[data-split-pane]').length, 2);
const handle = splitEl!.querySelector('[data-split-handle]') as HTMLElement;
await act(async () => {
handle.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, clientX: 220 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { bubbles: true, clientX: 280 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, clientX: 280 }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'),
{ nodeId: 'split', type: 'widget', widgetEvent: 'resizeEnd', detail: { size: 280, collapsed: false } },
);
// 5. DataGrid slotted in Light DOM: renders dirty cell, NULL pill, inline edit & sort
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement | null;
assert.ok(gridHost, 'data-grid slotted in shadow host Light DOM');
assert.ok(gridHost!.textContent?.includes('Alicia'), 'dirty cell value rendered');
assert.ok(gridHost!.textContent?.includes('NULL'), 'NULL pill rendered');
const nameHeaderBtn = gridHost!.querySelector('[data-col-name="name"] button') as HTMLButtonElement;
await act(async () => { nameHeaderBtn.click(); });
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'sortChange'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'sortChange', detail: { column: 'name', direction: 'asc' } },
);
const cell = gridHost!.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="name"]') as HTMLElement;
await act(async () => {
cell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const editorInput = cell.querySelector('input') as HTMLInputElement;
assert.ok(editorInput, 'double-click opens inline cell editor');
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!;
setter.call(editorInput, 'Bob');
editorInput.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
});
await act(async () => {
editorInput.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'name', value: 'Bob', isNull: false } },
);
// 6. ER Canvas slotted in Light DOM: renders tables + FK curve + emits tableClick
const erHost = document.querySelector('[data-plugin-widget-host="er-canvas"]') as HTMLElement | null;
assert.ok(erHost, 'er-canvas slotted in shadow host Light DOM');
const usersCard = erHost!.querySelector('[data-er-table="users"]') as Element | null;
assert.ok(usersCard, 'users table card rendered');
await act(async () => {
usersCard!.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableClick'),
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableClick', detail: { table: 'users' } },
);
} 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');
}
});
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');
}
});
test('RemoteImageElement renders a transparent placeholder while loading and never shows a broken img', 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', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
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');
let resolveImage!: (url: string) => void;
const loadImage = () => new Promise<string>((resolve) => { resolveImage = resolve; });
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={{ children: [{ id: 'img1', type: 1, element: 'img', attributes: { src: 'asset:assets/icons/pg.png', alt: 'PostgreSQL' }, children: [] }] }}
css=""
loadImage={loadImage}
onEvent={() => {}}
/>,
);
});
const img = shadows[0]?.querySelector('img');
assert.ok(img, 'img element rendered');
assert.equal(img!.getAttribute('data-plugin-image-loading'), 'true');
assert.match(img!.getAttribute('src') ?? '', /^data:image\/gif;base64,/);
assert.equal(img!.getAttribute('alt'), '', 'alt text hidden while placeholder loads');
const resolvedUrl = 'data:image/png;base64,iVBORw0KGgo=';
await act(async () => {
resolveImage(resolvedUrl);
await Promise.resolve();
});
assert.equal(img!.getAttribute('data-plugin-image-loading'), null);
assert.equal(img!.getAttribute('src'), resolvedUrl);
assert.equal(img!.getAttribute('alt'), 'PostgreSQL');
} 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');
}
});
+408 -37
View File
@@ -1,6 +1,10 @@
import React, { createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
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';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
@@ -9,16 +13,44 @@ type RemoteElementNode = {
id: string; type: 1; element: string; attributes: Record<string, string>; children: RemoteNode[];
};
type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | RemoteElementNode;
export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent;
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
'compositionstart', 'compositionupdate', 'compositionend',
'submit', 'reset',
'scroll',
] as const;
const SURFACE_EVENT_SET = new Set<string>(SURFACE_EVENTS);
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas']);
const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
const preventFormSubmit = (event: React.FormEvent) => event.preventDefault();
const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 });
const SurfaceContext = createContext<{
css: string;
onEvent(event: PluginSurfaceEvent): void;
depth: number;
shadowHost: HTMLDivElement | null;
}>({ css: '', onEvent: () => {}, depth: 0, shadowHost: null });
function remoteText(nodes: RemoteNode[]): string {
return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join('');
}
function parseOptionalNumber(raw: string | undefined): number | undefined {
if (raw === undefined || raw === '') return undefined;
const parsed = Number(raw);
return Number.isFinite(parsed) ? parsed : undefined;
}
const ResourceLoader = createContext<((path: string) => Promise<string>) | undefined>(undefined);
function buildRemoteElementProps(node: RemoteElementNode): Record<string, unknown> {
@@ -41,20 +73,179 @@ const RemotePopoverElement = memo(function RemotePopoverElement({ node, settled
const loadImage = useContext(ResourceLoader);
if (surface.depth >= 1) return null;
const attrs = node.attributes;
return <PluginViewPopover anchor={attrs['data-plugin-anchor'] ?? ''} open={Object.hasOwn(attrs, 'open')} dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}><PluginRemoteSurface tree={{ children: node.children }} css={surface.css} onEvent={surface.onEvent} settled={settled} loadImage={loadImage} depth={surface.depth + 1} /></PluginViewPopover>;
return (
<PluginViewPopover
anchor={attrs['data-plugin-anchor'] ?? ''}
anchorX={parseOptionalNumber(attrs['data-plugin-anchor-x'])}
anchorY={parseOptionalNumber(attrs['data-plugin-anchor-y'])}
width={parseOptionalNumber(attrs['data-plugin-popover-width'])}
maxHeight={parseOptionalNumber(attrs['data-plugin-popover-max-height'])}
open={Object.hasOwn(attrs, 'open')}
dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}
>
<PluginRemoteSurface
tree={{ children: node.children }}
css={surface.css}
onEvent={surface.onEvent}
settled={settled}
loadImage={loadImage}
depth={surface.depth + 1}
/>
</PluginViewPopover>
);
});
const RemoteSplitPaneElement = memo(function RemoteSplitPaneElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const { onEvent } = useContext(SurfaceContext);
const rawWidgetProps = node.attributes['data-plugin-widget-props'];
const parsed = useMemo(
() => parseWidgetPropsJson<PluginSplitPaneWidgetProps>(rawWidgetProps),
[rawWidgetProps],
);
const elementChildren = node.children.filter((child) => child.type === 1 || (child.type === 3 && child.data.length > 0));
const firstChild = elementChildren[0] ? renderRemoteNode(elementChildren[0], settled) : null;
const secondChild = elementChildren[1] ? renderRemoteNode(elementChildren[1], settled) : null;
const emit = useCallback(
(widgetEvent: string, detail?: Record<string, unknown>) => {
onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[onEvent, node.id],
);
return (
<PluginSplitPane
{...parsed}
nodeId={node.id}
className={node.attributes.class}
inlineStyle={node.attributes.style}
firstChild={firstChild}
secondChild={secondChild}
onWidgetEvent={emit}
/>
);
});
const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ node, kind }: { node: RemoteElementNode; kind: SlottedWidgetKind }): React.ReactNode {
const { onEvent, shadowHost } = useContext(SurfaceContext);
const slotName = `nc-widget-${node.id}`;
const emit = useCallback(
(widgetEvent: string, detail?: Record<string, unknown>) => {
onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[onEvent, node.id],
);
const wrapperProps = buildRemoteElementProps(node);
const origRef = wrapperProps.ref as ((el: HTMLElement | null) => void) | undefined;
const hasExplicitStyle = Object.hasOwn(node.attributes, 'style');
wrapperProps.ref = (el: HTMLElement | null) => {
origRef?.(el);
if (el && !hasExplicitStyle) {
el.setAttribute('style', 'display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;overflow:hidden');
}
};
return (
<>
{React.createElement(
'div',
wrapperProps,
React.createElement('slot', { name: slotName, style: { display: 'contents' } }),
)}
{shadowHost && createPortal(
<div
slot={slotName}
data-plugin-widget-host={kind}
data-plugin-widget-node={node.id}
className="flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden"
>
<PluginSlottedWidget
kind={kind}
rawProps={node.attributes['data-plugin-widget-props']}
onWidgetEvent={emit}
/>
</div>,
shadowHost,
)}
</>
);
});
const resolvedImageCache = new WeakMap<(path: string) => Promise<string>, Map<string, string>>();
const IMAGE_RETRY_DELAYS_MS = [150, 400, 1000] as const;
const TRANSPARENT_PLACEHOLDER_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
function getCachedImageUrl(loader: ((path: string) => Promise<string>) | undefined, imagePath: string | undefined): string | undefined {
if (!loader || !imagePath) return undefined;
return resolvedImageCache.get(loader)?.get(imagePath);
}
function setCachedImageUrl(loader: (path: string) => Promise<string>, imagePath: string, url: string) {
let map = resolvedImageCache.get(loader);
if (!map) {
map = new Map();
resolvedImageCache.set(loader, map);
}
if (map.size >= 256) {
const oldest = map.keys().next().value;
if (oldest !== undefined) map.delete(oldest);
}
map.set(imagePath, url);
}
const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: RemoteElementNode }): React.ReactNode {
const loadImage = useContext(ResourceLoader);
const imagePath = node.attributes.src?.slice(6);
const [imageUrl, setImageUrl] = useState<string | undefined>();
const [imageUrl, setImageUrl] = useState<string | undefined>(() => getCachedImageUrl(loadImage, imagePath));
useEffect(() => {
let cancelled = false; setImageUrl(undefined);
if (imagePath && loadImage) void loadImage(imagePath).then((url) => { if (!cancelled) setImageUrl(url); }).catch(() => {});
return () => { cancelled = true; };
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
const cached = getCachedImageUrl(loadImage, imagePath);
if (cached) {
setImageUrl(cached);
return () => { cancelled = true; };
}
setImageUrl(undefined);
if (imagePath && loadImage) {
const attemptLoad = (attempt: number) => {
void loadImage(imagePath).then((url) => {
if (cancelled) return;
setCachedImageUrl(loadImage, imagePath, url);
setImageUrl(url);
}).catch(() => {
if (cancelled) return;
const delay = IMAGE_RETRY_DELAYS_MS[attempt];
if (delay !== undefined) {
retryTimer = setTimeout(() => { if (!cancelled) attemptLoad(attempt + 1); }, delay);
}
});
};
attemptLoad(0);
}
return () => {
cancelled = true;
if (retryTimer !== undefined) clearTimeout(retryTimer);
};
}, [imagePath, loadImage]);
const props = buildRemoteElementProps(node);
props.src = imageUrl;
if (imageUrl) {
props.src = imageUrl;
} else {
// Use a transparent 1x1 placeholder while loading so Chromium never flashes
// a broken-image icon or raw alt text before the rasterized asset arrives.
props.src = TRANSPARENT_PLACEHOLDER_SRC;
props.alt = '';
props['data-plugin-image-loading'] = 'true';
}
return React.createElement('img', props);
});
@@ -111,34 +302,79 @@ function renderRemoteNode(node: RemoteNode, settled: boolean): React.ReactNode {
if (node.type === 3) return node.data;
if (node.type === 8) return null;
if (node.attributes['data-plugin-popover'] === 'true') return <RemotePopoverElement key={node.id} node={node} settled={settled} />;
const widgetKind = node.attributes['data-plugin-widget'];
if (widgetKind === 'split-pane') return <RemoteSplitPaneElement key={node.id} node={node} settled={settled} />;
if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) {
return <RemoteSlottedWidgetElement key={node.id} node={node} kind={widgetKind as SlottedWidgetKind} />;
}
if (node.element === 'img') return <RemoteImageElement key={node.id} node={node} />;
if (node.element === 'select') return <RemoteSelectElement key={node.id} node={node} settled={settled} />;
if (node.element === 'input' || node.element === 'textarea') return <RemoteInputElement key={node.id} node={node} settled={settled} />;
return <RemotePlainElement key={node.id} node={node} settled={settled} />;
}
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checked = useMemo(() => {
try {
validatePluginRemoteTree(tree);
return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) };
} catch { return null; }
}, [tree, css]);
const checkedCss = checked?.css;
const surfaceContextValue = useMemo(
() => (checkedCss !== undefined ? { css: checkedCss, onEvent, depth } : null),
[checkedCss, onEvent, depth],
);
if (!checked || !surfaceContextValue) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
return <LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}><SurfaceContext.Provider value={surfaceContextValue}><ResourceLoader.Provider value={loadImage}><ValidatedPluginRemoteSurface tree={checked.tree} css={checked.css} onEvent={onEvent} settled={settled} /></ResourceLoader.Provider></SurfaceContext.Provider></LazyLoadBoundary>;
function readSelectionRange(
target: HTMLElement,
view: Window & typeof globalThis,
): { selectionStart: number; selectionEnd: number } | undefined {
const isTextInput =
target instanceof view.HTMLTextAreaElement
|| (target instanceof view.HTMLInputElement && ['text', 'search', 'url', 'tel', 'password', ''].includes(target.type));
if (!isTextInput) return undefined;
try {
const start = target.selectionStart;
const end = target.selectionEnd;
if (typeof start === 'number' && typeof end === 'number' && Number.isFinite(start) && Number.isFinite(end)) {
return {
selectionStart: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(start))),
selectionEnd: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(end))),
};
}
} catch {
// Non-selectable input types throw InvalidStateError.
}
return undefined;
}
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled: boolean; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checkedTree = useMemo(() => {
try {
validatePluginRemoteTree(tree);
return tree as { children: RemoteNode[] };
} catch { return null; }
}, [tree]);
const checkedCss = useMemo(() => {
try {
return validatePluginStylesheet(css);
} catch { return null; }
}, [css]);
if (!checkedTree || checkedCss === null) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
return (
<LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}>
<ResourceLoader.Provider value={loadImage}>
<ValidatedPluginRemoteSurface tree={checkedTree} css={checkedCss} onEvent={onEvent} settled={settled} depth={depth} />
</ResourceLoader.Provider>
</LazyLoadBoundary>
);
}
const SHADOW_BASE_SCROLLBAR_CSS = [
'*::-webkit-scrollbar{width:6px;height:6px}',
'*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}',
'*::-webkit-scrollbar-thumb{min-height:28px;border:1px solid transparent;border-radius:999px;background-color:transparent;background-clip:content-box}',
'*:hover::-webkit-scrollbar-thumb{background-color:hsl(var(--muted-foreground) / 0.24)}',
'*::-webkit-scrollbar-thumb:hover{background-color:hsl(var(--muted-foreground) / 0.45)}',
].join('');
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
const surfaceRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const shadowRef = useRef<ShadowRoot | null>(null);
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const host = hostRef.current;
if (!host) return;
@@ -146,32 +382,167 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled
const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' });
shadowRef.current = root;
setShadow(root);
setShadowHost(host);
}, []);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
);
useEffect(() => {
if (!shadow) return;
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingScroll = new Map<string, PluginSurfaceEvent>();
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
const evt = pendingScroll.get(nodeId);
if (evt) {
pendingScroll.delete(nodeId);
onEventRef.current(evt);
}
};
const listener = (event: Event) => {
const target = event.target;
const view = shadow.ownerDocument.defaultView;
if (!view || !(target instanceof view.HTMLElement) || !['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset'].includes(event.type)) return;
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
// Closed-shadow events hide their editable target from window capture.
if (event.type === 'focusin') hostRef.current?.toggleAttribute('data-plugin-editing', target.matches('input, textarea, select, [contenteditable]'));
if (event.type === 'focusin') {
hostRef.current?.toggleAttribute(
'data-plugin-editing',
target.matches('input, textarea, select, [contenteditable]') || Boolean(target.closest('.monaco-editor')),
);
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
if (target.closest('[data-plugin-widget-host]')) return;
if (event.type === 'submit') event.preventDefault();
const nodeId = target.dataset.netcattyRemoteNode;
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);
if (!nodeId) return;
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
type: 'scroll' as PluginSurfaceEvent['type'],
scrollTop: Math.max(0, Math.round(target.scrollTop)),
scrollLeft: Math.max(0, Math.round(target.scrollLeft)),
clientHeight: Math.max(0, Math.round(target.clientHeight)),
clientWidth: Math.max(0, Math.round(target.clientWidth)),
};
pendingScroll.set(nodeId, scrollEvent);
if (!scrollTimers.has(nodeId)) {
scrollTimers.set(nodeId, setTimeout(() => flushScroll(nodeId), SCROLL_THROTTLE_MS));
}
return;
}
const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined;
const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined;
const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined;
if (value !== undefined && value.length > 8192) return;
if (value !== undefined && value.length > MAX_EVENT_VALUE_LENGTH) return;
const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } : {};
onEventRef.current({ nodeId, type: event.type as PluginSurfaceEvent['type'], ...(value === undefined ? {} : { value }), ...(checkedValue === undefined ? {} : { checked: checkedValue }), ...keyboard, ...(values ? { values } : {}), ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}) });
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey }
: {};
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
pointerCoords = {
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
};
}
const selection =
event.type === 'input' || event.type === 'change' || event.type === 'keyup' || event.type === 'keydown'
? readSelectionRange(target, view)
: undefined;
onEventRef.current({
nodeId,
type: event.type as PluginSurfaceEvent['type'],
...(value === undefined ? {} : { value }),
...(checkedValue === undefined ? {} : { checked: checkedValue }),
...keyboard,
...(pointerCoords ?? {}),
...(selection ?? {}),
...(values ? { values } : {}),
...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}),
});
};
for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.addEventListener(event, listener, true);
return () => { for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.removeEventListener(event, listener, true); };
}, [shadow]);
return <div className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size]" />
{shadow && createPortal(<><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
</div>;
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]);
return (
<SurfaceContext.Provider value={surfaceContextValue}>
<div ref={surfaceRef} className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size] [&::-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-transparent hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/25" />
{shadow && createPortal(<><style>{SHADOW_BASE_SCROLLBAR_CSS}</style><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
</div>
</SurfaceContext.Provider>
);
}
+3 -1
View File
@@ -3,7 +3,7 @@ import { useI18n } from '../../application/i18n/I18nProvider';
import type { usePluginVaultPages } from '../../application/state/usePluginVaultPages';
import { PluginContributionIcon } from './PluginContributionIcon';
import { Button } from '../ui/button';
import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
import { LazyPluginHostDrawnPage, preloadPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
type VaultPages = ReturnType<typeof usePluginVaultPages>;
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
@@ -17,6 +17,8 @@ export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages;
title={`${page.title} — ${page.pluginName}`}
aria-label={`${page.title} — ${page.pluginName}`}
aria-current={model.selected?.key === page.key ? 'page' : undefined}
onMouseEnter={preloadPluginHostDrawnPage}
onFocus={preloadPluginHostDrawnPage}
onClick={() => model.select(page.key)}>
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={16} className="shrink-0" />
{!collapsed && <span className="truncate">{page.title}</span>}
+222 -28
View File
@@ -1,41 +1,235 @@
import React, { useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
const MIN_POPOVER_WIDTH = 160;
const MAX_POPOVER_WIDTH = 480;
const DEFAULT_POPOVER_WIDTH = 240;
const MIN_POPOVER_HEIGHT = 80;
const MAX_POPOVER_HEIGHT = 420;
export interface PluginViewPopoverProps {
anchor?: string;
anchorX?: number;
anchorY?: number;
width?: number;
maxHeight?: number;
open: boolean;
dismiss(): void;
children: React.ReactNode;
}
/** Geometry and dismissal belong to the host; content belongs to the plugin. */
export function PluginViewPopover({ anchor, open, dismiss, children }: {
anchor: string; open: boolean; dismiss(): void; children: React.ReactNode;
}) {
export function PluginViewPopover({
anchor,
anchorX,
anchorY,
width: requestedWidth,
maxHeight: requestedMaxHeight,
open,
dismiss,
children,
}: PluginViewPopoverProps) {
const marker = useRef<HTMLSpanElement>(null);
const panel = useRef<HTMLDivElement>(null);
const dismissRef = useRef(dismiss); dismissRef.current = dismiss;
const [position, setPosition] = useState<{ left: number; top: number; width: number } | null>(null);
const dismissRef = useRef(dismiss);
dismissRef.current = dismiss;
const [position, setPosition] = useState<{
left: number;
top: number;
width: number;
maxHeight: number;
} | null>(null);
useLayoutEffect(() => {
if (!open || !marker.current) { setPosition(null); return; }
if (!open || !marker.current) {
setPosition(null);
return;
}
const root = marker.current.getRootNode() as ShadowRoot;
const target = root.getElementById(anchor);
if (!(target instanceof marker.current.ownerDocument.defaultView!.HTMLElement)) return;
const doc = target.ownerDocument; const win = doc.defaultView!;
const doc = marker.current.ownerDocument;
const win = doc.defaultView!;
const surface = root.host instanceof win.HTMLElement
? root.host.closest('[data-plugin-remote-surface]')
: null;
const hasCursorCoords =
typeof anchorX === 'number' && Number.isFinite(anchorX)
&& typeof anchorY === 'number' && Number.isFinite(anchorY);
const target = anchor ? root.getElementById(anchor) : null;
const targetEl = target instanceof win.HTMLElement ? target : null;
if (!hasCursorCoords && !targetEl) {
setPosition(null);
return;
}
const resolveSurfaceBounds = () => {
const vp = {
left: 8,
top: 8,
right: Math.max(8, win.innerWidth - 8),
bottom: Math.max(8, win.innerHeight - 8),
};
if (!surface) return vp;
const sr = surface.getBoundingClientRect();
if (sr.width <= 0 || sr.height <= 0) return vp;
return {
left: Math.max(vp.left, sr.left + 4),
top: Math.max(vp.top, sr.top + 4),
right: Math.min(vp.right, sr.right - 4),
bottom: Math.min(vp.bottom, sr.bottom - 4),
};
};
const update = () => {
const bounds = target.getBoundingClientRect();
if (!bounds.width || !bounds.height) { setPosition(null); dismissRef.current(); return; }
const width = Math.min(360, Math.max(220, bounds.width), win.innerWidth - 16);
setPosition({ left: Math.max(8, Math.min(bounds.left, win.innerWidth - width - 8)), top: Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - 248)), width });
const clip = resolveSurfaceBounds();
const availableW = Math.max(MIN_POPOVER_WIDTH, clip.right - clip.left);
const availableH = Math.max(MIN_POPOVER_HEIGHT, clip.bottom - clip.top);
const boundedMaxHeight = Math.min(
availableH,
Math.max(
MIN_POPOVER_HEIGHT,
Math.min(
MAX_POPOVER_HEIGHT,
typeof requestedMaxHeight === 'number' && Number.isFinite(requestedMaxHeight)
? Math.round(requestedMaxHeight)
: MAX_POPOVER_HEIGHT,
),
),
);
let width: number;
let rawLeft: number;
let rawTop: number;
let anchorTop: number;
if (hasCursorCoords) {
const sr = surface?.getBoundingClientRect();
const originLeft = sr && sr.width > 0 ? sr.left : 0;
const originTop = sr && sr.height > 0 ? sr.top : 0;
const desiredW =
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
? requestedWidth
: DEFAULT_POPOVER_WIDTH;
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
rawLeft = originLeft + anchorX!;
rawTop = originTop + anchorY! + 2;
anchorTop = originTop + anchorY!;
} else {
const bounds = targetEl!.getBoundingClientRect();
if (!bounds.width || !bounds.height) {
setPosition(null);
dismissRef.current();
return;
}
const desiredW =
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
? requestedWidth
: Math.min(360, Math.max(220, bounds.width));
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
rawLeft = bounds.left;
rawTop = bounds.bottom + 4;
anchorTop = bounds.top;
}
const left = Math.max(clip.left, Math.min(rawLeft, clip.right - width));
const measuredHeight = panel.current?.getBoundingClientRect().height || 0;
const estimatedHeight = measuredHeight > 0 ? Math.min(measuredHeight, boundedMaxHeight) : Math.min(240, boundedMaxHeight);
let top = rawTop;
let effectiveMaxHeight = boundedMaxHeight;
const spaceBelow = clip.bottom - rawTop;
const spaceAbove = anchorTop - 4 - clip.top;
if (spaceBelow < estimatedHeight && spaceAbove > spaceBelow) {
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceAbove)));
top = Math.max(clip.top, anchorTop - 4 - Math.min(estimatedHeight, effectiveMaxHeight));
} else {
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceBelow)));
top = Math.max(clip.top, Math.min(rawTop, clip.bottom - Math.min(estimatedHeight, effectiveMaxHeight)));
}
setPosition({ left: Math.round(left), top: Math.round(top), width: Math.round(width), maxHeight: Math.round(effectiveMaxHeight) });
};
const dismissNow = () => {
setPosition(null);
dismissRef.current();
};
const key = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
dismissNow();
targetEl?.focus();
}
};
const outside = (event: PointerEvent) => {
const path = event.composedPath();
if (targetEl && path.includes(targetEl)) return;
if (panel.current && path.includes(panel.current)) return;
dismissNow();
};
const dismissNow = () => { setPosition(null); dismissRef.current(); };
const key = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); dismissNow(); target.focus(); } };
const outside = (event: PointerEvent) => { if (!event.composedPath().includes(target) && (!panel.current || !event.composedPath().includes(panel.current))) dismissNow(); };
const blocked = () => [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
const rect = dialog.getBoundingClientRect(); return rect.width > 0 && rect.height > 0;
const rect = dialog.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
if (blocked()) { dismissNow(); return; }
const dialogs = new win.MutationObserver(() => { if (blocked()) dismissNow(); });
dialogs.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['aria-modal', 'hidden', 'data-state'] });
const resize = new win.ResizeObserver(update); resize.observe(target); update();
win.addEventListener('resize', update); doc.addEventListener('scroll', update, true);
doc.addEventListener('keydown', key, true); doc.addEventListener('pointerdown', outside, true);
return () => { dialogs.disconnect(); resize.disconnect(); win.removeEventListener('resize', update); doc.removeEventListener('scroll', update, true); doc.removeEventListener('keydown', key, true); doc.removeEventListener('pointerdown', outside, true); };
}, [anchor, open]);
return <><span ref={marker} hidden />{open && position && marker.current && createPortal(
<div ref={panel} role="region" aria-label="Plugin menu" data-plugin-view-popover className="fixed z-[45] overflow-hidden rounded-lg border border-border bg-background shadow-xl" style={{ ...position, height: 240, maxHeight: 'calc(100vh - 16px)', contain: 'paint', isolation: 'isolate' }}>{children}</div>, marker.current.ownerDocument.body,
)}</>;
if (blocked()) {
dismissNow();
return;
}
const dialogs = new win.MutationObserver(() => {
if (blocked()) dismissNow();
});
dialogs.observe(doc.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['aria-modal', 'hidden', 'data-state'],
});
const resize = new win.ResizeObserver(update);
if (targetEl) resize.observe(targetEl);
if (surface) resize.observe(surface);
update();
win.addEventListener('resize', update);
doc.addEventListener('scroll', update, true);
doc.addEventListener('keydown', key, true);
doc.addEventListener('pointerdown', outside, true);
return () => {
dialogs.disconnect();
resize.disconnect();
win.removeEventListener('resize', update);
doc.removeEventListener('scroll', update, true);
doc.removeEventListener('keydown', key, true);
doc.removeEventListener('pointerdown', outside, true);
};
}, [anchor, anchorX, anchorY, requestedWidth, requestedMaxHeight, open]);
return (
<>
<span ref={marker} hidden />
{open && position && marker.current && createPortal(
<div
ref={panel}
role="region"
aria-label="Plugin menu"
data-plugin-view-popover=""
className="fixed z-[45] overflow-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-xl"
style={{
left: position.left,
top: position.top,
width: position.width,
maxHeight: position.maxHeight,
contain: 'paint',
isolation: 'isolate',
}}
>
{children}
</div>,
marker.current.ownerDocument.body,
)}
</>
);
}
@@ -0,0 +1,29 @@
import { Loader2 } from 'lucide-react';
import React, { Suspense, lazy } from 'react';
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
import type { PluginCodeEditorWidgetProps, PluginWidgetEventCallback } from './types';
const LazyPluginCodeEditorInner = lazy(() => import('./PluginCodeEditorInner'));
export interface PluginCodeEditorProps extends PluginCodeEditorWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
export function PluginCodeEditor(props: PluginCodeEditorProps) {
return (
<LazyLoadBoundary
name="Plugin SQL Editor"
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to load code editor.</div>}
>
<Suspense
fallback={(
<div className="flex h-full w-full items-center justify-center bg-background text-muted-foreground">
<Loader2 size={18} className="animate-spin" />
</div>
)}
>
<LazyPluginCodeEditorInner {...props} />
</Suspense>
</LazyLoadBoundary>
);
}
@@ -0,0 +1,460 @@
import Editor, { loader, type Monaco, type OnMount, useMonaco } from '@monaco-editor/react';
import { Loader2 } from 'lucide-react';
import React, { useCallback, useEffect, useId, useRef } from 'react';
import { useClipboardBackend } from '@/application/state/useClipboardBackend';
import {
buildMonacoPasteEdits,
pasteForMonacoEditorCommand,
readClipboardTextWithFallbacks,
} from '@/infrastructure/monaco/monacoClipboardPaste';
import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme';
import { matchWorkbenchShortcut } from './shortcuts';
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
import type {
PluginCodeEditorCompletionSchema,
PluginCodeEditorDiagnostic,
PluginCodeEditorWidgetProps,
PluginWidgetEventCallback,
} from './types';
const viteEnv = (import.meta.env ?? { BASE_URL: '/', DEV: false }) as { BASE_URL?: string; DEV?: boolean };
const monacoBasePath = viteEnv.DEV
? './node_modules/monaco-editor/min/vs'
: `${viteEnv.BASE_URL ?? '/'}monaco/vs`;
loader.config({ paths: { vs: monacoBasePath } });
const DEFAULT_SQL_KEYWORDS = [
'SELECT', 'FROM', 'WHERE', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE',
'CREATE', 'ALTER', 'DROP', 'TABLE', 'INDEX', 'VIEW', 'JOIN', 'LEFT JOIN', 'RIGHT JOIN',
'INNER JOIN', 'FULL OUTER JOIN', 'ON', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT',
'OFFSET', 'DISTINCT', 'AS', 'AND', 'OR', 'NOT', 'IN', 'IS NULL', 'IS NOT NULL',
'BETWEEN', 'LIKE', 'ILIKE', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'UNION', 'UNION ALL',
'WITH', 'EXPLAIN', 'ANALYZE', 'BEGIN', 'COMMIT', 'ROLLBACK', 'RETURNING', 'PRIMARY KEY',
'FOREIGN KEY', 'REFERENCES', 'DEFAULT', 'CASCADE', 'COUNT', 'SUM', 'AVG', 'MIN', 'MAX',
];
const SEVERITY_MAP: Record<NonNullable<PluginCodeEditorDiagnostic['severity']>, number> = {
hint: 1,
info: 2,
warning: 4,
error: 8,
};
export interface PluginCodeEditorInnerProps extends PluginCodeEditorWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
export default function PluginCodeEditorInner({
value = '',
language = 'sql',
readOnly = false,
placeholder,
lineNumbers = 'on',
minimap = false,
wordWrap = 'off',
completionSchema,
diagnostics,
height = '100%',
onWidgetEvent,
}: PluginCodeEditorInnerProps) {
const monaco = useMonaco();
const themeName = useNetcattyMonacoTheme(monaco ?? undefined);
const { readClipboardText: readClipboardTextFromBridge } = useClipboardBackend();
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;
const schemaRef = useRef<PluginCodeEditorCompletionSchema | undefined>(completionSchema);
schemaRef.current = completionSchema;
const lastEmittedValueRef = useRef<string>(value);
const changeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selectionTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const readClipboardRef = useRef<() => Promise<string | null>>(() => Promise.resolve(null));
const readClipboardText = useCallback(async (): Promise<string | null> => (
readClipboardTextWithFallbacks({
readNavigator: navigator.clipboard?.readText
? () => navigator.clipboard.readText()
: undefined,
readBridge: readClipboardTextFromBridge,
})
), [readClipboardTextFromBridge]);
readClipboardRef.current = readClipboardText;
// Sync external value changes without disrupting cursor when value echoes local edits.
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
if (value === lastEmittedValueRef.current) return;
const model = editor.getModel();
if (!model || model.getValue() === value) {
lastEmittedValueRef.current = value;
return;
}
lastEmittedValueRef.current = value;
model.setValue(value);
}, [value]);
// Sync diagnostics markers cleanly.
useEffect(() => {
const editor = editorRef.current;
const monacoInstance = monacoRef.current ?? monaco;
if (!editor || !monacoInstance) return;
const model = editor.getModel();
if (!model) return;
const markers = (diagnostics ?? []).map((diag) => ({
startLineNumber: Math.max(1, Math.floor(diag.line || 1)),
startColumn: Math.max(1, Math.floor(diag.column || 1)),
endLineNumber: Math.max(1, Math.floor(diag.endLine ?? diag.line ?? 1)),
endColumn: Math.max(1, Math.floor(diag.endColumn ?? (diag.column ? diag.column + 1 : 2))),
message: diag.message,
severity: SEVERITY_MAP[diag.severity ?? 'error'] ?? 8,
}));
monacoInstance.editor.setModelMarkers(model, 'netcatty-plugin-diagnostics', markers);
}, [diagnostics, monaco]);
// Register local schema-aware CompletionItemProvider scoped to this editor's model URI.
useEffect(() => {
if (!monaco) return;
if (!['sql', 'pgsql', 'mysql'].includes(language)) return;
const disposable = monaco.languages.registerCompletionItemProvider(language, {
triggerCharacters: ['.', ' '],
provideCompletionItems(model, position) {
if (model.uri.toString() !== modelPath) return { suggestions: [] };
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn,
};
const linePrefix = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
const dotMatch = /["`]?([a-zA-Z_][\w$]*)["`]?\.\s*[\w$]*$/u.exec(linePrefix);
const schema = schemaRef.current;
const tables = schema?.tables ?? [];
const suggestions: Parameters<typeof monaco.languages.registerCompletionItemProvider>[1] extends {
provideCompletionItems: (...args: never[]) => infer R;
}
? R extends { suggestions: infer S }
? S
: never
: never = [] as never;
const list = suggestions as Array<{
label: string;
kind: number;
insertText: string;
detail?: string;
sortText?: string;
range: typeof range;
}>;
if (dotMatch) {
const qualifier = dotMatch[1].toLowerCase();
const aliases = extractSqlTableAliases(model.getValue());
const resolvedTableName = aliases.get(qualifier) ?? qualifier;
// Match either schema.table or table/alias.column
for (const tbl of tables) {
if (tbl.schema && tbl.schema.toLowerCase() === qualifier) {
list.push({
label: tbl.name,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: tbl.name,
detail: `${tbl.schema} table`,
sortText: `0_${tbl.name}`,
range,
});
}
if (tbl.name.toLowerCase() === resolvedTableName.toLowerCase()) {
for (const col of tbl.columns ?? []) {
list.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
detail: col.type ? `${tbl.name}.${col.name} (${col.type})` : `${tbl.name}.${col.name}`,
sortText: `0_${col.name}`,
range,
});
}
}
}
return { suggestions: list as never };
}
const seenColumns = new Set<string>();
for (const tbl of tables) {
const label = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
list.push({
label,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: label,
detail: tbl.schema ? `Table (${tbl.schema})` : 'Table',
sortText: `1_${tbl.name}`,
range,
});
if (tbl.schema) {
list.push({
label: tbl.name,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: tbl.name,
detail: `Table (${tbl.schema})`,
sortText: `1_${tbl.name}`,
range,
});
}
for (const col of tbl.columns ?? []) {
const key = `${col.name}:${tbl.name}`;
if (seenColumns.has(key)) continue;
seenColumns.add(key);
list.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
detail: col.type ? `${tbl.name} (${col.type})` : tbl.name,
sortText: `2_${col.name}`,
range,
});
}
}
for (const fn of schema?.functions ?? []) {
list.push({
label: fn.name,
kind: monaco.languages.CompletionItemKind.Function,
insertText: fn.insertText ?? `${fn.name}()`,
detail: fn.detail ?? 'Function',
sortText: `3_${fn.name}`,
range,
});
}
const keywords = schema?.keywords?.length ? schema.keywords : DEFAULT_SQL_KEYWORDS;
for (const kw of keywords) {
list.push({
label: kw,
kind: monaco.languages.CompletionItemKind.Keyword,
insertText: kw,
detail: 'Keyword',
sortText: `4_${kw}`,
range,
});
}
return { suggestions: list as never };
},
});
return () => disposable.dispose();
}, [language, modelPath, monaco]);
useEffect(() => () => {
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
for (const d of disposablesRef.current.splice(0)) {
try { d.dispose(); } catch { /* ignore already-disposed Monaco resources */ }
}
editorRef.current = null;
}, []);
const handleMount: OnMount = useCallback((editor, monacoInstance) => {
for (const d of disposablesRef.current.splice(0)) {
try { d.dispose(); } catch { /* ignore already-disposed Monaco resources */ }
}
editorRef.current = editor;
monacoRef.current = monacoInstance;
const emitExecute = () => {
const model = editor.getModel();
if (!model) return;
const fullValue = model.getValue();
const sel = editor.getSelection();
const selectedText = sel && !sel.isEmpty() ? model.getValueInRange(sel) : '';
const cursorOffset = sel ? model.getOffsetAt(sel.getPosition()) : 0;
const currentStatement = selectedText.trim()
? selectedText.trim()
: extractCurrentSqlStatement(fullValue, cursorOffset);
onWidgetEventRef.current('execute', {
value: fullValue,
selectedText,
currentStatement,
});
};
const emitFormat = () => {
const model = editor.getModel();
if (!model) return;
onWidgetEventRef.current('format', { value: model.getValue() });
};
const handlePaste = async () => {
const text = await readClipboardRef.current();
if (text === null) {
editor.trigger('keyboard', 'editor.action.clipboardPasteAction', null);
return;
}
if (!text) return;
const selections = editor.getSelections();
if (!selections || selections.length === 0) return;
editor.executeEdits('netcatty-plugin-paste', buildMonacoPasteEdits(text, selections));
editor.focus();
};
disposablesRef.current.push(
editor.addAction({
id: 'netcatty.pluginCodeEditor.execute',
label: 'Run Query',
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter],
run: emitExecute,
}),
editor.addAction({
id: 'netcatty.pluginCodeEditor.formatAlt',
label: 'Format Query',
keybindings: [
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.Alt | monacoInstance.KeyCode.KeyF,
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyF,
],
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',
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV],
run: () => {
void pasteForMonacoEditorCommand({
activeElement: document.activeElement,
readClipboardText: () => readClipboardRef.current(),
pasteIntoEditor: () => handlePaste(),
});
},
}),
editor.onDidChangeCursorSelection(() => {
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
selectionTimerRef.current = setTimeout(() => {
const model = editor.getModel();
const sel = editor.getSelection();
if (!model || !sel) return;
const selectionStart = model.getOffsetAt(sel.getStartPosition());
const selectionEnd = model.getOffsetAt(sel.getEndPosition());
const selectedText = sel.isEmpty() ? '' : model.getValueInRange(sel);
onWidgetEventRef.current('selection', { selectionStart, selectionEnd, selectedText });
}, 60);
}),
);
requestAnimationFrame(() => editor.layout());
}, []);
const handleChange = useCallback((nextValue: string | undefined) => {
const next = nextValue ?? '';
lastEmittedValueRef.current = next;
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
changeTimerRef.current = setTimeout(() => {
onWidgetEventRef.current('change', { value: next });
}, 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=""
>
<Editor
path={modelPath}
height={resolvedHeight}
language={language}
defaultValue={value}
onChange={handleChange}
onMount={handleMount}
theme={themeName}
loading={(
<div className="absolute inset-0 flex items-center justify-center bg-background">
<Loader2 size={18} className="animate-spin text-muted-foreground" />
</div>
)}
options={{
readOnly,
contextmenu: false,
minimap: { enabled: minimap },
fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
fontSize: 13,
fontLigatures: true,
lineNumbers,
wordWrap,
scrollBeyondLastLine: false,
automaticLayout: true,
tabSize: 2,
insertSpaces: true,
folding: true,
renderLineHighlight: 'line',
padding: { top: 8, bottom: 8 },
bracketPairColorization: { enabled: true },
quickSuggestions: { other: true, comments: false, strings: false },
suggestOnTriggerCharacters: true,
}}
/>
{placeholder && !value ? (
<span
aria-hidden="true"
className="pointer-events-none absolute left-[56px] top-2 z-10 font-mono text-[13px] text-muted-foreground/70"
>
{placeholder}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,709 @@
import { useVirtualizer } from '@tanstack/react-virtual';
import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, KeyRound, Link2, Loader2 } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
PluginDataGridColumn,
PluginDataGridRow,
PluginDataGridWidgetProps,
PluginWidgetEventCallback,
} from './types';
const ROW_HEIGHT = 30;
const HEADER_HEIGHT = 34;
const GUTTER_WIDTH = 64;
const DEFAULT_COL_WIDTH = 156;
const MIN_COL_WIDTH = 68;
const MAX_COL_WIDTH = 640;
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
function readCellValue(row: PluginDataGridRow, col: PluginDataGridColumn, colIndex: number): unknown {
if (Array.isArray(row)) return row[colIndex];
if (row && typeof row === 'object') return row[col.name];
return undefined;
}
function formatCellDisplay(value: unknown): string {
if (value === null || value === undefined) return '';
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean {
if (typeof value === 'number') return true;
if (!col.type) return false;
return /\b(int|bigint|smallint|tinyint|decimal|numeric|float|double|real|number|serial)\b/i.test(col.type);
}
export function PluginDataGrid({
columns = [],
rows = [],
hiddenColumns,
dirtyCells,
deletedRowIndices,
insertedRows = [],
selectedRowIndices,
sort = null,
editable = false,
loading = false,
emptyMessage = 'No rows returned',
onWidgetEvent,
}: PluginDataGridProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const editInputRef = useRef<HTMLInputElement>(null);
const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [colWidths, setColWidths] = useState<Record<string, number>>({});
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
const [editingCell, setEditingCell] = useState<{
rowIndex: number;
colIndex: number;
colName: string;
draft: string;
} | null>(null);
const editingCellRef = useRef(editingCell);
editingCellRef.current = editingCell;
const [lastSelectedRow, setLastSelectedRow] = useState<number | null>(null);
useEffect(() => () => {
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
}, []);
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 => {
const custom = colWidths[col.name];
if (custom !== undefined) return custom;
if (typeof col.width === 'number' && Number.isFinite(col.width)) {
return Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(col.width)));
}
return DEFAULT_COL_WIDTH;
}, [colWidths]);
const rowVirtualizer = useVirtualizer({
count: totalRows,
getScrollElement: () => scrollRef.current,
estimateSize: () => ROW_HEIGHT,
overscan: 8,
initialRect: { width: 960, height: 420 },
});
const colVirtualizer = useVirtualizer({
horizontal: true,
count: visibleCols.length,
getScrollElement: () => scrollRef.current,
estimateSize: (index) => (visibleCols[index] ? getColWidth(visibleCols[index].col) : DEFAULT_COL_WIDTH),
overscan: 4,
initialRect: { width: 960, height: 420 },
});
useEffect(() => {
colVirtualizer.measure();
}, [colWidths, visibleCols, colVirtualizer]);
const editRowIndex = editingCell?.rowIndex;
const editColIndex = editingCell?.colIndex;
useEffect(() => {
if (editRowIndex !== undefined && editColIndex !== undefined) {
const focusInput = () => {
editInputRef.current?.focus();
editInputRef.current?.select();
};
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(focusInput);
} else {
focusInput();
}
}
}, [editRowIndex, editColIndex]);
const getRowAt = useCallback((rowIndex: number): { row: PluginDataGridRow; isInserted: boolean } | null => {
if (rowIndex < rows.length) return { row: rows[rowIndex], isInserted: false };
const insertedIdx = rowIndex - rows.length;
if (insertedIdx >= 0 && insertedIdx < insertedRows.length) {
return { row: insertedRows[insertedIdx], isInserted: true };
}
return null;
}, [rows, insertedRows]);
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, origColIndex: 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;
return {
value: isDirty ? dirtyCells![dirtyKey] : rawValue,
isDirty,
isInserted: entry?.isInserted ?? false,
};
}, [dirtyCells, getRowAt]);
const commitEdit = useCallback((cell: { rowIndex: number; colIndex: number; colName: string; draft: string }, asNull = false) => {
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
editingCellRef.current = null;
setEditingCell(null);
onWidgetEvent('cellEdit', {
rowIndex: cell.rowIndex,
colName: cell.colName,
value: asNull ? null : cell.draft,
isNull: asNull,
});
}, [onWidgetEvent]);
const beginEdit = useCallback((rowIndex: number, visibleColIndex: 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 });
setEditingCell({
rowIndex,
colIndex: visibleColIndex,
colName: entry.col.name,
draft: value === null || value === undefined ? '' : formatCellDisplay(value),
});
}, [editable, deletedSet, visibleCols, getEffectiveValue]);
const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => {
const next = new Set(selectedSet);
if (shiftKey && lastSelectedRow !== null) {
const lo = Math.min(lastSelectedRow, rowIndex);
const hi = Math.max(lastSelectedRow, rowIndex);
for (let i = lo; i <= hi; i += 1) next.add(i);
} else if (next.has(rowIndex)) {
next.delete(rowIndex);
} else {
next.add(rowIndex);
}
setLastSelectedRow(rowIndex);
onWidgetEvent('rowSelect', { selectedRowIndices: [...next].sort((a, b) => a - b) });
}, [selectedSet, lastSelectedRow, onWidgetEvent]);
const toggleSelectAll = useCallback(() => {
if (totalRows === 0) return;
const allSelected = selectedSet.size >= totalRows;
const next = allSelected ? [] : Array.from({ length: totalRows }, (_, i) => i);
onWidgetEvent('rowSelect', { selectedRowIndices: next });
}, [totalRows, selectedSet.size, onWidgetEvent]);
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
if (col.sortable === false) return;
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
}, [sort, onWidgetEvent]);
const startResizeColumn = useCallback((event: React.PointerEvent<HTMLDivElement>, col: PluginDataGridColumn) => {
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
const startWidth = getColWidth(col);
const target = event.currentTarget;
try { target.setPointerCapture(event.pointerId); } catch { /* pointer capture unsupported */ }
const onMove = (moveEvent: PointerEvent) => {
const nextWidth = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(startWidth + (moveEvent.clientX - startX))));
setColWidths((prev) => (prev[col.name] === nextWidth ? prev : { ...prev, [col.name]: nextWidth }));
};
const onUp = () => {
try { target.releasePointerCapture(event.pointerId); } catch { /* pointer already released */ }
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [getColWidth]);
const handleCellContextMenu = useCallback((
event: React.MouseEvent,
rowIndex: number,
colName: string,
) => {
event.preventDefault();
event.stopPropagation();
const surface = scrollRef.current?.closest('[data-plugin-remote-surface]');
const rect = surface?.getBoundingClientRect();
const x = Math.round(rect ? event.clientX - rect.left : event.clientX);
const y = Math.round(rect ? event.clientY - rect.top : event.clientY);
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 { /* clipboard unavailable */ }
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 { /* clipboard unavailable */ }
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;
const { rowIndex, colIndex } = activeCell;
if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) {
event.preventDefault();
setActiveCell({ rowIndex: rowIndex + 1, colIndex });
rowVirtualizer.scrollToIndex(rowIndex + 1);
} else if (event.key === 'ArrowUp' && rowIndex > 0) {
event.preventDefault();
setActiveCell({ rowIndex: rowIndex - 1, colIndex });
rowVirtualizer.scrollToIndex(rowIndex - 1);
} else if (event.key === 'ArrowRight' && colIndex + 1 < visibleCols.length) {
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex + 1 });
colVirtualizer.scrollToIndex(colIndex + 1);
} else if (event.key === 'ArrowLeft' && colIndex > 0) {
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex - 1 });
colVirtualizer.scrollToIndex(colIndex - 1);
} else if ((event.key === 'Enter' || event.key === 'F2') && 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,
]);
const virtualRows = rowVirtualizer.getVirtualItems();
const virtualCols = colVirtualizer.getVirtualItems();
const totalWidth = GUTTER_WIDTH + colVirtualizer.getTotalSize();
const totalHeight = rowVirtualizer.getTotalSize();
const allSelected = totalRows > 0 && selectedSet.size >= totalRows;
return (
<div
className="relative flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground select-none"
data-plugin-data-grid=""
tabIndex={0}
onKeyDown={handleGridKeyDown}
>
{loading && (
<div className="pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center justify-end px-2 py-1">
<span className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background/95 px-2 py-0.5 text-[11px] text-muted-foreground shadow-sm">
<Loader2 size={12} className="animate-spin" />
Loading...
</span>
</div>
)}
<div ref={scrollRef} className="relative h-full w-full min-h-0 flex-1 overflow-auto">
{visibleCols.length === 0 ? (
<div className="flex h-full w-full items-center justify-center p-6 text-xs text-muted-foreground">
{emptyMessage}
</div>
) : (
<div style={{ width: totalWidth, minWidth: '100%', position: 'relative' }}>
{/* Sticky Header */}
<div
role="row"
className="sticky top-0 z-30 flex border-b border-border bg-muted text-[11px] font-medium text-foreground"
style={{ height: HEADER_HEIGHT, width: totalWidth, minWidth: '100%' }}
>
<div
className="sticky left-0 z-40 flex shrink-0 items-center justify-between border-r border-border bg-muted px-2 text-[10px] text-muted-foreground"
style={{ width: GUTTER_WIDTH, height: HEADER_HEIGHT }}
>
<input
type="checkbox"
aria-label="Select all rows"
checked={allSelected}
onChange={toggleSelectAll}
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
/>
<span className="font-mono">#</span>
</div>
<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 isSorted = sort?.column === col.name;
const sortable = col.sortable !== false;
return (
<div
key={col.name}
role="columnheader"
data-col-name={col.name}
className="group absolute top-0 bottom-0 flex items-center justify-between gap-1 border-r border-border/70 px-2.5"
style={{
left: vCol.start,
width: vCol.size,
}}
>
<button
type="button"
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}
>
{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">
{col.type}
</span>
)}
</button>
{sortable && (
<span className="shrink-0 text-muted-foreground/70">
{isSorted ? (
sort.direction === 'asc' ? <ArrowUp size={11} className="text-primary" /> : <ArrowDown size={11} className="text-primary" />
) : (
<ArrowUpDown size={10} className="opacity-0 group-hover:opacity-70 transition-opacity" />
)}
</span>
)}
<div
role="separator"
aria-orientation="vertical"
onPointerDown={(e) => startResizeColumn(e, col)}
className="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/60"
/>
</div>
);
})}
</div>
</div>
{/* Virtualized Rows Body */}
{totalRows === 0 ? (
<div className="flex h-40 w-full items-center justify-center text-xs text-muted-foreground">
{emptyMessage}
</div>
) : (
<div style={{ height: totalHeight, width: totalWidth, minWidth: '100%', position: 'relative' }}>
{virtualRows.map((vRow) => {
const rowIndex = vRow.index;
const entry = getRowAt(rowIndex);
if (!entry) return null;
const isDeleted = deletedSet.has(rowIndex);
const isSelected = selectedSet.has(rowIndex);
const isInserted = entry.isInserted;
const rowBg = isDeleted
? 'bg-destructive/10 text-destructive/80 line-through'
: isInserted
? 'bg-emerald-500/10'
: isSelected
? 'bg-primary/10'
: rowIndex % 2 === 1
? 'bg-muted/20'
: 'bg-background';
return (
<div
key={rowIndex}
role="row"
data-row-index={rowIndex}
className={`absolute left-0 flex border-b border-border/50 hover:bg-muted/50 ${rowBg}`}
style={{
top: vRow.start,
height: vRow.size,
width: totalWidth,
minWidth: '100%',
}}
>
{/* Sticky Gutter */}
<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 ?? '')}
>
<input
type="checkbox"
aria-label={`Select row ${rowIndex + 1}`}
checked={isSelected}
onChange={() => {}}
onClick={(e) => {
e.stopPropagation();
toggleRowSelection(rowIndex, e.shiftKey);
}}
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
/>
<span className={isInserted ? 'font-bold text-emerald-500' : ''}>
{isInserted ? '+' : rowIndex + 1}
</span>
</div>
{/* 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 isNull = value === null || value === undefined;
const numeric = !isNull && isNumericColumn(col, value);
const fk = col.foreignKey;
return (
<div
key={col.name}
role="gridcell"
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 ${
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 });
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,
});
}
}}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)}
>
{isEditing ? (
<div
className="flex h-full w-full items-center gap-1"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
<input
ref={editInputRef}
type="text"
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();
commitEdit(editingCell, false);
} else if (e.key === 'Escape') {
e.preventDefault();
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
editingCellRef.current = null;
setEditingCell(null);
} else if (e.key === 'Tab') {
e.preventDefault();
commitEdit(editingCell, false);
const nextCol = e.shiftKey ? visibleColIndex - 1 : visibleColIndex + 1;
if (nextCol >= 0 && nextCol < visibleCols.length) {
beginEdit(rowIndex, nextCol);
}
}
}}
onBlur={() => {
const snapshot = editingCell;
if (blurTimerRef.current !== null) clearTimeout(blurTimerRef.current);
blurTimerRef.current = setTimeout(() => {
blurTimerRef.current = null;
const curr = editingCellRef.current;
if (curr && curr.rowIndex === snapshot.rowIndex && curr.colIndex === snapshot.colIndex) {
commitEdit(curr, false);
}
}, 0);
}}
className="h-6 min-w-0 flex-1 rounded border border-primary bg-background px-1.5 font-mono text-[12px] text-foreground outline-none"
/>
{col.nullable !== false && (
<button
type="button"
onMouseDown={(e) => {
e.preventDefault();
commitEdit(editingCell, true);
}}
className="shrink-0 rounded border border-border bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
title="Set value to NULL"
>
NULL
</button>
)}
</div>
) : isNull ? (
<span className="inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] italic text-muted-foreground">
NULL
</span>
) : typeof value === 'boolean' ? (
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${
value
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
: 'bg-muted text-muted-foreground'
}`}
>
{value ? 'true' : 'false'}
</span>
) : (
<span className="truncate" title={formatCellDisplay(value)}>
{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>
);
})}
</div>
</div>
);
})}
</div>
)}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,566 @@
import { Download, 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 GRID_GAP_Y = 56;
const MIN_ZOOM = 0.25;
const MAX_ZOOM = 2.5;
export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
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);
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 y = colY[colIdx];
result[key] = { x, y };
colY[colIdx] = y + erCardHeight(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 = [],
onWidgetEvent,
}: PluginErCanvasProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables));
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [selectedTable, setSelectedTable] = useState<string | null>(null);
const [hoveredRelation, setHoveredRelation] = useState<number | null>(null);
const [panning, setPanning] = useState(false);
const tableSignature = useMemo(
() => tables.map((t) => `${erTableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
[tables],
);
useEffect(() => {
setPositions((prev) => {
const defaults = computeInitialPositions(tables);
const next: Record<string, { x: number; y: number }> = {};
for (const tbl of tables) {
const key = erTableKey(tbl);
next[key] = prev[key] ?? defaults[key];
}
return next;
});
}, [tableSignature, tables]);
const tableLookup = useMemo(() => {
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);
}
return { byKey, byName };
}, [tables]);
const resolveTable = useCallback((ref: string): PluginErTable | undefined => (
tableLookup.byKey.get(ref) ?? tableLookup.byName.get(ref)
), [tableLookup]);
const fitToView = useCallback(() => {
const el = containerRef.current;
if (!el || tables.length === 0) {
setViewport({ x: 0, y: 0, zoom: 1 });
return;
}
const rect = el.getBoundingClientRect();
if (!rect.width || !rect.height) return;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const tbl of tables) {
const pos = positions[erTableKey(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));
}
const contentW = Math.max(1, maxX - minX);
const contentH = Math.max(1, maxY - minY);
const pad = 48;
const zoom = Math.max(
MIN_ZOOM,
Math.min(1.15, Math.min((rect.width - pad * 2) / contentW, (rect.height - pad * 2) / contentH)),
);
const x = (rect.width - contentW * zoom) / 2 - minX * zoom;
const y = (rect.height - contentH * zoom) / 2 - minY * zoom;
setViewport({ x, y, zoom });
}, [tables, positions]);
const fitToViewRef = useRef(fitToView);
fitToViewRef.current = fitToView;
useEffect(() => {
if (typeof requestAnimationFrame !== 'function') {
fitToViewRef.current();
return;
}
const frame = requestAnimationFrame(() => fitToViewRef.current());
return () => cancelAnimationFrame(frame);
}, [tableSignature]);
const handleWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
event.preventDefault();
const el = containerRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
const factor = event.deltaY < 0 ? 1.1 : 0.9;
setViewport((prev) => {
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
const scale = nextZoom / prev.zoom;
return {
zoom: nextZoom,
x: mouseX - (mouseX - prev.x) * scale,
y: mouseY - (mouseY - prev.y) * scale,
};
});
}, []);
const handleCanvasPointerDown = useCallback((event: React.PointerEvent<SVGSVGElement>) => {
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;
const initialY = viewport.y;
setPanning(true);
const onMove = (moveEvent: PointerEvent) => {
setViewport((prev) => ({
...prev,
x: initialX + (moveEvent.clientX - startX),
y: initialY + (moveEvent.clientY - startY),
}));
};
const onUp = () => {
setPanning(false);
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [viewport.x, viewport.y]);
const startCardDrag = useCallback((event: React.PointerEvent<SVGGElement>, table: PluginErTable) => {
if (event.button !== 0) return;
event.stopPropagation();
containerRef.current?.focus();
const key = erTableKey(table);
const startX = event.clientX;
const startY = event.clientY;
const origin = positions[key] ?? { x: 0, y: 0 };
const zoom = viewport.zoom;
let moved = false;
const onMove = (moveEvent: PointerEvent) => {
const dx = moveEvent.clientX - startX;
const dy = moveEvent.clientY - startY;
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true;
if (!moved) return;
setPositions((prev) => ({
...prev,
[key]: { x: Math.round(origin.x + dx / zoom), y: Math.round(origin.y + dy / zoom) },
}));
};
const onUp = () => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
if (!moved) {
setSelectedTable(key);
onWidgetEvent('tableClick', {
table: table.name,
...(table.schema ? { schema: table.schema } : {}),
});
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
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();
const cx = rect ? rect.width / 2 : 300;
const cy = rect ? rect.height / 2 : 200;
setViewport((prev) => {
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
const scale = nextZoom / prev.zoom;
return {
zoom: nextZoom,
x: cx - (cx - prev.x) * scale,
y: cy - (cy - prev.y) * scale,
};
});
}, []);
const resetLayout = useCallback(() => {
setPositions(computeInitialPositions(tables));
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(fitToView);
} else {
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"
>
{/* 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">
<button
type="button"
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"
>
<ZoomIn size={13} />
</button>
<span className="min-w-[40px] text-center font-mono text-[11px] tabular-nums text-muted-foreground">
{Math.round(viewport.zoom * 100)}%
</span>
<button
type="button"
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"
>
<ZoomOut size={13} />
</button>
<div className="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
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"
>
<Maximize2 size={12} />
Fit
</button>
<button
type="button"
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"
>
<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 ? (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
No tables to visualize
</div>
) : (
<svg
className={`h-full w-full ${panning ? 'cursor-grabbing' : 'cursor-grab'}`}
onPointerDown={handleCanvasPointerDown}
>
<defs>
<pattern id="nc-er-dots" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="1" cy="1" r="1" fill="hsl(var(--border))" opacity="0.55" />
</pattern>
<filter id="nc-er-shadow" x="-10%" y="-10%" width="120%" height="125%">
<feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#000000" floodOpacity="0.14" />
</filter>
</defs>
<rect width="100%" height="100%" fill="url(#nc-er-dots)" />
<g transform={`translate(${viewport.x}, ${viewport.y}) scale(${viewport.zoom})`}>
{/* Foreign Key Bezier Curves */}
{relations.map((rel, idx) => {
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) return null;
const fromKey = erTableKey(fromTable);
const toKey = erTableKey(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 goRight = toCenter >= fromCenter;
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;
const isHovered = hoveredRelation === idx;
const highlighted = isHovered || 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)}
>
<path
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
fill="none"
stroke="transparent"
strokeWidth={14}
/>
<path
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
fill="none"
stroke={stroke}
strokeWidth={highlighted ? 2.2 : 1.4}
strokeOpacity={highlighted ? 1 : 0.65}
/>
<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>
)}
</g>
);
})}
{/* Table Cards */}
{tables.map((table) => {
const key = erTableKey(table);
const pos = positions[key] ?? { x: 0, y: 0 };
const height = erCardHeight(table);
const isSelected = selectedTable === key;
return (
<g
key={key}
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}
height={height}
rx={8}
fill="hsl(var(--card))"
stroke={isSelected ? 'hsl(var(--primary))' : 'hsl(var(--border))'}
strokeWidth={isSelected ? 2 : 1}
/>
{/* 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`}
fill="hsl(var(--muted))"
/>
<line
x1={0}
y1={ER_CARD_HEADER_HEIGHT}
x2={ER_CARD_WIDTH}
y2={ER_CARD_HEADER_HEIGHT}
stroke="hsl(var(--border))"
strokeWidth={1}
/>
<text
x={12}
y={21}
fontSize={12}
fontWeight={600}
fontFamily="var(--font-sans)"
fill="hsl(var(--card-foreground))"
>
{table.schema ? `${table.schema}.${table.name}` : table.name}
</text>
{/* Columns */}
{table.columns.map((col, colIdx) => {
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_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}
y2={0}
stroke="hsl(var(--border))"
strokeOpacity={0.45}
strokeWidth={0.75}
/>
)}
{col.isPk && (
<g transform="translate(8, 5)">
<rect width={22} height={14} rx={3} fill="#f59e0b" fillOpacity={0.2} />
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#d97706">
PK
</text>
</g>
)}
{col.isFk && (
<g transform={`translate(${col.isPk ? 34 : 8}, 5)`}>
<rect width={22} height={14} rx={3} fill="#3b82f6" fillOpacity={0.2} />
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#2563eb">
FK
</text>
</g>
)}
<text
x={10 + badgeOffset}
y={16}
fontSize={11}
fontFamily="var(--font-mono)"
fill="hsl(var(--card-foreground))"
>
{displayName}
</text>
<text
x={ER_CARD_WIDTH - 10}
y={16}
textAnchor="end"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--muted-foreground))"
>
{displayType}
</text>
</g>
);
})}
</g>
);
})}
</g>
</svg>
)}
</div>
);
}
@@ -0,0 +1,198 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { PluginSplitPaneWidgetProps, PluginWidgetEventCallback } from './types';
export interface PluginSplitPaneProps extends PluginSplitPaneWidgetProps {
firstChild: React.ReactNode;
secondChild: React.ReactNode;
nodeId: string;
className?: string;
inlineStyle?: string;
onWidgetEvent: PluginWidgetEventCallback;
}
/**
* 60fps host-managed 2-child split container rendered inside the shadow root so
* child plugin trees keep full plugin CSS scoping and can nest freely.
*/
export function PluginSplitPane({
direction = 'horizontal',
initialSize = 260,
minSize = 120,
maxSize = 900,
collapsible = false,
collapsed: controlledCollapsed,
firstChild,
secondChild,
nodeId,
className,
inlineStyle,
onWidgetEvent,
}: PluginSplitPaneProps) {
const containerRef = useRef<HTMLDivElement>(null);
const clampSize = useCallback(
(raw: number) => Math.max(minSize, Math.min(maxSize, Math.round(raw))),
[minSize, maxSize],
);
const [size, setSize] = useState<number>(() => clampSize(initialSize));
const [collapsed, setCollapsed] = useState<boolean>(Boolean(controlledCollapsed));
const [dragging, setDragging] = useState(false);
const [hovered, setHovered] = useState(false);
const sizeRef = useRef(size);
sizeRef.current = size;
useEffect(() => {
if (controlledCollapsed !== undefined) setCollapsed(controlledCollapsed);
}, [controlledCollapsed]);
const isHorizontal = direction !== 'vertical';
const handlePointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
const target = event.currentTarget;
const startCoord = isHorizontal ? event.clientX : event.clientY;
const startSize = collapsed ? minSize : sizeRef.current;
setDragging(true);
try { target.setPointerCapture(event.pointerId); } catch { /* pointer capture unsupported */ }
let latestSize = startSize;
let latestCollapsed = collapsed;
const onMove = (moveEvent: PointerEvent) => {
const containerRect = containerRef.current?.getBoundingClientRect();
const maxFromContainer = containerRect
? Math.max(minSize, (isHorizontal ? containerRect.width : containerRect.height) - 64)
: maxSize;
const effectiveMax = Math.min(maxSize, maxFromContainer);
const delta = (isHorizontal ? moveEvent.clientX : moveEvent.clientY) - startCoord;
const raw = startSize + delta;
if (collapsible && raw < minSize * 0.5) {
latestCollapsed = true;
setCollapsed(true);
} else {
latestCollapsed = false;
latestSize = Math.max(minSize, Math.min(effectiveMax, Math.round(raw)));
setCollapsed(false);
setSize(latestSize);
}
};
const onUp = () => {
setDragging(false);
try { target.releasePointerCapture(event.pointerId); } catch { /* pointer already released */ }
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
onWidgetEvent('resizeEnd', {
size: latestCollapsed ? 0 : latestSize,
collapsed: latestCollapsed,
});
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [isHorizontal, collapsed, minSize, maxSize, collapsible, onWidgetEvent]);
const handleDoubleClick = useCallback(() => {
if (!collapsible) return;
const nextCollapsed = !collapsed;
setCollapsed(nextCollapsed);
onWidgetEvent('resizeEnd', {
size: nextCollapsed ? 0 : sizeRef.current,
collapsed: nextCollapsed,
});
}, [collapsible, collapsed, onWidgetEvent]);
const setContainerRef = useCallback((el: HTMLDivElement | null) => {
containerRef.current = el;
if (!el) return;
if (inlineStyle) {
el.setAttribute('style', `${inlineStyle};display:flex;flex-direction:${isHorizontal ? 'row' : 'column'};width:100%;height:100%;min-width:0;min-height:0;overflow:hidden`);
}
}, [inlineStyle, isHorizontal]);
const dividerActive = dragging || hovered;
return (
<div
ref={setContainerRef}
data-netcatty-remote-node={nodeId}
data-plugin-widget="split-pane"
data-direction={isHorizontal ? 'horizontal' : 'vertical'}
className={className}
style={{
display: 'flex',
flexDirection: isHorizontal ? 'row' : 'column',
width: '100%',
height: '100%',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
userSelect: dragging ? 'none' : undefined,
}}
>
<div
data-split-pane="first"
style={{
flex: collapsed ? '0 0 0px' : `0 0 ${size}px`,
display: collapsed ? 'none' : 'flex',
flexDirection: 'column',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
}}
>
{firstChild}
</div>
<div
role="separator"
aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}
aria-valuenow={collapsed ? 0 : size}
aria-valuemin={minSize}
aria-valuemax={maxSize}
data-split-handle=""
onPointerDown={handlePointerDown}
onDoubleClick={handleDoubleClick}
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
style={{
position: 'relative',
flex: isHorizontal ? '0 0 5px' : '0 0 5px',
cursor: isHorizontal ? 'col-resize' : 'row-resize',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
zIndex: 5,
touchAction: 'none',
}}
>
<div
style={{
width: isHorizontal ? (dividerActive ? '2px' : '1px') : '100%',
height: isHorizontal ? '100%' : (dividerActive ? '2px' : '1px'),
background: dividerActive ? 'hsl(var(--primary))' : 'hsl(var(--border))',
transition: 'background 120ms ease',
}}
/>
</div>
<div
data-split-pane="second"
style={{
flex: '1 1 0%',
display: 'flex',
flexDirection: 'column',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
}}
>
{secondChild}
</div>
</div>
);
}
@@ -0,0 +1,55 @@
import React, { useMemo } from 'react';
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
import { PluginCodeEditor } from './PluginCodeEditor';
import { PluginDataGrid } from './PluginDataGrid';
import { PluginErCanvas } from './PluginErCanvas';
import type {
PluginCodeEditorWidgetProps,
PluginDataGridWidgetProps,
PluginErCanvasWidgetProps,
PluginWidgetEventCallback,
} from './types';
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas';
export function parseWidgetPropsJson<T extends object>(raw: string | undefined): T {
if (!raw) return {} as T;
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as T;
}
} catch {
// Policy already validates widget props; fall back to empty props defensively.
}
return {} as T;
}
export function PluginSlottedWidget({
kind,
rawProps,
onWidgetEvent,
}: {
kind: SlottedWidgetKind;
rawProps: string | undefined;
onWidgetEvent: PluginWidgetEventCallback;
}) {
const parsedProps = useMemo(() => parseWidgetPropsJson<Record<string, unknown>>(rawProps), [rawProps]);
return (
<LazyLoadBoundary
name={`Plugin ${kind}`}
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to render plugin widget.</div>}
>
{kind === 'code-editor' && (
<PluginCodeEditor {...(parsedProps as PluginCodeEditorWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
{kind === 'data-grid' && (
<PluginDataGrid {...(parsedProps as PluginDataGridWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
{kind === 'er-canvas' && (
<PluginErCanvas {...(parsedProps as PluginErCanvasWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
</LazyLoadBoundary>
);
}
@@ -0,0 +1,55 @@
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
@@ -0,0 +1,155 @@
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');
}
@@ -0,0 +1,36 @@
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;
}
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
test('extractCurrentSqlStatement splits statements respecting strings, comments, and PG dollar quotes', () => {
const sql = [
"-- first query; not a split",
"SELECT 'semi;colon' AS a;",
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql;",
"SELECT /* block; comment */ * FROM orders WHERE id = 1",
].join('\n');
const firstIdx = sql.indexOf("SELECT 'semi");
assert.equal(extractCurrentSqlStatement(sql, firstIdx + 5), "-- first query; not a split\nSELECT 'semi;colon' AS a");
const fnIdx = sql.indexOf("RETURN 'x;y'");
assert.equal(
extractCurrentSqlStatement(sql, fnIdx),
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql",
);
const lastIdx = sql.indexOf('FROM orders');
assert.equal(
extractCurrentSqlStatement(sql, lastIdx),
'SELECT /* block; comment */ * FROM orders WHERE id = 1',
);
});
test('extractSqlTableAliases resolves table names and aliases across FROM and JOIN clauses', () => {
const sql = 'SELECT o.id, u.email FROM public.orders AS o INNER JOIN users u ON u.id = o.user_id WHERE o.status = 1';
const aliases = extractSqlTableAliases(sql);
assert.equal(aliases.get('o'), 'orders');
assert.equal(aliases.get('orders'), 'orders');
assert.equal(aliases.get('u'), 'users');
assert.equal(aliases.get('users'), 'users');
assert.equal(aliases.has('where'), false);
});
@@ -0,0 +1,164 @@
/**
* Pure SQL statement and alias helpers used by PluginCodeEditor.
* Runs synchronously in the host renderer with zero IPC overhead.
*/
export function extractCurrentSqlStatement(sql: string, cursorOffset: number): string {
if (!sql) return '';
const clampedCursor = Math.max(0, Math.min(cursorOffset, sql.length));
const statements: Array<{ start: number; end: number; text: string }> = [];
let start = 0;
let i = 0;
let inSingle = false;
let inDouble = false;
let inBacktick = false;
let inLineComment = false;
let inBlockComment = false;
let dollarTag: string | null = null;
while (i < sql.length) {
const ch = sql[i];
const next = sql[i + 1];
if (inLineComment) {
if (ch === '\n') inLineComment = false;
i += 1;
continue;
}
if (inBlockComment) {
if (ch === '*' && next === '/') {
inBlockComment = false;
i += 2;
continue;
}
i += 1;
continue;
}
if (dollarTag !== null) {
if (sql.startsWith(dollarTag, i)) {
i += dollarTag.length;
dollarTag = null;
continue;
}
i += 1;
continue;
}
if (inSingle) {
if (ch === "'" && next === "'") {
i += 2;
continue;
}
if (ch === '\\' && next !== undefined) {
i += 2;
continue;
}
if (ch === "'") inSingle = false;
i += 1;
continue;
}
if (inDouble) {
if (ch === '"' && next === '"') {
i += 2;
continue;
}
if (ch === '"') inDouble = false;
i += 1;
continue;
}
if (inBacktick) {
if (ch === '`' && next === '`') {
i += 2;
continue;
}
if (ch === '`') inBacktick = false;
i += 1;
continue;
}
if (ch === '-' && next === '-') {
inLineComment = true;
i += 2;
continue;
}
if (ch === '/' && next === '*') {
inBlockComment = true;
i += 2;
continue;
}
if (ch === "'") {
inSingle = true;
i += 1;
continue;
}
if (ch === '"') {
inDouble = true;
i += 1;
continue;
}
if (ch === '`') {
inBacktick = true;
i += 1;
continue;
}
if (ch === '$') {
const match = /^\$[a-zA-Z0-9_]*\$/u.exec(sql.slice(i));
if (match) {
dollarTag = match[0];
i += dollarTag.length;
continue;
}
}
if (ch === ';') {
const raw = sql.slice(start, i);
if (raw.trim().length > 0) {
statements.push({ start, end: i + 1, text: raw.trim() });
}
start = i + 1;
i += 1;
continue;
}
i += 1;
}
const tail = sql.slice(start);
if (tail.trim().length > 0) {
statements.push({ start, end: sql.length, text: tail.trim() });
}
if (statements.length === 0) return sql.trim();
for (const stmt of statements) {
if (clampedCursor >= stmt.start && clampedCursor <= stmt.end) {
return stmt.text;
}
}
// If cursor sits in trailing whitespace after a semicolon, return the preceding statement.
let chosen = statements[0];
for (const stmt of statements) {
if (stmt.start <= clampedCursor) chosen = stmt;
}
return chosen.text;
}
/** Extract simple `FROM/JOIN [schema.]table [AS] alias` bindings for dot-completion. */
export function extractSqlTableAliases(sql: string): Map<string, string> {
const aliases = new Map<string, string>();
const pattern = /\b(?:from|join|update|into)\s+(?:["`]?([a-zA-Z_][\w$]*)["`]?\.)?["`]?([a-zA-Z_][\w$]*)["`]?(?:\s+(?:as\s+)?["`]?([a-zA-Z_][\w$]*)["`]?)?/giu;
const reserved = new Set([
'where', 'on', 'set', 'values', 'inner', 'left', 'right', 'full', 'outer',
'cross', 'join', 'group', 'order', 'having', 'limit', 'offset', 'union',
'select', 'from', 'as', 'using', 'returning',
]);
let match: RegExpExecArray | null;
while ((match = pattern.exec(sql)) !== null) {
const tableName = match[2];
const alias = match[3];
if (!tableName) continue;
aliases.set(tableName.toLowerCase(), tableName);
if (alias && !reserved.has(alias.toLowerCase())) {
aliases.set(alias.toLowerCase(), tableName);
}
}
return aliases;
}
+136
View File
@@ -0,0 +1,136 @@
export type PluginWidgetEventCallback = (
widgetEvent: string,
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;
}
export interface PluginCodeEditorCompletionTable {
name: string;
schema?: string;
columns?: PluginCodeEditorCompletionColumn[];
}
export interface PluginCodeEditorCompletionFunction {
name: string;
detail?: string;
insertText?: string;
}
export interface PluginCodeEditorCompletionSchema {
tables?: PluginCodeEditorCompletionTable[];
functions?: PluginCodeEditorCompletionFunction[];
keywords?: string[];
}
export interface PluginCodeEditorDiagnostic {
line: number;
column: number;
endLine?: number;
endColumn?: number;
message: string;
severity?: 'error' | 'warning' | 'info' | 'hint';
}
export interface PluginCodeEditorWidgetProps {
value?: string;
language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext';
readOnly?: boolean;
placeholder?: string;
lineNumbers?: 'on' | 'off' | 'relative';
minimap?: boolean;
wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded';
completionSchema?: PluginCodeEditorCompletionSchema;
diagnostics?: PluginCodeEditorDiagnostic[];
height?: number | string;
}
export interface PluginDataGridForeignKey {
table: string;
column: string;
schema?: string;
}
export interface PluginDataGridColumn {
name: string;
type?: string;
primaryKey?: boolean;
nullable?: boolean;
width?: number;
sortable?: boolean;
foreignKey?: PluginDataGridForeignKey;
}
export interface PluginDataGridSort {
column: string;
direction: 'asc' | 'desc';
}
export type PluginDataGridRow = Record<string, unknown> | unknown[];
export interface PluginDataGridWidgetProps {
columns?: PluginDataGridColumn[];
rows?: PluginDataGridRow[];
hiddenColumns?: string[];
rowKeyField?: string;
dirtyCells?: Record<string, unknown>;
deletedRowIndices?: number[];
insertedRows?: PluginDataGridRow[];
selectedRowIndices?: number[];
sort?: PluginDataGridSort | null;
editable?: boolean;
loading?: boolean;
emptyMessage?: string;
}
export interface PluginSplitPaneWidgetProps {
direction?: 'horizontal' | 'vertical';
initialSize?: number;
minSize?: number;
maxSize?: number;
collapsible?: boolean;
collapsed?: boolean;
}
export interface PluginErColumn {
name: string;
type: string;
isPk?: boolean;
isFk?: boolean;
nullable?: boolean;
}
export interface PluginErTable {
name: string;
schema?: string;
columns: PluginErColumn[];
x?: number;
y?: number;
}
export interface PluginErRelation {
fromTable: string;
fromColumn: string;
toTable: string;
toColumn: string;
name?: string;
onDelete?: string;
onUpdate?: string;
}
export interface PluginErCanvasWidgetProps {
tables?: PluginErTable[];
relations?: PluginErRelation[];
}
@@ -0,0 +1,57 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { enSystemManagerMessages } from '../../application/i18n/locales/en/systemManager.ts';
import { esSystemManagerMessages } from '../../application/i18n/locales/es/systemManager.ts';
import { ruSystemManagerMessages } from '../../application/i18n/locales/ru/systemManager.ts';
import { zhCnSystemManagerMessages } from '../../application/i18n/locales/zh-CN/systemManager.ts';
import { zhTwSystemManagerMessages } from '../../application/i18n/locales/zh-TW/systemManager.ts';
test('PortsManagerTab and QuickPortForwardDialog i18n keys exist across all five locales', () => {
const portsSource = readFileSync(new URL('./PortsManagerTab.tsx', import.meta.url), 'utf8');
const dialogSource = readFileSync(new URL('./QuickPortForwardDialog.tsx', import.meta.url), 'utf8');
const combined = `${portsSource}\n${dialogSource}`;
const keys = [...new Set([...combined.matchAll(/\bt\(['"](systemManager\.ports\.[^'"]+)['"]/g)].map((m) => m[1]))];
assert.ok(keys.length >= 15, `expected quick-forward i18n keys, found ${keys.length}`);
const locales = {
en: enSystemManagerMessages,
es: esSystemManagerMessages,
ru: ruSystemManagerMessages,
'zh-CN': zhCnSystemManagerMessages,
'zh-TW': zhTwSystemManagerMessages,
} as const;
for (const [locale, messages] of Object.entries(locales)) {
for (const key of keys) {
assert.ok(messages[key]?.trim(), `${locale} missing key: ${key}`);
if (locale !== 'en') {
assert.notEqual(messages[key], enSystemManagerMessages[key], `${locale} left ${key} untranslated`);
}
}
}
// Ensure Taiwan Traditional Chinese uses Taiwan terminology.
const zhTwForwardText = keys.map((key) => zhTwSystemManagerMessages[key]).join('\n');
assert.equal(zhTwForwardText.includes('端口'), false);
assert.equal(zhTwForwardText.includes('本地'), false);
assert.equal(zhTwForwardText.includes('地址'), false);
});
test('PortsManagerTab wires quick port forwarding with active badge, stop action, and dialog', () => {
const source = readFileSync(new URL('./PortsManagerTab.tsx', import.meta.url), 'utf8');
const slotSource = readFileSync(
new URL('../terminalLayer/terminalLayerSidePanelSlots.tsx', import.meta.url),
'utf8',
);
assert.match(source, /useQuickPortForwarding/);
assert.match(source, /QuickPortForwardDialog/);
assert.match(source, /isForwardableListeningPort/);
assert.match(source, /matchListeningPortForwardRules/);
assert.match(source, /handleCopyLocalEndpoint/);
assert.match(source, /handleStopForward/);
assert.match(slotSource, /portForwardingContext=\{portForwardingContext\}/);
});
+251 -27
View File
@@ -1,10 +1,27 @@
import { Network, Skull } from 'lucide-react';
import { ArrowRightLeft, Network, Skull, Square } from 'lucide-react';
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import {
useQuickPortForwarding,
type QuickPortForwardingContext,
} from '../../application/state/useQuickPortForwarding';
import type { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend';
import { usePolling, useStableTranslate } from '../../application/state/useSystemManager';
import type { PortForwardingRule } from '../../domain/models';
import { listeningPortInfoEqual } from '../../domain/systemManager/pollEquals';
import {
DEFAULT_QUICK_FORWARD_BIND_ADDRESS,
formatCopyableLocalEndpoint,
formatHostPort,
isForwardableListeningPort,
matchListeningPortForwardRules,
resolveForwardRemoteHost,
suggestQuickForwardLocalPort,
} from '../../domain/systemManager/portForwardQuick';
import type { ListeningPortInfo } from '../../domain/systemManager/types';
import { toast } from '../ui/toast';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
import { QuickPortForwardDialog } from './QuickPortForwardDialog';
import { SystemPanelConfirmDialog } from './SystemPanelConfirmDialog';
import { mergePollListByKey, useStableListOrder } from './listStable';
import {
@@ -39,6 +56,8 @@ interface PortsManagerTabProps {
refreshIntervalSec: number;
/** Network appliances: list only, no process terminate. */
allowMutations?: boolean;
/** Optional host/auth context enabling one-click SSH local port forwarding. */
portForwardingContext?: QuickPortForwardingContext;
}
export const PortsManagerTab = memo(function PortsManagerTab({
@@ -47,6 +66,7 @@ export const PortsManagerTab = memo(function PortsManagerTab({
backend,
refreshIntervalSec,
allowMutations = true,
portForwardingContext,
}: PortsManagerTabProps) {
const { t } = useI18n();
const stableT = useStableTranslate();
@@ -57,14 +77,24 @@ export const PortsManagerTab = memo(function PortsManagerTab({
const [killBusy, setKillBusy] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
const [listPending, setListPending] = useState(false);
const [forwardDialogPort, setForwardDialogPort] = useState<ListeningPortInfo | null>(null);
const [forwardDialogInitialPort, setForwardDialogInitialPort] = useState<number>(8080);
const [forwardDialogInitialBind, setForwardDialogInitialBind] = useState<string>(DEFAULT_QUICK_FORWARD_BIND_ADDRESS);
const [forwardBusy, setForwardBusy] = useState(false);
const [forwardError, setForwardError] = useState<string | null>(null);
const sessionIdRef = useRef(sessionId);
sessionIdRef.current = sessionId;
const quickForward = useQuickPortForwarding(portForwardingContext);
useEffect(() => {
setListPending(false);
setPendingKillPid(null);
setKillBusy(false);
setActionError(null);
setForwardDialogPort(null);
setForwardBusy(false);
setForwardError(null);
}, [sessionId]);
const fetcher = useCallback(async (): Promise<ListeningPortInfo[] | null> => {
@@ -120,6 +150,103 @@ export const PortsManagerTab = memo(function PortsManagerTab({
(a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol),
);
const portMatchesById = useMemo(() => {
const map = new Map<string, ReturnType<typeof matchListeningPortForwardRules>>();
if (!quickForward.canForward || !quickForward.hostId) return map;
for (const port of ports) {
map.set(
port.id,
matchListeningPortForwardRules(port, quickForward.hostId, quickForward.allRules),
);
}
return map;
}, [ports, quickForward.allRules, quickForward.canForward, quickForward.hostId]);
const activeForwardCount = useMemo(() => {
const uniqueRuleIds = new Set<string>();
for (const matches of portMatchesById.values()) {
for (const rule of matches.activeRules) {
uniqueRuleIds.add(rule.id);
}
}
return uniqueRuleIds.size;
}, [portMatchesById]);
const openForwardDialog = useCallback((port: ListeningPortInfo) => {
const matches = matchListeningPortForwardRules(
port,
quickForward.hostId,
quickForward.allRules,
);
const suggestedLocalPort = matches.reusableInactiveRule?.localPort
?? suggestQuickForwardLocalPort(port.port, quickForward.allRules);
const suggestedBind = matches.reusableInactiveRule?.bindAddress
|| DEFAULT_QUICK_FORWARD_BIND_ADDRESS;
setForwardDialogInitialPort(suggestedLocalPort);
setForwardDialogInitialBind(suggestedBind);
setForwardError(null);
setForwardDialogPort(port);
}, [quickForward.allRules, quickForward.hostId]);
const handleSubmitForward = useCallback(async (values: { localPort: number; bindAddress: string }) => {
const port = forwardDialogPort;
if (!port) return;
const requestedSessionId = sessionId;
setForwardBusy(true);
setForwardError(null);
setActionError(null);
try {
const result = await quickForward.startQuickForward({
port,
localPort: values.localPort,
bindAddress: values.bindAddress,
});
if (sessionIdRef.current !== requestedSessionId) return;
if (!result.success) {
setForwardError(result.error || t('systemManager.ports.forwardFailed'));
return;
}
setForwardDialogPort(null);
const localEndpoint = formatHostPort(values.bindAddress, values.localPort);
const remoteEndpoint = formatHostPort(resolveForwardRemoteHost(port), port.port);
toast.success(
t('systemManager.ports.forwardStarted', {
local: localEndpoint,
remote: remoteEndpoint,
}),
);
} finally {
if (sessionIdRef.current === requestedSessionId) {
setForwardBusy(false);
}
}
}, [forwardDialogPort, quickForward, sessionId, t]);
const handleStopForward = useCallback(async (rule: PortForwardingRule) => {
const requestedSessionId = sessionId;
setActionError(null);
const result = await quickForward.stopQuickForward(rule);
if (sessionIdRef.current !== requestedSessionId) return;
if (!result.success) {
setActionError(result.error || t('systemManager.errors.actionFailed'));
return;
}
toast.info(
t('systemManager.ports.forwardStopped', {
local: formatHostPort(rule.bindAddress, rule.localPort),
}),
);
}, [quickForward, sessionId, t]);
const handleCopyLocalEndpoint = useCallback((rule: PortForwardingRule) => {
const endpoint = formatCopyableLocalEndpoint(rule.bindAddress, rule.localPort);
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
void navigator.clipboard.writeText(endpoint).then(() => {
toast.success(t('systemManager.ports.copiedEndpoint', { endpoint }));
}).catch(() => {});
}
}, [t]);
const executeTerminate = useCallback(async (pid: number) => {
const requestedSessionId = sessionId;
setKillBusy(true);
@@ -145,6 +272,10 @@ export const PortsManagerTab = memo(function PortsManagerTab({
}
}, [backend, refresh, sessionId, t]);
const hostLabel = portForwardingContext?.sessionHost?.label
|| portForwardingContext?.session?.hostLabel
|| portForwardingContext?.sessionHost?.hostname;
return (
<SystemPanelShell section="system-manager-ports">
<SystemPanelToolbar
@@ -174,7 +305,9 @@ export const PortsManagerTab = memo(function PortsManagerTab({
/>
<SystemPanelMetaBar>
{t('systemManager.ports.meta', { count: ports.length })}
{activeForwardCount > 0
? `${t('systemManager.ports.meta', { count: ports.length })} · ${t('systemManager.ports.forwardedMeta', { count: activeForwardCount })}`
: t('systemManager.ports.meta', { count: ports.length })}
</SystemPanelMetaBar>
{actionError ? <SystemPanelInlineError message={actionError} /> : null}
@@ -192,34 +325,125 @@ export const PortsManagerTab = memo(function PortsManagerTab({
<SystemPanelEmpty icon={Network} message={t('systemManager.ports.empty')} />
) : (
<SystemPanelList>
{ports.map((port) => (
<SystemPanelRow
key={port.id}
title={`${port.address}:${port.port}`}
subtitle={
port.processName
? `${port.processName}${port.pid != null ? ` · PID ${port.pid}` : ''}`
: (port.pid != null ? `PID ${port.pid}` : t('systemManager.ports.unknownProcess'))
}
trailing={(
<SystemPanelStatusBadge tone="muted">
{port.protocol.toUpperCase()}
</SystemPanelStatusBadge>
)}
actions={allowMutations && port.pid != null ? (
<SystemPanelRoundButton
title={t('systemManager.ports.terminate')}
destructive
onClick={() => setPendingKillPid(port.pid)}
>
<Skull size={12} />
</SystemPanelRoundButton>
) : null}
/>
))}
{ports.map((port) => {
const canForwardRow = quickForward.canForward && isForwardableListeningPort(port);
const matches = canForwardRow ? portMatchesById.get(port.id) : undefined;
const activeRule = matches?.primaryActiveRule;
const extraActiveCount = Math.max(0, (matches?.activeRules.length ?? 0) - 1);
const isStopPending = Boolean(activeRule && quickForward.pendingRuleIds.has(activeRule.id));
const trailingBadge = activeRule ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="inline-flex shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring hover:opacity-90 transition-opacity"
aria-label={t('systemManager.ports.copyEndpointAria', {
endpoint: formatCopyableLocalEndpoint(activeRule.bindAddress, activeRule.localPort),
})}
onClick={(event) => {
event.stopPropagation();
handleCopyLocalEndpoint(activeRule);
}}
>
<SystemPanelStatusBadge tone={activeRule.status === 'active' ? 'success' : 'warning'}>
{extraActiveCount > 0
? `→ :${activeRule.localPort} +${extraActiveCount}`
: `→ :${activeRule.localPort}`}
</SystemPanelStatusBadge>
</button>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-0.5 text-xs">
<div className="font-mono">
{formatHostPort(activeRule.bindAddress, activeRule.localPort)}
{' → '}
{formatHostPort(
activeRule.remoteHost || resolveForwardRemoteHost(port),
activeRule.remotePort ?? port.port,
)}
</div>
<div className="text-[10px] opacity-80">
{activeRule.status === 'connecting'
? (activeRule.error || t('systemManager.ports.forwarding'))
: t('systemManager.ports.clickToCopy')}
</div>
</div>
</TooltipContent>
</Tooltip>
) : (
<SystemPanelStatusBadge tone="muted">
{port.protocol.toUpperCase()}
</SystemPanelStatusBadge>
);
const hasActions = canForwardRow || (allowMutations && port.pid != null);
return (
<SystemPanelRow
key={port.id}
title={formatHostPort(port.address, port.port)}
subtitle={
port.processName
? `${port.processName}${port.pid != null ? ` · PID ${port.pid}` : ''}`
: (port.pid != null ? `PID ${port.pid}` : t('systemManager.ports.unknownProcess'))
}
trailing={trailingBadge}
actions={hasActions ? (
<>
{canForwardRow ? (
activeRule ? (
<SystemPanelRoundButton
title={t('systemManager.ports.stopForward')}
loading={isStopPending}
onClick={() => void handleStopForward(activeRule)}
>
<Square size={10} />
</SystemPanelRoundButton>
) : (
<SystemPanelRoundButton
title={t('systemManager.ports.forward')}
onClick={() => openForwardDialog(port)}
>
<ArrowRightLeft size={12} />
</SystemPanelRoundButton>
)
) : null}
{allowMutations && port.pid != null ? (
<SystemPanelRoundButton
title={t('systemManager.ports.terminate')}
destructive
onClick={() => setPendingKillPid(port.pid)}
>
<Skull size={12} />
</SystemPanelRoundButton>
) : null}
</>
) : null}
/>
);
})}
</SystemPanelList>
)}
<QuickPortForwardDialog
open={forwardDialogPort != null}
port={forwardDialogPort}
hostLabel={hostLabel}
initialLocalPort={forwardDialogInitialPort}
initialBindAddress={forwardDialogInitialBind}
rules={quickForward.allRules}
busy={forwardBusy}
error={forwardError}
onOpenChange={(open) => {
if (!open && !forwardBusy) {
setForwardDialogPort(null);
setForwardError(null);
}
}}
onSubmit={(values) => void handleSubmitForward(values)}
/>
<SystemPanelConfirmDialog
open={allowMutations && pendingKillPid != null}
title={t('systemManager.ports.terminate')}
@@ -0,0 +1,243 @@
import { ArrowRight, Loader2 } from 'lucide-react';
import React, { memo, useEffect, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import type { PortForwardingRule } from '../../domain/models';
import {
DEFAULT_QUICK_FORWARD_BIND_ADDRESS,
formatHostPort,
resolveForwardRemoteHost,
validateQuickForwardInput,
} from '../../domain/systemManager/portForwardQuick';
import type { ListeningPortInfo } from '../../domain/systemManager/types';
import { cn } from '../../lib/utils';
import { Button } from '../ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '../ui/dialog';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
const BIND_ADDRESS_PRESETS = ['127.0.0.1', '0.0.0.0'] as const;
export interface QuickPortForwardDialogProps {
open: boolean;
port: ListeningPortInfo | null;
hostLabel?: string;
initialLocalPort: number;
initialBindAddress: string;
rules: readonly PortForwardingRule[];
excludeRuleId?: string;
busy?: boolean;
error?: string | null;
onOpenChange: (open: boolean) => void;
onSubmit: (values: { localPort: number; bindAddress: string }) => void;
}
export const QuickPortForwardDialog = memo(function QuickPortForwardDialog({
open,
port,
hostLabel,
initialLocalPort,
initialBindAddress,
rules,
excludeRuleId,
busy = false,
error,
onOpenChange,
onSubmit,
}: QuickPortForwardDialogProps) {
const { t } = useI18n();
const [localPortText, setLocalPortText] = useState(String(initialLocalPort));
const [bindAddressText, setBindAddressText] = useState(initialBindAddress);
const [localError, setLocalError] = useState<string | null>(null);
const localPortInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setLocalPortText(String(initialLocalPort));
setBindAddressText(initialBindAddress || DEFAULT_QUICK_FORWARD_BIND_ADDRESS);
setLocalError(null);
}, [initialBindAddress, initialLocalPort, open, port?.id]);
useEffect(() => {
if (!open) return;
const timer = window.setTimeout(() => {
const input = localPortInputRef.current;
input?.focus();
input?.select();
}, 50);
return () => window.clearTimeout(timer);
}, [open, port?.id]);
if (!port) return null;
const remoteHost = resolveForwardRemoteHost(port);
const remoteEndpoint = formatHostPort(remoteHost, port.port);
const previewBind = bindAddressText.trim() || DEFAULT_QUICK_FORWARD_BIND_ADDRESS;
const parsedPreviewPort = Number(localPortText.trim());
const localPreviewEndpoint = Number.isInteger(parsedPreviewPort) && parsedPreviewPort >= 1 && parsedPreviewPort <= 65535
? formatHostPort(previewBind, parsedPreviewPort)
: `${previewBind}:${localPortText.trim() || '?'}`;
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
if (busy) return;
const validation = validateQuickForwardInput({
localPortText,
bindAddressText,
rules,
excludeRuleId,
});
if ('error' in validation) {
if (validation.error.code === 'invalidPort') {
setLocalError(t('systemManager.ports.forwardInvalidPort'));
} else if (validation.error.code === 'invalidBindAddress') {
setLocalError(t('systemManager.ports.forwardInvalidBindAddress'));
} else {
setLocalError(
t('systemManager.ports.forwardPortInUse', {
port: String(localPortText.trim()),
label: validation.error.conflictRule.label,
}),
);
}
return;
}
setLocalError(null);
onSubmit({
localPort: validation.localPort,
bindAddress: validation.bindAddress,
});
};
const displayError = localError || error;
const trimmedBind = bindAddressText.trim();
return (
<Dialog open={open} onOpenChange={(nextOpen) => { if (!busy || nextOpen) onOpenChange(nextOpen); }}>
<DialogContent className="sm:max-w-[380px]">
<DialogHeader>
<DialogTitle>{t('systemManager.ports.forwardTitle')}</DialogTitle>
<DialogDescription>
{hostLabel
? t('systemManager.ports.forwardDescWithHost', { host: hostLabel })
: t('systemManager.ports.forwardDesc')}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="rounded-md border border-border/60 bg-muted/30 px-3 py-2.5 space-y-1">
<div className="flex items-center gap-2 font-mono text-xs text-foreground">
<span className="truncate">{localPreviewEndpoint}</span>
<ArrowRight size={12} className="shrink-0 text-muted-foreground" />
<span className="truncate text-primary">{remoteEndpoint}</span>
</div>
<div className="text-[11px] text-muted-foreground truncate">
{port.processName
? `${port.processName}${port.pid != null ? ` · PID ${port.pid}` : ''} · ${port.protocol.toUpperCase()}`
: `${port.protocol.toUpperCase()}${port.pid != null ? ` · PID ${port.pid}` : ''}`}
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="quick-forward-local-port" className="text-xs">
{t('systemManager.ports.forwardLocalPort')}
</Label>
<Input
id="quick-forward-local-port"
ref={localPortInputRef}
type="number"
min={1}
max={65535}
inputMode="numeric"
value={localPortText}
onChange={(event) => {
setLocalPortText(event.target.value);
if (localError) setLocalError(null);
}}
placeholder={String(initialLocalPort)}
className="h-9 font-mono text-sm"
disabled={busy}
/>
</div>
<div className="space-y-1.5">
<div className="flex items-center justify-between gap-2">
<Label htmlFor="quick-forward-bind-address" className="text-xs">
{t('systemManager.ports.forwardBindAddress')}
</Label>
<div className="flex items-center gap-1">
{BIND_ADDRESS_PRESETS.map((preset) => (
<button
key={preset}
type="button"
disabled={busy}
onClick={() => {
setBindAddressText(preset);
if (localError) setLocalError(null);
}}
className={cn(
'px-1.5 py-0.5 rounded font-mono text-[10px] transition-colors disabled:opacity-40',
trimmedBind === preset
? 'bg-muted text-foreground font-medium'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/60',
)}
>
{preset}
</button>
))}
</div>
</div>
<Input
id="quick-forward-bind-address"
value={bindAddressText}
onChange={(event) => {
setBindAddressText(event.target.value);
if (localError) setLocalError(null);
}}
placeholder={DEFAULT_QUICK_FORWARD_BIND_ADDRESS}
className="h-9 font-mono text-sm"
spellCheck={false}
disabled={busy}
/>
</div>
{displayError && (
<p className="text-xs text-destructive break-words" role="alert">
{displayError}
</p>
)}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={busy}
>
{t('common.cancel')}
</Button>
<Button
type="submit"
disabled={busy || !localPortText.trim()}
>
{busy ? (
<>
<Loader2 size={14} className="mr-1.5 animate-spin" />
{t('systemManager.ports.forwarding')}
</>
) : (
t('systemManager.ports.forwardAction')
)}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
});
@@ -3,6 +3,7 @@ import type { LucideIcon } from 'lucide-react';
import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { SYSTEM_MANAGER_TAB_LAYOUT_DEFAULTS } from '../../application/state/systemManagerTabLayout';
import type { QuickPortForwardingContext } from '../../application/state/useQuickPortForwarding';
import { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend';
import { useTerminalBackend } from '../../application/state/useTerminalBackend';
import { remoteSoftwareRequiresSingleChannel } from '@/domain/singleChannelSshBanner.shared.cjs';
@@ -69,6 +70,8 @@ interface SystemManagerSidePanelProps {
terminalSettings: TerminalSettings;
snippets: Snippet[];
onRequestTerminalFocus?: () => void;
/** Optional context enabling one-click SSH port forwarding from the Ports tab. */
portForwardingContext?: QuickPortForwardingContext;
}
export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
@@ -79,6 +82,7 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
terminalSettings,
snippets,
onRequestTerminalFocus,
portForwardingContext,
}: SystemManagerSidePanelProps) {
const { t } = useI18n();
const backend = useSystemManagerBackend();
@@ -568,6 +572,7 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
backend={backend}
refreshIntervalSec={terminalSettings.systemManagerProcessRefreshInterval}
allowMutations={allowMutations}
portForwardingContext={portForwardingContext}
/>
</div>
) : null}
@@ -0,0 +1,53 @@
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, directoryLabel } from '../../domain/directoryPicker';
import { directoryDisplayName } 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.cwd ? directoryLabel(model.cwd, model.home, model.pathFlavor) : t('terminal.directory.unknown') })}
title={model.cwd ? directoryDisplayName(model.cwd) : t('terminal.directory.unknown')}
aria-label={t('terminal.directory.open', { path: model.display?.ariaPath ?? t('terminal.directory.unknown') })}
title={model.display?.title ?? 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.cwd ? directoryDisplayName(directoryLabel(model.cwd, model.home, model.pathFlavor)) : t('terminal.directory.unknown')}</span>
<span className="truncate">{model.display?.label ?? t('terminal.directory.unknown')}</span>
<ChevronDown size={10} className="shrink-0 opacity-60" />
</button>
</PopoverTrigger>
@@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
import type { Host } from "../../types.ts";
import { TerminalConnectionDialog } from "./TerminalConnectionDialog.tsx";
import { TerminalConnectionDialog, resolveChainProgressAddressLine } from "./TerminalConnectionDialog.tsx";
const host: Host = {
id: "host-1",
@@ -193,6 +193,68 @@ test("keeps connection log padding inside the scrollable content", () => {
assert.match(markup, /class="[^"]*p-2\.5[^"]*pb-4[^"]*pr-4/);
});
test("chain progress shows the current jump hop's address, not the target's", () => {
const markup = renderDialog({
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
chainProgress: {
currentHop: 2,
totalHops: 3,
currentHostLabel: "Bastion B",
currentHostAddress: "b.example.com:2201",
},
});
assert.match(markup, /Chain 2 of 3: <\/span><span>Bastion B<\/span>/);
assert.match(markup, /SSH b\.example\.com:2201/);
assert.equal(markup.includes("10.0.0.5"), false);
});
test("chain progress shows the target's label and address on the final hop", () => {
const markup = renderDialog({
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
chainProgress: {
currentHop: 3,
totalHops: 3,
currentHostLabel: "Prod DB",
currentHostAddress: "10.0.0.5:22",
},
});
assert.match(markup, /Chain 3 of 3: <\/span><span>Prod DB<\/span>/);
assert.match(markup, /SSH 10\.0\.0\.5:22/);
});
test("chain progress address line keeps the target's protocol on the final hop", () => {
const t = (key: string) => ({
"terminal.connection.protocol.ssh": "SSH",
"terminal.connection.protocol.et": "ET",
}[key] ?? key);
const etInfo = { i18nKey: "terminal.connection.protocol.et", showPort: true, port: 2022 };
const target = { hostname: "10.0.0.5" };
// Jump hop: always SSH with the hop's own address.
assert.equal(
resolveChainProgressAddressLine(
{ currentHop: 1, totalHops: 2, currentHostAddress: "bastion.example.com:22" },
target, etInfo, t,
),
"SSH bastion.example.com:22",
);
// Final hop: the target's protocol and port (ET 2022, not the SSH port).
assert.equal(
resolveChainProgressAddressLine(
{ currentHop: 2, totalHops: 2, currentHostAddress: "10.0.0.5:22" },
target, etInfo, t,
),
"ET 10.0.0.5:2022",
);
// Older progress events without an address fall back to the target.
assert.equal(
resolveChainProgressAddressLine({ currentHop: 1, totalHops: 2 }, target, etInfo, t),
"ET 10.0.0.5:2022",
);
});
test("shows the ET server port (not the SSH port) for an ET host with a custom etPort", () => {
const markup = renderDialog({
host: { ...host, etEnabled: true, port: 22, etPort: 9022 },
@@ -28,8 +28,29 @@ export interface ChainProgress {
currentHop: number;
totalHops: number;
currentHostLabel: string;
/** host:port of the hop being connected; falls back to the target's address. */
currentHostAddress?: string;
}
/**
* Address line under the "Chain X of Y" heading. Jump hops are always SSH, so
* they show the hop's own address; the final hop keeps the target's
* protocol-aware line (Mosh/ET/Telnet ports differ from the SSH port).
*/
export const resolveChainProgressAddressLine = (
chainProgress: Pick<ChainProgress, 'currentHop' | 'totalHops' | 'currentHostAddress'>,
host: Pick<Host, 'hostname'>,
protocolInfo: { i18nKey: string; showPort: boolean; port: number },
t: (key: string) => string,
): string => {
const isJumpHop = chainProgress.currentHop < chainProgress.totalHops;
if (isJumpHop && chainProgress.currentHostAddress) {
return `${t('terminal.connection.protocol.ssh')} ${chainProgress.currentHostAddress}`;
}
const address = protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname;
return `${t(protocolInfo.i18nKey)} ${address}`;
};
export interface TerminalConnectionDialogProps {
host: Host;
status: 'connecting' | 'connected' | 'disconnected';
@@ -334,7 +355,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
className="text-[10px] font-mono truncate"
style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }}
>
{protocolLabel} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
{resolveChainProgressAddressLine(chainProgress, host, protocolInfo, t)}
</div>
</>
) : (
@@ -41,6 +41,7 @@ import { resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshA
import { connectionTotpFields } from "../../../domain/totpConfig";
import { requiresFidoSshAgentAuth } from "../../../domain/fidoSsh";
import {
formatHostPort,
hostRestrictsExtraSshChannels,
resolveHostKeepalive,
resolveTelnetPassword,
@@ -642,12 +643,15 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
totalHops,
currentHostLabel:
jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname,
currentHostAddress: jumpHosts[0]?.hostname
? formatHostPort(jumpHosts[0].hostname, jumpHosts[0].port || 22)
: undefined,
connectionPhase: 'connecting',
});
}
{
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error) => {
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error, address) => {
// P1: Only process events for this session
if (sid !== ctx.sessionId) return;
// Disconnect/reconnect can leave two SSH starts sharing this UI
@@ -660,6 +664,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
currentHop: hop,
totalHops: total,
currentHostLabel: label,
currentHostAddress: address,
connectionPhase: status,
});
}
@@ -95,7 +95,7 @@ export type TerminalBackendApi = {
error?: string;
}>;
onChainProgress: (
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void,
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void,
) => (() => void) | undefined;
onConnectionReuseFallback?: (
cb: (sessionId: string, sourceSessionId?: string) => void,
@@ -126,6 +126,8 @@ type ChainProgressState = {
currentHop: number;
totalHops: number;
currentHostLabel: string;
/** host:port of the hop being connected; absent from older progress events. */
currentHostAddress?: string;
connectionPhase: string;
} | null;
@@ -21,5 +21,6 @@ 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,4 +1,5 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { JSDOM } from 'jsdom';
@@ -19,6 +20,35 @@ 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, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
import { isRemoteDesktopProtocol } from '../../domain/remoteDesktop';
const MemoizedSidePanelMountedContent = memo(
@@ -169,7 +169,7 @@ function SidePanelPaneHost({
<span className="text-[11px] font-medium truncate flex-1">{label}</span>
<button
type="button"
className="h-5 w-5 grid place-items-center rounded-sm opacity-70 hover:opacity-100 hover:bg-white/10"
className="h-5 w-5 shrink-0 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) => {
@@ -1583,12 +1583,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
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"
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
style={{
borderColor: sidePanelTheme.accent,
borderWidth: resolveMagnifiedChromeBorderWidth(
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
),
outline: `1px solid ${sidePanelTheme.accent}`,
outlineOffset: -1,
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
}}
@@ -66,7 +66,6 @@ import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePane
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
PANE_MAGNIFICATION_DURATION_MS,
resolveMagnifiedChromeBorderWidth,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
type PaneMagnificationController,
@@ -803,6 +802,7 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE
AIChatPanelsHost.displayName = 'AIChatPanelsHost';
export interface TerminalLayerProps {
isVaultInitialized?: boolean;
hosts: Host[];
portForwardingRules?: import('../../domain/models').PortForwardingRule[];
customGroups: string[];
@@ -948,6 +948,7 @@ interface TerminalPaneProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -1096,6 +1097,7 @@ 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 &&
@@ -1390,6 +1392,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -1821,14 +1824,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
"absolute bg-background",
inActiveWorkspace && "workspace-pane",
isVisible && "z-10",
isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
)}
style={{
...style,
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
borderWidth: isMagnified && magnifiedSurfaceBounds
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
outline: magnifiedSurfaceBounds
? `1px solid ${sessionAppearanceTheme.colors.cursor}`
: undefined,
outlineOffset: magnifiedSurfaceBounds ? -1 : undefined,
}}
tabIndex={-1}
onClick={handlePaneClick}
@@ -1921,6 +1924,7 @@ 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}
@@ -2019,6 +2023,7 @@ interface TerminalPanesHostProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -2120,6 +2125,7 @@ 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,14 +9,41 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("magnified terminal panes use the resolved terminal accent for border chrome", () => {
test("terminal pane chrome follows retained surface bounds through restore with a continuous 1px inset outline", () => {
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, /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\)/);
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);
}
}
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
@@ -63,6 +63,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -233,6 +234,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef={splitVerticalHandlersRef}
resolveSessionAppearance={resolveSessionAppearance}
hostMap={hostMap}
isVaultInitialized={isVaultInitialized}
keys={keys}
identities={identities}
snippets={snippets}
@@ -47,6 +47,7 @@ const navigatorPlatform = typeof navigator !== 'undefined' ? navigator.platform
const EMPTY_VAULT_NOTES: never[] = [];
const EMPTY_VAULT_HOSTS: never[] = [];
const EMPTY_VAULT_SNIPPETS: never[] = [];
const EMPTY_ARRAY: never[] = [];
const subscribeShellHistoryNoop = () => () => {};
function useSidePanelLiveSnapshotForTab(tabId: string, subscribe: boolean) {
@@ -337,10 +338,42 @@ function SidePanelSystemSlotInner({
);
const {
effectiveHosts,
hosts,
identities,
keys,
knownHosts,
refocusActiveTerminalSession,
sftpAuthHostBySessionId,
snippets,
terminalSettings,
} = ctx;
const authHosts = sftpAuthHostBySessionId as Map<string, Host> | undefined;
const authHost = systemSession ? (authHosts?.get(systemSession.id) ?? null) : null;
const portForwardingContext = React.useMemo(
() => ({
session: systemSession,
sessionHost: systemHost,
authHost,
vaultHosts: (hosts ?? EMPTY_VAULT_HOSTS) as Host[],
effectiveHosts: (effectiveHosts ?? EMPTY_VAULT_HOSTS) as Host[],
keys: (keys ?? EMPTY_ARRAY) as import('../../domain/models').SSHKey[],
identities: (identities ?? EMPTY_ARRAY) as import('../../domain/models').Identity[],
knownHosts: (knownHosts ?? EMPTY_ARRAY) as import('../../domain/models').KnownHost[],
terminalSettings,
}),
[
authHost,
effectiveHosts,
hosts,
identities,
keys,
knownHosts,
systemHost,
systemSession,
terminalSettings,
],
);
return (
<div className={sidePanelHiddenPanelClassName(!isVisible)}>
@@ -353,6 +386,7 @@ function SidePanelSystemSlotInner({
terminalSettings={terminalSettings}
snippets={snippets}
onRequestTerminalFocus={refocusActiveTerminalSession}
portForwardingContext={portForwardingContext}
/>
</div>
);
@@ -383,6 +383,7 @@ const WORKSPACE_CTX_KEYS = [
'splitVerticalHandlersRef',
'resolveSessionAppearance',
'hostMap',
'isVaultInitialized',
'keys',
'identities',
'snippets',
+1
View File
@@ -4,6 +4,7 @@ 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 &&
+5 -16
View File
@@ -26,8 +26,6 @@ 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';
@@ -261,24 +259,15 @@ export const formatSessionTopTabLabel = (
type WorkspaceTopTabLabelWorkspace = Pick<
Workspace,
'title' | 'focusedSessionId' | 'autoTitle'
> & {
generatedTitle?: boolean;
};
'title' | 'focusedSessionId' | 'autoTitle' | 'generatedTitle'
>;
export const resolveWorkspaceTopTabLabel = (
workspace: WorkspaceTopTabLabelWorkspace,
sessions: readonly TerminalSession[],
dynamicTabTitleMode?: DynamicTabTitleMode,
): string => {
const presentedSessions = sessions.map(applySessionPresentation);
const resolvedWorkspace = workspace.generatedTitle
? {
...workspace,
title: buildMergedWorkspaceTitleFromSessions(presentedSessions) ?? DEFAULT_WORKSPACE_TITLE,
autoTitle: false,
}
: workspace;
return resolveWorkspaceTabLabel(resolvedWorkspace, presentedSessions);
return resolveWorkspaceTabLabel(workspace, sessions.map(applySessionPresentation), dynamicTabTitleMode);
};
export const createTopTabCopyDoubleClickHandler = (
@@ -1106,7 +1095,7 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
[onCopyWorkspace, workspace.id, tabDoubleClickBehavior],
);
const detachSessions = workspaceSessions ?? [];
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions);
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions, dynamicTabTitleMode);
return (
<ContextMenu>
+121
View File
@@ -0,0 +1,121 @@
# 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.
+4 -2
View File
@@ -3,7 +3,8 @@
`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.
`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)).
## Input
@@ -106,7 +107,8 @@ 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.
- `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.
- 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 与 Windows PowerShell 适配 | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD 和 Git Bash | [功能规格](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,6 +10,7 @@
| 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 |
## 路径与能力模型
@@ -60,6 +61,12 @@ 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,6 +9,7 @@
| 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 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
@@ -16,6 +17,8 @@ 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,再完善能力状态和路径确认策略。
@@ -35,12 +38,12 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。
### D:WSL、Git Bash 与 Cygwin
### D2/D3:WSL 与 Cygwin
为每类环境定义文件系统 authority、cwd 来源、结构化目录 helper 与执行策略:
- WSL:绑定所选 distro,验证 Linux home、挂载盘及 wslpath/UNC 映射。
- MSYS/Cygwin:验证 mount、驱动器、链接和编码转换。
- Cygwin:验证 mount、驱动器、链接和编码转换。Git Bash 后续补充共享路径和虚拟挂载语义。
- helper:保留原始名称、类型和目录链接,提供输出边界、取消及权限状态。
交付目标是让目录读取与命令执行处于同一命名空间,并按 distro/mount 身份组织缓存。
+23
View File
@@ -0,0 +1,23 @@
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,10 +6,130 @@ 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"}}');
+36 -1
View File
@@ -1,4 +1,39 @@
import { CustomKeyBindings } from './models';
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;
};
const SYNC_VERSION_FIELD = '__netcattySyncVersion';
const SYNC_ORIGIN_FIELD = '__netcattySyncOrigin';
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff. Show more