Compare commits

..
Author SHA1 Message Date
陈大猫 36fbc8b85b fix(plugins): cancel stuck SSH exec dials before the plugin RPC deadline
Plugin vault.execHostCommand could hit "Plugin request deadline exceeded"
when a pooled SSH reconnect used the interactive 20s/120s handshake
timeouts, and retries hitchhiked on the leftover pendingDial.

- Stop and drop a pending plugin dial when its last waiter cancels
- Pass tighter startPortForward connect/auth budgets (8s/8s) under an
  18s prepare+dial envelope, and map failures to "SSH connection timed out"
- Evict half-open or channel-open/RPC-deadline-failed pooled connections
2026-12-02 01:49:26 +08:00
陈大猫 960cc05219 fix(ai): move chat manager multi-select into overflow menu and confirm bulk delete (#4618) 2026-12-02 00:56:52 +08:00
陈大猫 7ad4a7daf5 fix(plugins): raise host-ui view message budget, deduplicate SDK CSS, and log runtime/view failures (#4616) 2026-12-02 00:21:31 +08:00
Skyandbincxz 469cecb963 feat: add external remote editor integration and *.netcatty SSH bridge (#4496)
* feat: add external remote editor integration and *.netcatty SSH bridge

Add cross-platform external remote editor integration (Zed, VS Code, Cursor, Windsurf, and Custom) backed by an in-process *.netcatty OpenSSH channel multiplexer, session-scoped remote shell helpers (~/.netcatty/bin), terminal OSC 7337 handling with per-host trust, and SFTP 'Open in <Editor>' context menus.

* fix(external-editor): address Codex PR review findings

- Keep SSH bridge fallback transport selection within the originating hostId profile for both terminal and SFTP fallbacks
- Resolve managed SFTP transports via __netcattyRefHolder.connRef so editor leases keep transports alive after SFTP closes
- Apply bidirectional backpressure across stdout, stderr, and stdin in bridgeChannelStreams and cap early channel buffering
- Insert Host *.netcatty before earlier wildcard Host */Match rules in ~/.ssh/config and relocate legacy appended blocks on update
- Preserve raw custom-editor argument input draft until blur/Enter instead of stripping trailing whitespace per keystroke
- Extract terminal external-editor session provisioning and OSC 7337 handling into application/state/useTerminalExternalEditor.ts and reinstall helpers on preferred-editor change without re-injecting PATH

* fix(external-editor): address second round of Codex PR review findings

- Catch synchronous ssh2 remote-channel/forwarding open throws in attachClientChannelMultiplexer and close external bridge clients when upstream SSH transport closes
- Coordinate stdout and backpressured stderr completion (including stderr drain) before sending SSH channel EOF/close
- Move editor detection, SSH-config bridge install/remove, and application picker lifecycle state into useExternalEditorEnvironment in application/state/useExternalEditorSettings.ts
- Preserve raw executable-path draft while typing spaces and normalize on blur/Enter
- Preserve exact leading/trailing whitespace in remote POSIX paths across domain/externalEditor.ts and electron/bridges/externalEditorBridge.cjs

* fix(external-editor): address third round of Codex PR review findings

- Expand custom-editor placeholders in a single literal pass via replacer callback in both externalEditorBridge.cjs and domain/externalEditor.ts so path contents like $& or {kind} are never reinterpreted
- Track external bridge client closure in attachClientChannelMultiplexer and cancel late forwardIn listens (and destroy late forwardOut streams) if the client closes while upstream open is in flight
- Move autoFocus on the untrusted-host OSC 7337 prompt from Always Trust Host to Deny so accidental Enter never persists permanent host trust

* fix(external-editor): address fourth round of Codex PR review findings

- Prefer native .exe binaries on Windows editor detection and reject .cmd/.bat launchers in buildLaunchSpec so remote filenames never pass through cmd.exe
- Allocate long-path Unix domain socket fallbacks through Netcatty's managed tempDirBridge.getTempFilePath instead of os.tmpdir()
- Retain resolved sshConnectionPool transportId and complete normalized endpoint on registered bridge targets so subsequent editor SSH connections reuse surviving transports after originating terminal/SFTP sessions close

* fix(external-editor): address fifth round of Codex PR review findings

- Include effective connect-time endpoint (username@hostname:port) alongside hostId in buildSshBridgeHostname so per-session port/user overrides on the same saved profile never collide
- Resolve retained transportId and complete retained pool endpoint before looser session/SFTP fallbacks, and enforce effective endpoint tuple matching in both session and SFTP fallback loops
- Check managed tempDirBridge socket path against the 96-byte Unix socket limit and fall back to an authenticated ephemeral 127.0.0.1 loopback TCP listener when both stateDir and custom managed tempDir exceed Unix socket limits

* fix(external-editor): use effective SFTP endpoint for bridge aliases

- Store connect-time hostname, port, and username on SftpConnection and prefer them over saved profile fields in handleOpenInExternalEditorForSide
- Canonicalize the registered *.netcatty bridge hostname from the backend-resolved transport endpoint in sshChannelBridge.registerTarget whenever the resolved endpoint differs from the caller payload, and launch external editors using the returned canonical bridgeHost

* fix(external-editor): abort SSH-config install on non-ENOENT read errors

- Propagate non-ENOENT read failures (such as EACCES) in installSshBridgeConfig and removeSshBridgeConfig instead of treating unreadable ~/.ssh/config files as empty and overwriting them
- Clean up the temporary staging file if atomic write/rename fails

* fix(external-editor): require regular file check in netcatty-ssh-proxy launchers

On GitHub Actions (/home/runner/work/Netcatty/Netcatty/electron/cli),
../../../../Netcatty resolves to the ancestor directory /home/runner/work/Netcatty.
POSIX `[ -x ]` is true for searchable directories, causing `netcatty-ssh-proxy` to
attempt `exec` on the directory and fail with Permission denied.

Require `[ -f ... ] && [ -x ... ]` in `netcatty-ssh-proxy` (and guard against
directories in `netcatty-ssh-proxy.cmd`) and add a regression test matching the
nested checkout layout.

* fix(external-editor): harden reverse-forward, ssh config symlinks, macOS .app launch, and tmux helper

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-12-01 23:29:02 +08:00
GOUKI9999and陈大猫 3c7b19a208 fix(sync): make manual per-provider sync actually single-provider (#4611)
* fix(sync): make manual per-provider sync actually single-provider

* fix(sync): keep single-provider sync on convergent writer and preserve pause guard

* test(sync): assert manual per-provider sync stays on the convergent writer

The CI wiring test still required forceSingleProvider to skip the
convergent branch. After the product fix, a manual per-provider Sync
must stay on the convergent writer and only narrow the run with
targetProviders. Update that assertion and add behavioral coverage
that the selected provider gets a v2 write while others are left
untouched, and that omitting the filter still fans out.

---------

Co-authored-by: 陈大猫 <16399091+binaricat@users.noreply.github.com>
2026-12-01 23:27:50 +08:00
GOUKI9999 782a59d246 feat(ai): batch delete and AI title regeneration in chat manager (#4615)
* feat(ai): batch delete and AI title regeneration in chat manager

* fix(ai): honor selection mode on keyboard activation and keep title on regen failure
2026-12-01 22:35:07 +08:00
GOUKI9999 6a950e1eed fix(ai): clear uncontrolled composer textarea reliably after message send (#4614)
* fix(ai): clear uncontrolled composer textarea reliably after message send

* fix(ai): keep clearScopeDraft contract compatible with mountRetention test
2026-12-01 22:34:45 +08:00
Joseph Hau a6eaaed9ef feat(terminal): show the current Git branch in the compose bar (#4600)
* refactor(terminal): centralize confirmed directory state

* feat(terminal): show the current Git branch in the compose bar

* fix(terminal): resolve Git from the login shell PATH
2026-12-01 17:39:23 +08:00
HHXXYY 6d2132f7fa fix(win): add finish-page desktop shortcut option in NSIS installer (#4597) 2026-12-01 17:28:51 +08:00
GOUKI9999 f5afbaaf90 fix(sync): show AI chat and settings counts in local backup summaries (#4607) 2026-12-01 17:28:46 +08:00
Chrisandwendeng.dong 329d2b631c fix(rdp): 兼容连接完成后迟到的 Font Map [4589] (#4604)
Co-authored-by: wendeng.dong <wendeng.dong@sailuntire.com>
2026-12-01 17:28:42 +08:00
Netcatty-Botandgithub-actions[bot] ea5521cae8 Update Nix release metadata for v1.1.97 (#4596)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-12-01 17:28:19 +08:00
陈大猫 ae1fff28ae fix(terminal): join visual wraps without xterm wrap markers (#4609)
Fixes #4484
2026-12-01 16:53:52 +08:00
陈大猫 902c7b33c4 fix(terminal): forward isVaultInitialized and refresh ctx on stableRef updates (#4428) (#4610) 2026-12-01 16:42:43 +08:00
陈大猫andCodex 57b8ac53e3 fix(plugins): keep ER relation labels from overlapping table cards (#4594)
Related to binaricat/netcatty-database-plugin#18

Co-authored-by: Codex <codex@openai.com>
2026-12-01 07:56:10 +08:00
陈大猫 b0e11af042 fix(vault): persist plugin sidebar order across restart (#4592) (#4593)
Fixes #4592
2026-12-01 07:53:15 +08:00
HHXXYY 1851ee39b9 [Bug] Windows 顶部拖动区影响标签与窗口控件点击 (#4595)
* fix(ui): remove dead titlebar drag strip

* feat: add optional top tabs drag strip setting

* fix: restore default top tabs drag area
2026-12-01 07:52:13 +08:00
陈大猫 a01e58ac77 fix(plugins): invalidate Vite local CJS cache and log invalid view updates (#4591) 2026-12-01 07:36:28 +08:00
陈大猫 2b766abe6b fix(plugins): sanitize outbound RPC JSON, add durable file bindings, and use LIS diffing in hostDom (#4590) 2026-12-01 00:44:13 +08:00
GOUKI9999andbincxz 4b65002a78 feat(ai): richer chat list with workspace/agent and LLM titles (#4586)
* feat(ai): show workspace name and agent in global chat list

* feat(ai): one-shot LLM chat titles with dedicated title model

* fix(ai): address PR #4586 Codex review feedback and polish title/sync state

* fix(ai): redact full title inputs before truncation and budget reasoning tokens

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-12-01 00:40:30 +08:00
GOUKI9999andbincxz 520b434866 feat(ui): add session to workspace from tab menu and Ctrl+N (#4578)
* feat(ui): add session to workspace from tab menu and Ctrl+N

* fix(hotkeys): pass Ctrl/Cmd+N through when no workspace is active

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-12-01 00:34:15 +08:00
Joseph Hau 7cdb07e9ed feat(terminal): support directory navigation in Cygwin Bash (#4573) 2026-11-30 23:17:38 +08:00
陈大猫 1b15e9773f fix(sftp): keep Follow Terminal Directory during nested-shell commands (#4583)
Honor allowLoginShellFallback=false in getSessionPwd so Follow stays at the last probed path when a nested shell is running a command like sleep. Also refresh the Follow preference before command cwd probes so a stale SFTP-panel host snapshot cannot ignore a just-toggled Follow setting.

Fixes #4583
2026-11-30 22:00:56 +08:00
陈大猫 ac1f779323 fix(keychain): surface a missing public key on Export and Attach (#4588)
Previously, clicking Export and Attach on an imported key without a public key returned silently before setting exporting state or showing a toast, while the button remained enabled.

Treat missing or whitespace-only publicKey values as missing: disable Export and Attach, show a muted info hint directing the user to paste the public key in the key editor, and show a toast.error instead of returning silently if the click guard is reached.

Fixes #4577
2026-11-30 20:37:09 +08:00
陈大猫 9d579c10ff fix(sftp): remember last chosen download folder for later dialogs (#4582)
After #4392, download dialogs always open in the Settings default (or
system Downloads) and never record the folder the user just picked.
Remember the last confirmed download directory in a device-local key
and prefer it on the next dialog, falling back to the Settings default
then Downloads if it is gone.

Fixes #4581
2026-11-30 16:05:06 +08:00
陈大猫 c3cd4850ab feat(rdp): fill mstsc password via ephemeral Credential Manager entries (#4570)
* feat(rdp): fill mstsc password via ephemeral Credential Manager entries

Related to #4566 item 3. On Windows, when opening the system RDP client,
temporarily write the already-vaulted password to TERMSRV/<host> via
CredWriteW so mstsc can auto-fill it, then delete the entry we created
after mstsc exits or Netcatty quits. Never write the password into the
.rdp file or process command line, and never overwrite an existing
TERMSRV credential.

* fix(rdp): retry failed TERMSRV cleanup and keep non-Windows .rdp prompts

Keep tracking a Credential Manager entry we created until delete succeeds
or the entry is already gone, and retry leftover deletes on shutdown.
On macOS and Linux, write the supplied .rdp content unchanged instead of
forcing prompt-for-credentials.
2026-11-30 14:00:47 +08:00
陈大猫 74a304952b fix(rdp): keep dropped clipboard files until remote paste (#4572)
* fix(rdp): keep dropped clipboard files until remote paste (#4571)

* fix(rdp): send CLIPRDR FileContents replies with IronRDP field names (#4571)

IronRDP's submit_file_contents extension parses stream_id and is_error.
camelCase keys made invokeExtension throw, so the remote never got file
data after a drag-drop staged pill.

* fix(rdp): clear failed CLIPRDR file offers so clipboard sync resumes (#4571)
2026-11-30 14:00:21 +08:00
陈大猫 db30429344 fix(ai): recognize Oh My Posh username-only powerline idle prompts (#4576)
Official oh-my-posh dracula (and similar) renders
" root  ~  ♥ 14:43 " with no user@host, so POWERLINE_PROMPT_PATTERN
missed it and MCP terminal_execute reported SHELL_NOT_READY. Fixes #4575.
2026-11-30 12:24:45 +08:00
陈大猫andNetcatty Contributor b9d58c2825 feat(plugins): add views.open to show a plugin's own contributed view (#4567)
Co-authored-by: Netcatty Contributor <contributor@netcatty.local>
2026-11-30 08:11:06 +08:00
github-actions[bot]andgithub-actions[bot] 12a49604d1 chore: update star history charts [skip ci] (#4574)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-11-30 00:07:55 +00:00
陈大猫 a06ebcc467 fix(rdp): keep Keys: Remote toggle in solo and focus panes (#4566) (#4569) 2026-11-30 01:30:17 +08:00
陈大猫 4686a945fc fix(rdp): portal fullscreen toolbar menus into the session pane (#4566) (#4568) 2026-11-30 00:46:34 +08:00
235 changed files with 20723 additions and 768 deletions

No files matched your search

@@ -1137,3 +1137,159 @@ test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and reco
assert.equal(logs[1].username, 'dev');
assert.equal(logs[1].protocol, 'local');
});
for (const scheme of ['pc', 'mac'] as const) {
test(`addSessionToWorkspace shortcut ${scheme}: opens append dialog and consumes event only when a workspace is active`, () => {
const target = new FakeHTMLElement();
for (const scenario of [
{ name: 'active workspace', activeTabId: 'workspace-1', expectConsume: true },
{ name: 'standalone terminal', activeTabId: 'session-1', expectConsume: false },
{ name: 'vault tab', activeTabId: 'vault', expectConsume: false },
{ name: 'sftp tab', activeTabId: 'sftp', expectConsume: false },
{ name: 'editor tab', activeTabId: 'editor:file-1', expectConsume: false },
{ name: 'log view tab', activeTabId: 'log-1', expectConsume: false },
{ name: 'plugin view tab', activeTabId: 'plugin-view:demo:main', expectConsume: false },
]) {
const dialogCalls: unknown[] = [];
let prevented = 0;
let stopped = 0;
const event = {
key: 'n',
code: 'KeyN',
ctrlKey: scheme === 'pc',
metaKey: scheme === 'mac',
altKey: false,
shiftKey: false,
target,
composedPath: () => [target],
preventDefault: () => { prevented += 1; },
stopPropagation: () => { stopped += 1; },
} as unknown as KeyboardEvent;
const actionCtx = {
activeTabStore: { getActiveTabId: () => scenario.activeTabId },
editorTabs: [{ id: 'file-1' }],
orderedTabs: ['session-1', 'workspace-1'],
sessions: [{ id: 'session-1' }, { id: 's-ws', workspaceId: 'workspace-1' }],
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
toEditorTabId: (id: string) => `editor:${id}`,
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
};
handleGlobalHotkeyKeyDownImpl(
() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '',
hotkeyScheme: scheme,
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
executeHotkeyActionImpl(() => actionCtx, action, ev),
}),
event,
);
assert.deepEqual(
dialogCalls,
scenario.expectConsume ? [{ mode: 'append', workspaceId: 'workspace-1' }] : [],
`${scheme} / ${scenario.name}: dialog calls`,
);
assert.equal(
prevented,
scenario.expectConsume ? 1 : 0,
`${scheme} / ${scenario.name}: preventDefault count`,
);
assert.equal(
stopped,
scenario.expectConsume ? 1 : 0,
`${scheme} / ${scenario.name}: stopPropagation count`,
);
}
});
}
test('addSessionToWorkspace shortcut stays out of form inputs and Monaco even while a workspace is active', () => {
for (const [label, target] of [
['input', new FakeInputHTMLElement()],
['monaco', new FakeMonacoHTMLElement()],
] as const) {
const dialogCalls: unknown[] = [];
let prevented = 0;
let stopped = 0;
const event = {
key: 'n',
code: 'KeyN',
ctrlKey: true,
metaKey: false,
altKey: false,
shiftKey: false,
target,
composedPath: () => [target],
preventDefault: () => { prevented += 1; },
stopPropagation: () => { stopped += 1; },
} as unknown as KeyboardEvent;
handleGlobalHotkeyKeyDownImpl(
() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '',
hotkeyScheme: 'pc',
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
executeHotkeyActionImpl(() => ({
activeTabStore: { getActiveTabId: () => 'workspace-1' },
editorTabs: [],
orderedTabs: ['workspace-1'],
sessions: [],
settings: {},
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
toEditorTabId: (id: string) => `editor:${id}`,
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
}), action, ev),
}),
event,
);
assert.deepEqual(dialogCalls, [], `${label} should not open workspace dialog`);
assert.equal(prevented, 0, `${label} should not preventDefault`);
assert.equal(stopped, 0, `${label} should not stopPropagation`);
}
});
test('executeHotkeyActionImpl addSessionToWorkspace returns boolean availability defensively', () => {
const dialogCalls: unknown[] = [];
const makeCtx = (overrides: Record<string, unknown> = {}) => ({
activeTabStore: { getActiveTabId: () => 'workspace-1' },
editorTabs: [],
orderedTabs: [],
sessions: [],
settings: {},
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
toEditorTabId: (id: string) => `editor:${id}`,
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
...overrides,
});
assert.equal(
executeHotkeyActionImpl(() => makeCtx({ workspaces: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
false,
);
assert.equal(
executeHotkeyActionImpl(() => makeCtx({ setAddToWorkspaceDialog: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
false,
);
assert.equal(
executeHotkeyActionImpl(() => makeCtx({ activeTabStore: { getActiveTabId: () => 'session-1' } }), 'addSessionToWorkspace', {} as KeyboardEvent),
false,
);
assert.deepEqual(dialogCalls, []);
assert.equal(
executeHotkeyActionImpl(() => makeCtx(), 'addSessionToWorkspace', {} as KeyboardEvent),
true,
);
assert.deepEqual(dialogCalls, [{ mode: 'append', workspaceId: 'workspace-1' }]);
});
+18 -2
View File
@@ -394,8 +394,13 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
// An unavailable action must leave the chord to the terminal.
// Broadcast keeps Ctrl/Cmd+B for tmux; the host list keeps Ctrl/Cmd+Shift+B
// when the sidebar cannot show. Dispatch once before consuming it.
if (binding.action === 'broadcast' || binding.action === 'toggleHostTree') {
// when the sidebar cannot show; addSessionToWorkspace keeps Ctrl/Cmd+N
// when no workspace tab is active. Dispatch once before consuming it.
if (
binding.action === 'broadcast'
|| binding.action === 'toggleHostTree'
|| binding.action === 'addSessionToWorkspace'
) {
if (executeHotkeyAction(binding.action, e) === true) {
e.preventDefault();
e.stopPropagation();
@@ -1218,6 +1223,17 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
// button, but without having to open QS first.
setAddToWorkspaceDialog({ mode: 'create' });
break;
case 'addSessionToWorkspace': {
// Open the same append-mode picker the workspace tab context menu
// uses, targeting the currently active workspace. A standalone tab
// (or vault/settings) has no workspace to append into, so return false
// to leave the chord for the active surface or terminal.
const currentId = activeTabStore.getActiveTabId();
const activeWs = (workspaces ?? []).find((w) => w.id === currentId);
if (!activeWs || typeof setAddToWorkspaceDialog !== 'function') return false;
setAddToWorkspaceDialog({ mode: 'append', workspaceId: activeWs.id });
return true;
}
case 'portForwarding':
// Navigate to vault and open port forwarding section
setActiveTabId('vault');
+1
View File
@@ -1847,6 +1847,7 @@ export function AppSideEffects() {
hostname: result.target.hostname,
port: result.target.port,
username: result.target.username || undefined,
...(result.target.password ? { password: result.target.password } : {}),
domain: result.target.domain || undefined,
label: result.target.label,
rdpContent: result.target.rawRdpFileContent,
+1
View File
@@ -572,6 +572,7 @@ function AppViewInner({ domains }: AppViewProps) {
onEditHost={handleEditHostFromOverlay}
onRenameWorkspace={startWorkspaceRename}
onCopyWorkspace={copyWorkspaceWithCurrentShell}
onRequestAddToWorkspace={handleRequestAddToWorkspace}
onCloseWorkspace={closeWorkspace}
onCloseLogView={closeLogView}
onCloseTabsBatch={closeTabsBatch}
+16
View File
@@ -629,12 +629,19 @@ export const enAiMessages: Messages = {
'ai.chat.managerRebindPick': 'Choose a terminal or workspace…',
'ai.chat.managerRebindHere': 'Current panel',
'ai.chat.managerRebindDone': 'Moved "{title}" to {target}.',
'ai.chat.managerToggleSelection': 'Select chats',
'ai.chat.managerSelectAll': 'Select all',
'ai.chat.managerSelectedCount': '{n} selected',
'ai.chat.managerSelectRow': 'Select this chat',
'ai.chat.managerRegenerateTitle': 'Regenerate title with AI',
'ai.chat.managerExportOne': 'Export this chat',
'ai.chat.managerBadgeActive': 'Active',
'ai.chat.managerBadgeIdle': 'Idle',
'ai.chat.managerMessagesCount': '{n} messages',
'ai.chat.managerDeleteTitle': 'Delete this chat?',
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
'ai.chat.justNow': 'Just now',
'ai.chat.minutesAgo': '{n}m ago',
'ai.chat.hoursAgo': '{n}h ago',
@@ -688,6 +695,15 @@ export const enAiMessages: Messages = {
'ai.chatHistory.messageCap': 'Messages kept per chat',
'ai.chatHistory.messageCap.description': 'Maximum number of messages stored per chat (50–2000). Lowering it drops the oldest messages from storage on the next write. Larger values increase storage and cloud-sync size.',
'ai.chatHistory.messageCap.unit': 'messages',
'ai.chatHistory.autoLlmTitle': 'Auto-generate chat titles',
'ai.chatHistory.autoLlmTitle.description': 'Use a small one-shot LLM call to write a short title after the first message. Falls back to the first line if unavailable. Local setting only.',
'ai.chatHistory.titleModel': 'Title model',
'ai.chatHistory.titleModel.description': 'Provider and model used to generate chat titles. Pick a small, cheap model. Defaults to the current Catty model.',
'ai.chatHistory.titleModel.none': 'No enabled provider available.',
'ai.chatHistory.titleModel.useCurrentCatty': 'Use current Catty model',
'ai.chatHistory.titleModel.unavailable': 'Unavailable',
'ai.chatHistory.titleModel.providerPlaceholder': 'Select provider',
'ai.chatHistory.titleModel.modelPlaceholder': 'Select model',
// AI Error
'ai.codex.bridgeError': 'Codex main-process handlers are not loaded yet. Fully restart Netcatty, or restart the Electron dev process, then try again.',
+39
View File
@@ -431,6 +431,8 @@ export const enCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Show SFTP tab',
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
'settings.vault.removeTopTabsDragArea': 'Remove the top window-drag area',
'settings.vault.removeTopTabsDragAreaDesc': 'When enabled, remove the draggable space above the tabs so the top edge is available for clicks.',
'settings.vault.showHostTreeSidebarDesc': 'Display the host list sidebar and its top-bar toggle on terminal and editor tabs.',
'settings.vault.autoImportSystemKnownHosts': 'Auto-import system known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': 'When Vault loads, silently import entries from the OpenSSH known_hosts file. Turn this off to keep Netcatty known hosts separate; Scan System still imports on demand.',
@@ -1061,6 +1063,7 @@ Highlight the focused split pane:
'settings.shortcuts.binding.command-palette': 'Open Command Palette',
'settings.shortcuts.binding.quick-switch': 'Quick Switch',
'settings.shortcuts.binding.new-workspace': 'New Workspace',
'settings.shortcuts.binding.add-session-to-workspace': 'Add Session to Workspace',
'settings.shortcuts.binding.snippets': 'Open Snippets',
'settings.shortcuts.binding.broadcast': 'Switch the Broadcast Mode',
'settings.shortcuts.binding.toggle-side-panel': 'Toggle Side Panel',
@@ -1498,5 +1501,41 @@ Highlight the focused split pane:
'plugins.hostActions.managedUnsupported': 'Managed SSH config changes require the Vault host editor.',
'plugins.hostActions.failed': 'The request expired, was revoked, or the host changed. Select the host again.',
'plugins.hostActions.selectionLimit': 'Select up to 50 current hosts.',
'settings.externalEditor.title': 'External Remote Editor',
'settings.externalEditor.desc': 'Open remote SSH projects and files directly in local editors such as Zed, VS Code, or Cursor.',
'settings.externalEditor.preferredEditor': 'Preferred editor',
'settings.externalEditor.preferredEditor.desc': 'Default local editor used for SFTP context menu actions and terminal open requests.',
'settings.externalEditor.executablePath': 'Editor executable',
'settings.externalEditor.executablePath.desc': 'Leave empty to auto-detect, or choose the local binary manually.',
'settings.externalEditor.executablePath.placeholder': 'Auto-detect executable path',
'settings.externalEditor.status.configured': 'Custom path',
'settings.externalEditor.status.detected': 'Auto-detected',
'settings.externalEditor.status.notFound': 'Not detected',
'settings.externalEditor.browse': 'Browse…',
'settings.externalEditor.resetPath': 'Reset to auto-detect',
'settings.externalEditor.redetect': 'Re-detect installed editors',
'settings.externalEditor.customArgs': 'Custom arguments',
'settings.externalEditor.customArgs.desc': 'Space-separated arguments (placeholders: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'SSH connection mode',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH Bridge reuses your active authenticated session without exposing vault keys or host lists.',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH Bridge (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'Direct OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty bridge rule',
'settings.externalEditor.sshBridge.desc': 'Adds a single static Host *.netcatty block to your OpenSSH config without writing any hostnames, keys, or passwords.',
'settings.externalEditor.sshBridge.install': 'Install bridge rule',
'settings.externalEditor.sshBridge.reinstall': 'Reinstall rule',
'settings.externalEditor.sshBridge.update': 'Update rule',
'settings.externalEditor.sshBridge.remove': 'Remove rule',
'settings.externalEditor.terminalRequests': 'Allow terminal open requests (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Let remote shells open paths in your configured local editor via commands like `zed .`.',
'settings.externalEditor.autoSetup': 'Enable remote editor commands for Netcatty sessions',
'settings.externalEditor.autoSetup.desc': 'Install `zed` / `ncedit` helpers into ~/.netcatty/bin and activate them in PATH for this Netcatty terminal session only, without modifying ~/.bashrc or ~/.zshrc (can also be toggled per host).',
'settings.externalEditor.defaultTrust': 'Default host trust',
'settings.externalEditor.defaultTrust.desc': 'Permission policy when an unrecognized remote host requests opening a local editor.',
'settings.externalEditor.trust.ask': 'Ask every time',
'settings.externalEditor.trust.allow': 'Always allow',
'settings.externalEditor.trust.deny': 'Always deny',
'settings.externalEditor.trustedHosts.host': 'Host',
'settings.externalEditor.trustedHosts.policy': 'Policy',
};
+17
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const enTerminalMessages: Messages = {
'terminal.directory.open': 'Current directory: {path}. Change directory',
'terminal.gitBranch.current': 'Git branch: {{value}}',
'terminal.gitBranch.detached': 'Detached HEAD: {{value}}',
'terminal.directory.unknown': 'Directory unknown',
'terminal.directory.search': 'Search child directories...',
'terminal.directory.directories': 'Directories',
@@ -16,6 +18,7 @@ export const enTerminalMessages: Messages = {
'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.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
'terminal.directory.cygwinIntegrationUnavailable': 'Waiting for Cygwin Bash to return to an idle prompt.',
'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.',
@@ -469,6 +472,7 @@ export const enTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Before restore',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} keys, {snippets} snippets, {notes} notes',
'cloudSync.localBackups.aiCounts': '{sessions} AI chats, {settings} settings',
'cloudSync.localBackups.restore': 'Restore',
'cloudSync.localBackups.restoreSuccess': 'Local backup restored.',
'cloudSync.localBackups.restoreFailedTitle': 'Restore failed',
@@ -619,6 +623,10 @@ export const enTerminalMessages: Messages = {
'keychain.export.scriptPlaceholder': 'Export script...',
'keychain.export.missingCredentials':
'Host has no saved password or key. Please add password credentials to the host first.',
'keychain.export.missingPublicKey':
'This key has no public key. Open Edit, paste the public key, then try Export and Attach again.',
'keychain.export.missingPublicKeyNote':
'This key has no public key. Paste it in the key editor before exporting.',
'keychain.export.successTitle': 'Export Successful',
'keychain.export.successMessage': 'Public key exported and attached to {host}',
'keychain.export.failedTitle': 'Export Failed',
@@ -695,6 +703,7 @@ export const enTerminalMessages: Messages = {
'tabs.logPrefix': 'Log:',
'tabs.logLocal': 'Local',
'tabs.copyTab': 'Copy Tab',
'tabs.addSessionToWorkspace': 'Add Session to Workspace',
'tabs.duplicateSession': 'Duplicate Session',
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
@@ -988,4 +997,12 @@ export const enTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'Show in every host’s browser.',
'terminal.browser.downloadLocation': 'Saved to your Downloads folder',
'terminal.browser.saveAs': 'Save as…',
'terminal.externalEditor.opened': 'Opened {path} in {editor}',
'terminal.externalEditor.failed': 'Failed to open in {editor}',
'terminal.externalEditor.prompt.title': 'Open in {editor}?',
'terminal.externalEditor.prompt.desc': 'Remote host {host} requested opening this remote path in {editor}:',
'terminal.externalEditor.prompt.deny': 'Deny',
'terminal.externalEditor.prompt.allowOnce': 'Allow Once',
'terminal.externalEditor.prompt.alwaysTrust': 'Always Trust Host',
'terminal.externalEditor.autoSetupConfigured': 'Remote editor commands configured ({editor})',
};
+3
View File
@@ -1463,5 +1463,8 @@ export const enVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
'sftp.context.openInExternalEditor': 'Open in {editor}',
'hostDetails.externalEditorShellIntegration': 'Enable external editor commands in this session',
'hostDetails.externalEditorShellIntegration.desc': 'Expose `zed` / `ncedit` via ~/.netcatty/bin for this Netcatty terminal session only (including tmux) without modifying ~/.bashrc or ~/.zshrc.',
};
+16
View File
@@ -629,12 +629,19 @@ export const esAiMessages: Messages = {
'ai.chat.managerRebindPick': 'Elegir terminal o espacio de trabajo…',
'ai.chat.managerRebindHere': 'Panel actual',
'ai.chat.managerRebindDone': 'Se movió «{title}» a {target}.',
'ai.chat.managerToggleSelection': 'Seleccionar chats',
'ai.chat.managerSelectAll': 'Seleccionar todo',
'ai.chat.managerSelectedCount': '{n} seleccionados',
'ai.chat.managerSelectRow': 'Seleccionar este chat',
'ai.chat.managerRegenerateTitle': 'Regenerar título con IA',
'ai.chat.managerExportOne': 'Exportar este chat',
'ai.chat.managerBadgeActive': 'Activo',
'ai.chat.managerBadgeIdle': 'Inactivo',
'ai.chat.managerMessagesCount': '{n} mensajes',
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.justNow': 'Ahora mismo',
'ai.chat.minutesAgo': 'hace {n} min',
'ai.chat.hoursAgo': 'hace {n} h',
@@ -688,6 +695,15 @@ export const esAiMessages: Messages = {
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
'ai.chatHistory.messageCap.unit': 'mensajes',
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
'ai.chatHistory.titleModel': 'Modelo de título',
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
'ai.chatHistory.titleModel.unavailable': 'No disponible',
'ai.chatHistory.titleModel.providerPlaceholder': 'Seleccionar proveedor',
'ai.chatHistory.titleModel.modelPlaceholder': 'Seleccionar modelo',
// AI Error
'ai.codex.bridgeError': 'Los controladores del proceso principal de Codex aún no están cargados. Reinicia Netcatty por completo o reinicia el proceso de desarrollo de Electron y vuelve a intentarlo.',
+39
View File
@@ -431,6 +431,8 @@ export const esCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
'settings.vault.removeTopTabsDragArea': 'Quitar el área superior para arrastrar la ventana',
'settings.vault.removeTopTabsDragAreaDesc': 'Al activarla, quita el espacio de arrastre sobre las pestañas para poder hacer clic en el borde superior.',
'settings.vault.showHostTreeSidebarDesc': 'Muestra la barra lateral de lista de hosts y su alternador en la barra superior en las pestañas de terminal y editor.',
'settings.vault.autoImportSystemKnownHosts': 'Importar automáticamente known_hosts del sistema',
'settings.vault.autoImportSystemKnownHostsDesc': 'Cuando se carga el Vault, importa en silencio las entradas del archivo known_hosts de OpenSSH. Desactívalo para mantener los hosts conocidos de Netcatty separados; Escanear sistema sigue importando a pedido.',
@@ -1062,6 +1064,7 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.binding.command-palette': 'Abrir paleta de comandos',
'settings.shortcuts.binding.quick-switch': 'Cambio rápido',
'settings.shortcuts.binding.new-workspace': 'Nuevo espacio de trabajo',
'settings.shortcuts.binding.add-session-to-workspace': 'Añadir sesión al espacio de trabajo',
'settings.shortcuts.binding.snippets': 'Abrir fragmentos',
'settings.shortcuts.binding.broadcast': 'Alternar modo de transmisión',
'settings.shortcuts.binding.toggle-opacity': 'Alternar la transparencia de la ventana',
@@ -1498,5 +1501,41 @@ Resalta el panel dividido enfocado:
'plugins.hostActions.managedUnsupported': 'Los cambios de configuración SSH administrada requieren el editor de equipos de Vault.',
'plugins.hostActions.failed': 'La solicitud caducó, se revocó o el equipo cambió. Selecciona el equipo de nuevo.',
'plugins.hostActions.selectionLimit': 'Selecciona hasta 50 equipos actuales.',
'settings.externalEditor.title': 'Editor remoto externo',
'settings.externalEditor.desc': 'Abre proyectos y archivos SSH remotos directamente en editores locales como Zed, VS Code o Cursor.',
'settings.externalEditor.preferredEditor': 'Editor preferido',
'settings.externalEditor.preferredEditor.desc': 'Editor local predeterminado para el menú contextual de SFTP y las solicitudes desde el terminal.',
'settings.externalEditor.executablePath': 'Ejecutable del editor',
'settings.externalEditor.executablePath.desc': 'Déjalo vacío para detectarlo automáticamente o elige el binario local manualmente.',
'settings.externalEditor.executablePath.placeholder': 'Detectar ruta del ejecutable automáticamente',
'settings.externalEditor.status.configured': 'Ruta personalizada',
'settings.externalEditor.status.detected': 'Detectado automáticamente',
'settings.externalEditor.status.notFound': 'No detectado',
'settings.externalEditor.browse': 'Examinar…',
'settings.externalEditor.resetPath': 'Restablecer a detección automática',
'settings.externalEditor.redetect': 'Volver a detectar editores instalados',
'settings.externalEditor.customArgs': 'Argumentos personalizados',
'settings.externalEditor.customArgs.desc': 'Argumentos separados por espacios (marcadores: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'Modo de conexión SSH',
'settings.externalEditor.connectionMode.desc': 'El puente SSH de Netcatty reutiliza tu sesión autenticada activa sin exponer claves ni listas de equipos.',
'settings.externalEditor.connectionMode.bridge': 'Puente SSH de Netcatty (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'OpenSSH directo (usuario@host:puerto)',
'settings.externalEditor.sshBridge.title': 'Regla OpenSSH *.netcatty',
'settings.externalEditor.sshBridge.desc': 'Añade un único bloque estático Host *.netcatty a tu configuración de OpenSSH sin escribir nombres de equipo, claves ni contraseñas.',
'settings.externalEditor.sshBridge.install': 'Instalar regla',
'settings.externalEditor.sshBridge.reinstall': 'Reinstalar regla',
'settings.externalEditor.sshBridge.update': 'Actualizar regla',
'settings.externalEditor.sshBridge.remove': 'Eliminar regla',
'settings.externalEditor.terminalRequests': 'Permitir solicitudes desde el terminal (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Permite que las shells remotas abran rutas en tu editor local configurado mediante comandos como `zed .`.',
'settings.externalEditor.autoSetup': 'Habilitar comandos de editor remoto en sesiones de Netcatty',
'settings.externalEditor.autoSetup.desc': 'Instala helpers `zed` / `ncedit` en ~/.netcatty/bin y los activa en el PATH solo para esta sesión de Netcatty, sin modificar ~/.bashrc ni ~/.zshrc (también configurable por equipo).',
'settings.externalEditor.defaultTrust': 'Confianza predeterminada del equipo',
'settings.externalEditor.defaultTrust.desc': 'Política de permisos cuando un equipo remoto no reconocido solicita abrir un editor local.',
'settings.externalEditor.trust.ask': 'Preguntar siempre',
'settings.externalEditor.trust.allow': 'Permitir siempre',
'settings.externalEditor.trust.deny': 'Denegar siempre',
'settings.externalEditor.trustedHosts.host': 'Equipo',
'settings.externalEditor.trustedHosts.policy': 'Política',
};
+17
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const esTerminalMessages: Messages = {
'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio',
'terminal.gitBranch.current': 'Rama de Git: {{value}}',
'terminal.gitBranch.detached': 'HEAD separado: {{value}}',
'terminal.directory.unknown': 'Directorio desconocido',
'terminal.directory.search': 'Buscar subdirectorios...',
'terminal.directory.directories': 'Directorios',
@@ -16,6 +18,7 @@ export const esTerminalMessages: Messages = {
'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.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
'terminal.directory.cygwinIntegrationUnavailable': 'Esperando que Bash de Cygwin vuelva a un indicador inactivo.',
'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.',
@@ -469,6 +472,7 @@ export const esTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Antes de la restauración',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} claves, {snippets} snippets, {notes} notas',
'cloudSync.localBackups.aiCounts': '{sessions} chats de IA, {settings} ajustes',
'cloudSync.localBackups.restore': 'Restaurar',
'cloudSync.localBackups.restoreSuccess': 'Copia de seguridad local restaurada.',
'cloudSync.localBackups.restoreFailedTitle': 'Falló la restauración',
@@ -619,6 +623,10 @@ export const esTerminalMessages: Messages = {
'keychain.export.scriptPlaceholder': 'Script de exportación...',
'keychain.export.missingCredentials':
'El host no tiene contraseña ni clave guardadas. Primero agrega credenciales de contraseña al host.',
'keychain.export.missingPublicKey':
'Esta clave no tiene clave pública. Ábrela en Editar, pega la clave pública y vuelve a intentar Exportar y adjuntar.',
'keychain.export.missingPublicKeyNote':
'Esta clave no tiene clave pública. Pégala en el editor de claves antes de exportar.',
'keychain.export.successTitle': 'Exportación exitosa',
'keychain.export.successMessage': 'Clave pública exportada y adjuntada a {host}',
'keychain.export.failedTitle': 'Falló la exportación',
@@ -697,6 +705,7 @@ export const esTerminalMessages: Messages = {
'tabs.logPrefix': 'Registro:',
'tabs.logLocal': 'Local',
'tabs.copyTab': 'Copiar pestaña',
'tabs.addSessionToWorkspace': 'Añadir sesión al espacio de trabajo',
'tabs.duplicateSession': 'Duplicar sesión',
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
@@ -990,4 +999,12 @@ export const esTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'Mostrar en el navegador de todos los hosts.',
'terminal.browser.downloadLocation': 'Guardado en la carpeta Descargas',
'terminal.browser.saveAs': 'Guardar como…',
'terminal.externalEditor.opened': 'Se abrió {path} en {editor}',
'terminal.externalEditor.failed': 'No se pudo abrir en {editor}',
'terminal.externalEditor.prompt.title': '¿Abrir en {editor}?',
'terminal.externalEditor.prompt.desc': 'El equipo remoto {host} solicitó abrir esta ruta remota en {editor}:',
'terminal.externalEditor.prompt.deny': 'Denegar',
'terminal.externalEditor.prompt.allowOnce': 'Permitir una vez',
'terminal.externalEditor.prompt.alwaysTrust': 'Confiar siempre en este equipo',
'terminal.externalEditor.autoSetupConfigured': 'Comandos de editor remoto configurados ({editor})',
};
+3
View File
@@ -1463,5 +1463,8 @@ export const esVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
'sftp.context.openInExternalEditor': 'Abrir en {editor}',
'hostDetails.externalEditorShellIntegration': 'Habilitar comandos de editor externo en esta sesión',
'hostDetails.externalEditorShellIntegration.desc': 'Activa `zed` / `ncedit` desde ~/.netcatty/bin solo para esta sesión de terminal de Netcatty (incluido tmux), sin modificar ~/.bashrc ni ~/.zshrc.',
};
@@ -228,3 +228,25 @@ test("AI tool output limit settings copy is localized across all five locales",
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
});
test("LLM chat title settings copy is localized across all five locales", () => {
const keys = [
"ai.chatHistory.autoLlmTitle",
"ai.chatHistory.autoLlmTitle.description",
"ai.chatHistory.titleModel",
"ai.chatHistory.titleModel.description",
"ai.chatHistory.titleModel.none",
"ai.chatHistory.titleModel.useCurrentCatty",
"ai.chatHistory.titleModel.unavailable",
"ai.chatHistory.titleModel.providerPlaceholder",
"ai.chatHistory.titleModel.modelPlaceholder",
] as const;
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
for (const key of keys) {
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
if (locale !== "en") {
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
}
}
}
});
+16
View File
@@ -628,12 +628,19 @@ export const ruAiMessages: Messages = {
'ai.chat.managerRebindPick': 'Выберите терминал или рабочее пространство…',
'ai.chat.managerRebindHere': 'Текущая панель',
'ai.chat.managerRebindDone': 'Чат «{title}» перемещён в {target}.',
'ai.chat.managerToggleSelection': 'Выбрать чаты',
'ai.chat.managerSelectAll': 'Выбрать все',
'ai.chat.managerSelectedCount': 'Выбрано: {n}',
'ai.chat.managerSelectRow': 'Выбрать этот чат',
'ai.chat.managerRegenerateTitle': 'Пересоздать заголовок через ИИ',
'ai.chat.managerExportOne': 'Экспортировать этот чат',
'ai.chat.managerBadgeActive': 'Активен',
'ai.chat.managerBadgeIdle': 'Простой',
'ai.chat.managerMessagesCount': '{n} сообщений',
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.justNow': 'Только что',
'ai.chat.minutesAgo': '{n}м назад',
'ai.chat.hoursAgo': '{n}ч назад',
@@ -687,6 +694,15 @@ export const ruAiMessages: Messages = {
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
'ai.chatHistory.messageCap.unit': 'сообщений',
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
'ai.chatHistory.titleModel': 'Модель для заголовков',
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
'ai.chatHistory.titleModel.providerPlaceholder': 'Выбрать провайдер',
'ai.chatHistory.titleModel.modelPlaceholder': 'Выбрать модель',
// AI Error
'ai.codex.bridgeError': 'Обработчики главного процесса Codex ещё не загружены. Полностью перезапустите Netcatty или dev-процесс Electron и попробуйте снова.',
+39
View File
@@ -430,6 +430,8 @@ export const ruCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
'settings.vault.removeTopTabsDragArea': 'Убрать верхнюю область перетаскивания окна',
'settings.vault.removeTopTabsDragAreaDesc': 'При включении удаляется область перетаскивания над вкладками, чтобы по верхнему краю можно было нажимать.',
'settings.vault.showHostTreeSidebarDesc': 'Показывать список хостов и кнопку в верхней панели для вкладок терминала и редактора.',
'settings.vault.autoImportSystemKnownHosts': 'Автоимпорт системного known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': 'При открытии хранилища тихо импортировать записи из OpenSSH known_hosts. Отключите, чтобы держать известные хосты Netcatty отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
@@ -1046,6 +1048,7 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.binding.command-palette': 'Открыть палитру команд',
'settings.shortcuts.binding.quick-switch': 'Быстрое переключение',
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
'settings.shortcuts.binding.add-session-to-workspace': 'Добавить сессию в рабочую область',
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
@@ -1439,4 +1442,40 @@ export const ruCoreMessages: Messages = {
'plugins.hostActions.managedUnsupported': 'Изменяйте управляемые настройки SSH в редакторе хостов Vault.',
'plugins.hostActions.failed': 'Запрос истёк, был отозван или хост изменился. Выберите хост заново.',
'plugins.hostActions.selectionLimit': 'Выберите не более 50 текущих хостов.',
'settings.externalEditor.title': 'Внешний удалённый редактор',
'settings.externalEditor.desc': 'Открывайте удалённые SSH-проекты и файлы напрямую в локальных редакторах, таких как Zed, VS Code или Cursor.',
'settings.externalEditor.preferredEditor': 'Предпочитаемый редактор',
'settings.externalEditor.preferredEditor.desc': 'Локальный редактор по умолчанию для контекстного меню SFTP и запросов из терминала.',
'settings.externalEditor.executablePath': 'Исполняемый файл редактора',
'settings.externalEditor.executablePath.desc': 'Оставьте пустым для автоопределения или выберите локальный файл вручную.',
'settings.externalEditor.executablePath.placeholder': 'Автоопределение пути к файлу',
'settings.externalEditor.status.configured': 'Указан вручную',
'settings.externalEditor.status.detected': 'Определён автоматически',
'settings.externalEditor.status.notFound': 'Не найден',
'settings.externalEditor.browse': 'Обзор…',
'settings.externalEditor.resetPath': 'Сбросить на автоопределение',
'settings.externalEditor.redetect': 'Повторить поиск редакторов',
'settings.externalEditor.customArgs': 'Пользовательские аргументы',
'settings.externalEditor.customArgs.desc': 'Аргументы через пробел (подстановки: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'Режим SSH-подключения',
'settings.externalEditor.connectionMode.desc': 'SSH-мост Netcatty переиспользует активную аутентифицированную сессию без раскрытия ключей или списка хостов.',
'settings.externalEditor.connectionMode.bridge': 'SSH-мост Netcatty (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'Прямой OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'Правило OpenSSH *.netcatty',
'settings.externalEditor.sshBridge.desc': 'Добавляет один статический блок Host *.netcatty в конфиг OpenSSH без записи хостов, ключей и паролей.',
'settings.externalEditor.sshBridge.install': 'Установить правило',
'settings.externalEditor.sshBridge.reinstall': 'Переустановить правило',
'settings.externalEditor.sshBridge.update': 'Обновить правило',
'settings.externalEditor.sshBridge.remove': 'Удалить правило',
'settings.externalEditor.terminalRequests': 'Разрешить запросы из терминала (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Позволяет удалённой оболочке открывать пути в локальном редакторе командами вроде `zed .`.',
'settings.externalEditor.autoSetup': 'Включить команды редактора только в сессиях Netcatty',
'settings.externalEditor.autoSetup.desc': 'Устанавливает утилиты `zed` / `ncedit` в ~/.netcatty/bin и добавляет их в PATH только для этой сессии Netcatty, не изменяя ~/.bashrc и ~/.zshrc (можно задать отдельно для хоста).',
'settings.externalEditor.defaultTrust': 'Доверие хостам по умолчанию',
'settings.externalEditor.defaultTrust.desc': 'Политика разрешений, когда неизвестный удалённый хост запрашивает открытие локального редактора.',
'settings.externalEditor.trust.ask': 'Спрашивать каждый раз',
'settings.externalEditor.trust.allow': 'Всегда разрешать',
'settings.externalEditor.trust.deny': 'Всегда запрещать',
'settings.externalEditor.trustedHosts.host': 'Хост',
'settings.externalEditor.trustedHosts.policy': 'Политика',
};
+15
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const ruTerminalMessages: Messages = {
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
'terminal.directory.unknown': 'Каталог неизвестен',
'terminal.directory.search': 'Поиск подкаталогов...',
'terminal.directory.directories': 'Каталоги',
@@ -16,6 +18,7 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
'terminal.directory.cygwinIntegrationUnavailable': 'Ожидание готовности Bash в Cygwin.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
@@ -489,6 +492,7 @@ export const ruTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Перед восстановлением',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} хостов, {keys} ключей, {snippets} сниппетов, {notes} заметок',
'cloudSync.localBackups.aiCounts': '{sessions} чатов ИИ, {settings} настроек',
'cloudSync.localBackups.restore': 'Восстановить',
'cloudSync.localBackups.restoreSuccess': 'Локальная резервная копия восстановлена.',
'cloudSync.localBackups.restoreFailedTitle': 'Ошибка восстановления',
@@ -636,6 +640,8 @@ export const ruTerminalMessages: Messages = {
'keychain.export.script': 'Скрипт *',
'keychain.export.scriptPlaceholder': 'Скрипт экспорта...',
'keychain.export.missingCredentials': 'У хоста нет сохранённого пароля или ключа. Сначала добавьте в хост учётные данные с паролем.',
'keychain.export.missingPublicKey': 'У этого ключа нет публичного ключа. Откройте «Редактировать», вставьте публичный ключ и снова нажмите «Экспортировать и привязать».',
'keychain.export.missingPublicKeyNote': 'У этого ключа нет публичного ключа. Вставьте его в редакторе ключа перед экспортом.',
'keychain.export.successTitle': 'Экспорт выполнен успешно',
'keychain.export.successMessage': 'Публичный ключ экспортирован и привязан к {host}',
'keychain.export.failedTitle': 'Ошибка экспорта',
@@ -712,6 +718,7 @@ export const ruTerminalMessages: Messages = {
'tabs.logPrefix': 'Журнал:',
'tabs.logLocal': 'Локальный',
'tabs.copyTab': 'Копировать вкладку',
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
'tabs.duplicateSession': 'Дублировать сессию',
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
@@ -1004,4 +1011,12 @@ export const ruTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'В браузерах всех хостов.',
'terminal.browser.downloadLocation': 'Файлы сохраняются в папку «Загрузки»',
'terminal.browser.saveAs': 'Сохранить как…',
'terminal.externalEditor.opened': 'Открыто {path} в {editor}',
'terminal.externalEditor.failed': 'Не удалось открыть в {editor}',
'terminal.externalEditor.prompt.title': 'Открыть в {editor}?',
'terminal.externalEditor.prompt.desc': 'Удалённый хост {host} запросил открытие этого пути в {editor}:',
'terminal.externalEditor.prompt.deny': 'Отклонить',
'terminal.externalEditor.prompt.allowOnce': 'Разрешить один раз',
'terminal.externalEditor.prompt.alwaysTrust': 'Всегда доверять хосту',
'terminal.externalEditor.autoSetupConfigured': 'Команды удалённого редактора настроены ({editor})',
};
+3
View File
@@ -1482,5 +1482,8 @@ export const ruVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
'sftp.context.openInExternalEditor': 'Открыть в {editor}',
'hostDetails.externalEditorShellIntegration': 'Включить команды внешнего редактора в этой сессии',
'hostDetails.externalEditorShellIntegration.desc': 'Добавляет `zed` / `ncedit` из ~/.netcatty/bin в PATH только для этой сессии терминала Netcatty (включая tmux), не изменяя ~/.bashrc и ~/.zshrc.',
};
+16
View File
@@ -629,12 +629,19 @@ export const zhCNAiMessages: Messages = {
'ai.chat.managerRebindPick': '选择目标终端或工作区…',
'ai.chat.managerRebindHere': '当前面板',
'ai.chat.managerRebindDone': '已将“{title}”移动到 {target}。',
'ai.chat.managerToggleSelection': '选择会话',
'ai.chat.managerSelectAll': '全选',
'ai.chat.managerSelectedCount': '已选 {n} 个',
'ai.chat.managerSelectRow': '选择此会话',
'ai.chat.managerRegenerateTitle': '用 AI 重新生成标题',
'ai.chat.managerExportOne': '导出此会话',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '空闲',
'ai.chat.managerMessagesCount': '{n} 条消息',
'ai.chat.managerDeleteTitle': '删除此会话?',
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.justNow': '刚刚',
'ai.chat.minutesAgo': '{n}分钟前',
'ai.chat.hoursAgo': '{n}小时前',
@@ -688,6 +695,15 @@ export const zhCNAiMessages: Messages = {
'ai.chatHistory.messageCap': '每个会话保留的消息数',
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
'ai.chatHistory.messageCap.unit': '条消息',
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
'ai.chatHistory.titleModel': '标题模型',
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
'ai.chatHistory.titleModel.unavailable': '不可用',
'ai.chatHistory.titleModel.providerPlaceholder': '选择 provider',
'ai.chatHistory.titleModel.modelPlaceholder': '选择模型',
// AI Error
'ai.codex.bridgeError': 'Codex 主进程处理器尚未加载。请完全重启 Netcatty 或重启 Electron 开发进程,然后重试。',
+38
View File
@@ -438,6 +438,8 @@ export const zhCNCoreMessages: Messages = {
'settings.vault.showSftpTab': '显示 SFTP 标签页',
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
'settings.vault.removeTopTabsDragArea': '移除顶部窗口拖动区域',
'settings.vault.removeTopTabsDragAreaDesc': '开启后移除标签页上方的拖动空白区域,让顶部可用于点击标签页和窗口按钮。',
'settings.vault.showHostTreeSidebarDesc': '在终端和编辑器标签页显示主机列表侧栏及顶部开关。',
'settings.vault.autoImportSystemKnownHosts': '自动导入系统 known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': '打开主机库时静默导入 OpenSSH known_hosts 中的记录。关闭后,Netcatty 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
@@ -1415,5 +1417,41 @@ Vaults 标签保持扁平,不使用这块背景。
'plugins.hostActions.managedUnsupported': '受管理的 SSH 配置变更需在 Vault 主机编辑器中完成。',
'plugins.hostActions.failed': '请求已过期、被撤销或主机已改变。请重新选择主机。',
'plugins.hostActions.selectionLimit': '最多选择 50 个当前主机。',
'settings.externalEditor.title': '外部远程编辑器',
'settings.externalEditor.desc': '直接在本地编辑器(如 Zed、VS Code 或 Cursor)中打开远程 SSH 项目和文件。',
'settings.externalEditor.preferredEditor': '首选编辑器',
'settings.externalEditor.preferredEditor.desc': 'SFTP 右键菜单和终端打开请求默认使用的本地编辑器。',
'settings.externalEditor.executablePath': '编辑器可执行文件',
'settings.externalEditor.executablePath.desc': '留空以自动检测,或手动选择本地程序路径。',
'settings.externalEditor.executablePath.placeholder': '自动检测可执行文件路径',
'settings.externalEditor.status.configured': '已自定义路径',
'settings.externalEditor.status.detected': '已自动检测',
'settings.externalEditor.status.notFound': '未检测到',
'settings.externalEditor.browse': '浏览…',
'settings.externalEditor.resetPath': '重置为自动检测',
'settings.externalEditor.redetect': '重新检测已安装的编辑器',
'settings.externalEditor.customArgs': '自定义参数',
'settings.externalEditor.customArgs.desc': '以空格分隔的参数列表(支持占位符:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
'settings.externalEditor.connectionMode': 'SSH 连接模式',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 桥接会直接复用当前已认证会话,无需向磁盘导出私钥或主机列表。',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 桥接 (*.netcatty)',
'settings.externalEditor.connectionMode.direct': '直连 OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 桥接规则',
'settings.externalEditor.sshBridge.desc': '仅在 OpenSSH 配置中写入单个静态 Host *.netcatty 规则块,不包含任何主机名、私钥或密码。',
'settings.externalEditor.sshBridge.install': '安装桥接规则',
'settings.externalEditor.sshBridge.reinstall': '重新安装规则',
'settings.externalEditor.sshBridge.update': '更新规则',
'settings.externalEditor.sshBridge.remove': '移除规则',
'settings.externalEditor.terminalRequests': '允许终端发起打开请求 (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': '允许远程 Shell 通过 `zed .` 等命令在本地编辑器中打开远程路径。',
'settings.externalEditor.autoSetup': '仅在 Netcatty 会话中启用远程编辑器命令',
'settings.externalEditor.autoSetup.desc': '将 `zed` / `ncedit` 脚本安装到 ~/.netcatty/bin,并仅在当前 Netcatty 终端会话的 PATH 中生效,不修改 ~/.bashrc 或 ~/.zshrc(也可按主机单独开关)。',
'settings.externalEditor.defaultTrust': '默认主机信任策略',
'settings.externalEditor.defaultTrust.desc': '未单独配置信任规则的远程主机发起打开编辑器请求时的处理方式。',
'settings.externalEditor.trust.ask': '每次询问',
'settings.externalEditor.trust.allow': '始终允许',
'settings.externalEditor.trust.deny': '始终拒绝',
'settings.externalEditor.trustedHosts.host': '主机',
'settings.externalEditor.trustedHosts.policy': '策略',
};
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const zhCNTerminalMessages: Messages = {
'terminal.directory.open': '当前目录:{path}。更改目录',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
'terminal.directory.unknown': '目录未知',
'terminal.directory.search': '搜索当前目录下的文件夹…',
'terminal.directory.directories': '目录',
@@ -16,6 +18,7 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回空闲提示符。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
@@ -630,6 +633,7 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.binding.command-palette': '打开命令面板',
'settings.shortcuts.binding.quick-switch': '快速切换',
'settings.shortcuts.binding.new-workspace': '新建工作区',
'settings.shortcuts.binding.add-session-to-workspace': '添加会话到工作区',
'settings.shortcuts.binding.snippets': '打开代码片段',
'settings.shortcuts.binding.broadcast': '切换广播模式',
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
@@ -719,6 +723,8 @@ export const zhCNTerminalMessages: Messages = {
'keychain.export.script': '脚本 *',
'keychain.export.scriptPlaceholder': '导出脚本...',
'keychain.export.missingCredentials': '主机未保存密码或密钥。请先为该主机添加密码凭据。',
'keychain.export.missingPublicKey': '此密钥没有公钥。请先在编辑页粘贴公钥,然后再试「导出并绑定」。',
'keychain.export.missingPublicKeyNote': '此密钥没有公钥。请先在密钥编辑页粘贴公钥,然后再导出。',
'keychain.export.successTitle': '导出成功',
'keychain.export.successMessage': '已导出公钥并绑定到 {host}',
'keychain.export.failedTitle': '导出失败',
@@ -795,6 +801,7 @@ export const zhCNTerminalMessages: Messages = {
'tabs.logPrefix': '日志:',
'tabs.logLocal': '本地',
'tabs.copyTab': '复制标签页',
'tabs.addSessionToWorkspace': '在此工作区添加会话',
'tabs.duplicateSession': '复制会话',
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
@@ -1088,4 +1095,12 @@ export const zhCNTerminalMessages: Messages = {
'terminal.browser.allScopeHint': '在每台主机的浏览器中显示。',
'terminal.browser.downloadLocation': '文件保存在系统“下载”文件夹',
'terminal.browser.saveAs': '另存为…',
'terminal.externalEditor.opened': '已在 {editor} 中打开 {path}',
'terminal.externalEditor.failed': '无法在 {editor} 中打开',
'terminal.externalEditor.prompt.title': '在 {editor} 中打开?',
'terminal.externalEditor.prompt.desc': '远程主机 {host} 请求在 {editor} 中打开以下远程路径:',
'terminal.externalEditor.prompt.deny': '拒绝',
'terminal.externalEditor.prompt.allowOnce': '仅允许本次',
'terminal.externalEditor.prompt.alwaysTrust': '始终信任此主机',
'terminal.externalEditor.autoSetupConfigured': '已配置远程编辑器命令 ({editor})',
};
+4
View File
@@ -848,6 +848,7 @@ export const zhCNVaultMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': '恢复前',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} 台主机,{keys} 个密钥,{snippets} 个代码片段,{notes} 条笔记',
'cloudSync.localBackups.aiCounts': '{sessions} 个 AI 会话,{settings} 项设置',
'cloudSync.localBackups.restore': '恢复',
'cloudSync.localBackups.restoreSuccess': '已恢复本地备份。',
'cloudSync.localBackups.restoreFailedTitle': '恢复失败',
@@ -1427,5 +1428,8 @@ export const zhCNVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
'sftp.context.openInExternalEditor': '在 {editor} 中打开',
'hostDetails.externalEditorShellIntegration': '在此会话中启用外部编辑器命令',
'hostDetails.externalEditorShellIntegration.desc': '通过 ~/.netcatty/bin 仅在当前 Netcatty 终端会话中启用 `zed` / `ncedit`(支持 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
};
+16
View File
@@ -628,12 +628,19 @@ export const zhTWAiMessages: Messages = {
'ai.chat.managerRebindPick': '選擇目標終端或工作區…',
'ai.chat.managerRebindHere': '目前面板',
'ai.chat.managerRebindDone': '已將「{title}」移動到 {target}。',
'ai.chat.managerToggleSelection': '選擇工作階段',
'ai.chat.managerSelectAll': '全選',
'ai.chat.managerSelectedCount': '已選 {n} 個',
'ai.chat.managerSelectRow': '選擇此工作階段',
'ai.chat.managerRegenerateTitle': '用 AI 重新產生標題',
'ai.chat.managerExportOne': '匯出此會話',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '閒置',
'ai.chat.managerMessagesCount': '{n} 則訊息',
'ai.chat.managerDeleteTitle': '刪除此會話?',
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.justNow': '剛剛',
'ai.chat.minutesAgo': '{n}分鐘前',
'ai.chat.hoursAgo': '{n}小時前',
@@ -687,6 +694,15 @@ export const zhTWAiMessages: Messages = {
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
'ai.chatHistory.messageCap.unit': '則訊息',
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
'ai.chatHistory.titleModel': '標題模型',
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
'ai.chatHistory.titleModel.unavailable': '無法使用',
'ai.chatHistory.titleModel.providerPlaceholder': '選擇 provider',
'ai.chatHistory.titleModel.modelPlaceholder': '選擇模型',
// AI Error
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
+38
View File
@@ -438,6 +438,8 @@ export const zhTWCoreMessages: Messages = {
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
'settings.vault.removeTopTabsDragArea': '移除頂部視窗拖曳區域',
'settings.vault.removeTopTabsDragAreaDesc': '開啟後移除分頁上方的拖曳空白區域,讓頂部可供點擊分頁與視窗按鈕。',
'settings.vault.showHostTreeSidebarDesc': '在終端和編輯器分頁顯示主機列表側欄及頂部開關。',
'settings.vault.autoImportSystemKnownHosts': '自動匯入系統 known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': '開啟主機庫時靜默匯入 OpenSSH known_hosts 中的記錄。關閉後,Netcatty 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
@@ -1416,4 +1418,40 @@ Vaults 分頁維持扁平,不使用這塊背景。
'plugins.hostActions.managedUnsupported': '受管理的 SSH 設定變更需在 Vault 主機編輯器中完成。',
'plugins.hostActions.failed': '請求已過期、被撤銷或主機已變更。請重新選擇主機。',
'plugins.hostActions.selectionLimit': '最多選擇 50 部目前的主機。',
'settings.externalEditor.title': '外部遠端編輯器',
'settings.externalEditor.desc': '直接在本機編輯器(如 Zed、VS Code 或 Cursor)中開啟遠端 SSH 專案與檔案。',
'settings.externalEditor.preferredEditor': '偏好編輯器',
'settings.externalEditor.preferredEditor.desc': 'SFTP 右鍵選單與終端機開啟請求預設使用的本機編輯器。',
'settings.externalEditor.executablePath': '編輯器執行檔',
'settings.externalEditor.executablePath.desc': '留空以自動偵測,或手動選擇本機程式路徑。',
'settings.externalEditor.executablePath.placeholder': '自動偵測執行檔路徑',
'settings.externalEditor.status.configured': '已自訂路徑',
'settings.externalEditor.status.detected': '已自動偵測',
'settings.externalEditor.status.notFound': '未偵測到',
'settings.externalEditor.browse': '瀏覽…',
'settings.externalEditor.resetPath': '重設為自動偵測',
'settings.externalEditor.redetect': '重新偵測已安裝的編輯器',
'settings.externalEditor.customArgs': '自訂參數',
'settings.externalEditor.customArgs.desc': '以空白分隔的參數清單(支援預留位置:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
'settings.externalEditor.connectionMode': 'SSH 連線模式',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 橋接會直接重複使用目前已完成驗證的連線,無需將私鑰或主機清單匯出至磁碟。',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 橋接 (*.netcatty)',
'settings.externalEditor.connectionMode.direct': '直連 OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 橋接規則',
'settings.externalEditor.sshBridge.desc': '僅在 OpenSSH 設定中寫入單一靜態 Host *.netcatty 規則區塊,不包含任何主機名稱、私鑰或密碼。',
'settings.externalEditor.sshBridge.install': '安裝橋接規則',
'settings.externalEditor.sshBridge.reinstall': '重新安裝規則',
'settings.externalEditor.sshBridge.update': '更新規則',
'settings.externalEditor.sshBridge.remove': '移除規則',
'settings.externalEditor.terminalRequests': '允許終端機發起開啟請求 (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': '允許遠端 Shell 透過 `zed .` 等指令在本機編輯器中開啟遠端路徑。',
'settings.externalEditor.autoSetup': '僅在 Netcatty 工作階段啟用遠端編輯器指令',
'settings.externalEditor.autoSetup.desc': '將 `zed` / `ncedit` 指令稿安裝至 ~/.netcatty/bin,並僅於目前 Netcatty 終端機工作階段的 PATH 生效,不修改 ~/.bashrc 或 ~/.zshrc(亦可依主機個別切換)。',
'settings.externalEditor.defaultTrust': '預設主機信任原則',
'settings.externalEditor.defaultTrust.desc': '尚未單獨設定信任原則的遠端主機請求開啟編輯器時的處理方式。',
'settings.externalEditor.trust.ask': '每次詢問',
'settings.externalEditor.trust.allow': '一律允許',
'settings.externalEditor.trust.deny': '一律拒絕',
'settings.externalEditor.trustedHosts.host': '主機',
'settings.externalEditor.trustedHosts.policy': '原則',
};
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const zhTWTerminalMessages: Messages = {
'terminal.directory.open': '目前目錄:{path}。變更目錄',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
'terminal.directory.unknown': '目錄未知',
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
'terminal.directory.directories': '目錄',
@@ -16,6 +18,7 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回閒置提示字元。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -630,6 +633,7 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.binding.command-palette': '開啟指令面板',
'settings.shortcuts.binding.quick-switch': '快速切換',
'settings.shortcuts.binding.new-workspace': '新增工作區',
'settings.shortcuts.binding.add-session-to-workspace': '新增工作階段至工作區',
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
'settings.shortcuts.binding.broadcast': '切換廣播模式',
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
@@ -719,6 +723,8 @@ export const zhTWTerminalMessages: Messages = {
'keychain.export.script': '指令碼 *',
'keychain.export.scriptPlaceholder': '匯出指令碼...',
'keychain.export.missingCredentials': '主機未儲存密碼或金鑰。請先為該主機新增密碼憑證。',
'keychain.export.missingPublicKey': '此金鑰沒有公鑰。請先在編輯頁貼上公鑰,然後再試「匯出並繫結」。',
'keychain.export.missingPublicKeyNote': '此金鑰沒有公鑰。請先在金鑰編輯頁貼上公鑰,然後再匯出。',
'keychain.export.successTitle': '匯出成功',
'keychain.export.successMessage': '已匯出公鑰並繫結到 {host}',
'keychain.export.failedTitle': '匯出失敗',
@@ -795,6 +801,7 @@ export const zhTWTerminalMessages: Messages = {
'tabs.logPrefix': '日誌:',
'tabs.logLocal': '本機',
'tabs.copyTab': '複製分頁',
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
'tabs.duplicateSession': '複製工作階段',
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
@@ -1088,4 +1095,12 @@ export const zhTWTerminalMessages: Messages = {
'terminal.browser.allScopeHint': '在每台主機的瀏覽器中顯示。',
'terminal.browser.downloadLocation': '檔案儲存在系統「下載項目」資料夾',
'terminal.browser.saveAs': '另存新檔…',
'terminal.externalEditor.opened': '已在 {editor} 中開啟 {path}',
'terminal.externalEditor.failed': '無法在 {editor} 中開啟',
'terminal.externalEditor.prompt.title': '在 {editor} 中開啟?',
'terminal.externalEditor.prompt.desc': '遠端主機 {host} 請求在 {editor} 中開啟以下遠端路徑:',
'terminal.externalEditor.prompt.deny': '拒絕',
'terminal.externalEditor.prompt.allowOnce': '僅允許這次',
'terminal.externalEditor.prompt.alwaysTrust': '一律信任此主機',
'terminal.externalEditor.autoSetupConfigured': '已設定遠端編輯器指令 ({editor})',
};
+4
View File
@@ -848,6 +848,7 @@ export const zhTWVaultMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': '恢復前',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} 台主機,{keys} 個金鑰,{snippets} 個程式碼片段,{notes} 條筆記',
'cloudSync.localBackups.aiCounts': '{sessions} 個 AI 工作階段,{settings} 項設定',
'cloudSync.localBackups.restore': '恢復',
'cloudSync.localBackups.restoreSuccess': '已恢復本機備份。',
'cloudSync.localBackups.restoreFailedTitle': '恢復失敗',
@@ -1427,5 +1428,8 @@ export const zhTWVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
'sftp.context.openInExternalEditor': '在 {editor} 中開啟',
'hostDetails.externalEditorShellIntegration': '於此工作階段啟用外部編輯器指令',
'hostDetails.externalEditorShellIntegration.desc': '透過 ~/.netcatty/bin 僅於目前 Netcatty 終端機工作階段啟用 `zed` / `ncedit`(支援 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
};
+3
View File
@@ -57,6 +57,9 @@ export interface LocalVaultBackupPreview {
noteCount: number;
identityCount: number;
portForwardingRuleCount: number;
/** Optional so backups written before these counters existed still load. */
aiSessionCount?: number;
settingCount?: number;
};
}
@@ -337,3 +337,43 @@ test('explicit CSS matching the last committed value supersedes pending CSS', ()
console.warn = originalWarn;
}
});
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
const bridgeWithDiag = {
...f.bridge,
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
diagnostics.push(payload);
return { success: true };
},
};
const store = new PluginViewSessions();
const view = store.acquire('diag-test', bridgeWithDiag, request);
const id = f.opened[0].instanceId;
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
assert.equal(view.getSnapshot().error, false);
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
assert.equal(diagnostics.length, 1);
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
assert.equal(view.getSnapshot().error, true);
assert.equal(diagnostics.length, 2);
assert.equal(diagnostics[1].source, 'plugin-view');
assert.match(diagnostics[1].message, /Invalid plugin update order/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
+27 -3
View File
@@ -3,7 +3,9 @@ import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
@@ -26,6 +28,7 @@ export class PluginViewSessions {
const id = crypto.randomUUID();
const tree = createPluginRemoteTree();
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
let loggedDuplicateNode = false;
let lastRawCss: string | null = null;
let pendingCss: string | null = null;
let pendingRawCss: string | null = null;
@@ -48,7 +51,7 @@ export class PluginViewSessions {
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
if (update.cssUnchanged) {
if (update.cssUnchanged || update.css === undefined) {
// keep pending CSS, if any, for the nextCss fallback below
} else if (lastRawCss !== null && update.css === lastRawCss) {
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
@@ -85,9 +88,23 @@ export class PluginViewSessions {
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
const duplicateNode = isDuplicatePluginViewNodeError(error);
if (!duplicateNode || !loggedDuplicateNode) {
if (duplicateNode) loggedDuplicateNode = true;
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to apply update for ${request.viewId}: ${message}`,
extra: {
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
viewId: request.viewId,
sequence: update.sequence,
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
},
}).catch(() => {});
}
// Recoverable duplicate-only batches are normalized as moves in
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
if (isDuplicatePluginViewNodeError(error)) {
if (duplicateNode) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
@@ -130,6 +147,13 @@ export class PluginViewSessions {
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
if (!disposed) {
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to send event for ${request.viewId}: ${message}`,
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
}).catch(() => {});
}
dispose(true);
});
},
+3
View File
@@ -25,6 +25,7 @@ export type SettingsChromeSnapshot = {
windowOpacity: number;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
removeTopTabsDragArea: boolean;
showRecentHosts: boolean;
hostClickBehavior: HostClickBehavior;
showOnlyUngroupedHostsInRoot: boolean;
@@ -59,6 +60,7 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
windowOpacity: 1,
showSftpTab: true,
showHostTreeSidebar: true,
removeTopTabsDragArea: false,
showRecentHosts: true,
hostClickBehavior: 'connect',
showOnlyUngroupedHostsInRoot: false,
@@ -86,6 +88,7 @@ export function settingsChromeSnapshotsEqual(
&& a.windowOpacity === b.windowOpacity
&& a.showSftpTab === b.showSftpTab
&& a.showHostTreeSidebar === b.showHostTreeSidebar
&& a.removeTopTabsDragArea === b.removeTopTabsDragArea
&& a.showRecentHosts === b.showRecentHosts
&& a.hostClickBehavior === b.hostClickBehavior
&& a.showOnlyUngroupedHostsInRoot === b.showOnlyUngroupedHostsInRoot
@@ -137,6 +137,7 @@ export type { HostClickBehavior } from '../../domain/hostClickBehavior';
export const DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = false;
export const DEFAULT_SHOW_SFTP_TAB = true;
export const DEFAULT_SHOW_HOST_TREE_SIDEBAR = true;
export const DEFAULT_REMOVE_TOP_TABS_DRAG_AREA = false;
export const DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = false;
export const DEFAULT_SHOW_TAB_NUMBER_BADGES = true;
export const DEFAULT_DISABLE_TERMINAL_FONT_ZOOM = false;
+14 -4
View File
@@ -35,6 +35,7 @@ import {
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
@@ -136,6 +137,7 @@ interface UseSettingsStorageSyncParams {
showOnlyUngroupedHostsInRoot: boolean;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
removeTopTabsDragArea: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
@@ -194,6 +196,7 @@ interface UseSettingsStorageSyncParams {
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setRemoveTopTabsDragAreaState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
@@ -238,7 +241,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -249,7 +252,7 @@ export function useSettingsStorageSync({
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
@@ -266,7 +269,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -278,7 +281,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -548,6 +551,12 @@ export function useSettingsStorageSync({
setShowHostTreeSidebarState(newValue);
}
}
if (e.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.removeTopTabsDragArea) {
setRemoveTopTabsDragAreaState(newValue);
}
}
if (e.key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.terminalSidePanelAutoOpen) {
@@ -701,6 +710,7 @@ export function useSettingsStorageSync({
setSftpSkipUnchanged,
setShowOnlyUngroupedHostsInRootState,
setShowHostTreeSidebarState,
setRemoveTopTabsDragAreaState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
+20 -3
View File
@@ -1,21 +1,38 @@
import {
buildSftpDownloadDialogDirectoryOptions,
normalizeSftpDefaultDownloadDirectory,
type SftpDownloadDialogDirectoryOptions,
} from "../../../domain/sftpDownloadLocation";
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
import {
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
STORAGE_KEY_SFTP_LAST_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
* Read the device-local download folders 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;
let lastUsed: string | null = null;
try {
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
lastUsed = localStorageAdapter.readString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
} catch {
// Storage unavailable (non-browser host); fall back to system Downloads.
}
return buildSftpDownloadDialogDirectoryOptions(stored);
return buildSftpDownloadDialogDirectoryOptions(stored, lastUsed);
};
/** Remember a confirmed download destination without changing the setting. */
export const rememberSftpDownloadDirectory = (directory: string): void => {
const normalized = normalizeSftpDefaultDownloadDirectory(directory);
if (!normalized) return;
try {
localStorageAdapter.writeString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR, normalized);
} catch {
// Unavailable storage must not interrupt the download.
}
};
@@ -1022,6 +1022,9 @@ export const useSftpConnections = ({
id: connectionId,
hostId: host.id,
hostLabel: host.label,
hostname: host.hostname,
port: host.port,
username: host.username,
isLocal: false,
status: "connecting",
currentPath: normalizedCachedStartPath,
@@ -47,6 +47,7 @@ test('Win32 adapters confirm actual native cwd and reject stale revisions or for
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
});
t.after(() => controller.dispose());
assert.equal(await controller.refresh(), cwd);
const revision = terminalCwdStore.getSessionRevision(id);
terminalCwdStore.setCwd(id, 'C:\\other', 'backend-strict');
terminalCwdStore.setCwd(id, 'C:\\base', 'backend-strict');
@@ -207,7 +208,7 @@ for (const probe of ['fails', 'stalls'] as const) {
t.after(() => controller.dispose());
await controller.change('/next', new AbortController().signal, () => {});
assert.deepEqual(writes, ["cd -- '/next'\r"]);
assert.equal(controller.hasConfirmedCwd(), true);
assert.equal(controller.getConfirmedCwd(), '/next');
});
}
@@ -1,5 +1,5 @@
import { DirectoryPickerError, directoryChangeCommand, isDirectoryPath, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
import { sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
import { DirectoryPickerError, directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
import { isAbsoluteDirectoryPath, sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { terminalCwdStore } from './terminalCwdStore';
@@ -17,21 +17,32 @@ export function createTerminalDirectoryController(options: {
capabilities?: DirectoryCapabilities;
buildChangeCommand?: (path: string) => string | null;
trustOsc7?: boolean;
localPosixSessionId?: string;
}) {
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
const valid = (path: string | null | undefined): path is string => isAbsoluteDirectoryPath(path, target.pathFlavor);
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
let disposed = false;
let changing = false;
let confirmed = false;
let verifiedCwd: string | null = null;
const cwdListeners = new Set<() => void>();
const notifyCwd = () => cwdListeners.forEach(listener => listener());
let refreshing: Promise<string> | null = null;
let refreshAgain = false;
let cwdError: DirectoryPickerError | null = null;
const lifetime = new AbortController();
const current = () => !disposed && options.isCurrent();
function getConfirmedCwd(): string | null {
if (!current() || !capabilities.readCwd) return null;
const cwd = terminalCwdStore.getCwd(options.sessionId);
const source = terminalCwdStore.getSource(options.sessionId);
if (source === 'stale') return null;
if (trustsOsc7 && source === 'osc7' && valid(cwd)) return cwd;
if (options.trustOsc7 === false && target.pathFlavor === 'posix') return verifiedCwd;
return verifiedCwd !== null && cwd === verifiedCwd ? verifiedCwd : null;
}
function check(signal?: AbortSignal) {
if (!current() || signal?.aborted) throw new DirectoryPickerError('unavailable');
}
@@ -69,7 +80,7 @@ export function createTerminalDirectoryController(options: {
// events and picker remounts. Only a cd submission may probe past its own
// pre-write report while waiting for fresh confirmation.
const reported = activeShellCwd();
if (reported) { confirmed = true; cwdError = null; return reported; }
if (reported) { cwdError = null; return reported; }
if (refreshing) {
// Output may settle while a pre-cd query is still in flight. Keep one
// follow-up query so that its older result cannot be the last update.
@@ -83,10 +94,10 @@ export function createTerminalDirectoryController(options: {
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
} catch (error) {
if (current() && !trustsOsc7) {
confirmed = false;
verifiedCwd = null;
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
options.publish('');
notifyCwd();
}
throw error;
}
@@ -94,12 +105,12 @@ export function createTerminalDirectoryController(options: {
const reported = activeShellCwd();
const live = terminalCwdStore.getCwd(options.sessionId);
const verifiedCwdChanged = verifiedCwd !== cwd;
confirmed = true;
verifiedCwd = cwd;
cwdError = null;
if (reported) return reported;
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|| (options.trustOsc7 === false && verifiedCwdChanged)) options.publish(cwd);
|| verifiedCwdChanged) options.publish(cwd);
if (verifiedCwdChanged) notifyCwd();
return cwd;
})();
refreshing = pending;
@@ -126,7 +137,7 @@ export function createTerminalDirectoryController(options: {
check(signal);
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
ready(); // The shell can become busy while resolving a remote symlink.
if (expectedCwd && (options.trustOsc7 === false ? verifiedCwd : terminalCwdStore.getCwd(options.sessionId)) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedCwd && getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
options.io.write(command + '\r');
@@ -172,17 +183,23 @@ export function createTerminalDirectoryController(options: {
};
await Promise.race([confirmFromProbe(), confirmFromOsc7()]);
check(signal);
confirmed = true;
} finally { confirmationFinished = true; changing = false; }
}
return {
target,
localPosixSessionId: options.localPosixSessionId,
capabilities,
trustsOsc7,
getVerifiedCwd: () => verifiedCwd,
getConfirmedCwd,
subscribeCwd(listener: () => void) {
const unsubscribe = terminalCwdStore.subscribe(listener);
cwdListeners.add(listener);
return () => {
unsubscribe();
cwdListeners.delete(listener);
};
},
getCwdError: () => cwdError?.code ?? null,
refresh: () => refresh(),
hasConfirmedCwd: () => confirmed,
async home() {
check();
const result = await bounded(options.io.home?.() ?? Promise.resolve(null));
+16 -1
View File
@@ -2,6 +2,7 @@ import type { TerminalDirectoryController } from './terminalDirectoryController'
const sessions = new Map<string, TerminalDirectoryController>();
const consumers = new Map<string, number>();
const refreshListeners = new Map<string, Set<() => void>>();
const scheduledRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
const OUTPUT_SETTLE_MS = 150;
@@ -36,10 +37,24 @@ export function observeTerminalDirectory(id: string) {
else { consumers.delete(id); cancelScheduledRefresh(id); }
};
}
export function subscribeTerminalDirectoryRefresh(id: string, listener: () => void) {
const listeners = refreshListeners.get(id) ?? new Set<() => void>();
listeners.add(listener);
refreshListeners.set(id, listeners);
return () => {
listeners.delete(listener);
if (!listeners.size) refreshListeners.delete(id);
};
}
/** Called by the existing command completion path, only while chips are visible. */
export function refreshObservedTerminalDirectory(id: string) {
cancelScheduledRefresh(id);
if (consumers.has(id)) void sessions.get(id)?.refresh().catch(() => {});
const controller = consumers.has(id) ? sessions.get(id) : undefined;
if (!controller) return;
void controller.refresh().then(() => {
if (sessions.get(id) === controller) refreshListeners.get(id)?.forEach(listener => listener());
}).catch(() => {});
}
/**
+88 -12
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
STORAGE_KEY_AI_PROVIDERS,
@@ -19,6 +19,8 @@ import {
STORAGE_KEY_AI_WEB_SEARCH,
STORAGE_KEY_AI_QUICK_MESSAGES,
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
STORAGE_KEY_AI_AUTO_LLM_TITLE,
STORAGE_KEY_AI_TITLE_MODEL,
} from '../../infrastructure/config/storageKeys';
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
@@ -46,6 +48,7 @@ import {
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
normalizeAiToolOutputMaxChars,
} from '../../domain/aiToolOutputLimit';
import type { TitleModelConfig } from '../../domain/aiSessionTitle';
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
import { getAIBridge } from './aiStateSnapshots';
import { useStoredBoolean } from './useStoredBoolean';
@@ -54,6 +57,25 @@ import {
readCommandBlocklistSetting,
} from './commandBlocklistSettings';
export type { TitleModelConfig };
function readTitleModelSetting(): TitleModelConfig | null {
const stored = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_TITLE_MODEL);
if (!stored || typeof stored !== 'object') return null;
const providerId = (stored as TitleModelConfig).providerId;
const modelId = (stored as TitleModelConfig).modelId;
return typeof providerId === 'string' && providerId.trim()
&& typeof modelId === 'string' && modelId.trim()
? { providerId: providerId.trim(), modelId: modelId.trim() }
: null;
}
function readAgentStringMap(key: string): Record<string, string> {
const stored = localStorageAdapter.read<unknown>(key);
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
return stored as Record<string, string>;
}
function readPermissionMode(): AIPermissionMode {
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
@@ -150,6 +172,25 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
);
const [autoLlmTitle, setAutoLlmTitle] = useStoredBoolean(STORAGE_KEY_AI_AUTO_LLM_TITLE, true);
const [titleModel, setTitleModelRaw] = useState<TitleModelConfig | null>(() =>
readTitleModelSetting(),
);
const titleModelRef = useRef(titleModel);
titleModelRef.current = titleModel;
const setTitleModel = useCallback((config: TitleModelConfig | null) => {
const normalized = config
&& typeof config.providerId === 'string' && config.providerId.trim()
&& typeof config.modelId === 'string' && config.modelId.trim()
? { providerId: config.providerId.trim(), modelId: config.modelId.trim() }
: null;
titleModelRef.current = normalized;
setTitleModelRaw(normalized);
if (normalized) localStorageAdapter.write(STORAGE_KEY_AI_TITLE_MODEL, normalized);
else localStorageAdapter.remove(STORAGE_KEY_AI_TITLE_MODEL);
emitAIStateChanged(STORAGE_KEY_AI_TITLE_MODEL);
}, []);
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
setProvidersRaw((prev) => {
@@ -183,6 +224,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, '');
return '';
});
if (titleModelRef.current?.providerId === id) {
setTitleModel(null);
}
if (onRemoveProvider) {
onRemoveProvider(id);
@@ -196,11 +240,13 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
const cleanup = removeProviderReferences(id, agentProviderMap, agentModelMap);
if (cleanup.providerMapChanged) {
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
emitAIStateChanged(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
}
if (cleanup.modelMapChanged) {
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
emitAIStateChanged(STORAGE_KEY_AI_AGENT_MODEL_MAP);
}
}, [onRemoveProvider, setProviders]);
}, [onRemoveProvider, setProviders, setTitleModel]);
const setActiveProviderId = useCallback((id: string) => {
setActiveProviderIdRaw(id);
@@ -375,6 +421,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
case STORAGE_KEY_AI_QUICK_MESSAGES:
setQuickMessagesRaw(sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)));
break;
case STORAGE_KEY_AI_TITLE_MODEL:
setTitleModelRaw(readTitleModelSetting());
break;
}
} catch (err) {
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
@@ -438,6 +487,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
}), [
providers,
setProviders,
@@ -471,6 +524,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
]);
}
@@ -486,6 +543,12 @@ export function useAISettingsState() {
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
true,
);
const [agentProviderMap, setAgentProviderMapRaw] = useState<Record<string, string>>(() =>
readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP),
);
const [agentModelMap, setAgentModelMapRaw] = useState<Record<string, string>>(() =>
readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP),
);
const setAiSessionMessageCap = useCallback((value: number) => {
const normalizedValue = normalizeAiSessionMessageCap(value);
@@ -494,23 +557,32 @@ export function useAISettingsState() {
}, []);
useEffect(() => {
const syncMessageCap = (key: string | null) => {
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
const syncSettingsOnlyKey = (key: string | null) => {
try {
setAiSessionMessageCapRaw(
normalizeAiSessionMessageCap(
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
),
);
switch (key) {
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
setAiSessionMessageCapRaw(
normalizeAiSessionMessageCap(
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
),
);
break;
case STORAGE_KEY_AI_AGENT_PROVIDER_MAP:
setAgentProviderMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP));
break;
case STORAGE_KEY_AI_AGENT_MODEL_MAP:
setAgentModelMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP));
break;
}
} catch (err) {
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
}
};
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
const handleStorage = (event: StorageEvent) => syncSettingsOnlyKey(event.key);
const handleLocalStateChanged = (event: Event) => {
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
syncSettingsOnlyKey((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
};
window.addEventListener('storage', handleStorage);
@@ -527,11 +599,15 @@ export function useAISettingsState() {
setAiSessionMessageCap,
showTerminalSelectionAIAction,
setShowTerminalSelectionAIAction,
agentProviderMap,
agentModelMap,
}), [
shared,
aiSessionMessageCap,
setAiSessionMessageCap,
showTerminalSelectionAIAction,
setShowTerminalSelectionAIAction,
agentProviderMap,
agentModelMap,
]);
}
@@ -0,0 +1,345 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import type { AISession, ProviderConfig } from '../../infrastructure/ai/types.ts';
import {
STORAGE_KEY_AI_ACTIVE_PROVIDER,
STORAGE_KEY_AI_AGENT_MODEL_MAP,
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
STORAGE_KEY_AI_AUTO_LLM_TITLE,
STORAGE_KEY_AI_PROVIDERS,
STORAGE_KEY_AI_TITLE_MODEL,
} from '../../infrastructure/config/storageKeys.ts';
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
import { useAISessionsStore } from './aiSessionsStore.ts';
import {
__resetIdbPersistenceForTests,
markAiSessionsHydrationComplete,
setLatestAISessionsSnapshot,
} from './aiStateSnapshots.ts';
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
type Capture = {
ai: ReturnType<typeof useAIState> | null;
sessions: AISession[];
};
function Harness({
capture,
options,
}: {
capture: Capture;
options?: UseAIStateOptions;
}) {
capture.ai = useAIState(options);
capture.sessions = useAISessionsStore().sessions as AISession[];
return null;
}
async function setupHook(options?: {
sessions?: AISession[];
providers?: ProviderConfig[];
activeProviderId?: string;
agentProviderMap?: Record<string, string>;
agentModelMap?: Record<string, string>;
autoLlmTitle?: boolean;
titleModel?: { providerId: string; modelId: string } | null;
generateSessionTitle?: UseAIStateOptions['generateSessionTitle'];
}) {
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
const prevDescriptors = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of [
['window', dom.window],
['document', dom.window.document],
['localStorage', dom.window.localStorage],
['CustomEvent', dom.window.CustomEvent],
['Event', dom.window.Event],
['IS_REACT_ACT_ENVIRONMENT', true],
] as const) {
prevDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
__resetIdbPersistenceForTests();
markAiSessionsHydrationComplete();
if (options?.providers) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify(options.providers));
}
if (options?.activeProviderId) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, options.activeProviderId);
}
if (options?.agentProviderMap) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify(options.agentProviderMap));
}
if (options?.agentModelMap) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify(options.agentModelMap));
}
if (options?.autoLlmTitle !== undefined) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AUTO_LLM_TITLE, String(options.autoLlmTitle));
}
if (options?.titleModel) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_TITLE_MODEL, JSON.stringify(options.titleModel));
}
const initialSessions = options?.sessions ?? [];
setLatestAISessionsSnapshot(initialSessions);
dom.window.localStorage.setItem('netcatty_ai_sessions_v1', JSON.stringify(initialSessions));
const container = dom.window.document.createElement('div');
dom.window.document.body.appendChild(container);
const root = createRoot(container);
const capture: Capture = { ai: null, sessions: [] };
await act(async () => {
root.render(
React.createElement(Harness, {
capture,
options: { generateSessionTitle: options?.generateSessionTitle },
}),
);
});
return {
capture,
cleanup: async () => {
await act(async () => root.unmount());
container.remove();
dom.window.close();
__resetIdbPersistenceForTests();
for (const [key, desc] of prevDescriptors) {
if (desc) Object.defineProperty(globalThis, key, desc);
else delete (globalThis as Record<string, unknown>)[key];
}
},
};
}
const providerA: ProviderConfig = {
id: 'p-catty',
providerId: 'openai',
name: 'Main OpenAI',
enabled: true,
defaultModel: 'gpt-5.4',
};
const providerB: ProviderConfig = {
id: 'p-title',
providerId: 'openai',
name: 'Cheap Title',
enabled: true,
defaultModel: 'gpt-4o-mini',
};
const untitledSession = (id = 's-1'): AISession => ({
id,
title: 'New Chat',
agentId: 'catty',
scope: { type: 'terminal', targetId: 'term-1' },
messages: [{ id: 'm-1', role: 'user', content: 'Check slow SSH handshake on prod', timestamp: 1 }],
createdAt: 1,
updatedAt: 1,
});
test('autoTitleSession preserves a user rename that happens while LLM title generation is pending', async () => {
const pending = deferred<string>();
let capturedSignal: AbortSignal | undefined;
const { capture, cleanup } = await setupHook({
sessions: [untitledSession()],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async (_source, opts) => {
capturedSignal = opts.signal;
return pending.promise;
},
});
try {
let titleTask!: Promise<void>;
await act(async () => {
titleTask = capture.ai!.autoTitleSession('s-1', 'Check slow SSH handshake on prod');
});
// Deterministic fallback landed immediately.
assert.equal(capture.sessions[0].title, 'Check slow SSH handshake on prod');
assert.equal(capturedSignal?.aborted, false);
// User renames the session (e.g. after closing & reopening the side panel).
await act(async () => {
capture.ai!.updateSessionTitle('s-1', 'Prod SSH Debug');
});
assert.equal(capturedSignal?.aborted, true, 'manual rename aborts pending LLM call');
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
// Even if the LLM promise resolves with a generated title afterwards, it
// must not overwrite the user's title.
await act(async () => {
pending.resolve('Slow SSH Handshake');
await titleTask;
});
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
} finally {
await cleanup();
}
});
test('autoTitleSession promotes the LLM title when unrenamed and passes Catty or explicit titleModel config', async () => {
const seenConfigs: Array<ProviderConfig | null | undefined> = [];
const pending = deferred<string>();
const { capture, cleanup } = await setupHook({
sessions: [untitledSession('s-catty'), untitledSession('s-explicit')],
providers: [providerB, providerA],
activeProviderId: providerB.id,
agentProviderMap: { catty: providerA.id },
agentModelMap: { catty: 'gpt-5.4-turbo' },
generateSessionTitle: async (_source, opts) => {
seenConfigs.push(opts.config);
return pending.promise;
},
});
try {
let task!: Promise<void>;
await act(async () => {
task = capture.ai!.autoTitleSession('s-catty', 'Check slow SSH handshake on prod');
});
assert.equal(seenConfigs[0]?.id, providerA.id);
assert.equal(seenConfigs[0]?.defaultModel, 'gpt-5.4-turbo');
await act(async () => {
pending.resolve('SSH Handshake Audit');
await task;
});
assert.equal(capture.sessions.find((s) => s.id === 's-catty')?.title, 'SSH Handshake Audit');
// Explicit titleModel overrides Catty model.
await act(async () => {
capture.ai!.setTitleModel({ providerId: providerB.id, modelId: 'gpt-4o-mini' });
});
await act(async () => {
await capture.ai!.autoTitleSession('s-explicit', 'Inspect nginx error logs');
});
assert.equal(seenConfigs[1]?.id, providerB.id);
assert.equal(seenConfigs[1]?.defaultModel, 'gpt-4o-mini');
assert.equal(capture.sessions.find((s) => s.id === 's-explicit')?.title, 'SSH Handshake Audit');
} finally {
await cleanup();
}
});
test('autoTitleSession aborts and ignores deleted sessions, deduplicates concurrent calls, and skips titled chats', async () => {
const pending = deferred<string>();
let calls = 0;
let signalRef: AbortSignal | undefined;
const { capture, cleanup } = await setupHook({
sessions: [
untitledSession('s-del'),
untitledSession('s-dup'),
{ ...untitledSession('s-titled'), title: 'Already named' },
],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async (_source, opts) => {
calls += 1;
signalRef = opts.signal;
return pending.promise;
},
});
try {
// Titled chat skips both fallback and LLM.
await act(async () => {
await capture.ai!.autoTitleSession('s-titled', 'New prompt text');
});
assert.equal(calls, 0);
assert.equal(capture.sessions.find((s) => s.id === 's-titled')?.title, 'Already named');
// Deleting a session aborts in-flight generation and never resurrects it.
let delTask!: Promise<void>;
await act(async () => {
delTask = capture.ai!.autoTitleSession('s-del', 'Delete me mid-flight');
});
assert.equal(calls, 1);
await act(async () => {
capture.ai!.deleteSession('s-del');
});
assert.equal(signalRef?.aborted, true);
await act(async () => {
pending.resolve('Ghost title');
await delTask;
});
assert.equal(capture.sessions.some((s) => s.id === 's-del'), false);
// Duplicate concurrent call for the same session only invokes LLM once.
const pendingDup = deferred<string>();
const dupHarness = await setupHook({
sessions: [untitledSession('s-dup2')],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async () => {
calls += 1;
return pendingDup.promise;
},
});
try {
let t1!: Promise<void>;
let t2!: Promise<void>;
await act(async () => {
t1 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'First call');
t2 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'Second call');
});
assert.equal(calls, 2);
await act(async () => {
pendingDup.resolve('Single Title');
await Promise.all([t1, t2]);
});
assert.equal(dupHarness.capture.sessions.find((s) => s.id === 's-dup2')?.title, 'Single Title');
} finally {
await dupHarness.cleanup();
}
} finally {
await cleanup();
}
});
test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dangling titleModel', async () => {
let calls = 0;
const { capture, cleanup } = await setupHook({
sessions: [untitledSession('s-off')],
providers: [providerA, providerB],
activeProviderId: providerA.id,
autoLlmTitle: false,
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
generateSessionTitle: async () => {
calls += 1;
return 'Should not run';
},
});
try {
await act(async () => {
await capture.ai!.autoTitleSession('s-off', 'Fallback only please');
});
assert.equal(calls, 0);
assert.equal(capture.sessions[0].title, 'Fallback only please');
assert.deepEqual(capture.ai!.titleModel, { providerId: providerB.id, modelId: 'gpt-4o-mini' });
await act(async () => {
capture.ai!.removeProvider(providerB.id);
});
assert.equal(capture.ai!.titleModel, null);
} finally {
await cleanup();
}
});
+263 -3
View File
@@ -98,8 +98,20 @@ import {
buildUndoLastTurnBranch,
type UndoLastTurnRestoredDraft,
} from '../../domain/aiUndoLastTurn';
import {
applySessionTitleIfCurrent,
buildFallbackTitle,
canAutoTitleSession,
resolveEffectiveTitleModelConfig,
} from '../../domain/aiSessionTitle';
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
export function useAIState() {
export interface UseAIStateOptions {
/** Optional test injection for one-shot LLM title generation. */
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
}
export function useAIState(options?: UseAIStateOptions) {
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
);
@@ -402,11 +414,35 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
} = useSharedAISettingsState({
ignoreInvalidPermissionModeOnStorage: true,
onRemoveProvider: handleRemoveProviderReferences,
});
const providersRef = useRef(providers);
providersRef.current = providers;
const activeProviderIdRef = useRef(activeProviderId);
activeProviderIdRef.current = activeProviderId;
const activeModelIdRef = useRef(activeModelId);
activeModelIdRef.current = activeModelId;
const autoLlmTitleRef = useRef(autoLlmTitle);
autoLlmTitleRef.current = autoLlmTitle;
const titleModelRef = useRef(titleModel);
titleModelRef.current = titleModel;
const generateSessionTitleRef = useRef(options?.generateSessionTitle);
generateSessionTitleRef.current = options?.generateSessionTitle;
const pendingCreatedSessionIdsRef = useRef<Set<string>>(new Set());
const titleAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
useEffect(() => {
for (const session of sessions) {
pendingCreatedSessionIdsRef.current.delete(session.id);
}
}, [sessions]);
useEffect(() => {
setLatestAISessionsSnapshot(sessions);
}, [sessions]);
@@ -724,6 +760,14 @@ export function useAIState() {
createdAt: now,
updatedAt: now,
};
// Keep the source workspace name when the fork stays in that workspace;
// a fork into a different/terminal scope must not inherit a stale name.
if (
source.workspaceNameSnapshot
&& (!viewingScope || (viewingScope.type === 'workspace' && viewingScope.targetId === source.scope.targetId))
) {
fork.workspaceNameSnapshot = source.workspaceNameSnapshot;
}
if (plan.contextCompaction) {
fork.contextCompaction = plan.contextCompaction;
}
@@ -739,17 +783,25 @@ export function useAIState() {
return fork;
}, [persistSessions, setActiveSessionId]);
const createSession = useCallback((scope: AISessionScope, agentId?: string): AISession => {
const createSession = useCallback((
scope: AISessionScope,
agentId?: string,
workspaceNameSnapshot?: string,
): AISession => {
const now = Date.now();
const session: AISession = {
id: `ai_${now}_${Math.random().toString(36).slice(2, 8)}`,
title: 'New Chat',
agentId: agentId || defaultAgentId,
scope,
...(scope.type === 'workspace' && workspaceNameSnapshot
? { workspaceNameSnapshot }
: {}),
messages: [],
createdAt: now,
updatedAt: now,
};
pendingCreatedSessionIdsRef.current.add(session.id);
setSessionsRaw(prev => {
const next = [session, ...prev];
setLatestAISessionsSnapshot(next);
@@ -796,6 +848,12 @@ export function useAIState() {
}, [persistSessions, setActiveSessionId]);
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
pendingCreatedSessionIdsRef.current.delete(sessionId);
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(sessionId);
pendingTitleController.abort();
}
cleanupDeletedAIChatSessions([sessionId]);
if (persistTimerRef.current) {
clearTimeout(persistTimerRef.current);
@@ -838,6 +896,14 @@ export function useAIState() {
const removedSessionIds = sessionsRef.current
.filter(s => s.scope.type === scopeType && s.scope.targetId === targetId)
.map(s => s.id);
for (const removedId of removedSessionIds) {
pendingCreatedSessionIdsRef.current.delete(removedId);
const pendingTitleController = titleAbortControllersRef.current.get(removedId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(removedId);
pendingTitleController.abort();
}
}
cleanupDeletedAIChatSessions(removedSessionIds);
if (persistTimerRef.current) {
clearTimeout(persistTimerRef.current);
@@ -865,6 +931,12 @@ export function useAIState() {
}, [persistSessions]);
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
// Manual rename supersedes any in-flight automatic title generation.
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(sessionId);
pendingTitleController.abort();
}
setSessionsRaw(prev => {
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
setLatestAISessionsSnapshot(next);
@@ -873,12 +945,182 @@ export function useAIState() {
});
}, [persistSessions]);
/**
* Auto-title a session if it still carries the placeholder title. Writes a
* deterministic fallback immediately, then (when enabled and a model is
* configured) upgrades it with a one-shot LLM summary. Lives in application
* state so panel close/reopen cannot break the in-flight lifecycle, and
* compares against live state atomically so a user rename always wins.
*/
const autoTitleSession = useCallback(async (
sessionId: string,
text: string,
callerSignal?: AbortSignal,
): Promise<void> => {
if (!sessionId) return;
if (titleAbortControllersRef.current.has(sessionId)) return;
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const existing = snapshot.find((s) => s.id === sessionId);
if (existing && !canAutoTitleSession(existing)) return;
if (!existing && !pendingCreatedSessionIdsRef.current.has(sessionId)) return;
const fallback = buildFallbackTitle(text);
// Phase 1: Atomically apply the deterministic fallback while still untitled.
setSessionsRaw((prev) => {
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
if (!result.updated) return prev;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
});
if (!autoLlmTitleRef.current || callerSignal?.aborted) return;
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
activeProviderId: activeProviderIdRef.current,
activeModelId: activeModelIdRef.current,
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) return;
const requestController = new AbortController();
titleAbortControllersRef.current.set(sessionId, requestController);
const onCallerAbort = () => requestController.abort();
if (callerSignal) {
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
}
try {
const latestBeforeCall = (latestAISessionsSnapshot ?? sessionsRef.current)
.find((s) => s.id === sessionId);
if (
latestBeforeCall
&& !canAutoTitleSession(latestBeforeCall)
&& latestBeforeCall.title !== fallback
) {
return;
}
const sourceMessages = latestBeforeCall?.messages?.length
? latestBeforeCall.messages
: (text ? [{ role: 'user' as const, content: text }] : []);
if (sourceMessages.length === 0) return;
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
{ messages: sourceMessages },
{
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: requestController.signal,
},
);
if (requestController.signal.aborted || !generated || generated === fallback) {
return;
}
// Phase 2: Atomically promote the LLM title only if the session still
// exists and still holds the exact fallback title applied in Phase 1.
if (mountedRef.current) {
setSessionsRaw((prev) => {
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
if (!result.updated) return prev;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
});
} else {
const current = latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot();
const result = applySessionTitleIfCurrent(current, sessionId, generated, fallback);
if (result.updated) {
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
}
}
} catch {
// Generation never throws; fallback was already applied above.
} finally {
if (callerSignal) {
callerSignal.removeEventListener('abort', onCallerAbort);
}
if (titleAbortControllersRef.current.get(sessionId) === requestController) {
titleAbortControllersRef.current.delete(sessionId);
}
}
}, [persistSessions]);
/**
* Explicitly regenerate an existing chat's title with the configured LLM
* (session-history management: no placeholder gate). The old title is the
* expected value, so a user rename during generation still wins.
*/
const regenerateSessionTitle = useCallback(async (sessionId: string): Promise<void> => {
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) return;
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const session = snapshot.find((s) => s.id === sessionId);
if (!session || session.messages.length === 0) return;
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
activeProviderId: activeProviderIdRef.current,
activeModelId: activeModelIdRef.current,
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) return;
const controller = new AbortController();
titleAbortControllersRef.current.set(sessionId, controller);
try {
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
{ messages: session.messages },
{
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: controller.signal,
fallbackOnFailure: false,
},
);
if (controller.signal.aborted || !generated || generated === session.title) return;
const previousTitle = session.title;
const commit = (sessions: AISession[]) => {
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
if (!result.updated) return sessions;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
};
if (mountedRef.current) setSessionsRaw(commit);
else {
const result = commit(latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot());
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
void result;
}
} catch {
// Title generation never throws; keep the existing title on failure.
} finally {
if (titleAbortControllersRef.current.get(sessionId) === controller) {
titleAbortControllersRef.current.delete(sessionId);
}
}
}, [persistSessions]);
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
// Rewrites `scope`, clears the dangling marker and makes the chat the
// active session of its new scope so it shows in the scoped history again.
const rebindSessionScope = useCallback((
sessionId: string,
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
workspaceNameSnapshot?: string,
) => {
const scopeKey = `${scope.type}:${scope.targetId}`;
// Capture the PRE-rebind active map before rebindActiveSessionMap drops the
@@ -903,9 +1145,15 @@ export function useAIState() {
if (scope.hostIds && scope.hostIds.length > 0) {
nextScope.hostIds = [...scope.hostIds];
}
// Snapshot follows the binding: keep it only for workspace scopes.
// `rest` may still carry a stale snapshot from a previous workspace.
const { workspaceNameSnapshot: _staleSnapshot, ...withoutSnapshot } = rest;
return {
...rest,
...withoutSnapshot,
scope: nextScope,
...(scope.type === 'workspace' && workspaceNameSnapshot
? { workspaceNameSnapshot }
: {}),
updatedAt: Date.now(),
} as AISession;
});
@@ -1453,6 +1701,10 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
// sessions / activeSessionIdMap / draftsByScope / panelViewByScope live in
// aiSessionsStore so streaming updates do not rebuild this config object.
setActiveSessionId,
@@ -1468,6 +1720,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -1522,6 +1776,10 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
setActiveSessionId,
ensureDraftForScope,
updateDraft,
@@ -1535,6 +1793,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
+4 -2
View File
@@ -63,6 +63,8 @@ interface CloudSyncRunOptions {
conflictActionOverride?: CloudSyncConflictAction;
applyConvergentPayload?: ConvergentPayloadApplier;
signal?: AbortSignal;
/** One-shot manual sync: skip convergent fan-out (single-provider only). */
forceSingleProvider?: boolean;
}
export interface CloudSyncHook {
@@ -134,7 +136,7 @@ export interface CloudSyncHook {
syncToProvider: (
provider: CloudProvider,
payload: SyncPayload,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
) => Promise<SyncResult>;
downloadFromProvider: (provider: CloudProvider) => Promise<RemoteSyncPayload | null>;
commitRemoteInspection: (provider: CloudProvider, remoteFile: SyncedFile, payload: SyncPayload, opts?: { recordDownload?: boolean }) => Promise<void>;
@@ -818,7 +820,7 @@ export const useCloudSync = (): CloudSyncHook => {
const syncToProviderWithUnlock = useCallback(async (
provider: CloudProvider,
payload: SyncPayload,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
) => {
await ensureUnlocked();
const controller = new AbortController();
+13 -18
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 { DirectoryPickerError, filterDirectories, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
import { parentDirectoryPath } from '../../domain/directoryPath';
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
import { terminalCwdStore } from './terminalCwdStore';
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
@@ -7,15 +8,9 @@ import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirect
export function useComposeDirectoryPicker(sessionId: string) {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const getCurrentCwd = useCallback(() => controller?.trustsOsc7 === false && pathFlavor === 'posix'
? controller.getVerifiedCwd() : terminalCwdStore.getCwd(sessionId), [controller, pathFlavor, sessionId]);
const observedCwd = getCurrentCwd();
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (controller.trustsOsc7 && terminalCwdStore.getSource(sessionId) === 'osc7'))
? observedCwd : null;
const subscribeCwd = controller?.subscribeCwd ?? terminalCwdStore.subscribe;
const getCurrentCwd = useCallback(() => controller?.getConfirmedCwd() ?? null, [controller]);
const cwd = useSyncExternalStore(subscribeCwd, getCurrentCwd, () => null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [showHidden, setShowHidden] = useState(false);
@@ -47,11 +42,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
const stopObserving = observeTerminalDirectory(sessionId);
lifetime.current = new AbortController();
sending.current = false;
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
listingBase.current = null;
listingRevision.current = null;
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
if (generation.current === id) setHome(nextHome);
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
return () => {
generation.current = id + 1;
@@ -63,9 +58,9 @@ export function useComposeDirectoryPicker(sessionId: string) {
if (!controller) { setError('unavailable'); return; }
const id = generation.current;
setError(null);
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
try { await controller.refresh(); }
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
}, [controller, report, sessionId]);
}, [controller, report]);
const load = useCallback(async () => {
if (!controller || !cwd) return;
@@ -105,7 +100,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
if (!controller) { setError('unavailable'); return; }
if (sending.current) return;
if (!cwd || getCurrentCwd() !== cwd
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|| (path !== parentDirectoryPath(cwd, pathFlavor) && (listingBase.current !== cwd
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
sending.current = true; setPending(true); setError(null);
const id = generation.current;
@@ -120,11 +115,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const cwdError = useSyncExternalStore(subscribeCwd, () => controller?.getCwdError() ?? null, () => null);
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'cygwinIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
parent: cwd ? parentDirectoryPath(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
refresh, reload: load, change };
@@ -0,0 +1,61 @@
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 type { TerminalGitHeadResult } from '../../domain/terminalGitHead';
import { useComposeGitBranch } from './useComposeGitBranch';
import { createTerminalDirectoryController } from './terminalDirectoryController';
import { observeTerminalDirectory, refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry';
import { terminalCwdStore } from './terminalCwdStore';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
test('Git chip follows confirmed cwd and ignores an old worktree result', async t => {
const id = 'git-chip-test';
const calls: { id: string; cwd: string; resolve: (head: TerminalGitHeadResult) => void }[] = [];
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
netcatty: { readLocalSessionGitHead: (backendId: string, cwd: string) => new Promise<TerminalGitHeadResult>(resolve => {
calls.push({ id: backendId, cwd, resolve });
}) },
} });
const controller = createTerminalDirectoryController({
sessionId: id, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => true,
io: { cwd: async () => '/other', list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} },
publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, controller);
const stopObserving = observeTerminalDirectory(id);
let root!: ReactTestRenderer;
let head: ReturnType<typeof useComposeGitBranch>;
function Harness() { head = useComposeGitBranch(id); return null; }
const waitForCalls = async (count: number) => {
for (let i = 0; calls.length < count && i < 100; i++) await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(calls.length, count);
};
t.after(async () => {
await act(async () => { root?.unmount(); });
stopObserving(); unregister(); terminalCwdStore.setCwd(id, null);
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
else Reflect.deleteProperty(globalThis, 'window');
});
terminalCwdStore.setCwd(id, '/old', 'inferred');
await act(async () => { root = create(React.createElement(Harness)); });
assert.equal(head!, null);
assert.deepEqual(calls, []);
await act(async () => { terminalCwdStore.setCwd(id, '/old', 'osc7'); });
await waitForCalls(1);
assert.equal(calls[0].id, 'local-pty');
assert.equal(calls[0].cwd, '/old');
await act(async () => { terminalCwdStore.setCwd(id, '/other', 'osc7'); });
await waitForCalls(2);
await act(async () => { calls[1].resolve({ kind: 'branch', name: 'current', worktreeRoot: '/other' }); });
await act(async () => { calls[0].resolve({ kind: 'branch', name: 'old', worktreeRoot: '/old' }); });
assert.deepEqual(head!, { kind: 'branch', name: 'current', worktreeRoot: '/other' });
refreshObservedTerminalDirectory(id);
await waitForCalls(3);
await act(async () => { calls[2].resolve({ kind: 'detached', hash: '123abcd', worktreeRoot: '/other' }); });
assert.deepEqual(head!, { kind: 'detached', hash: '123abcd', worktreeRoot: '/other' });
await act(async () => { terminalCwdStore.setCwd(id, null); });
assert.equal(head!, null);
});
+67
View File
@@ -0,0 +1,67 @@
import { useEffect, useState, useSyncExternalStore } from 'react';
import type { TerminalGitHead } from '../../domain/terminalGitHead';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
import type { TerminalDirectoryController } from './terminalDirectoryController';
const noCwd = () => null;
const noSubscription = () => () => {};
const REFRESH_DELAY_MS = 150;
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const backendId = controller?.localPosixSessionId;
const cwd = useSyncExternalStore(
backendId ? controller.subscribeCwd : noSubscription,
backendId ? controller.getConfirmedCwd : noCwd,
noCwd,
);
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
useEffect(() => {
const bridge = netcattyBridge.get();
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
let active = true;
let pending = false;
let refreshAgain = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const isCurrent = () => active && getTerminalDirectory(sessionId) === controller && controller.getConfirmedCwd() === cwd;
const read = async () => {
if (!isCurrent()) return;
pending = true;
try {
const next = await bridge.readLocalSessionGitHead?.(backendId, cwd);
if (isCurrent() && !refreshAgain) {
setResult({ controller, cwd, head: next?.kind === 'branch' || next?.kind === 'detached' ? next : null });
}
} catch {
if (isCurrent() && !refreshAgain) setResult({ controller, cwd, head: null });
} finally {
pending = false;
if (refreshAgain && active) {
refreshAgain = false;
schedule();
}
}
};
const schedule = () => {
if (pending) {
refreshAgain = true;
return;
}
clearTimeout(timer);
timer = setTimeout(() => { void read(); }, REFRESH_DELAY_MS);
};
schedule();
const unsubscribe = subscribeTerminalDirectoryRefresh(sessionId, schedule);
return () => {
active = false;
clearTimeout(timer);
unsubscribe();
setResult(current => current?.controller === controller && current.cwd === cwd ? null : current);
};
}, [backendId, controller, cwd, sessionId]);
return result?.controller === controller && result.cwd === cwd ? result.head : null;
}
@@ -0,0 +1,480 @@
/**
* useExternalEditorSettings - Reactive store & launcher for External Editor integration
*
* Device-local (not cloud-synced because executable paths differ across machines).
* Uses useSyncExternalStore + window `storage` events so the Settings window and
* main Terminal/SFTP windows stay immediately in sync.
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import {
buildDirectSshTarget,
buildSshBridgeHostname,
getHostKeyForExternalEditor,
normalizeExternalEditorSettings,
validateAndNormalizeRemotePath,
type ExternalEditorConnectionMode,
type ExternalEditorHostIdentity,
type ExternalEditorHostTrustPolicy,
type ExternalEditorPresetId,
type ExternalEditorSettings,
type ExternalEditorTargetKind,
} from '../../domain/externalEditor';
import { STORAGE_KEY_EXTERNAL_EDITOR } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
netcattyBridge,
type ExternalEditorBridgeConfigStatus,
type ExternalEditorDetectEntry,
type ExternalEditorOpenRemoteResult,
} from '../../infrastructure/services/netcattyBridge';
export type {
ExternalEditorBridgeConfigStatus,
ExternalEditorDetectEntry,
ExternalEditorOpenRemoteResult,
};
const subscribers = new Set<() => void>();
function hasBrowserStorage(): boolean {
return typeof window !== 'undefined' && 'localStorage' in window;
}
function loadExternalEditorSettings(): ExternalEditorSettings {
if (!hasBrowserStorage()) {
return normalizeExternalEditorSettings(undefined);
}
try {
const stored = localStorageAdapter.read<Partial<ExternalEditorSettings>>(STORAGE_KEY_EXTERNAL_EDITOR);
return normalizeExternalEditorSettings(stored);
} catch {
return normalizeExternalEditorSettings(undefined);
}
}
let currentSettings: ExternalEditorSettings = loadExternalEditorSettings();
let storageListenerAttached = false;
function ensureStorageListener() {
if (storageListenerAttached || typeof window === 'undefined' || typeof window.addEventListener !== 'function') {
return;
}
storageListenerAttached = true;
window.addEventListener('storage', (event: StorageEvent) => {
if (event.key === STORAGE_KEY_EXTERNAL_EDITOR) {
writeSettings(loadExternalEditorSettings(), false);
}
});
}
ensureStorageListener();
function notifySubscribers() {
subscribers.forEach((cb) => cb());
}
function writeSettings(next: ExternalEditorSettings, persist = true) {
currentSettings = normalizeExternalEditorSettings(next);
if (persist && hasBrowserStorage()) {
try {
localStorageAdapter.write(STORAGE_KEY_EXTERNAL_EDITOR, currentSettings);
} catch {
// ignore storage write failures in restricted contexts
}
}
notifySubscribers();
}
function subscribe(callback: () => void) {
subscribers.add(callback);
return () => {
subscribers.delete(callback);
};
}
export function getExternalEditorSettingsSnapshot(): ExternalEditorSettings {
return currentSettings;
}
export function updateExternalEditorSettings(
updater: (prev: ExternalEditorSettings) => ExternalEditorSettings,
): ExternalEditorSettings {
const next = updater(currentSettings);
writeSettings(next, true);
return currentSettings;
}
export function setExternalEditorHostTrust(
host: ExternalEditorHostIdentity,
policy: ExternalEditorHostTrustPolicy,
): void {
const hostKey = getHostKeyForExternalEditor(host);
if (!hostKey) return;
updateExternalEditorSettings((prev) => ({
...prev,
trustedHosts: {
...prev.trustedHosts,
[hostKey]: policy,
},
}));
}
export function removeExternalEditorHostTrust(hostKey: string): void {
updateExternalEditorSettings((prev) => {
if (!Object.prototype.hasOwnProperty.call(prev.trustedHosts, hostKey)) return prev;
const nextTrusted = { ...prev.trustedHosts };
delete nextTrusted[hostKey];
return {
...prev,
trustedHosts: nextTrusted,
};
});
}
export interface LaunchRemoteExternalEditorParams {
editorId?: ExternalEditorPresetId;
host: ExternalEditorHostIdentity;
remotePath: string;
fallbackCwd?: string;
kind?: ExternalEditorTargetKind;
sessionId?: string;
sftpId?: string;
settings?: ExternalEditorSettings;
}
/**
* Shared application-layer launcher invoked by both Terminal OSC 7337 handlers
* and SFTP context menus.
*/
export async function launchRemoteExternalEditor(
params: LaunchRemoteExternalEditorParams,
): Promise<ExternalEditorOpenRemoteResult> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.openRemote) {
throw new Error('External editor integration requires the desktop application.');
}
const settings = params.settings ?? getExternalEditorSettingsSnapshot();
const editorId = params.editorId ?? settings.defaultEditor;
const editorConfig = settings.editors[editorId];
const validated = validateAndNormalizeRemotePath(params.remotePath, params.fallbackCwd);
if (!validated.ok) {
throw new Error('error' in validated ? validated.error : 'Invalid remote path');
}
const connectionMode = settings.connectionMode;
const bridgeHost = connectionMode === 'bridge'
? buildSshBridgeHostname(params.host)
: undefined;
const directSshTarget = connectionMode === 'direct'
? buildDirectSshTarget(params.host) ?? undefined
: undefined;
if (connectionMode === 'direct' && !directSshTarget) {
throw new Error('Cannot construct a valid OpenSSH target for this host.');
}
return bridge.externalEditor.openRemote({
editorId,
executablePath: editorConfig?.executablePath || undefined,
customArgs: editorId === 'custom' ? editorConfig?.customArgs : undefined,
connectionMode,
bridgeHost,
directSshTarget,
sessionId: params.sessionId,
sftpId: params.sftpId,
hostId: params.host.hostId,
hostname: params.host.hostname,
port: params.host.port,
username: params.host.username,
remotePath: validated.path,
kind: params.kind ?? 'auto',
});
}
export async function detectInstalledExternalEditors(): Promise<Record<string, ExternalEditorDetectEntry>> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.detect) return {};
return (await bridge.externalEditor.detect()) || {};
}
export async function getExternalEditorBridgeConfigStatus(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.getBridgeConfigStatus) return null;
return (await bridge.externalEditor.getBridgeConfigStatus()) || null;
}
export async function installExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.installBridgeConfig) return null;
return bridge.externalEditor.installBridgeConfig();
}
export async function removeExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.removeBridgeConfig) return null;
return bridge.externalEditor.removeBridgeConfig();
}
export async function selectExternalEditorApplication(): Promise<{ path: string; name?: string } | null> {
const bridge = netcattyBridge.get();
if (!bridge?.selectApplication) return null;
return (await bridge.selectApplication()) || null;
}
function getTerminalAutoSetupSnapshotKey(): string {
const s = currentSettings;
return `${s.terminalRequestsEnabled ? 1 : 0}:${s.autoSetupShellIntegration ? 1 : 0}:${s.defaultEditor}`;
}
/**
* Narrow selector for Terminal panes so edits to unrelated External Editor settings
* (executable paths, custom args, trust list, bridge mode) never re-render open terminals.
*/
export function useExternalEditorTerminalAutoSetupConfig(): {
terminalRequestsEnabled: boolean;
autoSetupShellIntegration: boolean;
defaultEditor: ExternalEditorPresetId;
} {
const key = useSyncExternalStore(
subscribe,
getTerminalAutoSetupSnapshotKey,
getTerminalAutoSetupSnapshotKey,
);
useEffect(() => {
ensureStorageListener();
}, []);
const [reqFlag, autoFlag, defaultEditor] = key.split(':');
return {
terminalRequestsEnabled: reqFlag === '1',
autoSetupShellIntegration: autoFlag === '1',
defaultEditor: defaultEditor as ExternalEditorPresetId,
};
}
export function useExternalEditorSettings() {
const settings = useSyncExternalStore(
subscribe,
getExternalEditorSettingsSnapshot,
getExternalEditorSettingsSnapshot,
);
useEffect(() => {
ensureStorageListener();
}, []);
const setDefaultEditor = useCallback((editorId: ExternalEditorPresetId) => {
updateExternalEditorSettings((prev) => ({
...prev,
defaultEditor: editorId,
}));
}, []);
const setEditorExecutablePath = useCallback((editorId: ExternalEditorPresetId, executablePath: string) => {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
[editorId]: {
...prev.editors[editorId],
executablePath,
},
},
}));
}, []);
const setCustomEditorArgs = useCallback((customArgs: string[]) => {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
custom: {
...prev.editors.custom,
customArgs,
},
},
}));
}, []);
const setTerminalRequestsEnabled = useCallback((enabled: boolean) => {
updateExternalEditorSettings((prev) => ({
...prev,
terminalRequestsEnabled: enabled,
}));
}, []);
const setAutoSetupShellIntegration = useCallback((enabled: boolean) => {
updateExternalEditorSettings((prev) => ({
...prev,
autoSetupShellIntegration: enabled,
}));
}, []);
const setDefaultTrustPolicy = useCallback((policy: ExternalEditorHostTrustPolicy) => {
updateExternalEditorSettings((prev) => ({
...prev,
defaultTrustPolicy: policy,
}));
}, []);
const setConnectionMode = useCallback((mode: ExternalEditorConnectionMode) => {
updateExternalEditorSettings((prev) => ({
...prev,
connectionMode: mode,
}));
}, []);
const setHostTrustPolicy = useCallback((hostKey: string, policy: ExternalEditorHostTrustPolicy) => {
updateExternalEditorSettings((prev) => ({
...prev,
trustedHosts: {
...prev.trustedHosts,
[hostKey]: policy,
},
}));
}, []);
const removeHostTrustPolicy = useCallback((hostKey: string) => {
removeExternalEditorHostTrust(hostKey);
}, []);
return {
settings,
setDefaultEditor,
setEditorExecutablePath,
setCustomEditorArgs,
setTerminalRequestsEnabled,
setAutoSetupShellIntegration,
setDefaultTrustPolicy,
setConnectionMode,
setHostTrustPolicy,
removeHostTrustPolicy,
};
}
/**
* Application-state hook owning external editor detection, `~/.ssh/config` bridge
* installation/removal, and application picker lifecycle so UI settings sections
* stay presentation-only.
*/
export function useExternalEditorEnvironment() {
const [detectedEditors, setDetectedEditors] = useState<Record<string, ExternalEditorDetectEntry>>({});
const [detecting, setDetecting] = useState(false);
const [selectingApp, setSelectingApp] = useState(false);
const [bridgeStatus, setBridgeStatus] = useState<ExternalEditorBridgeConfigStatus | null>(null);
const [bridgeBusy, setBridgeBusy] = useState(false);
const [bridgeError, setBridgeError] = useState<string | null>(null);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const refreshStatus = useCallback(async () => {
setDetecting(true);
try {
const [detected, cfg] = await Promise.all([
detectInstalledExternalEditors(),
getExternalEditorBridgeConfigStatus(),
]);
if (!mountedRef.current) return;
setDetectedEditors(detected);
setBridgeStatus(cfg);
setBridgeError(null);
} catch (err) {
if (!mountedRef.current) return;
setBridgeError(err instanceof Error ? err.message : String(err));
} finally {
if (mountedRef.current) {
setDetecting(false);
}
}
}, []);
useEffect(() => {
void refreshStatus();
}, [refreshStatus]);
const browseExecutable = useCallback(async (editorId: ExternalEditorPresetId): Promise<string | null> => {
setSelectingApp(true);
try {
const picked = await selectExternalEditorApplication();
if (picked?.path) {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
[editorId]: {
...prev.editors[editorId],
executablePath: picked.path,
},
},
}));
return picked.path;
}
return null;
} catch (err) {
console.error('[ExternalEditor] Failed to select executable:', err);
return null;
} finally {
if (mountedRef.current) {
setSelectingApp(false);
}
}
}, []);
const installBridgeConfig = useCallback(async () => {
setBridgeBusy(true);
setBridgeError(null);
try {
const status = await installExternalEditorBridgeConfig();
if (mountedRef.current && status) {
setBridgeStatus(status);
}
} catch (err) {
if (mountedRef.current) {
setBridgeError(err instanceof Error ? err.message : String(err));
}
} finally {
if (mountedRef.current) {
setBridgeBusy(false);
}
}
}, []);
const removeBridgeConfig = useCallback(async () => {
setBridgeBusy(true);
setBridgeError(null);
try {
const status = await removeExternalEditorBridgeConfig();
if (mountedRef.current && status) {
setBridgeStatus(status);
}
} catch (err) {
if (mountedRef.current) {
setBridgeError(err instanceof Error ? err.message : String(err));
}
} finally {
if (mountedRef.current) {
setBridgeBusy(false);
}
}
}, []);
return {
detectedEditors,
detecting,
selectingApp,
bridgeStatus,
bridgeBusy,
bridgeError,
refreshStatus,
browseExecutable,
installBridgeConfig,
removeBridgeConfig,
};
}
+4 -1
View File
@@ -16,7 +16,10 @@ export const checkAppShortcut = (
return null;
};
// Get list of key bindings that should be handled at app level (not by terminal)
// Get list of key bindings that should be handled at app level (not by terminal).
// Conditional shortcuts that pass through to the terminal when unavailable
// (like toggleHostTree and addSessionToWorkspace) stay out so an unconsumed
// chord still gets full Kitty/Win32/broadcast handling in xterm.
export const getAppLevelActions = (): Set<string> => {
return new Set([
'switchToTab',
+21 -2
View File
@@ -88,6 +88,7 @@ import {
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
@@ -145,6 +146,7 @@ import {
DEFAULT_HOST_CLICK_BEHAVIOR,
DEFAULT_SHOW_SFTP_TAB,
DEFAULT_SHOW_HOST_TREE_SIDEBAR,
DEFAULT_REMOVE_TOP_TABS_DRAG_AREA,
DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
DEFAULT_SHOW_TAB_NUMBER_BADGES,
DEFAULT_DISABLE_TERMINAL_FONT_ZOOM,
@@ -472,6 +474,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
return stored ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR;
});
const [removeTopTabsDragArea, setRemoveTopTabsDragAreaState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
return stored ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA;
});
const [terminalSidePanelAutoOpen, setTerminalSidePanelAutoOpenState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
return stored ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED;
@@ -1186,6 +1192,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
setShowHostTreeSidebarState(storedShowHostTreeSidebar ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR);
const storedRemoveTopTabsDragArea = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
setRemoveTopTabsDragAreaState(storedRemoveTopTabsDragArea ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA);
const storedTerminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
setTerminalSidePanelAutoOpenState(storedTerminalSidePanelAutoOpen ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED);
const storedTerminalSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
@@ -1489,7 +1497,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -1501,7 +1509,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
@@ -1647,6 +1655,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
notifySettingsChanged(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, enabled);
}, [notifySettingsChanged]);
const setRemoveTopTabsDragArea = useCallback((enabled: boolean) => {
setRemoveTopTabsDragAreaState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
}, [notifySettingsChanged]);
const setTerminalSidePanelAutoOpen = useCallback((enabled: boolean) => {
setTerminalSidePanelAutoOpenState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, enabled);
@@ -2181,6 +2196,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
windowOpacity,
showSftpTab,
showHostTreeSidebar,
removeTopTabsDragArea,
showRecentHosts,
hostClickBehavior,
showOnlyUngroupedHostsInRoot,
@@ -2205,6 +2221,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
restoreTerminalCwd,
shellOnlyTabNumberShortcuts,
showHostTreeSidebar,
removeTopTabsDragArea,
showOnlyUngroupedHostsInRoot,
showRecentHosts,
showSftpTab,
@@ -2385,6 +2402,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setShowSftpTab,
showHostTreeSidebar,
setShowHostTreeSidebar,
removeTopTabsDragArea,
setRemoveTopTabsDragArea,
terminalSidePanelAutoOpen,
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
@@ -11,11 +11,11 @@ type SessionProps = Parameters<typeof useTerminalDirectorySession>[0];
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) {
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo'], discoverShells?: NetcattyBridge['discoverShells']) {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
let probes = 0; let lists = 0;
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
getAppInfo,
getAppInfo, discoverShells,
getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; },
listLocalDir: async () => { lists++; return []; },
} } });
@@ -55,6 +55,19 @@ for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) {
});
}
test('a discovered Cygwin terminal registers its own POSIX directory controller', async t => {
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }), async () => [
{ id: 'cygwin', name: 'Cygwin', command: 'C:/cygwin64/bin/bash.exe', args: ['--login', '-i'], icon: 'cygwin' },
]);
const props = options('cygwin-tab');
props.host = { ...props.host, localShell: 'cygwin' };
function Harness() { useTerminalDirectorySession(props); return null; }
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness)); });
t.after(async () => { await act(async () => { root.unmount(); }); });
assert.deepEqual(getTerminalDirectory(props.sessionId)?.target, { authority: 'cygwin:cygwin-tab', pathFlavor: 'posix' });
});
for (const platform of ['linux', 'darwin']) {
test(`local POSIX directory controller registers on ${platform}`, async t => {
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform }));
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell';
import { isDiscoveredCygwin, isDiscoveredGitBash } from '../../lib/localShell';
export function useTerminalDirectorySession(options: {
sessionId: string;
@@ -36,16 +36,18 @@ export function useTerminalDirectorySession(options: {
let unregister = () => {};
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
if (!isCurrent()) return;
const sessionFilesystem = integration === 'wsl' || integration === 'cygwin';
const controller = createTerminalDirectoryController({
sessionId,
localPosixSessionId: local && !integration ? backendId : undefined,
io: createTerminalDirectoryIO(bridge, backendId, {
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
encoding: host.sftpEncoding,
pathFlavor,
windowsShell: integration,
}, isCurrent),
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: integration !== 'wsl',
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: !sessionFilesystem,
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
@@ -67,6 +69,8 @@ export function useTerminalDirectorySession(options: {
register('posix', 'wsl');
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
} else if (isDiscoveredCygwin(host.localShell, shells?.find(item => item.id === 'cygwin')?.command)) {
register('posix', 'cygwin');
}
}
}).catch(() => {});
@@ -0,0 +1,169 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX,
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
} from '../../domain/externalEditor';
import { createExternalEditorSessionProvisioner } from './useTerminalExternalEditor';
function flushMicrotasks(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
test('provisions initial editor helpers and activates PATH once, then installs newly selected editor without re-injecting PATH', async () => {
const execCalls: { sessionId: string; command: string }[] = [];
const writeCalls: { sessionId: string; data: string; opts?: { automated?: boolean } }[] = [];
const configuredLabels: string[] = [];
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (sessionId, command) => {
execCalls.push({ sessionId, command });
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
};
},
writeToSession: (sessionId, data, opts) => {
writeCalls.push({ sessionId, data, opts });
},
getCurrentSessionId: () => 'sess-1',
isReadyForCommandInjection: () => true,
onConfigured: (label) => configuredLabels.push(label),
});
// 1. Initial connection with Zed
const cancelZed = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.match(execCalls[0].command, /write_bin '\\''zed'\\''/);
assert.doesNotMatch(execCalls[0].command, /write_bin '\\''code'\\''/);
assert.equal(writeCalls.length, 1);
assert.match(writeCalls[0].data, /export PATH="\$HOME\/\.netcatty\/bin:\$PATH" NETCATTY_EXTERNAL_EDITOR=1/);
assert.deepEqual(writeCalls[0].opts, { automated: true });
assert.deepEqual(configuredLabels, ['Zed']);
// 2. Switching preferred editor to VS Code in the same live session installs `code`
// without injecting a duplicate PATH activation command into the terminal.
cancelZed();
const cancelVscode = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'vscode' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.match(execCalls[1].command, /write_bin '\\''code'\\''/);
assert.equal(writeCalls.length, 1);
assert.deepEqual(configuredLabels, ['Zed', 'VS Code']);
// 3. Switching back to Zed in the same session is a no-op (already provisioned + activated).
cancelVscode();
const cancelZedAgain = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.equal(writeCalls.length, 1);
cancelZedAgain();
});
test('polls until terminal prompt is ready and cancels cleanly if editor changes before prompt settles', async () => {
const execCalls: string[] = [];
const writeCalls: string[] = [];
const timers = new Map<number, () => void>();
let nextTimerId = 1;
let ready = false;
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (_sessionId, command) => {
execCalls.push(command);
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}fish\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
};
},
writeToSession: (_sessionId, data) => {
writeCalls.push(data);
},
getCurrentSessionId: () => 'sess-2',
isReadyForCommandInjection: () => ready,
scheduleTimer: (fn) => {
const id = nextTimerId++;
timers.set(id, fn);
return id as unknown as ReturnType<typeof setTimeout>;
},
clearTimer: (handle) => {
timers.delete(handle as unknown as number);
},
});
// Start with Zed while prompt is still busy with MOTD.
const cancelZed = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.equal(writeCalls.length, 0);
assert.equal(timers.size, 1);
// Switch to Cursor before prompt becomes ready: old poll is cancelled, Cursor is provisioned.
cancelZed();
assert.equal(timers.size, 0);
const cancelCursor = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'cursor' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.match(execCalls[1], /write_bin '\\''cursor'\\''/);
assert.equal(writeCalls.length, 0);
assert.equal(timers.size, 1);
// Prompt becomes ready -> fish PATH activation executes once.
ready = true;
const scheduled = [...timers.values()];
timers.clear();
scheduled.forEach((fn) => fn());
assert.equal(writeCalls.length, 1);
assert.match(writeCalls[0], /set -gx PATH "\$HOME\/\.netcatty\/bin" \$PATH/);
cancelCursor();
});
test('resets per-session tracking on disconnect so reconnect re-activates PATH', async () => {
let activeSessionId = 'sess-3';
const execCalls: string[] = [];
const writeCalls: string[] = [];
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (sessionId) => {
execCalls.push(sessionId);
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n`,
};
},
writeToSession: (sessionId) => {
writeCalls.push(sessionId);
},
getCurrentSessionId: () => activeSessionId,
isReadyForCommandInjection: () => true,
});
const cancelFirst = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.equal(writeCalls.length, 1);
cancelFirst();
// Disconnect resets session state even if the same sessionId reconnects.
provisioner.reset();
const cancelSecond = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.equal(writeCalls.length, 2);
cancelSecond();
// New backend sessionId also provisions and activates fresh.
activeSessionId = 'sess-4';
const cancelThird = provisioner.sync({ sessionId: 'sess-4', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 3);
assert.equal(writeCalls.length, 3);
cancelThird();
});
@@ -0,0 +1,387 @@
/**
* useTerminalExternalEditor - Application-state hook & session provisioner for
* Terminal External Editor integration (OSC 7337 requests, per-host trust prompts,
* and session-scoped ~/.netcatty/bin helper provisioning + one-time PATH activation).
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import {
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
buildExternalEditorAutoSetupCommand,
buildExternalEditorSessionActivateCommand,
getExternalEditorLabel,
parseExternalEditorAutoSetupShell,
resolveExternalEditorTrustPolicy,
shouldAutoSetupExternalEditorShell,
validateAndNormalizeRemotePath,
type ExternalEditorOscRequest,
type ExternalEditorPresetId,
type ExternalEditorTargetKind,
} from '../../domain/externalEditor';
import type { Host } from '../../domain/models';
import { logger } from '../../lib/logger';
import {
getExternalEditorSettingsSnapshot,
launchRemoteExternalEditor,
setExternalEditorHostTrust,
useExternalEditorTerminalAutoSetupConfig,
} from './useExternalEditorSettings';
export interface PendingExternalEditorRequest {
editorId: ExternalEditorPresetId;
editorLabel: string;
remotePath: string;
kind: ExternalEditorTargetKind;
}
export interface ExternalEditorSessionSetupResult {
success?: boolean;
stdout?: string;
stderr?: string;
error?: string;
}
export interface ExternalEditorSessionProvisionerDeps {
setupExec: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
getCurrentSessionId: () => string | null;
isReadyForCommandInjection: () => boolean;
onConfigured?: (editorLabel: string) => void;
onWarn?: (message: string, detail?: unknown) => void;
scheduleTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
clearTimer?: (handle: ReturnType<typeof setTimeout>) => void;
pollIntervalMs?: number;
maxPollAttempts?: number;
}
export interface ExternalEditorSessionProvisioner {
reset: () => void;
sync: (params: {
sessionId: string;
defaultEditor: ExternalEditorPresetId;
}) => () => void;
}
/**
* Stateful session helper provisioner separated from React so lifecycle
* transitions (initial setup, preferred-editor switching without re-injecting
* PATH, disconnect reset, and cancellation) can be tested deterministically.
*/
export function createExternalEditorSessionProvisioner(
deps: ExternalEditorSessionProvisionerDeps,
): ExternalEditorSessionProvisioner {
const scheduleTimer = deps.scheduleTimer ?? ((fn, ms) => setTimeout(fn, ms));
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
const pollIntervalMs = deps.pollIntervalMs ?? 100;
const maxPollAttempts = deps.maxPollAttempts ?? 60;
let trackedSessionId: string | null = null;
let provisionedEditors = new Set<ExternalEditorPresetId>();
let pathActivated = false;
const reset = () => {
trackedSessionId = null;
provisionedEditors = new Set();
pathActivated = false;
};
const sync = ({
sessionId,
defaultEditor,
}: {
sessionId: string;
defaultEditor: ExternalEditorPresetId;
}): (() => void) => {
if (trackedSessionId !== sessionId) {
trackedSessionId = sessionId;
provisionedEditors = new Set();
pathActivated = false;
}
if (provisionedEditors.has(defaultEditor) && pathActivated) {
return () => {};
}
let cancelled = false;
let pollTimer: ReturnType<typeof setTimeout> | null = null;
const setupCmd = buildExternalEditorAutoSetupCommand(defaultEditor);
void deps.setupExec(sessionId, setupCmd).then((result) => {
if (cancelled) return;
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
if (!result?.success) {
deps.onWarn?.(
'[Terminal] External editor session helper setup failed:',
result?.error || result?.stderr,
);
return;
}
provisionedEditors.add(defaultEditor);
const updated = typeof result.stdout === 'string'
&& result.stdout.includes(EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER);
// PATH is already active in this shell session (e.g. user changed preferred
// editor while connected); the new wrapper in ~/.netcatty/bin is immediately
// available without injecting another PATH command into the running terminal.
if (pathActivated) {
if (updated) {
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
}
return;
}
const shellKind = parseExternalEditorAutoSetupShell(result.stdout);
const activateCmd = buildExternalEditorSessionActivateCommand(shellKind);
let attempts = 0;
const tryActivateInSession = () => {
if (cancelled) return;
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
if (pathActivated) return;
if (deps.isReadyForCommandInjection()) {
pathActivated = true;
deps.writeToSession(sessionId, activateCmd, { automated: true });
if (updated) {
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
}
return;
}
attempts += 1;
if (attempts < maxPollAttempts) {
pollTimer = scheduleTimer(tryActivateInSession, pollIntervalMs);
}
};
tryActivateInSession();
}).catch((err) => {
if (cancelled) return;
deps.onWarn?.('[Terminal] External editor session helper setup error:', err);
});
return () => {
cancelled = true;
if (pollTimer !== null) {
clearTimer(pollTimer);
pollTimer = null;
}
};
};
return { reset, sync };
}
export interface UseTerminalExternalEditorOptions {
sessionId: string;
status: string;
host: Pick<
Host,
'id' | 'hostname' | 'port' | 'username' | 'label' | 'protocol' | 'externalEditorShellIntegration'
>;
isLocalConnection: boolean;
isSerialConnection: boolean;
getBackendSessionId: () => string | null;
isVisible: () => boolean;
getFallbackCwd: () => string | undefined;
isReadyForCommandInjection: () => boolean;
setupOsc7Tracking?: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
focusTerminal: () => void;
onOpened: (editorLabel: string, remotePath: string) => void;
onOpenFailed: (message: string) => void;
formatFallbackOpenError: (editorLabel: string) => string;
onAutoSetupConfigured: (editorLabel: string) => void;
}
export function useTerminalExternalEditor(options: UseTerminalExternalEditorOptions) {
const liveRef = useRef(options);
liveRef.current = options;
const {
sessionId,
status,
host,
isLocalConnection,
isSerialConnection,
} = options;
const hostProtocol = host.protocol || 'ssh';
const [pendingExternalEditorRequest, setPendingExternalEditorRequest] =
useState<PendingExternalEditorRequest | null>(null);
const pendingExternalEditorRequestRef = useRef(pendingExternalEditorRequest);
pendingExternalEditorRequestRef.current = pendingExternalEditorRequest;
const lastExternalEditorLaunchRef = useRef<{ key: string; at: number } | null>(null);
const executeExternalEditorLaunch = useCallback((req: PendingExternalEditorRequest) => {
const launchKey = `${req.editorId}:${req.kind}:${req.remotePath}`;
const now = Date.now();
const prev = lastExternalEditorLaunchRef.current;
if (prev && prev.key === launchKey && now - prev.at < 800) {
return;
}
lastExternalEditorLaunchRef.current = { key: launchKey, at: now };
const current = liveRef.current;
void launchRemoteExternalEditor({
editorId: req.editorId,
host: {
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
},
remotePath: req.remotePath,
kind: req.kind,
sessionId: current.getBackendSessionId() ?? current.sessionId,
}).then(() => {
liveRef.current.onOpened(req.editorLabel, req.remotePath);
}).catch((err) => {
liveRef.current.onOpenFailed(
err instanceof Error
? err.message
: liveRef.current.formatFallbackOpenError(req.editorLabel),
);
});
}, []);
const handleOscExternalEditorRequest = useCallback((request: ExternalEditorOscRequest) => {
const current = liveRef.current;
// Strictly scope OSC 7337 remote editor opens to live SSH sessions on visible tabs.
if (current.isLocalConnection || current.isSerialConnection) return;
if (!current.isVisible()) return;
if ((current.host.protocol || 'ssh') !== 'ssh') return;
const settings = getExternalEditorSettingsSnapshot();
if (!settings.terminalRequestsEnabled) return;
const fallbackCwd = current.getFallbackCwd();
const normalized = validateAndNormalizeRemotePath(request.path, fallbackCwd);
if (!normalized.ok) {
logger.warn(
'[Terminal] Rejected invalid OSC 7337 remote path:',
'error' in normalized ? normalized.error : 'invalid path',
);
return;
}
const editorId: ExternalEditorPresetId = request.editorId ?? settings.defaultEditor;
const editorLabel = getExternalEditorLabel(editorId);
const hostIdentity = {
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
};
const trust = resolveExternalEditorTrustPolicy(settings, hostIdentity);
if (trust === 'deny') {
logger.debug('[Terminal] Ignored OSC 7337 external editor request (host denied)');
return;
}
const launchPayload: PendingExternalEditorRequest = {
editorId,
editorLabel,
remotePath: normalized.path,
kind: request.kind,
};
if (trust === 'allow') {
executeExternalEditorLaunch(launchPayload);
return;
}
// Untrusted host: show explicit inline confirmation prompt (do not overwrite an active prompt).
setPendingExternalEditorRequest((prev) => prev ?? launchPayload);
}, [executeExternalEditorLaunch]);
const handleExternalEditorPromptResponse = useCallback((decision: 'deny' | 'once' | 'always') => {
const currentRequest = pendingExternalEditorRequestRef.current;
pendingExternalEditorRequestRef.current = null;
setPendingExternalEditorRequest(null);
if (currentRequest) {
const current = liveRef.current;
if (decision === 'always') {
setExternalEditorHostTrust({
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
}, 'allow');
executeExternalEditorLaunch(currentRequest);
} else if (decision === 'once') {
executeExternalEditorLaunch(currentRequest);
}
}
liveRef.current.focusTerminal();
}, [executeExternalEditorLaunch]);
// Session-scoped external editor shell commands: install standalone helpers into
// ~/.netcatty/bin over the silent exec channel (never modifying shell rc files)
// and prepend ~/.netcatty/bin to PATH once per connected terminal session.
const autoSetupConfig = useExternalEditorTerminalAutoSetupConfig();
const shouldEnableSessionCommands = shouldAutoSetupExternalEditorShell(
autoSetupConfig,
{ externalEditorShellIntegration: host.externalEditorShellIntegration },
);
const defaultExternalEditor = autoSetupConfig.defaultEditor;
const provisionerRef = useRef<ExternalEditorSessionProvisioner | null>(null);
if (!provisionerRef.current) {
provisionerRef.current = createExternalEditorSessionProvisioner({
setupExec: (activeSessionId, command) => {
const fn = liveRef.current.setupOsc7Tracking;
if (!fn) return Promise.resolve({ success: false, error: 'setupOsc7Tracking unavailable' });
return fn(activeSessionId, command);
},
writeToSession: (activeSessionId, data, opts) => {
liveRef.current.writeToSession(activeSessionId, data, opts);
},
getCurrentSessionId: () => liveRef.current.getBackendSessionId() ?? liveRef.current.sessionId,
isReadyForCommandInjection: () => liveRef.current.isReadyForCommandInjection(),
onConfigured: (editorLabel) => liveRef.current.onAutoSetupConfigured(editorLabel),
onWarn: (message, detail) => logger.warn(message, detail),
scheduleTimer: (fn, ms) => window.setTimeout(fn, ms) as unknown as ReturnType<typeof setTimeout>,
clearTimer: (handle) => window.clearTimeout(handle as unknown as number),
});
}
useEffect(() => {
const provisioner = provisionerRef.current;
if (!provisioner) return;
if (status !== 'connected') {
provisioner.reset();
return;
}
if (isLocalConnection || isSerialConnection) return;
if (hostProtocol !== 'ssh') return;
if (!shouldEnableSessionCommands) return;
if (!liveRef.current.setupOsc7Tracking) return;
const activeSessionId = liveRef.current.getBackendSessionId() ?? sessionId;
if (!activeSessionId) return;
return provisioner.sync({
sessionId: activeSessionId,
defaultEditor: defaultExternalEditor,
});
}, [
status,
isLocalConnection,
isSerialConnection,
hostProtocol,
shouldEnableSessionCommands,
defaultExternalEditor,
sessionId,
]);
return {
pendingExternalEditorRequest,
handleOscExternalEditorRequest,
handleExternalEditorPromptResponse,
};
}
+128 -1
View File
@@ -4,6 +4,8 @@ import { JSDOM } from 'jsdom';
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
@@ -30,9 +32,10 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
let model!: ReturnType<typeof useVaultNavConfig>;
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
let pluginsLoading = false;
let pluginsAvailable = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
return <div />;
}
@@ -83,6 +86,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
const coldRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
pluginsLoading = true;
pluginsAvailable = false;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -93,6 +97,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
// Plugins finish loading, but DB_PLUGIN was uninstalled.
activePluginIds = [MONITOR_PLUGIN];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -122,3 +127,125 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
dom.window.close();
}
});
test('useVaultNavConfig preserves saved plugin order when settled with pluginsAvailable=false and restores slots once plugins become available', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
});
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
configurable: true,
writable: true,
value: true,
});
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { useVaultNavConfig } = await import('./useVaultNavConfig');
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
let model!: ReturnType<typeof useVaultNavConfig>;
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
OFFICIAL_DB_PLUGIN,
OFFICIAL_MONITOR_PLUGIN,
];
let pluginsLoading = false;
let pluginsAvailable: boolean | undefined = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
return <div />;
}
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
await act(async () => {
model.reorder(OFFICIAL_MONITOR_PLUGIN, 'hosts', 'after');
model.setVisible('logs', false);
});
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.isHidden('logs'), true);
await act(async () => {
root.unmount();
});
const restartedRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
pluginsLoading = false;
pluginsAvailable = false;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
assert.equal(model.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN), false);
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(model.config.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), true);
const persistedUnavailable = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedUnavailable.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(persistedUnavailable.order.includes(OFFICIAL_DB_PLUGIN), true);
assert.deepEqual(persistedUnavailable.hidden, ['logs']);
pluginsAvailable = undefined;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
const persistedDefault = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedDefault.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(persistedDefault.order.includes(OFFICIAL_DB_PLUGIN), true);
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
assert.equal(model.isHidden('logs'), true);
await act(async () => {
restartedRoot.unmount();
});
} finally {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});
+4 -1
View File
@@ -28,6 +28,8 @@ export interface UseVaultNavConfigOptions {
activePluginIds: readonly PluginVaultNavId[];
/** Pass true while plugin contributions are still loading on cold start. */
pluginsLoading?: boolean;
/** Pass true once plugin contributions are available from the plugin runtime. */
pluginsAvailable?: boolean;
}
export interface UseVaultNavConfigResult {
@@ -76,13 +78,14 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
export function useVaultNavConfig({
activePluginIds,
pluginsLoading = false,
pluginsAvailable = false,
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
const pluginKey = activePluginIds.join('\0');
const stablePluginIds = useMemo<PluginVaultNavId[]>(
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
[pluginKey],
);
const pruneMissingPlugins = !pluginsLoading;
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
const [config, setConfig] = useState<VaultNavConfig>(() =>
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
@@ -440,3 +440,43 @@ test('changed remote transcript resets the local native SDK thread before contin
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
delete (window as unknown as { netcatty?: unknown }).netcatty;
});
test('cloud apply keeps receiver workspaceNameSnapshot when workspace binding is unchanged and drops it on rebind', async () => {
const local: AISession = {
...session(),
id: 'ws-chat',
scope: { type: 'workspace', targetId: 'ws-1', hostIds: ['h-1'] },
workspaceNameSnapshot: 'Prod Cluster (this Mac)',
updatedAt: 10,
};
save([local]);
// Never uploaded to cloud.
const uploaded = await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined });
assert.equal(Object.hasOwn(uploaded.aiSessions?.[0] ?? {}, 'workspaceNameSnapshot'), false);
// Newer remote update on the same workspace (stripped by remote device, or even
// carrying a foreign snapshot that must be stripped on apply) keeps local name.
const remoteSameWs: AISession = {
...local,
updatedAt: 20,
title: 'Updated title from peer',
workspaceNameSnapshot: 'Peer stale name',
};
await applySyncPayload({ ...vault, aiSessions: [remoteSameWs], syncedAt: 20 }, { importVaultData: () => undefined });
const afterSameWs = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
assert.equal(afterSameWs?.title, 'Updated title from peer');
assert.equal(afterSameWs?.workspaceNameSnapshot, 'Prod Cluster (this Mac)');
// Newer remote update that rebinds to another workspace drops the old local name.
const remoteRebound: AISession = {
...local,
updatedAt: 30,
scope: { type: 'workspace', targetId: 'ws-2', hostIds: ['h-2'] },
workspaceNameSnapshot: undefined,
};
await applySyncPayload({ ...vault, aiSessions: [remoteRebound], syncedAt: 30 }, { importVaultData: () => undefined });
const afterRebound = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
assert.equal(afterRebound?.scope.targetId, 'ws-2');
assert.equal(afterRebound?.workspaceNameSnapshot, undefined);
});
+14 -10
View File
@@ -2422,13 +2422,17 @@ test('sync prepares header encryption once before importing and leaves input unc
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");
});
for (const key of [
storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
storageKeys.STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
]) {
test(`SFTP download folder ${key} stays device-local and is never synced`, async () => {
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");
});
}
+277
View File
@@ -1,3 +1,265 @@
!ifndef BUILD_UNINSTALLER
Var /GLOBAL CreateDesktopShortcutPref
!endif
!macro customHeader
!ifndef BUILD_UNINSTALLER
!ifdef LANG_ENGLISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ENGLISH} "Create &desktop shortcut"
!endif
!ifdef LANG_SIMPCHINESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SIMPCHINESE} "创建桌面快捷方式(&D)"
!endif
!ifdef LANG_TRADCHINESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TRADCHINESE} "建立桌面捷徑(&D)"
!endif
!ifdef LANG_RUSSIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_RUSSIAN} "Создать ярлык на &рабочем столе"
!endif
!ifdef LANG_JAPANESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_JAPANESE} "デスクトップにショートカットを作成する(&D)"
!endif
!ifdef LANG_KOREAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_KOREAN} "바탕 화면에 바로 가기 만들기(&D)"
!endif
!ifdef LANG_GERMAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_GERMAN} "&Desktopverknüpfung erstellen"
!endif
!ifdef LANG_FRENCH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FRENCH} "Créer un raccourci sur le &bureau"
!endif
!ifdef LANG_SPANISHINTERNATIONAL
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SPANISHINTERNATIONAL} "Crear acceso directo en el &escritorio"
!endif
!ifdef LANG_ITALIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ITALIAN} "Crea collegamento sul &desktop"
!endif
!ifdef LANG_DUTCH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DUTCH} "&Bureaublad-snelkoppeling maken"
!endif
!ifdef LANG_DANISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DANISH} "Opret genvej på &skrivebordet"
!endif
!ifdef LANG_SWEDISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SWEDISH} "Skapa genväg på &skrivbordet"
!endif
!ifdef LANG_NORWEGIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_NORWEGIAN} "Opprett snarvei på &skrivebordet"
!endif
!ifdef LANG_FINNISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FINNISH} "Luo pikakuvake &työpöydälle"
!endif
!ifdef LANG_PORTUGUESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESE} "Criar atalho na &área de trabalho"
!endif
!ifdef LANG_PORTUGUESEBR
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESEBR} "Criar atalho na &Área de Trabalho"
!endif
!ifdef LANG_POLISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_POLISH} "Utwórz skrót na &pulpicie"
!endif
!ifdef LANG_UKRAINIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_UKRAINIAN} "Створити ярлик на &робочому столі"
!endif
!ifdef LANG_CZECH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_CZECH} "Vytvořit zástupce na &ploše"
!endif
!ifdef LANG_SLOVAK
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SLOVAK} "Vytvoriť odkaz na &ploche"
!endif
!ifdef LANG_HUNGARIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_HUNGARIAN} "Parancsikon létrehozása az &asztalon"
!endif
!ifdef LANG_ARABIC
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ARABIC} "إنشاء اختصار على سطح ال&مكتب"
!endif
!ifdef LANG_TURKISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TURKISH} "&Masaüstü kısayolu oluştur"
!endif
!ifdef LANG_THAI
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_THAI} "สร้างทางลัดบน&เดสก์ท็อป"
!endif
!ifdef LANG_VIETNAMESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_VIETNAMESE} "Tạo lối tắt trên &màn hình nền"
!endif
; Determine whether the desktop shortcut should be checked/created.
; Must run before uninstallOldVersion deletes the old registry key or shortcut.
Function CaptureDesktopShortcutState
${if} ${isNoDesktopShortcut}
StrCpy $CreateDesktopShortcutPref "false"
Return
${endif}
!insertmacro setLinkVars
ReadRegStr $0 SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
${if} $0 == "false"
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
Return
${endif}
ReadRegStr $1 SHCTX "${INSTALL_REGISTRY_KEY}" InstallLocation
${if} $1 != ""
; Existing install: only preserve the shortcut if it still exists on the desktop.
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
Return
${endif}
; Migrating from per-user to all-users: inspect the previous per-user desktop shortcut.
${if} $installMode == "all"
ReadRegStr $2 HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation
${if} $2 != ""
ReadRegStr $3 HKCU "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
SetShellVarContext current
!insertmacro setLinkVars
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${elseif} $3 == "false"
StrCpy $CreateDesktopShortcutPref "false"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
SetShellVarContext all
!insertmacro setLinkVars
Return
${endif}
${endif}
; Fresh installation: default to creating the desktop shortcut (user can uncheck on finish page).
StrCpy $CreateDesktopShortcutPref "true"
FunctionEnd
Function InstFilesShowCaptureDesktopShortcut
Call CaptureDesktopShortcutState
FunctionEnd
!endif
!macroend
!macro ensureDesktopShortcut
${if} $appExe == ""
StrCpy $appExe "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
${endif}
${if} $newDesktopLink == ""
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
${endif}
${if} $oldDesktopLink != ""
${andIf} $oldDesktopLink != $newDesktopLink
${andIf} ${FileExists} "$oldDesktopLink"
Rename "$oldDesktopLink" "$newDesktopLink"
WinShell::UninstShortcut "$oldDesktopLink"
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${elseIfNot} ${FileExists} "$newDesktopLink"
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
ClearErrors
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
!macroend
!macro removeDesktopShortcut
${if} $newDesktopLink == ""
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
${endif}
${if} ${FileExists} "$newDesktopLink"
WinShell::UninstShortcut "$newDesktopLink"
Delete "$newDesktopLink"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
${if} $oldDesktopLink != ""
${andIf} $oldDesktopLink != $newDesktopLink
${andIf} ${FileExists} "$oldDesktopLink"
WinShell::UninstShortcut "$oldDesktopLink"
Delete "$oldDesktopLink"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
!macroend
!macro customPageAfterChangeDir
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstFilesShowCaptureDesktopShortcut
!macroend
!macro customFinishPage
!ifndef HIDE_RUN_AFTER_FINISH
Function StartApp
${if} ${isUpdated}
StrCpy $1 "--updated"
${else}
StrCpy $1 ""
${endif}
${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "$1"
FunctionEnd
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_FUNCTION "StartApp"
!endif
!define MUI_FINISHPAGE_SHOWREADME ""
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(CREATE_DESKTOP_SHORTCUT_TEXT)"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION "FinishDesktopShortcutNoop"
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
!define MUI_PAGE_CUSTOMFUNCTION_SHOW FinishPageShow
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE FinishPageLeave
!insertmacro MUI_PAGE_FINISH
Function FinishPageShow
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${ifNot} ${RebootFlag}
!endif
${if} $CreateDesktopShortcutPref == "true"
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_CHECKED} 0
${else}
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_UNCHECKED} 0
${endif}
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${endif}
!endif
FunctionEnd
Function FinishPageLeave
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${if} ${RebootFlag}
${if} $CreateDesktopShortcutPref == "true"
!insertmacro ensureDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
${else}
!insertmacro removeDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
${endif}
Return
${endif}
!endif
SendMessage $mui.FinishPage.ShowReadme ${BM_GETCHECK} 0 0 $0
${if} $0 = ${BST_CHECKED}
StrCpy $CreateDesktopShortcutPref "true"
!insertmacro ensureDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
!insertmacro removeDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
${endif}
FunctionEnd
Function FinishDesktopShortcutNoop
FunctionEnd
!macroend
!macro customInit
; #3946: external MCP hosts launch Netcatty.exe with ELECTRON_RUN_AS_NODE=1
; via netcatty-external-mcp.cmd. Those processes can outlive the host UI as
@@ -7,9 +269,17 @@
; and /T would terminate the installer itself. Ignore a missing process.
nsExec::ExecToLog "taskkill /F /IM Netcatty.exe"
Pop $0
Call CaptureDesktopShortcutState
!macroend
!macro customInstall
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "$CreateDesktopShortcutPref"
${if} ${Silent}
${andIf} $CreateDesktopShortcutPref == "true"
${andIfNot} ${isNoDesktopShortcut}
!insertmacro ensureDesktopShortcut
${endif}
; Open a selected folder in a new Netcatty local terminal.
; Args go after `--` so Electron/Chromium does not swallow them. Use
; `--open-terminal-path="%1."` so paths with spaces stay one token and drive
@@ -50,6 +320,13 @@
!macroend
!macro customUnInstall
; DO_NOT_CREATE_DESKTOP_SHORTCUT is set so electron-builder never auto-creates
; the desktop shortcut; remove an existing shortcut here on real uninstall.
${ifNot} ${isKeepShortcuts}
WinShell::UninstShortcut "$oldDesktopLink"
Delete "$oldDesktopLink"
${endif}
DeleteRegKey SHCTX "Software\Classes\Directory\shell\Netcatty"
DeleteRegKey SHCTX "Software\Classes\Directory\Background\shell\Netcatty"
DeleteRegKey SHCTX "Software\Classes\Netcatty.SSH"
+3
View File
@@ -59,6 +59,7 @@ interface AIChatPanelContentProps {
activeCompaction?: import('../application/state/useAgentCompactionUi').ActiveCompactionUi | null;
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
inputValue: string;
inputValueRevision?: number;
setInputValue: (value: string) => void;
handleSend: (textOverride?: string) => void;
handleSendQuickPrompt?: (promptText: string) => void;
@@ -171,6 +172,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
activeCompaction = null,
contextUsage = null,
inputValue,
inputValueRevision,
setInputValue,
handleSend,
handleSendQuickPrompt,
@@ -568,6 +570,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<ChatInput
parked={parked}
value={inputValue}
valueRevision={inputValueRevision}
onChange={setInputValue}
onSend={handleSend}
onSendQuickPrompt={handleSendQuickPrompt}
+49 -4
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import type { AISession } from '../infrastructure/ai/types';
import { useI18n } from '../application/i18n/I18nProvider';
import { cn } from '../lib/utils';
@@ -9,6 +9,7 @@ import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
// -------------------------------------------------------------------
@@ -52,6 +53,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
const { t } = useI18n();
const [view, setView] = useState<'scoped' | 'global'>('scoped');
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
const [searchQuery, setSearchQuery] = useState('');
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
@@ -70,6 +72,22 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
setRenderCount(SESSION_RENDER_BATCH);
}, [sessions, searchQuery]);
useEffect(() => {
if (view !== 'global' || !globalManager) {
setGlobalSelectionMode(false);
}
}, [view, globalManager]);
const selectionContextValue = useMemo(
() => ({
selectionMode: globalSelectionMode,
setSelectionMode: setGlobalSelectionMode,
}),
[globalSelectionMode],
);
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
const displayedSessions = filteredSessions.slice(0, renderCount);
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
@@ -132,7 +150,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
</div>
<div className="flex items-center gap-2">
{(onImportSessions || onExportSessions) && (
{hasHeaderMenu && (
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
<DropdownTrigger asChild>
<button
@@ -144,6 +162,31 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</button>
</DropdownTrigger>
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
{canSelectGlobalChats && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setHeaderMenuOpen(false);
setGlobalSelectionMode((prev) => !prev);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<CheckSquare
size={12}
className={cn(
'shrink-0',
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
)}
/>
<span>{t('ai.chat.managerToggleSelection')}</span>
</button>
{(onImportSessions || onExportSessions) && (
<div className="my-1 h-px bg-border/50" />
)}
</>
)}
{onImportSessions && (
<button
type="button"
@@ -184,7 +227,9 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</div>
</div>
{view === 'global' && globalManager ? (
globalManager
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
{globalManager}
</GlobalSessionSelectionContext.Provider>
) : (
<>
<div className="px-3 py-2 shrink-0 border-b border-border/30">
+62 -33
View File
@@ -14,6 +14,11 @@ import type {
ExternalAgentConfig,
} from '../infrastructure/ai/types';
import type { VaultNote } from '../domain/models';
import {
buildFallbackTitle,
canAutoTitleSession,
resolveCattyEffectiveModel,
} from '../domain/aiSessionTitle';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import {
DEFAULT_MAX_ITERATIONS,
@@ -294,6 +299,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
undoLastTurnInSession,
deleteSession,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -823,8 +830,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
showSessionView(scopeKey, sessionId);
}, [scopeKey, showSessionView]);
const [composerValueRevision, setComposerValueRevision] = useState(0);
const discardPendingComposerText = useCallback(() => {
pendingComposerTextRef.current = null;
if (currentDraftRef.current) {
currentDraftRef.current = { ...currentDraftRef.current, text: '' };
}
setComposerValueRevision((rev) => rev + 1);
}, []);
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
@@ -1038,26 +1051,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
[providers, activeProviderId],
);
const cattyAgentProvider = useMemo(() => {
const overrideId = agentProviderMap['catty'];
if (overrideId) {
const p = providers.find((cfg) => cfg.id === overrideId);
if (p) return p;
}
return activeProvider;
}, [agentProviderMap, providers, activeProvider]);
const cattyAgentModelId = useMemo(() => {
const trim = (s: string | undefined | null): string => (s ?? '').trim();
const overrideId = agentProviderMap['catty'];
const overrideProvider = overrideId
? providers.find((cfg) => cfg.id === overrideId)
: undefined;
if (overrideProvider) {
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
}
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
const { provider: cattyAgentProvider, modelId: cattyAgentModelId } = useMemo(
() => resolveCattyEffectiveModel({
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
}),
[providers, activeProviderId, activeModelId, agentProviderMap, agentModelMap],
);
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
@@ -1680,18 +1683,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}, [openSettingsWindow]);
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
/** Ref to always access latest sessions inside async send callbacks. */
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
/** Auto-title a session from the first user message if untitled. */
const autoTitleSession = useCallback((sessionId: string, text: string) => {
const s = sessionsRef.current.find(x => x.id === sessionId);
if (s && (!s.title || s.title === 'New Chat')) {
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
}
}, [updateSessionTitle]);
const buildExecutorContextForScope = useCallback((scope: {
type: 'terminal' | 'workspace' | 'global';
targetId?: string;
@@ -1875,7 +1870,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
let currentSession = currentSessionView ?? null;
if (isDraftMode) {
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
const createdSession = createSession(scope, sendAgentId);
const createdSession = createSession(scope, sendAgentId, scopeLabel);
sessionId = createdSession.id;
currentSession = createdSession;
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
@@ -1983,7 +1978,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
setStreamingForScope(sessionId, false);
abortControllersRef.current.delete(sessionId);
autoTitleSession(sessionId, titleText);
} else {
const toolScope = {
type: scopeType,
@@ -2005,12 +1999,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
terminalSessions,
webSearchConfig,
getExecutorContext: () => buildExecutorContextForScope(toolScope),
autoTitleSession,
// Title generation is triggered once, below, for both agent branches.
autoTitleSession: () => {},
selectedUserSkillSlugs: selectedSkillSlugs,
titleText,
pluginContext,
}, modelAttachments.length > 0 ? modelAttachments : undefined);
}
// Single title-generation trigger for both agent branches. Pass the
// signal explicitly: sendToCattyAgent's finally removes its controller.
if (autoTitleSession) {
void autoTitleSession(sessionId, titleText, abortController.signal);
} else {
const current = sessionsRef.current.find((s) => s.id === sessionId);
if (canAutoTitleSession(current)) {
updateSessionTitle(sessionId, buildFallbackTitle(titleText));
}
}
} finally {
setIsSending(false);
endSendForKey(sendGateKey);
@@ -2022,7 +2027,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
validateNoteMentions, loadCodexConfigModel,
isStreaming, isUndoingLastTurn, activeProvider, effectiveActiveProvider, effectiveActiveModelId, selectedCattyThinking, scopeKey, currentAgentId,
activeModelId, externalAgents,
createSession, addMessageToSession, updateMessageById, updateLastMessage,
createSession, addMessageToSession, updateMessageById, updateLastMessage, updateSessionTitle,
setStreamingForScope,
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
@@ -2430,6 +2435,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
deleteSession(sessionId);
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
// Regeneration lives in useAIState so it can reuse the maintainer's
// title-model resolution and atomic title-write helpers.
const handleManagerRegenerateTitle = useCallback((sessionId: string) => {
void regenerateSessionTitle?.(sessionId);
}, [regenerateSessionTitle]);
const handleManagerDeleteMany = useCallback(async (sessionIds: string[]) => {
for (const sessionId of sessionIds) {
if (abortControllersRef.current.has(sessionId) || streamingSessionIds.has(sessionId)) {
await stopStreamingForSession(sessionId);
}
// Each delete records an intentional tombstone so sync can propagate
// the removal (the "decrease" side of session-history sync).
deleteSession(sessionId);
}
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
const handleManagerExport = useCallback((sessionId: string) => {
void exportSessionsBackup?.([sessionId]).then((filePath) => {
if (filePath == null) {
@@ -2464,6 +2486,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onRebind={handleManagerRebind}
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
onExport={handleManagerExport}
/>
)
@@ -2483,6 +2507,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
handleManagerRebind,
handleRenameSession,
handleManagerDelete,
handleManagerDeleteMany,
handleManagerRegenerateTitle,
handleManagerExport,
onFocusAIScopeTarget,
]);
@@ -2556,6 +2582,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
contextUsage={contextUsage}
canCompact={canCompact}
inputValue={inputValue}
inputValueRevision={composerValueRevision}
setInputValue={setInputValue}
handleSend={handleSend}
handleSendQuickPrompt={handleSendQuickPrompt}
@@ -2666,6 +2693,8 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
'createSession',
'deleteSession',
'updateSessionTitle',
'autoTitleSession',
'regenerateSessionTitle',
'rebindSessionScope',
'exportSessionsBackup',
'importSessionsBackup',
+4 -1
View File
@@ -36,7 +36,7 @@ export interface AIChatSidePanelProps {
clearDraftForScope: (scopeKey: string) => void;
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
createSession: (scope: AISessionScope, agentId?: string) => AISession;
createSession: (scope: AISessionScope, agentId?: string, workspaceNameSnapshot?: string) => AISession;
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
undoLastTurnInSession?: (
sessionId: string,
@@ -44,6 +44,9 @@ export interface AIChatSidePanelProps {
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
deleteSession: (sessionId: string, scopeKey?: string) => void;
updateSessionTitle: (sessionId: string, title: string) => void;
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
/** Explicitly regenerate an existing chat title with the configured LLM. */
regenerateSessionTitle?: (sessionId: string) => void | Promise<void>;
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
+7 -3
View File
@@ -690,11 +690,15 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
if (!ensureSyncablePayload(payload)) return;
const result = await sync.syncToProvider(provider, payload, {
applyConvergentPayload: onApplyConvergentPayload,
// A per-provider button must sync only that provider: skip the
// convergent fan-out even when convergent mode is active.
// Auto-sync / top-bar Sync Now still use syncAllProviders.
forceSingleProvider: true,
});
// Convergent sync fans out to every provider. Even if the
// requested provider fails, another provider can verify a newer
// joined replica that must be applied before reporting the error.
// The selected provider may still carry a newer joined replica
// (e.g. written by another device); apply it locally before
// reporting the result. This is per-provider only now.
if (result.mergedPayload && !result.mergedPayloadApplied && onApplyPayload) {
const portableMerged = stripSyncPayloadEncryptedCredentials(result.mergedPayload);
await Promise.resolve(onApplyPayload(portableMerged));
@@ -4,6 +4,7 @@ import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
import React from "react";
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
import { customThemeStore } from "../application/state/customThemeStore";
import { useExternalEditorSettings } from "../application/state/useExternalEditorSettings";
import { clearHostFontSizeOverride, clearHostThemeOverride } from "../domain/terminalAppearance";
import { resolveSshAgentToggleUpdate } from "../domain/sshAuth";
import { MAX_FONT_SIZE, MIN_FONT_SIZE } from "../infrastructure/config/fonts";
@@ -67,6 +68,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxyInherited = false,
clearProxyConfig,
}) => {
const { settings: externalEditorSettings } = useExternalEditorSettings();
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
@@ -550,6 +552,39 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{isSshView && (
<HostDetailsSettingRow
label={t("hostDetails.externalEditorShellIntegration")}
hint={t("hostDetails.externalEditorShellIntegration.desc")}
>
<Select
value={
form.externalEditorShellIntegration === true
? "enabled"
: form.externalEditorShellIntegration === false
? "disabled"
: "default"
}
onValueChange={(v) =>
update(
"externalEditorShellIntegration",
v === "enabled" ? true : v === "disabled" ? false : undefined,
)
}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
{`${t("hostDetails.backspaceBehavior.default")} (${externalEditorSettings.autoSetupShellIntegration ? t("common.enabled") : t("common.disabled")})`}
</SelectItem>
<SelectItem value="enabled">{t("common.enabled")}</SelectItem>
<SelectItem value="disabled">{t("common.disabled")}</SelectItem>
</SelectContent>
</Select>
</HostDetailsSettingRow>
)}
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
<>
<ToggleRow
+37 -8
View File
@@ -2,6 +2,11 @@ import React from "react";
import { ChevronRight, Info } from "lucide-react";
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
import { sanitizeCredentialValue } from "../domain/credentials";
import {
getExportablePublicKey,
hasExportablePublicKey,
isKeychainExportDisabled,
} from "../domain/keychainExport";
import { hasBridgeSshCredentials, resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../domain/sshAuth";
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
import { connectionTotpFields } from "../domain/totpConfig";
@@ -41,6 +46,15 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
onSaveHost,
closePanel,
}) => {
const hasPublicKey = hasExportablePublicKey(panel.key?.publicKey);
const exportDisabled = isKeychainExportDisabled({
exportHost,
exportLocation,
exportFilename,
publicKey: panel.key?.publicKey,
isExporting,
});
return (
<>
{/* Key info card */}
@@ -159,17 +173,32 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
</CollapsibleContent>
</Collapsible>
{!hasPublicKey && (
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
<Info
size={14}
className="mt-0.5 text-muted-foreground shrink-0"
/>
<p className="text-xs text-muted-foreground">
{t("keychain.export.missingPublicKeyNote")}
</p>
</div>
)}
{/* Export button */}
<Button
className="w-full h-11"
disabled={
!exportHost ||
!exportLocation ||
!exportFilename ||
isExporting
}
disabled={exportDisabled}
onClick={async () => {
if (!exportHost || !panel.key.publicKey) return;
if (!exportHost) return;
const publicKey = getExportablePublicKey(panel.key?.publicKey);
if (!publicKey) {
toast.error(
t("keychain.export.missingPublicKey"),
t("keychain.export.failedTitle"),
);
return;
}
setIsExporting(true);
@@ -216,7 +245,7 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
}
// Escape the public key for shell (single quotes, escape existing quotes)
const escapedPublicKey = panel.key.publicKey.replace(
const escapedPublicKey = publicKey.replace(
/'/g,
"'\\''",
);
+8
View File
@@ -258,6 +258,12 @@ const SettingsAITabContainer: React.FC = () => {
setQuickMessages={aiState.setQuickMessages}
showTerminalSelectionAIAction={aiState.showTerminalSelectionAIAction}
setShowTerminalSelectionAIAction={aiState.setShowTerminalSelectionAIAction}
autoLlmTitle={aiState.autoLlmTitle}
setAutoLlmTitle={aiState.setAutoLlmTitle}
titleModel={aiState.titleModel}
setTitleModel={aiState.setTitleModel}
agentProviderMap={aiState.agentProviderMap}
agentModelMap={aiState.agentModelMap}
/>
</AITabErrorBoundary>
);
@@ -581,6 +587,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
setShowSftpTab={settings.setShowSftpTab}
showHostTreeSidebar={settings.showHostTreeSidebar}
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
removeTopTabsDragArea={settings.removeTopTabsDragArea}
setRemoveTopTabsDragArea={settings.setRemoveTopTabsDragArea}
windowOpacity={settings.windowOpacity}
setWindowOpacity={settings.setWindowOpacity}
windowBackgroundBlur={settings.windowBackgroundBlur}
+30 -2
View File
@@ -1,4 +1,5 @@
import { terminalCwdStore } from '../application/state/terminalCwdStore';
import { useTerminalExternalEditor } from '../application/state/useTerminalExternalEditor';
import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession';
import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
@@ -1411,6 +1412,32 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const osc52ReadResolverRef = useRef<((allowed: boolean) => void) | null>(null);
const [osc7SetupOpen, setOsc7SetupOpen] = useState(false);
const [osc7SetupRunning, setOsc7SetupRunning] = useState(false);
const {
pendingExternalEditorRequest,
handleOscExternalEditorRequest,
handleExternalEditorPromptResponse,
} = useTerminalExternalEditor({
sessionId,
status,
host,
isLocalConnection,
isSerialConnection,
getBackendSessionId: () => sessionRef.current ?? sessionId,
isVisible: () => isVisibleRef.current,
getFallbackCwd: () => terminalCwdTracker.getRendererCwd() ?? knownCwdRef.current ?? undefined,
isReadyForCommandInjection: () => isTerminalReadyForCommandInjection(sessionId),
setupOsc7Tracking: terminalBackend.setupOsc7Tracking,
writeToSession: terminalBackend.writeToSession,
focusTerminal: () => termRef.current?.focus(),
onOpened: (editor, path) =>
toast.success(t("terminal.externalEditor.opened", { editor, path })),
onOpenFailed: (message) => toast.error(message),
formatFallbackOpenError: (editor) =>
t("terminal.externalEditor.failed", { editor }),
onAutoSetupConfigured: (editor) =>
toast.success(t("terminal.externalEditor.autoSetupConfigured", { editor })),
});
const handleOsc52ReadRequest = useCallback((): Promise<boolean> => {
// Reject if terminal is not visible (background tab) — user can't see the prompt
if (!isVisibleRef.current) return Promise.resolve(false);
@@ -4812,6 +4839,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
});
},
onOsc52ReadRequest: handleOsc52ReadRequest,
onOscExternalEditorRequest: handleOscExternalEditorRequest,
onAutocompleteKeyEvent: (e: KeyboardEvent) => autocompleteKeyEventRef.current?.(e) ?? true,
onAutocompleteInput: (data: string) => autocompleteInputRef.current?.(data),
onAutocompleteReposition: () => autocompleteRepositionRef.current?.(),
@@ -5078,11 +5106,11 @@ const TerminalComponent: React.FC<TerminalProps> = ({
onWake: wakeFromHibernateRuntime,
});
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleOscExternalEditorRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
return (
<>
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleExternalEditorPromptResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, pendingExternalEditorRequest, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
<ScriptExecutionOverlay
run={activeScriptRun}
onPause={() => { void pauseScriptRun(activeScriptRun.runId); }}
+3
View File
@@ -1497,6 +1497,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!shouldProbeCommandCwd({
restoreTerminalCwd,
visibleSftpHost,
latestVisibleSftpHost: visibleSftpHost
? hostsRef.current.find((host) => host.id === visibleSftpHost.id)
: undefined,
sessionHost,
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
+10 -2
View File
@@ -217,6 +217,7 @@ interface TopTabsProps {
tabInsertionTarget?: { tabId: string; position: 'before' | 'after'; additionalTabIds?: readonly string[] },
) => void;
onAppendHostToWorkspace?: (workspaceId: string, hostId: string) => void;
onRequestAddToWorkspace?: (workspaceId: string) => void;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
switchTabKeyBinding: Pick<KeyBinding, 'mac' | 'pc'> | null;
@@ -270,6 +271,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
onReorderTabs,
onRemoveSessionFromWorkspace,
onAppendHostToWorkspace,
onRequestAddToWorkspace,
showSftpTab,
showHostTreeSidebar,
switchTabKeyBinding,
@@ -288,6 +290,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
const {
hotkeyScheme,
showTabNumberBadges,
removeTopTabsDragArea,
shellOnlyTabNumberShortcuts,
} = useSettingsChromeStore();
const switchTabKey = hotkeyScheme === 'mac'
@@ -1031,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
onTabDrop={handleTabDrop}
onRenameWorkspace={onRenameWorkspace}
onCopyWorkspace={onCopyWorkspace}
onRequestAddToWorkspace={onRequestAddToWorkspace}
onCloseWorkspace={onCloseWorkspace}
onDetachSessionFromWorkspace={handleDetachSessionFromWorkspace}
renderBulkCloseItems={renderBulkCloseItems}
@@ -1087,6 +1091,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
<div
data-top-tabs-root
data-section="top-tabs"
data-remove-top-tabs-drag-area={removeTopTabsDragArea ? 'true' : undefined}
className="relative w-full bg-secondary app-drag"
style={{
...dragRegionNoSelect,
@@ -1099,9 +1104,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
tabsContainerRef={tabsContainerRef}
updateScrollState={updateScrollState}
/>
{/* Always-on drag stripe so the window can be moved even when tabs fill the bar */}
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
{!removeTopTabsDragArea && (
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
)}
<div
data-section="top-tabs-toolbar-row"
className="h-9 flex items-end gap-0 app-drag overflow-visible"
style={{
...dragRegionStyle,
@@ -1387,6 +1394,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
prev.onEditHost === next.onEditHost &&
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
prev.onRequestAddToWorkspace === next.onRequestAddToWorkspace &&
prev.onCopyWorkspace === next.onCopyWorkspace &&
prev.onOpenSettings === next.onOpenSettings &&
prev.onLockApp === next.onLockApp &&
+1
View File
@@ -394,6 +394,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
const vaultNavConfig = useVaultNavConfig({
activePluginIds: activePluginNavIds,
pluginsLoading: pluginVault.contributions.loading,
pluginsAvailable: pluginVault.contributions.available,
});
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
useEffect(() => {
+14
View File
@@ -412,3 +412,17 @@ test('renders vault note attachment chips with the note title', () => {
assert.match(source, /file\.vaultNoteId \? \(/);
assert.match(source, /\{file\.vaultNoteTitle \|\| file\.filename\}/);
});
test('valueRevision clears the uncontrolled textarea even when value stays empty across renders', () => {
const chatInputSource = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8');
const sidePanelSource = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
const contentSource = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
assert.match(chatInputSource, /valueRevision\?: number/);
assert.match(chatInputSource, /prev\.valueRevision === next\.valueRevision/);
assert.match(chatInputSource, /const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
assert.match(chatInputSource, /if \(!revisionChanged && value === pushedParentTextRef\.current\) return/);
assert.match(sidePanelSource, /setComposerValueRevision\(\(rev\) => rev \+ 1\)/);
assert.match(sidePanelSource, /inputValueRevision=\{composerValueRevision\}/);
assert.match(contentSource, /valueRevision=\{inputValueRevision\}/);
});
+13 -2
View File
@@ -207,6 +207,12 @@ const ComposerSendUi = React.memo(function ComposerSendUi({
interface ChatInputProps {
value: string;
/**
* Monotonic revision bumped by the parent whenever an authoritative reset
* (e.g. post-send draft clear) must be applied to the uncontrolled textarea
* even when `value` stayed equal across renders (such as `""` -> `""`).
*/
valueRevision?: number;
onChange: (value: string) => void;
onSend: (textOverride?: string) => void;
onCompact?: () => void;
@@ -303,6 +309,7 @@ interface ChatInputProps {
const ChatInput: React.FC<ChatInputProps> = ({
value,
valueRevision = 0,
onChange,
onSend,
onCompact,
@@ -548,15 +555,18 @@ const ChatInput: React.FC<ChatInputProps> = ({
textareaRef.current?.value ?? composerTextRef.current
), []);
const lastValueRevisionRef = useRef(valueRevision);
useEffect(() => {
if (value === pushedParentTextRef.current) return;
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
lastValueRevisionRef.current = valueRevision;
if (!revisionChanged && value === pushedParentTextRef.current) return;
pushedParentTextRef.current = value;
composerTextRef.current = value;
if (textareaRef.current && textareaRef.current.value !== value) {
textareaRef.current.value = value;
}
syncHasComposerText(value);
}, [syncHasComposerText, value]);
}, [syncHasComposerText, value, valueRevision]);
const commitComposerText = useCallback((next: string) => {
composerTextRef.current = next;
@@ -1977,6 +1987,7 @@ function contextUsageEqual(
function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boolean {
return (
prev.value === next.value
&& prev.valueRevision === next.valueRevision
&& prev.onChange === next.onChange
&& prev.onSend === next.onSend
&& prev.onCompact === next.onCompact
@@ -52,6 +52,8 @@ function baseProps() {
onRebind: (_sessionId: string, _target: { type: string; targetId: string; hostIds?: string[] }) => {},
onRename: undefined as ((_sessionId: string, _title: string) => void) | undefined,
onDelete: (_sessionId: string) => {},
onDeleteMany: undefined as ((_ids: string[]) => void) | undefined,
onRegenerateTitle: undefined as ((_sessionId: string) => void) | undefined,
onExport: (_sessionId: string) => {},
};
}
@@ -542,3 +544,185 @@ test("clicking an active-elsewhere chat falls back to opening locally when focus
dom.cleanup();
}
});
test("subtitle styling keeps agent label emphasized and message count normal when scopeLabel is empty", async () => {
const dom = installDomEnvironment();
try {
const props = baseProps();
props.sessions = [
makeSession({ id: "no-scope-label", title: "Orphan chat", scope: { type: "terminal", targetId: "t-gone" } }),
];
const renderer = await renderManager(dom, props);
const row = rows(renderer)[0];
const spans = Array.from(row.querySelectorAll("span")).filter((el) => !el.getAttribute("aria-hidden"));
const agentSpan = spans.find((el) => el.textContent === "Catty Agent");
const countSpan = spans.find((el) => (el.textContent ?? "").includes("1"));
assert.ok(agentSpan?.className.includes("font-medium"));
assert.ok(!agentSpan?.className.includes("truncate"));
assert.ok(countSpan);
assert.ok(!countSpan.className.includes("font-medium"));
} finally {
dom.cleanup();
}
});
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
const dom = installDomEnvironment();
const restoreGlobals = installRadixGlobals(dom);
try {
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const renderer = await createDomRenderer(dom.document);
const props = baseProps();
props.sessions = [
makeSession({ id: "s-a", title: "A" }),
makeSession({ id: "s-b", title: "B" }),
];
const deletedMany: string[][] = [];
const regenerated: string[] = [];
const activated: string[] = [];
props.onDeleteMany = (ids) => deletedMany.push(ids);
props.onRegenerateTitle = (id) => regenerated.push(id);
props.onSelect = (id) => activated.push(id);
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<SessionHistoryDrawer
sessions={props.sessions}
activeSessionId="s-a"
onSelect={() => {}}
onDelete={() => {}}
onExportSessions={() => {}}
onClose={() => {}}
globalManager={<GlobalAIChatSessionManager {...props} />}
/>
</TooltipProvider>
</I18nProvider>,
);
const openHeaderMenu = async () => {
const trigger = renderer.container.querySelector<HTMLButtonElement>(
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
);
assert.ok(trigger, "drawer overflow trigger present");
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
};
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
await openHeaderMenu();
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
// Close header menu before switching tabs.
await openHeaderMenu();
// Switch to the "All chats" tab.
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
// Search/filter bar must not contain an inline selection toggle button.
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
null,
"no standalone selection button in filter bar",
);
// Trigger selection mode from the drawer's top-right overflow menu.
await openHeaderMenu();
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.ok(selectItem, "Select chats menu item present on All chats tab");
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection action bar opens",
);
// Clicking Cancel exits selection mode cleanly.
const cancelBtn = Array.from(
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.trim() === t("common.cancel"));
assert.ok(cancelBtn, "Cancel button present in selection bar");
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Cancel exits selection mode",
);
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
await openHeaderMenu();
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Escape exits selection mode",
);
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
await openHeaderMenu();
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection bar open before tab switch",
);
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"switching away from All chats resets selection mode",
);
await openHeaderMenu();
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
assert.deepEqual(activated, []);
const bulkRegen = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
assert.ok(bulkRegen, "bulk regenerate button present");
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
// Bulk delete is confirm-gated.
const bulkDelete = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("common.delete")));
assert.ok(bulkDelete, "bulk delete button present");
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"selection mode exits after confirmed bulk delete",
);
} finally {
restoreGlobals();
dom.cleanup();
}
});
+268 -61
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Download, FolderInput, MoreHorizontal, Pencil, Search, Trash2, X } from 'lucide-react';
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
import { useI18n } from '../../application/i18n/I18nProvider';
import { cn } from '../../lib/utils';
@@ -15,6 +15,7 @@ import {
} from '../ui/select';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
import {
buildGlobalManagerRows,
@@ -56,7 +57,13 @@ interface GlobalAIChatSessionManagerProps {
onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void;
onRename?: (sessionId: string, title: string) => void;
onDelete: (sessionId: string) => void;
onDeleteMany?: (sessionIds: string[]) => void;
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
onRegenerateTitle?: (sessionId: string) => void;
onExport: (sessionId: string) => void;
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
selectionMode?: boolean;
onSelectionModeChange?: (active: boolean) => void;
}
const MANAGER_RENDER_BATCH = 80;
@@ -78,19 +85,44 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
onRebind,
onRename,
onDelete,
onDeleteMany,
onRegenerateTitle,
onExport,
selectionMode: controlledSelectionMode,
onSelectionModeChange,
}) => {
const { t } = useI18n();
const selectionContext = useContext(GlobalSessionSelectionContext);
const [searchQuery, setSearchQuery] = useState('');
const [agentFilter, setAgentFilter] = useState<string>('all');
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
const [moveSession, setMoveSession] = useState<AISession | null>(null);
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [renameDraft, setRenameDraft] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
const selectionMode =
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
const setSelectionMode = useCallback(
(active: boolean) => {
if (controlledSelectionMode !== undefined) {
onSelectionModeChange?.(active);
} else if (selectionContext) {
selectionContext.setSelectionMode(active);
onSelectionModeChange?.(active);
} else {
setUncontrolledSelectionMode(active);
onSelectionModeChange?.(active);
}
},
[controlledSelectionMode, onSelectionModeChange, selectionContext],
);
const rows = useMemo(
() => buildGlobalManagerRows({
sessions,
@@ -129,6 +161,26 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
if (renamingSessionId) renameInputRef.current?.focus();
}, [renamingSessionId]);
useEffect(() => {
if (!selectionMode) {
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}
}, [selectionMode]);
const rowSessionIds = useMemo(
() => new Set(rows.map((row) => row.session.id)),
[rows],
);
const activeSelectedIds = useMemo(() => {
if (selectedIds.size === 0) return selectedIds;
const next = new Set<string>();
selectedIds.forEach((id) => {
if (rowSessionIds.has(id)) next.add(id);
});
return next;
}, [selectedIds, rowSessionIds]);
const displayedRows = filteredRows.slice(0, renderCount);
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
@@ -152,6 +204,50 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
setRenameDraft('');
};
const toggleSelected = (sessionId: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(sessionId)) next.delete(sessionId); else next.add(sessionId);
return next;
});
};
const exitSelectionMode = useCallback(() => {
setSelectionMode(false);
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}, [setSelectionMode]);
useEffect(() => {
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
exitSelectionMode();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
const toggleSelectAll = () => {
const visibleIds = displayedRows.map((row) => row.session.id);
setSelectedIds((prev) => {
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => prev.has(id));
return allSelected ? new Set() : new Set(visibleIds);
});
};
const commitBulkDelete = () => {
if (activeSelectedIds.size === 0) return;
const ids = [...activeSelectedIds];
if (onDeleteMany) onDeleteMany(ids);
else ids.forEach((id) => onDelete(id));
exitSelectionMode();
};
const commitBulkRegenerate = () => {
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
};
const getOtherMoveTargets = (session: AISession) =>
rebindTargets.filter(
(target) =>
@@ -236,6 +332,54 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</Select>
)}
</div>
{selectionMode && (
<div
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
data-section="ai-global-session-selection-bar"
>
<button
type="button"
onClick={toggleSelectAll}
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
>
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
{t('ai.chat.managerSelectAll')}
</button>
<span className="text-muted-foreground/60 whitespace-nowrap">
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
</span>
<div className="ml-auto flex items-center gap-1">
{onRegenerateTitle && (
<button
type="button"
disabled={activeSelectedIds.size === 0}
onClick={commitBulkRegenerate}
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<RefreshCw size={12} />
{t('ai.chat.managerRegenerateTitle')}
</button>
)}
<button
type="button"
disabled={activeSelectedIds.size === 0}
onClick={() => setBulkDeleteConfirmOpen(true)}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<Trash2 size={12} />
{t('common.delete')}
</button>
<button
type="button"
onClick={exitSelectionMode}
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
>
{t('common.cancel')}
</button>
</div>
</div>
)}
<ScrollArea className="flex-1">
<div className="px-3">
{filteredRows.length === 0 ? (
@@ -260,28 +404,43 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
const canMoveElsewhere = otherMoveTargets.length > 0;
const isRenaming = renamingSessionId === row.session.id;
const isMenuOpen = openMenuSessionId === row.session.id;
const subtitleParts: string[] = [];
if (row.scopeLabel) subtitleParts.push(row.scopeLabel);
if (showAgentMeta) subtitleParts.push(row.agentLabel);
const subtitleParts: Array<{ text: string; bold: boolean; truncate: boolean }> = [];
if (row.scopeLabel) {
subtitleParts.push({ text: row.scopeLabel, bold: true, truncate: true });
}
subtitleParts.push({ text: row.agentLabel, bold: true, truncate: false });
if (row.messageCount > 0) {
subtitleParts.push(
t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
);
subtitleParts.push({
text: t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
bold: false,
truncate: false,
});
}
return (
<React.Fragment key={row.session.id}>
<div
role="button"
tabIndex={row.canActivate ? 0 : -1}
tabIndex={selectionMode || row.canActivate ? 0 : -1}
onClick={() => {
if (selectionMode) {
toggleSelected(row.session.id);
return;
}
if (!isRenaming && row.canActivate) activateRow(row);
}}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (!isRenaming && row.canActivate && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
activateRow(row);
if (e.key === 'Enter' || e.key === ' ') {
if (selectionMode) {
e.preventDefault();
toggleSelected(row.session.id);
return;
}
if (!isRenaming && row.canActivate) {
e.preventDefault();
activateRow(row);
}
}
}}
className={cn(
@@ -289,69 +448,91 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
row.isCurrentActive
? 'text-foreground'
: 'text-foreground/75 hover:text-foreground',
!row.canActivate && 'cursor-default',
!selectionMode && !row.canActivate && 'cursor-default',
)}
data-session-id={row.session.id}
data-scope-state={row.scopeState}
>
<div className="min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
)}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
{selectionMode && (
<button
type="button"
aria-label={t('ai.chat.managerSelectRow')}
aria-pressed={activeSelectedIds.has(row.session.id)}
onClick={(e) => {
e.stopPropagation();
toggleSelected(row.session.id);
}}
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
>
{activeSelectedIds.has(row.session.id)
? <CheckSquare size={14} className="text-primary" />
: <Square size={14} />}
</button>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
</span>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/50 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={index === 0 ? 'truncate' : 'shrink-0'}>
{part}
</span>
</React.Fragment>
))}
</div>
)}
</div>
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
{formatRelativeTime(new Date(row.session.updatedAt), t)}
</span>
{!selectionMode && (
<Dropdown
open={isMenuOpen}
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
@@ -387,6 +568,20 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
<span>{t('ai.chat.renameChat')}</span>
</button>
)}
{onRegenerateTitle && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setOpenMenuSessionId(null);
onRegenerateTitle(row.session.id);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<RefreshCw size={12} className="shrink-0 text-muted-foreground" />
<span>{t('ai.chat.managerRegenerateTitle')}</span>
</button>
)}
<button
type="button"
onClick={(e) => {
@@ -430,6 +625,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
</DropdownContent>
</Dropdown>
)}
</div>
</div>
{moveSession?.id === row.session.id && (
@@ -490,6 +686,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
}}
onConfirm={commitDelete}
/>
<ConfirmDialog
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
confirmLabel={t('common.delete')}
destructive
onOpenChange={(open) => {
if (!open) setBulkDeleteConfirmOpen(false);
}}
onConfirm={commitBulkDelete}
/>
</div>
);
};
@@ -96,6 +96,39 @@ test("global rows cover every scope: live terminal, other terminal, workspace, c
assert.equal(byId.get("s-global")!.scopeLabel, t("ai.chat.chatsScopeGlobal"));
});
test("workspace name snapshot is the fallback for a dangling workspace, but live title wins", () => {
const input = {
...baseInput(),
hosts: [{ id: "h-old", label: "old-host", hostname: "10.0.0.5" }],
};
input.sessions = [
// Workspace gone: the captured name wins over the host fallback.
baseSession({
id: "s-snap",
scope: { type: "workspace", targetId: "w-gone", hostIds: ["h-old"] },
workspaceNameSnapshot: "Prod (old)",
}),
// Workspace still live: the live title wins even if a stale snapshot exists.
baseSession({
id: "s-live",
scope: { type: "workspace", targetId: "w-1" },
workspaceNameSnapshot: "Stale name",
}),
// Dangling flag with a live workspace present still falls back to the snapshot.
baseSession({
id: "s-flagged",
scope: { type: "workspace", targetId: "w-1" },
scopeDangling: true,
workspaceNameSnapshot: "Prod (archived)",
}),
];
const byId = new Map(buildGlobalManagerRows(input).map((row) => [row.session.id, row]));
assert.equal(byId.get("s-snap")!.scopeLabel, "Prod (old)");
assert.equal(byId.get("s-snap")!.scopeState, "dangling");
assert.equal(byId.get("s-live")!.scopeLabel, "Prod");
assert.equal(byId.get("s-flagged")!.scopeLabel, "Prod (archived)");
});
test("active marker distinguishes current panel active chat vs active elsewhere", () => {
const input = baseInput();
input.sessions = [
+5 -1
View File
@@ -165,10 +165,14 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
if (session.scope.type === 'workspace') {
const title = workspaceTitles.get(session.scope.targetId ?? '');
if (title != null && !session.scopeDangling) {
// Live title wins so a rename is reflected immediately.
scopeLabel = title;
isDangling = false;
} else {
scopeLabel = resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
// Workspace is gone/dangling: prefer the name captured at bind time,
// then fall back to the historical host labels.
scopeLabel = session.workspaceNameSnapshot
|| resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
isDangling = true;
}
} else if (session.scope.type === 'terminal') {
@@ -0,0 +1,9 @@
import { createContext } from 'react';
export interface GlobalSessionSelectionContextValue {
selectionMode: boolean;
setSelectionMode: (active: boolean) => void;
}
export const GlobalSessionSelectionContext =
createContext<GlobalSessionSelectionContextValue | null>(null);
@@ -345,6 +345,14 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<div className="text-xs text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
})}
</div>
) : null}
</div>
{restoreAllowed && (
<Button
@@ -443,6 +451,14 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<div className="text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
})}
</div>
) : null}
</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
@@ -141,6 +141,8 @@ export const PluginVaultAISidebar: React.FC<PluginVaultAISidebarProps> = ({
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
deleteSession={aiConfig.deleteSession}
updateSessionTitle={aiConfig.updateSessionTitle}
autoTitleSession={aiConfig.autoTitleSession}
regenerateSessionTitle={aiConfig.regenerateSessionTitle}
exportSessionsBackup={aiConfig.exportSessionsBackup}
importSessionsBackup={aiConfig.importSessionsBackup}
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
@@ -0,0 +1,135 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import React from 'react';
import { ER_CARD_WIDTH, erCardHeight } from './erFormat';
import type { ErRect } from './erFormat';
import type { PluginErTable } from './types';
function position(element: Element) {
const match = element.getAttribute('transform')?.match(/translate\(([-\d.]+), ([-\d.]+)\)/);
assert.ok(match);
return { x: Number(match[1]), y: Number(match[2]) };
}
function assertNoOverlap(label: ErRect, cards: ErRect[]) {
for (const card of cards) {
assert.ok(label.x + label.width < card.x || label.x > card.x + card.width
|| label.y + label.height < card.y || label.y > card.y + card.height,
`label ${JSON.stringify(label)} overlaps card ${JSON.stringify(card)}`);
}
}
test('ER hover labels stay in corridors through drag, zoom, fit, reset, and SVG export', async () => {
const dom = new JSDOM('<!doctype html><body><div id="root"></div></body>', { pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent']) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
install('IS_REACT_ACT_ENVIRONMENT', true);
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 1200, 600);
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginErCanvas } = await import('./PluginErCanvas');
const root = createRoot(document.getElementById('root')!);
let tables: PluginErTable[] = [
{ name: 'customers', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }, { name: 'email', type: 'TEXT' }] },
{ name: 'orders', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }, { name: 'customer_id', type: 'int4', isPk: true, isFk: true }] },
];
const relations = [{ fromTable: 'main.orders', fromColumn: 'customer_id', toTable: 'main.customers', toColumn: 'id', onDelete: 'CASCADE' }];
let exported = '';
const render = async () => {
await act(async () => root.render(<PluginErCanvas tables={tables} relations={relations} onWidgetEvent={(name, detail) => {
if (name === 'exportSvg') exported = String(detail?.svg);
}} />));
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 30)); });
};
const card = (name: string) => document.querySelector(`[data-er-table="${name}"]`)!;
const cards = () => tables.map((table) => ({ ...position(card(table.name)), width: ER_CARD_WIDTH, height: erCardHeight(table) }));
const label = () => document.querySelector('[data-er-relation-label]');
const assertSafeLabel = () => {
const group = label();
assert.ok(group);
const rect = group.querySelector('rect')!;
const bbox = { ...position(group), width: Number(rect.getAttribute('width')), height: Number(rect.getAttribute('height')) };
assertNoOverlap(bbox, cards());
assert.equal(group.querySelector('svg')?.getAttribute('overflow'), 'hidden');
assert.equal(group.getAttribute('pointer-events'), 'none');
// Label paints after every card, with all geometry in the same viewport.
for (const table of tables) assert.ok(card(table.name).compareDocumentPosition(group) & dom.window.Node.DOCUMENT_POSITION_FOLLOWING);
return bbox;
};
const click = async (name: string) => {
await act(async () => document.querySelector(`[aria-label="${name}"]`)!.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })));
};
const zoom = () => Number(document.querySelector('[data-er-table]')!.parentElement!.getAttribute('transform')!.match(/scale\(([^)]+)\)/)![1]);
const dragTo = async (name: string, x: number, y: number) => {
const origin = position(card(name));
const scale = zoom();
await act(async () => card(name).dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 0, clientY: 0 })));
await act(async () => dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { clientX: (x - origin.x) * scale, clientY: (y - origin.y) * scale })));
await act(async () => dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup')));
};
try {
await render();
assert.equal(label(), null);
await act(async () => document.querySelector('[data-er-relation] path')!.dispatchEvent(new dom.window.MouseEvent('pointerover', { bubbles: true })));
const initial = position(card('orders'));
const fullLabel = assertSafeLabel();
assert.equal(label()!.textContent, 'customer_id -> id (ON DELETE CASCADE)');
assert.ok(initial.x - position(card('customers')).x - ER_CARD_WIDTH > fullLabel.width);
// The reported three-table layout also keeps a vertical corridor.
tables = [...tables, { name: 'products', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }] }];
await render();
assertSafeLabel();
assert.ok(position(card('products')).y - position(card('customers')).y - erCardHeight(tables[0]) >= 80);
await click('Zoom in');
assertSafeLabel();
const left = position(card('customers'));
await dragTo('orders', left.x + ER_CARD_WIDTH + 100, left.y);
assertSafeLabel();
assert.match(label()!.textContent!, /\.\.\.$/);
assert.ok(Number(label()!.querySelector('rect')!.getAttribute('width')) < fullLabel.width);
await click('Fit to view');
assertSafeLabel();
await dragTo('orders', left.x + ER_CARD_WIDTH + 40, left.y);
assert.equal(label(), null);
await dragTo('orders', left.x + 100, left.y);
assert.equal(label(), null);
// The live and exported edge layers exclude every card, including overlaps.
const relation = document.querySelector('[data-er-relation]')!;
const maskId = relation.getAttribute('mask')!.slice(5, -1);
const mask = document.getElementById(maskId)!;
assert.equal(mask.querySelectorAll('rect[fill="black"]').length, tables.length);
await click('Export SVG');
const svg = new dom.window.DOMParser().parseFromString(exported, 'image/svg+xml');
assert.equal(svg.querySelector('parsererror'), null);
assert.equal(svg.querySelectorAll('mask rect[fill="black"]').length, tables.length);
assert.ok(svg.querySelector('g[mask] path'));
assert.equal(svg.querySelector('g[mask] text'), null);
const exportedCards = [...svg.querySelectorAll('mask rect[fill="black"]')];
for (const [index, bounds] of cards().entries()) {
for (const key of ['x', 'y', 'width', 'height'] as const) assert.equal(Number(exportedCards[index].getAttribute(key)), bounds[key]);
}
await click('Reset layout');
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 30)); });
assert.deepEqual(position(card('orders')), initial);
assertSafeLabel();
assert.ok(Number.isFinite(zoom()) && zoom() > 0);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, descriptor] of saved) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
@@ -1,5 +1,5 @@
import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import {
abbreviateSqlType,
buildStandaloneErSvg,
@@ -7,7 +7,11 @@ import {
ER_CARD_ROW_HEIGHT,
ER_CARD_WIDTH,
erCardHeight,
erCardRects,
erRelationLabelText,
erRelationLabelWidth,
erTableKey,
placeErRelationLabel,
} from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
import type {
@@ -16,8 +20,7 @@ import type {
PluginWidgetEventCallback,
} from './types';
const GRID_GAP_X = 80;
const GRID_GAP_Y = 56;
const GRID_GAP_Y = 80;
const MIN_ZOOM = 0.25;
const MAX_ZOOM = 2.5;
@@ -25,7 +28,7 @@ export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
}
function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: number; y: number }> {
function computeInitialPositions(tables: PluginErTable[], gapX: number): 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);
@@ -37,7 +40,7 @@ function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: n
return;
}
const colIdx = index % colsPerRow;
const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X);
const x = 40 + colIdx * (ER_CARD_WIDTH + gapX);
const y = colY[colIdx];
result[key] = { x, y };
colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y;
@@ -69,8 +72,10 @@ export function PluginErCanvas({
relations = [],
onWidgetEvent,
}: PluginErCanvasProps) {
const gapX = relations.reduce((gap, rel) => Math.max(gap, erRelationLabelWidth(erRelationLabelText(rel)) + 32), 160);
const containerRef = useRef<HTMLDivElement>(null);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables));
const relationMaskId = useId();
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables, gapX));
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [selectedTable, setSelectedTable] = useState<string | null>(null);
const [hoveredRelation, setHoveredRelation] = useState<number | null>(null);
@@ -83,7 +88,7 @@ export function PluginErCanvas({
useEffect(() => {
setPositions((prev) => {
const defaults = computeInitialPositions(tables);
const defaults = computeInitialPositions(tables, gapX);
const next: Record<string, { x: number; y: number }> = {};
for (const tbl of tables) {
const key = erTableKey(tbl);
@@ -91,7 +96,17 @@ export function PluginErCanvas({
}
return next;
});
}, [tableSignature, tables]);
}, [tableSignature, tables, gapX]);
const cardRects = useMemo(() => erCardRects(tables, positions), [tables, positions]);
const edgeBounds = {
x: Math.min(...cardRects.map((card) => card.x)) - 64,
y: Math.min(...cardRects.map((card) => card.y)) - 64,
width: 0,
height: 0,
};
edgeBounds.width = Math.max(...cardRects.map((card) => card.x + card.width)) - edgeBounds.x + 64;
edgeBounds.height = Math.max(...cardRects.map((card) => card.y + card.height)) - edgeBounds.y + 64;
const tableLookup = useMemo(() => {
const byKey = new Map<string, PluginErTable>();
@@ -262,13 +277,13 @@ export function PluginErCanvas({
}, []);
const resetLayout = useCallback(() => {
setPositions(computeInitialPositions(tables));
setPositions(computeInitialPositions(tables, gapX));
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(fitToView);
requestAnimationFrame(() => fitToViewRef.current());
} else {
fitToView();
}
}, [tables, fitToView]);
}, [tables, gapX, fitToView]);
const handleExportSvg = useCallback(() => {
const palette = resolveCanvasPalette(containerRef.current);
@@ -360,6 +375,10 @@ export function PluginErCanvas({
onPointerDown={handleCanvasPointerDown}
>
<defs>
<mask id={relationMaskId} maskUnits="userSpaceOnUse" {...edgeBounds}>
<rect {...edgeBounds} fill="white" />
{cardRects.map((card, index) => <rect key={index} {...card} fill="black" />)}
</mask>
<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>
@@ -394,15 +413,12 @@ export function PluginErCanvas({
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}`}
mask={`url(#${relationMaskId})`}
onPointerEnter={() => setHoveredRelation(idx)}
onPointerLeave={() => setHoveredRelation(null)}
>
@@ -421,28 +437,6 @@ export function PluginErCanvas({
/>
<circle cx={x1} cy={y1} r={3.5} fill={stroke} />
<circle cx={x2} cy={y2} r={3.5} fill="hsl(var(--background))" stroke={stroke} strokeWidth={1.8} />
{isHovered && (
<g transform={`translate(${midX - labelWidth / 2}, ${midY - 12})`}>
<rect
width={labelWidth}
height={18}
rx={4}
fill="hsl(var(--popover))"
stroke="hsl(var(--primary))"
strokeWidth={1}
/>
<text
x={labelWidth / 2}
y={12}
textAnchor="middle"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--popover-foreground))"
>
{edgeLabel}
</text>
</g>
)}
</g>
);
})}
@@ -558,6 +552,48 @@ export function PluginErCanvas({
</g>
);
})}
{/* Hover labels stay above cards, but only inside a free corridor. */}
{hoveredRelation !== null && (() => {
const rel = relations[hoveredRelation];
if (!rel) return null;
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
if (!fromTable || !toTable) return null;
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((col) => col.name === rel.fromColumn));
const toColIdx = Math.max(0, toTable.columns.findIndex((col) => col.name === rel.toColumn));
const midX = (fromPos.x + toPos.x + ER_CARD_WIDTH) / 2;
const midY = (fromPos.y + toPos.y) / 2 + ER_CARD_HEADER_HEIGHT
+ (fromColIdx + toColIdx + 1) * ER_CARD_ROW_HEIGHT / 2;
const text = erRelationLabelText(rel);
const label = placeErRelationLabel(text, midX, midY, cardRects);
if (!label) return null;
return (
<g data-er-relation-label="" transform={`translate(${label.x}, ${label.y})`} pointerEvents="none">
<rect
width={label.width}
height={label.height}
rx={4}
fill="hsl(var(--popover))"
stroke="hsl(var(--primary))"
strokeWidth={1}
/>
<svg x={7} y={0} width={label.width - 14} height={label.height} overflow="hidden">
<text
x={(label.width - 14) / 2}
y={12}
textAnchor="middle"
fontSize={10}
fontFamily="var(--font-mono)"
fill="hsl(var(--popover-foreground))"
>
{label.text}
</text>
</svg>
</g>
);
})()}
</g>
</svg>
)}
+23 -1
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat';
import { abbreviateSqlType, buildStandaloneErSvg, placeErRelationLabel } from './erFormat';
import { matchWorkbenchShortcut } from './shortcuts';
test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => {
@@ -40,6 +40,28 @@ test('buildStandaloneErSvg generates valid self-contained SVG markup with tables
assert.match(svg, /<path d="M /);
});
test('ER labels avoid unrelated card rectangles and fit vertical corridors', () => {
const text = 'customer_id -> id (ON DELETE CASCADE)';
const cards = [
{ x: 40, y: 40, width: 252, height: 90 },
{ x: 584, y: 40, width: 252, height: 90 },
];
const label = placeErRelationLabel(text, 438, 98, cards);
assert.ok(label);
assert.equal(label.text, text);
assert.ok(label.x > 292 && label.x + label.width < 584);
// An unrelated card can block an otherwise wide corridor.
assert.equal(placeErRelationLabel(text, 438, 98, [...cards, { x: 400, y: 40, width: 252, height: 90 }]), null);
// Vertically aligned tables leave a free label band between the rows.
const vertical = placeErRelationLabel(text, 166, 170, [cards[0], { ...cards[0], y: 210 }]);
assert.ok(vertical);
assert.ok(vertical.y > 130 && vertical.y + vertical.height < 210);
const long = placeErRelationLabel('very_long_column_name'.repeat(30), 438, 98, cards);
assert.ok(long);
assert.ok(long.width <= 260);
assert.match(long.text, /\.\.\.$/);
});
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');
+55
View File
@@ -36,6 +36,52 @@ 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;
}
export interface ErRect {
x: number;
y: number;
width: number;
height: number;
}
export function erCardRects(tables: PluginErTable[], positions: Record<string, { x: number; y: number }>): ErRect[] {
return tables.map((table) => ({
...(positions[erTableKey(table)] ?? { x: 0, y: 0 }),
width: ER_CARD_WIDTH,
height: erCardHeight(table),
}));
}
export function erRelationLabelText(rel: PluginErRelation): string {
return `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`;
}
export function erRelationLabelWidth(text: string): number {
return Math.min(260, Math.max(72, text.length * 6.2 + 14));
}
/** Fit the hover label into the free horizontal corridor at the edge midpoint. */
export function placeErRelationLabel(text: string, midX: number, midY: number, cards: ErRect[]): (ErRect & { text: string }) | null {
const y = midY - 12;
const height = 18;
const clearance = 4;
let left = -Infinity;
let right = Infinity;
for (const card of cards) {
if (y + height <= card.y - clearance || y >= card.y + card.height + clearance) continue;
const cardLeft = card.x - clearance;
const cardRight = card.x + card.width + clearance;
// Hide rather than paint inside a card when dragging closes the corridor.
if (midX >= cardLeft && midX <= cardRight) return null;
if (cardRight < midX) left = Math.max(left, cardRight);
if (cardLeft > midX) right = Math.min(right, cardLeft);
}
const width = Math.min(erRelationLabelWidth(text), right - left);
if (width < 72) return null;
const x = Math.max(left, Math.min(midX - width / 2, right - width));
const maxChars = Math.floor((width - 14) / 6.2 + 1e-6);
return { x, y, width, height, text: text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text };
}
function escapeXml(value: string): string {
return value
.replace(/&/g, '&amp;')
@@ -94,6 +140,14 @@ export function buildStandaloneErSvg(
`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="${escapeXml(palette.background)}" />`,
];
// Cut all edge decorations out of card rectangles, even with translucent fills.
lines.push(`<defs><mask id="er-edges" maskUnits="userSpaceOnUse" x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}">`);
lines.push(`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="white" />`);
for (const card of erCardRects(tables, positions)) {
lines.push(`<rect x="${card.x}" y="${card.y}" width="${card.width}" height="${card.height}" fill="black" />`);
}
lines.push('</mask></defs><g mask="url(#er-edges)">');
for (const rel of relations) {
const fromTable = resolveTable(rel.fromTable);
const toTable = resolveTable(rel.toTable);
@@ -116,6 +170,7 @@ export function buildStandaloneErSvg(
`<circle cx="${x2}" cy="${y2}" r="3.5" fill="${escapeXml(palette.background)}" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.8" />`,
);
}
lines.push('</g>');
for (const tbl of tables) {
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
+48 -24
View File
@@ -10,7 +10,7 @@ import React, {
import { AlertCircle, UploadCloud } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData } from '../../domain/rdpClipboard';
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData, shouldPushLocalClipboardToRdp } from '../../domain/rdpClipboard';
import {
computeMonitorVirtualBounds,
mapViewportToVirtualDesktopCoords,
@@ -29,6 +29,7 @@ import {
resolveKeyToRdpScancode,
type RemoteDesktopAction,
} from '../../domain/remoteDesktopActionCodec';
import { buildRdpFileContentsResponse } from '../../infrastructure/remoteDesktop/rdpFileContents';
import type { RemoteDesktopSharedFolder } from '../../infrastructure/remoteDesktop/remoteDesktopSharedFolders';
import {
captureFrameFromCanvas,
@@ -468,6 +469,15 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
callbacksRef.current.onClipboardFileTransferStatus?.(transfer?.message ?? null);
}, []);
const clearLocalClipboardFiles = useCallback(() => {
if (uploadedFilesRef.current.length === 0) return;
uploadedFilesRef.current = [];
uploadedHighWaterByIndexRef.current.clear();
uploadTransferIdRef.current = '';
lastUploadProgressEmitRef.current = 0;
emitClipboardTransfer(null);
}, [emitClipboardTransfer]);
const downloadRemoteClipboardFile = useCallback(async (fileIndex: number) => {
const session = sessionRef.current;
const mod = modRef.current;
@@ -579,6 +589,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
});
toast.info(stagedMessage);
} catch (err) {
uploadedFilesRef.current = [];
uploadedHighWaterByIndexRef.current.clear();
uploadTransferIdRef.current = '';
lastUploadProgressEmitRef.current = 0;
const errMessage = err instanceof Error ? err.message : 'Server does not support clipboard file transfer';
emitClipboardTransfer({
id: transferId,
@@ -601,7 +615,11 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
// Sync local clipboard to remote when focused or manually requested
const syncLocalClipboardToRdp = useCallback(async (force = false) => {
if ((!force && !propsRef.current.clipboardSyncEnabled) || propsRef.current.viewOnly) return;
if (!shouldPushLocalClipboardToRdp({
...propsRef.current,
force,
stagedLocalFileCount: uploadedFilesRef.current.length,
})) return;
const session = sessionRef.current;
const mod = modRef.current;
if (!session || !mod) return;
@@ -611,6 +629,12 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
Promise.resolve().then(() => navigator.clipboard?.readText()),
readClipboardImagePng(),
]);
// A file drop or session change can happen while clipboard reads are pending.
if (sessionRef.current !== session || !shouldPushLocalClipboardToRdp({
...propsRef.current,
force,
stagedLocalFileCount: uploadedFilesRef.current.length,
})) return;
const { text, pngBytes } = selectRdpClipboardData({
text: textResult.status === 'fulfilled' ? textResult.value : null,
pngBytes: pngResult.status === 'fulfilled' ? pngResult.value : null,
@@ -622,6 +646,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
try {
if (text) data.addText('text/plain', text);
if (pngBytes) data.addBinary('image/png', pngBytes);
if (force) clearLocalClipboardFiles();
await session.onClipboardPaste(data);
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text, pngBytes });
} finally {
@@ -630,7 +655,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
} catch {
// Clipboard permission or empty
}
}, [readClipboardImagePng]);
}, [clearLocalClipboardFiles, readClipboardImagePng]);
const syncClipboardNow = useCallback(() => syncLocalClipboardToRdp(true), [syncLocalClipboardToRdp]);
@@ -1169,7 +1194,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
// Clipboard (text / HTML / PNG)
builder.remoteClipboardChangedCallback((clipboardData: IronClipboardData) => {
if (disposed || !propsRef.current.clipboardSyncEnabled) return;
if (disposed) return;
try {
const items = clipboardData.items();
let plainText: string | null = null;
@@ -1183,6 +1208,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
pngBytes = val;
}
}
if (plainText !== null || pngBytes !== null) clearLocalClipboardFiles();
if (!propsRef.current.clipboardSyncEnabled) return;
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text: plainText, pngBytes });
if (pngBytes && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const data = buildRdpClipboardItemData({ text: plainText, pngBytes });
@@ -1226,6 +1253,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
isDirectory: Boolean(f?.isDirectory),
}),
);
if (offers.length > 0) clearLocalClipboardFiles();
remoteFilesRef.current = { clipDataId, files: offers };
callbacksRef.current.onRemoteClipboardFilesChange?.(offers);
},
@@ -1249,11 +1277,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
if (!file) {
try {
session.invokeExtension(
new mod.Extension('submit_file_contents', {
streamId: req.streamId,
isError: true,
data: new Uint8Array(0),
}),
new mod.Extension(
'submit_file_contents',
buildRdpFileContentsResponse(req.streamId, true, new Uint8Array(0)),
),
);
} catch { /* ignore */ }
return;
@@ -1268,11 +1295,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
dv.setUint32(4, high, true);
try {
session.invokeExtension(
new mod.Extension('submit_file_contents', {
streamId: req.streamId,
isError: false,
data: new Uint8Array(sizeBuf),
}),
new mod.Extension(
'submit_file_contents',
buildRdpFileContentsResponse(req.streamId, false, new Uint8Array(sizeBuf)),
),
);
} catch { /* ignore */ }
return;
@@ -1286,11 +1312,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
.then((ab) => {
if (disposed || !sessionRef.current) return;
sessionRef.current.invokeExtension(
new mod.Extension('submit_file_contents', {
streamId: req.streamId,
isError: false,
data: new Uint8Array(ab),
}),
new mod.Extension(
'submit_file_contents',
buildRdpFileContentsResponse(req.streamId, false, new Uint8Array(ab)),
),
);
const prevHighWater = uploadedHighWaterByIndexRef.current.get(req.index) ?? 0;
const nextHighWater = Math.max(
@@ -1328,11 +1353,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
if (disposed || !sessionRef.current) return;
try {
sessionRef.current.invokeExtension(
new mod.Extension('submit_file_contents', {
streamId: req.streamId,
isError: true,
data: new Uint8Array(0),
}),
new mod.Extension(
'submit_file_contents',
buildRdpFileContentsResponse(req.streamId, true, new Uint8Array(0)),
),
);
} catch { /* ignore */ }
const errMessage = err instanceof Error
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
const source = readFileSync(new URL('./RemoteDesktopPane.tsx', import.meta.url), 'utf8');
test('RemoteDesktopPane keeps keyboard grab in visible solo and focus panes and honors split focus', () => {
const terminalLayerSource = readFileSync(new URL('../terminalLayer/TerminalLayerSupport.tsx', import.meta.url), 'utf8');
const paneProps = terminalLayerSource.match(/<LazyRemoteDesktopPane\b[\s\S]*?\/>/)?.[0];
assert.ok(paneProps, 'RemoteDesktopPane must be wired into the terminal layer');
assert.match(paneProps, /isVisible=\{isVisible\}/);
// Solo and focus modes have no split contention; only split siblings use the focus boolean.
assert.match(paneProps, /isFocused=\{paneState.mode === 'split' \? isFocusedPane : true\}/);
});
test('RemoteDesktopPane releases keyboard grab for an unfocused split sibling, hidden, disconnected, or view-only pane', () => {
assert.match(
source,
/useEffect\(\(\) => \{\s*if \(\(!isVisible \|\| !isFocused \|\| status !== 'connected' \|\| viewOnly\) && keyboardGrabActive\) \{\s*releaseKeyboardGrab\(\);\s*\}\s*\}, \[isFocused, isVisible, keyboardGrabActive, releaseKeyboardGrab, status, viewOnly\]\)/,
);
});
test('RemoteDesktopPane scopes all pane UI portals to the pane only in session fullscreen', () => {
assert.match(source, /import \{ PortalContainerProvider \} from '\.\.\/ui\/portal-container'/);
assert.match(source, /const \[portalContainer, setPortalContainer\] = useState<HTMLDivElement \| null>\(null\)/);
assert.match(source, /const paneContent = \([\s\S]*<RemoteDesktopToolbar[\s\S]*<RemoteDesktopAuditDialog/);
assert.match(
source,
/<PortalContainerProvider container=\{isFullscreen \? portalContainer : null\}>\s*\{paneContent\}\s*<\/PortalContainerProvider>/,
);
});
test('RemoteDesktopPane uses the same root for fullscreen ownership and the portal container', () => {
assert.match(
source,
/const setPaneRoot = useCallback\(\(node: HTMLDivElement \| null\) => \{\s*paneRootRef.current = node;\s*setPortalContainer\(node\);\s*\}, \[\]\)/,
);
assert.match(source, /const paneContent = \(\s*<div\s+ref=\{setPaneRoot\}/);
assert.match(
source,
/const root = paneRootRef.current;\s*setIsFullscreen\(Boolean\(root && document.fullscreenElement === root\)\)/,
);
assert.match(source, /document.addEventListener\('fullscreenchange', handleFsChange\)/);
assert.match(source, /document.removeEventListener\('fullscreenchange', handleFsChange\)/);
assert.match(source, /const root = paneRootRef.current;[\s\S]*root.requestFullscreen\(\)/);
});
+17 -3
View File
@@ -79,6 +79,7 @@ import {
VncProtocolIcon,
} from '../icons/RemoteDesktopIcons';
import { Button } from '../ui/button';
import { PortalContainerProvider } from '../ui/portal-container';
import { toast } from '../ui/toast';
import {
trustKnownRemoteDesktopCert,
@@ -208,6 +209,11 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const { t } = useI18n();
const isRdp = protocol === 'rdp';
const paneRootRef = useRef<HTMLDivElement | null>(null);
const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(null);
const setPaneRoot = useCallback((node: HTMLDivElement | null) => {
paneRootRef.current = node;
setPortalContainer(node);
}, []);
const canvasAreaRef = useRef<HTMLDivElement | null>(null);
const canvasHandleRef = useRef<RemoteDesktopCanvasHandle | null>(null);
const activeBackendSessionIdRef = useRef<string | null>(null);
@@ -1161,6 +1167,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
keys,
identities,
knownHosts,
credentials,
});
const res = await rdBridge.openSystemClient(opts);
if (!res?.ok) {
@@ -1169,7 +1176,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to launch system client');
}
}, [chainHosts, host, identities, keys, knownHosts, protocol]);
}, [chainHosts, credentials, host, identities, keys, knownHosts, protocol]);
const handleToggleFullscreen = useCallback(() => {
const root = paneRootRef.current;
@@ -1747,9 +1754,9 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const showRemoteAppNotice =
isRdp && Boolean(spec.rdpConfig?.remoteApplicationMode) && !remoteAppBannerDismissed;
return (
const paneContent = (
<div
ref={paneRootRef}
ref={setPaneRoot}
className={cn(
'relative flex h-full w-full flex-col overflow-hidden bg-black text-foreground select-none',
keyboardGrabActive && 'ring-2 ring-inset ring-primary/80',
@@ -2309,6 +2316,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
/>
</div>
);
// Fullscreen portals must stay inside the pane; windowed menus need to escape its overflow clipping.
return (
<PortalContainerProvider container={isFullscreen ? portalContainer : null}>
{paneContent}
</PortalContainerProvider>
);
});
RemoteDesktopPane.displayName = 'RemoteDesktopPane';
@@ -8,6 +8,7 @@ import { selectConnectionLogForTerminalDataCapture } from '../../domain/connecti
import type { ConnectionLog } from '../../domain/models';
import type { Host, TerminalSession } from '../../types';
import {
buildSystemRemoteDesktopPayload,
canOpenCompanionRemoteDesktopSftp,
computeClipboardUploadProgress,
formatRecordingDuration,
@@ -155,3 +156,77 @@ test('stampRemoteDesktopSessionEndTimes and handleTerminalDataCaptureImpl stamp
assert.ok(typeof updates[0].patch.endTime === 'number' && updates[0].patch.endTime > 0);
assert.equal('terminalData' in updates[0].patch, false);
});
test('buildSystemRemoteDesktopPayload passes RDP password via payload without embedding it in rdpContent', () => {
const rdpHost = {
id: 'rdp-1',
label: 'Prod Win',
hostname: '10.10.0.5',
port: 3389,
username: 'CORP\\alice',
password: 'VaultedPassword123!',
group: '',
tags: [],
os: 'windows',
protocol: 'rdp',
} as unknown as Host;
const vaultedPayload = buildSystemRemoteDesktopPayload({
host: rdpHost,
protocol: 'rdp',
keys: [],
identities: [],
});
assert.equal(vaultedPayload.protocol, 'rdp');
assert.equal(vaultedPayload.username, 'alice');
assert.equal(vaultedPayload.domain, 'CORP');
assert.equal(vaultedPayload.password, 'VaultedPassword123!');
assert.ok(vaultedPayload.rdpContent);
assert.equal(vaultedPayload.rdpContent.includes('VaultedPassword123!'), false);
assert.match(vaultedPayload.rdpContent, /^prompt for credentials:i:1\r?$/m);
// Runtime credentials override (typed in auth dialog)
const runtimePayload = buildSystemRemoteDesktopPayload({
host: rdpHost,
protocol: 'rdp',
keys: [],
identities: [],
credentials: {
username: 'localadmin',
domain: '',
password: 'TypedRuntimePassword!',
},
});
assert.equal(runtimePayload.username, 'localadmin');
assert.equal(runtimePayload.domain, undefined);
assert.equal(runtimePayload.password, 'TypedRuntimePassword!');
assert.ok(runtimePayload.rdpContent);
assert.equal(runtimePayload.rdpContent.includes('TypedRuntimePassword!'), false);
assert.match(runtimePayload.rdpContent, /^username:s:localadmin\r?$/m);
// VNC never passes password on the system client payload
const vncHost = {
...rdpHost,
id: 'vnc-1',
port: 5900,
protocol: 'vnc',
} as unknown as Host;
const vncPayload = buildSystemRemoteDesktopPayload({
host: vncHost,
protocol: 'vnc',
keys: [],
identities: [],
credentials: {
username: 'bob',
domain: '',
password: 'VncPasswordShouldNotPass',
},
});
assert.equal(vncPayload.protocol, 'vnc');
assert.equal(vncPayload.password, undefined);
assert.equal(vncPayload.rdpContent, undefined);
});
@@ -1,6 +1,7 @@
import type { Host, Identity, KnownHost, SSHKey } from '../../types';
import {
resolveRemoteDesktopConnectionSpec,
splitWindowsUserDomain,
type MonitorLayoutSpec,
type RemoteDesktopConnectionSpec,
type RemoteDesktopProtocol,
@@ -447,18 +448,42 @@ export function buildSystemRemoteDesktopPayload(args: {
identities: readonly Identity[];
knownHosts?: readonly KnownHost[];
rawRdpContent?: string;
credentials?: {
username?: string;
password?: string;
domain?: string;
};
}): RemoteDesktopOpenSystemClientOptions {
const { host, protocol, chainHosts, keys, identities, knownHosts, rawRdpContent } = args;
const { host, protocol, chainHosts, keys, identities, knownHosts, rawRdpContent, credentials } = args;
const spec = resolveRemoteDesktopConnectionSpec(host, protocol, identities);
const jumpHosts = buildSshJumpHostConfigs(chainHosts, keys, identities);
const proxy = toBridgeProxy(host, identities);
const rawUsername = credentials?.username !== undefined ? credentials.username : spec.username;
const rawDomain = protocol === 'rdp'
? (credentials?.domain !== undefined ? credentials.domain : spec.domain)
: '';
const resolvedUserDomain = protocol === 'rdp'
? splitWindowsUserDomain(rawUsername, rawDomain)
: { username: (rawUsername || '').trim(), domain: '' };
const effectiveUsername = resolvedUserDomain.username || undefined;
const effectiveDomain = protocol === 'rdp' ? (resolvedUserDomain.domain || undefined) : undefined;
const rawPassword = protocol === 'rdp'
? (credentials?.password !== undefined && credentials.password.length > 0
? credentials.password
: spec.password)
: undefined;
const sanitizedPassword = sanitizeCredentialValue(rawPassword);
const effectivePassword = sanitizedPassword && sanitizedPassword.length > 0
? sanitizedPassword
: undefined;
const rdpContent = protocol === 'rdp'
? (rawRdpContent?.trim() || generateRdpFileContent({
hostname: spec.hostname,
port: spec.port,
username: spec.username || undefined,
domain: spec.domain || undefined,
username: effectiveUsername,
domain: effectiveDomain,
width: spec.rdpConfig?.width,
height: spec.rdpConfig?.height,
colorDepth: spec.rdpConfig?.colorDepth,
@@ -479,8 +504,9 @@ export function buildSystemRemoteDesktopPayload(args: {
protocol,
hostname: spec.hostname,
port: spec.port,
username: spec.username || undefined,
domain: spec.domain || undefined,
username: effectiveUsername,
...(effectivePassword !== undefined ? { password: effectivePassword } : {}),
domain: effectiveDomain,
label: spec.label,
rdpContent,
loadBalanceInfo: spec.rdpConfig?.loadBalanceInfo,
@@ -0,0 +1,168 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { createDomRenderer, dispatchDomEvent, installDomEnvironment } from "../../test-support/renderReactDom";
test("custom arguments input preserves trailing spaces while typing and tokenizes on blur", async (t) => {
const env = installDomEnvironment();
const previous = new Map<string, PropertyDescriptor | undefined>();
const globals = {
DocumentFragment: env.window.DocumentFragment,
MutationObserver: env.window.MutationObserver,
Element: env.window.Element,
requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),
cancelAnimationFrame: clearTimeout,
};
for (const [key, value] of Object.entries(globals)) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
const {
getExternalEditorSettingsSnapshot,
updateExternalEditorSettings,
} = await import("../../../application/state/useExternalEditorSettings");
const { I18nProvider } = await import("../../../application/i18n/I18nProvider");
const { TooltipProvider } = await import("../../ui/tooltip");
const { ExternalEditorSettingsSection } = await import("./ExternalEditorSettingsSection");
const originalSettings = getExternalEditorSettingsSnapshot();
updateExternalEditorSettings((prev) => ({
...prev,
defaultEditor: "custom",
editors: {
...prev.editors,
custom: {
...prev.editors.custom,
customArgs: ["{sshUri}"],
},
},
}));
const renderer = await createDomRenderer(env.document);
t.after(async () => {
await renderer.unmount();
updateExternalEditorSettings(() => originalSettings);
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
env.cleanup();
});
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<ExternalEditorSettingsSection />
</TooltipProvider>
</I18nProvider>,
);
const input = env.document.querySelector('input[placeholder="{sshUri}"]') as HTMLInputElement | null;
assert.ok(input, "expected custom arguments input to be rendered");
const setInputValue = (value: string) => {
const descriptor = Object.getOwnPropertyDescriptor(env.window.HTMLInputElement.prototype, "value");
descriptor?.set?.call(input, value);
};
await dispatchDomEvent(input, new env.window.FocusEvent("focusin", { bubbles: true }));
// Typing a trailing space must NOT be stripped before the next token is entered.
setInputValue("--remote ");
await dispatchDomEvent(input, new env.window.Event("input", { bubbles: true }));
assert.equal(input.value, "--remote ");
setInputValue("--remote {sshTarget} {remotePath}");
await dispatchDomEvent(input, new env.window.Event("input", { bubbles: true }));
assert.equal(input.value, "--remote {sshTarget} {remotePath}");
// Blur commits tokenized arguments to settings.
await dispatchDomEvent(input, new env.window.FocusEvent("focusout", { bubbles: true }));
assert.deepEqual(
getExternalEditorSettingsSnapshot().editors.custom.customArgs,
["--remote", "{sshTarget}", "{remotePath}"],
);
assert.equal(input.value, "--remote {sshTarget} {remotePath}");
});
test("executable path input preserves spaces while typing and commits trimmed value on blur", async (t) => {
const env = installDomEnvironment();
const previous = new Map<string, PropertyDescriptor | undefined>();
const globals = {
DocumentFragment: env.window.DocumentFragment,
MutationObserver: env.window.MutationObserver,
Element: env.window.Element,
requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),
cancelAnimationFrame: clearTimeout,
};
for (const [key, value] of Object.entries(globals)) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
const {
getExternalEditorSettingsSnapshot,
updateExternalEditorSettings,
} = await import("../../../application/state/useExternalEditorSettings");
const { I18nProvider } = await import("../../../application/i18n/I18nProvider");
const { TooltipProvider } = await import("../../ui/tooltip");
const { ExternalEditorSettingsSection } = await import("./ExternalEditorSettingsSection");
const originalSettings = getExternalEditorSettingsSnapshot();
updateExternalEditorSettings((prev) => ({
...prev,
defaultEditor: "vscode",
editors: {
...prev.editors,
vscode: {
...prev.editors.vscode,
executablePath: "",
},
},
}));
const renderer = await createDomRenderer(env.document);
t.after(async () => {
await renderer.unmount();
updateExternalEditorSettings(() => originalSettings);
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
env.cleanup();
});
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<ExternalEditorSettingsSection />
</TooltipProvider>
</I18nProvider>,
);
const input = env.document.querySelector('input[class*="flex-1"]') as HTMLInputElement | null;
assert.ok(input, "expected executable path input to be rendered");
const setInputValue = (value: string) => {
const descriptor = Object.getOwnPropertyDescriptor(env.window.HTMLInputElement.prototype, "value");
descriptor?.set?.call(input, value);
};
await dispatchDomEvent(input, new env.window.FocusEvent("focusin", { bubbles: true }));
setInputValue("/Applications/Visual ");
await dispatchDomEvent(input, new env.window.Event("input", { bubbles: true }));
assert.equal(input.value, "/Applications/Visual ");
setInputValue(" /Applications/Visual Studio Code.app ");
await dispatchDomEvent(input, new env.window.Event("input", { bubbles: true }));
assert.equal(input.value, " /Applications/Visual Studio Code.app ");
await dispatchDomEvent(input, new env.window.FocusEvent("focusout", { bubbles: true }));
assert.equal(
getExternalEditorSettingsSnapshot().editors.vscode.executablePath,
"/Applications/Visual Studio Code.app",
);
assert.equal(input.value, "/Applications/Visual Studio Code.app");
});
@@ -0,0 +1,437 @@
/**
* ExternalEditorSettingsSection - Configure remote SSH external editors (Zed, VS Code, Cursor, etc.),
* the *.netcatty OpenSSH channel bridge, terminal OSC 7337 permissions, per-host trust, and shell snippets.
*/
import { CheckCircle2, RefreshCw, RotateCcw, ShieldCheck, Trash2 } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import {
useExternalEditorEnvironment,
useExternalEditorSettings,
} from '../../../application/state/useExternalEditorSettings';
import {
EXTERNAL_EDITOR_PRESET_IDS,
EXTERNAL_EDITOR_PRESETS,
type ExternalEditorConnectionMode,
type ExternalEditorHostTrustPolicy,
type ExternalEditorPresetId,
} from '../../../domain/externalEditor';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip';
import {
SectionHeader,
Select,
SettingCard,
SettingRow,
SettingsAnchor,
Toggle,
} from '../settings-ui';
export function ExternalEditorSettingsSection() {
const { t } = useI18n();
const {
settings,
setDefaultEditor,
setEditorExecutablePath,
setCustomEditorArgs,
setTerminalRequestsEnabled,
setAutoSetupShellIntegration,
setDefaultTrustPolicy,
setConnectionMode,
setHostTrustPolicy,
removeHostTrustPolicy,
} = useExternalEditorSettings();
const {
detectedEditors,
detecting,
selectingApp,
bridgeStatus,
bridgeBusy,
bridgeError,
refreshStatus,
browseExecutable,
installBridgeConfig,
removeBridgeConfig,
} = useExternalEditorEnvironment();
const selectedEditor = settings.defaultEditor;
const selectedConfig = settings.editors[selectedEditor];
const detectedForSelected = detectedEditors[selectedEditor];
const [executablePathDraft, setExecutablePathDraft] = useState(selectedConfig.executablePath);
const [isEditingExecutablePath, setIsEditingExecutablePath] = useState(false);
useEffect(() => {
setIsEditingExecutablePath(false);
setExecutablePathDraft(selectedConfig.executablePath);
}, [selectedEditor]);
useEffect(() => {
if (!isEditingExecutablePath) {
setExecutablePathDraft(selectedConfig.executablePath);
}
}, [isEditingExecutablePath, selectedConfig.executablePath]);
const commitExecutablePathDraft = useCallback(
(editorId: ExternalEditorPresetId, rawValue: string) => {
const normalized = rawValue.trim();
setEditorExecutablePath(editorId, normalized);
setExecutablePathDraft(normalized);
},
[setEditorExecutablePath],
);
const storedCustomArgsText = useMemo(
() => (settings.editors.custom.customArgs || ['{sshUri}']).join(' '),
[settings.editors.custom.customArgs],
);
const [customArgsDraft, setCustomArgsDraft] = useState(storedCustomArgsText);
const [isEditingCustomArgs, setIsEditingCustomArgs] = useState(false);
useEffect(() => {
if (!isEditingCustomArgs) {
setCustomArgsDraft(storedCustomArgsText);
}
}, [isEditingCustomArgs, storedCustomArgsText]);
const commitCustomArgsDraft = useCallback((rawValue: string) => {
const tokens = rawValue.trim().split(/\s+/).filter(Boolean);
const nextTokens = tokens.length > 0 ? tokens : ['{sshUri}'];
setCustomEditorArgs(nextTokens);
setCustomArgsDraft(nextTokens.join(' '));
}, [setCustomEditorArgs]);
const handleBrowseExecutable = useCallback(async () => {
const pickedPath = await browseExecutable(selectedEditor);
if (pickedPath) {
setExecutablePathDraft(pickedPath);
}
}, [browseExecutable, selectedEditor]);
const trustedHostEntries = useMemo(
() => Object.entries(settings.trustedHosts).sort(([a], [b]) => a.localeCompare(b)),
[settings.trustedHosts],
);
const effectiveExecutable = selectedConfig.executablePath || detectedForSelected?.detectedPath || '';
return (
<>
<SectionHeader
title={t('settings.externalEditor.title')}
anchorId="external-editor-settings"
/>
<p className="text-xs text-muted-foreground -mt-3 mb-1">
{t('settings.externalEditor.desc')}
</p>
<SettingCard>
<SettingRow
anchorId="external-editor-default"
label={t('settings.externalEditor.preferredEditor')}
description={t('settings.externalEditor.preferredEditor.desc')}
>
<Select
value={selectedEditor}
options={EXTERNAL_EDITOR_PRESET_IDS.map((id) => ({
value: id,
label: EXTERNAL_EDITOR_PRESETS[id].label,
}))}
onChange={(value) => setDefaultEditor(value as ExternalEditorPresetId)}
className="w-48"
/>
</SettingRow>
<SettingsAnchor anchorId="external-editor-executable" className="py-3 space-y-2 border-t border-border/60">
<div className="flex items-center justify-between gap-2">
<div>
<div className="text-sm font-medium">{t('settings.externalEditor.executablePath')}</div>
<div className="text-xs text-muted-foreground mt-0.5">
{t('settings.externalEditor.executablePath.desc')}
</div>
</div>
{selectedEditor !== 'custom' && (
<span
className={
effectiveExecutable
? 'inline-flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400'
: 'text-xs text-muted-foreground'
}
>
{effectiveExecutable ? (
<>
<CheckCircle2 size={13} />
{selectedConfig.executablePath
? t('settings.externalEditor.status.configured')
: t('settings.externalEditor.status.detected')}
</>
) : (
t('settings.externalEditor.status.notFound')
)}
</span>
)}
</div>
<div className="flex items-center gap-2">
<Input
value={executablePathDraft}
onFocus={() => setIsEditingExecutablePath(true)}
onChange={(e) => setExecutablePathDraft(e.target.value)}
onBlur={(e) => {
setIsEditingExecutablePath(false);
commitExecutablePathDraft(selectedEditor, e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitExecutablePathDraft(selectedEditor, e.currentTarget.value);
e.currentTarget.blur();
}
}}
placeholder={
detectedForSelected?.detectedPath
|| t('settings.externalEditor.executablePath.placeholder')
}
className="font-mono text-xs h-8 flex-1"
/>
<Button
variant="outline"
size="sm"
onClick={() => void handleBrowseExecutable()}
disabled={selectingApp}
className="shrink-0"
>
{t('settings.externalEditor.browse')}
</Button>
{(selectedConfig.executablePath || executablePathDraft) && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => {
setIsEditingExecutablePath(false);
setExecutablePathDraft('');
setEditorExecutablePath(selectedEditor, '');
}}
aria-label={t('settings.externalEditor.resetPath')}
>
<RotateCcw size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>{t('settings.externalEditor.resetPath')}</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => void refreshStatus()}
disabled={detecting}
aria-label={t('settings.externalEditor.redetect')}
>
<RefreshCw size={14} className={detecting ? 'animate-spin' : undefined} />
</Button>
</TooltipTrigger>
<TooltipContent>{t('settings.externalEditor.redetect')}</TooltipContent>
</Tooltip>
</div>
</SettingsAnchor>
{selectedEditor === 'custom' && (
<SettingsAnchor anchorId="external-editor-custom-args" className="py-3 space-y-2 border-t border-border/60">
<div>
<div className="text-sm font-medium">{t('settings.externalEditor.customArgs')}</div>
<div className="text-xs text-muted-foreground mt-0.5">
{t('settings.externalEditor.customArgs.desc')}
</div>
</div>
<Input
value={customArgsDraft}
onFocus={() => setIsEditingCustomArgs(true)}
onChange={(e) => setCustomArgsDraft(e.target.value)}
onBlur={(e) => {
setIsEditingCustomArgs(false);
commitCustomArgsDraft(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitCustomArgsDraft(e.currentTarget.value);
e.currentTarget.blur();
}
}}
placeholder="{sshUri}"
className="font-mono text-xs h-8"
/>
</SettingsAnchor>
)}
<SettingRow
anchorId="external-editor-connection-mode"
label={t('settings.externalEditor.connectionMode')}
description={t('settings.externalEditor.connectionMode.desc')}
>
<Select
value={settings.connectionMode}
options={[
{ value: 'bridge', label: t('settings.externalEditor.connectionMode.bridge') },
{ value: 'direct', label: t('settings.externalEditor.connectionMode.direct') },
]}
onChange={(value) => setConnectionMode(value as ExternalEditorConnectionMode)}
className="w-56"
/>
</SettingRow>
{settings.connectionMode === 'bridge' && (
<SettingsAnchor anchorId="external-editor-ssh-bridge" className="py-3 space-y-2 border-t border-border/60">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-sm font-medium flex items-center gap-1.5">
<ShieldCheck size={14} className="text-primary shrink-0" />
{t('settings.externalEditor.sshBridge.title')}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{t('settings.externalEditor.sshBridge.desc')}
</div>
{bridgeStatus?.sshConfigPath && (
<div className="text-[11px] font-mono text-muted-foreground mt-1 truncate">
{bridgeStatus.sshConfigPath}
</div>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
{bridgeStatus?.installed ? (
<>
<Button
variant="outline"
size="sm"
onClick={() => void installBridgeConfig()}
disabled={bridgeBusy}
>
{bridgeStatus.upToDate
? t('settings.externalEditor.sshBridge.reinstall')
: t('settings.externalEditor.sshBridge.update')}
</Button>
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => void removeBridgeConfig()}
disabled={bridgeBusy}
>
{t('settings.externalEditor.sshBridge.remove')}
</Button>
</>
) : (
<Button
variant="outline"
size="sm"
onClick={() => void installBridgeConfig()}
disabled={bridgeBusy}
>
{t('settings.externalEditor.sshBridge.install')}
</Button>
)}
</div>
</div>
{bridgeError && (
<p className="text-xs text-destructive">{bridgeError}</p>
)}
</SettingsAnchor>
)}
<SettingRow
anchorId="external-editor-terminal-requests"
label={t('settings.externalEditor.terminalRequests')}
description={t('settings.externalEditor.terminalRequests.desc')}
>
<Toggle
checked={settings.terminalRequestsEnabled}
onChange={setTerminalRequestsEnabled}
/>
</SettingRow>
<SettingRow
anchorId="external-editor-auto-setup"
label={t('settings.externalEditor.autoSetup')}
description={t('settings.externalEditor.autoSetup.desc')}
>
<Toggle
checked={settings.autoSetupShellIntegration}
onChange={setAutoSetupShellIntegration}
disabled={!settings.terminalRequestsEnabled}
/>
</SettingRow>
<SettingRow
anchorId="external-editor-default-trust"
label={t('settings.externalEditor.defaultTrust')}
description={t('settings.externalEditor.defaultTrust.desc')}
>
<Select
value={settings.defaultTrustPolicy}
options={[
{ value: 'ask', label: t('settings.externalEditor.trust.ask') },
{ value: 'allow', label: t('settings.externalEditor.trust.allow') },
{ value: 'deny', label: t('settings.externalEditor.trust.deny') },
]}
onChange={(value) => setDefaultTrustPolicy(value as ExternalEditorHostTrustPolicy)}
className="w-48"
disabled={!settings.terminalRequestsEnabled}
/>
</SettingRow>
</SettingCard>
{trustedHostEntries.length > 0 && (
<div className="rounded-lg border bg-card overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/50 border-b border-border">
<th className="text-left px-4 py-2 font-medium">
{t('settings.externalEditor.trustedHosts.host')}
</th>
<th className="text-left px-4 py-2 font-medium">
{t('settings.externalEditor.trustedHosts.policy')}
</th>
<th className="text-right px-4 py-2 font-medium w-16" />
</tr>
</thead>
<tbody>
{trustedHostEntries.map(([hostKey, policy]) => (
<tr key={hostKey} className="border-b border-border last:border-b-0 hover:bg-muted/30">
<td className="px-4 py-2 font-mono text-xs">{hostKey}</td>
<td className="px-4 py-2">
<Select
value={policy}
options={[
{ value: 'allow', label: t('settings.externalEditor.trust.allow') },
{ value: 'ask', label: t('settings.externalEditor.trust.ask') },
{ value: 'deny', label: t('settings.externalEditor.trust.deny') },
]}
onChange={(value) => setHostTrustPolicy(hostKey, value as ExternalEditorHostTrustPolicy)}
className="w-40"
/>
</td>
<td className="px-4 py-2 text-right">
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => removeHostTrustPolicy(hostKey)}
aria-label={t('action.remove')}
>
<Trash2 size={14} />
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
+44 -1
View File
@@ -18,6 +18,7 @@ import type {
ProviderConfig,
WebSearchConfig,
} from "../../../infrastructure/ai/types";
import type { TitleModelConfig } from "../../../application/state/useAISettingsState";
import type { ManagedAgentKey } from "../../../infrastructure/ai/managedAgents";
import { PROVIDER_PRESETS } from "../../../infrastructure/ai/types";
import { withOpencodeGoAutoConfiguredModel, shouldAutoActivateOpencodeGo } from "../../../infrastructure/ai/opencodeGo";
@@ -62,6 +63,7 @@ import {
} from "../../../domain/aiSessionMessageCap";
import { WebSearchSettings } from "./ai/WebSearchSettings";
import { QuickMessagesSettings } from "./ai/QuickMessagesSettings";
import { TitleModelPicker } from "./ai/TitleModelPicker";
import type { AIQuickMessage } from "../../../infrastructure/ai/quickMessages";
import { encryptField } from "../../../infrastructure/persistence/secureFieldAdapter";
import { CursorSdkCard } from "./ai/CursorSdkCard";
@@ -175,6 +177,12 @@ interface SettingsAITabProps {
setQuickMessages: (value: AIQuickMessage[] | ((prev: AIQuickMessage[]) => AIQuickMessage[])) => void;
showTerminalSelectionAIAction: boolean;
setShowTerminalSelectionAIAction: (value: boolean | ((prev: boolean) => boolean)) => void;
autoLlmTitle: boolean;
setAutoLlmTitle: (value: boolean | ((prev: boolean) => boolean)) => void;
titleModel: TitleModelConfig | null;
setTitleModel: (config: TitleModelConfig | null) => void;
agentProviderMap: Record<string, string>;
agentModelMap: Record<string, string>;
}
// ---------------------------------------------------------------------------
@@ -188,7 +196,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
removeProvider,
activeProviderId,
setActiveProviderId,
activeModelId: _activeModelId,
activeModelId,
setActiveModelId,
globalPermissionMode,
setGlobalPermissionMode,
@@ -216,6 +224,12 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
setQuickMessages,
showTerminalSelectionAIAction,
setShowTerminalSelectionAIAction,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
agentProviderMap,
agentModelMap,
}) => {
const {
permissionGrants,
@@ -1369,6 +1383,35 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
<span className="text-xs text-muted-foreground">{t('ai.chatHistory.messageCap.unit')}</span>
</div>
</SettingRow>
<SettingRow
anchorId="ai-chat-history-auto-llm-title"
label={t('ai.chatHistory.autoLlmTitle')}
description={t('ai.chatHistory.autoLlmTitle.description')}
>
<Toggle
checked={autoLlmTitle}
onChange={setAutoLlmTitle}
ariaLabel={t('ai.chatHistory.autoLlmTitle')}
/>
</SettingRow>
{autoLlmTitle && (
<SettingRow
anchorId="ai-chat-history-title-model"
label={t('ai.chatHistory.titleModel')}
description={t('ai.chatHistory.titleModel.description')}
>
<TitleModelPicker
providers={providers}
activeProviderId={activeProviderId}
activeModelId={activeModelId}
agentProviderMap={agentProviderMap}
agentModelMap={agentModelMap}
value={titleModel}
onChange={setTitleModel}
t={t}
/>
</SettingRow>
)}
</SettingCard>
</SettingsSection>
@@ -68,6 +68,8 @@ function SettingsAppearanceTab(props: {
setShowSftpTab: (enabled: boolean) => void;
showHostTreeSidebar: boolean;
setShowHostTreeSidebar: (enabled: boolean) => void;
removeTopTabsDragArea: boolean;
setRemoveTopTabsDragArea: (enabled: boolean) => void;
windowOpacity: number;
setWindowOpacity: (opacity: number) => void;
windowBackgroundBlur: boolean;
@@ -141,6 +143,8 @@ function SettingsAppearanceTab(props: {
setShowSftpTab,
showHostTreeSidebar,
setShowHostTreeSidebar,
removeTopTabsDragArea,
setRemoveTopTabsDragArea,
windowOpacity,
setWindowOpacity,
windowBackgroundBlur,
@@ -525,6 +529,13 @@ function SettingsAppearanceTab(props: {
>
<Toggle checked={showHostTreeSidebar} onChange={setShowHostTreeSidebar} />
</SettingRow>
<SettingRow
anchorId="appearance-vault-remove-top-tabs-drag-area"
label={t('settings.vault.removeTopTabsDragArea')}
description={t('settings.vault.removeTopTabsDragAreaDesc')}
>
<Toggle checked={removeTopTabsDragArea} onChange={setRemoveTopTabsDragArea} />
</SettingRow>
<SettingRow
anchorId="appearance-vault-auto-import-known-hosts"
label={t('settings.vault.autoImportSystemKnownHosts')}
@@ -26,6 +26,7 @@ import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"
import { Button } from "../../ui/button";
import { ConfirmDialog } from "../../ui/confirm-dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip";
import { ExternalEditorSettingsSection } from "./ExternalEditorSettingsSection";
import {
SectionHeader,
SettingCard,
@@ -384,6 +385,8 @@ export default function SettingsFileAssociationsTab() {
</SettingRow>
</SettingCard>
<ExternalEditorSettingsSection />
<SectionHeader title={t('settings.sftp.defaultOpener')} />
<SettingCard>
<SettingRow
@@ -0,0 +1,198 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { getLoadedLocaleMessages, loadLocaleMessages } from "../../../../application/i18n/messages.ts";
import type { ProviderConfig } from "../../../../infrastructure/ai/types.ts";
import { createDomRenderer, dispatchDomEvent, installDomEnvironment } from "../../../test-support/renderReactDom.tsx";
import {
buildTitleModelPickerViewModel,
TITLE_MODEL_INHERIT_VALUE,
} from "./titleModelPickerViewModel.ts";
await loadLocaleMessages("en");
const enMessages = getLoadedLocaleMessages("en")!;
const t = (key: string) => {
const hit = enMessages[key as keyof typeof enMessages];
return typeof hit === "string" ? hit : key;
};
const firstProvider: ProviderConfig = {
id: "p-first",
providerId: "openai",
name: "DeepSeek Cheap",
enabled: true,
defaultModel: "deepseek-chat",
};
const cattyProvider: ProviderConfig = {
id: "p-catty",
providerId: "anthropic",
name: "Claude Main",
enabled: true,
defaultModel: "claude-sonnet-4",
};
const disabledProvider: ProviderConfig = {
id: "p-off",
providerId: "openai",
name: "Disabled Provider",
enabled: false,
defaultModel: "gpt-4o-mini",
};
const customEmptyProvider: ProviderConfig = {
id: "p-custom-empty",
providerId: "custom",
name: "Custom Empty",
enabled: true,
defaultModel: "",
};
function installRadixGlobals(dom: ReturnType<typeof installDomEnvironment>) {
const globalAsRecord = globalThis as Record<string, unknown>;
const saved = new Map<string, { existed: boolean; value: unknown }>();
const setGlobal = (key: string, value: unknown) => {
saved.set(key, { existed: Object.prototype.hasOwnProperty.call(globalAsRecord, key), value: globalAsRecord[key] });
globalAsRecord[key] = value;
};
for (const key of [
"MutationObserver", "NodeFilter", "Element", "HTMLElement", "HTMLInputElement",
"HTMLTextAreaElement", "HTMLButtonElement", "HTMLAnchorElement", "HTMLSelectElement",
"DocumentFragment", "Text", "CharacterData", "ShadowRoot", "SVGElement", "DOMRect",
] as const) {
const winValue = (dom.window as unknown as Record<string, unknown>)[key];
if (globalAsRecord[key] == null && winValue != null) setGlobal(key, winValue);
}
if (globalAsRecord.PointerEvent == null) setGlobal("PointerEvent", dom.window.MouseEvent);
if (globalAsRecord.ResizeObserver == null) {
setGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
}
if (globalAsRecord.requestAnimationFrame == null) {
setGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0));
}
if (globalAsRecord.cancelAnimationFrame == null) {
setGlobal("cancelAnimationFrame", (id: ReturnType<typeof setTimeout>) => clearTimeout(id));
}
const proto = dom.window.HTMLElement.prototype as unknown as Record<string, unknown>;
if (typeof proto.hasPointerCapture !== "function") proto.hasPointerCapture = () => false;
if (typeof proto.releasePointerCapture !== "function") proto.releasePointerCapture = () => {};
if (typeof proto.setPointerCapture !== "function") proto.setPointerCapture = () => {};
if (typeof proto.scrollIntoView !== "function") proto.scrollIntoView = () => {};
return () => {
for (const [key, entry] of saved) {
if (entry.existed) globalAsRecord[key] = entry.value;
else delete globalAsRecord[key];
}
};
}
test("null titleModel represents 'Use current Catty model' and reflects Catty's effective model instead of providers[0]", () => {
const vm = buildTitleModelPickerViewModel({
providers: [firstProvider, cattyProvider],
activeProviderId: firstProvider.id,
activeModelId: "deepseek-chat",
agentProviderMap: { catty: cattyProvider.id },
agentModelMap: { catty: "claude-opus-4" },
value: null,
t,
});
assert.equal(vm.mode, "inherit");
assert.equal(vm.providerSelectValue, TITLE_MODEL_INHERIT_VALUE);
assert.equal(vm.providerOptions[0].value, TITLE_MODEL_INHERIT_VALUE);
assert.equal(vm.providerOptions[0].label, t("ai.chatHistory.titleModel.useCurrentCatty"));
assert.equal(vm.inheritedLabel, "Claude Main · claude-opus-4");
});
test("explicit disabled or missing titleModel stays visible as unavailable rather than pretending to inherit", () => {
const vm = buildTitleModelPickerViewModel({
providers: [firstProvider, disabledProvider],
activeProviderId: firstProvider.id,
activeModelId: "deepseek-chat",
agentProviderMap: {},
agentModelMap: {},
value: { providerId: disabledProvider.id, modelId: "gpt-4o-mini" },
t,
});
assert.equal(vm.mode, "explicit");
assert.equal(vm.providerSelectValue, disabledProvider.id);
const unavailable = vm.providerOptions.find((opt) => opt.value === disabledProvider.id);
assert.ok(unavailable?.disabled);
assert.match(unavailable?.label ?? "", /Unavailable/);
});
test("TitleModelPicker lets user pick providers[0] from inherit mode, revert to null, and avoids saving empty modelId", async () => {
const dom = installDomEnvironment();
const restoreGlobals = installRadixGlobals(dom);
try {
const { TitleModelPicker } = await import("./TitleModelPicker.tsx");
const changes: Array<{ providerId: string; modelId: string } | null> = [];
const renderer = await createDomRenderer(dom.document);
const renderPicker = async (value: { providerId: string; modelId: string } | null) => {
await renderer.render(
<TitleModelPicker
providers={[firstProvider, cattyProvider, customEmptyProvider]}
activeProviderId={cattyProvider.id}
activeModelId="claude-sonnet-4"
agentProviderMap={{ catty: cattyProvider.id }}
agentModelMap={{ catty: "claude-opus-4" }}
value={value}
onChange={(next) => changes.push(next)}
t={t}
/>,
);
};
await renderPicker(null);
const inheritedSummary = renderer.container.querySelector('[data-section="ai-title-model-inherited"]');
assert.equal(inheritedSummary?.textContent, "Claude Main · claude-opus-4");
// Open provider select and choose providers[0] ("DeepSeek Cheap").
const triggers = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
assert.equal(triggers.length, 1, "model picker hidden while inheriting Catty model");
assert.ok((triggers[0].textContent ?? "").includes(t("ai.chatHistory.titleModel.useCurrentCatty")));
await dispatchDomEvent(triggers[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
const options = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'));
const deepseekOption = options.find((el) => (el.textContent ?? "").includes("DeepSeek Cheap"));
assert.ok(deepseekOption);
await dispatchDomEvent(deepseekOption, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(changes, [{ providerId: "p-first", modelId: "deepseek-chat" }]);
// Re-render with an explicit custom modelId not in seed catalog -> still renders its label.
await renderPicker({ providerId: "p-first", modelId: "custom-tiny-model" });
const triggersExplicit = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
assert.equal(triggersExplicit.length, 2);
assert.ok((triggersExplicit[1].textContent ?? "").includes("custom-tiny-model"));
// Selecting a provider with no defaultModel/seed models does not persist empty modelId.
await dispatchDomEvent(triggersExplicit[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
const emptyOpt = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'))
.find((el) => (el.textContent ?? "").includes("Custom Empty"));
assert.ok(emptyOpt);
await dispatchDomEvent(emptyOpt, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
assert.equal(changes.length, 1, "does not persist incomplete { providerId, modelId: '' }");
// Reverting to "Use current Catty model" emits null.
const triggersAfterPending = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
await dispatchDomEvent(triggersAfterPending[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
const inheritOpt = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'))
.find((el) => (el.textContent ?? "").includes(t("ai.chatHistory.titleModel.useCurrentCatty")));
assert.ok(inheritOpt);
await dispatchDomEvent(inheritOpt, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((r) => setTimeout(r, 30));
assert.equal(changes.at(-1), null);
} finally {
restoreGlobals();
dom.cleanup();
}
});
@@ -0,0 +1,133 @@
import React, { useEffect, useState } from "react";
import type { TitleModelConfig } from "../../../../domain/aiSessionTitle";
import { seedProviderModelCatalog } from "../../../../infrastructure/ai/cattyProviderModels";
import type { ProviderConfig } from "../../../../infrastructure/ai/types";
import { useProviderModelCatalog } from "../../../ai/useProviderModelCatalog";
import { Select } from "../../settings-ui";
import {
buildTitleModelPickerViewModel,
TITLE_MODEL_INHERIT_VALUE,
} from "./titleModelPickerViewModel";
export {
buildTitleModelPickerViewModel,
TITLE_MODEL_INHERIT_VALUE,
type TitleModelPickerOption,
type TitleModelPickerViewModel,
} from "./titleModelPickerViewModel";
export interface TitleModelPickerProps {
providers: ProviderConfig[];
activeProviderId: string;
activeModelId: string;
agentProviderMap: Record<string, string>;
agentModelMap: Record<string, string>;
value: TitleModelConfig | null;
onChange: (config: TitleModelConfig | null) => void;
t: (key: string) => string;
}
/** Provider + model pickers for the one-shot title model. */
export const TitleModelPicker: React.FC<TitleModelPickerProps> = ({
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
value,
onChange,
t,
}) => {
// Hold a newly chosen provider locally until it has a concrete non-empty
// modelId so incomplete configs are never persisted to storage.
const [pendingProviderId, setPendingProviderId] = useState<string | null>(null);
useEffect(() => {
setPendingProviderId(null);
}, [value]);
const vm = buildTitleModelPickerViewModel({
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
value,
pendingProviderId,
t,
});
const catalog = useProviderModelCatalog(
vm.selectedEnabledProvider,
Boolean(vm.selectedEnabledProvider),
);
if (vm.mode === "none") {
return (
<span className="text-xs text-muted-foreground">
{t("ai.chatHistory.titleModel.none")}
</span>
);
}
const baseModelOptions = catalog.models.map((model) => ({
value: model.id,
label: model.name || model.id,
}));
const modelOptions = vm.activeModelId
&& !baseModelOptions.some((option) => option.value === vm.activeModelId)
? [{ value: vm.activeModelId, label: vm.activeModelId }, ...baseModelOptions]
: baseModelOptions;
return (
<div className="flex flex-wrap items-center justify-end gap-2">
<Select
value={vm.providerSelectValue}
options={vm.providerOptions}
onChange={(nextValue) => {
if (nextValue === TITLE_MODEL_INHERIT_VALUE) {
setPendingProviderId(null);
onChange(null);
return;
}
const provider = providers.find((item) => item.id === nextValue && Boolean(item.enabled));
if (!provider) return;
const fallbackModelId = (provider.defaultModel ?? "").trim()
|| seedProviderModelCatalog(provider).models[0]?.id
|| "";
if (fallbackModelId) {
setPendingProviderId(null);
onChange({ providerId: provider.id, modelId: fallbackModelId });
} else {
setPendingProviderId(provider.id);
}
}}
className="w-48"
placeholder={t("ai.chatHistory.titleModel.providerPlaceholder")}
/>
{vm.mode === "inherit" ? (
vm.inheritedLabel ? (
<span
data-section="ai-title-model-inherited"
className="text-xs text-muted-foreground max-w-48 truncate"
title={vm.inheritedLabel}
>
{vm.inheritedLabel}
</span>
) : null
) : (
<Select
value={vm.activeModelId}
options={modelOptions}
onChange={(modelId) => {
if (!vm.selectedEnabledProvider || !modelId) return;
setPendingProviderId(null);
onChange({ providerId: vm.selectedEnabledProvider.id, modelId });
}}
className="w-48"
disabled={!vm.selectedEnabledProvider || (catalog.loading && !catalog.fetched)}
placeholder={t("ai.chatHistory.titleModel.modelPlaceholder")}
/>
)}
</div>
);
};
@@ -0,0 +1,114 @@
import { resolveCattyEffectiveModel, type TitleModelConfig } from "../../../../domain/aiSessionTitle";
import type { ProviderConfig } from "../../../../infrastructure/ai/types";
export const TITLE_MODEL_INHERIT_VALUE = "__netcatty_inherit_catty__";
export interface TitleModelPickerOption {
value: string;
label: string;
disabled?: boolean;
}
export interface TitleModelPickerViewModel {
mode: "none" | "inherit" | "explicit";
providerSelectValue: string;
providerOptions: TitleModelPickerOption[];
selectedEnabledProvider: ProviderConfig | undefined;
activeModelId: string;
inheritedLabel: string | null;
}
/** Pure derivation for TitleModelPicker options and inherited summary. */
export function buildTitleModelPickerViewModel(input: {
providers: readonly ProviderConfig[];
activeProviderId: string;
activeModelId: string;
agentProviderMap: Readonly<Record<string, string>>;
agentModelMap: Readonly<Record<string, string>>;
value: TitleModelConfig | null;
pendingProviderId?: string | null;
t: (key: string) => string;
}): TitleModelPickerViewModel {
const {
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
value,
pendingProviderId = null,
t,
} = input;
const enabledProviders = providers.filter((provider) => Boolean(provider.enabled));
const inherited = resolveCattyEffectiveModel({
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
});
const inheritedIsUsable = Boolean(
inherited.provider && inherited.provider.enabled && inherited.modelId,
);
const inheritedLabel = inheritedIsUsable && inherited.provider
? `${inherited.provider.name} · ${inherited.modelId}`
: null;
const targetProviderId = pendingProviderId ?? value?.providerId ?? null;
if (!targetProviderId && enabledProviders.length === 0) {
return {
mode: "none",
providerSelectValue: TITLE_MODEL_INHERIT_VALUE,
providerOptions: [],
selectedEnabledProvider: undefined,
activeModelId: "",
inheritedLabel: null,
};
}
const providerOptions: TitleModelPickerOption[] = [
{
value: TITLE_MODEL_INHERIT_VALUE,
label: t("ai.chatHistory.titleModel.useCurrentCatty"),
},
...enabledProviders.map((provider) => ({
value: provider.id,
label: provider.name,
})),
];
if (!targetProviderId) {
return {
mode: "inherit",
providerSelectValue: TITLE_MODEL_INHERIT_VALUE,
providerOptions,
selectedEnabledProvider: undefined,
activeModelId: "",
inheritedLabel,
};
}
const selectedEnabledProvider = enabledProviders.find((provider) => provider.id === targetProviderId);
if (!selectedEnabledProvider) {
const savedProvider = providers.find((provider) => provider.id === targetProviderId);
providerOptions.push({
value: targetProviderId,
label: `${savedProvider?.name ?? targetProviderId} (${t("ai.chatHistory.titleModel.unavailable")})`,
disabled: true,
});
}
const resolvedModelId = pendingProviderId
? ""
: (value?.modelId?.trim() || "");
return {
mode: "explicit",
providerSelectValue: targetProviderId,
providerOptions,
selectedEnabledProvider,
activeModelId: resolvedModelId,
inheritedLabel,
};
}
+1
View File
@@ -66,6 +66,7 @@ export interface SftpPaneCallbacks {
onOpenFile?: (entry: SftpFileEntry, fullPath?: string) => void;
onOpenFileWithSystemDefault?: (entry: SftpFileEntry, fullPath?: string) => void;
onOpenFileWith?: (entry: SftpFileEntry, fullPath?: string) => void; // Always show opener dialog
onOpenInExternalEditor?: (entry: SftpFileEntry, fullPath?: string, host?: Host) => void; // Open remote path in configured external IDE (e.g. Zed)
onDownloadFile?: (entry: SftpFileEntry, fullPath?: string) => void; // Download to local filesystem
onDownloadFiles?: (entries: SftpFileEntry[], fullPaths?: string[]) => void; // Batch download — picks one target directory for remote panes
onExtractArchive?: (entry: SftpFileEntry, fullPath?: string) => void | Promise<void>;
@@ -0,0 +1,195 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { createEmptyPane } from "../../application/state/sftp/types";
import type { SftpFileEntry } from "../../types";
import { ContextMenuContent } from "../ui/context-menu";
import { TooltipProvider } from "../ui/tooltip";
import { installDomEnvironment } from "../test-support/renderReactDom";
import { SftpPaneFileList } from "./SftpPaneFileList";
import { useSftpPaneTreeContextMenu } from "./useSftpPaneTreeContextMenu";
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
after(() => { environment.IS_REACT_ACT_ENVIRONMENT = previous; });
type MenuItem = React.ReactElement<{ children?: React.ReactNode; onClick: () => void }>;
function findMenuItem(children: React.ReactNode, label: string) {
return React.Children.toArray(children).find((child): child is MenuItem =>
React.isValidElement<{ children?: React.ReactNode }>(child)
&& React.Children.toArray(child.props.children).includes(label),
);
}
const folder: SftpFileEntry = {
name: "project",
type: "directory",
size: 0,
sizeFormatted: "0 B",
lastModified: 0,
lastModifiedFormatted: "",
};
const file: SftpFileEntry = {
name: "main.rs",
type: "file",
size: 120,
sizeFormatted: "120 B",
lastModified: 0,
lastModifiedFormatted: "",
};
const parentEntry: SftpFileEntry = {
name: "..",
type: "directory",
size: 0,
sizeFormatted: "0 B",
lastModified: 0,
lastModifiedFormatted: "",
};
test("SFTP list context menu exposes Open in Zed for remote directories and files, and hides on local panes", async (t) => {
const dom = installDomEnvironment();
const noop = () => {};
const opened: string[] = [];
const tFn = (key: string, params?: Record<string, unknown>) =>
key === "sftp.context.openInExternalEditor" ? `Open in ${params?.editor ?? ""}` : key;
let props: React.ComponentProps<typeof SftpPaneFileList> = {
t: tFn,
pane: {
...createEmptyPane("pane-ext-editor"),
connection: { id: "conn", hostId: "host", hostLabel: "Host", isLocal: false, status: "connected", currentPath: "/home/dev" },
selectedFiles: new Set(),
files: [folder, file],
},
side: "left",
isPaneFocused: true,
sorting: {
sortField: "name",
sortOrder: "asc",
directoriesFirst: true,
columnWidths: { name: 50, modified: 24, size: 7, type: 9, owner: 10 },
visibleColumns: { name: true, modified: true, size: true, type: true, owner: true },
handleSort: noop,
handleResizeStart: noop,
toggleColumnVisibility: noop,
toggleDirectoriesFirst: noop,
},
fileListRef: { current: null },
handleFileListScroll: noop,
shouldVirtualize: false,
totalHeight: 0,
sortedDisplayFiles: [folder, file],
isDragOverPane: false,
draggedFiles: null,
onRefresh: noop,
onNavigateTo: noop,
onClearSelection: noop,
setShowNewFolderDialog: noop,
setShowNewFileDialog: noop,
getNextUntitledName: () => "",
setNewFileName: noop,
setFileNameError: noop,
dragOverEntry: null,
handleRowSelect: noop,
handleRowOpen: noop,
handleFileDragStart: noop,
onDragEnd: noop,
handleEntryDragOver: noop,
handleRowDragLeave: noop,
handleEntryDrop: noop,
onCopyToOtherPane: noop,
onMoveEntriesToPath: async () => {},
openRenameDialog: noop,
openDeleteConfirm: noop,
onOpenInExternalEditor: (entry) => opened.push(entry.name),
externalEditorLabel: "Zed",
rowHeight: 28,
visibleRows: [],
};
const render = () => React.createElement(TooltipProvider, null, React.createElement(SftpPaneFileList, props));
let renderer!: ReactTestRenderer;
await act(async () => { renderer = create(render()); });
t.after(async () => {
await act(async () => { renderer.unmount(); });
dom.cleanup();
environment.IS_REACT_ACT_ENVIRONMENT = true;
});
const actions = () => renderer.root.findAllByType(ContextMenuContent)
.map((menu) => findMenuItem(menu.props.children, "Open in Zed"))
.filter((item): item is MenuItem => !!item);
assert.equal(actions().length, 2, "both remote directory and remote file should show Open in Zed");
actions()[0].props.onClick();
actions()[1].props.onClick();
assert.deepEqual(opened, ["project", "main.rs"]);
// Local pane must not show remote external editor action.
props = { ...props, isLocal: true, pane: { ...props.pane, connection: { ...props.pane.connection!, isLocal: true } } };
await act(async () => { renderer.update(render()); });
assert.equal(actions().length, 0, "local pane should not expose remote external editor action");
});
test("SFTP tree context menu exposes Open in Zed for remote entries and hides on parent entry or local pane", async (t) => {
const opened: Array<{ name: string; path: string }> = [];
const emptyRef = { current: undefined };
const tFn = (key: string, params?: Record<string, unknown>) =>
key === "sftp.context.openInExternalEditor" ? `Open in ${params?.editor ?? ""}` : key;
let props: Parameters<typeof useSftpPaneTreeContextMenu>[0] = {
contextTarget: { entry: folder, entryPath: "/home/dev/project" },
pane: { connection: { id: "conn", isLocal: false } },
tRef: { current: tFn },
onOpenFileWithSystemDefaultRef: emptyRef,
onOpenFileWithRef: emptyRef,
onOpenInExternalEditorRef: {
current: (entry: SftpFileEntry, fullPath: string) => opened.push({ name: entry.name, path: fullPath }),
},
externalEditorLabel: "Zed",
onEditFileRef: emptyRef,
onDownloadFileRef: emptyRef,
onDownloadFilesRef: emptyRef,
entryByPathRef: { current: new Map() },
onExtractArchiveRef: emptyRef,
onEditPermissionsRef: emptyRef,
onDuplicateEntriesRef: emptyRef,
toTransferSources: () => [],
onCreateArchiveRef: emptyRef,
getActionPaths: (p: string) => [p],
};
let menu: React.ReactNode;
function Probe() {
menu = useSftpPaneTreeContextMenu(props);
return null;
}
let renderer!: ReactTestRenderer;
await act(async () => { renderer = create(React.createElement(Probe)); });
t.after(async () => { await act(async () => { renderer.unmount(); }); });
const action = () => findMenuItem((menu as React.ReactElement<{ children: React.ReactNode }>).props.children, "Open in Zed");
assert.ok(action(), "remote folder should expose Open in Zed");
action()!.props.onClick();
assert.deepEqual(opened, [{ name: "project", path: "/home/dev/project" }]);
// Remote file
props = { ...props, contextTarget: { entry: file, entryPath: "/home/dev/project/main.rs" } };
await act(async () => { renderer.update(React.createElement(Probe)); });
assert.ok(action(), "remote file should expose Open in Zed");
action()!.props.onClick();
assert.deepEqual(opened[1], { name: "main.rs", path: "/home/dev/project/main.rs" });
// Synthetic parent ".." row
props = { ...props, contextTarget: { entry: parentEntry, entryPath: "/home/dev" } };
await act(async () => { renderer.update(React.createElement(Probe)); });
assert.equal(action(), undefined, "synthetic .. row must not expose Open in Zed");
// Local pane
props = { ...props, pane: { connection: { id: "local", isLocal: true } }, contextTarget: { entry: folder, entryPath: "/tmp" } };
await act(async () => { renderer.update(React.createElement(Probe)); });
assert.equal(action(), undefined, "local pane must not expose Open in Zed");
});
+13 -1
View File
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AppWindow, Archive, ArrowDown, ArrowRight, ArrowUp, ChevronDown, ClipboardCopy, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderPlus, Loader2, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Unplug, Upload } from "lucide-react";
import { AppWindow, Archive, ArrowDown, ArrowRight, ArrowUp, ChevronDown, ClipboardCopy, Code2, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderPlus, Loader2, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Unplug, Upload } from "lucide-react";
import { Button } from "../ui/button";
import {
ContextMenu,
@@ -65,6 +65,8 @@ interface SftpPaneFileListProps {
onMoveEntriesToPath: (sourcePaths: string[], targetPath: string) => Promise<void>;
onOpenFileWithSystemDefault?: (entry: SftpFileEntry) => void;
onOpenFileWith?: (entry: SftpFileEntry) => void;
onOpenInExternalEditor?: (entry: SftpFileEntry) => void;
externalEditorLabel?: string;
onEditFile?: (entry: SftpFileEntry) => void;
onDownloadFile?: (entry: SftpFileEntry) => void;
onDownloadFiles?: (entries: SftpFileEntry[]) => void;
@@ -159,6 +161,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
onMoveEntriesToPath,
onOpenFileWithSystemDefault,
onOpenFileWith,
onOpenInExternalEditor,
externalEditorLabel,
onEditFile,
onDownloadFile,
onDownloadFiles,
@@ -354,6 +358,12 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
<ArrowRight size={14} className="mr-2" /> {t("sftp.context.navigateTo")}
</ContextMenuItem>
)}
{!isLocal && onOpenInExternalEditor && (
<ContextMenuItem onClick={() => onOpenInExternalEditor(entry)}>
<Code2 size={14} className="mr-2" />{" "}
{t("sftp.context.openInExternalEditor", { editor: externalEditorLabel || "Zed" })}
</ContextMenuItem>
)}
{!isNavigableDirectory(entry) && onOpenFileWithSystemDefault && (
<ContextMenuItem onClick={() => onOpenFileWithSystemDefault(entry)}>
<AppWindow size={14} className="mr-2" />{" "}
@@ -560,6 +570,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
onNavigateTo,
onOpenFileWithSystemDefault,
onOpenFileWith,
onOpenInExternalEditor,
externalEditorLabel,
onRefresh,
onUploadExternalFileList,
onUploadExternalFolder,
+6
View File
@@ -64,6 +64,8 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
onReceiveFromOtherPane,
onOpenFileWithSystemDefault,
onOpenFileWith,
onOpenInExternalEditor,
externalEditorLabel,
onEditFile,
onDownloadFile,
onDownloadFiles,
@@ -227,6 +229,8 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
onOpenFileWithSystemDefaultRef.current = onOpenFileWithSystemDefault;
const onOpenFileWithRef = useRef(onOpenFileWith);
onOpenFileWithRef.current = onOpenFileWith;
const onOpenInExternalEditorRef = useRef(onOpenInExternalEditor);
onOpenInExternalEditorRef.current = onOpenInExternalEditor;
const onEditFileRef = useRef(onEditFile);
onEditFileRef.current = onEditFile;
const onDownloadFileRef = useRef(onDownloadFile);
@@ -978,6 +982,8 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
onNavigateToRef,
onOpenFileWithSystemDefaultRef,
onOpenFileWithRef,
onOpenInExternalEditorRef,
externalEditorLabel,
onEditFileRef,
onDownloadFileRef,
onDownloadFilesRef,
@@ -23,6 +23,8 @@ export interface SftpPaneTreeViewProps {
onReceiveFromOtherPane: (files: SftpTransferSource[]) => void;
onOpenFileWithSystemDefault?: (entry: SftpFileEntry, fullPath?: string) => void;
onOpenFileWith?: (entry: SftpFileEntry, fullPath?: string) => void;
onOpenInExternalEditor?: (entry: SftpFileEntry, fullPath?: string) => void;
externalEditorLabel?: string;
onEditFile?: (entry: SftpFileEntry, fullPath?: string) => void;
onDownloadFile?: (entry: SftpFileEntry, fullPath?: string) => void;
onDownloadFiles?: (entries: SftpFileEntry[], fullPaths?: string[]) => void;
+18
View File
@@ -1,5 +1,7 @@
import React, { memo, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition } from "react";
import { useI18n } from "../../application/i18n/I18nProvider";
import { useExternalEditorSettings } from "../../application/state/useExternalEditorSettings";
import { getExternalEditorLabel } from "../../domain/externalEditor";
import { logger } from "../../lib/logger";
import { useRenderTracker } from "../../lib/useRenderTracker";
import { cn } from "../../lib/utils";
@@ -124,7 +126,19 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
const writableHosts = useSftpWritableHosts();
const { t } = useI18n();
const { settings: externalEditorSettings } = useExternalEditorSettings();
const externalEditorLabel = getExternalEditorLabel(externalEditorSettings.defaultEditor);
const hostId = pane.connection?.hostId;
const paneHost = useMemo(
() => (hostId ? hosts.find((h) => h.id === hostId) : undefined),
[hostId, hosts],
);
const handleOpenInExternalEditor = useMemo(() => {
if (pane.connection?.isLocal || !callbacks.onOpenInExternalEditor) return undefined;
return (entry: Parameters<NonNullable<typeof callbacks.onOpenInExternalEditor>>[0], fullPath?: string) => {
callbacks.onOpenInExternalEditor?.(entry, fullPath, paneHost);
};
}, [callbacks, pane.connection?.isLocal, paneHost]);
const { hostViewMode, setHostViewMode: saveHostViewMode } = useSftpHostViewMode(hostId);
const [, startTransition] = useTransition();
const [showFilterBar, setShowFilterBar] = useState(false);
@@ -668,6 +682,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
onReceiveFromOtherPane={callbacks.onReceiveFromOtherPane}
onOpenFileWithSystemDefault={callbacks.onOpenFileWithSystemDefault}
onOpenFileWith={callbacks.onOpenFileWith}
onOpenInExternalEditor={handleOpenInExternalEditor}
externalEditorLabel={externalEditorLabel}
onEditFile={callbacks.onEditFile}
onDownloadFile={callbacks.onDownloadFile}
onDownloadFiles={callbacks.onDownloadFiles}
@@ -724,6 +740,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
onMoveEntriesToPath={handleMoveEntriesToPath}
onOpenFileWithSystemDefault={callbacks.onOpenFileWithSystemDefault}
onOpenFileWith={callbacks.onOpenFileWith}
onOpenInExternalEditor={handleOpenInExternalEditor}
externalEditorLabel={externalEditorLabel}
onEditFile={callbacks.onEditFile}
onDownloadFile={callbacks.onDownloadFile}
onDownloadFiles={callbacks.onDownloadFiles}
+69 -2
View File
@@ -1,5 +1,10 @@
import { useCallback, useRef, useState } from "react";
import type { SftpFileEntry } from "../../../types";
import type { Host, SftpFileEntry } from "../../../types";
import { getExternalEditorLabel } from "../../../domain/externalEditor";
import {
getExternalEditorSettingsSnapshot,
launchRemoteExternalEditor,
} from "../../../application/state/useExternalEditorSettings";
import type { TransferStatus } from "../../../domain/models";
import { getParentPath, joinTransferTargetPath } from "../../../application/state/sftp/utils";
import {
@@ -12,7 +17,10 @@ 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 {
getSftpDownloadDialogDirectoryOptions,
rememberSftpDownloadDirectory,
} from "../../../application/state/sftp/downloadLocation";
import { reportSftpUploadResults } from "../reportSftpUploadResults";
import { editorTabStore } from "../../../application/state/editorTabStore";
import { popOutEditorTab } from "../../../application/state/editorWindowClient";
@@ -361,6 +369,59 @@ export const useSftpViewFileOps = ({
[handleOpenFileWithForSide],
);
const handleOpenInExternalEditorForSide = useCallback(
(side: "left" | "right", entry: SftpFileEntry, fullPath?: string, host?: Host) => {
const pane = side === "left" ? sftpRef.current.leftPane : sftpRef.current.rightPane;
const conn = pane.connection;
if (!conn || conn.isLocal) return;
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(conn.currentPath, entry.name);
const settings = getExternalEditorSettingsSnapshot();
const editorLabel = getExternalEditorLabel(settings.defaultEditor);
const sftpId = getSftpIdForConnection?.(conn.id);
void launchRemoteExternalEditor({
host: {
hostId: host?.id ?? conn.hostId,
hostname: conn.hostname ?? host?.hostname,
port: conn.port ?? host?.port,
username: conn.username ?? host?.username,
label: host?.label ?? conn.hostLabel,
},
remotePath: resolvedFullPath,
kind: isNavigableDirectory(entry) ? "dir" : "file",
sessionId: conn.sourceSessionId,
sftpId,
settings,
}).then(() => {
toast.success(
t("terminal.externalEditor.opened", { editor: editorLabel, path: resolvedFullPath }),
editorLabel,
);
}).catch((error) => {
logger.error("[SftpView] Failed to open remote path in external editor:", error);
toast.error(
error instanceof Error
? error.message
: t("terminal.externalEditor.failed", { editor: editorLabel }),
editorLabel,
);
});
},
[getSftpIdForConnection, sftpRef, t],
);
const onOpenInExternalEditorLeft = useCallback(
(entry: SftpFileEntry, fullPath?: string, host?: Host) =>
handleOpenInExternalEditorForSide("left", entry, fullPath, host),
[handleOpenInExternalEditorForSide],
);
const onOpenInExternalEditorRight = useCallback(
(entry: SftpFileEntry, fullPath?: string, host?: Host) =>
handleOpenInExternalEditorForSide("right", entry, fullPath, host),
[handleOpenInExternalEditorForSide],
);
const handleUploadExternalFilesForSide = useCallback(
async (side: "left" | "right", dataTransfer: DataTransfer, targetPath?: string) => {
try {
@@ -469,6 +530,7 @@ export const useSftpViewFileOps = ({
getSftpDownloadDialogDirectoryOptions(),
);
if (!destination) return null;
rememberSftpDownloadDirectory(destination);
localDirectory = destination;
continue;
}
@@ -547,6 +609,7 @@ export const useSftpViewFileOps = ({
getSftpDownloadDialogDirectoryOptions(),
);
if (!selectedDirectory) return;
rememberSftpDownloadDirectory(selectedDirectory);
// The picker may stay open while the remote entry changes again.
const selectedSnapshot = await resolveDownloadSourceSnapshot(
@@ -601,6 +664,7 @@ export const useSftpViewFileOps = ({
getSftpDownloadDialogDirectoryOptions(),
);
if (!targetPath) return;
rememberSftpDownloadDirectory(getParentPath(targetPath));
const selectedSnapshot = await resolveDownloadSourceSnapshot(
statSftp,
@@ -793,6 +857,7 @@ export const useSftpViewFileOps = ({
getSftpDownloadDialogDirectoryOptions(),
);
if (!selectedDirectory) return;
rememberSftpDownloadDirectory(selectedDirectory);
if (parents.every((parent) => parent === parents[0]) && files.every((file) => file.type !== "symlink")) {
try {
@@ -982,6 +1047,8 @@ export const useSftpViewFileOps = ({
onOpenFileWithSystemDefaultRight,
onOpenFileWithLeft,
onOpenFileWithRight,
onOpenInExternalEditorLeft,
onOpenInExternalEditorRight,
onDownloadFileLeft,
onDownloadFileRight,
onExtractArchiveLeft,
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more