diff --git a/AGENTS.md b/AGENTS.md index a21b64c2a..724ab4687 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. diff --git a/application/app/AppHandlers.ts b/application/app/AppHandlers.ts index 9a80aac1a..d98a027fc 100644 --- a/application/app/AppHandlers.ts +++ b/application/app/AppHandlers.ts @@ -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('[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('[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; diff --git a/application/app/AppView.tsx b/application/app/AppView.tsx index e2c541203..83efe2fc7 100644 --- a/application/app/AppView.tsx +++ b/application/app/AppView.tsx @@ -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) { /> (); +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('
'); + const prevWindow = globalThis.window; + const prevDocument = globalThis.document; + const prevActEnv = (globalThis as Record).IS_REACT_ACT_ENVIRONMENT; + + (globalThis as Record).window = dom.window; + (globalThis as Record).document = dom.window.document; + (globalThis as Record).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).window = prevWindow; + (globalThis as Record).document = prevDocument; + (globalThis as Record).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, / { 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', }); }); diff --git a/application/state/pluginContributionEnvironment.ts b/application/state/pluginContributionEnvironment.ts index bc5edf409..690b8093f 100644 --- a/application/state/pluginContributionEnvironment.ts +++ b/application/state/pluginContributionEnvironment.ts @@ -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( diff --git a/application/state/pluginViewSession.ts b/application/state/pluginViewSession.ts index 991c74cd1..c4beb0d70 100644 --- a/application/state/pluginViewSession.ts +++ b/application/state/pluginViewSession.ts @@ -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>(); 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, diff --git a/application/state/promptHostnameSessionSignalController.test.ts b/application/state/promptHostnameSessionSignalController.test.ts index f76a25e7a..6a236bd58 100644 --- a/application/state/promptHostnameSessionSignalController.test.ts +++ b/application/state/promptHostnameSessionSignalController.test.ts @@ -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', () => { diff --git a/application/state/promptHostnameSessionSignalController.ts b/application/state/promptHostnameSessionSignalController.ts index 105e6868e..1b76bc1ac 100644 --- a/application/state/promptHostnameSessionSignalController.ts +++ b/application/state/promptHostnameSessionSignalController.ts @@ -5,7 +5,7 @@ import { } from '../../domain/terminalPromptSecurity'; type PromptHostnameSessionSignalOptions = { - getSession: (sessionId: string) => Pick | undefined; + getSession: (sessionId: string) => Pick | 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(); - const baselines = new Map(); const published = new Map(); 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): 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); diff --git a/application/state/useComposeDirectoryPicker.test.ts b/application/state/useComposeDirectoryPicker.test.ts index 4a06e93c3..aa2dc97ea 100644 --- a/application/state/useComposeDirectoryPicker.test.ts +++ b/application/state/useComposeDirectoryPicker.test.ts @@ -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; + 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['display']> = []; + let model!: ReturnType; + 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(); }); diff --git a/application/state/useComposeDirectoryPicker.ts b/application/state/useComposeDirectoryPicker.ts index ae445d8f8..c49733075 100644 --- a/application/state/useComposeDirectoryPicker.ts +++ b/application/state/useComposeDirectoryPicker.ts @@ -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([]); - const [home, setHome] = useState(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(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, diff --git a/application/state/useHostConnectionTest.ts b/application/state/useHostConnectionTest.ts index 07a47a660..aa9fad7cd 100644 --- a/application/state/useHostConnectionTest.ts +++ b/application/state/useHostConnectionTest.ts @@ -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, }); } diff --git a/application/state/useHostDrawnPluginView.ts b/application/state/useHostDrawnPluginView.ts index 6f7b0f7ca..a3d37c782 100644 --- a/application/state/useHostDrawnPluginView.ts +++ b/application/state/useHostDrawnPluginView.ts @@ -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; + }>({ key: '', snapshot: initial() }); const [hidden, setHidden] = useState(false); const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable; const sessionRef = useRef<{ key: string; image(path: string): Promise; 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]); diff --git a/application/state/useModelCatalogWarningDismissal.test.tsx b/application/state/useModelCatalogWarningDismissal.test.tsx new file mode 100644 index 000000000..a2ff59fc0 --- /dev/null +++ b/application/state/useModelCatalogWarningDismissal.test.tsx @@ -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('
'); + const prevWindow = globalThis.window; + const prevDocument = globalThis.document; + const prevActEnv = (globalThis as Record).IS_REACT_ACT_ENVIRONMENT; + + (globalThis as Record).window = dom.window; + (globalThis as Record).document = dom.window.document; + (globalThis as Record).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).window = prevWindow; + (globalThis as Record).document = prevDocument; + (globalThis as Record).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, + /; + dismissWarning: (cacheKey: string | undefined) => void; + rearmWarning: (cacheKey: string | undefined) => void; +} + +type Listener = () => void; + +let dismissedKeysSnapshot: ReadonlySet = new Set(); +const listeners = new Set(); + +function emitChange(): void { + for (const listener of listeners) { + listener(); + } +} + +function subscribe(listener: Listener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function getSnapshot(): ReadonlySet { + 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, + }; +} diff --git a/application/state/usePluginHostActions.ts b/application/state/usePluginHostActions.ts index 52aad9eb2..415344a7b 100644 --- a/application/state/usePluginHostActions.ts +++ b/application/state/usePluginHostActions.ts @@ -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(null); const [selectedIds, setSelectedIds] = useState([]); + const [remember, setRemember] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(false); const current = useRef(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 }; } diff --git a/application/state/useQuickPortForwarding.test.tsx b/application/state/useQuickPortForwarding.test.tsx new file mode 100644 index 000000000..01f12cffe --- /dev/null +++ b/application/state/useQuickPortForwarding.test.tsx @@ -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(); + 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(); + 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 { + 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 void>(); + let failNextStart: string | null = null; + const startedPayloads: Array> = []; + 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) => { + 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; + const ctx = makeContext(); + function Probe() { + api = useQuickPortForwarding(ctx); + return null; + } + + let root: ReactTestRenderer | undefined; + try { + await act(async () => { + root = create(); + }); + + 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>; + 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>; + 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>; + 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 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) => { + 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; + 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(); + }); + + 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(); + } +}); diff --git a/application/state/useQuickPortForwarding.ts b/application/state/useQuickPortForwarding.ts new file mode 100644 index 000000000..3c0ad0cbd --- /dev/null +++ b/application/state/useQuickPortForwarding.ts @@ -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(); +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>(() => 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 => { + 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, + }; +} diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index 303ffa859..588437014 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -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) => { diff --git a/application/state/useTerminalBackend.ts b/application/state/useTerminalBackend.ts index 37304a186..6ecee0e00 100644 --- a/application/state/useTerminalBackend.ts +++ b/application/state/useTerminalBackend.ts @@ -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); }, []); diff --git a/application/state/useTerminalDirectorySession.ts b/application/state/useTerminalDirectorySession.ts index ec6c92bf5..5b34bb420 100644 --- a/application/state/useTerminalDirectorySession.ts +++ b/application/state/useTerminalDirectorySession.ts @@ -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]); } diff --git a/components/AIChatPanelContent.tsx b/components/AIChatPanelContent.tsx index 0d6fa69ca..245b8bd27 100644 --- a/components/AIChatPanelContent.tsx +++ b/components/AIChatPanelContent.tsx @@ -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 = ({ handleSteer, handleStop, handleModelCatalogRetry, + handleModelCatalogDismiss, handleModelPickerOpen, canSteer, isSteering, @@ -186,6 +191,7 @@ export const AIChatPanelContent: React.FC = ({ providerDisplayName, modelDisplayName, modelCatalogWarning, + modelCatalogWarningDismissed = false, modelCatalogLoading = false, modelCatalogSource, modelCatalogFetchedAt, @@ -425,7 +431,7 @@ export const AIChatPanelContent: React.FC = ({
{steerWarning}
- ) : modelCatalogWarning ? ( + ) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
{modelCatalogWarning} {handleModelCatalogRetry && ( @@ -436,6 +442,17 @@ export const AIChatPanelContent: React.FC = ({ {t('ai.chat.modelCatalogRetry')} )} + {handleModelCatalogDismiss && ( + + )}
) : modelCatalogLoading ? (
diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 0f85fc2f0..51d6f560f 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -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 = ({ const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false); const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState>({}); const [runtimeModelWarnings, setRuntimeModelWarnings] = useState>({}); + 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 = ({ 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 = ({ } return null; }); - }, [t, buildExternalAgentRuntimeModelTarget]); + }, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]); useEffect(() => { if (!isVisible) return; @@ -1390,6 +1402,9 @@ const AIChatSidePanelActive: React.FC = ({ 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 = ({ buildExternalAgentRuntimeModelTarget, loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog, + rearmModelCatalogWarning, t, ]); @@ -1625,6 +1641,14 @@ const AIChatSidePanelActive: React.FC = ({ 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 = ({ && 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]) diff --git a/components/AIChatSidePanelHelpers.test.tsx b/components/AIChatSidePanelHelpers.test.tsx index 3dda4ed15..e55b73799 100644 --- a/components/AIChatSidePanelHelpers.test.tsx +++ b/components/AIChatSidePanelHelpers.test.tsx @@ -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( diff --git a/components/AIChatSidePanelHelpers.ts b/components/AIChatSidePanelHelpers.ts index af96c1b9e..7a78a833f 100644 --- a/components/AIChatSidePanelHelpers.ts +++ b/components/AIChatSidePanelHelpers.ts @@ -293,6 +293,25 @@ export const sdkRuntimeModelCache = createSdkRuntimeModelCache(); export type RuntimeModelWarnings = Record; +/** + * 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 | 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 diff --git a/components/HostDetailsAdvancedSections.tsx b/components/HostDetailsAdvancedSections.tsx index b80b34212..efa2d5774 100644 --- a/components/HostDetailsAdvancedSections.tsx +++ b/components/HostDetailsAdvancedSections.tsx @@ -25,10 +25,13 @@ import { // eslint-disable-next-line @typescript-eslint/no-explicit-any type HostDetailsAdvancedSectionsProps = Record; -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 ( - onToggle()} /> +
+ {inheritance} + onToggle()} /> +
); }; @@ -54,6 +57,7 @@ export const HostDetailsAdvancedSections: React.FC { 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 ? ( + + {t("vault.groups.details.inherited")} + + ) : ( + { + 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 { - const enabling = !form.moshEnabled; + const enabling = !effectiveMoshEnabled; if (enabling) { setForm(prev => ({ ...prev, @@ -250,9 +278,10 @@ export const HostDetailsAdvancedSections: React.FC { - const enabling = !form.etEnabled; + const enabling = !effectiveEtEnabled; if (enabling) { setForm(prev => ({ ...prev, @@ -265,7 +294,7 @@ export const HostDetailsAdvancedSections: React.FC - {form.etEnabled && ( + {effectiveEtEnabled && ( <> } title={t("hostDetails.section.deviceType")} > - {isSshView && !form.moshEnabled && !form.etEnabled && (<> + {isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (<> update("deviceType", effectiveDeviceType === 'network' ? 'general' : 'network')} /> {effectiveDeviceType === 'network' && ( @@ -519,7 +549,7 @@ export const HostDetailsAdvancedSections: React.FC update("showLineTimestamps", !form.showLineTimestamps)} /> - {isSshView && !form.moshEnabled && !form.etEnabled && ( + {isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && ( <> )} - +
+ {form.backspaceBehavior !== undefined && groupSettingControl("backspaceBehavior")} + +
+ {form.backspaceBehavior === undefined && groupSettingControl("backspaceBehavior")} {/* Per-host keepalive override */} @@ -675,9 +709,14 @@ export const HostDetailsAdvancedSections: React.FC
) : ( - - {t("hostDetails.jumpHosts.direct")} - +
+ + {t("hostDetails.jumpHosts.direct")} + + {canRestoreHostChain && ( + + )} +
) } > diff --git a/components/HostDetailsPanel.groupPath.test.tsx b/components/HostDetailsPanel.groupPath.test.tsx new file mode 100644 index 000000000..fba77e539 --- /dev/null +++ b/components/HostDetailsPanel.groupPath.test.tsx @@ -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; + created: string[]; + }) => Promise, + 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( + {kind === 'ssh' ? created.push(path)} /> + : kind === 'local' ? + : } + ); + }); + 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\}/); +}); diff --git a/components/HostDetailsPanel.helpers.ts b/components/HostDetailsPanel.helpers.ts index a09781a2f..95e8762a2 100644 --- a/components/HostDetailsPanel.helpers.ts +++ b/components/HostDetailsPanel.helpers.ts @@ -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; diff --git a/components/HostDetailsPanel.inherit.test.tsx b/components/HostDetailsPanel.inherit.test.tsx new file mode 100644 index 000000000..810fd7e9f --- /dev/null +++ b/components/HostDetailsPanel.inherit.test.tsx @@ -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, 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, + run: (editor: { root: ReactTestInstance; save: () => Promise }) => Promise, + 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( + { saved = value; }} /> + ); + }); + 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")); + }); +}); diff --git a/components/HostDetailsPanel.proxyProfile.test.tsx b/components/HostDetailsPanel.proxyProfile.test.tsx index 13c443c29..a9ec3a0c2 100644 --- a/components/HostDetailsPanel.proxyProfile.test.tsx +++ b/components/HostDetailsPanel.proxyProfile.test.tsx @@ -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", () => { diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index 03cff9e71..d9ae212d4 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -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 = ({ }, [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(null); const initialHostId = initialData?.id; @@ -377,6 +380,8 @@ const HostDetailsPanel: React.FC = ({ }, [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 = ({ }, [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 = ({ 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 = ({ } 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 = ({ } }; - 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 = ({ [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 = ({ 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 = ({ setShowAlgorithmOverrides={setShowAlgorithmOverrides} chainedHosts={chainedHosts} hostChainInherited={hostChainInherited} + canRestoreHostChain={canRestoreHostChain} setActiveSubPanel={setActiveSubPanel} clearHostChain={clearHostChain} proxySummaryType={proxySummaryType} diff --git a/components/LocalShellHostDetailsPanel.tsx b/components/LocalShellHostDetailsPanel.tsx index 17292cb1a..7a2a2766b 100644 --- a/components/LocalShellHostDetailsPanel.tsx +++ b/components/LocalShellHostDetailsPanel.tsx @@ -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 discoveredShells.find((candidate) => candidate.id === shell), @@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC(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 = ({ currentHop: number; totalHops: number; currentHostLabel: string; + currentHostAddress?: string; connectionPhase: string; } | null>(null); const [isConnectionAwaitingUserInput, setIsConnectionAwaitingUserInput] = useState(false); diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 113c4b6e4..9b37016e3 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -203,6 +203,7 @@ function buildScriptSessionMeta( } const TerminalLayerInner: React.FC = ({ + isVaultInitialized, hosts, portForwardingRules = [], customGroups, @@ -2876,6 +2877,7 @@ const TerminalLayerInner: React.FC = ({ onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isComposeBarOpen, + isVaultInitialized, keyBindings, keys, knownHosts, diff --git a/components/TopTabs.test.ts b/components/TopTabs.test.ts index 7a9e68205..7e9755cfb 100644 --- a/components/TopTabs.test.ts +++ b/components/TopTabs.test.ts @@ -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: "" }), diff --git a/components/plugins/LazyPluginHostDrawnPage.tsx b/components/plugins/LazyPluginHostDrawnPage.tsx index d9dbf8c7e..28ff5d970 100644 --- a/components/plugins/LazyPluginHostDrawnPage.tsx +++ b/components/plugins/LazyPluginHostDrawnPage.tsx @@ -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 | 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 diff --git a/components/plugins/PluginContributionIcon.tsx b/components/plugins/PluginContributionIcon.tsx index a855d5e6a..e072f54ea 100644 --- a/components/plugins/PluginContributionIcon.tsx +++ b/components/plugins/PluginContributionIcon.tsx @@ -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> = 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, diff --git a/components/plugins/PluginHostActionHost.tsx b/components/plugins/PluginHostActionHost.tsx index db8bc6086..d1ae7b3af 100644 --- a/components/plugins/PluginHostActionHost.tsx +++ b/components/plugins/PluginHostActionHost.tsx @@ -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 { if (!open) void state.respond('cancel'); }}> - {t(selection ? 'plugins.hostActions.select' : connection ? 'plugins.hostActions.connect' : entry.host ? 'plugins.hostActions.edit' : 'plugins.hostActions.create')} + {dialogTitle} {entry.prompt.pluginId} · {entry.prompt.pluginVersion} {selection ? <> @@ -29,17 +43,89 @@ export function PluginHostActionHost() {

{request.title}

{state.selectedIds.length > 50 &&

{t('plugins.hostActions.selectionLimit')}

} 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 ?
+
+

Destination Endpoint

+

{request.endpoint}

+

+ {request.transport.toUpperCase()} · {request.host}:{request.port} + {request.isLocal ? ' · Local / Private Network' : ''} +

+
+

+ This plugin is requesting a direct {request.transport.toUpperCase()} connection to this endpoint. Netcatty's internal control ports remain blocked. +

+ +
: tlsConfirm ?
+

+ The server certificate could not be verified ({request.reason}). +

+
+
+ Endpoint: + {request.endpoint} +
+ {request.subject &&
+ Subject: + {request.subject} +
} + {request.issuer &&
+ Issuer: + {request.issuer} +
} + {request.validTo &&
+ Valid Until: + {request.validTo} +
} +
+ SHA-256 Fingerprint: + + {request.fingerprint256} + +
+
+ +
: connection && effective ? <>

{effective.label}

{protocol !== 'local' && effective.username ? `${effective.username}@` : ''}{effective.hostname}{protocol !== 'local' && effective.port ? `:${effective.port}` : ''} ({protocol})

{protocol === 'local' &&

{t('plugins.hostActions.localExecution')}

} - {stream ? <>

{request.endpoint}

{t('plugins.hostActions.streamNote')}

: <> + {stream ? <> +

{request.endpoint}

+

{t('plugins.hostActions.streamNote')}

+ + : <>

{t(entry.scriptsRun ? 'plugins.hostActions.scriptsRun' : 'plugins.hostActions.noScripts')}

{t('plugins.hostActions.connectionNote')}

} : request.kind === 'vault.requestHostDraft' ? void state.respond('submit', draft)} /> : null} {state.error &&

{t('plugins.hostActions.failed')}

} + {directStreamConfirm && } + {tlsConfirm && } {connection && }
diff --git a/components/plugins/PluginHostDrawnPage.tsx b/components/plugins/PluginHostDrawnPage.tsx index 0871b670e..3feb38245 100644 --- a/components/plugins/PluginHostDrawnPage.tsx +++ b/components/plugins/PluginHostDrawnPage.tsx @@ -7,14 +7,39 @@ export type PluginHostDrawnPageProps = Parameters pluginId: string; }; +type MinimalTreeNode = { + type?: number; + attributes?: Record; + 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

{props.loadingLabel}

; - return
+ const fullBleed = hasFullBleedChrome(view.tree); + return
-
- -
+ {!fullBleed && ( +
+ +
+ )}
; } diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx index dd57fc2cb..9634234bc 100644 --- a/components/plugins/PluginRemoteSurface.test.tsx +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -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( {}} />); }); @@ -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('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + 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> = []; + 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( events.push(e as unknown as Record)} />); + }); + + 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('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + 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> = []; + 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( events.push(e as unknown as Record)} />); + }); + + // 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), /^ 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('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + 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((resolve) => { resolveImage = resolve; }); + const root = createRoot(document.getElementById('root')!); + try { + await act(async () => { + root.render( + {}} + />, + ); + }); + 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'); + } +}); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 56ff40bff..f3aa945fd 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -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; 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(SURFACE_EVENTS); +const SLOTTED_WIDGET_KINDS = new Set(['code-editor', 'data-grid', 'er-canvas']); + const ATTRIBUTE_NAMES: Record = { 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) | undefined>(undefined); function buildRemoteElementProps(node: RemoteElementNode): Record { @@ -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 surface.onEvent({ nodeId: node.id, type: 'dismiss' })}>; + return ( + surface.onEvent({ nodeId: node.id, type: 'dismiss' })} + > + + + ); }); +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(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) => { + onEvent({ + nodeId: node.id, + type: 'widget', + widgetEvent, + detail: detail as PluginSurfaceEvent['detail'], + }); + }, + [onEvent, node.id], + ); + return ( + + ); +}); + +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) => { + 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( +
+ +
, + shadowHost, + )} + + ); +}); + +const resolvedImageCache = new WeakMap<(path: string) => Promise, Map>(); +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) | undefined, imagePath: string | undefined): string | undefined { + if (!loader || !imagePath) return undefined; + return resolvedImageCache.get(loader)?.get(imagePath); +} + +function setCachedImageUrl(loader: (path: string) => Promise, 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(); + const [imageUrl, setImageUrl] = useState(() => 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 | 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 ; + const widgetKind = node.attributes['data-plugin-widget']; + if (widgetKind === 'split-pane') return ; + if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) { + return ; + } if (node.element === 'img') return ; if (node.element === 'select') return ; if (node.element === 'input' || node.element === 'textarea') return ; return ; } -/** 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; 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

Unable to display plugin view.

; - return Unable to display plugin view.

}>
; +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; 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

Unable to display plugin view.

; + return ( + Unable to display plugin view.

}> + + + +
+ ); +} + +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(null); const hostRef = useRef(null); const onEventRef = useRef(onEvent); onEventRef.current = onEvent; const shadowRef = useRef(null); const [shadow, setShadow] = useState(null); + const [shadowHost, setShadowHost] = useState(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>(); + const pendingScroll = new Map(); + + 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
-
- {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)} -
; + + 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 ( + +
+
+ {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)} +
+ + ); } diff --git a/components/plugins/PluginVaultPages.tsx b/components/plugins/PluginVaultPages.tsx index 1b1061ba8..0344667db 100644 --- a/components/plugins/PluginVaultPages.tsx +++ b/components/plugins/PluginVaultPages.tsx @@ -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; 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)}> {!collapsed && {page.title}} diff --git a/components/plugins/PluginViewPopover.tsx b/components/plugins/PluginViewPopover.tsx index 1d4bcd6ac..aa282f84d 100644 --- a/components/plugins/PluginViewPopover.tsx +++ b/components/plugins/PluginViewPopover.tsx @@ -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(null); const panel = useRef(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 <>
} + > + + +
+ )} + > + + + + ); +} diff --git a/components/plugins/primitives/PluginCodeEditorInner.tsx b/components/plugins/primitives/PluginCodeEditorInner.tsx new file mode 100644 index 000000000..7d98853da --- /dev/null +++ b/components/plugins/primitives/PluginCodeEditorInner.tsx @@ -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, 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(null); + const editorRef = useRef[0] | null>(null); + const monacoRef = useRef(null); + const handledKeyEventsRef = useRef>(new WeakSet()); + const disposablesRef = useRef>([]); + const onWidgetEventRef = useRef(onWidgetEvent); + onWidgetEventRef.current = onWidgetEvent; + const schemaRef = useRef(completionSchema); + schemaRef.current = completionSchema; + const lastEmittedValueRef = useRef(value); + const changeTimerRef = useRef | null>(null); + const selectionTimerRef = useRef | null>(null); + const readClipboardRef = useRef<() => Promise>(() => Promise.resolve(null)); + + const readClipboardText = useCallback(async (): Promise => ( + 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[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(); + 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 ( +
+ + +
+ )} + 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 ? ( + + ) : null} +
+ ); +} diff --git a/components/plugins/primitives/PluginDataGrid.tsx b/components/plugins/primitives/PluginDataGrid.tsx new file mode 100644 index 000000000..161f2d87b --- /dev/null +++ b/components/plugins/primitives/PluginDataGrid.tsx @@ -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(null); + const editInputRef = useRef(null); + const blurTimerRef = useRef | null>(null); + + const [colWidths, setColWidths] = useState>({}); + 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(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, 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) => { + 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 ( +
+ {loading && ( +
+ + + Loading... + +
+ )} + +
+ {visibleCols.length === 0 ? ( +
+ {emptyMessage} +
+ ) : ( +
+ {/* Sticky Header */} +
+
+ + # +
+ +
+ {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 ( +
+ + {sortable && ( + + {isSorted ? ( + sort.direction === 'asc' ? : + ) : ( + + )} + + )} +
startResizeColumn(e, col)} + className="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/60" + /> +
+ ); + })} +
+
+ + {/* Virtualized Rows Body */} + {totalRows === 0 ? ( +
+ {emptyMessage} +
+ ) : ( +
+ {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 ( +
+ {/* Sticky Gutter */} +
handleCellContextMenu(e, rowIndex, visibleCols[0]?.col.name ?? '')} + > + {}} + onClick={(e) => { + e.stopPropagation(); + toggleRowSelection(rowIndex, e.shiftKey); + }} + className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer" + /> + + {isInserted ? '+' : rowIndex + 1} + +
+ + {/* Virtualized Cells */} +
+ {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 ( +
{ + 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 ? ( +
e.stopPropagation()} + onDoubleClick={(e) => e.stopPropagation()} + > + 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 && ( + + )} +
+ ) : isNull ? ( + + NULL + + ) : typeof value === 'boolean' ? ( + + {value ? 'true' : 'false'} + + ) : ( + + {formatCellDisplay(value)} + + )} + {!isEditing && !isNull && fk && ( + + )} +
+ ); + })} +
+
+ ); + })} +
+ )} +
+ )} +
+
+ ); +} diff --git a/components/plugins/primitives/PluginErCanvas.tsx b/components/plugins/primitives/PluginErCanvas.tsx new file mode 100644 index 000000000..1f056deda --- /dev/null +++ b/components/plugins/primitives/PluginErCanvas.tsx @@ -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 { + const result: Record = {}; + 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(null); + const [positions, setPositions] = useState>(() => computeInitialPositions(tables)); + const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 }); + const [selectedTable, setSelectedTable] = useState(null); + const [hoveredRelation, setHoveredRelation] = useState(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 = {}; + 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(); + const byName = new Map(); + 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) => { + 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) => { + 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, 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, 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) => { + const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true }); + if (!shortcut) return; + if (shortcut !== 'escape') event.preventDefault(); + event.stopPropagation(); + onWidgetEvent('shortcut', { shortcut }); + }, [onWidgetEvent]); + + return ( +
+ {/* Floating Canvas Controls */} +
+ + + {Math.round(viewport.zoom * 100)}% + + +
+ + +
+ +
+ + {tables.length === 0 ? ( +
+ No tables to visualize +
+ ) : ( + + + + + + + + + + + + + {/* 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 ( + ${toKey}.${rel.toColumn}:${idx}`} + data-er-relation={`${rel.fromTable}.${rel.fromColumn}->${rel.toTable}.${rel.toColumn}`} + onPointerEnter={() => setHoveredRelation(idx)} + onPointerLeave={() => setHoveredRelation(null)} + > + + + + + {isHovered && ( + + + + {edgeLabel} + + + )} + + ); + })} + + {/* 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 ( + startCardDrag(e, table)} + onDoubleClick={(e) => handleCardDoubleClick(e, table)} + className="cursor-pointer" + filter="url(#nc-er-shadow)" + > + + {/* Header band */} + + + + {table.schema ? `${table.schema}.${table.name}` : table.name} + + + {/* 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 ( + + {`${col.name}: ${col.type}${col.nullable ? ' NULL' : ' NOT NULL'}`} + {colIdx > 0 && ( + + )} + {col.isPk && ( + + + + PK + + + )} + {col.isFk && ( + + + + FK + + + )} + + {displayName} + + + {displayType} + + + ); + })} + + ); + })} + + + )} +
+ ); +} diff --git a/components/plugins/primitives/PluginSplitPane.tsx b/components/plugins/primitives/PluginSplitPane.tsx new file mode 100644 index 000000000..35a15cfcd --- /dev/null +++ b/components/plugins/primitives/PluginSplitPane.tsx @@ -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(null); + const clampSize = useCallback( + (raw: number) => Math.max(minSize, Math.min(maxSize, Math.round(raw))), + [minSize, maxSize], + ); + + const [size, setSize] = useState(() => clampSize(initialSize)); + const [collapsed, setCollapsed] = useState(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) => { + 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 ( +
+
+ {firstChild} +
+ +
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', + }} + > +
+
+ +
+ {secondChild} +
+
+ ); +} diff --git a/components/plugins/primitives/PluginWidgetRenderer.tsx b/components/plugins/primitives/PluginWidgetRenderer.tsx new file mode 100644 index 000000000..7789c2bdd --- /dev/null +++ b/components/plugins/primitives/PluginWidgetRenderer.tsx @@ -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(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>(rawProps), [rawProps]); + + return ( + Unable to render plugin widget.
} + > + {kind === 'code-editor' && ( + + )} + {kind === 'data-grid' && ( + + )} + {kind === 'er-canvas' && ( + + )} + + ); +} diff --git a/components/plugins/primitives/erFormat.test.ts b/components/plugins/primitives/erFormat.test.ts new file mode 100644 index 000000000..1c615622f --- /dev/null +++ b/components/plugins/primitives/erFormat.test.ts @@ -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, /^$/); + assert.match(svg, /public\.customers/); + assert.match(svg, /varchar\(180\)/); + assert.match(svg, />PKFK { + 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); +}); diff --git a/components/plugins/primitives/erFormat.ts b/components/plugins/primitives/erFormat.ts new file mode 100644 index 000000000..243a87b1c --- /dev/null +++ b/components/plugins/primitives/erFormat.ts @@ -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): 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, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +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, + palette: ErSvgPalette, +): string { + const byKey = new Map(); + const byName = new Map(); + 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[] = [ + ``, + ``, + ]; + + 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( + ``, + ``, + ``, + ); + } + + 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(``); + lines.push(``); + lines.push(``); + lines.push(``); + lines.push(`${escapeXml(title)}`); + + 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(``); + if (colIdx > 0) { + lines.push(``); + } + if (col.isPk) { + lines.push(`PK`); + } + if (col.isFk) { + const fkX = col.isPk ? 34 : 8; + lines.push(`FK`); + } + lines.push(`${escapeXml(colLabel)}`); + lines.push(`${escapeXml(shortType)}`); + lines.push(''); + }); + lines.push(''); + } + + lines.push(''); + return lines.join('\n'); +} diff --git a/components/plugins/primitives/shortcuts.ts b/components/plugins/primitives/shortcuts.ts new file mode 100644 index 000000000..3f32acc45 --- /dev/null +++ b/components/plugins/primitives/shortcuts.ts @@ -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; +} diff --git a/components/plugins/primitives/sqlStatement.test.ts b/components/plugins/primitives/sqlStatement.test.ts new file mode 100644 index 000000000..1a194ae89 --- /dev/null +++ b/components/plugins/primitives/sqlStatement.test.ts @@ -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); +}); diff --git a/components/plugins/primitives/sqlStatement.ts b/components/plugins/primitives/sqlStatement.ts new file mode 100644 index 000000000..ceb9ded02 --- /dev/null +++ b/components/plugins/primitives/sqlStatement.ts @@ -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 { + const aliases = new Map(); + 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; +} diff --git a/components/plugins/primitives/types.ts b/components/plugins/primitives/types.ts new file mode 100644 index 000000000..8b48ef92a --- /dev/null +++ b/components/plugins/primitives/types.ts @@ -0,0 +1,136 @@ +export type PluginWidgetEventCallback = ( + widgetEvent: string, + detail?: Record, +) => 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 | unknown[]; + +export interface PluginDataGridWidgetProps { + columns?: PluginDataGridColumn[]; + rows?: PluginDataGridRow[]; + hiddenColumns?: string[]; + rowKeyField?: string; + dirtyCells?: Record; + 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[]; +} diff --git a/components/systemManager/PortsManagerTab.test.tsx b/components/systemManager/PortsManagerTab.test.tsx new file mode 100644 index 000000000..47e7b8db4 --- /dev/null +++ b/components/systemManager/PortsManagerTab.test.tsx @@ -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\}/); +}); diff --git a/components/systemManager/PortsManagerTab.tsx b/components/systemManager/PortsManagerTab.tsx index 7885b952a..ea34bf938 100644 --- a/components/systemManager/PortsManagerTab.tsx +++ b/components/systemManager/PortsManagerTab.tsx @@ -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(null); const [listPending, setListPending] = useState(false); + const [forwardDialogPort, setForwardDialogPort] = useState(null); + const [forwardDialogInitialPort, setForwardDialogInitialPort] = useState(8080); + const [forwardDialogInitialBind, setForwardDialogInitialBind] = useState(DEFAULT_QUICK_FORWARD_BIND_ADDRESS); + const [forwardBusy, setForwardBusy] = useState(false); + const [forwardError, setForwardError] = useState(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 => { @@ -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>(); + 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(); + 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 ( - {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 })} {actionError ? : null} @@ -192,34 +325,125 @@ export const PortsManagerTab = memo(function PortsManagerTab({ ) : ( - {ports.map((port) => ( - - {port.protocol.toUpperCase()} - - )} - actions={allowMutations && port.pid != null ? ( - setPendingKillPid(port.pid)} - > - - - ) : 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 ? ( + + + + + +
+
+ {formatHostPort(activeRule.bindAddress, activeRule.localPort)} + {' → '} + {formatHostPort( + activeRule.remoteHost || resolveForwardRemoteHost(port), + activeRule.remotePort ?? port.port, + )} +
+
+ {activeRule.status === 'connecting' + ? (activeRule.error || t('systemManager.ports.forwarding')) + : t('systemManager.ports.clickToCopy')} +
+
+ + + ) : ( + + {port.protocol.toUpperCase()} + + ); + + const hasActions = canForwardRow || (allowMutations && port.pid != null); + + return ( + + {canForwardRow ? ( + activeRule ? ( + void handleStopForward(activeRule)} + > + + + ) : ( + openForwardDialog(port)} + > + + + ) + ) : null} + {allowMutations && port.pid != null ? ( + setPendingKillPid(port.pid)} + > + + + ) : null} + + ) : null} + /> + ); + })} )} + { + if (!open && !forwardBusy) { + setForwardDialogPort(null); + setForwardError(null); + } + }} + onSubmit={(values) => void handleSubmitForward(values)} + /> + 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(null); + const localPortInputRef = useRef(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 ( + { if (!busy || nextOpen) onOpenChange(nextOpen); }}> + + + {t('systemManager.ports.forwardTitle')} + + {hostLabel + ? t('systemManager.ports.forwardDescWithHost', { host: hostLabel }) + : t('systemManager.ports.forwardDesc')} + + + +
+
+
+ {localPreviewEndpoint} + + {remoteEndpoint} +
+
+ {port.processName + ? `${port.processName}${port.pid != null ? ` · PID ${port.pid}` : ''} · ${port.protocol.toUpperCase()}` + : `${port.protocol.toUpperCase()}${port.pid != null ? ` · PID ${port.pid}` : ''}`} +
+
+ +
+ + { + setLocalPortText(event.target.value); + if (localError) setLocalError(null); + }} + placeholder={String(initialLocalPort)} + className="h-9 font-mono text-sm" + disabled={busy} + /> +
+ +
+
+ +
+ {BIND_ADDRESS_PRESETS.map((preset) => ( + + ))} +
+
+ { + 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} + /> +
+ + {displayError && ( +

+ {displayError} +

+ )} + + + + + +
+
+
+ ); +}); diff --git a/components/systemManager/SystemManagerSidePanel.tsx b/components/systemManager/SystemManagerSidePanel.tsx index 8e9410436..e8528e7a2 100644 --- a/components/systemManager/SystemManagerSidePanel.tsx +++ b/components/systemManager/SystemManagerSidePanel.tsx @@ -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} />
) : null} diff --git a/components/terminal/ComposeDirectoryPicker.test.tsx b/components/terminal/ComposeDirectoryPicker.test.tsx new file mode 100644 index 000000000..8af2430a8 --- /dev/null +++ b/components/terminal/ComposeDirectoryPicker.test.tsx @@ -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( + {}} /> + ); + }); + 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); + }); +} diff --git a/components/terminal/ComposeDirectoryPicker.tsx b/components/terminal/ComposeDirectoryPicker.tsx index 665d4fe1c..78533d2ff 100644 --- a/components/terminal/ComposeDirectoryPicker.tsx +++ b/components/terminal/ComposeDirectoryPicker.tsx @@ -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 { if (value) outside.current = false; model.setOpen(value); }}> diff --git a/components/terminal/TerminalConnectionDialog.test.ts b/components/terminal/TerminalConnectionDialog.test.ts index f17ae97dd..70e871bd9 100644 --- a/components/terminal/TerminalConnectionDialog.test.ts +++ b/components/terminal/TerminalConnectionDialog.test.ts @@ -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>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>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 }, diff --git a/components/terminal/TerminalConnectionDialog.tsx b/components/terminal/TerminalConnectionDialog.tsx index 12e59c649..ed3b81bb3 100644 --- a/components/terminal/TerminalConnectionDialog.tsx +++ b/components/terminal/TerminalConnectionDialog.tsx @@ -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, + host: Pick, + 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 = 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)}
) : ( diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index a7e956c46..0179cf6c1 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -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, }); } diff --git a/components/terminal/runtime/createTerminalSessionStarters.types.ts b/components/terminal/runtime/createTerminalSessionStarters.types.ts index d30c4550c..2b7b46784 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.types.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.types.ts @@ -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; diff --git a/components/terminal/runtime/terminalBackspaceInput.test.ts b/components/terminal/runtime/terminalBackspaceInput.test.ts index 5f1f1f37b..5de44b283 100644 --- a/components/terminal/runtime/terminalBackspaceInput.test.ts +++ b/components/terminal/runtime/terminalBackspaceInput.test.ts @@ -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"); }); diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts index 912d261fc..d8d5ad55b 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts +++ b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts @@ -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(/ { + 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', diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.tsx b/components/terminalLayer/TerminalLayerSidePanelSection.tsx index d5f6cd7e4..65fdbe2da 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.tsx +++ b/components/terminalLayer/TerminalLayerSidePanelSection.tsx @@ -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({ {label} + { received.dismissed = true; }}> + Action + + { received.resizeEnd = d; }}> + { received.execute = d; }} onShortcut={(d) => { received.editorShortcut = d; }} /> + { received.cellEdit = d; }} + onFkJump={(d) => { received.fkJump = d; }} + onCellCopy={(d) => { received.cellCopy = d; }} + onCellDoubleClick={(d) => { received.cellDoubleClick = d; }} + /> + + { received.tableClick = d; }} + onTableDoubleClick={(d) => { received.tableDoubleClick = d; }} + onExportSvg={(d) => { received.exportSvg = d; }} + /> +
+ ); + } + + const registration = registerHostReactView(views, 'com.example.ide', () => ); + try { + await act(async () => { + receive({ kind: 'host-ui.open', instanceId: 'ide-1' }); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + + const btn = document.getElementById('row-btn')!; + const editorEl = document.querySelector('[data-plugin-widget="code-editor"]')!; + const gridEl = document.querySelector('[data-plugin-widget="data-grid"]')!; + const splitEl = document.querySelector('[data-plugin-widget="split-pane"]')!; + const erEl = document.querySelector('[data-plugin-widget="er-canvas"]')!; + const popoverEl = document.querySelector('[data-plugin-popover="true"]')!; + + assert.equal(popoverEl.getAttribute('data-plugin-anchor-x'), '40'); + assert.equal(popoverEl.getAttribute('data-plugin-anchor-y'), '60'); + assert.equal(popoverEl.getAttribute('data-plugin-popover-width'), '240'); + assert.equal(popoverEl.getAttribute('data-plugin-popover-max-height'), '300'); + + await act(async () => { + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'dblclick', nodeId: remoteId(btn), x: 12, y: 34 } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'contextmenu', nodeId: remoteId(btn), x: 56, y: 78 } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'keydown', nodeId: remoteId(btn), key: 'k', metaKey: true } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'execute', detail: { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+s' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'id', value: '2', isNull: false } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellCopy', detail: { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 1 } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(splitEl), widgetEvent: 'resizeEnd', detail: { size: 320, collapsed: false } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableClick', detail: { table: 'users' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableDoubleClick', detail: { table: 'users' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'exportSvg', detail: { svg: '' } } }); + }); + + assert.deepEqual(received.dblclick, { x: 12, y: 34 }); + assert.deepEqual(received.contextmenu, { x: 56, y: 78 }); + assert.deepEqual(received.execute, { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' }); + assert.deepEqual(received.editorShortcut, { shortcut: 'mod+s' }); + // editorEl consumed mod+s via onShortcut (must NOT double-fire usePluginShortcuts); + // btn (Shadow DOM) and gridEl (no onShortcut) bubble to usePluginShortcuts once each. + assert.deepEqual(globalShortcuts, ['mod+k', 'mod+z']); + assert.deepEqual(received.cellEdit, { rowIndex: 0, colName: 'id', value: '2', isNull: false }); + assert.deepEqual(received.fkJump, { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' }); + assert.deepEqual(received.cellCopy, { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] }); + assert.deepEqual(received.cellDoubleClick, { rowIndex: 0, colName: 'id', value: 1 }); + assert.deepEqual(received.resizeEnd, { size: 320, collapsed: false }); + assert.deepEqual(received.tableClick, { table: 'users' }); + assert.deepEqual(received.tableDoubleClick, { table: 'users' }); + assert.deepEqual(received.exportSvg, { svg: '' }); + await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'ide-1' }); }); + } finally { + await act(async () => { registration.dispose(); }); + 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'); + dom.window.close(); + } +}); diff --git a/packages/plugin-sdk/src/hostReact.ts b/packages/plugin-sdk/src/hostReact.ts index 023bf3509..68f0a4389 100644 --- a/packages/plugin-sdk/src/hostReact.ts +++ b/packages/plugin-sdk/src/hostReact.ts @@ -1,5 +1,5 @@ import { createRoot } from 'react-dom/client'; -import { createElement, useEffect, useRef, type ReactNode } from 'react'; +import { createElement, useEffect, useMemo, useRef, type CSSProperties, type ReactNode } from 'react'; import type { Disposable, PluginViews } from './index.js'; import { registerHostDomView } from './hostDom.js'; @@ -10,13 +10,436 @@ export function registerHostReactView(views: PluginViews, viewId: string, render }, css); } +export type PluginWorkbenchShortcut = + | 'mod+k' + | 'mod+s' + | 'mod+t' + | 'mod+w' + | 'mod+z' + | 'mod+shift+z' + | 'escape'; + +/** + * Subscribe to normalized global workbench shortcuts forwarded from both the + * Shadow DOM surface and slotted host-rendered widgets (CodeEditor, DataGrid, ErCanvas). + */ +export function usePluginShortcuts(handler: (shortcut: PluginWorkbenchShortcut) => void): void { + const handlerRef = useRef(handler); + handlerRef.current = handler; + useEffect(() => { + const listener = (event: Event) => { + const shortcut = (event as CustomEvent<{ shortcut?: PluginWorkbenchShortcut }>).detail?.shortcut; + if (typeof shortcut === 'string') { + handlerRef.current(shortcut); + } + }; + document.addEventListener('netcatty-shortcut', listener); + return () => document.removeEventListener('netcatty-shortcut', listener); + }, []); +} + +export interface PluginPopoverProps { + anchor?: string; + anchorX?: number; + anchorY?: number; + width?: number; + maxHeight?: number; + open: boolean; + onClose(): void; + children: ReactNode; +} + /** A host-positioned popup with freely authored content. */ -export function PluginPopover({ anchor, open, onClose, children }: { anchor: string; open: boolean; onClose(): void; children: ReactNode }) { +export function PluginPopover({ + anchor, + anchorX, + anchorY, + width, + maxHeight, + open, + onClose, + children, +}: PluginPopoverProps) { const ref = useRef(null); useEffect(() => { const node = ref.current; if (!node) return; node.addEventListener('netcatty-dismiss', onClose); return () => node.removeEventListener('netcatty-dismiss', onClose); }, [onClose]); - return createElement('div', { ref, 'data-plugin-popover': 'true', 'data-plugin-anchor': anchor, ...(open ? { open: true } : {}) }, children); + return createElement( + 'div', + { + ref, + 'data-plugin-popover': 'true', + ...(anchor ? { 'data-plugin-anchor': anchor } : {}), + ...(anchorX !== undefined ? { 'data-plugin-anchor-x': String(anchorX) } : {}), + ...(anchorY !== undefined ? { 'data-plugin-anchor-y': String(anchorY) } : {}), + ...(width !== undefined ? { 'data-plugin-popover-width': String(width) } : {}), + ...(maxHeight !== undefined ? { 'data-plugin-popover-max-height': String(maxHeight) } : {}), + ...(open ? { open: true } : {}), + }, + children, + ); +} + +type WidgetEventDetail = { widgetEvent?: string; detail?: Record }; + +function useWidgetEventBridge( + ref: React.RefObject, + handler: (widgetEvent: string, detail: Record) => boolean | void, +) { + const handlerRef = useRef(handler); + handlerRef.current = handler; + useEffect(() => { + const node = ref.current; + if (!node) return; + const listener = (event: Event) => { + const payload = (event as CustomEvent).detail; + if (!payload || typeof payload.widgetEvent !== 'string') return; + if (handlerRef.current(payload.widgetEvent, payload.detail ?? {}) === true) { + event.preventDefault(); + } + }; + node.addEventListener('netcatty-widget-event', listener); + return () => node.removeEventListener('netcatty-widget-event', listener); + }, [ref]); +} + +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 PluginCodeEditorProps { + 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; + className?: string; + style?: CSSProperties; + onChange?: (detail: { value: string }) => void; + onSelection?: (detail: { selectionStart: number; selectionEnd: number; selectedText: string }) => void; + onExecute?: (detail: { value: string; selectedText: string; currentStatement: string }) => void; + onFormat?: (detail: { value: string }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; +} + +/** Host-rendered Monaco code editor with local zero-IPC schema completion. */ +export function PluginCodeEditor({ + value, + language, + readOnly, + placeholder, + lineNumbers, + minimap, + wordWrap, + completionSchema, + diagnostics, + height, + className, + style, + onChange, + onSelection, + onExecute, + onFormat, + onShortcut, +}: PluginCodeEditorProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'change') onChange?.(detail as { value: string }); + else if (eventName === 'selection') onSelection?.(detail as { selectionStart: number; selectionEnd: number; selectedText: string }); + else if (eventName === 'execute') onExecute?.(detail as { value: string; selectedText: string; currentStatement: string }); + else if (eventName === 'format') onFormat?.(detail as { value: string }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } + }); + const serialized = useMemo( + () => JSON.stringify({ + value, + ...(language !== undefined ? { language } : {}), + ...(readOnly !== undefined ? { readOnly } : {}), + ...(placeholder !== undefined ? { placeholder } : {}), + ...(lineNumbers !== undefined ? { lineNumbers } : {}), + ...(minimap !== undefined ? { minimap } : {}), + ...(wordWrap !== undefined ? { wordWrap } : {}), + ...(completionSchema !== undefined ? { completionSchema } : {}), + ...(diagnostics !== undefined ? { diagnostics } : {}), + ...(height !== undefined ? { height } : {}), + }), + [value, language, readOnly, placeholder, lineNumbers, minimap, wordWrap, completionSchema, diagnostics, height], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'code-editor', + 'data-plugin-widget-props': serialized, + }); +} + +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 | unknown[]; + +export interface PluginDataGridProps { + columns: PluginDataGridColumn[]; + rows: PluginDataGridRow[]; + hiddenColumns?: string[]; + rowKeyField?: string; + dirtyCells?: Record; + deletedRowIndices?: number[]; + insertedRows?: PluginDataGridRow[]; + selectedRowIndices?: number[]; + sort?: PluginDataGridSort | null; + editable?: boolean; + loading?: boolean; + emptyMessage?: string; + className?: string; + style?: CSSProperties; + onCellSelect?: (detail: { rowIndex: number; colName: string; value: unknown }) => void; + onCellDoubleClick?: (detail: { rowIndex: number; colName: string; value: unknown }) => void; + onCellEdit?: (detail: { rowIndex: number; colName: string; value: unknown; isNull: boolean }) => void; + onCellContextMenu?: (detail: { rowIndex: number; colName: string; x: number; y: number }) => void; + onCellCopy?: (detail: { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] }) => void; + onFkJump?: (detail: { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string }) => void; + onSortChange?: (detail: { column: string; direction: 'asc' | 'desc' }) => void; + onRowSelect?: (detail: { selectedRowIndices: number[] }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; +} + +/** Host-rendered virtualized editable data grid powered by @tanstack/react-virtual. */ +export function PluginDataGrid({ + columns, + rows, + hiddenColumns, + rowKeyField, + dirtyCells, + deletedRowIndices, + insertedRows, + selectedRowIndices, + sort, + editable, + loading, + emptyMessage, + className, + style, + onCellSelect, + onCellDoubleClick, + onCellEdit, + onCellContextMenu, + onCellCopy, + onFkJump, + onSortChange, + onRowSelect, + onShortcut, +}: PluginDataGridProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'cellSelect') onCellSelect?.(detail as { rowIndex: number; colName: string; value: unknown }); + else if (eventName === 'cellDoubleClick') onCellDoubleClick?.(detail as { rowIndex: number; colName: string; value: unknown }); + else if (eventName === 'cellEdit') onCellEdit?.(detail as { rowIndex: number; colName: string; value: unknown; isNull: boolean }); + else if (eventName === 'cellContextMenu') onCellContextMenu?.(detail as { rowIndex: number; colName: string; x: number; y: number }); + else if (eventName === 'cellCopy') onCellCopy?.(detail as { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] }); + else if (eventName === 'fkJump') onFkJump?.(detail as { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string }); + else if (eventName === 'sortChange') onSortChange?.(detail as { column: string; direction: 'asc' | 'desc' }); + else if (eventName === 'rowSelect') onRowSelect?.(detail as { selectedRowIndices: number[] }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } + }); + const serialized = useMemo( + () => JSON.stringify({ + columns, + rows, + ...(hiddenColumns !== undefined ? { hiddenColumns } : {}), + ...(rowKeyField !== undefined ? { rowKeyField } : {}), + ...(dirtyCells !== undefined ? { dirtyCells } : {}), + ...(deletedRowIndices !== undefined ? { deletedRowIndices } : {}), + ...(insertedRows !== undefined ? { insertedRows } : {}), + ...(selectedRowIndices !== undefined ? { selectedRowIndices } : {}), + ...(sort !== undefined ? { sort } : {}), + ...(editable !== undefined ? { editable } : {}), + ...(loading !== undefined ? { loading } : {}), + ...(emptyMessage !== undefined ? { emptyMessage } : {}), + }), + [columns, rows, hiddenColumns, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'data-grid', + 'data-plugin-widget-props': serialized, + }); +} + +export interface PluginSplitPaneProps { + direction?: 'horizontal' | 'vertical'; + initialSize?: number; + minSize?: number; + maxSize?: number; + collapsible?: boolean; + collapsed?: boolean; + className?: string; + style?: CSSProperties; + onResizeEnd?: (detail: { size: number; collapsed?: boolean }) => void; + children: ReactNode; +} + +/** Host-rendered 60fps resizable 2-child split pane container. */ +export function PluginSplitPane({ + direction = 'horizontal', + initialSize, + minSize, + maxSize, + collapsible, + collapsed, + className, + style, + onResizeEnd, + children, +}: PluginSplitPaneProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'resizeEnd') onResizeEnd?.(detail as { size: number; collapsed?: boolean }); + }); + const serialized = useMemo( + () => JSON.stringify({ + direction, + ...(initialSize !== undefined ? { initialSize } : {}), + ...(minSize !== undefined ? { minSize } : {}), + ...(maxSize !== undefined ? { maxSize } : {}), + ...(collapsible !== undefined ? { collapsible } : {}), + ...(collapsed !== undefined ? { collapsed } : {}), + }), + [direction, initialSize, minSize, maxSize, collapsible, collapsed], + ); + return createElement( + 'div', + { + ref, + className, + style, + 'data-plugin-widget': 'split-pane', + 'data-plugin-widget-props': serialized, + }, + children, + ); +} + +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 PluginErCanvasProps { + tables: PluginErTable[]; + relations: PluginErRelation[]; + className?: string; + style?: CSSProperties; + onTableClick?: (detail: { table: string; schema?: string }) => void; + onTableDoubleClick?: (detail: { table: string; schema?: string }) => void; + onExportSvg?: (detail: { svg: string }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; +} + +/** Host-rendered interactive pan/zoom SVG ER diagram canvas. */ +export function PluginErCanvas({ + tables, + relations, + className, + style, + onTableClick, + onTableDoubleClick, + onExportSvg, + onShortcut, +}: PluginErCanvasProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'tableClick') onTableClick?.(detail as { table: string; schema?: string }); + else if (eventName === 'tableDoubleClick') onTableDoubleClick?.(detail as { table: string; schema?: string }); + else if (eventName === 'exportSvg') onExportSvg?.(detail as { svg: string }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } + }); + const serialized = useMemo( + () => JSON.stringify({ tables, relations }), + [tables, relations], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'er-canvas', + 'data-plugin-widget-props': serialized, + }); } diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts index 8e80fd11c..9f93f1f3c 100644 --- a/packages/plugin-sdk/src/index.test.ts +++ b/packages/plugin-sdk/src/index.test.ts @@ -55,6 +55,12 @@ const testSecretStore: PluginSecretStore = { async get() { return testSecretRef; }, + async getPlaintext() { + return "own-secret-value"; + }, + async readOwn() { + return "own-secret-value"; + }, async set() { return testSecretRef; }, diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 7ac3ff675..8e34f6d8b 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -72,11 +72,15 @@ export interface PluginKeyValueStore { get(key: string): Promise; set(key: string, value: JsonValue): Promise; delete(key: string): Promise; - keys(): Promise; + keys(options?: Readonly<{ prefix?: string }>): Promise; } export interface PluginSecretStore { get(key: string): Promise; + /** Reads plaintext of a secret previously stored by this plugin in its own encrypted namespace. */ + getPlaintext(key: string): Promise; + /** Alias for getPlaintext(key); strictly scoped to this plugin's own secrets, never Netcatty Vault credentials. */ + readOwn(key: string): Promise; set(key: string, value: string): Promise; delete(key: string): Promise; } @@ -110,10 +114,68 @@ export interface PluginCommands { executeCommand(commandId: string, args?: JsonValue): Promise; } +export interface PluginFileDialogFilter { + readonly name: string; + readonly extensions: readonly string[]; +} + +export interface PluginOpenFileOptions { + readonly title?: string; + readonly filters?: readonly PluginFileDialogFilter[]; + readonly readAs?: "bytes" | "utf8"; + readonly maxBytes?: number; +} + +export type PluginOpenFileResult = + | Readonly<{ cancelled: true }> + | Readonly<{ + cancelled: false; + name: string; + size: number; + handleId: string; + data: TData; + }>; + +export interface PluginSaveFileOptions { + readonly title?: string; + readonly defaultName?: string; + readonly filters?: readonly PluginFileDialogFilter[]; + readonly data: Uint8Array | ArrayBuffer | string; + readonly encoding?: "base64" | "utf8"; +} + +export type PluginSaveFileResult = + | Readonly<{ cancelled: true }> + | Readonly<{ + cancelled: false; + name: string; + size: number; + handleId: string; + }>; + +export interface PluginFileHandleWriteResult { + readonly bytesWritten: number; + readonly totalSize: number; +} + export interface PluginHostUI { quickPick(title: string, items: readonly import("@netcatty/plugin-contract").HostQuickPickItem[]): Promise; /** Single-line text. The host rejects CR/LF in initial values and submitted responses. */ input(title: string, initialValue?: string): Promise; + /** Opens a native OS file picker and returns contents + a revocable per-runtime file handle. */ + openFile(options?: PluginOpenFileOptions & Readonly<{ readAs: "utf8" }>): Promise>; + openFile(options?: PluginOpenFileOptions & Readonly<{ readAs?: "bytes" }>): Promise>; + openFile(options?: PluginOpenFileOptions): Promise; + /** Opens a native OS save dialog and writes atomically, returning a revocable per-runtime file handle. */ + saveFile(options: PluginSaveFileOptions): Promise; + /** Reads from a previously user-picked file handle without re-prompting. */ + readFileHandle(handleId: string, options: Readonly<{ readAs: "utf8" }>): Promise; + readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" }>): Promise; + readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" | "utf8" }>): Promise; + /** Atomically writes back to a previously user-picked file handle without re-prompting. */ + writeFileHandle(handleId: string, data: Uint8Array | ArrayBuffer | string, options?: Readonly<{ encoding?: "base64" | "utf8" }>): Promise; + /** Releases a user-picked file handle. */ + closeFileHandle(handleId: string): Promise; } /** Saved-host selection does not grant editing, connecting or session access. @@ -124,6 +186,8 @@ export interface PluginVault { /** Managed SSH-config drafts require the full Vault host editor. */ requestHostDraft(params: import("@netcatty/plugin-contract").VaultHostDraftParams): Promise; requestConnect(params: import("@netcatty/plugin-contract").VaultHostConnectParams): Promise; + /** Revokes a previously remembered durable SSH tunnel binding token. */ + revokeHostBinding(hostBindingToken: string): Promise>; } export interface PluginClipboard { @@ -701,10 +765,20 @@ export interface PluginAgentClient { closeChat(params: import("@netcatty/plugin-contract").PluginAgentChatRef): Promise; } +export interface PluginByteStreamUpgradeTlsOptions { + readonly servername?: string; + readonly allowSelfSigned?: boolean; + readonly caPem?: string; +} + export interface PluginByteConnection extends Disposable { readonly endpoint: string; + /** Present when connectViaHost created or reused a durable SSH tunnel binding. */ + readonly hostBindingToken?: string; readonly readable: PluginReadableByteStream; readonly writable: PluginWritableByteStream; + /** Performs an in-band STARTTLS upgrade on an open plaintext byte stream. */ + upgradeTls(options?: PluginByteStreamUpgradeTlsOptions): Promise; /** Closes both directions. Repeated calls on this handle are harmless. */ close(): Promise; } @@ -985,7 +1059,7 @@ export function throwIfCancellationRequested(token: CancellationToken): void { } export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contract"; -export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract"; +export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_HOST_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract"; export { PLUGIN_AI_MODEL_INVOCATION_FEATURE, PLUGIN_SELECTED_CONTEXT_FEATURE } from "@netcatty/plugin-contract"; export { PLUGIN_HOST_INTERACTION_FEATURE } from "@netcatty/plugin-contract"; diff --git a/scripts/fixtures/ssh-tab-title-policy.tsx b/scripts/fixtures/ssh-tab-title-policy.tsx new file mode 100644 index 000000000..93c0eac43 --- /dev/null +++ b/scripts/fixtures/ssh-tab-title-policy.tsx @@ -0,0 +1,242 @@ +import React, { useState } from "react"; +import { createRoot } from "react-dom/client"; +import { flushSync } from "react-dom"; +import { useSessionState } from "../../application/state/useSessionState"; +import { createPromptHostnameSessionSignalController } from "../../application/state/promptHostnameSessionSignalController"; +import { sessionPresentationStore } from "../../application/state/sessionPresentationStore"; +import { extractTerminalPromptHostname } from "../../domain/terminalPromptSecurity"; +import type { DynamicTabTitleMode, Host, TerminalSession, Workspace } from "../../domain/models"; +import { SessionTopTab, WorkspaceTopTab } from "../../components/top-tabs/TopTabItems"; +import { TooltipProvider } from "../../components/ui/tooltip"; + +const hosts: Host[] = [ + { id: "production", label: "\u751f\u4ea7", hostname: "203.0.113.10", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, + { id: "database", label: "Database", hostname: "198.51.100.20", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, + { id: "jump", label: "Jump fleet", hostname: "jump.example.test", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, +]; +const noop = () => {}; +type SessionState = ReturnType; +let state: SessionState; +let setMode: React.Dispatch>; +let setRevision: React.Dispatch>; +let revision = 0; +let fixtureRenderCount = 0; + +function workspace(id: string, sessions: TerminalSession[], title: string, autoTitle: boolean, generatedTitle = false): Workspace { + return { + id, title, autoTitle, generatedTitle, focusedSessionId: sessions[0].id, + root: { id: `${id}-root`, type: "split", direction: "vertical", children: sessions.map(session => ({ id: `${id}-${session.id}`, type: "pane", sessionId: session.id })) }, + }; +} + +function Fixture() { + fixtureRenderCount += 1; + state = useSessionState({ persistSessionRestore: false }); + const [mode, updateMode] = useState(); + const [commit, updateRevision] = useState(0); + setMode = updateMode; + setRevision = updateRevision; + const members = state.sessions.slice(0, 2); + const shared = { + isBeingDragged: false, isDraggingForReorder: false, shiftStyle: {}, + showDropIndicatorBefore: false, showDropIndicatorAfter: false, + onTabDragStart: noop, onTabDragEnd: noop, onTabDragOver: noop, onTabDragLeave: noop, onTabDrop: noop, + tabDoubleClickBehavior: "disabled" as const, dynamicTabTitleMode: mode, + renderBulkCloseItems: () => null, t: (key: string) => key, + }; + const workspaces = members.length === 2 ? [ + workspace("auto", members, "Workspace", true), + workspace("generated", members, members.map(session => session.hostLabel).join("/"), false, true), + workspace("explicit", members, "My Cluster", false), + ] : []; + return +
+

Production SSH tab title policy

+
+ {state.sessions.map(session => host.id === session.hostId)} + onCloseSession={noop} onRenameSession={state.startSessionRename} + onCopySession={noop} onCopySessionToNewWindow={noop} />)} +
+
+ {workspaces.map(item => session.id)} + paneCount={members.length} isHostDropTarget={false} + onRenameWorkspace={noop} onCopyWorkspace={noop} onCloseWorkspace={noop} />)} +
+
+
; +} + +function waitForCommit(expected: number): Promise { + const ready = () => document.querySelector(`[data-fixture-commit="${expected}"]`) !== null; + if (ready()) return Promise.resolve(); + return new Promise((resolve, reject) => { + const observer = new MutationObserver(() => { + if (!ready()) return; + observer.disconnect(); + clearTimeout(timeout); + resolve(); + }); + const timeout = setTimeout(() => { + observer.disconnect(); + reject(new Error(`React commit ${expected} was not observed within 60 seconds`)); + }, 60_000); + observer.observe(document.body, { attributes: true, childList: true, subtree: true }); + }); +} + +async function change(action: () => void): Promise { + revision += 1; + flushSync(() => { action(); setRevision(revision); }); + await waitForCommit(revision); +} + +export type TitleMeasurement = { scenario: string; tabId: string; actual: string; expected: string }; + +function titleSpan(tabId: string): Element { + const span = document.querySelector(`[data-tab-id="${tabId}"] span.truncate.leading-5`); + if (!span) throw new Error(`Missing production title span for ${tabId}`); + return span; +} + +function title(tabId: string): string { + return titleSpan(tabId).textContent ?? ""; +} + +function waitForTitleMutation(tabId: string, action: () => void): Promise { + const span = titleSpan(tabId); + const before = span.textContent; + return new Promise((resolve, reject) => { + const observer = new MutationObserver(() => { + if (span.textContent === before) return; + observer.disconnect(); + clearTimeout(timeout); + resolve(); + }); + const timeout = setTimeout(() => { + observer.disconnect(); + reject(new Error(`Production title ${tabId} did not mutate after a store-only update within 60 seconds`)); + }, 60_000); + observer.observe(span, { characterData: true, childList: true, subtree: true }); + try { action(); } catch (error) { + observer.disconnect(); + clearTimeout(timeout); + reject(error); + } + }); +} + +function promptHost(prompt: string): string { + const hostname = extractTerminalPromptHostname(prompt); + if (!hostname) throw new Error(`Fixture prompt was not parsed: ${JSON.stringify(prompt)}`); + return hostname; +} + +export async function runSshTabTitlePolicy(): Promise<{ rows: TitleMeasurement[]; promptOnlyParentRenders: number }> { + const node = document.getElementById("root"); + if (!node) throw new Error("Missing fixture root"); + const root = createRoot(node); + const rows: TitleMeasurement[] = []; + const record = (scenario: string, tabId: string, expected: string) => { + rows.push({ scenario, tabId, actual: title(tabId), expected }); + }; + const controller = createPromptHostnameSessionSignalController({ + getSession: id => state.sessions.find(session => session.id === id), + onChange: (id, hostname) => state.updateSessionPromptHost(id, hostname), + }); + let first = ""; + let second = ""; + let jump = ""; + try { + flushSync(() => root.render()); + await waitForCommit(0); + await change(() => { + first = state.connectToHost(hosts[0]); + second = state.connectToHost(hosts[1]); + }); + await change(() => { + state.updateSessionStatus(first, "connected"); + state.updateSessionStatus(second, "connected"); + }); + record("initial saved host name", first, hosts[0].label); + const firstPrompt = "[fixture@VM-0-8-centos ~]# "; + const secondPrompt = "[fixture@db-target ~]# "; + const firstObserved = promptHost(firstPrompt); + const secondObserved = promptHost(secondPrompt); + await change(() => { + controller.handleTerminalOutput(first, firstPrompt); + controller.handleTerminalOutput(second, secondPrompt); + }); + // Do not call the title resolver for expectations: names come from the + // saved host entities; dynamic hostnames come from the prompt parser. + const recordGroup = (scenario: string, firstName: string, secondName: string) => { + record(scenario, first, firstName); + record(scenario, second, secondName); + record(scenario, "auto", `${firstName} +1`); + record(scenario, "generated", `${firstName}/${secondName}`); + record(scenario, "explicit", "My Cluster"); + }; + for (const mode of [undefined, "off", "agent", "all"] as const) { + await change(() => setMode(mode)); + recordGroup(`ordinary SSH mode=${mode ?? "default"}`, + mode === "all" ? firstObserved : hosts[0].label, + mode === "all" ? secondObserved : hosts[1].label); + } + const updatedPrompt = "[fixture@production-next ~]# "; + const parentRendersBefore = fixtureRenderCount; + // This action deliberately bypasses change(), setRevision and flushSync: + // only the production store subscriptions may update these mounted tabs. + await waitForTitleMutation(first, () => controller.handleTerminalOutput(first, `\r\n${updatedPrompt}`)); + const promptOnlyParentRenders = fixtureRenderCount - parentRendersBefore; + recordGroup("all-mode prompt-only store subscription", promptHost(updatedPrompt), secondObserved); + const agentTitle = "claude: deploy"; + await change(() => { + state.updateSessionCodingCliProvider(first, "claude"); + state.updateSessionDynamicTitle(first, agentTitle); + }); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + recordGroup(`Agent title mode=${mode}`, mode === "off" ? hosts[0].label : agentTitle, + mode === "all" ? secondObserved : hosts[1].label); + } + const manualName = "Manual production"; + await change(() => state.submitSessionRename(first, manualName)); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + const renamed = state.sessions.find(session => session.id === first); + if (!renamed?.customName) throw new Error("Production rename hook did not set customName"); + recordGroup(`manual title mode=${mode}`, renamed.customName, + mode === "all" ? secondObserved : hosts[1].label); + } + await change(() => { jump = state.connectToHost(hosts[2]); setMode("all"); }); + await change(() => state.updateSessionStatus(jump, "connected")); + const targetPrompt = "[fixture@app-target ~]# "; + const targetObserved = promptHost(targetPrompt); + await change(() => controller.handleTerminalOutput(jump, targetPrompt)); + record("JumpServer first output is target", jump, targetObserved); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + record(`JumpServer direct target mode=${mode}`, jump, mode === "all" ? targetObserved : hosts[2].label); + } + for (const menu of ["Opt> ", "[Host]> ", "\x1b[32mOpt> \x1b[0m"]) { + await change(() => controller.handleTerminalOutput(jump, `\r\nlogout\r\n${menu}`)); + record(`JumpServer return to menu ${JSON.stringify(menu)}`, jump, hosts[2].label); + await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`)); + record("JumpServer re-enter target", jump, targetObserved); + } + await change(() => controller.handleTerminalOutput(jump, "\r\nOpt> ")); + await change(() => state.updateSessionStatus(jump, "disconnected")); + await change(() => { state.updateSessionStatus(jump, "connecting"); setMode("off"); }); + record("same-session reconnect preserves saved name in off", jump, hosts[2].label); + await change(() => { state.updateSessionStatus(jump, "connected"); setMode("all"); }); + await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`)); + record("first target after reconnect is observed again", jump, targetObserved); + return { rows, promptOnlyParentRenders }; + } finally { + flushSync(() => root.unmount()); + for (const id of [first, second, jump]) { + if (id) { controller.forgetSession(id); sessionPresentationStore.clearSession(id); } + } + } +} diff --git a/scripts/generate-plugin-contract.mjs b/scripts/generate-plugin-contract.mjs index 2f8922ce5..cb7c78f06 100644 --- a/scripts/generate-plugin-contract.mjs +++ b/scripts/generate-plugin-contract.mjs @@ -22,7 +22,7 @@ const electronBundlePath = path.join( ); const checkOnly = process.argv.includes("--check"); const typescriptTypeOverrides = new Map([ - ["PermissionDeclaration", 'Exclude | PermissionResourceDeclaration'], + ["PermissionDeclaration", "PluginPermission | PermissionResourceDeclaration"], [ "ActivationEvent", '"onStartupFinished" | `onCommand:${ContributionId}` | `onView:${ContributionId}` | `onProvider:${ContributionId}`', diff --git a/scripts/ssh-tab-title-policy.live.test.cjs b/scripts/ssh-tab-title-policy.live.test.cjs new file mode 100644 index 000000000..481458b65 --- /dev/null +++ b/scripts/ssh-tab-title-policy.live.test.cjs @@ -0,0 +1,125 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const esbuild = require("esbuild"); +const root = path.resolve(__dirname, ".."); + +function launchFromNode() { + const { spawnSync } = require("node:child_process"); + const { applyElectronLaunchEnv } = require("../electron/launchEnv.cjs"); + const temp = require("../electron/bridges/tempDirBridge.cjs"); + const prefix = `${temp.getTempFilePath("ssh-tab-title-policy")}-`; + const userData = fs.mkdtempSync(prefix); + let code = 1; + try { + const result = spawnSync(require("electron"), [__filename], { + cwd: root, stdio: "inherit", timeout: 65_000, + env: { ...applyElectronLaunchEnv(process.env), NETCATTY_SSH_TITLE_USER_DATA: userData }, + }); + if (result.error) throw result.error; + code = result.status ?? 1; + } finally { + // Chromium owns profile files until the child exits, especially on Windows. + const target = path.resolve(userData); + console.log("SSH_TAB_TITLE_CLEANUP", target); + assert.equal(path.dirname(target), path.dirname(path.resolve(prefix))); + assert.ok(path.basename(target).startsWith(path.basename(prefix))); + const stat = fs.lstatSync(target); + assert.ok(stat.isDirectory() && !stat.isSymbolicLink()); + fs.rmSync(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + process.exit(code); +} + +function fixtureResponse(request) { + const url = new URL(request.url); + if (url.hostname !== "fixture") return new Response("Not found", { status: 404 }); + if (url.pathname === "/index.html") return new Response("
", { + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + let pathname; + try { pathname = decodeURIComponent(url.pathname); } catch { + return new Response("Invalid resource path", { status: 400 }); + } + const publicRoot = path.join(root, "public"); + const file = path.resolve(publicRoot, `.${pathname}`); + const relative = path.relative(publicRoot, file); + if (relative.startsWith("..") || path.isAbsolute(relative)) return new Response("Not found", { status: 404 }); + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return new Response("Not found", { status: 404 }); + const mime = { + ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", + ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", + }[path.extname(file)] ?? "application/octet-stream"; + return new Response(fs.readFileSync(file), { headers: { "Content-Type": mime } }); +} + +function runInElectron() { + const { app, BrowserWindow, protocol } = require("electron"); + assert.ok(process.env.NETCATTY_SSH_TITLE_USER_DATA, + "Launch with node scripts/ssh-tab-title-policy.live.test.cjs so profile cleanup runs after Electron exits."); + protocol.registerSchemesAsPrivileged([{ + scheme: "ssh-title-test", privileges: { standard: true, secure: true, supportFetchAPI: true }, + }]); + app.setPath("userData", process.env.NETCATTY_SSH_TITLE_USER_DATA); + app.on("window-all-closed", () => {}); + let win; + let finished = false; + const finish = code => { + if (finished) return; + finished = true; + clearTimeout(watchdog); + win?.destroy(); + app.exit(code); + }; + const watchdog = setTimeout(() => { + console.error("SSH_TAB_TITLE_FAILED: real component verification exceeded 60 seconds"); + finish(1); + }, 60_000); + + void app.whenReady().then(async () => { + const bundle = esbuild.buildSync({ + entryPoints: [path.join(__dirname, "fixtures/ssh-tab-title-policy.tsx")], + bundle: true, format: "cjs", platform: "browser", write: false, + alias: { + "node:diagnostics_channel": path.join(root, "infrastructure/shims/nodeDiagnosticsChannel.ts"), + "diagnostics_channel": path.join(root, "infrastructure/shims/nodeDiagnosticsChannel.ts"), + }, + define: { + "import.meta.env.DEV": "false", "import.meta.env.PROD": "true", "import.meta": "{}", + "process.env.NODE_ENV": '"production"', + }, + }).outputFiles[0].text; + win = new BrowserWindow({ + show: process.env.NETCATTY_SSH_TITLE_SHOW_WINDOW === "1", width: 1280, height: 800, + webPreferences: { contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }, + }); + const consoleErrors = []; + win.webContents.on("console-message", details => { + if (details.level === "error") consoleErrors.push(details.message); + }); + protocol.handle("ssh-title-test", fixtureResponse); + await win.loadURL("ssh-title-test://fixture/index.html"); + const { rows, promptOnlyParentRenders } = await win.webContents.executeJavaScript(`(async () => { + const loaded = { exports: {} }; + ((module, exports) => { ${bundle} })(loaded, loaded.exports); + return loaded.exports.runSshTabTitlePolicy(); + })()`); + assert.ok(rows.length > 0, "The real component fixture must produce assertions"); + for (const row of rows) { + assert.equal(row.actual, row.expected, `${row.scenario}; production tab=${row.tabId}`); + } + console.log("SSH_TAB_TITLE_BROWSER_CONSOLE_ERRORS", JSON.stringify(consoleErrors)); + assert.equal(consoleErrors.length, 0, "The real production components must not log browser errors"); + assert.equal(promptOnlyParentRenders, 0, "Prompt-only store updates must not force the fixture parent to render"); + console.log("SSH_TAB_TITLE_POLICY_OK", JSON.stringify({ assertions: rows.length, consoleErrors: consoleErrors.length, promptOnlyParentRenders })); + finish(0); + }).catch(error => { + console.error("SSH_TAB_TITLE_POLICY_FAILED", error); + finish(1); + }); +} + +if (process.versions.electron) runInElectron(); +else launchFromNode(); diff --git a/skills/netcatty-mcp/SKILL.md b/skills/netcatty-mcp/SKILL.md index 139085d30..0e8488acd 100644 --- a/skills/netcatty-mcp/SKILL.md +++ b/skills/netcatty-mcp/SKILL.md @@ -14,6 +14,6 @@ Use the Netcatty MCP tools whenever the task targets Netcatty or a remote sessio - If a required specialized tool is not visible, call `load_netcatty_tools` with `terminal_bulk`, `sessions`, `attachments`, `sftp_advanced`, `vault_hosts`, `vault_notes`, `snippets`, `scripts`, or `portforward`. Use `all` only when several categories are needed. - For disconnected sessions already in scope, load `sessions` and use `session_reconnect` / `session_recover` instead of `host_open`, which creates a new tab. - If no live session matches, use `vault_hosts_list` and `host_open`. A newly opened tab lands in your own bound workspace by default (workspace chat → that workspace; terminal chat → that terminal's workspace); only pass `workspaceId` when the user asks for a different target. Close only sessions opened for the current task when they are no longer needed. -- To run the same short command on 2-20 sessions at once, load `terminal_bulk` and use `terminal_execute_bulk` (all-or-nothing: if any session id is invalid, nothing runs). For one session use `terminal_execute`. +- For the same command on 2-20 sessions, load `terminal_bulk`: `terminal_execute_bulk` for short commands (all-or-nothing: if any session id is invalid, nothing runs), or `terminal_start_bulk`, then `terminal_poll_bulk` / `terminal_stop_bulk` with its `bulkId`, for long-running ones. - Use `terminal_execute` for short commands. Use `terminal_start`, `terminal_poll`, and `terminal_stop` for long-running or streaming commands. - Treat Netcatty permission denials and tool errors as authoritative. Do not bypass them with local commands or alternate connection tools. diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 768461174..7a2e4d340 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -253,7 +253,7 @@ declare global { }, ): Promise<{ success: boolean; cwd?: string; error?: string; directoryState?: { revision: number; - shellKind: 'powershell' | 'cmd'; + shellKind: 'powershell' | 'cmd' | 'git-bash'; pathFlavor: 'win32'; provider: string; cwd: string | null; diff --git a/types/global/netcatty-bridge-sync.d.ts b/types/global/netcatty-bridge-sync.d.ts index 0306b4e6c..86953de56 100644 --- a/types/global/netcatty-bridge-sync.d.ts +++ b/types/global/netcatty-bridge-sync.d.ts @@ -310,8 +310,9 @@ declare global { onLanguageChanged?(cb: (language: string) => void): () => void; // Chain progress listener for jump host connections - // Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string) - onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void): () => void; + // Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string, address?: string) + // `address` is the current hop's host:port, so the UI can show the hop being connected. + onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void): () => void; // Fired when a requested SSH connection reuse cannot be honored and the // session falls back to a regular fresh connection.