Compare commits

...
Author SHA1 Message Date
bincxz e4fc53763a feat(sftp): add setting for tree view folder double-click behavior (#4424) 2026-11-26 23:24:13 +08:00
Joseph Hauandbincxz d557a05ac2 feat: support Git Bash in the terminal directory picker (#4407)
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-26 23:02:34 +08:00
Radwan Seloandbincxz 42311e62ab feat(capabilities): add terminal_start_bulk, terminal_poll_bulk and terminal_stop_bulk (#4423)
* feat(capabilities): add terminal_start_bulk, terminal_poll_bulk and terminal_stop_bulk

Background jobs on 2-20 terminal sessions at once, in the terminal_bulk
MCP toolset next to terminal_execute_bulk (MCP-only).

- terminal_start_bulk: the same all-or-nothing preflight as
  terminal_execute_bulk plus terminal_start's refusals, one fresh
  approval listing every host, then one background job per session.
  Returns a bulkId and a jobId per host.
- terminal_poll_bulk: polls every job of a bulkId (or a jobIds list)
  with per-job offsets. Output is capped at 4 KB per job and 32 KB in
  total, shared by need; when a job has more, the newest output is
  returned with skippedChars. Per-job problems never fail the call.
- terminal_stop_bulk: stops every job, no approval, like terminal_stop.
- The terminal worker's job start gets a no-send precheck mode, and
  the main process gets preflightJobStart, so worker-hosted and
  main-process sessions are validated before any job starts.
- Shared bulk target checks are extracted from execBulk.cjs.

* docs(skill): describe all terminal_bulk tools in one line

Merge the terminal_execute_bulk and terminal_start_bulk lines so the skill
names every bulk tool once, like the toolset groups them. The next line
already covers single-session commands.

* fix(mcp): let observer-bypassing write tools through the MCP tool registry

The generic MCP handler ran the observer write guard for every write tool,
ignoring the catalog's bypassesObserverBlock. terminal_stop and session_close
have their own handlers, but terminal_stop_bulk did not, so MCP clients could
not stop bulk jobs in observer mode. Skip the guard for tools that declare
the bypass; the bridge enforces the same policy again.

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-26 23:00:33 +08:00
GOUKI9999andbincxz 883313f483 fix(ui): keep per-pane close button visible at narrow widths (#4448)
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-26 22:51:40 +08:00
陈大猫 1d6c9fc693 fix(terminal): sync vaultInitialized with VaultHost props to avoid stale key boot (#4428) (#4458) 2026-11-26 22:40:50 +08:00
Radwan Selo 7b36f574f4 fix(mcp): tighten terminal_execute_bulk text and output budget, drop the lone toolset hint (#4425)
- terminal_execute_bulk description: drop the sentence that repeated the
  summary, and stop promising a separate stderr. On interactive terminals
  stderr is part of stdout, so the field is almost always empty.
- terminal_execute_bulk output: stdout and stderr shared each group's
  budget as a fixed 75%/25% split, so with empty stderr a quarter was
  never used and stdout was cut early. Apply tailLines first, then give
  each stream's unused share to the other. The per-group cap is unchanged.
- load_netcatty_tools: terminal_bulk was the only toolset with a hint.
  Remove it so every toolset is listed the same way, and test that the
  description names every toolset.
2026-11-26 22:32:45 +08:00
陈大猫 6e6e22460d fix(hotkeys): keep custom Open Local Terminal shortcuts ahead of Reopen Closed Tab (#4414)
* fix(hotkeys): keep custom Open Local Terminal shortcuts ahead of the new Reopen Closed Tab default

Fixes #4411

* fix(hotkeys): evict conflicting default shortcuts only within the same input context
2026-11-26 22:32:41 +08:00
Radwan Selo 5360385c41 fix(vault): normalize the vault_hosts_list group filter and explain empty group results (#4418)
* fix(vault): normalize the vault_hosts_list group filter and explain empty group results

The group filter only trimmed whitespace and trailing slashes, while saved
group paths are normalized (backslashes to "/", segments trimmed, empty
segments dropped). A filter like "/prod", "prod / web", "prod\web" or
"prod//db" silently returned no hosts.

- Normalize the filter with normalizeGroupTargetPath, the same rules used
  for saved groups. "/" still means no filter.
- When the group filter alone leaves the list empty, add a note so an
  agent can tell a mistyped group from an empty one: a case-only mismatch
  suggests the right name, an unknown group points to vault_groups_list,
  and a known group without hosts says so. Results with hosts, and empty
  results caused by the query, are unchanged.

* fix(vault): normalize stored host group paths in the vault_hosts_list group filter

Host Details saves a typed group verbatim apart from outer whitespace, so
hosts can carry noncanonical paths such as "prod / web" or "prod//db".
Normalizing only the filter made an exact match on such a value return no
hosts and report that the group exists but is empty. Normalize the stored
path the same way before comparing, so the exact stored value, its
canonical spelling, and parent filters all find the host.

* fix(vault): list known group names in the unknown-group note

vault_groups_list returns only saved groups, so pointing to it dead-ended
for groups that exist only through host paths. List the known group names
(saved groups and host paths, capped at 20) in the note instead.
2026-11-26 22:32:36 +08:00
陈大猫 cde4274041 fix(terminal): keep compose bar cwd label across command submit (#4422) 2026-11-26 22:32:32 +08:00
陈大猫 444b360727 fix(vault): restore Host Details inheritance (#4441) (#4447)
* fix(vault): restore Host Details inheritance (#4441)

* fix(vault): keep Mosh/ET exclusive when restoring group transport
2026-11-26 22:32:28 +08:00
GOUKI9999andbincxz bbbea4a157 fix(ai): allow dismissing the model catalog warning banner (#4431)
* fix(ai): allow dismissing the model catalog warning banner

* fix(ai): address Codex review on catalog warning dismissal

* fix(ai): persist catalog warning dismissals across empty-panel remounts

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-26 22:32:23 +08:00
陈大猫andCodex 1009f131fe fix(ui): use a 1px continuous stroke for magnified pane chrome (#4168) (#4452)
Co-authored-by: Codex <codex@openai.com>
2026-11-26 22:25:32 +08:00
Radwan Selo 6236f5bb95 fix(mcp): keep host and group proxy updates consistent with Host Details (#4443)
* fix(mcp): keep vault_hosts_update proxy changes consistent with Host Details

- Selecting a proxy profile now removes an explicit direct choice, so the
  host actually connects through the selected proxy instead of staying direct.
- Clearing with an empty proxyProfileId now removes every host proxy setting
  (as the Host Details remove button does) instead of storing "". The stored
  "" made Host Details show no proxy and skipped a group's one-off proxy.
- Correct the proxyProfileId description: an empty value inherits the group
  or global default proxy rather than clearing it.

* fix(mcp): clearing a group proxy lets the parent group proxy apply

vault_groups_update stored proxyProfileId "" on the group. resolveGroupDefaults
treats that as a group value, so it dropped the parent group's proxy and
hosts in the child group fell back to the global default or no proxy.
Group Details removes the keys instead; do the same.
2026-11-26 21:23:51 +08:00
陈大猫andCodex db433c4c19 fix(terminal): keep magnified pane chrome through the shrink animation (#4335) (#4450)
Co-authored-by: Codex <codex@openai.com>
2026-11-26 20:47:31 +08:00
陈大猫 93c74cb068 feat(plugins): add workbench shortcut forwarding, DataGrid FK jump & keyboard parity, and ER canvas polish (#4451) 2026-11-26 19:21:11 +08:00
Imzl-zl a0f7a376db fix(tabs): respect configured SSH names and dynamic title modes (#4409)
Fixes #4432
Fixes #4436
2026-11-26 18:52:09 +08:00
陈大猫 1595d2ed62 style(plugins): apply immersive overlay scrollbars to plugin surfaces and data grid (#4438) 2026-11-26 18:03:26 +08:00
陈大猫 f4a087e890 feat(plugins): add host-rendered IDE primitives, STARTTLS/SSH bindings, file/secret APIs, and pooled image rasterizer (#4437)
- Add host-rendered native IDE primitives (PluginCodeEditor/Monaco, PluginDataGrid/@tanstack/react-virtual, PluginSplitPane, PluginErCanvas) with Shadow DOM slot projection (zero iframes, zero plugin JS in renderer)
- Expand Remote DOM budgets, expose full 22 Netcatty semantic CSS tokens, add dblclick/contextmenu/scroll/selection events, cursor-anchored PluginPopover, database theme icon, and full-bleed chrome flag
- Add dynamic user-approved TCP/TLS byte streams (incl. localhost opt-in blocking internal control ports), in-band STARTTLS upgrade with cert fingerprint confirmation, durable revocable Vault SSH host bindings, plugin-owned encrypted secrets, native ui.openFile/saveFile streaming handles, 4 MiB clipboard, and prefix-filtered storage.keys
- Optimize plugin view image pipeline with pooled sandboxed rasterizer window (auto-destroyed on idle/error/dispose), LRU version+hash cache in PluginViewResources, transient failure eviction in HostDrawnViewHost, renderer-side session deduplication, and RemoteImageElement cache + retry
- Temporarily enable plugin host by default in hostBootstrap.cjs (marked TODO(revert), opt-out via NETCATTY_PLUGIN_DEV=0)
2026-11-26 17:52:27 +08:00
陈大猫 ac8869884f fix(vault): normalize Host Details group paths only when the group changes (#4427)
* fix(vault): normalize changed Host Details group paths

Preserve unchanged legacy group paths to avoid changing connection defaults.

Fixes #4426

* fix(vault): normalize explicitly selected trimmed group paths

Related #4426
2026-11-26 15:59:12 +08:00
陈大猫 d556e5c5de fix(mcp): recognize short decorative tokens before idle prompts (#4420)
Leading theme glyphs such as ⚡ made the POSIX and Powerline idle-prompt
whitelists miss, so terminal_execute waited out the default 30s probe and
returned SHELL_READINESS_UNKNOWN. Strip a 1-4 character decorative prefix
for recognition only; keep the original prompt text for suffix matching.

Related #4354
2026-11-26 13:21:06 +08:00
Radwan Selo 3026be2dc9 fix(ssh): show the target's label and each hop's address in chain progress (#4413)
When connecting through "Proxy via Hosts", the connection dialog named
jump hops by their label but the final target by its raw address
("Chain 2 of 2: 192.168.1.10"), and the address line under the heading
always showed the target's address, whichever hop was connecting
("Chain 1 of 3: Bastion A" above "SSH 192.168.1.10:22"). Longer chains
made this more confusing.

- Name the final hop by its vault label (falling back to its address
  when unlabeled). Direct connections are unchanged.
- Send each hop's host:port with chain progress events and show it
  under the heading for jump hops; the final hop keeps the target's
  protocol-aware address line (Mosh/ET ports).
- Applies to terminal sessions and the host "Test connection" dialog.
- Share the host:port formatting for chain hops in chainProgress.cjs.
2026-11-26 12:29:30 +08:00
Netcatty-Bot 883fdaf114 Update Nix release metadata for v1.1.91 (#4404) 2026-11-26 00:31:31 +08:00
陈大猫 9a49ac33bf feat(sftp): add default download folder setting (#4353) (#4392) 2026-11-25 22:18:12 +08:00
218 changed files with 13911 additions and 702 deletions

No files matched your search

+1 -1
View File
@@ -100,7 +100,7 @@ Placement rules (`resolveAgentKinds` in `toolSurfaces.cjs`):
| Vault bridge | `electron/bridges/aiBridge/vaultAgentBridge.cjs` + `infrastructure/ai/vaultAgentBridgeClient.ts` | Renderer vault state; **never** returns password/privateKey |
| AI context | `buildAITerminalSessionInfo` + `useTerminalAiContexts` | Per-session `hostChain` + `activePortForwards`; mirrored in `getContext` and Catty system prompt |
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes. `terminal_execute_bulk` (2–20 sessions, loaded via the `terminal_bulk` toolset) is all-or-nothing before sending and sets `policy.requiresFreshApproval`: remembered grants and external-client session approval never satisfy it. See `docs/features/terminal-execute-bulk.md`.
**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`.
+20
View File
@@ -331,6 +331,26 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
if (binding.category === 'sftp') {
continue;
}
if (binding.action === 'commandPalette') {
const hasOpenHostModal = Array.from(
document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]:not([data-plugin-dialog])'),
).some((el) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (!hasOpenHostModal) {
const inPluginSurface = Boolean(target?.closest?.('[data-plugin-remote-surface]'));
const activeFullBleedSurface = inPluginSurface || Array.from(
document.querySelectorAll<HTMLElement>('[data-plugin-chrome="full-bleed"] [data-plugin-remote-surface]'),
).some((el) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (activeFullBleedSurface) {
return;
}
}
}
if (TERMINAL_PASSTHROUGH_ACTIONS.has(binding.action)) {
if (isTerminalElement) {
return;
+2 -1
View File
@@ -281,7 +281,7 @@ function AppViewInner({ domains }: AppViewProps) {
handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit,
handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect,
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions,
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
@@ -734,6 +734,7 @@ function AppViewInner({ domains }: AppViewProps) {
/>
<TerminalLayerMount
isVaultInitialized={isVaultInitialized}
hosts={terminalHosts}
portForwardingRules={portForwardingRules}
customGroups={customGroups}
+2
View File
@@ -55,6 +55,7 @@ export function VaultHost() {
hosts: vault.hosts,
identities: vault.identities,
importOrReuseKey: actions?.importOrReuseKey,
isVaultInitialized: vault.isVaultInitialized,
keys: vault.keys,
managedSources: vault.managedSources,
navigateToSection: local.navigateToSection,
@@ -90,6 +91,7 @@ export function VaultHost() {
vault.groupConfigs,
vault.hosts,
vault.identities,
vault.isVaultInitialized,
vault.keys,
vault.managedSources,
vault.proxyProfiles,
@@ -0,0 +1,233 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import React, { useEffect, useLayoutEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import {
EMPTY_VAULT_SNAPSHOT,
publishVaultSnapshot,
useVaultSnapshot,
useVaultSnapshotField,
} from '../state/vaultSnapshotStore.ts';
import {
publishAppShellDomainSlice,
useAppShellProps,
} from './appShellPropsStore.ts';
import { registerAppHandlers } from './appHandlersBridge.ts';
import { resolveTerminalVaultInitialized } from '../../components/terminal/restoredSessionGate.ts';
import { terminalLayerAreEqual } from '../../components/terminalLayerMemo.ts';
import {
terminalLayerViewCtxEqual,
terminalLayerWorkspaceCtxEqual,
} from '../../components/terminalLayer/terminalLayerViewMemo.ts';
import type { Host, Identity, SSHKey } from '../../domain/models.ts';
const storageBacking = new Map<string, string>();
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (key: string) => storageBacking.get(key) ?? null,
setItem: (key: string, value: string) => {
storageBacking.set(key, value);
},
removeItem: (key: string) => {
storageBacking.delete(key);
},
clear: () => {
storageBacking.clear();
},
},
});
const { VaultHost } = await import('./hosts/VaultHost.tsx');
test('VaultHost keeps isVaultInitialized synchronized with hydrated hosts, keys, and identities for Terminal boot (#4428)', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
(globalThis as Record<string, unknown>).window = dom.window;
(globalThis as Record<string, unknown>).document = dom.window.document;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
const host: Host = {
id: 'host-1',
label: 'test-myhost',
hostname: '10.243.2.249',
port: 22,
username: 'user1',
authMethod: 'key',
identityFileId: 'key-1',
tags: [],
createdAt: 0,
};
const key: SSHKey = {
id: 'key-1',
label: 'Imported Key',
type: 'ED25519',
privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----',
publicKey: 'ssh-ed25519 AAAA test',
passphrase: 'secret',
source: 'imported',
category: 'key',
created: 0,
};
const identity: Identity = {
id: 'id-1',
label: 'User Identity',
username: 'user1',
authMethod: 'key',
keyId: 'key-1',
createdAt: 0,
};
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
registerAppHandlers({} as never);
// Mirror TerminalHost's layout-effect slice publication order (sibling after VaultHost).
function TerminalHostMirror() {
const vault = useVaultSnapshot();
useLayoutEffect(() => {
publishAppShellDomainSlice('terminal', { terminalHosts: vault.hosts });
}, [vault.hosts]);
return null;
}
const syncedBoots: Array<{
hostCount: number;
keyCount: number;
identityCount: number;
hasPrivateKey: boolean;
}> = [];
function SyncedTerminal({
vaultInitializedOverride,
hosts,
keys,
identities,
}: {
vaultInitializedOverride: boolean;
hosts: readonly Host[];
keys: readonly SSHKey[];
identities: readonly Identity[];
}) {
const sharedVaultInitialized = useVaultSnapshotField('isVaultInitialized');
const vaultInitialized = resolveTerminalVaultInitialized(
sharedVaultInitialized,
vaultInitializedOverride,
);
useEffect(() => {
if (!vaultInitialized) return;
syncedBoots.push({
hostCount: hosts.length,
keyCount: keys.length,
identityCount: identities.length,
hasPrivateKey: Boolean(keys[0]?.privateKey),
});
// Intentionally matches useTerminalEffects' boot effect dep shape (gated on vaultInitialized, not keys).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vaultInitialized]);
return null;
}
function ShellHarness() {
const { domains } = useAppShellProps();
const vaultDomain = domains?.vault as
| { isVaultInitialized?: boolean; keys?: readonly SSHKey[]; identities?: readonly Identity[] }
| undefined;
const terminalDomain = domains?.terminal as
| { terminalHosts?: readonly Host[] }
| undefined;
return React.createElement(
React.Fragment,
null,
React.createElement(VaultHost),
React.createElement(TerminalHostMirror),
vaultDomain && terminalDomain
? React.createElement(SyncedTerminal, {
vaultInitializedOverride: vaultDomain.isVaultInitialized ?? false,
hosts: terminalDomain.terminalHosts ?? [],
keys: vaultDomain.keys ?? [],
identities: vaultDomain.identities ?? [],
})
: null,
);
}
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await React.act(async () => {
root.render(React.createElement(ShellHarness));
});
assert.equal(syncedBoots.length, 0, 'restored terminal must not boot before vault hydration');
// Publish hydrated hosts, keys, identities, and isVaultInitialized together.
await React.act(async () => {
publishVaultSnapshot({
...EMPTY_VAULT_SNAPSHOT,
isVaultInitialized: true,
hosts: [host],
keys: [key],
identities: [identity],
});
});
assert.deepEqual(syncedBoots, [
{
hostCount: 1,
keyCount: 1,
identityCount: 1,
hasPrivateKey: true,
},
]);
} finally {
await React.act(async () => {
root.unmount();
});
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
registerAppHandlers(null);
(globalThis as Record<string, unknown>).window = prevWindow;
(globalThis as Record<string, unknown>).document = prevDocument;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
}
});
test('terminal layer memo comparators propagate isVaultInitialized changes', () => {
const baseLayerProps = {
isVaultInitialized: false,
hosts: [],
sessions: [],
};
assert.equal(
terminalLayerAreEqual(baseLayerProps, { ...baseLayerProps, isVaultInitialized: true }),
false,
);
assert.equal(
terminalLayerWorkspaceCtxEqual(
{ isVaultInitialized: false },
{ isVaultInitialized: true },
),
false,
);
assert.equal(
terminalLayerViewCtxEqual(
{ isVaultInitialized: false },
{ isVaultInitialized: true },
),
false,
);
const appViewSource = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8');
const supportSource = readFileSync(
new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url),
'utf8',
);
assert.match(appViewSource, /<TerminalLayerMount[\s\S]*?isVaultInitialized=\{isVaultInitialized\}/);
assert.match(supportSource, /vaultInitializedOverride=\{isVaultInitialized\}/);
});
+1
View File
@@ -98,6 +98,7 @@ export const enCoreMessages: Messages = {
'common.apply': 'Apply',
'common.use': 'Use',
'common.useGlobal': 'Use global',
'common.useGroup': 'Use group',
'common.saveChanges': 'Save Changes',
'common.advanced': 'Advanced',
'common.left': 'Left',
+1
View File
@@ -14,6 +14,7 @@ export const enTerminalMessages: Messages = {
'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.',
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
'terminal.directory.busy': 'Wait for an empty shell prompt.',
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
+11
View File
@@ -584,6 +584,10 @@ export const enVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Display files in a flat list for the current directory',
'settings.sftp.defaultViewMode.tree': 'Tree View',
'settings.sftp.defaultViewMode.treeDesc': 'Display files in a hierarchical tree structure',
'settings.sftp.treeFolderDoubleClick': 'Tree view folder double-click',
'settings.sftp.treeFolderDoubleClick.desc': 'Choose what happens when double-clicking a folder in SFTP Tree View. Clicking the chevron always expands or collapses in place.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Enter directory',
'settings.sftp.treeFolderDoubleClick.expand': 'Expand or collapse in place',
'sftp.autoSync.success': 'File synced to remote: {fileName}',
'sftp.autoSync.error': 'Failed to sync file: {error}',
@@ -619,6 +623,13 @@ export const enVaultMessages: Messages = {
'settings.sftp.packedDownload': 'Packed downloads',
'settings.sftp.packedDownload.enable': 'Pack folders and multiple items for download',
'settings.sftp.packedDownload.enableDesc': 'Download the selection in one stream and restore its original layout on this device. If the server cannot pack it, download files individually.',
'settings.sftp.downloadLocation': 'Download location',
'settings.sftp.downloadLocation.directory': 'Default download folder',
'settings.sftp.downloadLocation.directoryDesc': 'SFTP download dialogs open in this folder. If it is not set or no longer exists, the system Downloads folder is used.',
'settings.sftp.downloadLocation.systemDefault': 'System Downloads folder',
'settings.sftp.downloadLocation.browse': 'Browse…',
'settings.sftp.downloadLocation.reset': 'Use the system Downloads folder',
'settings.sftp.downloadLocation.select': 'Choose default download folder',
'settings.sftp.skipUnchanged.enable': 'Skip unchanged files',
'settings.sftp.skipUnchanged.enableDesc': 'Skip files whose size and modification time already match the destination (rsync-style). Disabled when replacing a folder into a staging path.',
+1
View File
@@ -98,6 +98,7 @@ export const esCoreMessages: Messages = {
'common.apply': 'Aplicar',
'common.use': 'Usar',
'common.useGlobal': 'Usar global',
'common.useGroup': 'Usar grupo',
'common.saveChanges': 'Guardar cambios',
'common.advanced': 'Avanzado',
'common.left': 'Izquierda',
+1
View File
@@ -14,6 +14,7 @@ export const esTerminalMessages: Messages = {
'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.',
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
+11
View File
@@ -584,6 +584,10 @@ export const esVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Muestra los archivos en una lista plana del directorio actual',
'settings.sftp.defaultViewMode.tree': 'Vista de árbol',
'settings.sftp.defaultViewMode.treeDesc': 'Muestra los archivos en una estructura de árbol jerárquica',
'settings.sftp.treeFolderDoubleClick': 'Doble clic en carpetas (vista de árbol)',
'settings.sftp.treeFolderDoubleClick.desc': 'Elige qué ocurre al hacer doble clic en una carpeta en la vista de árbol de SFTP. Hacer clic en la flecha siempre expande o contrae en su lugar.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Entrar en el directorio',
'settings.sftp.treeFolderDoubleClick.expand': 'Expandir o contraer en su lugar',
'sftp.autoSync.success': 'Archivo sincronizado con el remoto: {fileName}',
'sftp.autoSync.error': 'No se pudo sincronizar el archivo: {error}',
@@ -619,6 +623,13 @@ export const esVaultMessages: Messages = {
'settings.sftp.packedDownload': 'Descargas empaquetadas',
'settings.sftp.packedDownload.enable': 'Empaquetar carpetas y selecciones múltiples para descargar',
'settings.sftp.packedDownload.enableDesc': 'Descarga la selección en una sola transferencia y restaura su estructura original en este dispositivo. Si el servidor no puede empaquetarla, los archivos se descargan por separado.',
'settings.sftp.downloadLocation': 'Ubicación de descarga',
'settings.sftp.downloadLocation.directory': 'Carpeta de descarga predeterminada',
'settings.sftp.downloadLocation.directoryDesc': 'Los diálogos de descarga SFTP se abren en esta carpeta. Si no está configurada o ya no existe, se usa la carpeta Descargas del sistema.',
'settings.sftp.downloadLocation.systemDefault': 'Carpeta Descargas del sistema',
'settings.sftp.downloadLocation.browse': 'Examinar…',
'settings.sftp.downloadLocation.reset': 'Usar la carpeta Descargas del sistema',
'settings.sftp.downloadLocation.select': 'Elegir la carpeta de descarga predeterminada',
'settings.sftp.skipUnchanged.enable': 'Omitir archivos sin cambios',
'settings.sftp.skipUnchanged.enableDesc': 'Omite los archivos cuyo tamaño y hora de modificación ya coinciden con el destino (estilo rsync). Deshabilitado al reemplazar una carpeta en una ruta de staging.',
+1
View File
@@ -71,6 +71,7 @@ export const ruCoreMessages: Messages = {
'common.apply': 'Применить',
'common.use': 'Использовать',
'common.useGlobal': 'Использовать глобальное',
'common.useGroup': 'Использовать настройки группы',
'common.saveChanges': 'Сохранить изменения',
'common.advanced': 'Дополнительно',
'common.left': 'Слева',
+1
View File
@@ -14,6 +14,7 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.',
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
+11
View File
@@ -627,6 +627,10 @@ export const ruVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Показывать файлы в виде плоского списка для текущего каталога',
'settings.sftp.defaultViewMode.tree': 'Дерево',
'settings.sftp.defaultViewMode.treeDesc': 'Показывать файлы в иерархической древовидной структуре',
'settings.sftp.treeFolderDoubleClick': 'Двойной щелчок по папке в дереве',
'settings.sftp.treeFolderDoubleClick.desc': 'Выберите действие при двойном щелчке по папке в режиме дерева SFTP. Щелчок по стрелке всегда раскрывает или сворачивает папку на месте.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Перейти в каталог',
'settings.sftp.treeFolderDoubleClick.expand': 'Раскрыть или свернуть на месте',
'sftp.autoSync.success': 'Файл синхронизирован с удалённым сервером: {fileName}',
'sftp.autoSync.error': 'Не удалось синхронизировать файл: {error}',
@@ -662,6 +666,13 @@ export const ruVaultMessages: Messages = {
'settings.sftp.packedDownload': 'Скачивание архивом',
'settings.sftp.packedDownload.enable': 'Упаковывать папки и выбранные вместе файлы перед скачиванием',
'settings.sftp.packedDownload.enableDesc': 'Выбранные файлы передаются одним потоком и распаковываются с сохранением структуры папок. Если сервер не поддерживает упаковку, файлы скачиваются по отдельности.',
'settings.sftp.downloadLocation': 'Папка для загрузок',
'settings.sftp.downloadLocation.directory': 'Папка загрузок по умолчанию',
'settings.sftp.downloadLocation.directoryDesc': 'Диалоги скачивания по SFTP открываются в этой папке. Если она не задана или больше не существует, используется системная папка «Загрузки».',
'settings.sftp.downloadLocation.systemDefault': 'Системная папка «Загрузки»',
'settings.sftp.downloadLocation.browse': 'Обзор…',
'settings.sftp.downloadLocation.reset': 'Использовать системную папку «Загрузки»',
'settings.sftp.downloadLocation.select': 'Выберите папку загрузок по умолчанию',
'settings.sftp.skipUnchanged.enable': 'Пропускать неизменённые файлы',
'settings.sftp.skipUnchanged.enableDesc': 'Пропускать файлы, у которых размер и время изменения уже совпадают с назначением (в стиле rsync). Отключается при замене папки во временный путь.',
@@ -285,3 +285,22 @@ test("localized vault messages include interactive authentication labels", () =>
assert.deepEqual(missing, [], `${locale.name} is missing interactive authentication labels`);
}
});
test("localized settings include SFTP tree folder double-click labels across all locales", () => {
const keys = [
"settings.sftp.treeFolderDoubleClick",
"settings.sftp.treeFolderDoubleClick.desc",
"settings.sftp.treeFolderDoubleClick.navigate",
"settings.sftp.treeFolderDoubleClick.expand",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing SFTP tree folder double-click labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
+1
View File
@@ -89,6 +89,7 @@ export const zhCNCoreMessages: Messages = {
'common.apply': '应用',
'common.use': '使用',
'common.useGlobal': '跟随全局',
'common.useGroup': '跟随分组',
'common.left': '左侧',
'common.right': '右侧',
'common.more': '更多',
@@ -14,6 +14,7 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.unavailable': '此会话暂不支持目录导航。',
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
@@ -190,6 +191,10 @@ export const zhCNTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表显示当前目录的文件',
'settings.sftp.defaultViewMode.tree': '树形视图',
'settings.sftp.defaultViewMode.treeDesc': '以层级树形结构显示文件',
'settings.sftp.treeFolderDoubleClick': '树形视图双击文件夹',
'settings.sftp.treeFolderDoubleClick.desc': '选择在 SFTP 树形视图中双击文件夹时的操作。点击左侧箭头始终在原处展开或折叠。',
'settings.sftp.treeFolderDoubleClick.navigate': '进入目录',
'settings.sftp.treeFolderDoubleClick.expand': '原地展开/折叠',
'sftp.autoSync.success': '文件已同步到远程:{fileName}',
'sftp.autoSync.error': '同步文件失败:{error}',
@@ -225,6 +230,13 @@ export const zhCNTerminalMessages: Messages = {
'settings.sftp.packedDownload': '打包下载',
'settings.sftp.packedDownload.enable': '下载文件夹或多选项目时打包',
'settings.sftp.packedDownload.enableDesc': '将所选内容一次传回,在本地自动还原原有目录结构。服务器不支持打包时,自动逐文件下载。',
'settings.sftp.downloadLocation': '下载位置',
'settings.sftp.downloadLocation.directory': '默认下载文件夹',
'settings.sftp.downloadLocation.directoryDesc': '下载 SFTP 文件时,保存对话框默认打开此文件夹。未设置或文件夹已不存在时,使用系统“下载”文件夹。',
'settings.sftp.downloadLocation.systemDefault': '系统“下载”文件夹',
'settings.sftp.downloadLocation.browse': '浏览…',
'settings.sftp.downloadLocation.reset': '恢复为系统“下载”文件夹',
'settings.sftp.downloadLocation.select': '选择默认下载文件夹',
'settings.sftp.skipUnchanged.enable': '跳过未改文件',
'settings.sftp.skipUnchanged.enableDesc': '当目标文件的大小与修改时间已与源一致时跳过传输(类似 rsync)。替换到暂存路径时自动禁用。',
+1
View File
@@ -89,6 +89,7 @@ export const zhTWCoreMessages: Messages = {
'common.apply': '套用',
'common.use': '使用',
'common.useGlobal': '跟隨全域',
'common.useGroup': '跟隨群組',
'common.left': '左側',
'common.right': '右側',
'common.more': '更多',
@@ -14,6 +14,7 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。',
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -190,6 +191,10 @@ export const zhTWTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表顯示目前目錄的檔案',
'settings.sftp.defaultViewMode.tree': '樹形檢視',
'settings.sftp.defaultViewMode.treeDesc': '以層級樹形結構顯示檔案',
'settings.sftp.treeFolderDoubleClick': '樹形檢視雙擊資料夾',
'settings.sftp.treeFolderDoubleClick.desc': '選擇在 SFTP 樹形檢視中雙擊資料夾時的操作。點選左側箭頭始終在原地展開或摺疊。',
'settings.sftp.treeFolderDoubleClick.navigate': '進入目錄',
'settings.sftp.treeFolderDoubleClick.expand': '原地展開/摺疊',
'sftp.autoSync.success': '檔案已同步到遠端:{fileName}',
'sftp.autoSync.error': '同步檔案失敗:{error}',
@@ -225,6 +230,13 @@ export const zhTWTerminalMessages: Messages = {
'settings.sftp.packedDownload': '打包下載',
'settings.sftp.packedDownload.enable': '下載資料夾或多個項目時打包',
'settings.sftp.packedDownload.enableDesc': '一次傳回所選內容,並在本機自動還原原本的資料夾結構。若伺服器不支援打包,會自動逐檔下載。',
'settings.sftp.downloadLocation': '下載位置',
'settings.sftp.downloadLocation.directory': '預設下載資料夾',
'settings.sftp.downloadLocation.directoryDesc': '下載 SFTP 檔案時,儲存對話框預設開啟此資料夾。未設定或資料夾已不存在時,使用系統「下載」資料夾。',
'settings.sftp.downloadLocation.systemDefault': '系統「下載」資料夾',
'settings.sftp.downloadLocation.browse': '瀏覽…',
'settings.sftp.downloadLocation.reset': '恢復為系統「下載」資料夾',
'settings.sftp.downloadLocation.select': '選擇預設下載資料夾',
'settings.sftp.skipUnchanged.enable': '跳過未改檔案',
'settings.sftp.skipUnchanged.enableDesc': '當目標檔案的大小與修改時間已與來源一致時跳過傳輸(類似 rsync)。替換到暫存路徑時自動停用。',
@@ -7,12 +7,20 @@ test('plugin theme tokens come from the themed app surface style', () => {
assert.deepEqual(selectPluginThemeTokens({
'--background': '220 10% 10%',
'--foreground': '0 0% 98%',
'--card': '220 10% 12%',
'--primary': '210 90% 55%',
'--destructive': '0 84% 60%',
'--radius': '0.5rem',
'--font-mono': '"JetBrains Mono", monospace',
colorScheme: 'dark',
'--unknown-plugin-token': 'ignored',
}), {
'--background': '220 10% 10%',
'--foreground': '0 0% 98%',
'--card': '220 10% 12%',
'--primary': '210 90% 55%',
'--destructive': '0 84% 60%',
'--radius': '0.5rem',
'--font-mono': '"JetBrains Mono", monospace',
});
});
@@ -1,11 +1,26 @@
export const PLUGIN_THEME_TOKEN_NAMES = Object.freeze([
'--background',
'--foreground',
'--muted',
'--muted-foreground',
'--border',
'--card',
'--card-foreground',
'--popover',
'--popover-foreground',
'--primary',
'--primary-foreground',
'--secondary',
'--secondary-foreground',
'--muted',
'--muted-foreground',
'--accent',
'--accent-foreground',
'--destructive',
'--destructive-foreground',
'--border',
'--input',
'--ring',
'--radius',
'--font-sans',
'--font-mono',
] as const);
export function selectPluginThemeTokens(
+14 -5
View File
@@ -38,14 +38,23 @@ export class PluginViewSessions {
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
}).catch(() => dispose(true));
const imageCache = new Map<string, Promise<string>>();
return {
viewId: request.viewId,
scope: request.scopeId,
image: async (path: string) => {
if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable');
const result = await bridge.getPluginViewResource({ instanceId: id, path });
if (disposed) throw new Error('Plugin view closed');
return result.url;
image: (path: string) => {
if (disposed || !bridge.getPluginViewResource) return Promise.reject(new Error('Plugin image unavailable'));
const existing = imageCache.get(path);
if (existing) return existing;
const pending = bridge.getPluginViewResource({ instanceId: id, path }).then((result) => {
if (disposed) throw new Error('Plugin view closed');
return result.url;
}).catch((error) => {
if (imageCache.get(path) === pending) imageCache.delete(path);
throw error;
});
imageCache.set(path, pending);
return pending;
},
get idle() { return users === 0; },
getSnapshot: () => state,
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createPromptHostnameSessionSignalController } from './promptHostnameSessionSignalController.ts';
import { extractTerminalPromptHostname } from '../../domain/terminalPromptSecurity';
type Change = readonly [sessionId: string, hostname: string | null];
@@ -20,10 +21,34 @@ function createHarness() {
return { changes, controller };
}
test('prompt host controller ignores the initial jumpserver prompt', () => {
test('prompt observations are independent of IP, alias, and matching connection addresses', () => {
const prompt = '[root@vm-prod ~]# ';
const observedHost = extractTerminalPromptHostname(prompt)!;
for (const hostname of ['203.0.113.10', 'alias.example.test', observedHost]) {
const changes: Change[] = [];
const controller = createPromptHostnameSessionSignalController({
getSession: () => ({ protocol: 'ssh', hostname }),
onChange: (sessionId, host) => changes.push([sessionId, host]),
});
controller.handleTerminalOutput('ssh-1', prompt);
assert.deepEqual(changes, [['ssh-1', observedHost]], hostname);
}
});
test('forgetting a session permits the first matching-host prompt to publish again', () => {
const { changes, controller } = createHarness();
const prompt = '[root@jump.example.com ~]# ';
const observedHost = extractTerminalPromptHostname(prompt)!;
controller.handleTerminalOutput('ssh-1', prompt);
controller.forgetSession('ssh-1');
controller.handleTerminalOutput('ssh-1', prompt);
assert.deepEqual(changes, [['ssh-1', observedHost], ['ssh-1', observedHost]]);
});
test('prompt host controller observes the initial jumpserver prompt', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# ');
assert.deepEqual(changes, []);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname]]);
});
test('prompt host controller publishes a nested target and de-duplicates it', () => {
@@ -31,17 +56,18 @@ test('prompt host controller publishes a nested target and de-duplicates it', ()
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# ');
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
});
test('prompt host controller clears the override when returning to the jumpserver', () => {
test('prompt host controller observes the original host when returning from a target', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
controller.handleTerminalOutput('ssh-1', 'exit\r\n[root@jump.example.com ~]# ');
assert.deepEqual(changes, [
['ssh-1', getSession('ssh-1').hostname],
['ssh-1', '10.1.64.1'],
['ssh-1', null],
['ssh-1', getSession('ssh-1').hostname],
]);
});
@@ -50,26 +76,28 @@ test('prompt host controller detects an identity split across output chunks', ()
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
controller.handleTerminalOutput('ssh-1', 'ssh target\r\n[root@10.1.');
controller.handleTerminalOutput('ssh-1', '64.1 ~]# ');
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
});
test('prompt host controller ignores ambiguous, sensitive, and local output', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
const initialChanges = changes.slice();
controller.handleTerminalOutput('ssh-1', 'Password:\n# ');
controller.handleTerminalOutput('ssh-1', 'copied output\n# ');
controller.handleTerminalOutput('local-1', '[root@10.1.64.1 ~]# ');
assert.deepEqual(changes, []);
assert.deepEqual(changes, initialChanges);
});
test('prompt host controller ignores host-like text embedded in copied output', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
const initialChanges = changes.slice();
controller.handleTerminalOutput('ssh-1', 'see [root@prod] logs\n# ');
controller.handleTerminalOutput('ssh-1', '[root@prod] copied output\n# ');
controller.handleTerminalOutput('ssh-1', 'root@prod output\n# ');
controller.handleTerminalOutput('ssh-1', '[root@prod] version = 1.2\n# ');
assert.deepEqual(changes, []);
assert.deepEqual(changes, initialChanges);
});
test('prompt host controller publishes common zsh, Alpine, and macOS root prompt hosts', () => {
@@ -5,7 +5,7 @@ import {
} from '../../domain/terminalPromptSecurity';
type PromptHostnameSessionSignalOptions = {
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol' | 'hostname'> | undefined;
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol'> | undefined;
onChange: (sessionId: string, hostname: string | null) => void;
maxTailChars?: number;
};
@@ -22,20 +22,18 @@ export function createPromptHostnameSessionSignalController({
maxTailChars = DEFAULT_MAX_TAIL_CHARS,
}: PromptHostnameSessionSignalOptions) {
const tails = new Map<string, string>();
const baselines = new Map<string, string>();
const published = new Map<string, string>();
const tailLimit = Math.max(256, maxTailChars);
const forgetSession = (sessionId: string): void => {
tails.delete(sessionId);
baselines.delete(sessionId);
published.delete(sessionId);
};
return {
forgetSession,
pruneSessions(validSessionIds: ReadonlySet<string>): void {
for (const sessionId of [...tails.keys(), ...baselines.keys(), ...published.keys()]) {
for (const sessionId of [...tails.keys(), ...published.keys()]) {
if (!validSessionIds.has(sessionId)) {
forgetSession(sessionId);
}
@@ -65,19 +63,8 @@ export function createPromptHostnameSessionSignalController({
const detectedKey = normalizedHostname(detected);
if (!detectedKey) return;
let baseline = baselines.get(sessionId);
if (baseline === undefined) {
baseline = normalizedHostname(session.hostname) || detectedKey;
baselines.set(sessionId, baseline);
}
if (detectedKey === baseline) {
if (!published.has(sessionId)) return;
published.delete(sessionId);
onChange(sessionId, null);
return;
}
// Observe the prompt, not whether its hostname matches an IP or DNS alias.
// The domain title policy decides if this presentation is shown.
if (published.get(sessionId) === detectedKey) return;
published.set(sessionId, detectedKey);
onChange(sessionId, detected);
@@ -0,0 +1,21 @@
import {
buildSftpDownloadDialogDirectoryOptions,
type SftpDownloadDialogDirectoryOptions,
} from "../../../domain/sftpDownloadLocation";
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
/**
* Read the device-local default download folder at call time so every SFTP
* surface (main view, terminal side panel, other windows) sees the latest
* value without threading it through props.
*/
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
let stored: string | null = null;
try {
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
} catch {
// Storage unavailable (non-browser host); fall back to system Downloads.
}
return buildSftpDownloadDialogDirectoryOptions(stored);
};
@@ -10,6 +10,89 @@ import { DirectoryPickerError, directoryChangeCommand } from '../../domain/direc
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
for (const home of [null, '/tmp'] as const) {
test(`command invalidation retains only the compose display (home=${home})`, async t => {
const id = 'hook-sticky-cwd-' + home;
let cwd = '/tmp/test_dir';
const writes: string[] = [];
const controller = createTerminalDirectoryController({
sessionId: id, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => cwd, home: async () => home, realpath: async path => path,
write: data => { writes.push(data); },
list: async () => ({ home, entries: [{ name: 'child', path: cwd + '/child', hidden: false }] }) },
publish: path => terminalCwdStore.setCwd(id, path, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, controller);
let model!: ReturnType<typeof useComposeDirectoryPicker>;
function Harness() { model = useComposeDirectoryPicker(id); return null; }
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness)); });
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); });
await act(async () => { model.setOpen(true); });
const label = home ? '~/test_dir' : cwd;
assert.equal(model.display?.label, label);
assert.equal(model.display?.title, cwd);
assert.equal(model.display?.ariaPath, label);
const revision = terminalCwdStore.getSessionRevision(id);
await act(async () => { terminalCwdStore.setCwd(id, null); });
assert.equal(model.cwd, null);
assert.equal(model.home, null);
assert.equal(terminalCwdStore.getCwd(id), null);
assert.equal(terminalCwdStore.getSource(id), undefined);
assert.ok(terminalCwdStore.getSessionRevision(id) > revision);
assert.equal(model.display?.label, label);
assert.equal(model.display?.title, cwd);
assert.equal(model.display?.ariaPath, label);
assert.equal(model.parent, null);
assert.deepEqual(model.entries, []);
await act(async () => { await model.change('/tmp'); });
assert.equal(model.error, 'unavailable');
await assert.rejects(controller.change('/tmp', new AbortController().signal, () => {}, cwd), { code: 'unavailable' });
assert.deepEqual(writes, []);
await act(async () => { await controller.refresh(); });
assert.equal(model.display?.label, label, 'restoring the same path preserves its home abbreviation');
await act(async () => { cwd = '/tmp/next'; await controller.refresh(); });
assert.equal(model.display?.label, home ? '~/next' : cwd);
assert.equal(model.display?.title, cwd);
});
}
for (const transition of ['session', 'controller', 'disconnect'] as const) {
test(`compose display never crosses a ${transition} boundary`, async t => {
const id = 'hook-display-boundary-' + transition;
const makeController = (sessionId: string, initial: boolean) => createTerminalDirectoryController({
sessionId, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => { if (!initial) throw new DirectoryPickerError('unknown'); return '/old/path'; },
home: async () => '/old', realpath: async path => path, write() {}, list: async () => ({ home: null, entries: [] }) },
publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, makeController(id, true));
let unregisterNext = () => {};
const renders: Array<ReturnType<typeof useComposeDirectoryPicker>['display']> = [];
let model!: ReturnType<typeof useComposeDirectoryPicker>;
function Harness({ session }: { session: string }) {
model = useComposeDirectoryPicker(session); renders.push(model.display); return null;
}
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness, { session: id })); });
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); unregisterNext(); });
assert.equal(model.display?.label, '~/path');
renders.length = 0;
await act(async () => {
if (transition === 'session') {
unregisterNext = registerTerminalDirectory(id + '-next', makeController(id + '-next', false));
root.update(React.createElement(Harness, { session: id + '-next' }));
} else if (transition === 'controller') {
// Leave the old backend value in the store: a new controller has not confirmed it.
unregisterNext = registerTerminalDirectory(id, makeController(id, false));
} else unregister();
});
assert.equal(model.cwd, null);
assert.equal(model.display, null);
assert.ok(renders.every(display => display === null), 'even the first render must discard the old display');
});
}
for (const outcome of ['complete', 'close', 'switch', 'repeated-reports'] as const) {
test(`unchanged OSC 7 during directory loading retries within the active menu (${outcome})`, async t => {
const id = 'hook-list-revision-' + outcome;
@@ -89,9 +172,11 @@ test('PowerShell non-filesystem reports clear an open menu and recover after ret
assert.equal(model.pathFlavor, 'win32');
assert.equal(model.parent, 'C:\\');
assert.equal(model.entries.length, 1);
assert.equal(model.display?.title, 'C:\\base');
await act(async () => { filesystem = false; await controller.refresh().catch(() => {}); });
assert.equal(model.cwd, null);
assert.equal(model.home, null);
assert.equal(model.display, null, 'native provider failures must not retain a filesystem label');
assert.equal(model.error, 'nonFilesystem');
assert.deepEqual(model.entries, []);
await act(async () => { filesystem = true; await controller.refresh(); });
+22 -11
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
import { terminalCwdStore } from './terminalCwdStore';
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
@@ -7,7 +8,8 @@ export function useComposeDirectoryPicker(sessionId: string) {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmed, setConfirmed] = useState(false);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const observedCwd = terminalCwdStore.getCwd(sessionId);
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
@@ -16,7 +18,15 @@ export function useComposeDirectoryPicker(sessionId: string) {
const [query, setQuery] = useState('');
const [showHidden, setShowHidden] = useState(false);
const [entries, setEntries] = useState<DirectoryEntry[]>([]);
const [home, setHome] = useState<string | null>(null);
const [homeResult, setHomeResult] = useState<{ sessionId: string; controller: typeof controller; value: string | null } | null>(null);
const home = homeResult?.sessionId === sessionId && homeResult.controller === controller ? homeResult.value : null;
const setHome = useCallback((value: string | null) => setHomeResult({ sessionId, controller, value }), [sessionId, controller]);
// Controller identity scopes the display to one connected shell generation.
const displayCache = useRef<{ sessionId: string; controller: typeof controller; value: ComposeDirectoryDisplay | null } | null>(null);
const previousDisplay = displayCache.current?.sessionId === sessionId && displayCache.current.controller === controller
? displayCache.current.value : null;
const display = resolveComposeDirectoryDisplay(previousDisplay, cwd, home, pathFlavor);
useEffect(() => { displayCache.current = { sessionId, controller, value: display }; }, [sessionId, controller, display]);
const [loading, setLoading] = useState(false);
const [pending, setPending] = useState(false);
const listingBase = useRef<string | null>(null);
@@ -35,25 +45,25 @@ export function useComposeDirectoryPicker(sessionId: string) {
const stopObserving = observeTerminalDirectory(sessionId);
lifetime.current = new AbortController();
sending.current = false;
setConfirmed(false); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
listingBase.current = null;
listingRevision.current = null;
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
if (generation.current === id) { setConfirmed(true); setHome(nextHome); }
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
return () => {
generation.current = id + 1;
lifetime.current.abort(); read.current?.abort(); stopObserving();
};
}, [sessionId, controller, report]);
}, [sessionId, controller, report, setHome]);
const refresh = useCallback(async () => {
if (!controller) { setError('unavailable'); return; }
const id = generation.current;
setError(null);
try { await controller.refresh(); if (generation.current === id) setConfirmed(true); }
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
}, [controller, report]);
}, [controller, report, sessionId]);
const load = useCallback(async () => {
if (!controller || !cwd) return;
@@ -76,7 +86,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
} catch (failure) {
if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed');
} finally { if (!task.signal.aborted && id === generation.current) setLoading(false); }
}, [controller, cwd, report, sessionId]);
}, [controller, cwd, report, sessionId, setHome]);
useEffect(() => {
if (!cwd) {
@@ -87,7 +97,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
}
if (open) { setQuery(''); void load(); }
return () => { read.current?.abort(); };
}, [open, load, cwd]);
}, [open, load, cwd, setHome]);
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
@@ -109,8 +119,9 @@ export function useComposeDirectoryPicker(sessionId: string) {
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
+4 -1
View File
@@ -15,6 +15,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;
@@ -117,13 +119,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,
});
}
@@ -0,0 +1,125 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import {
resetModelCatalogWarningDismissals,
useModelCatalogWarningDismissal,
type ModelCatalogWarningDismissalState,
} from './useModelCatalogWarningDismissal.ts';
import { isModelCatalogWarningVisible } from '../../components/AIChatSidePanelHelpers.ts';
test('useModelCatalogWarningDismissal dismisses per cacheKey, survives remounts, and rearms on clean catalog', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
(globalThis as Record<string, unknown>).window = dom.window;
(globalThis as Record<string, unknown>).document = dom.window.document;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
resetModelCatalogWarningDismissals();
let latest!: ModelCatalogWarningDismissalState;
const Probe: React.FC = () => {
latest = useModelCatalogWarningDismissal();
return null;
};
const container = dom.window.document.getElementById('root')!;
let root = createRoot(container);
try {
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.size, 0);
const warningK1 = { cacheKey: 'k1', message: 'Catalog unavailable' };
const warningK2 = { cacheKey: 'k2', message: 'Other catalog unavailable' };
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Dismissing k1 hides only k1, leaving k2 visible.
await React.act(async () => {
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
assert.equal(
isModelCatalogWarningVisible(warningK2, 'k2', latest.dismissedKeys),
'Other catalog unavailable',
);
// Unmounting and remounting (e.g., empty panel hidden on tab/tool switch)
// must keep the dismissed cacheKey hidden until a clean catalog arrives.
await React.act(async () => {
root.unmount();
});
root = createRoot(container);
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
// Undefined and duplicate dismissals are no-ops that keep state identity.
const setBeforeNoop = latest.dismissedKeys;
await React.act(async () => {
latest.dismissWarning(undefined);
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys, setBeforeNoop);
// A clean catalog for k1 re-arms k1 so future failures surface again.
await React.act(async () => {
latest.rearmWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), false);
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Rearming a non-dismissed or undefined key is a no-op.
const setAfterRearm = latest.dismissedKeys;
await React.act(async () => {
latest.rearmWarning('k1');
latest.rearmWarning(undefined);
});
assert.equal(latest.dismissedKeys, setAfterRearm);
} finally {
await React.act(async () => {
root.unmount();
});
resetModelCatalogWarningDismissals();
(globalThis as Record<string, unknown>).window = prevWindow;
(globalThis as Record<string, unknown>).document = prevDocument;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
}
});
test('AIChatPanelContent keeps raw modelCatalogWarning for ChatInput when banner is dismissed', () => {
const panelSource = readFileSync(new URL('../../components/AIChatPanelContent.tsx', import.meta.url), 'utf8');
const sidePanelSource = readFileSync(new URL('../../components/AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(
panelSource,
/modelCatalogWarning && !modelCatalogWarningDismissed \?/,
'banner visibility must check modelCatalogWarningDismissed separately from raw modelCatalogWarning',
);
assert.match(
panelSource,
/<ChatInput[\s\S]*?modelCatalogWarning=\{modelCatalogWarning\}/,
'ChatInput must still receive the raw modelCatalogWarning so ComposerModelPicker keeps its refresh action',
);
assert.match(
sidePanelSource,
/useModelCatalogWarningDismissal\(\)/,
'AIChatSidePanel must consume the application/state dismissal hook rather than owning inline dismissal state',
);
});
@@ -0,0 +1,70 @@
import { useSyncExternalStore } from 'react';
export interface ModelCatalogWarningDismissalState {
dismissedKeys: ReadonlySet<string>;
dismissWarning: (cacheKey: string | undefined) => void;
rearmWarning: (cacheKey: string | undefined) => void;
}
type Listener = () => void;
let dismissedKeysSnapshot: ReadonlySet<string> = new Set();
const listeners = new Set<Listener>();
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function subscribe(listener: Listener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
function getSnapshot(): ReadonlySet<string> {
return dismissedKeysSnapshot;
}
export function dismissModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.add(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function rearmModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || !dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.delete(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function resetModelCatalogWarningDismissals(): void {
if (dismissedKeysSnapshot.size === 0) return;
dismissedKeysSnapshot = new Set();
emitChange();
}
/**
* Tracks SDK model catalog cache keys whose composer warning banner was
* dismissed by the user.
*
* Stored at module scope so dismissals survive empty-panel unmounts during
* normal tab/tool navigation and stay consistent with the shared
* `sdkRuntimeModelCache`. Dismissals remain scoped by cacheKey so switching
* agents or config re-arms the banner, and a clean catalog load clears that
* key so a later failure warns again.
*/
export function useModelCatalogWarningDismissal(): ModelCatalogWarningDismissalState {
const dismissedKeys = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return {
dismissedKeys,
dismissWarning: dismissModelCatalogWarningKey,
rearmWarning: rearmModelCatalogWarningKey,
};
}
+68 -9
View File
@@ -24,9 +24,17 @@ type Review = {
completionToken?: string;
};
function isHostActionRequestKind(kind: string): boolean {
return kind.startsWith('vault.')
|| kind === 'network.stream.connectViaHost'
|| kind === 'network.stream.confirm'
|| kind === 'network.stream.tlsConfirm';
}
export function usePluginHostActions() {
const [review, setReview] = useState<Review | null>(null);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [remember, setRemember] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const current = useRef<Review | null>(null);
@@ -44,9 +52,19 @@ export function usePluginHostActions() {
const assertCurrent = useCallback((entry: Review) => {
if (current.current !== entry || Date.now() >= entry.prompt.expiresAt) throw new Error('Host action expired');
if (entry.prompt.request.kind === 'network.stream.confirm' || entry.prompt.request.kind === 'network.stream.tlsConfirm') {
const lock = getAppAppLockRuntime();
if (lock && lock.initialized && lock.locked) throw new Error('App is locked');
return;
}
const vault = getVault();
const target = entry.prompt.vaultTarget;
if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) throw new Error('Selected host changed');
if (entry.prompt.durableHostId) {
const liveHost = vault.hosts.find((candidate) => candidate.id === entry.prompt.durableHostId);
if (!liveHost || liveHost !== entry.host) throw new Error('Saved SSH host changed or was removed');
} else if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) {
throw new Error('Selected host changed');
}
if ((entry.prompt.request.kind === 'vault.requestConnect' || entry.prompt.request.kind === 'network.stream.connectViaHost') && (vault.groupConfigs !== entry.groups || vault.snippets !== entry.snippets)) {
throw new Error('Saved connection settings changed');
}
@@ -71,7 +89,7 @@ export function usePluginHostActions() {
assertCurrent(entry);
const request = entry.prompt.request;
const target = entry.prompt.vaultTarget;
if (request.kind === 'network.stream.connectViaHost' && target && entry.host) {
if (request.kind === 'network.stream.connectViaHost' && entry.host && (target || entry.prompt.durableHostId)) {
const vault = getVault();
const settings = getAppSettingsRuntime();
if (!settings || !bridge.openPluginHostStream) throw new Error('Host stream unavailable');
@@ -83,7 +101,15 @@ export function usePluginHostActions() {
|| latest.hosts !== vault.hosts || latest.knownHosts !== vault.knownHosts || getAppSettingsRuntime()?.terminalSettings !== settings.terminalSettings) throw new Error('Connection settings changed');
};
assertPrepared();
await executePluginHostAction({ kind: 'connect', target }, {
if (entry.prompt.durableHostId) {
entry.claimed = true;
await bridge.openPluginHostStream!({
response: { requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' },
connectionOptions,
});
return;
}
await executePluginHostAction({ kind: 'connect', target: target! }, {
getVault, resources: resources.current, assertCurrent: assertPrepared,
authorizeCommit: async () => { assertPrepared(); },
connect: async () => {
@@ -126,12 +152,35 @@ export function usePluginHostActions() {
const unsubscribe = bridge.onPluginInteraction((event) => {
if ('closed' in event) {
if (current.current?.prompt.requestId !== event.requestId) return;
current.current = null; setReview(null); setBusy(false); responding.current = false;
current.current = null; setReview(null); setRemember(false); setBusy(false); responding.current = false;
return;
}
if (!event.request.kind.startsWith('vault.') && event.request.kind !== 'network.stream.connectViaHost') return;
if (!isHostActionRequestKind(event.request.kind)) return;
const prompt = event as VaultHostPrompt;
try {
if (prompt.request.kind === 'network.stream.confirm' || prompt.request.kind === 'network.stream.tlsConfirm') {
const entry: Review = {
prompt, candidates: [], candidateRevisions: new Map(), customGroups: [],
groups: [], snippets: [], managedSources: [], scriptsRun: false, claimed: false,
};
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(false); setError(false); responding.current = false;
setReview(entry);
return;
}
if (prompt.phase === 'commit' && prompt.autoCommit && prompt.durableHostId && prompt.request.kind === 'network.stream.connectViaHost') {
const vault = getVault();
const host = vault.hosts.find((candidate) => candidate.id === prompt.durableHostId);
if (!host) throw new Error('Saved SSH host no longer exists');
const entry: Review = {
prompt, candidates: [], candidateRevisions: new Map(), customGroups: vault.customGroups,
host, groups: vault.groupConfigs, snippets: vault.snippets, managedSources: vault.managedSources,
scriptsRun: false, claimed: false,
};
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(true); setError(false); responding.current = false;
setReview(null);
void execute(entry);
return;
}
if (prompt.phase === 'commit') {
const entry = current.current;
if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable');
@@ -150,7 +199,10 @@ export function usePluginHostActions() {
scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false,
claimed: false,
};
current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
const defaultRemember = prompt.request.kind === 'network.stream.connectViaHost'
&& 'durable' in prompt.request
&& prompt.request.durable === true;
current.current = entry; setSelectedIds([]); setRemember(defaultRemember); setBusy(false); setError(false); responding.current = false;
if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') {
setReview(null);
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken,
@@ -168,7 +220,7 @@ export function usePluginHostActions() {
};
}, [execute, fail, getVault]);
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => {
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
const entry = current.current;
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
@@ -181,17 +233,24 @@ export function usePluginHostActions() {
resources.current.resolve(id, revision);
return resources.current.metadata(id);
}) : undefined;
const includeRemember = action === 'submit' && (
request.kind === 'network.stream.connectViaHost'
|| request.kind === 'network.stream.confirm'
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
} catch { await fail(entry); }
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, fail, selectedIds]);
}, [assertCurrent, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, busy, error, respond };
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
+6 -12
View File
@@ -11,7 +11,7 @@ import {
publishTerminalSettingsSnapshot,
registerTerminalSettingsActions,
} from './terminalSettingsStore';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models';
import {
normalizeAppLockTimeoutMinutes,
type AppLockSettings,
@@ -97,6 +97,7 @@ import {
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding as updateCustomKeyBindingRecord,
@@ -1939,17 +1940,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) => {
+9 -4
View File
@@ -159,17 +159,22 @@ export const useSftpBackend = () => {
const showSaveDialog = useCallback(async (
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => {
const bridge = netcattyBridge.get();
if (!bridge?.showSaveDialog) return null;
return bridge.showSaveDialog(defaultPath, filters);
return bridge.showSaveDialog(defaultPath, filters, directoryOptions);
}, []);
const selectDirectory = async (title?: string, defaultPath?: string) => {
const selectDirectory = async (
title?: string,
defaultPath?: string,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => {
const bridge = netcattyBridge.get();
if (!bridge?.selectDirectory) return null;
return bridge.selectDirectory(title, defaultPath);
return bridge.selectDirectory(title, defaultPath, directoryOptions);
};
return {
+1 -1
View File
@@ -419,7 +419,7 @@ export const useTerminalBackend = () => {
return bridge.getTelnetEchoMode(sessionId);
}, []);
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void) => {
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void) => {
const bridge = netcattyBridge.get();
return bridge?.onChainProgress?.(cb);
}, []);
@@ -5,8 +5,9 @@ import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { createTerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { createTerminalDirectoryController } from './terminalDirectoryController';
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell.cjs';
export function useTerminalDirectorySession(options: {
sessionId: string;
@@ -33,7 +34,7 @@ export function useTerminalDirectorySession(options: {
let active = true;
const isCurrent = () => active && live.current.status === 'connected' && live.current.getBackendId() === backendId;
let unregister = () => {};
const register = (pathFlavor: DirectoryPathFlavor = 'posix') => {
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
if (!isCurrent()) return;
const controller = createTerminalDirectoryController({
sessionId,
@@ -41,11 +42,11 @@ export function useTerminalDirectorySession(options: {
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
encoding: host.sftpEncoding,
pathFlavor,
windowsShell,
windowsShell: integration,
}, isCurrent),
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, windowsShell ?? 'posix', pathFlavor),
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
isReady: () => live.current.isReady(),
publish: cwd => live.current.publish(cwd),
@@ -53,13 +54,18 @@ export function useTerminalDirectorySession(options: {
unregister = registerTerminalDirectory(sessionId, controller);
};
if (local) {
// POSIX wrappers on Windows still use win32 PTYs. Neither their cwd nor
// their path namespace is supported by readLocalSessionCwd/local FS.
void bridge.getAppInfo?.().then(info => {
void bridge.getAppInfo?.().then(async info => {
if ((info.platform === 'darwin' || info.platform === 'linux') && !windowsShell) register();
else if (info.platform === 'win32' && windowsShell) register('win32');
if (info.platform !== 'win32' || !isCurrent()) return;
if (windowsShell) register('win32', windowsShell);
else if (shellType === 'posix' && host.localShell) {
const shells = await bridge.discoverShells?.();
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
}
}
}).catch(() => {});
} else register();
return () => { active = false; unregister(); };
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, windowsShell]);
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, host.localShell, shellType, windowsShell]);
}
+43
View File
@@ -2291,6 +2291,38 @@ test("legacy and invalid packed download settings preserve the local preference"
}
});
test("tree folder double-click preference round-trips in sync payloads and preserves local value on missing or invalid input", async () => {
const key = storageKeys.STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR;
assert.ok((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key));
for (const behavior of ["navigate", "expand"] as const) {
localStorage.clear();
localStorage.setItem(key, behavior);
const payload = buildSyncPayload(vault());
assert.equal(payload.settings?.sftpTreeDoubleClickBehavior, behavior);
localStorage.clear();
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), behavior);
}
localStorage.clear();
const emptyPayload = buildSyncPayload(vault());
assert.equal(emptyPayload.settings?.sftpTreeDoubleClickBehavior, undefined);
localStorage.setItem(key, "expand");
await applySyncPayload(emptyPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
for (const invalid of ["open", "transfer", 1, null]) {
await applySyncPayload({
...emptyPayload,
settings: { sftpTreeDoubleClickBehavior: invalid },
} as unknown as SyncPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
}
});
test("old bottom tab preference is ignored by settings export and import", async () => {
localStorage.clear();
const legacyKey = "netcatty_tab_bar_position_v1";
@@ -2389,3 +2421,14 @@ test('sync prepares header encryption once before importing and leaves input unc
assert.equal(JSON.stringify(payload), original);
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed });
});
test("SFTP default download folder stays device-local and is never synced", async () => {
const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR;
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
localStorage.clear();
localStorage.setItem(key, "/Users/me/server-files");
const payload = buildSyncPayload(vault());
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
});
+11
View File
@@ -109,6 +109,7 @@ import {
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_CUSTOM_THEMES,
STORAGE_KEY_SHOW_RECENT_HOSTS,
@@ -149,6 +150,7 @@ import {
import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge';
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
import { normalizeAiToolOutputMaxChars } from '../domain/aiToolOutputLimit';
import { isSftpTreeFolderDoubleClickBehavior } from '../domain/sftpTreeFolderDoubleClick';
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
// ---------------------------------------------------------------------------
@@ -345,6 +347,7 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_SHOW_RECENT_HOSTS,
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
@@ -576,6 +579,8 @@ export function collectSyncableSettings(): SyncPayload['settings'] {
if (followTerminalCwd === 'true' || followTerminalCwd === 'false') settings.sftpFollowTerminalCwd = followTerminalCwd === 'true';
const defaultViewMode = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE);
if (defaultViewMode === 'list' || defaultViewMode === 'tree') settings.sftpDefaultViewMode = defaultViewMode;
const treeDblClick = localStorageAdapter.readString(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR);
if (isSftpTreeFolderDoubleClickBehavior(treeDblClick)) settings.sftpTreeDoubleClickBehavior = treeDblClick;
// SFTP Bookmarks (global only - local bookmarks are device-specific)
const globalBookmarks = localStorageAdapter.read<SftpBookmark[]>(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS);
@@ -895,6 +900,12 @@ async function applySyncableSettings(
if (settings.sftpDefaultViewMode != null) {
localStorageAdapter.writeString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, settings.sftpDefaultViewMode);
}
if (isSftpTreeFolderDoubleClickBehavior(settings.sftpTreeDoubleClickBehavior)) {
localStorageAdapter.writeString(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
settings.sftpTreeDoubleClickBehavior,
);
}
// SFTP Bookmarks (global only)
if (settings.sftpGlobalBookmarks != null) localStorageAdapter.write(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS, settings.sftpGlobalBookmarks);
+19 -2
View File
@@ -1,5 +1,5 @@
import React, { type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Undo2 } from 'lucide-react';
import { History, Plus, Undo2, X } from 'lucide-react';
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
import type { Host, VaultNote } from '../types';
import type { UserSkillOption } from './ai/userSkillsState';
@@ -87,6 +87,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. */
@@ -95,6 +97,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). */
@@ -174,6 +178,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
handleSteer,
handleStop,
handleModelCatalogRetry,
handleModelCatalogDismiss,
handleModelPickerOpen,
canSteer,
isSteering,
@@ -183,6 +188,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
providerDisplayName,
modelDisplayName,
modelCatalogWarning,
modelCatalogWarningDismissed = false,
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
@@ -421,7 +427,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<div role="status" className="mx-3 mb-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
{steerWarning}
</div>
) : modelCatalogWarning ? (
) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
<div role="status" className="mx-3 mb-1.5 flex items-center gap-2 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
<span className="min-w-0 flex-1">{modelCatalogWarning}</span>
{handleModelCatalogRetry && (
@@ -432,6 +438,17 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
{t('ai.chat.modelCatalogRetry')}
</button>
)}
{handleModelCatalogDismiss && (
<button
type="button"
aria-label={t('common.close')}
title={t('common.close')}
onClick={handleModelCatalogDismiss}
className="shrink-0 rounded p-0.5 text-amber-600/70 transition-colors hover:bg-amber-500/10 hover:text-amber-600 cursor-pointer dark:text-amber-400/70 dark:hover:text-amber-300"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</button>
)}
</div>
) : modelCatalogLoading ? (
<div role="status" className="mx-3 mb-1.5 rounded-md bg-muted/40 px-2.5 py-1.5 text-[11px] leading-4 text-muted-foreground/70">
+36 -1
View File
@@ -85,12 +85,14 @@ import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime
import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState';
import { useConversationExport } from './ai/hooks/useConversationExport';
import { useAgentContextUsage } from '../application/state/useAgentCompactionUi';
import { useModelCatalogWarningDismissal } from '../application/state/useModelCatalogWarningDismissal';
import type { AIChatSidePanelProps } from './AIChatSidePanel.types';
import {
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
sdkRuntimeModelCache,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
retainStoredModelPresetForCatalog,
toSdkRuntimeModelCatalog,
generateId,
@@ -361,6 +363,11 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false);
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, { cacheKey: string; models: AgentModelPreset[]; catalogUnavailable: boolean }>>({});
const [runtimeModelWarnings, setRuntimeModelWarnings] = useState<Record<string, { cacheKey: string; message: string }>>({});
const {
dismissedKeys: dismissedModelCatalogKeys,
dismissWarning: dismissModelCatalogWarning,
rearmWarning: rearmModelCatalogWarning,
} = useModelCatalogWarningDismissal();
// Tracks SDK runtime model catalogs currently loading (per agent scope);
// the composer shows the loading row alongside the build-time presets and
// the live catalog replaces them when it arrives.
@@ -1352,6 +1359,11 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
t('ai.chat.modelCatalogWarning'),
);
});
// A clean catalog re-arms a banner the user previously dismissed, so a
// later failure for the same config is visible again.
if (catalog && !catalog.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
return catalog;
}).catch((err) => {
setRuntimeModelWarnings((current) => {
@@ -1367,7 +1379,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}
return null;
});
}, [t, buildExternalAgentRuntimeModelTarget]);
}, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]);
useEffect(() => {
if (!isVisible) return;
@@ -1390,6 +1402,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
Boolean(cached.warning),
t('ai.chat.modelCatalogWarning'),
));
if (!cached.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
}
// Respect renderer TTL / in-flight coalescing for all SDK agents including
@@ -1470,6 +1485,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
rearmModelCatalogWarning,
t,
]);
@@ -1625,6 +1641,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
applySdkRuntimeModelCatalog,
]);
// Hide the composer warning banner for this config until a clean catalog
// re-arms it. The underlying warning stays active so the model picker keeps
// its manual refresh action.
const handleDismissModelCatalogWarning = useCallback(() => {
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
dismissModelCatalogWarning(target?.cacheKey);
}, [currentAgentConfig, buildExternalAgentRuntimeModelTarget, dismissModelCatalogWarning]);
const selectedCattyThinking = agentThinkingMap.catty;
const handleCattyThinkingSelect = useCallback((level: string) => {
setAgentThinking('catty', level);
@@ -2516,6 +2540,17 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
? runtimeModelWarnings[currentAgentId].message
: undefined}
modelCatalogWarningDismissed={!hasCodexCustomConfig
&& Boolean(
runtimeModelWarnings[currentAgentId]
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
&& !isModelCatalogWarningVisible(
runtimeModelWarnings[currentAgentId],
buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey,
dismissedModelCatalogKeys,
),
)}
handleModelCatalogDismiss={handleDismissModelCatalogWarning}
modelCatalogLoading={
!hasCodexCustomConfig
&& Boolean(runtimeModelLoading[currentAgentId])
@@ -17,6 +17,7 @@ import {
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
toSdkRuntimeModelCatalog,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
@@ -685,6 +686,26 @@ test('reconcileRuntimeModelWarning clears only the banner that belongs to this c
assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current);
});
test('isModelCatalogWarningVisible shows a matching, non-dismissed banner', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k1', new Set()), 'cannot load models');
});
test('isModelCatalogWarningVisible hides a dismissed cache key but re-arms on a new key', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
const dismissed = new Set(['k1']);
assert.equal(isModelCatalogWarningVisible(warning, 'k1', dismissed), undefined);
// A config/agent switch produces a different cache key, which is not dismissed.
assert.equal(isModelCatalogWarningVisible({ cacheKey: 'k2', message: 'again' }, 'k2', dismissed), 'again');
});
test('isModelCatalogWarningVisible never shows a warning for another cache key or without a target', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k2', new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(warning, undefined, new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(undefined, 'k1', new Set()), undefined);
});
test('cacheOnly hydration in AIChatSidePanel reconciles cached refresh warnings before applying persisted models', () => {
const source = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(
+19
View File
@@ -293,6 +293,25 @@ export const sdkRuntimeModelCache = createSdkRuntimeModelCache();
export type RuntimeModelWarnings = Record<string, { cacheKey: string; message: string }>;
/**
* Whether a per-agent catalog warning should surface in the composer banner.
*
* A warning the user explicitly dismissed stays hidden for its cache key until
* a clean catalog is observed (the caller then drops the key from
* `dismissedKeys`). A warning belonging to a different cache key is never
* shown — config/agent switches must not inherit a stale dismissal.
*/
export function isModelCatalogWarningVisible(
warning: { cacheKey: string; message: string } | undefined,
cacheKey: string | undefined,
dismissedKeys: ReadonlySet<string>,
): string | undefined {
if (!warning || !cacheKey) return undefined;
if (warning.cacheKey !== cacheKey) return undefined;
if (dismissedKeys.has(cacheKey)) return undefined;
return warning.message;
}
/**
* Make the per-agent catalog warning banner match a catalog result. Used both
* for cache reads and after a refresh settles: a refresh that coalesced onto
+63 -24
View File
@@ -24,10 +24,13 @@ import {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type HostDetailsAdvancedSectionsProps = Record<string, any>;
const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void }> = ({ label, hint, enabled, disabled, onToggle }) => {
const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void; inheritance?: React.ReactNode }> = ({ label, hint, enabled, disabled, onToggle, inheritance }) => {
return (
<HostDetailsSettingRow label={label} hint={hint}>
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
<div className="flex items-center gap-2">
{inheritance}
<Switch checked={enabled} disabled={disabled} onCheckedChange={() => onToggle()} />
</div>
</HostDetailsSettingRow>
);
};
@@ -49,6 +52,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
setShowAlgorithmOverrides,
chainedHosts,
hostChainInherited = false,
canRestoreHostChain = false,
setActiveSubPanel,
clearHostChain,
proxySummaryType,
@@ -59,6 +63,29 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
}) => {
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
const effectiveEtEnabled = form.etEnabled ?? effectiveGroupDefaults?.etEnabled;
const inheritedBackspaceBehavior = effectiveGroupDefaults?.backspaceBehavior;
const groupSettingControl = (key: "moshEnabled" | "etEnabled" | "deviceType" | "backspaceBehavior") => {
if (effectiveGroupDefaults?.[key] === undefined) return null;
return form[key] === undefined ? (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("vault.groups.details.inherited")}
</Badge>
) : (
<HostDetailsOverrideReset size="sm" label={t("common.useGroup")} onClick={() => {
if ((key === "moshEnabled" || key === "etEnabled") && effectiveGroupDefaults[key] === true) {
setForm(prev => ({
...prev,
[key]: undefined,
[key === "moshEnabled" ? "etEnabled" : "moshEnabled"]: false,
}));
} else {
update(key, undefined);
}
}} />
);
};
const inheritedStartupCommandRunMode = effectiveGroupDefaults?.startupCommandRunMode ?? "paste";
const effectiveStartupCommandRunMode = form.startupCommandRunMode ?? inheritedStartupCommandRunMode;
const systemSshAgentSupported = effectiveAuthMethod === "auto" || effectiveAuthMethod === "key";
@@ -197,9 +224,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="Mosh"
enabled={!!form.moshEnabled}
enabled={!!effectiveMoshEnabled}
inheritance={groupSettingControl("moshEnabled")}
onToggle={() => {
const enabling = !form.moshEnabled;
const enabling = !effectiveMoshEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -220,9 +248,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<ToggleRow
label="EternalTerminal"
enabled={!!form.etEnabled}
enabled={!!effectiveEtEnabled}
inheritance={groupSettingControl("etEnabled")}
onToggle={() => {
const enabling = !form.etEnabled;
const enabling = !effectiveEtEnabled;
if (enabling) {
setForm(prev => ({
...prev,
@@ -235,7 +264,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
}
}}
/>
{form.etEnabled && (
{effectiveEtEnabled && (
<>
<HostDetailsSettingRow label={t("hostDetails.et.port")} hint={t("hostDetails.et.port.desc")}>
<Input
@@ -367,11 +396,12 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
icon={<Router size={14} className="text-muted-foreground" />}
title={t("hostDetails.section.deviceType")}
>
{(!form.protocol || form.protocol === 'ssh') && !form.moshEnabled && !form.etEnabled && (<>
{(!form.protocol || form.protocol === 'ssh') && !effectiveMoshEnabled && !effectiveEtEnabled && (<>
<ToggleRow
label={t("hostDetails.deviceType")}
hint={t("hostDetails.deviceType.desc")}
enabled={effectiveDeviceType === 'network'}
inheritance={groupSettingControl("deviceType")}
onToggle={() => update("deviceType", effectiveDeviceType === 'network' ? 'general' : 'network')}
/>
{effectiveDeviceType === 'network' && (
@@ -485,7 +515,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{(form.protocol === undefined || form.protocol === "ssh") && !form.moshEnabled && !form.etEnabled && (
{(form.protocol === undefined || form.protocol === "ssh") && !effectiveMoshEnabled && !effectiveEtEnabled && (
<>
<ToggleRow
label={t("hostDetails.sshInputCompatibility")}
@@ -499,19 +529,23 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</>
)}
<HostDetailsSettingRow label={t("hostDetails.backspaceBehavior")}>
<Select
value={form.backspaceBehavior ?? "default"}
onValueChange={(v) => update("backspaceBehavior", v === "default" ? undefined : v)}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">{t("hostDetails.backspaceBehavior.default")}</SelectItem>
<SelectItem value="ctrl-h">^H (0x08)</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-2">
{form.backspaceBehavior !== undefined && groupSettingControl("backspaceBehavior")}
<Select
value={form.backspaceBehavior ?? inheritedBackspaceBehavior ?? "default"}
onValueChange={(v) => update("backspaceBehavior", v === "default" && inheritedBackspaceBehavior === undefined ? undefined : v)}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">{inheritedBackspaceBehavior !== undefined ? t("serial.backspace.default") : t("hostDetails.backspaceBehavior.default")}</SelectItem>
<SelectItem value="ctrl-h">^H (0x08)</SelectItem>
</SelectContent>
</Select>
</div>
</HostDetailsSettingRow>
{form.backspaceBehavior === undefined && groupSettingControl("backspaceBehavior")}
</HostDetailsSection>
{/* Per-host keepalive override */}
@@ -634,9 +668,14 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
</div>
) : (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
</Badge>
<div className="flex items-center gap-1">
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
</Badge>
{canRestoreHostChain && (
<HostDetailsOverrideReset size="sm" label={t("common.useGroup")} onClick={clearHostChain} />
)}
</div>
)
}
>
@@ -0,0 +1,160 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { I18nProvider } from '../application/i18n/I18nProvider';
import type { Host } from '../domain/models';
import HostDetailsPanel from './HostDetailsPanel';
import { HostDetailsConnectionSections } from './HostDetailsConnectionSections';
import { LocalShellHostDetailsPanel } from './LocalShellHostDetailsPanel';
import { SerialHostDetailsPanel } from './SerialHostDetailsPanel';
import { installDomEnvironment } from './test-support/renderReactDom';
import { AsidePanelFooter } from './ui/aside-panel';
import { Button } from './ui/button';
import { Combobox } from './ui/combobox';
import { Input } from './ui/input';
import { TooltipProvider } from './ui/tooltip';
type PanelKind = 'ssh' | 'local' | 'serial';
const host: Host = {
id: 'existing', label: 'Web', hostname: 'web.example.com', username: 'root',
password: 'test-password', authMethod: 'password', tags: [], os: 'linux',
protocol: 'ssh', group: 'prod / web',
};
async function withPanel(
kind: PanelKind,
initialData: Host | undefined,
run: (editor: {
renderer: ReactTestRenderer;
save: () => Promise<Host>;
created: string[];
}) => Promise<void>,
groups: string[] = [],
) {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let saved: Host | undefined;
const created: string[] = [];
const common = { onSave: (value: Host) => { saved = value; }, onCancel() {}, groups, layout: 'inline' as const };
try {
await act(async () => {
renderer = create(<I18nProvider locale="en"><TooltipProvider>
{kind === 'ssh' ? <HostDetailsPanel {...common} initialData={initialData}
availableKeys={[]} identities={[]} terminalThemeId="default" terminalFontSize={14}
onCreateGroup={(path) => created.push(path)} />
: kind === 'local' ? <LocalShellHostDetailsPanel {...common} initialData={initialData} />
: <SerialHostDetailsPanel {...common} initialData={initialData!} />}
</TooltipProvider></I18nProvider>);
});
await run({
renderer: renderer!, created,
save: async () => {
saved = undefined;
await act(async () => {
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
await buttons[buttons.length - 1].props.onClick();
});
assert.ok(saved, 'the panel must call onSave');
return saved;
},
});
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
}
function groupPicker(renderer: ReactTestRenderer, kind: PanelKind) {
return renderer.root.findAllByType(Combobox).find((picker) =>
kind === 'ssh' ? picker.props.createText === 'Create Group' : picker.props.placeholder === 'Select Group',
)!;
}
for (const kind of ['ssh', 'local', 'serial'] as const) {
const initialData = { ...host, protocol: kind, ...(kind === 'serial' ? { hostname: 'COM3' } : {}) };
test(`${kind} Host Details keeps the exact stored group on a label-only edit`, async () => {
for (const group of ['prod / web', ' prod / web ', ' prod/web ']) {
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
await act(async () => {
renderer.root.findAllByType(Input).find((input) => input.props.value === host.label)!
.props.onChange({ target: { value: 'Updated label' } });
});
const saved = await save();
assert.equal(saved.label, 'Updated label');
assert.equal(saved.group, group);
});
}
});
test(`${kind} Host Details normalizes an explicitly selected trimmed-equivalent group`, async () => {
for (const group of [' prod/web ', ' prod / web ']) {
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
await act(async () => { groupPicker(renderer, kind).props.onValueChange(group.trim()); });
assert.equal((await save()).group, 'prod/web');
}, [group.trim()]);
}
});
test(`${kind} Host Details normalizes a changed group and allows clearing it`, async () => {
await withPanel(kind, initialData, async ({ renderer, save }) => {
const picker = groupPicker(renderer, kind);
await act(async () => { picker.props.onValueChange(host.group); });
assert.equal((await save()).group, host.group, 'reselecting the original group preserves it');
for (const [value, expected] of [[' stage / / web ', 'stage/web'], ['', '']]) {
await act(async () => { picker.props.onValueChange(value); });
assert.equal((await save()).group, expected);
}
});
});
}
for (const kind of ['ssh', 'local'] as const) {
test(`${kind} Host Details normalizes a new host's group`, async () => {
await withPanel(kind, undefined, async ({ renderer, save }) => {
await act(async () => {
if (kind === 'ssh') {
const { update } = renderer.root.findByType(HostDetailsConnectionSections).props;
update('hostname', 'web.example.com');
update('password', 'test-password');
}
groupPicker(renderer, kind).props.onValueChange('prod / web');
});
assert.equal((await save()).group, 'prod/web');
});
});
}
test('Create Group normalizes paths before creation and selection, including the Combobox follow-up', async () => {
const values = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
for (const groups of [[], ['prod/web']]) {
await withPanel('ssh', host, async ({ renderer, save, created }) => {
for (const value of values) {
const picker = groupPicker(renderer, 'ssh');
await act(async () => { picker.props.onCreateNew(value); });
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
// Combobox calls both callbacks with the original input when creating.
await act(async () => { picker.props.onValueChange(value); });
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
assert.equal((await save()).group, 'prod/web');
}
assert.deepEqual(created, groups.length ? [] : values.map(() => 'prod/web'));
await act(async () => { groupPicker(renderer, 'ssh').props.onCreateNew(' / / \\ '); });
assert.equal(created.length, groups.length ? 0 : values.length);
}, groups);
}
});
test('new-group sub-panel passes both parent and name through the same creation handler', () => {
const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8');
assert.match(source, /createAndSelectGroup\(`\$\{newGroupParent\}\/\$\{newGroupName\}`\)/);
assert.match(source, /onSave=\{handleCreateGroup\}/);
assert.match(source, /onCreateNew=\{createAndSelectGroup\}/);
});
+1 -1
View File
@@ -225,7 +225,7 @@ export const nextFormAfterClearHostChain = (
groupDefaults
&& applyGroupDefaults({ ...prev, hostChain: undefined }, groupDefaults).hostChain?.hostIds?.length,
);
if (prev.hostChain === undefined || groupWouldRestore) {
if (prev.hostChain === undefined || (groupWouldRestore && prev.hostChain.hostIds?.length)) {
return { ...prev, hostChain: { hostIds: [] } };
}
const { hostChain: _hostChain, ...rest } = prev;
@@ -0,0 +1,222 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider";
import { applyGroupDefaults } from "../domain/groupConfig";
import type { GroupConfig, Host } from "../domain/models";
import { resolveEffectiveTerminalProtocol } from "../domain/terminalProtocol";
import HostDetailsPanel from "./HostDetailsPanel";
import { ChainPanel } from "./host-details/ChainPanel";
import { HostDetailsOverrideReset } from "./host-details/HostDetailsOverrideReset";
import { HostDetailsSection, HostDetailsSettingRow } from "./host-details/HostDetailsSection";
import { mapTerminalBackspaceInput } from "./terminal/runtime/terminalBackspaceInput";
import { installDomEnvironment } from "./test-support/renderReactDom";
import { AsidePanelFooter } from "./ui/aside-panel";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Select } from "./ui/select";
import { Switch } from "./ui/switch";
import { TooltipProvider } from "./ui/tooltip";
const host: Host = {
id: "host-1", label: "Host", hostname: "example.com", username: "root",
password: "password", authMethod: "password", tags: [], os: "linux",
protocol: "ssh", group: "network",
};
const panelProps = (groupDefaults: Partial<GroupConfig>, initialData = host) => ({
initialData, availableKeys: [], identities: [], proxyProfiles: [],
groups: ["network"], groupConfigs: [{ path: "network", ...groupDefaults }],
allHosts: [{ ...host, id: "jump-1", label: "Jump", hostname: "jump.example.com" }],
terminalThemeId: "default", terminalFontSize: 14, layout: "inline" as const,
onSave: (_value: Host) => {}, onCancel: () => {},
});
async function withPanel(
groupDefaults: Partial<GroupConfig>,
run: (editor: { root: ReactTestInstance; save: () => Promise<Host> }) => Promise<void>,
initialData = host,
) {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let saved: Host | undefined;
try {
await act(async () => {
renderer = create(<I18nProvider locale="en"><TooltipProvider>
<HostDetailsPanel {...panelProps(groupDefaults, initialData)} onSave={(value) => { saved = value; }} />
</TooltipProvider></I18nProvider>);
});
await run({
root: renderer!.root,
save: async () => {
saved = undefined;
await act(async () => {
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
await buttons[buttons.length - 1].props.onClick();
});
assert.ok(saved, "the actual panel save handler must emit a host");
return saved;
},
});
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
}
function setting(root: ReactTestInstance, label: string) {
const row = root.findAllByType(HostDetailsSettingRow).find((node) => node.props.label === label);
assert.ok(row, `expected setting ${label}`);
return row;
}
function assertInherited(row: ReactTestInstance) {
assert.ok(row.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
assert.equal(row.findAllByType(HostDetailsOverrideReset).length, 0);
}
for (const [key, label] of [["moshEnabled", "Mosh"], ["etEnabled", "EternalTerminal"]] as const) {
test(`Host Details shows inherited ${label}, saves Off, and resets to the group`, async () => {
const group = { [key]: true };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, label);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "Network Device Mode"), false);
if (key === "etEnabled") setting(root, "ET server port");
await act(async () => { row().findByType(Switch).props.onCheckedChange(false); });
const off = await save();
assert.equal(off[key], false);
assert.equal(applyGroupDefaults(off, group)[key], false);
assert.equal(row().findByType(Switch).props.checked, false);
assert.equal(row().findAllByType(Badge).length, 0);
if (key === "etEnabled") {
assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "ET server port"), false);
}
const reset = row().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited[key], undefined);
assert.equal(applyGroupDefaults(inherited, group)[key], true);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
});
});
test(`Host Details restores inherited ${label} and disables the competing transport`, async () => {
const competingKey = key === "moshEnabled" ? "etEnabled" : "moshEnabled";
const competingLabel = key === "moshEnabled" ? "EternalTerminal" : "Mosh";
const group = { [key]: true };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, label);
assert.equal(row().findByType(Switch).props.checked, false);
assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, true);
const reset = row().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited[key], undefined);
assert.equal(inherited[competingKey], false);
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, false);
const effective = applyGroupDefaults(inherited, group);
assert.equal(effective[key], true);
assert.equal(effective[competingKey], false);
assert.equal(resolveEffectiveTerminalProtocol(effective), key === "moshEnabled" ? "mosh" : "et");
}, { ...host, [key]: false, [competingKey]: true });
});
}
test("Host Details device type override can return to the group", async () => {
const group = { deviceType: "network" as const };
await withPanel(group, async ({ root, save }) => {
const row = () => setting(root, "Network Device Mode");
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
await act(async () => { row().findByType(Switch).props.onCheckedChange(false); });
assert.equal((await save()).deviceType, "general");
assert.equal(row().findByType(Switch).props.checked, false);
await act(async () => { row().findByType(HostDetailsOverrideReset).props.onClick(); });
const inherited = await save();
assert.equal(inherited.deviceType, undefined);
assert.equal(applyGroupDefaults(inherited, group).deviceType, "network");
assert.equal(row().findByType(Switch).props.checked, true);
assertInherited(row());
});
});
test("Host Details backspace shows inherited Ctrl-H and saves explicit DEL or Ctrl-H or inherit", async () => {
const group = { backspaceBehavior: "ctrl-h" as const };
await withPanel(group, async ({ root, save }) => {
const select = () => setting(root, "Backspace Behavior").findByType(Select);
assert.equal(select().props.value, "ctrl-h");
assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
await act(async () => { select().props.onValueChange("default"); });
const del = await save();
assert.equal(del.backspaceBehavior, "default");
const reloaded: Host = JSON.parse(JSON.stringify(del));
assert.equal(mapTerminalBackspaceInput("\x7f", applyGroupDefaults(reloaded, group).backspaceBehavior), "\x7f");
assert.equal(select().props.value, "default");
await act(async () => { select().props.onValueChange("ctrl-h"); });
assert.equal((await save()).backspaceBehavior, "ctrl-h");
await act(async () => { setting(root, "Backspace Behavior").findByType(HostDetailsOverrideReset).props.onClick(); });
const inherited = await save();
assert.equal(inherited.backspaceBehavior, undefined);
assert.equal(applyGroupDefaults(inherited, group).backspaceBehavior, "ctrl-h");
assert.equal(select().props.value, "ctrl-h");
assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
});
});
test("Host Details keeps no-group toggle and Default backspace behavior", async () => {
await withPanel({}, async ({ root, save }) => {
const mosh = setting(root, "Mosh");
assert.equal(mosh.findByType(Switch).props.checked, false);
assert.equal(mosh.findAllByType(HostDetailsOverrideReset).length, 0);
await act(async () => { mosh.findByType(Switch).props.onCheckedChange(true); });
assert.equal((await save()).moshEnabled, true);
await act(async () => { setting(root, "Mosh").findByType(Switch).props.onCheckedChange(false); });
assert.equal((await save()).moshEnabled, false);
assert.equal(setting(root, "Mosh").findAllByType(HostDetailsOverrideReset).length, 0);
const select = () => setting(root, "Backspace Behavior").findByType(Select);
await act(async () => { select().props.onValueChange("ctrl-h"); });
assert.equal((await save()).backspaceBehavior, "ctrl-h");
await act(async () => { select().props.onValueChange("default"); });
assert.equal((await save()).backspaceBehavior, undefined);
});
});
test("Host Details can restore group jump hosts from the empty-override Direct row", async () => {
const group = { hostChain: { hostIds: ["jump-1"] } };
await withPanel(group, async ({ root, save }) => {
const section = () => root.findAllByType(HostDetailsSection).find((node) => node.props.title === "Proxy via Hosts")!;
await act(async () => { section().findAllByType("button").find((node) => node.props.className?.includes("cursor-pointer"))!.props.onClick(); });
await act(async () => { root.findByType(ChainPanel).props.onClearChain(); });
await act(async () => { root.findByType(ChainPanel).props.onBack(); });
const direct = await save();
assert.deepEqual(direct.hostChain, { hostIds: [] });
assert.deepEqual(applyGroupDefaults(direct, group).hostChain, { hostIds: [] });
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Direct"));
const reset = section().findByType(HostDetailsOverrideReset);
assert.equal(reset.props.label, "Use group");
await act(async () => { reset.props.onClick(); });
const inherited = await save();
assert.equal(inherited.hostChain, undefined);
assert.deepEqual(applyGroupDefaults(inherited, group).hostChain, group.hostChain);
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
});
});
@@ -4,9 +4,10 @@ import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { Host, Identity } from "../types.ts";
import type { Host, Identity, ProxyProfile } from "../types.ts";
import HostDetailsPanel, { parseOptionalPortInput } from "./HostDetailsPanel.tsx";
import { applyGroupDefaults } from "../domain/groupConfig.ts";
import { getActiveGlobalDefaultProxyProfileId, publishActiveGlobalDefaultProxyProfileId } from "../domain/globalDefaultProxy.ts";
import {
mapProxySaveErrorKey,
prepareProxyConfigForSave,
@@ -37,7 +38,7 @@ const hostWithMissingProxyProfile: Host = {
const renderHostDetails = (
initialData: Host = hostWithMissingProxyProfile,
options: { identities?: Identity[] } = {},
options: { identities?: Identity[]; proxyProfiles?: ProxyProfile[] } = {},
) =>
renderToStaticMarkup(
React.createElement(
@@ -50,7 +51,7 @@ const renderHostDetails = (
initialData,
availableKeys: [],
identities: options.identities ?? [],
proxyProfiles: [],
proxyProfiles: options.proxyProfiles ?? [],
groups: [],
managedSources: [],
allTags: [],
@@ -101,6 +102,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,
@@ -698,6 +724,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(
@@ -749,6 +788,7 @@ test("HostDetailsPanel empty jump-host override hides the inherited group chain"
assert.doesNotMatch(markup, /bastion\.example\.com/);
assert.doesNotMatch(markup, /edge\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
assert.match(markup, /aria-label="Use group"/);
});
test("mapProxySaveErrorKey maps every proxy save validation error to its i18n key", () => {
+35 -16
View File
@@ -14,6 +14,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,
@@ -281,6 +282,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [form.agentForwarding, form.identityAgent, form.hostname, form.port, form.username, checkSshAgent]);
const [groupInputValue, setGroupInputValue] = useState(form.group || "");
const originalGroupRef = useRef(initialData ? initialData.group || "" : undefined);
const createdGroupInputRef = useRef<string | null>(null);
const initialHostId = initialData?.id;
@@ -315,6 +318,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [initialData, snippets]);
useEffect(() => {
originalGroupRef.current = initialData ? initialData.group || "" : undefined;
createdGroupInputRef.current = null;
if (!initialData) return;
const normalized = normalizePrimaryTelnetState(initialData);
setForm(
@@ -373,7 +378,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, [defaultGroup, form.group, groupConfigs, groupDefaults]);
const effectiveAuthHost = useMemo(
() => effectiveGroupDefaults ? applyGroupDefaults(form, effectiveGroupDefaults) : form,
() => applyGroupDefaults(form, effectiveGroupDefaults ?? {}),
[effectiveGroupDefaults, form],
);
@@ -444,7 +449,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
) && Boolean(effectiveGroupDefaults?.proxyProfileId || effectiveGroupDefaults?.proxyConfig);
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || displayProxyConfig) || "HTTP";
@@ -578,7 +583,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}
const normalizedProxyConfig = proxySave.normalizedProxyConfig;
let finalLabel = form.label?.trim() || hostname;
const finalGroup = groupInputValue.trim() || form.group || "";
const finalGroup = resolveHostGroupForSave(
groupInputValue.trim() || form.group || "",
originalGroupRef.current,
groupInputValue !== originalGroupRef.current,
);
const targetManagedSource = managedSources
.filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/"))
@@ -761,14 +770,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}
};
const handleCreateGroup = () => {
if (!newGroupName.trim()) return;
const fullPath = newGroupParent
? `${newGroupParent}/${newGroupName.trim()}`
: newGroupName.trim();
onCreateGroup?.(fullPath);
const createAndSelectGroup = (value: string) => {
const fullPath = normalizeGroupTargetPath(value);
if (!fullPath) return;
createdGroupInputRef.current = value;
if (!groups.includes(fullPath)) onCreateGroup?.(fullPath);
setGroupInputValue(fullPath);
update("group", fullPath);
};
const handleCreateGroup = () => {
if (!newGroupName.trim()) return;
createAndSelectGroup(`${newGroupParent}/${newGroupName}`);
setNewGroupName("");
setNewGroupParent("");
setActiveSubPanel("none");
@@ -781,6 +794,9 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
[effectiveAuthHost.hostChain?.hostIds, form.hostChain],
);
const hostChainInherited = form.hostChain === undefined && displayHostChainIds.length > 0;
const canRestoreHostChain = form.hostChain !== undefined
&& !form.hostChain.hostIds?.length
&& resolveFormHostChainIds({ ...form, hostChain: undefined }, effectiveGroupDefaults).length > 0;
const availableHostsForChain = useMemo(() => {
const chainedIds = new Set(displayHostChainIds);
@@ -1117,16 +1133,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
options={groupOptions}
value={form.group || ""}
onValueChange={(val) => {
update("group", val);
setGroupInputValue(val);
// Creation also calls onValueChange with the raw input. Keep that
// path normalized while preserving a reselected legacy group.
const groupPath = val === createdGroupInputRef.current
? normalizeGroupTargetPath(val)
: resolveHostGroupForSave(val, originalGroupRef.current, val !== originalGroupRef.current);
createdGroupInputRef.current = null;
update("group", groupPath);
setGroupInputValue(groupPath);
}}
placeholder={t("hostDetails.group.placeholder")}
allowCreate={true}
onCreateNew={(val) => {
onCreateGroup?.(val);
update("group", val);
setGroupInputValue(val);
}}
onCreateNew={createAndSelectGroup}
createText="Create Group"
triggerClassName="flex-1 h-10"
/>
@@ -1247,6 +1265,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setShowAlgorithmOverrides={setShowAlgorithmOverrides}
chainedHosts={chainedHosts}
hostChainInherited={hostChainInherited}
canRestoreHostChain={canRestoreHostChain}
setActiveSubPanel={setActiveSubPanel}
clearHostChain={clearHostChain}
proxySummaryType={proxySummaryType}
+6 -4
View File
@@ -5,12 +5,13 @@
* into vault groups next to their SSH hosts (issue #3615).
*/
import { Save, TerminalSquare, X } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import React, { useMemo, useRef, useState } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import { useDiscoveredShells } from '../lib/useDiscoveredShells';
import { detectLocalOs } from '../lib/localShell';
import type { Host } from '../domain/models';
import { createLocalShellHost } from '../domain/localShellHost';
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
import { Button } from './ui/button';
import { Combobox, ComboboxOption } from './ui/combobox';
@@ -68,6 +69,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
const [group, setGroup] = useState(
initialData ? initialData.group ?? '' : defaultGroup ?? '',
);
const originalGroupRef = useRef(initialData ? initialData.group ?? '' : undefined);
const matchedShell = useMemo(
() => discoveredShells.find((candidate) => candidate.id === shell),
@@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
shellIcon: shellMeta?.icon,
startDir,
startupCommand,
// Save the controlled value directly: '' means the user explicitly
// cleared the group, which persists at the vault root.
group: group,
group,
tags: initialData?.tags,
notes: initialData?.notes,
});
// Apply after the factory's outer trim to retain unchanged legacy paths exactly.
host.group = resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current);
// On edits, merge over the existing host so fields this form does not
// expose (pinned, lastConnectedAt, order, ...) and the original
// creation timestamp survive a save.
+4 -2
View File
@@ -3,9 +3,10 @@
* A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel)
*/
import { Eye, EyeOff, Save, Tag, X } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import React, { useMemo, useRef, useState } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import type { GroupConfig, Host, SerialConfig, SerialFlowControl, SerialParity } from '../domain/models';
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
import {
resolveSerialBackspaceFormValue,
resolveSerialBackspaceOverrideOnSave,
@@ -97,6 +98,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
const [charset, setCharset] = useState(initialData.charset || 'UTF-8');
const [tags, setTags] = useState<string[]>(initialData.tags || []);
const [group, setGroup] = useState(initialData.group || '');
const originalGroupRef = useRef(initialData.group || '');
const [notes, setNotes] = useState(initialData.notes ?? '');
const handleSave = () => {
@@ -136,7 +138,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
? (passwordCleared ? undefined : password)
: (initialData.password ?? undefined),
tags,
group,
group: resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current),
charset,
serialConfig: config,
backspaceBehavior: undefined,
+1
View File
@@ -1020,6 +1020,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
currentHop: number;
totalHops: number;
currentHostLabel: string;
currentHostAddress?: string;
connectionPhase: string;
} | null>(null);
const [isConnectionAwaitingUserInput, setIsConnectionAwaitingUserInput] = useState(false);
+2
View File
@@ -192,6 +192,7 @@ function buildScriptSessionMeta(
}
const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
isVaultInitialized,
hosts,
portForwardingRules = [],
customGroups,
@@ -2802,6 +2803,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onToggleGlobalComposeSendTarget,
canUseGlobalBroadcast,
isComposeBarOpen,
isVaultInitialized,
keyBindings,
keys,
knownHosts,
+26 -2
View File
@@ -80,7 +80,7 @@ test("host tree tab gutter style animates only when host tree transitions and yi
});
});
test("workspace tabs resolve generated labels from live prompt hosts", () => {
test("workspace tabs resolve generated labels from live prompt hosts in all mode", () => {
const sessions = [
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
topTabSession("s2", "h2", { customName: "", promptHostname: "" }),
@@ -95,7 +95,7 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => {
publishSessionPromptHost("s1", "target-a");
publishSessionPromptHost("s2", "target-b");
assert.equal(
resolveWorkspaceTopTabLabel(workspace, sessions),
resolveWorkspaceTopTabLabel(workspace, sessions, "all"),
"target-a/target-b",
);
@@ -103,6 +103,30 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => {
sessionPresentationStore.clearSession("s2");
});
test("generated workspace tabs keep saved names in disabled and agent-only modes", (t) => {
const sessions = [
topTabSession("mode-s1", "h1", { hostLabel: "Production" }),
topTabSession("mode-s2", "h2", { hostLabel: "Database" }),
];
t.after(() => sessions.forEach((session) => sessionPresentationStore.clearSession(session.id)));
const savedTitle = sessions.map((session) => session.hostLabel).join("/");
const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: "mode-s1" };
publishSessionPromptHost("mode-s1", "vm-prod");
publishSessionPromptHost("mode-s2", "db-prod");
for (const mode of [undefined, "off", "agent"] as const) {
assert.equal(resolveWorkspaceTopTabLabel(workspace, sessions, mode), savedTitle, String(mode));
}
});
test("auto workspace tabs apply presentation with the current mode", (t) => {
const session = topTabSession("auto-mode", "h1", { hostLabel: "Production" });
t.after(() => sessionPresentationStore.clearSession(session.id));
const workspace = { title: "Workspace", autoTitle: true, focusedSessionId: session.id };
publishSessionPromptHost(session.id, "vm-prod");
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "off"), session.hostLabel);
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "all"), "vm-prod");
});
test("workspace tabs keep explicit names ahead of live prompt hosts", () => {
const sessions = [
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
@@ -3,18 +3,23 @@ import {
Box,
Code,
Command,
Database,
FileText,
Folder,
Globe,
HardDrive,
Key,
Layers,
LayoutPanelLeft,
List,
Network,
Palette,
Play,
Puzzle,
Server,
Settings,
Shield,
Sparkles,
Table,
Terminal,
Wrench,
@@ -30,17 +35,22 @@ const THEME_ICONS: Readonly<Record<string, LucideIcon>> = Object.freeze({
box: Box,
code: Code,
command: Command,
database: Database,
file: FileText,
folder: Folder,
globe: Globe,
'hard-drive': HardDrive,
key: Key,
layers: Layers,
'layout-panel': LayoutPanelLeft,
list: List,
network: Network,
palette: Palette,
play: Play,
server: Server,
settings: Settings,
shield: Shield,
sparkles: Sparkles,
table: Table,
terminal: Terminal,
wrench: Wrench,
+89 -3
View File
@@ -15,13 +15,27 @@ export function PluginHostActionHost() {
const request = entry.prompt.request;
const selection = request.kind === 'vault.selectHosts';
const stream = request.kind === 'network.stream.connectViaHost';
const directStreamConfirm = request.kind === 'network.stream.confirm';
const tlsConfirm = request.kind === 'network.stream.tlsConfirm';
const connection = request.kind === 'vault.requestConnect' || stream;
const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined;
const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined;
const dialogTitle = selection
? t('plugins.hostActions.select')
: directStreamConfirm
? 'Confirm Network Connection'
: tlsConfirm
? 'Verify TLS Certificate'
: connection
? t('plugins.hostActions.connect')
: entry.host
? t('plugins.hostActions.edit')
: t('plugins.hostActions.create');
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
<DialogContent className={selection ? 'max-w-md h-[min(85vh,640px)] flex flex-col p-0 gap-0 overflow-hidden' : 'sm:max-w-[560px] max-h-[85vh] overflow-y-auto'} hideCloseButton>
<DialogHeader className={selection ? 'px-4 pt-4 pb-2 shrink-0 border-b border-border/60' : undefined}>
<DialogTitle>{t(selection ? 'plugins.hostActions.select' : connection ? 'plugins.hostActions.connect' : entry.host ? 'plugins.hostActions.edit' : 'plugins.hostActions.create')}</DialogTitle>
<DialogTitle>{dialogTitle}</DialogTitle>
<DialogDescription className="break-all">{entry.prompt.pluginId} · {entry.prompt.pluginVersion}</DialogDescription>
</DialogHeader>
{selection ? <>
@@ -29,17 +43,89 @@ export function PluginHostActionHost() {
<p className="px-4 pt-2 text-sm font-medium break-words">{request.title}</p>
{state.selectedIds.length > 50 && <p role="alert" className="px-4 text-sm text-destructive">{t('plugins.hostActions.selectionLimit')}</p>}
<SelectHostPanelContent hosts={entry.candidates} customGroups={entry.customGroups} selectedHostIds={state.selectedIds} multiSelect className="flex-1 min-h-0" confirmDisabled={state.busy || state.selectedIds.length > 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} />
</> : connection && effective ? <>
</> : directStreamConfirm ? <div className="space-y-3">
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1">
<p className="text-xs text-muted-foreground">Destination Endpoint</p>
<p className="font-mono text-sm font-medium break-all">{request.endpoint}</p>
<p className="text-xs text-muted-foreground">
{request.transport.toUpperCase()} · {request.host}:{request.port}
{request.isLocal ? ' · Local / Private Network' : ''}
</p>
</div>
<p className="text-xs text-muted-foreground">
This plugin is requesting a direct {request.transport.toUpperCase()} connection to this endpoint. Netcatty&apos;s internal control ports remain blocked.
</p>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Remember for this endpoint</span>
</label>
</div> : tlsConfirm ? <div className="space-y-3">
<p className="text-sm text-amber-600 dark:text-amber-400 font-medium">
The server certificate could not be verified ({request.reason}).
</p>
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1.5 text-xs">
<div>
<span className="text-muted-foreground">Endpoint: </span>
<span className="font-mono break-all">{request.endpoint}</span>
</div>
{request.subject && <div>
<span className="text-muted-foreground">Subject: </span>
<span className="font-mono break-all">{request.subject}</span>
</div>}
{request.issuer && <div>
<span className="text-muted-foreground">Issuer: </span>
<span className="font-mono break-all">{request.issuer}</span>
</div>}
{request.validTo && <div>
<span className="text-muted-foreground">Valid Until: </span>
<span className="font-mono">{request.validTo}</span>
</div>}
<div>
<span className="text-muted-foreground">SHA-256 Fingerprint: </span>
<code className="block mt-1 font-mono text-[11px] break-all rounded bg-background/60 p-1.5 border border-border/40">
{request.fingerprint256}
</code>
</div>
</div>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Trust &amp; remember this certificate fingerprint</span>
</label>
</div> : connection && effective ? <>
<p className="break-all text-sm font-medium">{effective.label}</p>
<p className="break-all text-sm">{protocol !== 'local' && effective.username ? `${effective.username}@` : ''}{effective.hostname}{protocol !== 'local' && effective.port ? `:${effective.port}` : ''} ({protocol})</p>
{protocol === 'local' && <p className="text-sm font-medium" role="note">{t('plugins.hostActions.localExecution')}</p>}
{stream ? <><p className="text-sm font-medium break-all">{request.endpoint}</p><p className="text-sm">{t('plugins.hostActions.streamNote')}</p></> : <>
{stream ? <>
<p className="text-sm font-medium break-all">{request.endpoint}</p>
<p className="text-sm">{t('plugins.hostActions.streamNote')}</p>
<label className="flex items-center gap-2 text-sm select-none cursor-pointer pt-1">
<input
type="checkbox"
checked={state.remember}
disabled={state.busy}
onChange={(event) => state.setRemember(event.target.checked)}
/>
<span>Remember this SSH tunnel binding</span>
</label>
</> : <>
<p className="text-sm" role="note">{t(entry.scriptsRun ? 'plugins.hostActions.scriptsRun' : 'plugins.hostActions.noScripts')}</p>
<p className="text-xs text-muted-foreground">{t('plugins.hostActions.connectionNote')}</p></>}
</> : request.kind === 'vault.requestHostDraft' ? <PluginHostDraftPreview key={entry.prompt.requestId} before={entry.host} draft={request.draft} managedSources={entry.managedSources} busy={state.busy} onConfirm={(draft) => void state.respond('submit', draft)} /> : null}
{state.error && <p role="alert" className="text-sm text-destructive">{t('plugins.hostActions.failed')}</p>}
<DialogFooter className={selection ? 'p-3 border-t' : undefined}>
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>{t('common.cancel')}</Button>
{directStreamConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
{tlsConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>Trust &amp; Continue</Button>}
{connection && <Button disabled={state.busy || (stream && protocol !== 'ssh')} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
</DialogFooter>
</DialogContent>
+29 -4
View File
@@ -7,14 +7,39 @@ export type PluginHostDrawnPageProps = Parameters<typeof useHostDrawnPluginView>
pluginId: string;
};
type MinimalTreeNode = {
type?: number;
attributes?: Record<string, string>;
children?: MinimalTreeNode[];
};
function hasFullBleedChrome(tree: unknown): boolean {
if (!tree || typeof tree !== 'object') return false;
const children = (tree as { children?: MinimalTreeNode[] }).children;
if (!Array.isArray(children)) return false;
// Check root and immediate child (hostDom wraps React trees in a mountRoot div).
const check = (nodes: MinimalTreeNode[], depth: number): boolean => {
for (const node of nodes) {
if (node?.type !== 1) continue;
if (node.attributes?.['data-plugin-chrome'] === 'full-bleed') return true;
if (depth < 2 && Array.isArray(node.children) && check(node.children, depth + 1)) return true;
}
return false;
};
return check(children, 0);
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const view = useHostDrawnPluginView(props);
if (!view.visible) return null;
if (view.loading) return <p data-plugin-view-slot={props.slot.split(':')[0]} role="status" className="p-4 text-sm text-muted-foreground">{props.loadingLabel}</p>;
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]}>
const fullBleed = hasFullBleedChrome(view.tree);
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
</div>
{!fullBleed && (
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
</div>
)}
</div>;
}
+394 -1
View File
@@ -31,7 +31,7 @@ test('plugin surface forwards its own input and contains malformed updates and r
assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]);
const input = captured!.querySelector('input')!; input.value = 'typed';
await act(async () => { input.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed' });
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed', selectionStart: 5, selectionEnd: 5 });
await act(async () => { document.getElementById('host')!.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
assert.equal(events.length, 2);
await act(async () => { root.render(<PluginRemoteSurface tree={tree} css="@import 'https://bad.example/x';" onEvent={() => {}} />); });
@@ -254,3 +254,396 @@ test('PluginRemoteSurface avoids JSON/form hook work on text and plain elements
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, cursor popover, and host-rendered widgets', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [
{ name: 'id', type: 'int4', primaryKey: true },
{ name: 'name', type: 'varchar', nullable: true },
],
rows: [
{ id: 1, name: 'Alice' },
{ id: 2, name: null },
],
dirtyCells: { '0:name': 'Alicia' },
editable: true,
};
const erProps = {
tables: [
{ name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] },
{ name: 'orders', columns: [{ name: 'id', type: 'int', isPk: true }, { name: 'user_id', type: 'int', isFk: true }] },
],
relations: [{ fromTable: 'orders', fromColumn: 'user_id', toTable: 'users', toColumn: 'id' }],
};
const tree = {
children: [
{
id: 'scroller',
type: 1,
element: 'div',
attributes: { class: 'list' },
children: [{ id: 'item', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'it', type: 3, data: 'Row' }] }],
},
{
id: 'ctx-popover',
type: 1,
element: 'div',
attributes: {
'data-plugin-popover': 'true',
'data-plugin-anchor-x': '120',
'data-plugin-anchor-y': '80',
'data-plugin-popover-width': '260',
'data-plugin-popover-max-height': '320',
open: '',
},
children: [{ id: 'pop-item', type: 1, element: 'span', attributes: {}, children: [{ id: 'pt', type: 3, data: 'Menu' }] }],
},
{
id: 'split',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'split-pane',
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 220, minSize: 120, maxSize: 400 }),
},
children: [
{ id: 'pane-a', type: 1, element: 'div', attributes: {}, children: [{ id: 'pa', type: 3, data: 'Left' }] },
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
],
},
{
id: 'grid',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
children: [],
},
{
id: 'er',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) },
children: [],
},
],
};
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={tree} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
const mainShadow = shadows[0];
assert.ok(mainShadow, 'main shadow mounted');
// 1. dblclick & contextmenu with surface-relative coordinates + preventDefault
const btn = mainShadow.querySelector('button')!;
const ctxEvent = new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 250, clientY: 170 });
await act(async () => {
btn.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, clientX: 180, clientY: 90 }));
btn.dispatchEvent(ctxEvent);
});
assert.equal(ctxEvent.defaultPrevented, true, 'contextmenu must call preventDefault');
assert.deepEqual(events[0], { nodeId: 'item', type: 'dblclick', x: 80, y: 40 });
assert.deepEqual(events[1], { nodeId: 'item', type: 'contextmenu', x: 150, y: 120 });
// 2. throttled scroll
const scroller = mainShadow.querySelector('.list') as HTMLElement;
scroller.scrollTop = 140;
scroller.scrollLeft = 20;
await act(async () => {
scroller.dispatchEvent(new dom.window.Event('scroll', { bubbles: false }));
await new Promise((resolve) => setTimeout(resolve, 90));
});
const scrollEvt = events.find((e) => e.type === 'scroll');
assert.ok(scrollEvt, 'scroll event emitted');
assert.equal(scrollEvt!.scrollTop, 140);
assert.equal(scrollEvt!.scrollLeft, 20);
// 3. cursor-anchored popover positioned within surface bounds with custom width & maxHeight
const popoverEl = document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
assert.ok(popoverEl, 'cursor-anchored popover rendered');
assert.equal(popoverEl!.style.width, '260px');
assert.equal(popoverEl!.style.maxHeight, '320px');
assert.equal(popoverEl!.style.left, '220px'); // surface.left (100) + anchorX (120)
// 4. SplitPane rendered inside shadow root with two panes and drag handle
const splitEl = mainShadow.querySelector('[data-plugin-widget="split-pane"]') as HTMLElement | null;
assert.ok(splitEl, 'split-pane rendered in shadow root');
assert.equal(splitEl!.querySelectorAll('[data-split-pane]').length, 2);
const handle = splitEl!.querySelector('[data-split-handle]') as HTMLElement;
await act(async () => {
handle.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, clientX: 220 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { bubbles: true, clientX: 280 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, clientX: 280 }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'),
{ nodeId: 'split', type: 'widget', widgetEvent: 'resizeEnd', detail: { size: 280, collapsed: false } },
);
// 5. DataGrid slotted in Light DOM: renders dirty cell, NULL pill, inline edit & sort
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement | null;
assert.ok(gridHost, 'data-grid slotted in shadow host Light DOM');
assert.ok(gridHost!.textContent?.includes('Alicia'), 'dirty cell value rendered');
assert.ok(gridHost!.textContent?.includes('NULL'), 'NULL pill rendered');
const nameHeaderBtn = gridHost!.querySelector('[data-col-name="name"] button') as HTMLButtonElement;
await act(async () => { nameHeaderBtn.click(); });
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'sortChange'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'sortChange', detail: { column: 'name', direction: 'asc' } },
);
const cell = gridHost!.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="name"]') as HTMLElement;
await act(async () => {
cell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const editorInput = cell.querySelector('input') as HTMLInputElement;
assert.ok(editorInput, 'double-click opens inline cell editor');
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!;
setter.call(editorInput, 'Bob');
editorInput.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
});
await act(async () => {
editorInput.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'name', value: 'Bob', isNull: false } },
);
// 6. ER Canvas slotted in Light DOM: renders tables + FK curve + emits tableClick
const erHost = document.querySelector('[data-plugin-widget-host="er-canvas"]') as HTMLElement | null;
assert.ok(erHost, 'er-canvas slotted in shadow host Light DOM');
const usersCard = erHost!.querySelector('[data-er-table="users"]') as Element | null;
assert.ok(usersCard, 'users table card rendered');
await act(async () => {
usersCard!.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableClick'),
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableClick', detail: { table: 'users' } },
);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid FK jump, hiddenColumns, keyboard shortcuts, and PluginErCanvas double-click + SVG export', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [
{ name: 'id', type: 'int4', primaryKey: true },
{ name: 'customer_id', type: 'int4', foreignKey: { table: 'customers', column: 'id', schema: 'public' } },
{ name: 'secret_col', type: 'text' },
],
hiddenColumns: ['secret_col'],
rows: [[10, 42, 'hidden-val']],
editable: true,
};
const roGridProps = {
columns: [{ name: 'id', type: 'int4' }],
rows: [{ id: 99 }],
editable: false,
};
const erProps = {
tables: [
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'created_at', type: 'timestamp with time zone' }] },
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
],
relations: [{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
};
const tree = {
children: [
{ id: 'surface-btn', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'sbt', type: 3, data: 'Btn' }] },
{ id: 'grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) }, children: [] },
{ id: 'ro-grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(roGridProps) }, children: [] },
{ id: 'er', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) }, children: [] },
],
};
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={tree} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
// Shadow surface prevents default on Cmd+K / Cmd+S
const btn = shadows[0].querySelector('button')!;
const modK = new dom.window.KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true, cancelable: true });
await act(async () => { btn.dispatchEvent(modK); });
assert.equal(modK.defaultPrevented, true, 'Cmd+K inside shadow surface must preventDefault');
// DataGrid: hiddenColumns excludes secret_col while preserving values
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
assert.equal(gridHost.querySelector('[data-col-name="secret_col"]'), null, 'hidden column must not render');
const fkCell = gridHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="customer_id"]') as HTMLElement;
assert.ok(fkCell, 'customer_id FK cell rendered');
const jumpBtn = fkCell.querySelector('[data-fk-jump]') as HTMLButtonElement;
assert.ok(jumpBtn, 'FK jump button rendered');
await act(async () => { jumpBtn.click(); });
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'fkJump'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'customer_id', value: 42, targetTable: 'customers', targetColumn: 'id', targetSchema: 'public' } },
);
// Select FK cell then press Cmd+C -> cellCopy, Delete -> cellEdit NULL, Cmd+Z -> shortcut mod+z
await act(async () => { fkCell.click(); });
const gridRoot = gridHost.querySelector('[data-plugin-data-grid]') as HTMLElement;
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'c', metaKey: true, bubbles: true, cancelable: true }));
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true }));
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'z', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellCopy'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellCopy', detail: { text: '42', rowIndex: 0, colName: 'customer_id', rowIndices: [0] } },
);
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'customer_id', value: null, isNull: true } },
);
assert.deepEqual(
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut'),
{ nodeId: 'grid', type: 'widget', widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } },
);
// Non-editable grid double-click emits cellDoubleClick
const roHost = document.querySelector('[data-plugin-widget-node="ro-grid"]') as HTMLElement;
const roCell = roHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="id"]') as HTMLElement;
await act(async () => { roCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
assert.deepEqual(
events.find((e) => e.nodeId === 'ro-grid' && e.widgetEvent === 'cellDoubleClick'),
{ nodeId: 'ro-grid', type: 'widget', widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 99 } },
);
// ER Canvas: abbreviated type, tableDoubleClick, Export SVG
const erHost = document.querySelector('[data-plugin-widget-node="er"]') as HTMLElement;
assert.ok(erHost.textContent?.includes('timestamptz'), 'verbose PG timestamp abbreviated to timestamptz');
const ordersCard = erHost.querySelector('[data-er-table="orders"]') as Element;
await act(async () => { ordersCard.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
assert.deepEqual(
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableDoubleClick'),
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableDoubleClick', detail: { table: 'orders', schema: 'public' } },
);
const exportBtn = erHost.querySelector('[data-er-export-svg]') as HTMLButtonElement;
await act(async () => { exportBtn.click(); });
const exportEvt = events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'exportSvg');
assert.ok(exportEvt, 'exportSvg event emitted');
assert.match(String((exportEvt!.detail as { svg: string }).svg), /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
// Host global hotkey handler yields Cmd+K (commandPalette) to active plugin surface while keeping Cmd+J (quickSwitch)
const { handleGlobalHotkeyKeyDownImpl } = await import('../../application/app/AppHandlers');
const { matchesKeyBinding } = await import('../../domain/models');
const { DEFAULT_KEY_BINDINGS } = await import('../../domain/models/keyBindings');
const hostActions: string[] = [];
const onGlobalKey = (event: KeyboardEvent) => handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '⌘ + W',
hotkeyScheme: 'mac',
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
executeHotkeyAction: (action: string) => hostActions.push(action),
}), event);
dom.window.addEventListener('keydown', onGlobalKey as unknown as EventListener, true);
try {
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'k', code: 'KeyK', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(hostActions, [], 'host commandPalette must not hijack Cmd+K inside plugin surface');
assert.ok(
events.some((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut' && (e.detail as { shortcut?: string })?.shortcut === 'mod+k'),
'Cmd+K reaches plugin DataGrid as mod+k shortcut',
);
await act(async () => {
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'j', code: 'KeyJ', metaKey: true, bubbles: true, cancelable: true }));
});
assert.deepEqual(hostActions, ['quickSwitch'], 'Cmd+J still opens Netcatty Quick Switcher');
} finally {
dom.window.removeEventListener('keydown', onGlobalKey as unknown as EventListener, true);
}
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+383 -27
View File
@@ -1,6 +1,10 @@
import React, { createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
import { PluginViewPopover } from './PluginViewPopover';
import { PluginSplitPane } from './primitives/PluginSplitPane';
import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer';
import { matchWorkbenchShortcut } from './primitives/shortcuts';
import type { PluginSplitPaneWidgetProps } from './primitives/types';
import { createPortal } from 'react-dom';
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
@@ -9,16 +13,44 @@ type RemoteElementNode = {
id: string; type: 1; element: string; attributes: Record<string, string>; children: RemoteNode[];
};
type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | RemoteElementNode;
export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent;
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
'compositionstart', 'compositionupdate', 'compositionend',
'submit', 'reset',
'scroll',
] as const;
const SURFACE_EVENT_SET = new Set<string>(SURFACE_EVENTS);
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas']);
const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
const preventFormSubmit = (event: React.FormEvent) => event.preventDefault();
const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 });
const SurfaceContext = createContext<{
css: string;
onEvent(event: PluginSurfaceEvent): void;
depth: number;
shadowHost: HTMLDivElement | null;
}>({ css: '', onEvent: () => {}, depth: 0, shadowHost: null });
function remoteText(nodes: RemoteNode[]): string {
return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join('');
}
function parseOptionalNumber(raw: string | undefined): number | undefined {
if (raw === undefined || raw === '') return undefined;
const parsed = Number(raw);
return Number.isFinite(parsed) ? parsed : undefined;
}
const ResourceLoader = createContext<((path: string) => Promise<string>) | undefined>(undefined);
function buildRemoteElementProps(node: RemoteElementNode): Record<string, unknown> {
@@ -41,17 +73,166 @@ const RemotePopoverElement = memo(function RemotePopoverElement({ node, settled
const loadImage = useContext(ResourceLoader);
if (surface.depth >= 1) return null;
const attrs = node.attributes;
return <PluginViewPopover anchor={attrs['data-plugin-anchor'] ?? ''} open={Object.hasOwn(attrs, 'open')} dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}><PluginRemoteSurface tree={{ children: node.children }} css={surface.css} onEvent={surface.onEvent} settled={settled} loadImage={loadImage} depth={surface.depth + 1} /></PluginViewPopover>;
return (
<PluginViewPopover
anchor={attrs['data-plugin-anchor'] ?? ''}
anchorX={parseOptionalNumber(attrs['data-plugin-anchor-x'])}
anchorY={parseOptionalNumber(attrs['data-plugin-anchor-y'])}
width={parseOptionalNumber(attrs['data-plugin-popover-width'])}
maxHeight={parseOptionalNumber(attrs['data-plugin-popover-max-height'])}
open={Object.hasOwn(attrs, 'open')}
dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}
>
<PluginRemoteSurface
tree={{ children: node.children }}
css={surface.css}
onEvent={surface.onEvent}
settled={settled}
loadImage={loadImage}
depth={surface.depth + 1}
/>
</PluginViewPopover>
);
});
const RemoteSplitPaneElement = memo(function RemoteSplitPaneElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const surface = useContext(SurfaceContext);
const parsed = useMemo(
() => parseWidgetPropsJson<PluginSplitPaneWidgetProps>(node.attributes['data-plugin-widget-props']),
[node.attributes['data-plugin-widget-props']],
);
const elementChildren = node.children.filter((child) => child.type === 1 || (child.type === 3 && child.data.length > 0));
const firstChild = elementChildren[0] ? renderRemoteNode(elementChildren[0], settled) : null;
const secondChild = elementChildren[1] ? renderRemoteNode(elementChildren[1], settled) : null;
const emit = useCallback(
(widgetEvent: string, detail?: Record<string, unknown>) => {
surface.onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[surface.onEvent, node.id],
);
return (
<PluginSplitPane
{...parsed}
nodeId={node.id}
className={node.attributes.class}
inlineStyle={node.attributes.style}
firstChild={firstChild}
secondChild={secondChild}
onWidgetEvent={emit}
/>
);
});
const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ node, kind }: { node: RemoteElementNode; kind: SlottedWidgetKind }): React.ReactNode {
const surface = useContext(SurfaceContext);
const slotName = `nc-widget-${node.id}`;
const emit = useCallback(
(widgetEvent: string, detail?: Record<string, unknown>) => {
surface.onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[surface.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' } }),
)}
{surface.shadowHost && createPortal(
<div
slot={slotName}
data-plugin-widget-host={kind}
data-plugin-widget-node={node.id}
className="flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden"
>
<PluginSlottedWidget
kind={kind}
rawProps={node.attributes['data-plugin-widget-props']}
onWidgetEvent={emit}
/>
</div>,
surface.shadowHost,
)}
</>
);
});
const resolvedImageCache = new WeakMap<(path: string) => Promise<string>, Map<string, string>>();
const IMAGE_RETRY_DELAYS_MS = [200, 600] as const;
function getCachedImageUrl(loader: ((path: string) => Promise<string>) | undefined, imagePath: string | undefined): string | undefined {
if (!loader || !imagePath) return undefined;
return resolvedImageCache.get(loader)?.get(imagePath);
}
function setCachedImageUrl(loader: (path: string) => Promise<string>, imagePath: string, url: string) {
let map = resolvedImageCache.get(loader);
if (!map) {
map = new Map();
resolvedImageCache.set(loader, map);
}
if (map.size >= 256) {
const oldest = map.keys().next().value;
if (oldest !== undefined) map.delete(oldest);
}
map.set(imagePath, url);
}
const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: RemoteElementNode }): React.ReactNode {
const loadImage = useContext(ResourceLoader);
const imagePath = node.attributes.src?.slice(6);
const [imageUrl, setImageUrl] = useState<string | undefined>();
const [imageUrl, setImageUrl] = useState<string | undefined>(() => getCachedImageUrl(loadImage, imagePath));
useEffect(() => {
let cancelled = false; setImageUrl(undefined);
if (imagePath && loadImage) void loadImage(imagePath).then((url) => { if (!cancelled) setImageUrl(url); }).catch(() => {});
return () => { cancelled = true; };
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
const cached = getCachedImageUrl(loadImage, imagePath);
if (cached) {
setImageUrl(cached);
return () => { cancelled = true; };
}
setImageUrl(undefined);
if (imagePath && loadImage) {
const attemptLoad = (attempt: number) => {
void loadImage(imagePath).then((url) => {
if (cancelled) return;
setCachedImageUrl(loadImage, imagePath, url);
setImageUrl(url);
}).catch(() => {
if (cancelled) return;
const delay = IMAGE_RETRY_DELAYS_MS[attempt];
if (delay !== undefined) {
retryTimer = setTimeout(() => { if (!cancelled) attemptLoad(attempt + 1); }, delay);
}
});
};
attemptLoad(0);
}
return () => {
cancelled = true;
if (retryTimer !== undefined) clearTimeout(retryTimer);
};
}, [imagePath, loadImage]);
const props = buildRemoteElementProps(node);
props.src = imageUrl;
@@ -111,12 +292,40 @@ function renderRemoteNode(node: RemoteNode, settled: boolean): React.ReactNode {
if (node.type === 3) return node.data;
if (node.type === 8) return null;
if (node.attributes['data-plugin-popover'] === 'true') return <RemotePopoverElement key={node.id} node={node} settled={settled} />;
const widgetKind = node.attributes['data-plugin-widget'];
if (widgetKind === 'split-pane') return <RemoteSplitPaneElement key={node.id} node={node} settled={settled} />;
if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) {
return <RemoteSlottedWidgetElement key={node.id} node={node} kind={widgetKind as SlottedWidgetKind} />;
}
if (node.element === 'img') return <RemoteImageElement key={node.id} node={node} />;
if (node.element === 'select') return <RemoteSelectElement key={node.id} node={node} settled={settled} />;
if (node.element === 'input' || node.element === 'textarea') return <RemoteInputElement key={node.id} node={node} settled={settled} />;
return <RemotePlainElement key={node.id} node={node} settled={settled} />;
}
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;
}
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checked = useMemo(() => {
@@ -125,20 +334,32 @@ export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadIm
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) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
return (
<LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}>
<ResourceLoader.Provider value={loadImage}>
<ValidatedPluginRemoteSurface tree={checked.tree} css={checked.css} onEvent={onEvent} settled={settled} depth={depth} />
</ResourceLoader.Provider>
</LazyLoadBoundary>
);
if (!checked || !surfaceContextValue) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
return <LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}><SurfaceContext.Provider value={surfaceContextValue}><ResourceLoader.Provider value={loadImage}><ValidatedPluginRemoteSurface tree={checked.tree} css={checked.css} onEvent={onEvent} settled={settled} /></ResourceLoader.Provider></SurfaceContext.Provider></LazyLoadBoundary>;
}
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled: boolean; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
const SHADOW_BASE_SCROLLBAR_CSS = [
'*::-webkit-scrollbar{width:6px;height:6px}',
'*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}',
'*::-webkit-scrollbar-thumb{min-height:28px;border:1px solid transparent;border-radius:999px;background-color:transparent;background-clip:content-box}',
'*:hover::-webkit-scrollbar-thumb{background-color:hsl(var(--muted-foreground) / 0.24)}',
'*::-webkit-scrollbar-thumb:hover{background-color:hsl(var(--muted-foreground) / 0.45)}',
].join('');
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
const surfaceRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const shadowRef = useRef<ShadowRoot | null>(null);
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const host = hostRef.current;
if (!host) return;
@@ -146,32 +367,167 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled
const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' });
shadowRef.current = root;
setShadow(root);
setShadowHost(host);
}, []);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
);
useEffect(() => {
if (!shadow) return;
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingScroll = new Map<string, PluginSurfaceEvent>();
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
const evt = pendingScroll.get(nodeId);
if (evt) {
pendingScroll.delete(nodeId);
onEventRef.current(evt);
}
};
const listener = (event: Event) => {
const target = event.target;
const view = shadow.ownerDocument.defaultView;
if (!view || !(target instanceof view.HTMLElement) || !['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset'].includes(event.type)) return;
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
// Closed-shadow events hide their editable target from window capture.
if (event.type === 'focusin') hostRef.current?.toggleAttribute('data-plugin-editing', target.matches('input, textarea, select, [contenteditable]'));
if (event.type === 'focusin') {
hostRef.current?.toggleAttribute(
'data-plugin-editing',
target.matches('input, textarea, select, [contenteditable]') || Boolean(target.closest('.monaco-editor')),
);
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
if (target.closest('[data-plugin-widget-host]')) return;
if (event.type === 'submit') event.preventDefault();
const nodeId = target.dataset.netcattyRemoteNode;
if (event.type === 'contextmenu') event.preventDefault();
if (event.type === 'keydown' && event instanceof view.KeyboardEvent) {
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (sc === 'mod+k' || sc === 'mod+s') {
event.preventDefault();
}
}
const nodeId = target.dataset.netcattyRemoteNode
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
if (!nodeId) return;
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
type: 'scroll' as PluginSurfaceEvent['type'],
scrollTop: Math.max(0, Math.round(target.scrollTop)),
scrollLeft: Math.max(0, Math.round(target.scrollLeft)),
clientHeight: Math.max(0, Math.round(target.clientHeight)),
clientWidth: Math.max(0, Math.round(target.clientWidth)),
};
pendingScroll.set(nodeId, scrollEvent);
if (!scrollTimers.has(nodeId)) {
scrollTimers.set(nodeId, setTimeout(() => flushScroll(nodeId), SCROLL_THROTTLE_MS));
}
return;
}
const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined;
const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined;
const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined;
if (value !== undefined && value.length > 8192) return;
if (value !== undefined && value.length > MAX_EVENT_VALUE_LENGTH) return;
const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } : {};
onEventRef.current({ nodeId, type: event.type as PluginSurfaceEvent['type'], ...(value === undefined ? {} : { value }), ...(checkedValue === undefined ? {} : { checked: checkedValue }), ...keyboard, ...(values ? { values } : {}), ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}) });
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey }
: {};
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
pointerCoords = {
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
};
}
const selection =
event.type === 'input' || event.type === 'change' || event.type === 'keyup' || event.type === 'keydown'
? readSelectionRange(target, view)
: undefined;
onEventRef.current({
nodeId,
type: event.type as PluginSurfaceEvent['type'],
...(value === undefined ? {} : { value }),
...(checkedValue === undefined ? {} : { checked: checkedValue }),
...keyboard,
...(pointerCoords ?? {}),
...(selection ?? {}),
...(values ? { values } : {}),
...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}),
});
};
for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.addEventListener(event, listener, true);
return () => { for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.removeEventListener(event, listener, true); };
}, [shadow]);
return <div className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size]" />
{shadow && createPortal(<><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
</div>;
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
// into the plugin so its Command Palette and Save shortcuts work reliably.
const view = shadow.ownerDocument.defaultView;
const onWindowKeyDown = (event: KeyboardEvent) => {
if (depth !== 0 || event.defaultPrevented) return;
const surfaceEl = surfaceRef.current;
if (!surfaceEl || !surfaceEl.closest('[data-plugin-chrome="full-bleed"]')) return;
const rect = surfaceEl.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
const doc = surfaceEl.ownerDocument;
const hasHostModal = [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
const r = dialog.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (hasHostModal) return;
const active = doc.activeElement;
const focusInsideHostChrome = active
&& active !== doc.body
&& active !== doc.documentElement
&& !surfaceEl.contains(active)
&& !active.closest?.('[data-plugin-view-slot]');
if (focusInsideHostChrome) return;
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (sc !== 'mod+k' && sc !== 'mod+s') return;
const rootNodeId = (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode;
if (!rootNodeId) return;
event.preventDefault();
onEventRef.current({
nodeId: rootNodeId,
type: 'keydown',
key: event.key,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
altKey: event.altKey,
shiftKey: event.shiftKey,
});
};
view?.addEventListener('keydown', onWindowKeyDown, false);
return () => {
view?.removeEventListener('keydown', onWindowKeyDown, false);
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true);
};
}, [shadow, depth]);
return (
<SurfaceContext.Provider value={surfaceContextValue}>
<div ref={surfaceRef} className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/25" />
{shadow && createPortal(<><style>{SHADOW_BASE_SCROLLBAR_CSS}</style><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
</div>
</SurfaceContext.Provider>
);
}
+222 -28
View File
@@ -1,41 +1,235 @@
import React, { useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
const MIN_POPOVER_WIDTH = 160;
const MAX_POPOVER_WIDTH = 480;
const DEFAULT_POPOVER_WIDTH = 240;
const MIN_POPOVER_HEIGHT = 80;
const MAX_POPOVER_HEIGHT = 420;
export interface PluginViewPopoverProps {
anchor?: string;
anchorX?: number;
anchorY?: number;
width?: number;
maxHeight?: number;
open: boolean;
dismiss(): void;
children: React.ReactNode;
}
/** Geometry and dismissal belong to the host; content belongs to the plugin. */
export function PluginViewPopover({ anchor, open, dismiss, children }: {
anchor: string; open: boolean; dismiss(): void; children: React.ReactNode;
}) {
export function PluginViewPopover({
anchor,
anchorX,
anchorY,
width: requestedWidth,
maxHeight: requestedMaxHeight,
open,
dismiss,
children,
}: PluginViewPopoverProps) {
const marker = useRef<HTMLSpanElement>(null);
const panel = useRef<HTMLDivElement>(null);
const dismissRef = useRef(dismiss); dismissRef.current = dismiss;
const [position, setPosition] = useState<{ left: number; top: number; width: number } | null>(null);
const dismissRef = useRef(dismiss);
dismissRef.current = dismiss;
const [position, setPosition] = useState<{
left: number;
top: number;
width: number;
maxHeight: number;
} | null>(null);
useLayoutEffect(() => {
if (!open || !marker.current) { setPosition(null); return; }
if (!open || !marker.current) {
setPosition(null);
return;
}
const root = marker.current.getRootNode() as ShadowRoot;
const target = root.getElementById(anchor);
if (!(target instanceof marker.current.ownerDocument.defaultView!.HTMLElement)) return;
const doc = target.ownerDocument; const win = doc.defaultView!;
const doc = marker.current.ownerDocument;
const win = doc.defaultView!;
const surface = root.host instanceof win.HTMLElement
? root.host.closest('[data-plugin-remote-surface]')
: null;
const hasCursorCoords =
typeof anchorX === 'number' && Number.isFinite(anchorX)
&& typeof anchorY === 'number' && Number.isFinite(anchorY);
const target = anchor ? root.getElementById(anchor) : null;
const targetEl = target instanceof win.HTMLElement ? target : null;
if (!hasCursorCoords && !targetEl) {
setPosition(null);
return;
}
const resolveSurfaceBounds = () => {
const vp = {
left: 8,
top: 8,
right: Math.max(8, win.innerWidth - 8),
bottom: Math.max(8, win.innerHeight - 8),
};
if (!surface) return vp;
const sr = surface.getBoundingClientRect();
if (sr.width <= 0 || sr.height <= 0) return vp;
return {
left: Math.max(vp.left, sr.left + 4),
top: Math.max(vp.top, sr.top + 4),
right: Math.min(vp.right, sr.right - 4),
bottom: Math.min(vp.bottom, sr.bottom - 4),
};
};
const update = () => {
const bounds = target.getBoundingClientRect();
if (!bounds.width || !bounds.height) { setPosition(null); dismissRef.current(); return; }
const width = Math.min(360, Math.max(220, bounds.width), win.innerWidth - 16);
setPosition({ left: Math.max(8, Math.min(bounds.left, win.innerWidth - width - 8)), top: Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - 248)), width });
const clip = resolveSurfaceBounds();
const availableW = Math.max(MIN_POPOVER_WIDTH, clip.right - clip.left);
const availableH = Math.max(MIN_POPOVER_HEIGHT, clip.bottom - clip.top);
const boundedMaxHeight = Math.min(
availableH,
Math.max(
MIN_POPOVER_HEIGHT,
Math.min(
MAX_POPOVER_HEIGHT,
typeof requestedMaxHeight === 'number' && Number.isFinite(requestedMaxHeight)
? Math.round(requestedMaxHeight)
: MAX_POPOVER_HEIGHT,
),
),
);
let width: number;
let rawLeft: number;
let rawTop: number;
let anchorTop: number;
if (hasCursorCoords) {
const sr = surface?.getBoundingClientRect();
const originLeft = sr && sr.width > 0 ? sr.left : 0;
const originTop = sr && sr.height > 0 ? sr.top : 0;
const desiredW =
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
? requestedWidth
: DEFAULT_POPOVER_WIDTH;
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
rawLeft = originLeft + anchorX!;
rawTop = originTop + anchorY! + 2;
anchorTop = originTop + anchorY!;
} else {
const bounds = targetEl!.getBoundingClientRect();
if (!bounds.width || !bounds.height) {
setPosition(null);
dismissRef.current();
return;
}
const desiredW =
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
? requestedWidth
: Math.min(360, Math.max(220, bounds.width));
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
rawLeft = bounds.left;
rawTop = bounds.bottom + 4;
anchorTop = bounds.top;
}
const left = Math.max(clip.left, Math.min(rawLeft, clip.right - width));
const measuredHeight = panel.current?.getBoundingClientRect().height || 0;
const estimatedHeight = measuredHeight > 0 ? Math.min(measuredHeight, boundedMaxHeight) : Math.min(240, boundedMaxHeight);
let top = rawTop;
let effectiveMaxHeight = boundedMaxHeight;
const spaceBelow = clip.bottom - rawTop;
const spaceAbove = anchorTop - 4 - clip.top;
if (spaceBelow < estimatedHeight && spaceAbove > spaceBelow) {
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceAbove)));
top = Math.max(clip.top, anchorTop - 4 - Math.min(estimatedHeight, effectiveMaxHeight));
} else {
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceBelow)));
top = Math.max(clip.top, Math.min(rawTop, clip.bottom - Math.min(estimatedHeight, effectiveMaxHeight)));
}
setPosition({ left: Math.round(left), top: Math.round(top), width: Math.round(width), maxHeight: Math.round(effectiveMaxHeight) });
};
const dismissNow = () => {
setPosition(null);
dismissRef.current();
};
const key = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
dismissNow();
targetEl?.focus();
}
};
const outside = (event: PointerEvent) => {
const path = event.composedPath();
if (targetEl && path.includes(targetEl)) return;
if (panel.current && path.includes(panel.current)) return;
dismissNow();
};
const dismissNow = () => { setPosition(null); dismissRef.current(); };
const key = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); dismissNow(); target.focus(); } };
const outside = (event: PointerEvent) => { if (!event.composedPath().includes(target) && (!panel.current || !event.composedPath().includes(panel.current))) dismissNow(); };
const blocked = () => [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
const rect = dialog.getBoundingClientRect(); return rect.width > 0 && rect.height > 0;
const rect = dialog.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
if (blocked()) { dismissNow(); return; }
const dialogs = new win.MutationObserver(() => { if (blocked()) dismissNow(); });
dialogs.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['aria-modal', 'hidden', 'data-state'] });
const resize = new win.ResizeObserver(update); resize.observe(target); update();
win.addEventListener('resize', update); doc.addEventListener('scroll', update, true);
doc.addEventListener('keydown', key, true); doc.addEventListener('pointerdown', outside, true);
return () => { dialogs.disconnect(); resize.disconnect(); win.removeEventListener('resize', update); doc.removeEventListener('scroll', update, true); doc.removeEventListener('keydown', key, true); doc.removeEventListener('pointerdown', outside, true); };
}, [anchor, open]);
return <><span ref={marker} hidden />{open && position && marker.current && createPortal(
<div ref={panel} role="region" aria-label="Plugin menu" data-plugin-view-popover className="fixed z-[45] overflow-hidden rounded-lg border border-border bg-background shadow-xl" style={{ ...position, height: 240, maxHeight: 'calc(100vh - 16px)', contain: 'paint', isolation: 'isolate' }}>{children}</div>, marker.current.ownerDocument.body,
)}</>;
if (blocked()) {
dismissNow();
return;
}
const dialogs = new win.MutationObserver(() => {
if (blocked()) dismissNow();
});
dialogs.observe(doc.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['aria-modal', 'hidden', 'data-state'],
});
const resize = new win.ResizeObserver(update);
if (targetEl) resize.observe(targetEl);
if (surface) resize.observe(surface);
update();
win.addEventListener('resize', update);
doc.addEventListener('scroll', update, true);
doc.addEventListener('keydown', key, true);
doc.addEventListener('pointerdown', outside, true);
return () => {
dialogs.disconnect();
resize.disconnect();
win.removeEventListener('resize', update);
doc.removeEventListener('scroll', update, true);
doc.removeEventListener('keydown', key, true);
doc.removeEventListener('pointerdown', outside, true);
};
}, [anchor, anchorX, anchorY, requestedWidth, requestedMaxHeight, open]);
return (
<>
<span ref={marker} hidden />
{open && position && marker.current && createPortal(
<div
ref={panel}
role="region"
aria-label="Plugin menu"
data-plugin-view-popover=""
className="fixed z-[45] overflow-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-xl"
style={{
left: position.left,
top: position.top,
width: position.width,
maxHeight: position.maxHeight,
contain: 'paint',
isolation: 'isolate',
}}
>
{children}
</div>,
marker.current.ownerDocument.body,
)}
</>
);
}
@@ -0,0 +1,29 @@
import { Loader2 } from 'lucide-react';
import React, { Suspense, lazy } from 'react';
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
import type { PluginCodeEditorWidgetProps, PluginWidgetEventCallback } from './types';
const LazyPluginCodeEditorInner = lazy(() => import('./PluginCodeEditorInner'));
export interface PluginCodeEditorProps extends PluginCodeEditorWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
export function PluginCodeEditor(props: PluginCodeEditorProps) {
return (
<LazyLoadBoundary
name="Plugin SQL Editor"
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to load code editor.</div>}
>
<Suspense
fallback={(
<div className="flex h-full w-full items-center justify-center bg-background text-muted-foreground">
<Loader2 size={18} className="animate-spin" />
</div>
)}
>
<LazyPluginCodeEditorInner {...props} />
</Suspense>
</LazyLoadBoundary>
);
}
@@ -0,0 +1,460 @@
import Editor, { loader, type Monaco, type OnMount, useMonaco } from '@monaco-editor/react';
import { Loader2 } from 'lucide-react';
import React, { useCallback, useEffect, useId, useRef } from 'react';
import { useClipboardBackend } from '@/application/state/useClipboardBackend';
import {
buildMonacoPasteEdits,
pasteForMonacoEditorCommand,
readClipboardTextWithFallbacks,
} from '@/infrastructure/monaco/monacoClipboardPaste';
import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme';
import { matchWorkbenchShortcut } from './shortcuts';
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
import type {
PluginCodeEditorCompletionSchema,
PluginCodeEditorDiagnostic,
PluginCodeEditorWidgetProps,
PluginWidgetEventCallback,
} from './types';
const viteEnv = (import.meta.env ?? { BASE_URL: '/', DEV: false }) as { BASE_URL?: string; DEV?: boolean };
const monacoBasePath = viteEnv.DEV
? './node_modules/monaco-editor/min/vs'
: `${viteEnv.BASE_URL ?? '/'}monaco/vs`;
loader.config({ paths: { vs: monacoBasePath } });
const DEFAULT_SQL_KEYWORDS = [
'SELECT', 'FROM', 'WHERE', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE',
'CREATE', 'ALTER', 'DROP', 'TABLE', 'INDEX', 'VIEW', 'JOIN', 'LEFT JOIN', 'RIGHT JOIN',
'INNER JOIN', 'FULL OUTER JOIN', 'ON', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT',
'OFFSET', 'DISTINCT', 'AS', 'AND', 'OR', 'NOT', 'IN', 'IS NULL', 'IS NOT NULL',
'BETWEEN', 'LIKE', 'ILIKE', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'UNION', 'UNION ALL',
'WITH', 'EXPLAIN', 'ANALYZE', 'BEGIN', 'COMMIT', 'ROLLBACK', 'RETURNING', 'PRIMARY KEY',
'FOREIGN KEY', 'REFERENCES', 'DEFAULT', 'CASCADE', 'COUNT', 'SUM', 'AVG', 'MIN', 'MAX',
];
const SEVERITY_MAP: Record<NonNullable<PluginCodeEditorDiagnostic['severity']>, number> = {
hint: 1,
info: 2,
warning: 4,
error: 8,
};
export interface PluginCodeEditorInnerProps extends PluginCodeEditorWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
export default function PluginCodeEditorInner({
value = '',
language = 'sql',
readOnly = false,
placeholder,
lineNumbers = 'on',
minimap = false,
wordWrap = 'off',
completionSchema,
diagnostics,
height = '100%',
onWidgetEvent,
}: PluginCodeEditorInnerProps) {
const monaco = useMonaco();
const themeName = useNetcattyMonacoTheme(monaco ?? undefined);
const { readClipboardText: readClipboardTextFromBridge } = useClipboardBackend();
const editorId = useId();
const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`;
const wrapperRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<Parameters<OnMount>[0] | null>(null);
const monacoRef = useRef<Monaco | null>(null);
const handledKeyEventsRef = useRef<WeakSet<Event>>(new WeakSet());
const disposablesRef = useRef<Array<{ dispose(): void }>>([]);
const onWidgetEventRef = useRef(onWidgetEvent);
onWidgetEventRef.current = onWidgetEvent;
const schemaRef = useRef<PluginCodeEditorCompletionSchema | undefined>(completionSchema);
schemaRef.current = completionSchema;
const lastEmittedValueRef = useRef<string>(value);
const changeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selectionTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const readClipboardRef = useRef<() => Promise<string | null>>(() => Promise.resolve(null));
const readClipboardText = useCallback(async (): Promise<string | null> => (
readClipboardTextWithFallbacks({
readNavigator: navigator.clipboard?.readText
? () => navigator.clipboard.readText()
: undefined,
readBridge: readClipboardTextFromBridge,
})
), [readClipboardTextFromBridge]);
readClipboardRef.current = readClipboardText;
// Sync external value changes without disrupting cursor when value echoes local edits.
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
if (value === lastEmittedValueRef.current) return;
const model = editor.getModel();
if (!model || model.getValue() === value) {
lastEmittedValueRef.current = value;
return;
}
lastEmittedValueRef.current = value;
model.setValue(value);
}, [value]);
// Sync diagnostics markers cleanly.
useEffect(() => {
const editor = editorRef.current;
const monacoInstance = monacoRef.current ?? monaco;
if (!editor || !monacoInstance) return;
const model = editor.getModel();
if (!model) return;
const markers = (diagnostics ?? []).map((diag) => ({
startLineNumber: Math.max(1, Math.floor(diag.line || 1)),
startColumn: Math.max(1, Math.floor(diag.column || 1)),
endLineNumber: Math.max(1, Math.floor(diag.endLine ?? diag.line ?? 1)),
endColumn: Math.max(1, Math.floor(diag.endColumn ?? (diag.column ? diag.column + 1 : 2))),
message: diag.message,
severity: SEVERITY_MAP[diag.severity ?? 'error'] ?? 8,
}));
monacoInstance.editor.setModelMarkers(model, 'netcatty-plugin-diagnostics', markers);
}, [diagnostics, monaco]);
// Register local schema-aware CompletionItemProvider scoped to this editor's model URI.
useEffect(() => {
if (!monaco) return;
if (!['sql', 'pgsql', 'mysql'].includes(language)) return;
const disposable = monaco.languages.registerCompletionItemProvider(language, {
triggerCharacters: ['.', ' '],
provideCompletionItems(model, position) {
if (model.uri.toString() !== modelPath) return { suggestions: [] };
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn,
};
const linePrefix = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
const dotMatch = /["`]?([a-zA-Z_][\w$]*)["`]?\.\s*[\w$]*$/u.exec(linePrefix);
const schema = schemaRef.current;
const tables = schema?.tables ?? [];
const suggestions: Parameters<typeof monaco.languages.registerCompletionItemProvider>[1] extends {
provideCompletionItems: (...args: never[]) => infer R;
}
? R extends { suggestions: infer S }
? S
: never
: never = [] as never;
const list = suggestions as Array<{
label: string;
kind: number;
insertText: string;
detail?: string;
sortText?: string;
range: typeof range;
}>;
if (dotMatch) {
const qualifier = dotMatch[1].toLowerCase();
const aliases = extractSqlTableAliases(model.getValue());
const resolvedTableName = aliases.get(qualifier) ?? qualifier;
// Match either schema.table or table/alias.column
for (const tbl of tables) {
if (tbl.schema && tbl.schema.toLowerCase() === qualifier) {
list.push({
label: tbl.name,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: tbl.name,
detail: `${tbl.schema} table`,
sortText: `0_${tbl.name}`,
range,
});
}
if (tbl.name.toLowerCase() === resolvedTableName.toLowerCase()) {
for (const col of tbl.columns ?? []) {
list.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
detail: col.type ? `${tbl.name}.${col.name} (${col.type})` : `${tbl.name}.${col.name}`,
sortText: `0_${col.name}`,
range,
});
}
}
}
return { suggestions: list as never };
}
const seenColumns = new Set<string>();
for (const tbl of tables) {
const label = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
list.push({
label,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: label,
detail: tbl.schema ? `Table (${tbl.schema})` : 'Table',
sortText: `1_${tbl.name}`,
range,
});
if (tbl.schema) {
list.push({
label: tbl.name,
kind: monaco.languages.CompletionItemKind.Struct,
insertText: tbl.name,
detail: `Table (${tbl.schema})`,
sortText: `1_${tbl.name}`,
range,
});
}
for (const col of tbl.columns ?? []) {
const key = `${col.name}:${tbl.name}`;
if (seenColumns.has(key)) continue;
seenColumns.add(key);
list.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
detail: col.type ? `${tbl.name} (${col.type})` : tbl.name,
sortText: `2_${col.name}`,
range,
});
}
}
for (const fn of schema?.functions ?? []) {
list.push({
label: fn.name,
kind: monaco.languages.CompletionItemKind.Function,
insertText: fn.insertText ?? `${fn.name}()`,
detail: fn.detail ?? 'Function',
sortText: `3_${fn.name}`,
range,
});
}
const keywords = schema?.keywords?.length ? schema.keywords : DEFAULT_SQL_KEYWORDS;
for (const kw of keywords) {
list.push({
label: kw,
kind: monaco.languages.CompletionItemKind.Keyword,
insertText: kw,
detail: 'Keyword',
sortText: `4_${kw}`,
range,
});
}
return { suggestions: list as never };
},
});
return () => disposable.dispose();
}, [language, modelPath, monaco]);
useEffect(() => () => {
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
for (const d of disposablesRef.current.splice(0)) {
try { d.dispose(); } catch {}
}
editorRef.current = null;
}, []);
const handleMount: OnMount = useCallback((editor, monacoInstance) => {
for (const d of disposablesRef.current.splice(0)) {
try { d.dispose(); } catch {}
}
editorRef.current = editor;
monacoRef.current = monacoInstance;
const emitExecute = () => {
const model = editor.getModel();
if (!model) return;
const fullValue = model.getValue();
const sel = editor.getSelection();
const selectedText = sel && !sel.isEmpty() ? model.getValueInRange(sel) : '';
const cursorOffset = sel ? model.getOffsetAt(sel.getPosition()) : 0;
const currentStatement = selectedText.trim()
? selectedText.trim()
: extractCurrentSqlStatement(fullValue, cursorOffset);
onWidgetEventRef.current('execute', {
value: fullValue,
selectedText,
currentStatement,
});
};
const emitFormat = () => {
const model = editor.getModel();
if (!model) return;
onWidgetEventRef.current('format', { value: model.getValue() });
};
const handlePaste = async () => {
const text = await readClipboardRef.current();
if (text === null) {
editor.trigger('keyboard', 'editor.action.clipboardPasteAction', null);
return;
}
if (!text) return;
const selections = editor.getSelections();
if (!selections || selections.length === 0) return;
editor.executeEdits('netcatty-plugin-paste', buildMonacoPasteEdits(text, selections));
editor.focus();
};
disposablesRef.current.push(
editor.addAction({
id: 'netcatty.pluginCodeEditor.execute',
label: 'Run Query',
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter],
run: emitExecute,
}),
editor.addAction({
id: 'netcatty.pluginCodeEditor.formatAlt',
label: 'Format Query',
keybindings: [
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.Alt | monacoInstance.KeyCode.KeyF,
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyF,
],
run: emitFormat,
}),
editor.onKeyDown((monacoKeyEvent) => {
const nativeEvent = monacoKeyEvent.browserEvent;
if (handledKeyEventsRef.current.has(nativeEvent)) return;
const shortcut = matchWorkbenchShortcut(nativeEvent, { includeUndoRedo: false });
if (!shortcut) return;
if (shortcut === 'escape') {
const target = nativeEvent.target as Element | null;
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
handledKeyEventsRef.current.add(nativeEvent);
onWidgetEventRef.current('shortcut', { shortcut });
return;
}
handledKeyEventsRef.current.add(nativeEvent);
monacoKeyEvent.preventDefault();
monacoKeyEvent.stopPropagation();
nativeEvent.preventDefault();
nativeEvent.stopImmediatePropagation?.();
nativeEvent.stopPropagation();
onWidgetEventRef.current('shortcut', { shortcut });
}),
editor.addAction({
id: 'netcatty.pluginCodeEditor.paste',
label: 'Paste',
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV],
run: () => {
void pasteForMonacoEditorCommand({
activeElement: document.activeElement,
readClipboardText: () => readClipboardRef.current(),
pasteIntoEditor: () => handlePaste(),
});
},
}),
editor.onDidChangeCursorSelection(() => {
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
selectionTimerRef.current = setTimeout(() => {
const model = editor.getModel();
const sel = editor.getSelection();
if (!model || !sel) return;
const selectionStart = model.getOffsetAt(sel.getStartPosition());
const selectionEnd = model.getOffsetAt(sel.getEndPosition());
const selectedText = sel.isEmpty() ? '' : model.getValueInRange(sel);
onWidgetEventRef.current('selection', { selectionStart, selectionEnd, selectedText });
}, 60);
}),
);
requestAnimationFrame(() => editor.layout());
}, []);
const handleChange = useCallback((nextValue: string | undefined) => {
const next = nextValue ?? '';
lastEmittedValueRef.current = next;
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
changeTimerRef.current = setTimeout(() => {
onWidgetEventRef.current('change', { value: next });
}, 80);
}, []);
// Native capture listener runs BEFORE Monaco's textarea / chord-prefix handler
// so Cmd/Ctrl+K never enters Monaco's chord state and always reaches the plugin once.
useEffect(() => {
const el = wrapperRef.current;
if (!el) return;
const onNativeKeyDownCapture = (event: KeyboardEvent) => {
if (handledKeyEventsRef.current.has(event)) return;
// Keep Monaco's native Cmd/Ctrl+Z undo/redo intact while forwarding global workbench shortcuts.
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (!shortcut) return;
if (shortcut === 'escape') {
const target = event.target as Element | null;
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
handledKeyEventsRef.current.add(event);
onWidgetEventRef.current('shortcut', { shortcut });
return;
}
handledKeyEventsRef.current.add(event);
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
onWidgetEventRef.current('shortcut', { shortcut });
};
el.addEventListener('keydown', onNativeKeyDownCapture, true);
return () => el.removeEventListener('keydown', onNativeKeyDownCapture, true);
}, []);
const resolvedHeight = typeof height === 'number' ? `${height}px` : height;
return (
<div
ref={wrapperRef}
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background"
style={resolvedHeight !== '100%' ? { height: resolvedHeight } : undefined}
data-plugin-code-editor=""
>
<Editor
path={modelPath}
height={resolvedHeight}
language={language}
defaultValue={value}
onChange={handleChange}
onMount={handleMount}
theme={themeName}
loading={(
<div className="absolute inset-0 flex items-center justify-center bg-background">
<Loader2 size={18} className="animate-spin text-muted-foreground" />
</div>
)}
options={{
readOnly,
contextmenu: false,
minimap: { enabled: minimap },
fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
fontSize: 13,
fontLigatures: true,
lineNumbers,
wordWrap,
scrollBeyondLastLine: false,
automaticLayout: true,
tabSize: 2,
insertSpaces: true,
folding: true,
renderLineHighlight: 'line',
padding: { top: 8, bottom: 8 },
bracketPairColorization: { enabled: true },
quickSuggestions: { other: true, comments: false, strings: false },
suggestOnTriggerCharacters: true,
}}
/>
{placeholder && !value ? (
<span
aria-hidden="true"
className="pointer-events-none absolute left-[56px] top-2 z-10 font-mono text-[13px] text-muted-foreground/70"
>
{placeholder}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,693 @@
import { useVirtualizer } from '@tanstack/react-virtual';
import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, KeyRound, Link2, Loader2 } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
PluginDataGridColumn,
PluginDataGridRow,
PluginDataGridWidgetProps,
PluginWidgetEventCallback,
} from './types';
const ROW_HEIGHT = 30;
const HEADER_HEIGHT = 34;
const GUTTER_WIDTH = 64;
const DEFAULT_COL_WIDTH = 156;
const MIN_COL_WIDTH = 68;
const MAX_COL_WIDTH = 640;
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
function readCellValue(row: PluginDataGridRow, col: PluginDataGridColumn, colIndex: number): unknown {
if (Array.isArray(row)) return row[colIndex];
if (row && typeof row === 'object') return row[col.name];
return undefined;
}
function formatCellDisplay(value: unknown): string {
if (value === null || value === undefined) return '';
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean {
if (typeof value === 'number') return true;
if (!col.type) return false;
return /\b(int|bigint|smallint|tinyint|decimal|numeric|float|double|real|number|serial)\b/i.test(col.type);
}
export function PluginDataGrid({
columns = [],
rows = [],
hiddenColumns,
dirtyCells,
deletedRowIndices,
insertedRows = [],
selectedRowIndices,
sort = null,
editable = false,
loading = false,
emptyMessage = 'No rows returned',
onWidgetEvent,
}: PluginDataGridProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const editInputRef = useRef<HTMLInputElement>(null);
const [colWidths, setColWidths] = useState<Record<string, number>>({});
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
const [editingCell, setEditingCell] = useState<{
rowIndex: number;
colIndex: number;
colName: string;
draft: string;
} | null>(null);
const [lastSelectedRow, setLastSelectedRow] = useState<number | null>(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]);
useEffect(() => {
if (editingCell) {
const focusInput = () => {
editInputRef.current?.focus();
editInputRef.current?.select();
};
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(focusInput);
} else {
focusInput();
}
}
}, [editingCell?.rowIndex, editingCell?.colIndex]);
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) => {
setEditingCell(null);
onWidgetEvent('cellEdit', {
rowIndex: cell.rowIndex,
colName: cell.colName,
value: asNull ? null : cell.draft,
isNull: asNull,
});
}, [onWidgetEvent]);
const beginEdit = useCallback((rowIndex: number, visibleColIndex: number) => {
if (!editable || deletedSet.has(rowIndex)) return;
const entry = visibleCols[visibleColIndex];
if (!entry) return;
const { value } = getEffectiveValue(rowIndex, entry.col, entry.origIndex);
setActiveCell({ rowIndex, colIndex: visibleColIndex });
setEditingCell({
rowIndex,
colIndex: visibleColIndex,
colName: entry.col.name,
draft: value === null || value === undefined ? '' : formatCellDisplay(value),
});
}, [editable, deletedSet, visibleCols, getEffectiveValue]);
const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => {
const next = new Set(selectedSet);
if (shiftKey && lastSelectedRow !== null) {
const lo = Math.min(lastSelectedRow, rowIndex);
const hi = Math.max(lastSelectedRow, rowIndex);
for (let i = lo; i <= hi; i += 1) next.add(i);
} else if (next.has(rowIndex)) {
next.delete(rowIndex);
} else {
next.add(rowIndex);
}
setLastSelectedRow(rowIndex);
onWidgetEvent('rowSelect', { selectedRowIndices: [...next].sort((a, b) => a - b) });
}, [selectedSet, lastSelectedRow, onWidgetEvent]);
const toggleSelectAll = useCallback(() => {
if (totalRows === 0) return;
const allSelected = selectedSet.size >= totalRows;
const next = allSelected ? [] : Array.from({ length: totalRows }, (_, i) => i);
onWidgetEvent('rowSelect', { selectedRowIndices: next });
}, [totalRows, selectedSet.size, onWidgetEvent]);
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
if (col.sortable === false) return;
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
}, [sort, onWidgetEvent]);
const startResizeColumn = useCallback((event: React.PointerEvent<HTMLDivElement>, col: PluginDataGridColumn) => {
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
const startWidth = getColWidth(col);
const target = event.currentTarget;
try { target.setPointerCapture(event.pointerId); } catch {}
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 {}
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 {}
onWidgetEvent('cellCopy', {
text,
rowIndex: activeCell?.rowIndex ?? selectedIndices[0],
colName: activeCell ? visibleCols[activeCell.colIndex]?.col.name ?? null : null,
rowIndices: selectedIndices,
});
return true;
}
if (activeCell) {
const entry = visibleCols[activeCell.colIndex];
if (!entry) return false;
const { value } = getEffectiveValue(activeCell.rowIndex, entry.col, entry.origIndex);
const text = value === null || value === undefined ? 'NULL' : formatCellDisplay(value);
try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {}
onWidgetEvent('cellCopy', {
text,
rowIndex: activeCell.rowIndex,
colName: entry.col.name,
rowIndices: [activeCell.rowIndex],
});
return true;
}
return false;
}, [selectedSet, visibleCols, activeCell, getEffectiveValue, onWidgetEvent]);
const handleGridKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
const mod = event.metaKey || event.ctrlKey;
// While editing an inline cell input, only forward Cmd/Ctrl+K and Cmd/Ctrl+S.
if (editingCell) {
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
if (shortcut === 'mod+k' || shortcut === 'mod+s') {
event.preventDefault();
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
}
return;
}
// Global workbench shortcuts + grid Undo/Redo
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
if (shortcut) {
if (shortcut !== 'escape') {
event.preventDefault();
}
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
return;
}
// Cmd/Ctrl+C copies active cell or selected rows
if (mod && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'c') {
if (copySelectionOrActiveCell()) {
event.preventDefault();
event.stopPropagation();
}
return;
}
if (!activeCell || visibleCols.length === 0 || totalRows === 0) return;
const { rowIndex, colIndex } = activeCell;
if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) {
event.preventDefault();
setActiveCell({ rowIndex: rowIndex + 1, colIndex });
rowVirtualizer.scrollToIndex(rowIndex + 1);
} else if (event.key === 'ArrowUp' && rowIndex > 0) {
event.preventDefault();
setActiveCell({ rowIndex: rowIndex - 1, colIndex });
rowVirtualizer.scrollToIndex(rowIndex - 1);
} else if (event.key === 'ArrowRight' && colIndex + 1 < visibleCols.length) {
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex + 1 });
colVirtualizer.scrollToIndex(colIndex + 1);
} else if (event.key === 'ArrowLeft' && colIndex > 0) {
event.preventDefault();
setActiveCell({ rowIndex, colIndex: colIndex - 1 });
colVirtualizer.scrollToIndex(colIndex - 1);
} else if ((event.key === 'Enter' || event.key === 'F2') && editable) {
event.preventDefault();
beginEdit(rowIndex, colIndex);
} else if ((event.key === 'Delete' || event.key === 'Backspace') && editable && !deletedSet.has(rowIndex)) {
const entry = visibleCols[colIndex];
if (entry && entry.col.nullable !== false) {
event.preventDefault();
onWidgetEvent('cellEdit', {
rowIndex,
colName: entry.col.name,
value: null,
isNull: true,
});
}
}
}, [
editingCell,
activeCell,
visibleCols,
totalRows,
rowVirtualizer,
colVirtualizer,
editable,
deletedSet,
beginEdit,
copySelectionOrActiveCell,
onWidgetEvent,
]);
const virtualRows = rowVirtualizer.getVirtualItems();
const virtualCols = colVirtualizer.getVirtualItems();
const totalWidth = GUTTER_WIDTH + colVirtualizer.getTotalSize();
const totalHeight = rowVirtualizer.getTotalSize();
const allSelected = totalRows > 0 && selectedSet.size >= totalRows;
return (
<div
className="relative flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground select-none"
data-plugin-data-grid=""
tabIndex={0}
onKeyDown={handleGridKeyDown}
>
{loading && (
<div className="pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center justify-end px-2 py-1">
<span className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background/95 px-2 py-0.5 text-[11px] text-muted-foreground shadow-sm">
<Loader2 size={12} className="animate-spin" />
Loading...
</span>
</div>
)}
<div ref={scrollRef} className="relative h-full w-full min-h-0 flex-1 overflow-auto">
{visibleCols.length === 0 ? (
<div className="flex h-full w-full items-center justify-center p-6 text-xs text-muted-foreground">
{emptyMessage}
</div>
) : (
<div style={{ width: totalWidth, minWidth: '100%', position: 'relative' }}>
{/* Sticky Header */}
<div
role="row"
className="sticky top-0 z-30 flex border-b border-border bg-muted text-[11px] font-medium text-foreground"
style={{ height: HEADER_HEIGHT, width: totalWidth, minWidth: '100%' }}
>
<div
className="sticky left-0 z-40 flex shrink-0 items-center justify-between border-r border-border bg-muted px-2 text-[10px] text-muted-foreground"
style={{ width: GUTTER_WIDTH, height: HEADER_HEIGHT }}
>
<input
type="checkbox"
aria-label="Select all rows"
checked={allSelected}
onChange={toggleSelectAll}
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
/>
<span className="font-mono">#</span>
</div>
<div className="relative flex-1" style={{ height: HEADER_HEIGHT }}>
{virtualCols.map((vCol) => {
const colEntry = visibleCols[vCol.index];
if (!colEntry) return null;
const { col } = colEntry;
const isSorted = sort?.column === col.name;
const sortable = col.sortable !== false;
return (
<div
key={col.name}
role="columnheader"
data-col-name={col.name}
className="group absolute top-0 bottom-0 flex items-center justify-between gap-1 border-r border-border/70 px-2.5"
style={{
left: vCol.start,
width: vCol.size,
}}
>
<button
type="button"
disabled={!sortable}
onClick={() => handleSortClick(col)}
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
title={col.foreignKey
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
: col.type ? `${col.name} (${col.type})` : col.name}
>
{col.primaryKey && (
<KeyRound size={11} className="shrink-0 text-amber-500" aria-label="Primary key" />
)}
{col.foreignKey && (
<Link2 size={11} className="shrink-0 text-blue-500" aria-label="Foreign key" />
)}
<span className="truncate font-medium">{col.name}</span>
{col.type && (
<span className="truncate font-mono text-[10px] font-normal text-muted-foreground">
{col.type}
</span>
)}
</button>
{sortable && (
<span className="shrink-0 text-muted-foreground/70">
{isSorted ? (
sort.direction === 'asc' ? <ArrowUp size={11} className="text-primary" /> : <ArrowDown size={11} className="text-primary" />
) : (
<ArrowUpDown size={10} className="opacity-0 group-hover:opacity-70 transition-opacity" />
)}
</span>
)}
<div
role="separator"
aria-orientation="vertical"
onPointerDown={(e) => startResizeColumn(e, col)}
className="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/60"
/>
</div>
);
})}
</div>
</div>
{/* Virtualized Rows Body */}
{totalRows === 0 ? (
<div className="flex h-40 w-full items-center justify-center text-xs text-muted-foreground">
{emptyMessage}
</div>
) : (
<div style={{ height: totalHeight, width: totalWidth, minWidth: '100%', position: 'relative' }}>
{virtualRows.map((vRow) => {
const rowIndex = vRow.index;
const entry = getRowAt(rowIndex);
if (!entry) return null;
const isDeleted = deletedSet.has(rowIndex);
const isSelected = selectedSet.has(rowIndex);
const isInserted = entry.isInserted;
const rowBg = isDeleted
? 'bg-destructive/10 text-destructive/80 line-through'
: isInserted
? 'bg-emerald-500/10'
: isSelected
? 'bg-primary/10'
: rowIndex % 2 === 1
? 'bg-muted/20'
: 'bg-background';
return (
<div
key={rowIndex}
role="row"
data-row-index={rowIndex}
className={`absolute left-0 flex border-b border-border/50 hover:bg-muted/50 ${rowBg}`}
style={{
top: vRow.start,
height: vRow.size,
width: totalWidth,
minWidth: '100%',
}}
>
{/* Sticky Gutter */}
<div
className="sticky left-0 z-10 flex shrink-0 items-center justify-between border-r border-border/70 bg-background px-2 font-mono text-[10px] tabular-nums text-muted-foreground"
style={{ width: GUTTER_WIDTH, height: ROW_HEIGHT }}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, visibleCols[0]?.col.name ?? '')}
>
<input
type="checkbox"
aria-label={`Select row ${rowIndex + 1}`}
checked={isSelected}
onChange={() => {}}
onClick={(e) => {
e.stopPropagation();
toggleRowSelection(rowIndex, e.shiftKey);
}}
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
/>
<span className={isInserted ? 'font-bold text-emerald-500' : ''}>
{isInserted ? '+' : rowIndex + 1}
</span>
</div>
{/* Virtualized Cells */}
<div className="relative z-0 flex-1 overflow-hidden" style={{ height: ROW_HEIGHT }}>
{virtualCols.map((vCol) => {
const visibleColIndex = vCol.index;
const colEntry = visibleCols[visibleColIndex];
if (!colEntry) return null;
const { col, origIndex } = colEntry;
const { value, isDirty } = getEffectiveValue(rowIndex, col, origIndex);
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === visibleColIndex;
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === visibleColIndex;
const isNull = value === null || value === undefined;
const numeric = !isNull && isNumericColumn(col, value);
const fk = col.foreignKey;
return (
<div
key={col.name}
role="gridcell"
data-row-index={rowIndex}
data-col-name={col.name}
data-dirty={isDirty ? 'true' : undefined}
className={`group/cell absolute top-0 bottom-0 flex items-center gap-1 border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
isDirty ? 'bg-amber-500/15 ring-1 ring-inset ring-amber-500/50' : ''
} ${isActive ? 'ring-2 ring-inset ring-primary z-[5]' : ''} ${
numeric ? 'justify-end' : 'justify-start'
}`}
style={{ left: vCol.start, width: vCol.size }}
onClick={() => {
setActiveCell({ rowIndex, colIndex: visibleColIndex });
onWidgetEvent('cellSelect', {
rowIndex,
colName: col.name,
value: value === undefined ? null : value,
});
}}
onDoubleClick={() => {
if (editable && !isDeleted) {
beginEdit(rowIndex, visibleColIndex);
} else {
onWidgetEvent('cellDoubleClick', {
rowIndex,
colName: col.name,
value: value === undefined ? null : value,
});
}
}}
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)}
>
{isEditing ? (
<div
className="flex h-full w-full items-center gap-1"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
<input
ref={editInputRef}
type="text"
value={editingCell.draft}
onChange={(e) => setEditingCell({ ...editingCell, draft: e.target.value })}
onKeyDown={(e) => {
const sc = matchWorkbenchShortcut(e, { includeUndoRedo: false });
if (sc === 'mod+k' || sc === 'mod+s') {
e.preventDefault();
e.stopPropagation();
onWidgetEvent('shortcut', { shortcut: sc });
return;
}
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitEdit(editingCell, false);
} else if (e.key === 'Escape') {
e.preventDefault();
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;
setTimeout(() => {
setEditingCell((curr) => {
if (curr && curr.rowIndex === snapshot.rowIndex && curr.colIndex === snapshot.colIndex) {
onWidgetEvent('cellEdit', {
rowIndex: curr.rowIndex,
colName: curr.colName,
value: curr.draft,
isNull: false,
});
return null;
}
return curr;
});
}, 0);
}}
className="h-6 min-w-0 flex-1 rounded border border-primary bg-background px-1.5 font-mono text-[12px] text-foreground outline-none"
/>
{col.nullable !== false && (
<button
type="button"
onMouseDown={(e) => {
e.preventDefault();
commitEdit(editingCell, true);
}}
className="shrink-0 rounded border border-border bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
title="Set value to NULL"
>
NULL
</button>
)}
</div>
) : isNull ? (
<span className="inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] italic text-muted-foreground">
NULL
</span>
) : typeof value === 'boolean' ? (
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${
value
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
: 'bg-muted text-muted-foreground'
}`}
>
{value ? 'true' : 'false'}
</span>
) : (
<span className="truncate" title={formatCellDisplay(value)}>
{formatCellDisplay(value)}
</span>
)}
{!isEditing && !isNull && fk && (
<button
type="button"
data-fk-jump=""
aria-label={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column}`}
title={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column} = ${formatCellDisplay(value)}`}
onClick={(e) => {
e.stopPropagation();
onWidgetEvent('fkJump', {
rowIndex,
colName: col.name,
value,
targetTable: fk.table,
targetColumn: fk.column,
...(fk.schema ? { targetSchema: fk.schema } : {}),
});
}}
className="ml-auto shrink-0 inline-flex h-4 w-4 items-center justify-center rounded text-blue-500 opacity-0 transition-opacity hover:bg-blue-500/15 group-hover/cell:opacity-100 focus:opacity-100"
>
<ArrowUpRight size={11} />
</button>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
)}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,563 @@
import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
abbreviateSqlType,
buildStandaloneErSvg,
ER_CARD_HEADER_HEIGHT,
ER_CARD_ROW_HEIGHT,
ER_CARD_WIDTH,
erCardHeight,
erTableKey,
} from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
PluginErCanvasWidgetProps,
PluginErTable,
PluginWidgetEventCallback,
} from './types';
const GRID_GAP_X = 80;
const GRID_GAP_Y = 56;
const MIN_ZOOM = 0.25;
const MAX_ZOOM = 2.5;
export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: number; y: number }> {
const result: Record<string, { x: number; y: number }> = {};
const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1))));
const colY = Array.from({ length: colsPerRow }, () => 40);
tables.forEach((table, index) => {
const key = erTableKey(table);
if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) {
result[key] = { x: table.x, y: table.y };
return;
}
const colIdx = index % colsPerRow;
const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X);
const y = colY[colIdx];
result[key] = { x, y };
colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y;
});
return result;
}
function resolveCanvasPalette(el: HTMLElement | null) {
const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
const readVar = (name: string, fallback: string) => {
if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return fallback;
const val = window.getComputedStyle(el).getPropertyValue(name).trim();
return val ? `hsl(${val})` : fallback;
};
return {
background: readVar('--background', isDark ? '#0f1117' : '#ffffff'),
card: readVar('--card', isDark ? '#161922' : '#ffffff'),
cardForeground: readVar('--card-foreground', isDark ? '#f1f5f9' : '#0f172a'),
muted: readVar('--muted', isDark ? '#1e2230' : '#f1f5f9'),
mutedForeground: readVar('--muted-foreground', isDark ? '#94a3b8' : '#64748b'),
border: readVar('--border', isDark ? '#2a3040' : '#e2e8f0'),
primary: readVar('--primary', isDark ? '#38bdf8' : '#2563eb'),
};
}
export function PluginErCanvas({
tables = [],
relations = [],
onWidgetEvent,
}: PluginErCanvasProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables));
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [selectedTable, setSelectedTable] = useState<string | null>(null);
const [hoveredRelation, setHoveredRelation] = useState<number | null>(null);
const [panning, setPanning] = useState(false);
const tableSignature = useMemo(
() => tables.map((t) => `${erTableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
[tables],
);
useEffect(() => {
setPositions((prev) => {
const defaults = computeInitialPositions(tables);
const next: Record<string, { x: number; y: number }> = {};
for (const tbl of tables) {
const key = erTableKey(tbl);
next[key] = prev[key] ?? defaults[key];
}
return next;
});
}, [tableSignature, tables]);
const tableLookup = useMemo(() => {
const byKey = new Map<string, PluginErTable>();
const byName = new Map<string, PluginErTable>();
for (const tbl of tables) {
byKey.set(erTableKey(tbl), tbl);
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
}
return { byKey, byName };
}, [tables]);
const resolveTable = useCallback((ref: string): PluginErTable | undefined => (
tableLookup.byKey.get(ref) ?? tableLookup.byName.get(ref)
), [tableLookup]);
const fitToView = useCallback(() => {
const el = containerRef.current;
if (!el || tables.length === 0) {
setViewport({ x: 0, y: 0, zoom: 1 });
return;
}
const rect = el.getBoundingClientRect();
if (!rect.width || !rect.height) return;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
minX = Math.min(minX, pos.x);
minY = Math.min(minY, pos.y);
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
}
const contentW = Math.max(1, maxX - minX);
const contentH = Math.max(1, maxY - minY);
const pad = 48;
const zoom = Math.max(
MIN_ZOOM,
Math.min(1.15, Math.min((rect.width - pad * 2) / contentW, (rect.height - pad * 2) / contentH)),
);
const x = (rect.width - contentW * zoom) / 2 - minX * zoom;
const y = (rect.height - contentH * zoom) / 2 - minY * zoom;
setViewport({ x, y, zoom });
}, [tables, positions]);
useEffect(() => {
if (typeof requestAnimationFrame !== 'function') {
fitToView();
return;
}
const frame = requestAnimationFrame(fitToView);
return () => cancelAnimationFrame(frame);
}, [tableSignature]);
const handleWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
event.preventDefault();
const el = containerRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
const factor = event.deltaY < 0 ? 1.1 : 0.9;
setViewport((prev) => {
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
const scale = nextZoom / prev.zoom;
return {
zoom: nextZoom,
x: mouseX - (mouseX - prev.x) * scale,
y: mouseY - (mouseY - prev.y) * scale,
};
});
}, []);
const handleCanvasPointerDown = useCallback((event: React.PointerEvent<SVGSVGElement>) => {
if (event.button !== 0) return;
if ((event.target as Element).closest?.('[data-er-table]')) return;
event.preventDefault();
containerRef.current?.focus();
const startX = event.clientX;
const startY = event.clientY;
const initialX = viewport.x;
const initialY = viewport.y;
setPanning(true);
const onMove = (moveEvent: PointerEvent) => {
setViewport((prev) => ({
...prev,
x: initialX + (moveEvent.clientX - startX),
y: initialY + (moveEvent.clientY - startY),
}));
};
const onUp = () => {
setPanning(false);
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [viewport.x, viewport.y]);
const startCardDrag = useCallback((event: React.PointerEvent<SVGGElement>, table: PluginErTable) => {
if (event.button !== 0) return;
event.stopPropagation();
containerRef.current?.focus();
const key = erTableKey(table);
const startX = event.clientX;
const startY = event.clientY;
const origin = positions[key] ?? { x: 0, y: 0 };
const zoom = viewport.zoom;
let moved = false;
const onMove = (moveEvent: PointerEvent) => {
const dx = moveEvent.clientX - startX;
const dy = moveEvent.clientY - startY;
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true;
if (!moved) return;
setPositions((prev) => ({
...prev,
[key]: { x: Math.round(origin.x + dx / zoom), y: Math.round(origin.y + dy / zoom) },
}));
};
const onUp = () => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
if (!moved) {
setSelectedTable(key);
onWidgetEvent('tableClick', {
table: table.name,
...(table.schema ? { schema: table.schema } : {}),
});
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [positions, viewport.zoom, onWidgetEvent]);
const handleCardDoubleClick = useCallback((event: React.MouseEvent<SVGGElement>, table: PluginErTable) => {
event.stopPropagation();
onWidgetEvent('tableDoubleClick', {
table: table.name,
...(table.schema ? { schema: table.schema } : {}),
});
}, [onWidgetEvent]);
const zoomBy = useCallback((factor: number) => {
const el = containerRef.current;
const rect = el?.getBoundingClientRect();
const cx = rect ? rect.width / 2 : 300;
const cy = rect ? rect.height / 2 : 200;
setViewport((prev) => {
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
const scale = nextZoom / prev.zoom;
return {
zoom: nextZoom,
x: cx - (cx - prev.x) * scale,
y: cy - (cy - prev.y) * scale,
};
});
}, []);
const resetLayout = useCallback(() => {
setPositions(computeInitialPositions(tables));
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(fitToView);
} else {
fitToView();
}
}, [tables, fitToView]);
const handleExportSvg = useCallback(() => {
const palette = resolveCanvasPalette(containerRef.current);
const svg = buildStandaloneErSvg(tables, relations, positions, palette);
onWidgetEvent('exportSvg', { svg });
}, [tables, relations, positions, onWidgetEvent]);
const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
if (!shortcut) return;
if (shortcut !== 'escape') event.preventDefault();
event.stopPropagation();
onWidgetEvent('shortcut', { shortcut });
}, [onWidgetEvent]);
return (
<div
ref={containerRef}
data-plugin-er-canvas=""
tabIndex={0}
onWheel={handleWheel}
onKeyDown={handleKeyDown}
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none outline-none"
>
{/* Floating Canvas Controls */}
<div className="absolute right-3 top-3 z-20 flex items-center gap-1 rounded-lg border border-border bg-background/95 p-1 shadow-sm backdrop-blur-sm">
<button
type="button"
onClick={() => zoomBy(1.2)}
aria-label="Zoom in"
title="Zoom in"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
>
<ZoomIn size={13} />
</button>
<span className="min-w-[40px] text-center font-mono text-[11px] tabular-nums text-muted-foreground">
{Math.round(viewport.zoom * 100)}%
</span>
<button
type="button"
onClick={() => zoomBy(1 / 1.2)}
aria-label="Zoom out"
title="Zoom out"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
>
<ZoomOut size={13} />
</button>
<div className="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
onClick={fitToView}
aria-label="Fit to view"
title="Fit to view"
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
>
<Maximize2 size={12} />
Fit
</button>
<button
type="button"
onClick={resetLayout}
aria-label="Reset layout"
title="Reset layout"
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
>
<RotateCcw size={12} />
</button>
<div className="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
data-er-export-svg=""
onClick={handleExportSvg}
aria-label="Export SVG"
title="Export SVG"
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
>
<Download size={12} />
Export SVG
</button>
</div>
{tables.length === 0 ? (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
No tables to visualize
</div>
) : (
<svg
className={`h-full w-full ${panning ? 'cursor-grabbing' : 'cursor-grab'}`}
onPointerDown={handleCanvasPointerDown}
>
<defs>
<pattern id="nc-er-dots" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="1" cy="1" r="1" fill="hsl(var(--border))" opacity="0.55" />
</pattern>
<filter id="nc-er-shadow" x="-10%" y="-10%" width="120%" height="125%">
<feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#000000" floodOpacity="0.14" />
</filter>
</defs>
<rect width="100%" height="100%" fill="url(#nc-er-dots)" />
<g transform={`translate(${viewport.x}, ${viewport.y}) scale(${viewport.zoom})`}>
{/* Foreign Key Bezier Curves */}
{relations.map((rel, idx) => {
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) return null;
const fromKey = erTableKey(fromTable);
const toKey = erTableKey(toTable);
const fromPos = positions[fromKey] ?? { x: 0, y: 0 };
const toPos = positions[toKey] ?? { x: 0, y: 0 };
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const fromCenter = fromPos.x + ER_CARD_WIDTH / 2;
const toCenter = toPos.x + ER_CARD_WIDTH / 2;
const goRight = toCenter >= fromCenter;
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
const c1x = goRight ? x1 + dx : x1 - dx;
const c2x = goRight ? x2 - dx : x2 + dx;
const isHovered = hoveredRelation === idx;
const highlighted = isHovered || selectedTable === fromKey || selectedTable === toKey;
const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))';
const midX = (x1 + x2) / 2;
const midY = (y1 + y2) / 2;
const edgeLabel = `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`;
const labelWidth = Math.min(260, Math.max(72, edgeLabel.length * 6.2 + 14));
return (
<g
key={rel.name ?? `${fromKey}.${rel.fromColumn}->${toKey}.${rel.toColumn}:${idx}`}
data-er-relation={`${rel.fromTable}.${rel.fromColumn}->${rel.toTable}.${rel.toColumn}`}
onPointerEnter={() => setHoveredRelation(idx)}
onPointerLeave={() => setHoveredRelation(null)}
>
<path
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
fill="none"
stroke="transparent"
strokeWidth={14}
/>
<path
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
fill="none"
stroke={stroke}
strokeWidth={highlighted ? 2.2 : 1.4}
strokeOpacity={highlighted ? 1 : 0.65}
/>
<circle cx={x1} cy={y1} r={3.5} fill={stroke} />
<circle cx={x2} cy={y2} r={3.5} fill="hsl(var(--background))" stroke={stroke} strokeWidth={1.8} />
{isHovered && (
<g transform={`translate(${midX - labelWidth / 2}, ${midY - 12})`}>
<rect
width={labelWidth}
height={18}
rx={4}
fill="hsl(var(--popover))"
stroke="hsl(var(--primary))"
strokeWidth={1}
/>
<text
x={labelWidth / 2}
y={12}
textAnchor="middle"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--popover-foreground))"
>
{edgeLabel}
</text>
</g>
)}
</g>
);
})}
{/* Table Cards */}
{tables.map((table) => {
const key = erTableKey(table);
const pos = positions[key] ?? { x: 0, y: 0 };
const height = erCardHeight(table);
const isSelected = selectedTable === key;
return (
<g
key={key}
data-er-table={table.name}
transform={`translate(${pos.x}, ${pos.y})`}
onPointerDown={(e) => startCardDrag(e, table)}
onDoubleClick={(e) => handleCardDoubleClick(e, table)}
className="cursor-pointer"
filter="url(#nc-er-shadow)"
>
<rect
width={ER_CARD_WIDTH}
height={height}
rx={8}
fill="hsl(var(--card))"
stroke={isSelected ? 'hsl(var(--primary))' : 'hsl(var(--border))'}
strokeWidth={isSelected ? 2 : 1}
/>
{/* Header band */}
<path
d={`M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z`}
fill="hsl(var(--muted))"
/>
<line
x1={0}
y1={ER_CARD_HEADER_HEIGHT}
x2={ER_CARD_WIDTH}
y2={ER_CARD_HEADER_HEIGHT}
stroke="hsl(var(--border))"
strokeWidth={1}
/>
<text
x={12}
y={21}
fontSize={12}
fontWeight={600}
fontFamily="var(--font-sans)"
fill="hsl(var(--card-foreground))"
>
{table.schema ? `${table.schema}.${table.name}` : table.name}
</text>
{/* Columns */}
{table.columns.map((col, colIdx) => {
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
const maxNameChars = badgeOffset >= 52 ? 12 : badgeOffset >= 26 ? 15 : 19;
const displayName = col.name.length > maxNameChars ? `${col.name.slice(0, maxNameChars - 1)}…` : col.name;
const displayType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
return (
<g key={col.name} transform={`translate(0, ${rowY})`}>
<title>{`${col.name}: ${col.type}${col.nullable ? ' NULL' : ' NOT NULL'}`}</title>
{colIdx > 0 && (
<line
x1={8}
y1={0}
x2={ER_CARD_WIDTH - 8}
y2={0}
stroke="hsl(var(--border))"
strokeOpacity={0.45}
strokeWidth={0.75}
/>
)}
{col.isPk && (
<g transform="translate(8, 5)">
<rect width={22} height={14} rx={3} fill="#f59e0b" fillOpacity={0.2} />
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#d97706">
PK
</text>
</g>
)}
{col.isFk && (
<g transform={`translate(${col.isPk ? 34 : 8}, 5)`}>
<rect width={22} height={14} rx={3} fill="#3b82f6" fillOpacity={0.2} />
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#2563eb">
FK
</text>
</g>
)}
<text
x={10 + badgeOffset}
y={16}
fontSize={11}
fontFamily="var(--font-mono)"
fill="hsl(var(--card-foreground))"
>
{displayName}
</text>
<text
x={ER_CARD_WIDTH - 10}
y={16}
textAnchor="end"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--muted-foreground))"
>
{displayType}
</text>
</g>
);
})}
</g>
);
})}
</g>
</svg>
)}
</div>
);
}
@@ -0,0 +1,198 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { PluginSplitPaneWidgetProps, PluginWidgetEventCallback } from './types';
export interface PluginSplitPaneProps extends PluginSplitPaneWidgetProps {
firstChild: React.ReactNode;
secondChild: React.ReactNode;
nodeId: string;
className?: string;
inlineStyle?: string;
onWidgetEvent: PluginWidgetEventCallback;
}
/**
* 60fps host-managed 2-child split container rendered inside the shadow root so
* child plugin trees keep full plugin CSS scoping and can nest freely.
*/
export function PluginSplitPane({
direction = 'horizontal',
initialSize = 260,
minSize = 120,
maxSize = 900,
collapsible = false,
collapsed: controlledCollapsed,
firstChild,
secondChild,
nodeId,
className,
inlineStyle,
onWidgetEvent,
}: PluginSplitPaneProps) {
const containerRef = useRef<HTMLDivElement>(null);
const clampSize = useCallback(
(raw: number) => Math.max(minSize, Math.min(maxSize, Math.round(raw))),
[minSize, maxSize],
);
const [size, setSize] = useState<number>(() => clampSize(initialSize));
const [collapsed, setCollapsed] = useState<boolean>(Boolean(controlledCollapsed));
const [dragging, setDragging] = useState(false);
const [hovered, setHovered] = useState(false);
const sizeRef = useRef(size);
sizeRef.current = size;
useEffect(() => {
if (controlledCollapsed !== undefined) setCollapsed(controlledCollapsed);
}, [controlledCollapsed]);
const isHorizontal = direction !== 'vertical';
const handlePointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
const target = event.currentTarget;
const startCoord = isHorizontal ? event.clientX : event.clientY;
const startSize = collapsed ? minSize : sizeRef.current;
setDragging(true);
try { target.setPointerCapture(event.pointerId); } catch {}
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 {}
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
onWidgetEvent('resizeEnd', {
size: latestCollapsed ? 0 : latestSize,
collapsed: latestCollapsed,
});
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
}, [isHorizontal, collapsed, minSize, maxSize, collapsible, onWidgetEvent]);
const handleDoubleClick = useCallback(() => {
if (!collapsible) return;
const nextCollapsed = !collapsed;
setCollapsed(nextCollapsed);
onWidgetEvent('resizeEnd', {
size: nextCollapsed ? 0 : sizeRef.current,
collapsed: nextCollapsed,
});
}, [collapsible, collapsed, onWidgetEvent]);
const setContainerRef = useCallback((el: HTMLDivElement | null) => {
containerRef.current = el;
if (!el) return;
if (inlineStyle) {
el.setAttribute('style', `${inlineStyle};display:flex;flex-direction:${isHorizontal ? 'row' : 'column'};width:100%;height:100%;min-width:0;min-height:0;overflow:hidden`);
}
}, [inlineStyle, isHorizontal]);
const dividerActive = dragging || hovered;
return (
<div
ref={setContainerRef}
data-netcatty-remote-node={nodeId}
data-plugin-widget="split-pane"
data-direction={isHorizontal ? 'horizontal' : 'vertical'}
className={className}
style={{
display: 'flex',
flexDirection: isHorizontal ? 'row' : 'column',
width: '100%',
height: '100%',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
userSelect: dragging ? 'none' : undefined,
}}
>
<div
data-split-pane="first"
style={{
flex: collapsed ? '0 0 0px' : `0 0 ${size}px`,
display: collapsed ? 'none' : 'flex',
flexDirection: 'column',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
}}
>
{firstChild}
</div>
<div
role="separator"
aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}
aria-valuenow={collapsed ? 0 : size}
aria-valuemin={minSize}
aria-valuemax={maxSize}
data-split-handle=""
onPointerDown={handlePointerDown}
onDoubleClick={handleDoubleClick}
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
style={{
position: 'relative',
flex: isHorizontal ? '0 0 5px' : '0 0 5px',
cursor: isHorizontal ? 'col-resize' : 'row-resize',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
zIndex: 5,
touchAction: 'none',
}}
>
<div
style={{
width: isHorizontal ? (dividerActive ? '2px' : '1px') : '100%',
height: isHorizontal ? '100%' : (dividerActive ? '2px' : '1px'),
background: dividerActive ? 'hsl(var(--primary))' : 'hsl(var(--border))',
transition: 'background 120ms ease',
}}
/>
</div>
<div
data-split-pane="second"
style={{
flex: '1 1 0%',
display: 'flex',
flexDirection: 'column',
minWidth: 0,
minHeight: 0,
overflow: 'hidden',
}}
>
{secondChild}
</div>
</div>
);
}
@@ -0,0 +1,55 @@
import React, { useMemo } from 'react';
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
import { PluginCodeEditor } from './PluginCodeEditor';
import { PluginDataGrid } from './PluginDataGrid';
import { PluginErCanvas } from './PluginErCanvas';
import type {
PluginCodeEditorWidgetProps,
PluginDataGridWidgetProps,
PluginErCanvasWidgetProps,
PluginWidgetEventCallback,
} from './types';
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas';
export function parseWidgetPropsJson<T extends object>(raw: string | undefined): T {
if (!raw) return {} as T;
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as T;
}
} catch {
// Policy already validates widget props; fall back to empty props defensively.
}
return {} as T;
}
export function PluginSlottedWidget({
kind,
rawProps,
onWidgetEvent,
}: {
kind: SlottedWidgetKind;
rawProps: string | undefined;
onWidgetEvent: PluginWidgetEventCallback;
}) {
const parsedProps = useMemo(() => parseWidgetPropsJson<Record<string, unknown>>(rawProps), [rawProps]);
return (
<LazyLoadBoundary
name={`Plugin ${kind}`}
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to render plugin widget.</div>}
>
{kind === 'code-editor' && (
<PluginCodeEditor {...(parsedProps as PluginCodeEditorWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
{kind === 'data-grid' && (
<PluginDataGrid {...(parsedProps as PluginDataGridWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
{kind === 'er-canvas' && (
<PluginErCanvas {...(parsedProps as PluginErCanvasWidgetProps)} onWidgetEvent={onWidgetEvent} />
)}
</LazyLoadBoundary>
);
}
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => {
assert.equal(abbreviateSqlType('character varying(180)'), 'varchar(180)');
assert.equal(abbreviateSqlType('timestamp with time zone'), 'timestamptz');
assert.equal(abbreviateSqlType('timestamp without time zone'), 'timestamp');
assert.equal(abbreviateSqlType('double precision'), 'float8');
assert.equal(abbreviateSqlType('integer'), 'int4');
assert.equal(abbreviateSqlType('boolean'), 'bool');
assert.equal(abbreviateSqlType('numeric(10,2)'), 'numeric(10,2)');
});
test('buildStandaloneErSvg generates valid self-contained SVG markup with tables, PK/FK pills, and Bezier relations', () => {
const svg = buildStandaloneErSvg(
[
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'email', type: 'character varying(180)', nullable: false }] },
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
],
[{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
{ 'public.customers': { x: 40, y: 40 }, 'public.orders': { x: 380, y: 40 } },
{
background: '#0f1117',
card: '#161922',
cardForeground: '#f1f5f9',
muted: '#1e2230',
mutedForeground: '#94a3b8',
border: '#2a3040',
primary: '#38bdf8',
},
);
assert.match(svg, /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
assert.match(svg, /<\/svg>$/);
assert.match(svg, /public\.customers/);
assert.match(svg, /varchar\(180\)/);
assert.match(svg, />PK</);
assert.match(svg, />FK</);
assert.match(svg, /<path d="M /);
});
test('matchWorkbenchShortcut normalizes mod+k/s/t/w/z/shift+z and escape while respecting includeUndoRedo', () => {
assert.equal(matchWorkbenchShortcut({ key: 'k', metaKey: true }), 'mod+k');
assert.equal(matchWorkbenchShortcut({ key: 'K', ctrlKey: true }), 'mod+k');
assert.equal(matchWorkbenchShortcut({ key: 's', metaKey: true }), 'mod+s');
assert.equal(matchWorkbenchShortcut({ key: 't', ctrlKey: true }), 'mod+t');
assert.equal(matchWorkbenchShortcut({ key: 'w', metaKey: true }), 'mod+w');
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }), 'mod+z');
assert.equal(matchWorkbenchShortcut({ key: 'Z', metaKey: true, shiftKey: true }), 'mod+shift+z');
assert.equal(matchWorkbenchShortcut({ key: 'y', ctrlKey: true }), 'mod+shift+z');
assert.equal(matchWorkbenchShortcut({ key: 'Escape' }), 'escape');
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }, { includeUndoRedo: false }), null);
assert.equal(matchWorkbenchShortcut({ key: 'c', metaKey: true }), null);
});
+155
View File
@@ -0,0 +1,155 @@
import type { PluginErRelation, PluginErTable } from './types';
export const ER_CARD_WIDTH = 252;
export const ER_CARD_HEADER_HEIGHT = 34;
export const ER_CARD_ROW_HEIGHT = 24;
export const ER_CARD_FOOTER_PADDING = 8;
/** Abbreviate verbose SQL types (especially PostgreSQL catalog names) so ER cards never clip mid-word. */
export function abbreviateSqlType(rawType: string): string {
const trimmed = rawType.trim();
if (!trimmed) return '';
let out = trimmed
.replace(/\bcharacter\s+varying\b/gi, 'varchar')
.replace(/\bcharacter\b(?=\s*\()/gi, 'char')
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timestamptz')
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'timestamp')
.replace(/\btime\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timetz')
.replace(/\btime\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'time')
.replace(/\bdouble\s+precision\b/gi, 'float8')
.replace(/\bboolean\b/gi, 'bool')
.replace(/\binteger\b/gi, 'int4')
.replace(/\bsmallint\b/gi, 'int2')
.replace(/\bbigint\b/gi, 'int8')
.replace(/\s+/g, ' ');
if (out.length > 18) {
out = `${out.slice(0, 17)}…`;
}
return out;
}
export function erTableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
return table.schema ? `${table.schema}.${table.name}` : table.name;
}
export function erCardHeight(table: PluginErTable): number {
return ER_CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * ER_CARD_ROW_HEIGHT + ER_CARD_FOOTER_PADDING;
}
function escapeXml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
export interface ErSvgPalette {
background: string;
card: string;
cardForeground: string;
muted: string;
mutedForeground: string;
border: string;
primary: string;
}
export function buildStandaloneErSvg(
tables: PluginErTable[],
relations: PluginErRelation[],
positions: Record<string, { x: number; y: number }>,
palette: ErSvgPalette,
): string {
const byKey = new Map<string, PluginErTable>();
const byName = new Map<string, PluginErTable>();
for (const tbl of tables) {
byKey.set(erTableKey(tbl), tbl);
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
}
const resolveTable = (ref: string) => byKey.get(ref) ?? byName.get(ref);
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 40, y: 40 };
minX = Math.min(minX, pos.x);
minY = Math.min(minY, pos.y);
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
}
if (!Number.isFinite(minX)) {
minX = 0; minY = 0; maxX = 400; maxY = 240;
}
const pad = 40;
const vbX = Math.floor(minX - pad);
const vbY = Math.floor(minY - pad);
const vbW = Math.max(200, Math.ceil(maxX - minX + pad * 2));
const vbH = Math.max(160, Math.ceil(maxY - minY + pad * 2));
const lines: string[] = [
`<svg xmlns="http://www.w3.org/2000/svg" width="${vbW}" height="${vbH}" viewBox="${vbX} ${vbY} ${vbW} ${vbH}">`,
`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="${escapeXml(palette.background)}" />`,
];
for (const rel of relations) {
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) continue;
const fromPos = positions[erTableKey(fromTable)] ?? { x: 0, y: 0 };
const toPos = positions[erTableKey(toTable)] ?? { x: 0, y: 0 };
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
const goRight = (toPos.x + ER_CARD_WIDTH / 2) >= (fromPos.x + ER_CARD_WIDTH / 2);
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
const c1x = goRight ? x1 + dx : x1 - dx;
const c2x = goRight ? x2 - dx : x2 + dx;
lines.push(
`<path d="M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}" fill="none" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.5" stroke-opacity="0.75" />`,
`<circle cx="${x1}" cy="${y1}" r="3.5" fill="${escapeXml(palette.mutedForeground)}" />`,
`<circle cx="${x2}" cy="${y2}" r="3.5" fill="${escapeXml(palette.background)}" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.8" />`,
);
}
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
const h = erCardHeight(tbl);
const title = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
lines.push(`<g transform="translate(${pos.x}, ${pos.y})">`);
lines.push(`<rect width="${ER_CARD_WIDTH}" height="${h}" rx="8" fill="${escapeXml(palette.card)}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
lines.push(`<path d="M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z" fill="${escapeXml(palette.muted)}" />`);
lines.push(`<line x1="0" y1="${ER_CARD_HEADER_HEIGHT}" x2="${ER_CARD_WIDTH}" y2="${ER_CARD_HEADER_HEIGHT}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
lines.push(`<text x="12" y="21" font-size="12" font-weight="600" font-family="system-ui, -apple-system, sans-serif" fill="${escapeXml(palette.cardForeground)}">${escapeXml(title)}</text>`);
tbl.columns.forEach((col, colIdx) => {
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
const shortType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
const colLabel = col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name;
lines.push(`<g transform="translate(0, ${rowY})">`);
if (colIdx > 0) {
lines.push(`<line x1="8" y1="0" x2="${ER_CARD_WIDTH - 8}" y2="0" stroke="${escapeXml(palette.border)}" stroke-opacity="0.45" stroke-width="0.75" />`);
}
if (col.isPk) {
lines.push(`<rect x="8" y="5" width="22" height="14" rx="3" fill="#f59e0b" fill-opacity="0.2" /><text x="19" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#d97706">PK</text>`);
}
if (col.isFk) {
const fkX = col.isPk ? 34 : 8;
lines.push(`<rect x="${fkX}" y="5" width="22" height="14" rx="3" fill="#3b82f6" fill-opacity="0.2" /><text x="${fkX + 11}" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#2563eb">FK</text>`);
}
lines.push(`<text x="${10 + badgeOffset}" y="16" font-size="11" font-family="ui-monospace, monospace" fill="${escapeXml(palette.cardForeground)}">${escapeXml(colLabel)}</text>`);
lines.push(`<text x="${ER_CARD_WIDTH - 10}" y="16" text-anchor="end" font-size="10" font-family="ui-monospace, monospace" fill="${escapeXml(palette.mutedForeground)}">${escapeXml(shortType)}</text>`);
lines.push('</g>');
});
lines.push('</g>');
}
lines.push('</svg>');
return lines.join('\n');
}
@@ -0,0 +1,36 @@
import type { PluginWorkbenchShortcut } from './types';
export interface KeyboardShortcutLike {
key: string;
metaKey?: boolean;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
}
/**
* Normalize global workbench shortcuts pressed inside plugin views/widgets.
* Returns null for unrecognized key combinations.
*/
export function matchWorkbenchShortcut(
event: KeyboardShortcutLike,
options?: { includeUndoRedo?: boolean },
): PluginWorkbenchShortcut | null {
const includeUndoRedo = options?.includeUndoRedo ?? true;
if (event.key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) {
return 'escape';
}
const mod = Boolean(event.metaKey || event.ctrlKey);
if (!mod || event.altKey) return null;
const key = event.key.toLowerCase();
if (key === 'k' && !event.shiftKey) return 'mod+k';
if (key === 's' && !event.shiftKey) return 'mod+s';
if (key === 't' && !event.shiftKey) return 'mod+t';
if (key === 'w' && !event.shiftKey) return 'mod+w';
if (includeUndoRedo) {
if (key === 'z' && event.shiftKey) return 'mod+shift+z';
if (key === 'z' && !event.shiftKey) return 'mod+z';
if (key === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z';
}
return null;
}
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
test('extractCurrentSqlStatement splits statements respecting strings, comments, and PG dollar quotes', () => {
const sql = [
"-- first query; not a split",
"SELECT 'semi;colon' AS a;",
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql;",
"SELECT /* block; comment */ * FROM orders WHERE id = 1",
].join('\n');
const firstIdx = sql.indexOf("SELECT 'semi");
assert.equal(extractCurrentSqlStatement(sql, firstIdx + 5), "-- first query; not a split\nSELECT 'semi;colon' AS a");
const fnIdx = sql.indexOf("RETURN 'x;y'");
assert.equal(
extractCurrentSqlStatement(sql, fnIdx),
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql",
);
const lastIdx = sql.indexOf('FROM orders');
assert.equal(
extractCurrentSqlStatement(sql, lastIdx),
'SELECT /* block; comment */ * FROM orders WHERE id = 1',
);
});
test('extractSqlTableAliases resolves table names and aliases across FROM and JOIN clauses', () => {
const sql = 'SELECT o.id, u.email FROM public.orders AS o INNER JOIN users u ON u.id = o.user_id WHERE o.status = 1';
const aliases = extractSqlTableAliases(sql);
assert.equal(aliases.get('o'), 'orders');
assert.equal(aliases.get('orders'), 'orders');
assert.equal(aliases.get('u'), 'users');
assert.equal(aliases.get('users'), 'users');
assert.equal(aliases.has('where'), false);
});
@@ -0,0 +1,164 @@
/**
* Pure SQL statement and alias helpers used by PluginCodeEditor.
* Runs synchronously in the host renderer with zero IPC overhead.
*/
export function extractCurrentSqlStatement(sql: string, cursorOffset: number): string {
if (!sql) return '';
const clampedCursor = Math.max(0, Math.min(cursorOffset, sql.length));
const statements: Array<{ start: number; end: number; text: string }> = [];
let start = 0;
let i = 0;
let inSingle = false;
let inDouble = false;
let inBacktick = false;
let inLineComment = false;
let inBlockComment = false;
let dollarTag: string | null = null;
while (i < sql.length) {
const ch = sql[i];
const next = sql[i + 1];
if (inLineComment) {
if (ch === '\n') inLineComment = false;
i += 1;
continue;
}
if (inBlockComment) {
if (ch === '*' && next === '/') {
inBlockComment = false;
i += 2;
continue;
}
i += 1;
continue;
}
if (dollarTag !== null) {
if (sql.startsWith(dollarTag, i)) {
i += dollarTag.length;
dollarTag = null;
continue;
}
i += 1;
continue;
}
if (inSingle) {
if (ch === "'" && next === "'") {
i += 2;
continue;
}
if (ch === '\\' && next !== undefined) {
i += 2;
continue;
}
if (ch === "'") inSingle = false;
i += 1;
continue;
}
if (inDouble) {
if (ch === '"' && next === '"') {
i += 2;
continue;
}
if (ch === '"') inDouble = false;
i += 1;
continue;
}
if (inBacktick) {
if (ch === '`' && next === '`') {
i += 2;
continue;
}
if (ch === '`') inBacktick = false;
i += 1;
continue;
}
if (ch === '-' && next === '-') {
inLineComment = true;
i += 2;
continue;
}
if (ch === '/' && next === '*') {
inBlockComment = true;
i += 2;
continue;
}
if (ch === "'") {
inSingle = true;
i += 1;
continue;
}
if (ch === '"') {
inDouble = true;
i += 1;
continue;
}
if (ch === '`') {
inBacktick = true;
i += 1;
continue;
}
if (ch === '$') {
const match = /^\$[a-zA-Z0-9_]*\$/u.exec(sql.slice(i));
if (match) {
dollarTag = match[0];
i += dollarTag.length;
continue;
}
}
if (ch === ';') {
const raw = sql.slice(start, i);
if (raw.trim().length > 0) {
statements.push({ start, end: i + 1, text: raw.trim() });
}
start = i + 1;
i += 1;
continue;
}
i += 1;
}
const tail = sql.slice(start);
if (tail.trim().length > 0) {
statements.push({ start, end: sql.length, text: tail.trim() });
}
if (statements.length === 0) return sql.trim();
for (const stmt of statements) {
if (clampedCursor >= stmt.start && clampedCursor <= stmt.end) {
return stmt.text;
}
}
// If cursor sits in trailing whitespace after a semicolon, return the preceding statement.
let chosen = statements[0];
for (const stmt of statements) {
if (stmt.start <= clampedCursor) chosen = stmt;
}
return chosen.text;
}
/** Extract simple `FROM/JOIN [schema.]table [AS] alias` bindings for dot-completion. */
export function extractSqlTableAliases(sql: string): Map<string, string> {
const aliases = new Map<string, string>();
const pattern = /\b(?:from|join|update|into)\s+(?:["`]?([a-zA-Z_][\w$]*)["`]?\.)?["`]?([a-zA-Z_][\w$]*)["`]?(?:\s+(?:as\s+)?["`]?([a-zA-Z_][\w$]*)["`]?)?/giu;
const reserved = new Set([
'where', 'on', 'set', 'values', 'inner', 'left', 'right', 'full', 'outer',
'cross', 'join', 'group', 'order', 'having', 'limit', 'offset', 'union',
'select', 'from', 'as', 'using', 'returning',
]);
let match: RegExpExecArray | null;
while ((match = pattern.exec(sql)) !== null) {
const tableName = match[2];
const alias = match[3];
if (!tableName) continue;
aliases.set(tableName.toLowerCase(), tableName);
if (alias && !reserved.has(alias.toLowerCase())) {
aliases.set(alias.toLowerCase(), tableName);
}
}
return aliases;
}
+136
View File
@@ -0,0 +1,136 @@
export type PluginWidgetEventCallback = (
widgetEvent: string,
detail?: Record<string, unknown>,
) => void;
export type PluginWorkbenchShortcut =
| 'mod+k'
| 'mod+s'
| 'mod+t'
| 'mod+w'
| 'mod+z'
| 'mod+shift+z'
| 'escape';
export interface PluginCodeEditorCompletionColumn {
name: string;
type?: string;
}
export interface PluginCodeEditorCompletionTable {
name: string;
schema?: string;
columns?: PluginCodeEditorCompletionColumn[];
}
export interface PluginCodeEditorCompletionFunction {
name: string;
detail?: string;
insertText?: string;
}
export interface PluginCodeEditorCompletionSchema {
tables?: PluginCodeEditorCompletionTable[];
functions?: PluginCodeEditorCompletionFunction[];
keywords?: string[];
}
export interface PluginCodeEditorDiagnostic {
line: number;
column: number;
endLine?: number;
endColumn?: number;
message: string;
severity?: 'error' | 'warning' | 'info' | 'hint';
}
export interface PluginCodeEditorWidgetProps {
value?: string;
language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext';
readOnly?: boolean;
placeholder?: string;
lineNumbers?: 'on' | 'off' | 'relative';
minimap?: boolean;
wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded';
completionSchema?: PluginCodeEditorCompletionSchema;
diagnostics?: PluginCodeEditorDiagnostic[];
height?: number | string;
}
export interface PluginDataGridForeignKey {
table: string;
column: string;
schema?: string;
}
export interface PluginDataGridColumn {
name: string;
type?: string;
primaryKey?: boolean;
nullable?: boolean;
width?: number;
sortable?: boolean;
foreignKey?: PluginDataGridForeignKey;
}
export interface PluginDataGridSort {
column: string;
direction: 'asc' | 'desc';
}
export type PluginDataGridRow = Record<string, unknown> | unknown[];
export interface PluginDataGridWidgetProps {
columns?: PluginDataGridColumn[];
rows?: PluginDataGridRow[];
hiddenColumns?: string[];
rowKeyField?: string;
dirtyCells?: Record<string, unknown>;
deletedRowIndices?: number[];
insertedRows?: PluginDataGridRow[];
selectedRowIndices?: number[];
sort?: PluginDataGridSort | null;
editable?: boolean;
loading?: boolean;
emptyMessage?: string;
}
export interface PluginSplitPaneWidgetProps {
direction?: 'horizontal' | 'vertical';
initialSize?: number;
minSize?: number;
maxSize?: number;
collapsible?: boolean;
collapsed?: boolean;
}
export interface PluginErColumn {
name: string;
type: string;
isPk?: boolean;
isFk?: boolean;
nullable?: boolean;
}
export interface PluginErTable {
name: string;
schema?: string;
columns: PluginErColumn[];
x?: number;
y?: number;
}
export interface PluginErRelation {
fromTable: string;
fromColumn: string;
toTable: string;
toColumn: string;
name?: string;
onDelete?: string;
onUpdate?: string;
}
export interface PluginErCanvasWidgetProps {
tables?: PluginErTable[];
relations?: PluginErRelation[];
}
@@ -1,13 +1,26 @@
/**
* SettingsFileAssociationsTab - Manage SFTP file opener associations and behavior
*/
import { FileType, Pencil, Trash2 } from "lucide-react";
import { FileType, Pencil, RotateCcw, Trash2 } from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { useI18n } from "../../../application/i18n/I18nProvider";
import { useSftpFileAssociations } from "../../../application/state/useSftpFileAssociations";
import { useSettingsState } from "../../../application/state/useSettingsState";
import { useStoredString } from "../../../application/state/useStoredString";
import { STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD } from "../../../infrastructure/config/storageKeys";
import {
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD,
} from "../../../infrastructure/config/storageKeys";
import {
buildSftpDownloadDialogDirectoryOptions,
normalizeSftpDefaultDownloadDirectory,
} from "../../../domain/sftpDownloadLocation";
import {
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
type SftpTreeFolderDoubleClickBehavior,
} from "../../../domain/sftpTreeFolderDoubleClick";
import type { FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { Button } from "../../ui/button";
@@ -16,6 +29,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip";
import {
SectionHeader,
SettingCard,
SettingsAnchor,
SettingsTabContent,
SettingRow,
Toggle,
@@ -38,6 +52,14 @@ const getOpenerLabel = (
export default function SettingsFileAssociationsTab() {
const { t } = useI18n();
const [packedDownload, setPackedDownload] = useStoredString<string>(STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD, "true");
const [storedDownloadDir, setStoredDownloadDir] = useStoredString<string>(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR, "");
const [sftpTreeFolderDoubleClick, setSftpTreeFolderDoubleClick] = useStoredString<SftpTreeFolderDoubleClickBehavior>(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
);
const defaultDownloadDir = normalizeSftpDefaultDownloadDirectory(storedDownloadDir);
const [isSelectingDownloadDir, setIsSelectingDownloadDir] = useState(false);
const { getAllAssociations, removeAssociation, setOpenerForExtension, getDefaultOpener, setDefaultOpener, removeDefaultOpener } = useSftpFileAssociations();
const {
sftpDoubleClickBehavior, setSftpDoubleClickBehavior,
@@ -102,6 +124,24 @@ export default function SettingsFileAssociationsTab() {
void handleSelectDefaultSystemApp();
}, [handleSelectDefaultSystemApp, removeDefaultOpener, setDefaultOpener]);
const handleSelectDownloadDir = useCallback(async () => {
const bridge = netcattyBridge.get();
if (!bridge?.selectDirectory) return;
setIsSelectingDownloadDir(true);
try {
const selected = await bridge.selectDirectory(
t('settings.sftp.downloadLocation.select'),
undefined,
buildSftpDownloadDialogDirectoryOptions(defaultDownloadDir),
);
if (selected) setStoredDownloadDir(selected);
} catch (e) {
console.error('Failed to select download directory:', e);
} finally {
setIsSelectingDownloadDir(false);
}
}, [defaultDownloadDir, setStoredDownloadDir, t]);
const handleEdit = useCallback(async (extension: string) => {
setEditingExtension(extension);
try {
@@ -158,6 +198,24 @@ export default function SettingsFileAssociationsTab() {
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.treeFolderDoubleClick')} />
<SettingCard>
<SettingRow
anchorId="sftp-tree-folder-double-click"
description={t('settings.sftp.treeFolderDoubleClick.desc')}
>
<Select
value={sftpTreeFolderDoubleClick}
options={[
{ value: 'navigate', label: t('settings.sftp.treeFolderDoubleClick.navigate') },
{ value: 'expand', label: t('settings.sftp.treeFolderDoubleClick.expand') },
]}
onChange={(value) => setSftpTreeFolderDoubleClick(value as SftpTreeFolderDoubleClickBehavior)}
className="w-56"
/>
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.showHiddenFiles')} />
<SettingCard>
<SettingRow
@@ -191,6 +249,61 @@ export default function SettingsFileAssociationsTab() {
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.downloadLocation')} />
<SettingCard className="py-3">
<SettingsAnchor anchorId="sftp-default-download-directory" className="space-y-2">
<div>
<div className="text-sm font-medium">{t('settings.sftp.downloadLocation.directory')}</div>
<div className="text-xs text-muted-foreground mt-0.5">
{t('settings.sftp.downloadLocation.directoryDesc')}
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex-1 min-w-0">
{defaultDownloadDir ? (
<Tooltip>
<TooltipTrigger asChild>
<div className="bg-background border border-input rounded-md px-3 py-2 text-sm font-mono truncate">
{defaultDownloadDir}
</div>
</TooltipTrigger>
<TooltipContent>{defaultDownloadDir}</TooltipContent>
</Tooltip>
) : (
<div className="bg-background border border-input rounded-md px-3 py-2 text-sm text-muted-foreground truncate">
{t('settings.sftp.downloadLocation.systemDefault')}
</div>
)}
</div>
<Button
variant="outline"
size="sm"
onClick={() => void handleSelectDownloadDir()}
disabled={isSelectingDownloadDir}
className="shrink-0"
>
{t('settings.sftp.downloadLocation.browse')}
</Button>
{defaultDownloadDir && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() => setStoredDownloadDir("")}
aria-label={t('settings.sftp.downloadLocation.reset')}
className="shrink-0"
>
<RotateCcw size={16} />
</Button>
</TooltipTrigger>
<TooltipContent>{t('settings.sftp.downloadLocation.reset')}</TooltipContent>
</Tooltip>
)}
</div>
</SettingsAnchor>
</SettingCard>
<SectionHeader title={t('settings.sftp.packedDownload')} />
<SettingCard>
<SettingRow
+184 -1
View File
@@ -10,6 +10,7 @@ import type { SftpFileEntry } from "../../types";
import { createEmptyPane } from "../../application/state/sftp/types";
import { sftpTreeSelectionStore } from "../../application/state/sftp/sftpTreeSelectionStore";
import { installDomEnvironment, createDomRenderer } from "../test-support/renderReactDom";
import { STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR } from "../../infrastructure/config/storageKeys";
const entry = (name: string, type: SftpFileEntry["type"]): SftpFileEntry => ({
name,
@@ -20,10 +21,21 @@ const entry = (name: string, type: SftpFileEntry["type"]): SftpFileEntry => ({
lastModifiedFormatted: "--",
});
test("tree activation enters directories and keeps file opening separate", () => {
test("tree activation resolves directory double-click action per preference while keeping parent and file actions separate", () => {
const dirLink: SftpFileEntry = { ...entry("linked-docs", "symlink"), linkTarget: "directory" };
const fileLink: SftpFileEntry = { ...entry("linked-file", "symlink"), linkTarget: "file" };
assert.equal(getSftpTreeEntryOpenAction(entry("..", "directory")), "up");
assert.equal(getSftpTreeEntryOpenAction(entry("docs", "directory")), "navigate");
assert.equal(getSftpTreeEntryOpenAction(dirLink), "navigate");
assert.equal(getSftpTreeEntryOpenAction(entry("notes.txt", "file")), "open");
assert.equal(getSftpTreeEntryOpenAction(fileLink), "open");
assert.equal(getSftpTreeEntryOpenAction(entry("..", "directory"), "expand"), "up");
assert.equal(getSftpTreeEntryOpenAction(entry("docs", "directory"), "expand"), "expand");
assert.equal(getSftpTreeEntryOpenAction(dirLink, "expand"), "expand");
assert.equal(getSftpTreeEntryOpenAction(entry("notes.txt", "file"), "expand"), "open");
assert.equal(getSftpTreeEntryOpenAction(fileLink, "expand"), "open");
});
test("tree double clicks open entries while the chevron only toggles expansion", async () => {
@@ -197,3 +209,174 @@ test("tree view routes double clicks to navigation and preserves selection, expa
dom.cleanup();
}
});
test("tree view expands and collapses folders in place on double-click when configured and reacts to live setting updates", async () => {
const dom = installDomEnvironment();
const previousObserver = Object.getOwnPropertyDescriptor(globalThis, "ResizeObserver");
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const eventTargetKeys = ["addEventListener", "removeEventListener", "dispatchEvent"] as const;
const previousEventTarget = eventTargetKeys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);
for (const key of eventTargetKeys) {
Object.defineProperty(globalThis, key, {
configurable: true,
value: dom.window[key].bind(dom.window),
});
}
const backing = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
get length() { return backing.size; },
clear() { backing.clear(); },
getItem(key: string) { return backing.get(key) ?? null; },
key(index: number) { return Array.from(backing.keys())[index] ?? null; },
removeItem(key: string) { backing.delete(key); },
setItem(key: string, value: string) { backing.set(key, value); },
} satisfies Storage,
});
Object.defineProperty(globalThis, "ResizeObserver", {
configurable: true,
value: class { observe() {} disconnect() {} },
});
dom.window.requestAnimationFrame = callback => dom.window.setTimeout(() => callback(0), 0);
dom.window.cancelAnimationFrame = id => dom.window.clearTimeout(id);
const renderer = await createDomRenderer(dom.document);
const noop = () => {};
const calls: string[] = [];
const paneId = "tree-activation-expand";
const directoryLink: SftpFileEntry = { ...entry("linked-docs", "symlink"), linkTarget: "directory" };
const fileLink: SftpFileEntry = { ...entry("linked-file", "symlink"), linkTarget: "file" };
const files = [entry("docs", "directory"), entry("src", "directory"), entry("notes.txt", "file"), directoryLink, fileLink];
const childrenByPath: Record<string, SftpFileEntry[]> = {
"/root/docs": [entry("nested", "directory")],
"/root/docs/nested": [entry("leaf.txt", "file")],
"/root/src": [entry("index.ts", "file")],
"/root/linked-docs": [entry("guide.md", "file")],
};
const props: React.ComponentProps<typeof SftpPaneTreeView> = {
pane: {
...createEmptyPane(paneId),
files,
connection: { id: "conn", hostId: "host", hostLabel: "Host", isLocal: false, status: "connected", currentPath: "/root" },
},
side: "left",
onPrepareSelection: noop,
onLoadChildren: async path => {
calls.push(`load:${path}`);
return childrenByPath[path] ?? [];
},
onMoveEntriesToPath: async () => {},
onNavigateUp: () => calls.push("up"),
onNavigateTo: path => calls.push(`navigate:${path}`),
onOpenEntry: (_item, path) => { calls.push(`open:${path}`); },
onRefresh: noop,
onDragStart: noop,
onDragEnd: noop,
openRenameDialog: noop,
openDeleteConfirm: noop,
onCopyToOtherPane: noop,
onReceiveFromOtherPane: noop,
draggedFiles: null,
openNewFolderDialog: noop,
openNewFileDialog: noop,
sorting: {
sortField: "name",
sortOrder: "asc",
directoriesFirst: true,
columnWidths: { name: 50, modified: 24, size: 7, type: 9, owner: 10 },
visibleColumns: { name: true, modified: false, size: false, type: false, owner: false },
handleSort: noop,
handleResizeStart: noop,
toggleColumnVisibility: noop,
toggleDirectoriesFirst: noop,
},
reloadRequest: { token: 0 },
};
const row = (name: string) => {
const element = renderer.container.querySelector(`[data-entry-name="${name}"]`);
assert.ok(element, `missing row ${name}`);
return element;
};
const click = async (target: Element, type = "click", detail = 1) => {
await act(async () => { target.dispatchEvent(new dom.window.MouseEvent(type, { bubbles: true, detail })); });
};
const doubleClick = async (target: Element) => {
await click(target);
await click(target, "click", 2);
await click(target, "dblclick", 2);
};
try {
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "expand");
await renderer.render(React.createElement(SftpPaneTreeView, props));
// Double-clicking folders expands them in place while keeping other expanded branches.
await doubleClick(row("docs").querySelector("span.truncate")!);
assert.deepEqual(calls.splice(0), ["load:/root/docs"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
row("nested");
await doubleClick(row("src").querySelector("span.truncate")!);
assert.deepEqual(calls.splice(0), ["load:/root/src"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
assert.equal(row("src").getAttribute("data-expanded"), "true");
row("index.ts");
await doubleClick(row("nested"));
assert.deepEqual(calls.splice(0), ["load:/root/docs/nested"]);
assert.equal(row("nested").getAttribute("data-expanded"), "true");
row("leaf.txt");
// Double-clicking an expanded folder collapses it in place without navigating.
await doubleClick(row("nested"));
assert.deepEqual(calls, []);
assert.equal(row("nested").getAttribute("data-expanded"), "false");
assert.equal(renderer.container.querySelector('[data-entry-name="leaf.txt"]'), null);
assert.equal(row("src").getAttribute("data-expanded"), "true");
// Directory symlinks also expand/collapse in place; files, file symlinks and ".." keep their actions.
await doubleClick(row("linked-docs"));
assert.deepEqual(calls.splice(0), ["load:/root/linked-docs"]);
assert.equal(row("linked-docs").getAttribute("data-expanded"), "true");
row("guide.md");
for (const [name, action] of [["notes.txt", "open:/root/notes.txt"], ["linked-file", "open:/root/linked-file"], ["..", "up"]]) {
await doubleClick(row(name));
assert.deepEqual(calls.splice(0), [action]);
}
// Switching the setting back to "navigate" takes effect immediately on the mounted tree.
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "navigate");
await act(async () => {
dom.window.dispatchEvent(new dom.window.CustomEvent("netcatty:local-storage-adapter-changed", {
detail: { key: STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR },
}));
});
await doubleClick(row("docs"));
assert.deepEqual(calls.splice(0), ["navigate:/root/docs"]);
assert.equal(row("docs").getAttribute("data-expanded"), "true");
// Cross-window storage events also update the mounted tree live.
backing.set(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR, "expand");
await act(async () => {
dom.window.dispatchEvent(new dom.window.StorageEvent("storage", {
key: STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
newValue: "expand",
}));
});
await doubleClick(row("docs"));
assert.deepEqual(calls, []);
assert.equal(row("docs").getAttribute("data-expanded"), "false");
} finally {
await renderer.unmount();
sftpTreeSelectionStore.clearPane(paneId);
for (const [key, descriptor] of previousEventTarget) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
if (previousObserver) Object.defineProperty(globalThis, "ResizeObserver", previousObserver);
else Reflect.deleteProperty(globalThis, "ResizeObserver");
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
dom.cleanup();
}
});
+27 -4
View File
@@ -22,6 +22,13 @@ import {
shouldShowSftpUploadFolderMenu,
shouldShowSftpUploadFilesMenu,
} from './sftpUploadMenu';
import { useStoredString } from '../../application/state/useStoredString';
import {
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
type SftpTreeFolderDoubleClickBehavior,
} from '../../domain/sftpTreeFolderDoubleClick';
import { STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR } from '../../infrastructure/config/storageKeys';
interface ContextTarget {
entry: SftpFileEntry;
entryPath: string;
@@ -29,9 +36,12 @@ interface ContextTarget {
export const getSftpTreeEntryOpenAction = (
entry: SftpFileEntry,
): 'up' | 'navigate' | 'open' => {
folderDoubleClickBehavior: SftpTreeFolderDoubleClickBehavior = DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
): 'up' | 'navigate' | 'expand' | 'open' => {
if (entry.name === '..') return 'up';
if (isNavigableDirectory(entry)) return 'navigate';
if (isNavigableDirectory(entry)) {
return folderDoubleClickBehavior === 'expand' ? 'expand' : 'navigate';
}
return 'open';
};
@@ -70,6 +80,7 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
onCdInTerminal,
sorting,
reloadRequest,
folderDoubleClickBehavior,
}) => {
const {
columnWidths,
@@ -425,18 +436,30 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
}
lastClickedPathRef.current = entryPath;
}, [focusTreeContainer, pane.id]);
const [storedFolderDoubleClickBehavior] = useStoredString<SftpTreeFolderDoubleClickBehavior>(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
DEFAULT_SFTP_TREE_FOLDER_DOUBLE_CLICK_BEHAVIOR,
isSftpTreeFolderDoubleClickBehavior,
);
const effectiveFolderDoubleClickBehavior = folderDoubleClickBehavior ?? storedFolderDoubleClickBehavior;
const folderDoubleClickBehaviorRef = useRef(effectiveFolderDoubleClickBehavior);
folderDoubleClickBehaviorRef.current = effectiveFolderDoubleClickBehavior;
const openTreeEntry = useCallback((entry: SftpFileEntry, entryPath: string) => {
const action = getSftpTreeEntryOpenAction(entry);
const action = getSftpTreeEntryOpenAction(entry, folderDoubleClickBehaviorRef.current);
if (action === 'up') {
onNavigateUpRef.current();
return;
}
if (action === 'expand') {
void toggleExpand(entry, entryPath);
return;
}
if (action === 'navigate') {
onNavigateToRef.current(entryPath);
return;
}
onOpenEntryRef.current(entry, entryPath);
}, []);
}, [toggleExpand]);
const stableOnRefresh = useCallback(() => onRefreshRef.current(), []);
const handleTreeContainerKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
@@ -2,6 +2,7 @@ import type { SftpFileEntry } from '../../types';
import type { SftpPane } from '../../application/state/sftp/types';
import type { SftpTransferSource } from './SftpContext';
import type { UseSftpPaneSortingResult } from '../../application/state/sftp/useSftpPaneSorting';
import type { SftpTreeFolderDoubleClickBehavior } from '../../domain/sftpTreeFolderDoubleClick';
export interface SftpPaneTreeViewProps {
pane: SftpPane;
@@ -38,4 +39,5 @@ export interface SftpPaneTreeViewProps {
onCdInTerminal?: (dirPath: string) => void;
sorting: UseSftpPaneSortingResult;
reloadRequest: { token: number; paths?: string[]; full?: boolean };
folderDoubleClickBehavior?: SftpTreeFolderDoubleClickBehavior;
}
+21 -4
View File
@@ -12,6 +12,7 @@ import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"
import { getFileExtension, getLanguageId, FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import { isNavigableDirectory } from "../utils";
import { resolveDownloadSourceSnapshot } from "../../../application/state/sftp/downloadSourceSnapshot";
import { getSftpDownloadDialogDirectoryOptions } from "../../../application/state/sftp/downloadLocation";
import { reportSftpUploadResults } from "../reportSftpUploadResults";
import { editorTabStore } from "../../../application/state/editorTabStore";
import { popOutEditorTab } from "../../../application/state/editorWindowClient";
@@ -462,7 +463,11 @@ export const useSftpViewFileOps = ({
const status = await sftpRef.current.tryPackedDownload?.({ ...request, localDirectory }) ?? "regular";
if (status === "conflict") {
if (!window.confirm(t("sftp.packedDownload.conflict"))) return null;
const destination = await selectDirectory?.(t("sftp.context.download"));
const destination = await selectDirectory?.(
t("sftp.context.download"),
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!destination) return null;
localDirectory = destination;
continue;
@@ -536,7 +541,11 @@ export const useSftpViewFileOps = ({
return;
}
const selectedDirectory = await selectDirectory(t("sftp.context.download"));
const selectedDirectory = await selectDirectory(
t("sftp.context.download"),
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!selectedDirectory) return;
// The picker may stay open while the remote entry changes again.
@@ -586,7 +595,11 @@ export const useSftpViewFileOps = ({
return;
}
const targetPath = await showSaveDialog(file.name);
const targetPath = await showSaveDialog(
file.name,
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!targetPath) return;
const selectedSnapshot = await resolveDownloadSourceSnapshot(
@@ -774,7 +787,11 @@ export const useSftpViewFileOps = ({
return;
}
const parents = paths.map((path) => getParentPath(path));
let selectedDirectory = await selectDirectory(t("sftp.context.download"));
let selectedDirectory = await selectDirectory(
t("sftp.context.download"),
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!selectedDirectory) return;
if (parents.every((parent) => parent === parents[0]) && files.every((file) => file.type !== "symlink")) {
@@ -19,8 +19,16 @@ export interface UseSftpViewFileOpsParams {
systemApp?: SystemAppInfo,
) => void;
t: (key: string, vars?: Record<string, string | number>) => string;
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
showSaveDialog?: (
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
selectDirectory?: (
title?: string,
defaultPath?: string,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
/** Application-layer fresh stat for download source snapshots (kept off the raw bridge). */
statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<SftpStatResult>;
@@ -25,8 +25,16 @@ interface UseSftpViewPaneCallbacksParams {
) => void;
t: (key: string, vars?: Record<string, string | number>) => string;
listSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<RemoteFile[]>;
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
showSaveDialog?: (
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
selectDirectory?: (
title?: string,
defaultPath?: string,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<SftpStatResult>;
listLocalFiles: (path: string) => Promise<RemoteFile[]>;
@@ -212,3 +212,88 @@ test("duplicate-name downloads keep captured paths and stop when the source conn
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
}
});
test("download dialogs open in the configured default download folder", async () => {
const globals = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
localStorage?: Storage;
};
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
const hadLocalStorage = Object.prototype.hasOwnProperty.call(globals, "localStorage");
const previousLocalStorage = globals.localStorage;
globals.IS_REACT_ACT_ENVIRONMENT = true;
const store = new Map<string, string>();
Object.defineProperty(globals, "localStorage", {
configurable: true,
writable: true,
value: {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => { store.set(key, String(value)); },
removeItem: (key: string) => { store.delete(key); },
clear: () => store.clear(),
key: () => null,
get length() { return store.size; },
} as Storage,
});
const types = new Map<string, SftpStatResult>([
["/remote/a.txt", { name: "a.txt", size: 1, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/b.txt", { name: "b.txt", size: 1, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/dir", { name: "dir", size: 0, sizeKnown: true, type: "directory", lastModified: 0 }],
]);
const saveOptions: unknown[] = [];
const directoryOptions: unknown[] = [];
const connection = { id: "conn-1", hostId: "host-1", hostLabel: "Host", currentPath: "/remote", isLocal: false };
const pane = { connection, filenameEncoding: "auto" };
const sftpRef = { current: {
leftPane: pane, rightPane: pane,
joinPath: (parent: string, name: string) => `${parent}/${name}`,
tryPackedDownload: async () => "regular",
downloadToLocal: async () => "completed",
} as unknown as SftpStateApi };
let ops: ReturnType<typeof useSftpViewFileOps> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpViewFileOps({
sftpRef,
behaviorRef: { current: "" },
autoSyncRef: { current: false },
getOpenerForFileRef: { current: () => null },
setOpenerForExtension: () => undefined,
t: (key) => key,
showSaveDialog: async (name, _filters, options) => { saveOptions.push(options); return `/picked/${name}`; },
selectDirectory: async (_title, _defaultPath, options) => { directoryOptions.push(options); return "/picked"; },
getSftpIdForConnection: () => "sftp-1",
statSftp: async (_id, path) => types.get(path) ?? null as unknown as SftpStatResult,
listSftp: async () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
const single = ops!.onDownloadFileLeft as unknown as (entry: SftpFileEntry) => Promise<void>;
const batch = ops!.onDownloadFilesLeft as unknown as (entries: SftpFileEntry[]) => Promise<void>;
await act(async () => { await single(file("a.txt", 1)); });
assert.deepEqual(saveOptions.at(-1), { fallbackDirectory: "downloads" },
"unset preference falls back to the system Downloads folder");
store.set("netcatty_sftp_default_download_dir_v1", "/home/me/server-files");
const configured = { preferredDirectory: "/home/me/server-files", fallbackDirectory: "downloads" };
await act(async () => { await single(file("a.txt", 1)); });
assert.deepEqual(saveOptions.at(-1), configured, "Save As opens in the configured folder");
await act(async () => { await single(file("dir", 0, "directory")); });
assert.deepEqual(directoryOptions.at(-1), configured, "folder downloads use the configured folder");
await act(async () => { await batch([file("a.txt", 1), file("b.txt", 1)]); });
assert.deepEqual(directoryOptions.at(-1), configured, "multi-select downloads use the configured folder");
} finally {
await act(async () => { renderer?.unmount(); });
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
if (hadLocalStorage) {
Object.defineProperty(globals, "localStorage", { configurable: true, writable: true, value: previousLocalStorage });
} else {
delete (globals as { localStorage?: Storage }).localStorage;
}
}
});
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { I18nProvider } from '../../application/i18n/I18nProvider';
import { loadLocaleMessages } from '../../application/i18n/messages';
import { terminalCwdStore } from '../../application/state/terminalCwdStore';
import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController';
import { registerTerminalDirectory } from '../../application/state/terminalDirectoryRegistry';
import { ComposeDirectoryPicker } from './ComposeDirectoryPicker';
import type { ComposeBarTheme } from './TerminalComposeBar';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
for (const home of [null, '/tmp'] as const) {
test(`chip text, title and ARIA retain the confirmed display during a null cwd (home=${home})`, async t => {
await loadLocaleMessages('zh-CN');
const sessionId = 'chip-display-' + home;
const cwd = '/tmp/test_dir';
let root!: ReactTestRenderer;
let unregister = () => {};
t.after(async () => { await act(async () => { root.unmount(); }); unregister(); });
await act(async () => {
root = create(<I18nProvider locale="zh-CN">
<ComposeDirectoryPicker sessionId={sessionId} theme={{} as ComposeBarTheme} onReturnFocus={() => {}} />
</I18nProvider>);
});
const chip = () => root.root.findByType('button');
const text = () => root.root.findByProps({ className: 'truncate' }).children.join('');
assert.equal(text(), '\u76ee\u5f55\u672a\u77e5');
assert.equal(chip().props.title, text());
assert.ok(chip().props['aria-label'].includes(text()));
await act(async () => {
unregister = registerTerminalDirectory(sessionId, createTerminalDirectoryController({
sessionId, isCurrent: () => true, isReady: () => true,
io: { cwd: async () => cwd, home: async () => home, realpath: async path => path,
write() { assert.fail('display updates must not write to the terminal'); }, list: async () => ({ home, entries: [] }) },
publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'),
}));
});
const label = home ? '~/test_dir' : cwd;
assert.equal(text(), label);
const aria = chip().props['aria-label'];
assert.ok(aria.includes(label));
assert.equal(chip().props.title, cwd);
await act(async () => { terminalCwdStore.setCwd(sessionId, null); });
assert.equal(terminalCwdStore.getCwd(sessionId), null);
assert.equal(text(), label);
assert.equal(chip().props.title, cwd);
assert.equal(chip().props['aria-label'], aria);
});
}
@@ -2,7 +2,7 @@ import { ArrowUp, ChevronDown, Folder, LoaderCircle, RefreshCw } from 'lucide-re
import { memo, useEffect, useId, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useComposeDirectoryPicker } from '../../application/state/useComposeDirectoryPicker';
import { directoryDisplayName, directoryLabel } from '../../domain/directoryPicker';
import { directoryDisplayName } from '../../domain/directoryPicker';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import type { ComposeBarTheme } from './TerminalComposeBar';
@@ -51,8 +51,8 @@ export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ ses
<Popover open={model.open} onOpenChange={value => { if (value) outside.current = false; model.setOpen(value); }}>
<PopoverTrigger asChild>
<button type="button" disabled={model.pending}
aria-label={t('terminal.directory.open', { path: model.cwd ? directoryLabel(model.cwd, model.home, model.pathFlavor) : t('terminal.directory.unknown') })}
title={model.cwd ? directoryDisplayName(model.cwd) : t('terminal.directory.unknown')}
aria-label={t('terminal.directory.open', { path: model.display?.ariaPath ?? t('terminal.directory.unknown') })}
title={model.display?.title ?? t('terminal.directory.unknown')}
className="h-6 min-w-0 max-w-full flex items-center gap-1.5 rounded border px-2 text-[11px] font-mono transition-colors duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-60"
style={{ backgroundColor: theme.chipBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
onMouseEnter={(event) => {
@@ -63,7 +63,7 @@ export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ ses
}}
>
{model.pending ? <LoaderCircle size={12} className="shrink-0 animate-spin" /> : <Folder size={12} className="shrink-0" />}
<span className="truncate">{model.cwd ? directoryDisplayName(directoryLabel(model.cwd, model.home, model.pathFlavor)) : t('terminal.directory.unknown')}</span>
<span className="truncate">{model.display?.label ?? t('terminal.directory.unknown')}</span>
<ChevronDown size={10} className="shrink-0 opacity-60" />
</button>
</PopoverTrigger>
@@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
import type { Host } from "../../types.ts";
import { TerminalConnectionDialog } from "./TerminalConnectionDialog.tsx";
import { TerminalConnectionDialog, resolveChainProgressAddressLine } from "./TerminalConnectionDialog.tsx";
const host: Host = {
id: "host-1",
@@ -193,6 +193,68 @@ test("keeps connection log padding inside the scrollable content", () => {
assert.match(markup, /class="[^"]*p-2\.5[^"]*pb-4[^"]*pr-4/);
});
test("chain progress shows the current jump hop's address, not the target's", () => {
const markup = renderDialog({
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
chainProgress: {
currentHop: 2,
totalHops: 3,
currentHostLabel: "Bastion B",
currentHostAddress: "b.example.com:2201",
},
});
assert.match(markup, /Chain 2 of 3: <\/span><span>Bastion B<\/span>/);
assert.match(markup, /SSH b\.example\.com:2201/);
assert.equal(markup.includes("10.0.0.5"), false);
});
test("chain progress shows the target's label and address on the final hop", () => {
const markup = renderDialog({
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
chainProgress: {
currentHop: 3,
totalHops: 3,
currentHostLabel: "Prod DB",
currentHostAddress: "10.0.0.5:22",
},
});
assert.match(markup, /Chain 3 of 3: <\/span><span>Prod DB<\/span>/);
assert.match(markup, /SSH 10\.0\.0\.5:22/);
});
test("chain progress address line keeps the target's protocol on the final hop", () => {
const t = (key: string) => ({
"terminal.connection.protocol.ssh": "SSH",
"terminal.connection.protocol.et": "ET",
}[key] ?? key);
const etInfo = { i18nKey: "terminal.connection.protocol.et", showPort: true, port: 2022 };
const target = { hostname: "10.0.0.5" };
// Jump hop: always SSH with the hop's own address.
assert.equal(
resolveChainProgressAddressLine(
{ currentHop: 1, totalHops: 2, currentHostAddress: "bastion.example.com:22" },
target, etInfo, t,
),
"SSH bastion.example.com:22",
);
// Final hop: the target's protocol and port (ET 2022, not the SSH port).
assert.equal(
resolveChainProgressAddressLine(
{ currentHop: 2, totalHops: 2, currentHostAddress: "10.0.0.5:22" },
target, etInfo, t,
),
"ET 10.0.0.5:2022",
);
// Older progress events without an address fall back to the target.
assert.equal(
resolveChainProgressAddressLine({ currentHop: 1, totalHops: 2 }, target, etInfo, t),
"ET 10.0.0.5:2022",
);
});
test("shows the ET server port (not the SSH port) for an ET host with a custom etPort", () => {
const markup = renderDialog({
host: { ...host, etEnabled: true, port: 22, etPort: 9022 },
@@ -28,8 +28,29 @@ export interface ChainProgress {
currentHop: number;
totalHops: number;
currentHostLabel: string;
/** host:port of the hop being connected; falls back to the target's address. */
currentHostAddress?: string;
}
/**
* Address line under the "Chain X of Y" heading. Jump hops are always SSH, so
* they show the hop's own address; the final hop keeps the target's
* protocol-aware line (Mosh/ET/Telnet ports differ from the SSH port).
*/
export const resolveChainProgressAddressLine = (
chainProgress: Pick<ChainProgress, 'currentHop' | 'totalHops' | 'currentHostAddress'>,
host: Pick<Host, 'hostname'>,
protocolInfo: { i18nKey: string; showPort: boolean; port: number },
t: (key: string) => string,
): string => {
const isJumpHop = chainProgress.currentHop < chainProgress.totalHops;
if (isJumpHop && chainProgress.currentHostAddress) {
return `${t('terminal.connection.protocol.ssh')} ${chainProgress.currentHostAddress}`;
}
const address = protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname;
return `${t(protocolInfo.i18nKey)} ${address}`;
};
export interface TerminalConnectionDialogProps {
host: Host;
status: 'connecting' | 'connected' | 'disconnected';
@@ -304,7 +325,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
className="text-[10px] font-mono truncate"
style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }}
>
{t(protocolInfo.i18nKey)} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
{resolveChainProgressAddressLine(chainProgress, host, protocolInfo, t)}
</div>
</>
) : (
@@ -41,6 +41,7 @@ import { resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshA
import { connectionTotpFields } from "../../../domain/totpConfig";
import { requiresFidoSshAgentAuth } from "../../../domain/fidoSsh";
import {
formatHostPort,
hostRestrictsExtraSshChannels,
resolveHostKeepalive,
resolveTelnetPassword,
@@ -642,12 +643,15 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
totalHops,
currentHostLabel:
jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname,
currentHostAddress: jumpHosts[0]?.hostname
? formatHostPort(jumpHosts[0].hostname, jumpHosts[0].port || 22)
: undefined,
connectionPhase: 'connecting',
});
}
{
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error) => {
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error, address) => {
// P1: Only process events for this session
if (sid !== ctx.sessionId) return;
// Disconnect/reconnect can leave two SSH starts sharing this UI
@@ -660,6 +664,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
currentHop: hop,
totalHops: total,
currentHostLabel: label,
currentHostAddress: address,
connectionPhase: status,
});
}
@@ -95,7 +95,7 @@ export type TerminalBackendApi = {
error?: string;
}>;
onChainProgress: (
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void,
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void,
) => (() => void) | undefined;
onConnectionReuseFallback?: (
cb: (sessionId: string, sourceSessionId?: string) => void,
@@ -126,6 +126,8 @@ type ChainProgressState = {
currentHop: number;
totalHops: number;
currentHostLabel: string;
/** host:port of the hop being connected; absent from older progress events. */
currentHostAddress?: string;
connectionPhase: string;
} | null;
@@ -21,5 +21,6 @@ test("Ctrl-H mode makes Backspace delete on network-device serial consoles", ()
test("default mode preserves xterm Backspace and ordinary input", () => {
assert.equal(mapTerminalBackspaceInput("\x7f", undefined), "\x7f");
assert.equal(mapTerminalBackspaceInput("\x7f", "default"), "\x7f");
assert.equal(mapTerminalBackspaceInput("show version", "ctrl-h"), "show version");
});
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { JSDOM } from 'jsdom';
@@ -19,6 +20,35 @@ import {
resolveSidePanelPortalTarget,
} from './terminalLayerSidePanelSlots.tsx';
test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it away', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const paneHost = source.slice(
source.indexOf('function SidePanelPaneHost'),
source.indexOf('function TerminalLayerSidePanelInner'),
);
assert.ok(paneHost.length > 0, 'SidePanelPaneHost source slice must exist');
// The close button is the only button in the pane header; it must not shrink
// when the pane label is truncated at narrow split widths.
const closeButton = paneHost.match(/<button[\s\S]*?aria-label=\{`\$\{closePaneLabel\}/);
assert.ok(closeButton, 'pane header close button must exist');
assert.match(
closeButton![0],
/className="[^"]*\bshrink-0\b[^"]*"/,
'pane header close button must carry shrink-0 so it stays visible at narrow widths',
);
});
test('magnified side panels use a continuous 1px inset outline in the side panel accent', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /outline: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(chromeSource, /outlineOffset: -1/);
assert.doesNotMatch(chromeSource, /\bborder(?:Color|Width|Style)?\b/);
});
test('AI side panel shell can be force-hidden for layout isolation', () => {
assert.equal(getTerminalSidePanelShellWidth({
activeSidePanelTab: 'ai',
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
const MemoizedSidePanelMountedContent = memo(
SidePanelMountedContent,
@@ -168,7 +168,7 @@ function SidePanelPaneHost({
<span className="text-[11px] font-medium truncate flex-1">{label}</span>
<button
type="button"
className="h-5 w-5 grid place-items-center rounded-sm opacity-70 hover:opacity-100 hover:bg-white/10"
className="h-5 w-5 shrink-0 grid place-items-center rounded-sm opacity-70 hover:opacity-100 hover:bg-white/10"
aria-label={`${closePaneLabel}: ${label}`}
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => {
@@ -1567,12 +1567,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
style={{
borderColor: sidePanelTheme.accent,
borderWidth: resolveMagnifiedChromeBorderWidth(
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
),
outline: `1px solid ${sidePanelTheme.accent}`,
outlineOffset: -1,
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
}}
@@ -53,7 +53,6 @@ import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePane
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
PANE_MAGNIFICATION_DURATION_MS,
resolveMagnifiedChromeBorderWidth,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
type PaneMagnificationController,
@@ -683,6 +682,7 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE
AIChatPanelsHost.displayName = 'AIChatPanelsHost';
export interface TerminalLayerProps {
isVaultInitialized?: boolean;
hosts: Host[];
portForwardingRules?: import('../../domain/models').PortForwardingRule[];
customGroups: string[];
@@ -822,6 +822,7 @@ interface TerminalPaneProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -961,6 +962,7 @@ const terminalPanePropsAreEqual = (
prev.splitHorizontalHandlersRef === next.splitHorizontalHandlersRef &&
prev.splitVerticalHandlersRef === next.splitVerticalHandlersRef &&
getPaneAppearanceThemeId(prev) === getPaneAppearanceThemeId(next) &&
prev.isVaultInitialized === next.isVaultInitialized &&
prev.keys === next.keys &&
prev.identities === next.identities &&
prev.snippets === next.snippets &&
@@ -1253,6 +1255,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -1643,14 +1646,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
"absolute bg-background",
inActiveWorkspace && "workspace-pane",
isVisible && "z-10",
isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
)}
style={{
...style,
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
borderWidth: isMagnified && magnifiedSurfaceBounds
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
outline: magnifiedSurfaceBounds
? `1px solid ${sessionAppearanceTheme.colors.cursor}`
: undefined,
outlineOffset: magnifiedSurfaceBounds ? -1 : undefined,
}}
tabIndex={-1}
onClick={handlePaneClick}
@@ -1680,6 +1683,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
sessionId={session.id}
workspaceId={session.workspaceId}
restoreState={session.restoreState}
vaultInitializedOverride={isVaultInitialized}
pendingInitialCwd={session.pendingInitialCwd}
shellType={session.shellType}
lastCwd={session.lastCwd}
@@ -1776,6 +1780,7 @@ interface TerminalPanesHostProps {
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
hostMap: Map<string, Host>;
isVaultInitialized?: boolean;
keys: SSHKey[];
identities: Identity[];
snippets: Snippet[];
@@ -1871,6 +1876,7 @@ const terminalPanesHostPropsAreEqual = (
if (prev.splitVerticalHandlersRef !== next.splitVerticalHandlersRef) return false;
if (prev.resolveSessionAppearance !== next.resolveSessionAppearance) return false;
if (prev.hostMap !== next.hostMap) return false;
if (prev.isVaultInitialized !== next.isVaultInitialized) return false;
if (prev.keys !== next.keys) return false;
if (prev.identities !== next.identities) return false;
if (prev.snippets !== next.snippets) return false;
@@ -9,14 +9,41 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("magnified terminal panes use the resolved terminal accent for border chrome", () => {
test("terminal pane chrome follows retained surface bounds through restore with a continuous 1px inset outline", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl"/);
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
assert.match(paneSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
assert.match(paneSource, /outline: magnifiedSurfaceBounds\s+\? `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`\s+: undefined/);
assert.match(paneSource, /outlineOffset: magnifiedSurfaceBounds \? -1 : undefined/);
assert.doesNotMatch(paneSource, /\bborder(?:Color|Width|Style)?\b/);
});
test("restoring terminal chrome keeps its 1px inset outline until surface bounds clear at any DPR", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
const styleSource = paneSource.match(/style=\{\{([\s\S]*?)\}\}/);
assert.ok(styleSource);
const resolveStyle = new Function(
"style", "isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme",
"magnifiedDevicePixelRatio",
`return ({${styleSource[1]}});`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStyle({}, true, bounds, theme, dpr);
const restoring = resolveStyle({}, false, bounds, theme, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.outline, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.outlineOffset, -1);
for (const isMagnified of [false, true]) {
const cleared = resolveStyle({}, isMagnified, null, theme, dpr);
assert.equal(cleared.outline, undefined);
assert.equal(cleared.outlineOffset, undefined);
}
}
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
@@ -62,6 +62,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef,
resolveSessionAppearance,
hostMap,
isVaultInitialized,
keys,
identities,
snippets,
@@ -230,6 +231,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
splitVerticalHandlersRef={splitVerticalHandlersRef}
resolveSessionAppearance={resolveSessionAppearance}
hostMap={hostMap}
isVaultInitialized={isVaultInitialized}
keys={keys}
identities={identities}
snippets={snippets}
@@ -383,6 +383,7 @@ const WORKSPACE_CTX_KEYS = [
'splitVerticalHandlersRef',
'resolveSessionAppearance',
'hostMap',
'isVaultInitialized',
'keys',
'identities',
'snippets',
+1
View File
@@ -4,6 +4,7 @@ export const terminalLayerAreEqual = (
prev: Record<string, unknown>,
next: Record<string, unknown>,
): boolean => (
prev.isVaultInitialized === next.isVaultInitialized &&
prev.hosts === next.hosts &&
prev.customGroups === next.customGroups &&
prev.groupConfigs === next.groupConfigs &&
+5 -16
View File
@@ -26,8 +26,6 @@ import { resolveSessionCodingCliProvider } from '../../domain/codingCliProviderM
import type { CodingCliProvider } from '../../domain/codingCliProviders';
import { resolveCodingCliActivityPhase, type CodingCliActivityPhase } from '../../domain/codingCliTitleParse';
import {
buildMergedWorkspaceTitleFromSessions,
DEFAULT_WORKSPACE_TITLE,
resolveSessionTabTitle,
resolveWorkspaceTabLabel,
} from '../../domain/sessionTabTitle';
@@ -261,24 +259,15 @@ export const formatSessionTopTabLabel = (
type WorkspaceTopTabLabelWorkspace = Pick<
Workspace,
'title' | 'focusedSessionId' | 'autoTitle'
> & {
generatedTitle?: boolean;
};
'title' | 'focusedSessionId' | 'autoTitle' | 'generatedTitle'
>;
export const resolveWorkspaceTopTabLabel = (
workspace: WorkspaceTopTabLabelWorkspace,
sessions: readonly TerminalSession[],
dynamicTabTitleMode?: DynamicTabTitleMode,
): string => {
const presentedSessions = sessions.map(applySessionPresentation);
const resolvedWorkspace = workspace.generatedTitle
? {
...workspace,
title: buildMergedWorkspaceTitleFromSessions(presentedSessions) ?? DEFAULT_WORKSPACE_TITLE,
autoTitle: false,
}
: workspace;
return resolveWorkspaceTabLabel(resolvedWorkspace, presentedSessions);
return resolveWorkspaceTabLabel(workspace, sessions.map(applySessionPresentation), dynamicTabTitleMode);
};
export const createTopTabCopyDoubleClickHandler = (
@@ -1106,7 +1095,7 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
[onCopyWorkspace, workspace.id, tabDoubleClickBehavior],
);
const detachSessions = workspaceSessions ?? [];
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions);
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions, dynamicTabTitleMode);
return (
<ContextMenu>
+121
View File
@@ -0,0 +1,121 @@
# Long-running jobs on many sessions (`terminal_start_bulk`, `terminal_poll_bulk`, `terminal_stop_bulk`)
These tools start the same long-running command as a background job on 2–20 open
terminal sessions, then poll and stop those jobs together. They are the bulk versions
of `terminal_start`, `terminal_poll` and `terminal_stop`, for upgrades, builds, scans
or log checks across hosts. For short commands on many sessions use
`terminal_execute_bulk` (see [terminal-execute-bulk.md](terminal-execute-bulk.md)).
They are available to MCP clients only. Load them over MCP with `load_netcatty_tools`
and the `terminal_bulk` toolset.
## `terminal_start_bulk`
| Field | Type | Notes |
|---|---|---|
| `command` | string | Same rules as `terminal_start`. |
| `sessionIds` | string | JSON array of 2–20 unique session IDs. Resolve IDs with `get_environment`. |
Before anything starts, every target is checked with the rules `terminal_start` uses:
session scope, closing, already busy, connected, a shell-backed PTY (network devices,
serial sessions and sessions without a writable terminal are refused), and the command
safety policy for that session's shell. If **any** target fails, no job starts on any
host and the call fails, listing every bad target at once. Out-of-scope IDs are
reported without a label.
Approval works like `terminal_execute_bulk`: observer mode refuses, confirm mode asks
**once** with a card listing the command and every host, and that approval is never
satisfied by a remembered grant or by "allow for this session". In confirm mode no host
is contacted before you answer; the shell-kind probe and the shell-specific safety
patterns run right after approval, before any job starts. Sessions hosted by the
terminal worker are checked the same way, with a no-send `precheck` of the worker's
job start.
```json
{
"ok": true,
"bulkId": "bulk_m1x2y3_ab12cd34",
"hostCount": 3,
"counts": { "running": 3 },
"jobs": [
{ "sessionId": "s-web1", "label": "web1", "jobId": "job_…", "status": "running" },
{ "sessionId": "s-web2", "label": "web2", "jobId": "job_…", "status": "running" },
{ "sessionId": "s-db1", "label": "db1", "jobId": "job_…", "status": "running" }
],
"recommendedPollIntervalMs": 30000
}
```
- `running` means the job was **launched**. As with `terminal_start`, a terminal that is
not ready when the command is sent (a pager, a password prompt, a prompt that cannot
be recognized) shows up as `failed` on the first poll.
- A host whose job could not be started at all is listed with `status: "not_started"` and
an `error`; the other jobs keep running, because jobs already started are not undone.
If no job started, the call fails with `Error: No background job was started.`
- Each session stays busy until its job ends (at most 1 hour), so other commands on it
are refused meanwhile.
- Jobs keep running when the agent run is stopped. Stop them with `terminal_stop_bulk`.
- There is no way to answer prompts in a running job, so use non-interactive commands
(`-y`, `DEBIAN_FRONTEND=noninteractive`, `sudo -n`).
## `terminal_poll_bulk`
| Field | Type | Notes |
|---|---|---|
| `bulkId` | string, optional | From `terminal_start_bulk`. Pass this or `jobIds`. |
| `jobIds` | string, optional | JSON array of 1–20 job IDs, instead of a `bulkId`. |
| `offsets` | string, optional | JSON object `{ "<jobId>": <nextOffset> }` from the previous poll. Missing jobs start at 0. |
```json
{
"ok": true,
"bulkId": "bulk_m1x2y3_ab12cd34",
"jobCount": 3,
"allCompleted": false,
"counts": { "running": 1, "completed": 1, "failed": 1 },
"jobs": [
{ "jobId": "job_…", "sessionId": "s-web1", "label": "web1", "status": "running", "exitCode": null, "nextOffset": 5120, "output": "…" },
{ "jobId": "job_…", "sessionId": "s-web2", "label": "web2", "status": "completed", "exitCode": 0, "nextOffset": 9000, "output": "…" },
{ "jobId": "job_…", "sessionId": "s-db1", "label": "db1", "status": "failed", "exitCode": 100, "nextOffset": 300, "output": "…", "error": "…" }
],
"recommendedPollIntervalMs": 30000
}
```
- Each job returns at most 4 KB of new output, and all jobs together at most 32 KB.
The total is shared by need: jobs with little new output take only what they need,
and the rest goes to busy jobs (with 20 busy jobs, about 1.6 KB each). When a job has
more new output than its share, the **newest** output is returned and `skippedChars`
says how much was skipped. Output older than the job's kept window (the last 256 KB)
also counts as skipped. Use `terminal_poll` on one job for its full output.
- Pass each job's `nextOffset` back in `offsets` to get only new output next time.
Offsets count the raw output; progress redraws (`\r`) are collapsed to the latest frame.
- `allCompleted` is `true` when no job is `running` or `stopping`.
- A job that expired (10 minutes after it finished), is out of scope, or belongs to
another chat is reported per job with `status: "unavailable"`; the poll itself still
succeeds.
## `terminal_stop_bulk`
| Field | Type | Notes |
|---|---|---|
| `bulkId` | string, optional | From `terminal_start_bulk`. Pass this or `jobIds`. |
| `jobIds` | string, optional | JSON array of 1–20 job IDs, instead of a `bulkId`. |
Stops every job with the existing `terminal_stop` behavior: no approval, and it works
in observer mode, so a runaway rollout can always be stopped. Each job reports its
status (`stopping`, or its final status if it already ended); missing jobs are reported
per job as `unavailable`.
## `bulkId`
A `bulkId` names the jobs one `terminal_start_bulk` call started, so polling and
stopping need one ID instead of many. It belongs to the chat that created it, like each
job does, and expires after the jobs' lifetime (75 minutes). After that, poll or stop
the jobs by `jobIds`.
## Not included
The in-app agents (Catty and the global agent) do not get these tools yet, and plugin
agents cannot call them. Sending input to running jobs, targets by group or tag, and
opening missing sessions are not part of these tools.
+4 -2
View File
@@ -3,7 +3,8 @@
`terminal_execute_bulk` runs the same short command on 2–20 open terminal sessions and
waits for all of them. It is available to MCP clients only (the in-app agents do not get it yet). Load it
over MCP with `load_netcatty_tools` and the `terminal_bulk` toolset. For a single host use
`terminal_execute`; fewer than 2 sessions is rejected.
`terminal_execute`; fewer than 2 sessions is rejected. For long-running commands on many sessions use
`terminal_start_bulk` (see [terminal-bulk-jobs.md](terminal-bulk-jobs.md)).
## Input
@@ -106,7 +107,8 @@ are grouped, which keeps the response small on large fleets.
`cancelled`, `connection_lost`, `error`, or `not_sent`.
- `exitCode` is a number only for `completed`. A non-zero exit code is a normal result,
not a tool failure. Serial and network-device sessions have no exit code (`null`).
- `stderr` and `error` are omitted when empty.
- `stderr` and `error` are omitted when empty. On interactive terminals stderr is part of stdout, so `stderr` usually
appears only for sessions that run the command over an SSH exec channel.
- Output is grouped on the full, untruncated result, so two hosts that differ only in the
part that was cut off are never merged. `tailLines` and a per-group size cap are then
applied; a cut group has `outputTruncated: true` (also set when the exec layer had already dropped the beginning of a very large output) and, when lines were dropped,
@@ -8,7 +8,7 @@ Context Chips 位于终端撰写栏的快捷命令与输入区之间,为当前
| 功能 | 当前范围 | 文档 |
| --- | --- | --- |
| Directory Picker | 目录展示、当前层搜索、父级/子目录导航;POSIX 与 Windows PowerShell 适配 | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD 和 Git Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Git Branch | 后续接入仓库识别、分支读取与切换 | [Git Branch](git-branch.md) |
| Git Changes | 后续接入变更统计与详情入口 | [Git Changes](git-changes.md) |
| Node Version | 后续接入当前 shell 的运行时与版本管理器 | [Node Version](node-version.md) |
@@ -10,6 +10,7 @@
| Unix SSH | 活动会话的严格查询/OSC 7 | 同一认证连接的 SFTP | 绑定原终端,按连接能力确认 |
| Windows PowerShell 5.1/7 | 原 runspace 的 FileSystem ProviderPath | Windows 本地 FS | Set-Location -LiteralPath,等待新位置报告 |
| Windows CMD | 会话 PROMPT 的 `$P` | Windows 本地 FS | `cd /d`,等待原 CMD 报告目标位置 |
| Git for Windows Bash | 原 Bash 的 MSYS `/proc/<pid>/cwd` | MSYS 映射的 Windows 盘符路径 | Bash 内建 `cd`,重新读取原进程 cwd |
## 路径与能力模型
@@ -60,6 +61,12 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根
目录列表遵循 Windows 访问权限。系统兼容链接拒绝枚举时,菜单显示权限原因,并保留父目录入口。等待原 CMD 会话报告位置时,菜单显示对应的 CMD 状态,收到有效报告后恢复目录导航。
## Git Bash 会话集成
根据 Git for Windows 的安装记录识别 Bash。定位启动器下的原 Bash 进程后,用同一安装的 MSYS 工具读取 `/proc/<pid>/cwd`,再通过 `cygpath` 映射为 Windows 盘符路径。菜单按 Windows 文件系统展示父级和子目录,原会话使用 Bash 内建 `cd` 切换,并由新一次读取确认结果。
启动参数、profile 和提示符沿用用户配置。存在子进程时暂缓目录操作,原 Bash 恢复后重新读取。共享路径和虚拟挂载留到各自的路径语义明确后扩展。
## 后续设计方向
- POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。
@@ -9,6 +9,7 @@
| A:路径与能力 | POSIX/Win32 路径模型;盘符/UNC 根;authority、cwd revision;独立 read/list/change/confirm 能力;可注入命令策略 | 将目标文件系统和 shell 语法分别建模,保持菜单可复用 |
| B:PowerShell | 5.1/7 会话级脚本;原 runspace ProviderPath;私有位置报告;本地 FS;LiteralPath 切换和实际结果确认 | 用原 shell 状态串联展示、读取和执行 |
| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 |
| D1:Git Bash | 绑定原 Git for Windows Bash,读取 MSYS cwd 并映射为 Windows 盘符路径 | 保留 Bash 启动行为,复用 Windows 文件系统和目录控制器 |
| 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
@@ -16,6 +17,8 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
## 后续阶段
Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库与 worktree 状态推进 [Git Changes](git-changes.md) 和 [Pull Request](pull-request.md)。[Node Version](node-version.md) 独立接入 shell 与版本管理器。目录兼容性按环境分别提交。
### PowerShell 覆盖扩展
继续补充主题/profile 组合、prompt 内位置变化、受限语言模式、大小写敏感目录和共享目录权限场景。每项先建立原生 ConPTY fixture,再完善能力状态和路径确认策略。
@@ -35,12 +38,12 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。
### D:WSL、Git Bash 与 Cygwin
### D2/D3:WSL 与 Cygwin
为每类环境定义文件系统 authority、cwd 来源、结构化目录 helper 与执行策略:
- WSL:绑定所选 distro,验证 Linux home、挂载盘及 wslpath/UNC 映射。
- MSYS/Cygwin:验证 mount、驱动器、链接和编码转换。
- Cygwin:验证 mount、驱动器、链接和编码转换。Git Bash 后续补充共享路径和虚拟挂载语义。
- helper:保留原始名称、类型和目录链接,提供输出边界、取消及权限状态。
交付目标是让目录读取与命令执行处于同一命名空间,并按 distro/mount 身份组织缓存。
+23
View File
@@ -0,0 +1,23 @@
import { directoryDisplayName, directoryLabel } from './directoryPicker';
import type { DirectoryPathFlavor } from './directoryPath';
export type ComposeDirectoryDisplay = {
home: string | null;
label: string;
title: string;
ariaPath: string;
};
/** Display only: a retained label must never be used as a live cwd. */
export function resolveComposeDirectoryDisplay(
previous: ComposeDirectoryDisplay | null,
cwd: string | null,
home: string | null,
flavor: DirectoryPathFlavor,
): ComposeDirectoryDisplay | null {
// Native Windows nulls can mean a non-filesystem provider or integration failure.
if (!cwd) return flavor === 'posix' ? previous : null;
const displayHome = home ?? previous?.home ?? null;
const ariaPath = directoryLabel(cwd, displayHome, flavor);
return { home: displayHome, label: directoryDisplayName(ariaPath), title: directoryDisplayName(cwd), ariaPath };
}
+120
View File
@@ -6,10 +6,130 @@ import {
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding,
} from './customKeyBindings.ts';
import { DEFAULT_KEY_BINDINGS, keyStringToKeyboardEvent } from './models/keyBindings.ts';
import { checkAppShortcut } from '../application/state/useGlobalHotkeys.ts';
function shortcut(key: string, bindings = DEFAULT_KEY_BINDINGS, isMac = false) {
const event = keyStringToKeyboardEvent(key);
assert.ok(event);
return checkAppShortcut(event, bindings, isMac)?.action ?? null;
}
test('resolving defaults preserves reopen, new tab, and local terminal shortcuts', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {});
assert.deepEqual(bindings, DEFAULT_KEY_BINDINGS);
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
assert.equal(shortcut('Ctrl + T', bindings), 'newTab');
assert.equal(shortcut('\u2318 + L', bindings, true), 'openLocal');
});
test('custom PC open-local evicts the conflicting reopen default only on PC', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'openLocal');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
});
test('custom macOS open-local evicts the conflicting reopen default only on macOS', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { mac: '\u2318 + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, '\u2318 + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.mac, 'Disabled');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'openLocal');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
});
test('unrelated custom shortcuts leave reopen defaults intact', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + L' },
});
assert.equal(shortcut('Ctrl + L', bindings), 'openLocal');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
});
for (const [id, key] of [['copy', 'C'], ['paste', 'V']]) {
test(`recording the terminal ${id} default preserves the SFTP default`, () => {
const chord = `\u2318 + ${key}`;
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
[id]: { mac: chord },
});
assert.equal(bindings.find(binding => binding.id === id)?.mac, chord);
assert.equal(bindings.find(binding => binding.id === `sftp-${id}`)?.mac, chord);
});
}
test('custom SFTP chords preserve conflicting app-level defaults on both schemes', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'sftp-copy': { mac: '\u2318 + Shift + T', pc: 'Ctrl + Shift + T' },
});
for (const id of ['sftp-copy', 'reopen-closed-tab']) {
assert.equal(bindings.find(binding => binding.id === id)?.mac, '\u2318 + Shift + T');
assert.equal(bindings.find(binding => binding.id === id)?.pc, 'Ctrl + Shift + T');
}
});
test('custom SFTP chords still evict conflicting defaults within SFTP', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'sftp-copy': { mac: '\u2318 + V', pc: 'Ctrl + V' },
});
assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.mac, '\u2318 + V');
assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.pc, 'Ctrl + V');
assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.mac, 'Disabled');
assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.pc, 'Disabled');
assert.equal(bindings.find(binding => binding.id === 'paste')?.mac, '\u2318 + V');
});
test('conflicting custom shortcuts remain while uncustomized defaults are evicted', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
'open-hosts': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'open-hosts')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
});
test('an explicitly customized reopen binding retains its conflicting chord', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { pc: 'Ctrl + Shift + T' },
'reopen-closed-tab': { pc: 'Ctrl + Shift + T' },
});
assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T');
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T');
});
test('resolving conflicts does not mutate defaults or custom overrides', () => {
const defaults = structuredClone(DEFAULT_KEY_BINDINGS);
const custom = { 'open-local': { pc: 'Ctrl + Shift + T', mac: 'Disabled' } };
const originalCustom = structuredClone(custom);
const bindings = resolveKeyBindings(defaults, custom);
assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, 'Disabled');
assert.deepEqual(defaults, DEFAULT_KEY_BINDINGS);
assert.deepEqual(custom, originalCustom);
});
test('parses legacy stored custom key bindings without sync metadata', () => {
const parsed = parseCustomKeyBindingsStorageRecord('{"open":{"mac":"Cmd+K"}}');
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more