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
陈大猫 4b05b03776 docs: note that the plugin system and official plugins are still unstable (#4555) 2026-11-29 22:51:13 +08:00
陈大猫 5d5c5b0940 fix(ai): keep the turn when a privacy placeholder cannot be restored
Fixes #4562.

Unknown, stale, or cross-chat AI privacy placeholders now pass through as opaque text so the assistant turn can continue. Known same-chat aliases still restore. Tool execution and managed MCP/CLI dispatch stay fail-closed via restoreStrict.

GitHub Codex CLEAN on 5a74c2116d.
CI: lint-and-test https://github.com/binaricat/Netcatty/actions/runs/46268444968 attempt 2 green (attempt 1 was an unrelated Node test-runner deserialize flake in scripts/electron-builder-config.test.cjs). build-packages linux/mac/windows green.
Real-app Electron smoke PASS: /workspace/netcatty-smoke-shots/pr-4563-5a74c2116d-20261129-213846 — Settings text redaction and private-IP redaction saved on; unknown/foreign/stale placeholders stayed opaque; known 10.45.63.7 restored; turn continued (TURN-CONTINUED-4563); no empty retryable=false error.
2026-11-29 22:01:53 +08:00
陈大猫 549f58c653 fix(plugins): keep vault plugin pages on header double-click and view errors (#4548)
* fix(plugins): keep vault pages on view errors and ignore header double-clicks

Double-clicking a PluginDataGrid column header fired two sortChange events.
A failed host-drawn view session then called the vault unavailable fallback,
which selected Hosts and kicked the user out of the plugin workbench.

Ignore the second click of a header double-click, and when a started view
session fails, stay on the plugin page with an in-page error and Retry
instead of navigating to Hosts. Missing vault-page contributions still
fall back to Hosts.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): debounce PluginDataGrid header sort clicks

event.detail > 1 was not enough: CDP/Electron double-clicks can still
deliver two detail=1 clicks about 40ms apart, and overlapping
host-ui.update payloads disposed the view session. Ignore a second
sort click within 500ms, and warn with the dispose reason when an
update or event send fails.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): keep the last good tree on duplicate view-node updates

A PluginDataGrid header double-click can produce a host-ui.update whose
projected tree has duplicate node IDs. apply() previously mutated the
live receiver first, then hard-failed the view. Stage the batch on a
scratch receiver, reject Duplicate view node without closing the
session, and keep the last good snapshot. Forbidden mutations still
fail the view.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): hard-fail mixed policy violations and stash rejected CSS

Duplicate view-node recovery now re-validates the projected tree with
unique IDs so a batch that also contains a forbidden mutation still
closes the view. Validated CSS from a rejected duplicate update is
stashed and published on the next accepted update.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): let explicit CSS supersede a stashed pending stylesheet

If a rejected duplicate update stashed CSS, an later accepted update
that explicitly resends the last committed CSS must drop the pending
stylesheet instead of publishing it.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): apply duplicate view-node inserts as moves

RemoteReceiver leaves a stale copy when a host-ui.update inserts an
already-attached id, or a parent that re-serializes one. Rejecting the
batch kept the last good grid but desynced the producer, so a later
PluginDataGrid sort did not visually apply.

Normalize duplicate-only batches by detaching those ids first, then
apply the rewritten batch to both the scratch projection and the live
receiver. Mixed policy violations still hard-fail.

* fix(plugins): remap producer removals after rewrite detaches

rewriteDuplicateInsertBatch already detached already-attached IDs
before inserting a wrapper, but then replayed the producer's original
removal index. That index could now point at a sibling the producer
kept, so a same-tick wrap of b dropped a and later updates to a were
ignored.

Skip producer removals whose slot was already detached by the rewrite,
and shift later indices down accordingly.

* fix(plugins): remap wrap insert index after descendant detaches

RemoteMutationObserver can encode insert-at-0 when the previous sibling
was moved into the inserted wrapper. After detaching that descendant
from the same parent, honoring the stale 0 put wrapper before a, so a
later remove of wrapper at index 1 deleted a.

Bump the insert index to the hole left by a same-parent descendant
detach. Do not bump when the detached id is the insert root itself, so
ordinary moves stay intact.
2026-11-29 21:01:48 +08:00
陈大猫 3a913b8fc2 feat(plugins): forward pointer and wheel events through host-drawn views (#4556)
Host-drawn Remote DOM surfaces now translate pointerdown, pointermove,
pointerup, pointercancel, and wheel into HostDrawnViewEvent so plugin
HTML canvases can drag, pan, and zoom in the real workbench. The official
SDK dispatches PointerEvent and WheelEvent with surface-relative
coordinates.

Includes host-side pointer capture after pointerdown, move coalescing
with acknowledgedEvent backpressure, pointercancel on surface teardown,
a non-passive wheel listener on the shadow host, and native scrolling
when a scrollable ancestor or host-owned popover panel can consume the
gesture.
2026-11-29 20:14:06 +08:00
陈大猫 8cae6c5784 fix(tray): preload hidden tray panel so first right-click is not delayed (#4558)
Fixes #4557
2026-11-29 18:14:18 +08:00
陈大猫 3c4f561beb fix(rdp): send local clipboard images to the remote desktop (#4552)
* fix(rdp): send local clipboard images to the remote desktop

Fixes #4551

* fix(rdp): invalidate clipboard echo guards on format replacement

Fixes the Codex P2 on PR #4552: a later text-only or image-only clipboard must replace the remote clipboard even when one format matches a stale guard from the previous snapshot.

* fix(rdp): write mixed remote clipboard text and PNG locally

Addresses the Codex P2 on PR #4552: write mixed remote snapshots locally as both text/plain and image/png so the echo guard does not wipe remote text on refocus. Fall back to PNG, then text, if the mixed write fails.
2026-11-29 17:25:37 +08:00
陈大猫 d04bf9ce72 fix(terminal): clear full snippet label on autocomplete accept when the name has spaces (#4550)
Fixes #4549
2026-11-29 16:49:21 +08:00
陈大猫 bfe63719d8 feat(terminal): unify 1px focus and magnification borders with deterministic state (#4543) (#4545)
* feat(terminal): unify 1px focus and magnification borders with deterministic state

* fix(terminal): preserve zoom entry animation on unchanged initial ResizeObserver callback

* test(terminal): update browserPanelLifecycle vm stub for setMagnifiedPanesByTab
2026-11-29 14:45:56 +08:00
陈大猫 08f22349c1 fix(plugins): clear stale PluginDataGrid editingCell and blur timer on row removal (#4547) 2026-11-29 14:41:35 +08:00
陈大猫 c846cd6fd8 feat(vault): allow Direct (no proxy) on groups (#4442) (#4546) 2026-11-29 14:34:10 +08:00
Netcatty-Bot 2506b5d1bc Update Nix release metadata for v1.1.95 (#4536) 2026-11-29 12:50:41 +08:00
陈大猫 a24be98a6b fix(rdp): reuse MCS server public key when license request has no cert (#4542)
Related #4540
2026-11-29 12:23:04 +08:00
陈大猫 b08a1398e3 test(plugins): sync Database 0.3.2 brand fixture and list avatar assertions (#4537) 2026-11-29 09:18:47 +08:00
陈大猫 bc849a3aa2 docs(readme): add WeChat group badge linking to QR code across all READMEs (#4535) 2026-11-29 08:34:21 +08:00
陈大猫 2a48e30278 docs(readme): add official WeChat user group QR code to READMEs (#4534) 2026-11-29 08:33:05 +08:00
陈大猫 bf14ef9d8f docs(readme): add Plugin System section with marketplace, dev, and submission links across all READMEs (#4533) 2026-11-29 08:28:07 +08:00
陈大猫 0f1177a43b feat(plugins): automatically check for updates on plugin views and detail pages (#4532) 2026-11-29 08:21:19 +08:00
陈大猫 8c813a6fbd feat(plugins): unify installed and marketplace detail views with README first and permissions below (#4531) 2026-11-29 08:15:58 +08:00
陈大猫 775bd12443 feat(plugins): auto-recognize official binaricat plugins from official marketplace without hardcoded ID list (#4530) 2026-11-29 08:07:56 +08:00
陈大猫 4e161b3a5b feat(vault): remove standalone Customize Sidebar rail button and trigger via item context menu (#4529) 2026-11-29 06:21:25 +08:00
陈大猫 55906e1f46 fix(ai): recognize bracket [host path]$ prompts without a time field (#4527) (#4528)
Fixes #4527
2026-11-29 06:15:13 +08:00
陈大猫 8fd8983b4d chore(plugins): sync fallback catalog to Netcatty Database 0.3.2 (#4525) 2026-11-29 00:48:20 +08:00
陈大猫 a62c0f7f7f feat(plugins): open plugin detail directly when clicking plugin avatar or name (#4524) 2026-11-29 00:26:50 +08:00
陈大猫 92db9371e6 chore(plugins): omit verbose description from Settings installed plugins list (#4523) 2026-11-29 00:21:21 +08:00
陈大猫 0189ae996a feat(plugins): add one-click emerald Update button across installed list, cards, and detail header (#4522) 2026-11-29 00:18:18 +08:00
陈大猫 61ca623a08 fix(plugins): use Update label and emerald button style when upgrading installed plugin (#4521) 2026-11-29 00:11:03 +08:00
陈大猫 b4015f8719 feat(plugins): support theme-aware README pictures and sync Database 0.3.1 / Monitor 0.2.2 (#4520) 2026-11-28 23:50:00 +08:00
陈大猫 880e11eff5 fix(rdp): emit use redirection server name in system-client .rdp files
Related #4514

Add use redirection server name:i:1 to default system-client .rdp writers.

This is only a partial step for #4514 and should leave that issue open.
2026-11-28 23:49:46 +08:00
陈大猫 dc044961b5 fix(plugins): add install spinner, hide Install once installed, toggle Enable/Enabled (#4519) 2026-11-28 23:44:23 +08:00
陈大猫 873c8cfb52 feat(plugins): align official badge, render HTML/table READMEs, add gauge icon, streamline install UX (#4517) 2026-11-28 23:32:27 +08:00
bincxz cd0c24f3a4 feat(plugins): support verified remote catalog brand icons and sync official catalog 2026-11-28 23:06:51 +08:00
bincxz 93a3a37987 chore(plugins): remove duplicate in-tree plugins/netcatty-monitor directory 2026-11-28 21:41:47 +08:00
bincxz 2df6aad44b fix(lint): fix netcatty-monitor ESLint errors and configure Node globals for plugin scripts 2026-11-28 21:35:45 +08:00
bincxz 5b669539c7 build(packaging): prune unused bare-*, claude-agent-sdk, native source, and preload source payloads from release bundles 2026-11-28 21:35:45 +08:00
Joseph Hau a4cacc4bc5 fix: keep WSL directory navigation working across windows 2026-11-28 21:35:29 +08:00
Joseph Hau f491676ff9 feat: support directory picker in WSL Bash 2026-11-28 21:35:29 +08:00
pyroch f213300c81 fix(vault): restore host search focus after clearing 2026-11-28 21:27:42 +08:00
pyroch 0ef7cb3d3c feat(vault): add a clear button to host search 2026-11-28 21:27:42 +08:00
bincxz 24e07bee97 fix(plugins): enforce ai.openSidebar autoSend consent and overlay live portForward status 2026-11-28 21:26:17 +08:00
bincxz 28b09513e6 chore(tests): remove unused React bindings in plugin sidebar tests 2026-11-28 21:10:33 +08:00
bincxz 30ff6c2b94 feat(plugins): add native Catty Agent contextual sidebar, plugin AI tools, and inline BI/SQL artifacts
- Add additive ai.sidebar-tools feature, canonical JSON Schema definitions, and SDK context.ai.{registerTools, setContext, clearContext, openSidebar, closeSidebar} + PluginBiChartToolArtifact / PluginSqlResultToolArtifact contracts.
- Add main-process PluginAISidebarService with host-side feature enforcement, view-ownership & size caps, collision-proof plugin tool naming, plugin.ai.invokeTool dispatch, auto-cleanup, and preload/IPC bridge.
- Inject active plugin tools & untrusted-data-framed view context into Catty Agent (AI SDK v7 jsonSchema, dynamic read/write approval policies, host-stamped artifact origin stripping/stamping, compact model output, and global plugin-view session retention).
- Dock resizable borderless PluginVaultAISidebar in PluginVaultPage wired to cancelable capture-phase TopTabs AI toggle and plugin openSidebar/closeSidebar commands, and render inline PluginBiChart & SQL result artifacts in ChatMessageList.
2026-11-28 21:10:33 +08:00
bincxz a4f50c391f feat(plugins): harden plugin runtime and add host-rendered PluginBiChart widget
- Fix all 15 adversarial review findings across SSH exec, SFTP, TCP probe, loopback-only port forwarding, durable vault bindings, openExternalUrl, hostDom mount lifecycle, useHostDrawnPluginView snapshot reset, PluginMetricChart bounds, VaultNavCustomizePopover drag cleanup, and plugin-cli archive hashing, plus viewResourceService test teardown retries.
- Add zero-dependency host-rendered PluginBiChart (bi-chart) widget supporting 10 chart types, strict caps, static color allowlist, local hover/legend toggle, datumClick cross-filtering, and resolved-theme SVG/2x PNG export, exported via @netcatty/plugin-sdk/host-react.
2026-11-28 21:10:33 +08:00
bincxz e2f2021c88 feat(plugins): production-ready plugin host, customizable Vault nav, safe host capabilities, sidebar badges, and official Monitor plugin
- Plugin host production readiness & loading speed: BrowserRuntimePool pre-warming, inline bootstrap config + modulepreload, parallel archive hashing, atomic first paint, CSS dedupe, zero-flicker view remount, and host-drawn widget/event polish.
- Customizable Vault left sidebar navigation & built-in Monitor retirement: vaultNavConfig, drag/reorder/hide/reset VaultNavSidebar & VaultNavCustomizePopover.
- Expanded safe host capabilities & sidebar badges: vault.execHostCommand, vault.probeHost, vault.sftp.*, portForward.*, snippets.*, terminals.*, ui.confirm/ui.openExternalUrl, workspace.*, PluginMetricChart, and views.setBadge (PluginViewBadgeService + expanded/collapsed Vault sidebar & terminal launcher badges).
- Official Netcatty Monitor plugin: commercial observability & ops workbench under plugins/netcatty-monitor/, flat Cat-Mascot icons, Retina screenshots, and synced first-party identity & catalog metadata for binaricat/netcatty-monitor-plugin.
2026-11-28 21:10:33 +08:00
陈大猫 242028dcb7 refactor(ai): remove ctx.require from aiBridge handler context and anchor lazy helpers (#4508) 2026-11-28 21:00:53 +08:00
GOUKI9999 81af709d9b fix(ai): resolve lazy SDK modules from their own directory (#4507) 2026-11-28 20:38:06 +08:00
Pyroandpyroch fc21162bd7 fix(i18n): shorten Russian labels in narrow panels (#4506)
Co-authored-by: pyroch <cvdysh@gmail.com>
2026-11-28 19:54:37 +08:00
陈大猫 9d64860ba6 feat(vault): unify group details UI and add RDP/VNC group defaults (#4503) (#4505)
* feat(vault): unify group details UI and add RDP/VNC group defaults (#4503)

* fix(vault): address PR review findings for RDP/VNC group defaults

* fix(vault): preserve inherited RDP/VNC username when creating identity

* fix(vault): retain inherited desktop username when detaching standalone identity
2026-11-28 19:06:27 +08:00
Pyroandpyroch f208b46b40 fix(i18n): complete Russian translations (#4502)
Co-authored-by: pyroch <cvdysh@gmail.com>
2026-11-28 17:36:48 +08:00
陈大猫 f6d1ed2deb fix(ui): clip magnified pane fill to rounded chrome (#4499) 2026-11-28 16:38:50 +08:00
陈大猫 baa8ef5743 feat(remote-desktop): enable leak-free RDP/VNC video recording with multi-clip logs, timeline seek, and posters (#4501)
* feat(remote-desktop): enable leak-free RDP/VNC video recording with multi-clip logs, timeline seek, and posters

* test(remote-desktop): stub navigator.locks in remoteDesktopLogActions test for Node 22 CI
2026-11-28 16:24:31 +08:00
陈大猫 7a7deba65a fix(packaging): stop platform files arrays from triggering **/* fallback in app.asar (#4498) 2026-11-28 13:29:13 +08:00
Netcatty-Botandgithub-actions[bot] 2433d56d90 Update Nix release metadata for v1.1.94 (#4497)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-28 11:49:13 +08:00
dependabot[bot] 9ec417cbe4 ci: bump softprops/action-gh-release (#4495)
Bumps the github-actions group with 1 update: [softprops/action-gh-release](https://github.com/softprops/action-gh-release).


Updates `softprops/action-gh-release` from 2.6.2 to 3.0.4
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v2.6.2...v3.0.4)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: 3.0.4
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-28 10:12:59 +08:00
475 changed files with 55402 additions and 3342 deletions

No files matched your search

+4 -4
View File
@@ -16,7 +16,7 @@ workflows:
- 'actions/setup-node@v7.1.0'
- 'actions/upload-artifact@v7.0.2'
- 'ilammy/msvc-dev-cmd@v1.13.0'
- 'softprops/action-gh-release@v2.6.2'
- 'softprops/action-gh-release@v3.0.4'
'.github/workflows/grokbot-issue-relay.yml': []
'.github/workflows/issue-format.yml':
- 'actions/checkout@v7.0.1'
@@ -65,8 +65,8 @@ dependencies:
commit: 'sha1-0b201ec74fa43914dc39ae48a89fd1d8cb592756'
owner_id: 1256587
repo_id: 212181767
'softprops/action-gh-release@v2.6.2':
ref: 'v2.6.2'
commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65'
'softprops/action-gh-release@v3.0.4':
ref: 'v3.0.4'
commit: 'sha1-8a0cd651e5b2365bd640854a3fa5dfc70e4875f3'
owner_id: 2242
repo_id: 204253808
+1 -1
View File
@@ -828,7 +828,7 @@ jobs:
GITHUB_SHA: ${{ github.sha }}
- name: Create GitHub Release
uses: softprops/action-gh-release@v2.6.2
uses: softprops/action-gh-release@v3.0.4
with:
body_path: release_notes.md
prerelease: ${{ contains(github.ref_name, '-') }}
-4
View File
@@ -1,5 +1,3 @@
import { MonitorHostKeyDialog } from './components/vault/MonitorHostKeyDialog';
import { MonitorRuntimeHost } from './application/app/MonitorRuntimeHost';
import React, { useEffect } from 'react';
import { initializeFonts } from './application/state/fontStore';
@@ -55,9 +53,7 @@ function App() {
}, []);
return (
<AppLocalStateProvider>
<MonitorRuntimeHost />
<AppSideEffects />
<MonitorHostKeyDialog />
<AppShell />
</AppLocalStateProvider>
);
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
Electron、React、xterm.js で構築された機能豊富な SSH ワークスペース。<br/>
🔥 内蔵 AI Agent · 分割ターミナル · Vault ビュー · SFTP ワークフロー · カスタムテーマ — すべてが一つに。
🔥 内蔵 AI Agent · 🧩 プラグインシステム · 分割ターミナル · Vault ビュー · SFTP ワークフロー · カスタムテーマ — すべてが一つに。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="GitHub でスポンサーになる"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Ko-fi でサポート"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/WeChat-Official%20Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="公式 WeChat グループに参加"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
---
<a name="plugin-system"></a>
# 🧩 プラグインシステム — Netcatty を安全に拡張
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
- 🔒 **オフラインサンドボックス & 最小権限モデル** — プラグインは SSH パスワードや秘密鍵に直接アクセスできず、すべての機能はホスト管理の **許可 / 毎回確認 / 拒否** ポリシーを経由します。
- 🖥️ **ホストネイティブ IDE コンポーネント** — `@netcatty/plugin-sdk` を使い、React または DOM で Vault ページ、ターミナルサイドバー、モーダルを構築できます。
- 🗄️ **公式プラグインをすぐ導入** — **設定 → プラグイン** から [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database)(113 エンジン対応 SQL IDE・Catty Agent・BI ダッシュボード)や [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor)(エージェントレス SSH サーバー監視・Monaco ライブ可視化ログ)をワンクリック導入できます。
- 🚀 **柔軟な配布と自動更新チェック** — 内蔵の**公式マーケットプレイス**(`plugins.netcatty.app`)、GitHub Release からの直接インストール、ローカル `.ncpkg` インポート、自社ホスト静的ソースに対応します。
### 🔗 関連リンク & ガイド
- 🛒 [**公式プラグインマーケットプレイス**](https://netcatty.app/en/plugins) — 公式・コミュニティプラグインを閲覧
- 📖 [**プラグイン基盤概要**](https://netcatty.app/en/docs/plugins-overview) — サンドボックス設計・ホストレンダリング UI・権限モデル
- 🛠️ [**プラグイン開発ガイド**](https://netcatty.app/en/docs/plugins-development) — プロジェクト作成・UI 実装・権限宣言・`.ncpkg` パッケージング
- 📤 [**マーケットプレイス公開・提出ガイド**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release 規約と公式カタログ PR 手順([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目次 <!-- omit in toc -->
- [🔥 Catty Agent — AI パートナー](#catty-agent)
- [🧩 プラグインシステム](#plugin-system)
- [Netcatty とは](#netcatty-とは)
- [なぜ Netcatty](#なぜ-netcatty)
- [機能](#機能)
@@ -94,6 +122,7 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
- [はじめに](#はじめに)
- [ビルドとパッケージ](#ビルドとパッケージ)
- [技術スタック](#技術スタック)
- [コミュニティ](#コミュニティ)
- [コントリビューション](#コントリビューション)
- [コントリビューター](#コントリビューター)
- [Star 履歴](#star-履歴)
@@ -326,6 +355,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="コミュニティ"></a>
# 💬 コミュニティ
WeChat で QR コードをスキャンして **Netcatty 公式ユーザーグループ** に参加し、フィードバックやプラグインの話題を共有しましょう:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 公式 WeChat グループ QR コード" width="260" />
</p>
---
<a name="コントリビューション"></a>
# コントリビューション
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
A beautiful, feature-rich SSH workspace built with Electron, React, and xterm.js.<br/>
🔥 Built-in AI Agent · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
🔥 Built-in AI Agent · 🧩 Plugin System · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="Sponsor on GitHub"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Support on Ko-fi"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/WeChat-Official%20Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="Join Official WeChat Group"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,11 +83,35 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
<img width="3294" height="1974" alt="image" src="docs/assets/readme/catty-multi-host.webp" />
---
<a name="plugin-system"></a>
# 🧩 Plugin System — Extend Netcatty Safely
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
### ✨ Highlights
- 🔒 **Offline Sandbox & Least-Privilege Permissions** — Plugins never touch SSH passwords, private keys, or the host renderer; every capability goes through host-mediated **Allow / Ask / Deny** brokers.
- 🖥️ **Host-Rendered IDE Components** — Build native-feeling Vault pages, terminal sidebars, and modals with React or DOM via `@netcatty/plugin-sdk`.
- 🗄️ **Official Plugins Out of the Box** — Install [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database) (113 database profiles, SQL IDE, Catty Agent sidebar & BI Dashboard) and [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor) (agentless cross-OS SSH fleet observability, Monaco live logs & multi-host compare) directly in **Settings → Plugins**.
- 🚀 **Flexible Distribution** — Install from the built-in **Official Marketplace** (`plugins.netcatty.app`), directly from any public GitHub Release (**Install from GitHub**), via local `.ncpkg` import, or self-hosted static market sources.
### 🔗 Resources & Guides
- 🛒 [**Official Plugin Marketplace**](https://netcatty.app/en/plugins) — Browse official and curated plugins
- 📖 [**Plugin Platform Overview**](https://netcatty.app/en/docs/plugins-overview) — Sandbox architecture, host-rendered UI, and permission model
- 🛠️ [**Plugin Development Guide**](https://netcatty.app/en/docs/plugins-development) — Scaffold, build host-rendered views, declare permissions, and pack `.ncpkg`
- 📤 [**Marketplace Submission & Publishing Guide**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release contract & official catalog PR workflow ([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# Contents <!-- omit in toc -->
- [🔥 Catty Agent — AI Partner](#catty-agent)
- [🧩 Plugin System](#plugin-system)
- [What is Netcatty](#what-is-netcatty)
- [Why Netcatty](#why-netcatty)
- [Features](#features)
@@ -96,6 +124,7 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
- [Open a local terminal from the command line](#open-a-local-terminal-from-the-command-line)
- [Build & Package](#build--package)
- [Tech Stack](#tech-stack)
- [Community](#community)
- [Contributing](#contributing)
- [Contributors](#contributors)
- [Star History](#star-history)
@@ -359,6 +388,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="community"></a>
# 💬 Community
Scan the QR code with WeChat to join the **Netcatty Official User Group** for feedback, tips, and plugin discussions:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty Official WeChat Group QR Code" width="260" />
</p>
---
<a name="contributing"></a>
# Contributing
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
一个基于 Electron、React 和 xterm.js 构建的功能丰富的 SSH 工作空间。<br/>
🔥 内置 AI Agent · 分屏终端 · Vault 多视图 · SFTP 工作流 · 自定义主题 —— 一应俱全。
🔥 内置 AI Agent · 🧩 插件系统 · 分屏终端 · Vault 多视图 · SFTP 工作流 · 自定义主题 —— 一应俱全。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="通过 GitHub 赞助我"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="在 Ko-fi 上支持我"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/%E5%BE%AE%E4%BF%A1%E7%BE%A4-%E5%AE%98%E6%96%B9%E4%BA%A4%E6%B5%81%E7%BE%A4-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="加入官方微信交流群"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@
---
<a name="plugin-system"></a>
# 🧩 插件系统 — 安全扩展你的工作台
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
### ✨ 核心亮点
- 🔒 **离线沙箱与最小权限控制** —— 插件永远无法读取 SSH 密码或私钥,所有宿主能力均受 **允许 / 询问 / 拒绝** 三态权限代理与审计保护。
- 🖥️ **宿主原生 IDE 组件** —— 通过 `@netcatty/plugin-sdk` 使用 React 或原生 DOM 构建 Vault 页面、终端侧栏与弹窗,无缝复用宿主主题。
- 🗄️ **官方插件开箱即用** —— 在 **设置 → 插件** 一键安装 [**Netcatty 数据库**](https://netcatty.app/zh/plugins/netcatty-database)(覆盖 113 种数据库配置、SQL IDE、Catty Agent 侧栏与 BI 看板)和 [**Netcatty 监控**](https://netcatty.app/zh/plugins/netcatty-monitor)(无 Agent 跨平台 SSH 集群监控、Monaco 实时日志与多机对比)。
- 🚀 **多渠道分发与自动检查更新** —— 支持内置**官方插件市场**(`plugins.netcatty.app`)、**从 GitHub 安装**公开 Release、本地导入 `.ncpkg` 以及自建第三方静态市场源。
### 🔗 相关链接与指南
- 🛒 [**官方插件市场**](https://netcatty.app/zh/plugins) —— 浏览官方与社区插件
- 📖 [**插件平台概览**](https://netcatty.app/zh/docs/plugins-overview) —— 隔离架构、宿主渲染 UI 与权限安全模型
- 🛠️ [**插件开发指南**](https://netcatty.app/zh/docs/plugins-development) —— 脚手架初始化、UI 开发、权限声明与 `.ncpkg` 打包调试
- 📤 [**插件市场发布与提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契约与官方市场 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目录 <!-- omit in toc -->
- [🔥 Catty Agent — AI 搭档](#catty-agent)
- [🧩 插件系统](#plugin-system)
- [Netcatty 是什么](#netcatty-是什么)
- [为什么是 Netcatty](#为什么是-netcatty)
- [功能特性](#功能特性)
@@ -94,6 +122,7 @@
- [快速开始](#快速开始)
- [构建与打包](#构建与打包)
- [技术栈](#技术栈)
- [社区交流](#社区交流)
- [参与贡献](#参与贡献)
- [贡献者](#贡献者)
- [Star 历史](#star-历史)
@@ -326,6 +355,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="社区交流"></a>
# 💬 社区交流
欢迎使用微信扫码加入 **Netcatty 官方用户交流群**,交流使用技巧、插件开发与反馈建议:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 官方用户交流群二维码" width="260" />
</p>
---
<a name="参与贡献"></a>
# 参与贡献
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
以 Electron、React 與 xterm.js 打造,介面精緻、功能完整的 SSH 工作區。<br/>
🔥 內建 AI Agent · 分割終端 · Vault 檢視 · SFTP 工作流 · 自訂主題 —— 全部整合在一起。
🔥 內建 AI Agent · 🧩 外掛系統 · 分割終端 · Vault 檢視 · SFTP 工作流 · 自訂主題 —— 全部整合在一起。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="透過 GitHub 贊助我"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Support on Ko-fi"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/%E5%BE%AE%E4%BF%A1%E7%BE%A4-%E5%AE%98%E6%96%B9%E4%BA%A4%E6%B5%81%E7%BE%A4-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="加入官方微信交流群"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@
---
<a name="plugin-system"></a>
# 🧩 外掛系統 —— 安全擴充你的工作台
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
### ✨ 核心亮點
- 🔒 **離線沙箱與最小權限控制** —— 外掛永遠無法讀取 SSH 密碼或私鑰,所有宿主能力均受 **允許 / 詢問 / 拒絕** 三態權限代理保護。
- 🖥️ **宿主原生 IDE 元件** —— 透過 `@netcatty/plugin-sdk` 以 React 或原生 DOM 開發 Vault 頁面、終端側欄與視窗,無縫跟隨宿主主題。
- 🗄️ **官方外掛開箱即用** —— 在 **設定 → 外掛** 一鍵安裝 [**Netcatty 資料庫**](https://netcatty.app/zh/plugins/netcatty-database)(113 種資料庫設定、SQL IDE、Catty Agent 側欄與 BI 看板)與 [**Netcatty 監控**](https://netcatty.app/zh/plugins/netcatty-monitor)(無 Agent 跨平台 SSH 叢集監控、Monaco 即時日誌與多機對比)。
- 🚀 **多元分發與自動檢查更新** —— 支援內建**官方外掛市場**(`plugins.netcatty.app`)、**從 GitHub 安裝**公開 Release、本機匯入 `.ncpkg` 以及自建第三方靜態市場源。
### 🔗 相關連結與指南
- 🛒 [**官方外掛市場**](https://netcatty.app/zh/plugins) —— 瀏覽官方與社群外掛
- 📖 [**外掛平台概覽**](https://netcatty.app/zh/docs/plugins-overview) —— 隔離架構、宿主渲染 UI 與權限安全模型
- 🛠️ [**外掛開發指南**](https://netcatty.app/zh/docs/plugins-development) —— 初始化專案、UI 開發、權限宣告與 `.ncpkg` 打包除錯
- 📤 [**外掛市場發布與提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契約與官方市場 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目錄 <!-- omit in toc -->
- [🔥 Catty Agent —— AI 夥伴](#catty-agent)
- [🧩 外掛系統](#plugin-system)
- [Netcatty 是什麼](#netcatty-是什麼)
- [為什麼選 Netcatty](#為什麼選-netcatty)
- [功能特色](#功能特色)
@@ -94,6 +122,7 @@
- [快速開始](#快速開始)
- [建置與打包](#建置與打包)
- [技術堆疊](#技術堆疊)
- [社群交流](#社群交流)
- [參與貢獻](#參與貢獻)
- [貢獻者](#貢獻者)
- [Star 紀錄](#star-紀錄)
@@ -325,6 +354,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="社群交流"></a>
# 💬 社群交流
歡迎使用微信掃描下方 QR Code 加入 **Netcatty 官方用戶交流群**,交流使用技巧、外掛開發與回饋建議:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 官方用戶交流群 QR Code" width="260" />
</p>
---
<a name="參與貢獻"></a>
# 參與貢獻
@@ -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');
+32 -1
View File
@@ -604,7 +604,37 @@ export function AppSideEffects() {
});
// Window controls - must be before update toast effect which uses openSettingsWindow
const { openSettingsWindow } = useWindowControls();
const { openSettingsWindow, isFullscreen, onFullscreenChanged } = useWindowControls();
// Sync host platform and fullscreen state to DOM so platform-aware chrome
// (such as macOS rounded window corners on outer split-pane focus borders)
// stays accurate across fullscreen transitions without per-pane polling.
useEffect(() => {
const isMac = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform);
if (isMac) {
document.documentElement.setAttribute('data-platform', 'darwin');
} else {
document.documentElement.removeAttribute('data-platform');
document.documentElement.removeAttribute('data-window-fullscreen');
return undefined;
}
let cancelled = false;
const syncFullscreen = (value: boolean) => {
if (value) {
document.documentElement.setAttribute('data-window-fullscreen', 'true');
} else {
document.documentElement.removeAttribute('data-window-fullscreen');
}
};
void isFullscreen().then((value) => {
if (!cancelled) syncFullscreen(!!value);
});
const unsubscribe = onFullscreenChanged((value) => syncFullscreen(!!value));
return () => {
cancelled = true;
unsubscribe();
};
}, [isFullscreen, onFullscreenChanged]);
const _handleTrayJumpToSession = useEffectEvent((sessionId: string) => {
return handleTrayJumpToSessionImpl(() => ({
sessionId,
@@ -1817,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}
+43 -18
View File
@@ -32,41 +32,66 @@ function loadComponent(path: string, name: string, bindings: Record<string, unkn
}) as React.ComponentType;
}
test('monitor controls update their runtime without rendering unrelated app siblings', async () => {
test('App no longer mounts retired built-in MonitorRuntimeHost or MonitorHostKeyDialog', async () => {
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = env.IS_REACT_ACT_ENVIRONMENT;
env.IS_REACT_ACT_ENVIRONMENT = true;
let sideEffectRenders = 0;
let shellRenders = 0;
const appSource = readFileSync(new URL('../../App.tsx', import.meta.url), 'utf8');
assert.doesNotMatch(appSource, /MonitorRuntimeHost/, 'App must not mount retired MonitorRuntimeHost');
assert.doesNotMatch(appSource, /MonitorHostKeyDialog/, 'App must not mount retired MonitorHostKeyDialog');
const App = loadComponent('../../App.tsx', 'App', {
performance: { mark: () => {} },
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
AppSideEffects: () => { sideEffectRenders += 1; return null; },
AppShell: React.memo(() => { shellRenders += 1; return null; }),
});
let renderer: ReturnType<typeof create> | undefined;
try {
await act(async () => { renderer = create(React.createElement(App)); });
assert.equal(sideEffectRenders, 1);
assert.equal(shellRenders, 1);
} finally {
await act(async () => renderer?.unmount());
env.IS_REACT_ACT_ENVIRONMENT = previous;
}
});
test('MonitorRuntimeHost keeps monitor runtime updates isolated from sibling components when mounted', async () => {
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = env.IS_REACT_ACT_ENVIRONMENT;
env.IS_REACT_ACT_ENVIRONMENT = true;
let updateMonitor: (() => void) | undefined;
let runtimeRenders = 0;
let sideEffectRenders = 0;
let shellRenders = 0;
let siblingRenders = 0;
const useMonitorRuntime = () => {
const [, setVersion] = useState(0);
updateMonitor = () => setVersion((version) => version + 1);
runtimeRenders += 1;
};
const MonitorRuntimeHost = loadComponent('./MonitorRuntimeHost.tsx', 'MonitorRuntimeHost', { useMonitorRuntime });
const App = loadComponent('../../App.tsx', 'App', {
performance: { mark: () => {} },
useMonitorRuntime,
MonitorRuntimeHost,
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
AppSideEffects: () => { sideEffectRenders += 1; return null; },
MonitorHostKeyDialog: () => null,
AppShell: React.memo(() => { shellRenders += 1; return null; }),
});
const StableSibling = React.memo(() => { siblingRenders += 1; return null; });
let renderer: ReturnType<typeof create> | undefined;
try {
await act(async () => { renderer = create(React.createElement(App)); });
await act(async () => {
renderer = create(
React.createElement(
React.Fragment,
null,
React.createElement(MonitorRuntimeHost),
React.createElement(StableSibling),
),
);
});
const initialRuntimeRenders = runtimeRenders;
const initialSideEffectRenders = sideEffectRenders;
const initialShellRenders = shellRenders;
const initialSiblingRenders = siblingRenders;
for (let i = 0; i < 10; i += 1) {
await act(async () => updateMonitor!());
}
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must still run');
assert.equal(sideEffectRenders - initialSideEffectRenders, 0, 'monitor-only state must not render AppSideEffects');
assert.equal(shellRenders - initialShellRenders, 0, 'monitor controls must leave the shell stable');
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must run inside MonitorRuntimeHost');
assert.equal(siblingRenders - initialSiblingRenders, 0, 'monitor updates must not re-render siblings');
} finally {
await act(async () => renderer?.unmount());
env.IS_REACT_ACT_ENVIRONMENT = previous;
+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.',
+62 -2
View File
@@ -8,7 +8,7 @@ export const enCoreMessages: Messages = {
"settings.plugins.github.busy": "Downloading, validating or installing the package...",
"settings.plugins.github.review": "Repository ownership and package integrity do not verify publisher trust. No build scripts run. The plugin installs disabled; review permission modes before enabling.",
"settings.plugins.github.accept": "I trust this repository and have reviewed the declared permissions.",
"settings.plugins.github.confirm": "Install disabled",
"settings.plugins.github.confirm": "Install",
"settings.plugins.github.download": "Download and review",
"settings.plugins.github.error.invalidRepository": "Enter https://github.com/owner/repo, github.com/owner/repo or owner/repo (repository only; no credentials, query, fragment or extra paths).",
"settings.plugins.github.error.unavailable": "GitHub plugin installation is unavailable in this session.",
@@ -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',
@@ -1174,6 +1177,16 @@ Highlight the focused split pane:
'vault.nav.notes': 'Notes',
'vault.nav.knownHosts': 'Known Hosts',
'vault.nav.logs': 'Logs',
'vault.nav.customize': 'Customize sidebar',
'vault.nav.customizeHint': 'Drag items to reorder or toggle visibility.',
'vault.nav.hideItem': 'Hide {label}',
'vault.nav.moveUp': 'Move up',
'vault.nav.moveDown': 'Move down',
'vault.nav.resetDefault': 'Reset to default',
'vault.nav.alwaysVisible': 'Always visible',
'vault.nav.pluginBadge': 'Plugin',
'vault.nav.dragToReorder': 'Drag to reorder {label}',
'vault.nav.toggleVisibility': 'Toggle {label} visibility',
'proxyProfiles.action.add': 'Add Proxy',
'proxyProfiles.search.placeholder': 'Search proxies…',
@@ -1225,7 +1238,10 @@ Highlight the focused split pane:
'vault.groups.details': 'Group Details',
'vault.groups.details.general': 'General',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'Default {protocol} settings are not configured for this group yet.',
'vault.groups.details.advanced': 'Advanced',
'vault.groups.details.appearance': 'Appearance',
'vault.groups.details.mosh': 'Mosh',
@@ -1317,7 +1333,12 @@ Highlight the focused split pane:
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
"plugins.sidebar.loading": "Loading extension page…",
"plugins.vault.loading": "Loading plugin page…",
"plugins.vault.viewError": "The plugin page failed to render.",
"plugins.vault.retry": "Retry",
"plugins.interaction.title": "Plugin request",
"plugins.interaction.openUrlTitle": "Open external link?",
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
"plugins.interaction.openUrlAction": "Open URL",
"plugins.interaction.sharing": "Text you share becomes available to this plugin and its granted capabilities, including network access. Reading does not approve a new network destination.",
"plugins.interaction.input": "Input text",
"plugins.interaction.filter": "Filter choices",
@@ -1391,7 +1412,10 @@ Highlight the focused split pane:
"settings.plugins.market.title": "Marketplace",
"settings.plugins.market.note": "Curated open-source plugins. Review is not a security certification. Updates are manual.",
"settings.plugins.market.back": "All plugins",
"settings.plugins.market.install": "Install this version (disabled)",
"settings.plugins.market.install": "Install",
"settings.plugins.market.installing": "Installing...",
"settings.plugins.market.update": "Update",
"settings.plugins.market.updating": "Updating...",
"settings.plugins.market.installNote": "This replaces and stops the installed version. Review its permissions in Installed plugins before enabling.",
"settings.plugins.market.sourceOnly": "First-party source example. Build with the local CLI and import the .ncpkg; no downloadable release has been published.",
"settings.plugins.market.readmeNote": "Pinned to the commit above. HTML is inert and remote images are not loaded. Written by the plugin author.",
@@ -1477,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',
};
+18
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',
@@ -15,6 +17,8 @@ export const enTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.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.',
@@ -468,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',
@@ -618,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',
@@ -694,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',
@@ -987,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})',
};
+15
View File
@@ -1319,6 +1319,7 @@ export const enVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Record session',
'remoteDesktop.toolbar.stopRecording': 'Stop recording',
'remoteDesktop.toolbar.savingRecording': 'Saving...',
'remoteDesktop.toolbar.recording': 'Recording',
'remoteDesktop.toolbar.askAi': 'Ask AI',
'remoteDesktop.toolbar.askAiFull': 'Capture Screen & Ask AI',
@@ -1424,7 +1425,18 @@ export const enVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Started',
'logView.remoteDesktop.ended': 'Ended',
'logView.remoteDesktop.duration': 'Duration',
'logView.remoteDesktop.resolution': 'Resolution',
'logView.remoteDesktop.security': 'Security',
'logView.remoteDesktop.disconnectReason': 'Disconnect reason',
'logView.remoteDesktop.timeline': 'Session Timeline',
'logView.remoteDesktop.recordingTip': 'Click Record in the remote desktop toolbar or enable Auto-record in Settings -> System to save .webm replays here.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'All',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Remote Desktop',
'logs.filter.recorded': 'Recorded',
'logs.filter.emptyTitle': 'No matching logs',
'logs.filter.emptyDesc': 'No connection logs match the selected filter yet.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Remote Desktop Recordings',
@@ -1451,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.',
+62 -2
View File
@@ -8,7 +8,7 @@ export const esCoreMessages: Messages = {
"settings.plugins.github.busy": "Descargando, validando o instalando el paquete...",
"settings.plugins.github.review": "El origen y la integridad no verifican la confianza en el autor. No se ejecutan scripts de compilación. Se instala desactivado; revisa los permisos antes de activarlo.",
"settings.plugins.github.accept": "Confío en este repositorio y he revisado los permisos declarados.",
"settings.plugins.github.confirm": "Instalar desactivado",
"settings.plugins.github.confirm": "Instalar",
"settings.plugins.github.download": "Descargar y revisar",
"settings.plugins.github.error.invalidRepository": "Introduce https://github.com/owner/repo, github.com/owner/repo u owner/repo. Usa solo el repositorio, sin credenciales, parámetros, fragmentos ni rutas adicionales.",
"settings.plugins.github.error.unavailable": "La instalación de plugins desde GitHub no está disponible en esta sesión.",
@@ -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',
@@ -1174,6 +1177,16 @@ Resalta el panel dividido enfocado:
'vault.nav.notes': 'Notas',
'vault.nav.knownHosts': 'Hosts conocidos',
'vault.nav.logs': 'Registros',
'vault.nav.customize': 'Personalizar barra lateral',
'vault.nav.customizeHint': 'Arrastra elementos para reordenar o alternar visibilidad.',
'vault.nav.hideItem': 'Ocultar {label}',
'vault.nav.moveUp': 'Subir',
'vault.nav.moveDown': 'Bajar',
'vault.nav.resetDefault': 'Restablecer a los valores predeterminados',
'vault.nav.alwaysVisible': 'Siempre visible',
'vault.nav.pluginBadge': 'Complemento',
'vault.nav.dragToReorder': 'Arrastra para reordenar {label}',
'vault.nav.toggleVisibility': 'Alternar visibilidad de {label}',
'proxyProfiles.action.add': 'Agregar proxy',
'proxyProfiles.search.placeholder': 'Buscar proxies…',
@@ -1225,7 +1238,10 @@ Resalta el panel dividido enfocado:
'vault.groups.details': 'Detalles del grupo',
'vault.groups.details.general': 'General',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'La configuración predeterminada de {protocol} aún no está configurada para este grupo.',
'vault.groups.details.advanced': 'Avanzado',
'vault.groups.details.appearance': 'Apariencia',
'vault.groups.details.mosh': 'Mosh',
@@ -1317,7 +1333,12 @@ Resalta el panel dividido enfocado:
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
"plugins.sidebar.loading": "Cargando página de extensión…",
"plugins.vault.loading": "Cargando página del plugin…",
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
"plugins.vault.retry": "Reintentar",
"plugins.interaction.title": "Solicitud de complemento",
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
"plugins.interaction.openUrlAction": "Abrir URL",
"plugins.interaction.sharing": "El texto compartido estará disponible para este complemento y sus capacidades autorizadas, incluida la red. Leer no autoriza un nuevo destino de red.",
"plugins.interaction.input": "Introducir texto",
"plugins.interaction.filter": "Filtrar opciones",
@@ -1391,7 +1412,10 @@ Resalta el panel dividido enfocado:
"settings.plugins.market.title": "Catálogo",
"settings.plugins.market.note": "Plugins de código abierto seleccionados. La revisión no certifica su seguridad. Las actualizaciones son manuales.",
"settings.plugins.market.back": "Todos los plugins",
"settings.plugins.market.install": "Instalar esta versión (desactivada)",
"settings.plugins.market.install": "Instalar",
"settings.plugins.market.installing": "Instalando...",
"settings.plugins.market.update": "Actualizar",
"settings.plugins.market.updating": "Actualizando...",
"settings.plugins.market.installNote": "Esto reemplaza y detiene la versión instalada. Revisa sus permisos antes de activarla.",
"settings.plugins.market.sourceOnly": "Ejemplo propio con código fuente. Compílalo con la CLI local e importa el .ncpkg; no hay versión publicada para descargar.",
"settings.plugins.market.readmeNote": "Fijado al commit indicado. El HTML no se ejecuta y las imágenes remotas no se cargan. Contenido del autor.",
@@ -1477,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',
};
+18
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',
@@ -15,6 +17,8 @@ export const esTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.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.',
@@ -468,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',
@@ -618,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',
@@ -696,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',
@@ -989,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})',
};
+15
View File
@@ -1378,6 +1378,7 @@ export const esVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Grabar sesión',
'remoteDesktop.toolbar.stopRecording': 'Detener grabación',
'remoteDesktop.toolbar.savingRecording': 'Guardando...',
'remoteDesktop.toolbar.recording': 'Grabando',
'remoteDesktop.toolbar.askAi': 'Preguntar a la IA',
'remoteDesktop.toolbar.askAiFull': 'Capturar pantalla y preguntar a la IA',
@@ -1424,7 +1425,18 @@ export const esVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Inicio',
'logView.remoteDesktop.ended': 'Fin',
'logView.remoteDesktop.duration': 'Duración',
'logView.remoteDesktop.resolution': 'Resolución',
'logView.remoteDesktop.security': 'Seguridad',
'logView.remoteDesktop.disconnectReason': 'Motivo de desconexión',
'logView.remoteDesktop.timeline': 'Cronología de sesión',
'logView.remoteDesktop.recordingTip': 'Haz clic en Grabar en la barra de escritorio remoto o activa la grabación automática en Ajustes → Sistema para guardar repeticiones .webm aquí.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'Todos',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Escritorio remoto',
'logs.filter.recorded': 'Con grabación',
'logs.filter.emptyTitle': 'Sin registros coincidentes',
'logs.filter.emptyDesc': 'Todavía no hay registros de conexión que coincidan con este filtro.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Grabaciones de escritorio remoto',
@@ -1451,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`);
}
}
}
});
@@ -8,12 +8,6 @@ import ru from "./ru.ts";
import zhCN from "./zh-CN.ts";
import zhTW from "./zh-TW.ts";
// Locales that are not at full key parity with `en` yet. They are tracked here
// so the remaining debt stays visible instead of silently rendering in English
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
// Move a locale out of this list once it covers every `en` key.
const LOCALES_PENDING_PARITY = ["ru"] as const;
const hasKey = (messages: Record<string, string>, key: string) =>
Object.hasOwn(messages, key);
@@ -110,7 +104,7 @@ test("en shortcut labels stay identical to DEFAULT_KEY_BINDINGS", () => {
}
});
test("every locale outside the pending list is at full parity with en", () => {
test("every translated locale defines every message key from en", () => {
const locales = [
{ name: "es", messages: es },
{ name: "ru", messages: ru },
@@ -119,10 +113,6 @@ test("every locale outside the pending list is at full parity with en", () => {
];
for (const locale of locales) {
if ((LOCALES_PENDING_PARITY as readonly string[]).includes(locale.name)) {
continue;
}
const missing = Object.keys(en).filter(
(key) => !hasKey(locale.messages, key),
);
+135 -50
View File
@@ -10,9 +10,28 @@ export const ruAiMessages: Messages = {
'ai.chat.preparing': 'Подготовка…',
'ai.chat.modelCatalogWarning': 'Не удалось обновить список моделей. Показаны последние доступные или встроенные модели.',
'ai.chat.modelCatalogRetry': 'Повторить',
'ai.chat.compactingContext': 'Сжимаем предыдущий контекст…',
'ai.chat.compactingStep': 'Сокращаем контекст для следующего шага…',
'ai.chat.contextCompacted': 'Контекст сжат',
'ai.title': 'AI',
'ai.description': 'Настройка AI-провайдеров, агентов и параметров безопасности',
'ai.chat.compactionRetry': 'Запрос слишком большой. Сжимаем контекст и повторяем попытку…',
'ai.chat.compactionBanner': 'Контекст сжат: с {before} тыс. до {after} тыс. токенов',
'ai.chat.activity.title': 'Действия агента',
'ai.chat.activity.plan': 'План',
'ai.chat.activity.webSearch': 'Поиск в интернете',
'ai.chat.activity.fileChanges': 'Изменения файлов',
'ai.chat.activity.status.running': 'Выполняется',
'ai.chat.activity.status.completed': 'Завершено',
'ai.chat.activity.status.failed': 'Ошибка',
'ai.chat.activity.file.add': 'Добавление',
'ai.chat.activity.file.update': 'Изменение',
'ai.chat.activity.file.delete': 'Удаление',
'ai.chat.activity.usage': 'Токены',
'ai.chat.activity.usage.input': 'вход',
'ai.chat.activity.usage.output': 'выход',
'ai.chat.activity.usage.cached': 'из кэша',
'ai.chat.activity.usage.reasoning': 'рассуждение',
'ai.title': 'ИИ',
'ai.description': 'Настройка провайдеров ИИ, агентов и параметров безопасности',
'ai.providers': 'Провайдеры',
'ai.agents': 'Агенты',
'ai.providers.empty': 'Провайдеры не настроены. Добавьте провайдера, чтобы начать.',
@@ -43,6 +62,15 @@ export const ruAiMessages: Messages = {
'ai.providers.apiKey': 'API-ключ',
'ai.providers.apiKey.placeholder': 'Введите API-ключ',
'ai.providers.apiKey.decrypting': 'Расшифровка...',
'ai.providers.headers': 'Пользовательские заголовки HTTP',
'ai.providers.headers.help': 'Необязательные заголовки для этого провайдера. Значения скрыты и шифруются при сохранении.',
'ai.providers.headers.name': 'Имя заголовка',
'ai.providers.headers.value': 'Значение заголовка',
'ai.providers.headers.add': 'Добавить заголовок',
'ai.providers.headers.remove': 'Удалить заголовок',
'ai.providers.headers.invalid': 'Укажите корректные заголовки HTTP без повторяющихся имён. Content-Length и Transfer-Encoding задаются автоматически.',
'ai.providers.headers.loadError': 'Не удалось открыть сохранённые заголовки. Отмените операцию, разблокируйте системное хранилище ключей и повторите попытку.',
'ai.providers.headers.saveError': 'Не удалось сохранить заголовки в зашифрованном виде. Проверьте, доступно ли системное хранилище ключей, и повторите попытку.',
'ai.providers.opencodeGo.help': 'Вставьте API-ключ OpenCode, чтобы использовать OpenCode Go. Базовый URL и список моделей настроятся автоматически.',
'ai.providers.opencodeGo.getKey': 'Получить API-ключ',
'ai.providers.fixedBaseUrl.help': 'Задаётся провайдером. Netcatty автоматически выбирает путь эндпоинта для каждой модели.',
@@ -166,20 +194,20 @@ export const ruAiMessages: Messages = {
'ai.cursor.detected': 'Доступен',
'ai.cursor.notFound': 'Недоступен',
'ai.cursor.path': 'Среда:',
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на CLI login.',
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на вход через CLI.',
'ai.cursor.notInstalledHint': 'Cursor SDK / Agent CLI не обнаружен.',
'ai.cursor.installStatus': 'Среда Cursor',
'ai.cursor.installed': 'Обнаружено',
'ai.cursor.notInstalled': 'Не обнаружено',
'ai.cursor.modeCli': 'CLI login',
'ai.cursor.modeApiKey': 'API Key',
'ai.cursor.modeCli': 'Вход через CLI',
'ai.cursor.modeApiKey': 'API-ключ',
'ai.cursor.modeCliHint': 'Использует локальный `cursor-agent login` и квоту подписки Auto. Сохранённый API-ключ сохраняется, но в этом режиме не используется.',
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. CLI login в этом режиме игнорируется.',
'ai.cursor.cliLoginStatus': 'CLI login',
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. Вход через CLI в этом режиме игнорируется.',
'ai.cursor.cliLoginStatus': 'Вход через CLI',
'ai.cursor.cliLoginOk': 'Вход выполнен',
'ai.cursor.cliLoginAs': 'Вход как {{email}}',
'ai.cursor.cliLoginMissing': 'Нет входа',
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите Check.',
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите «Проверить».',
'ai.cursor.apiKeyStatus': 'API-ключ',
'ai.cursor.apiKeyConfigured': 'Настроен',
'ai.cursor.apiKeyMissing': 'Не указан',
@@ -210,22 +238,22 @@ export const ruAiMessages: Messages = {
'ai.codebuddy.configSection': 'Аутентификация и конфигурация (необязательно)',
'ai.codebuddy.internetEnv': 'Сетевая среда',
'ai.codebuddy.internetEnv.default': 'По умолчанию (зарубежная)',
'ai.codebuddy.internetEnv.internal': 'Internal',
'ai.codebuddy.internetEnv.internal': 'Внутренняя',
'ai.codebuddy.internetEnv.ioa': 'IOA',
'ai.codebuddy.internetEnv.hint': 'Устанавливает CODEBUDDY_INTERNET_ENVIRONMENT — выберите Internal или IOA для ограниченных сетевых сред.',
'ai.codebuddy.internetEnv.hint': 'Задаёт переменную CODEBUDDY_INTERNET_ENVIRONMENT. Для сетей с ограниченным доступом выберите «Внутренняя» или IOA.',
'ai.codebuddy.envVars': 'Переменные окружения',
'ai.codebuddy.envVars.placeholder': 'CODEBUDDY_API_KEY=...\nCODEBUDDY_AUTH_TOKEN=...\nOTHER_VAR=...',
'ai.codebuddy.envVars.hint': 'По одной записи KEY=VALUE на строку, передаются агенту CodeBuddy. Укажите CODEBUDDY_API_KEY или CODEBUDDY_AUTH_TOKEN для аутентификации. Хранятся локально в открытом виде.',
'ai.codebuddy.advancedSection': 'Расширенные параметры (SDK 0.3.258)',
'ai.codebuddy.effort': 'Усилие рассуждения',
'ai.codebuddy.effort': 'Глубина рассуждения',
'ai.codebuddy.effort.default': 'По умолчанию',
'ai.codebuddy.effort.minimal': 'Minimal',
'ai.codebuddy.effort.low': 'Low',
'ai.codebuddy.effort.medium': 'Medium',
'ai.codebuddy.effort.high': 'High',
'ai.codebuddy.effort.xhigh': 'XHigh',
'ai.codebuddy.effort.max': 'Max',
'ai.codebuddy.effort.hint': 'Управляет глубиной рассуждения модели. Для простых команд используйте Minimal/Low, чтобы экономить токены, а для сложной диагностики — Max/High.',
'ai.codebuddy.effort.minimal': 'Минимальная',
'ai.codebuddy.effort.low': 'Низкая',
'ai.codebuddy.effort.medium': 'Средняя',
'ai.codebuddy.effort.high': 'Высокая',
'ai.codebuddy.effort.xhigh': 'Очень высокая',
'ai.codebuddy.effort.max': 'Максимальная',
'ai.codebuddy.effort.hint': 'Для простых команд выбирайте минимальную или низкую глубину рассуждения, чтобы экономить токены. Для сложной диагностики выбирайте высокую или максимальную.',
'ai.codebuddy.maxTurns': 'Максимум шагов',
'ai.codebuddy.maxTurns.hint': 'Ограничивает максимальное число шагов диалога за запрос, предотвращая зацикливание. Оставьте пустым для значения по умолчанию.',
'ai.codebuddy.maxBudget': 'Максимальный бюджет (USD)',
@@ -274,22 +302,54 @@ export const ruAiMessages: Messages = {
'ai.grok.runtime.streamingJson.hint':
'Режим headless streaming-json (grok -p --output-format streaming-json). MCP внедряется через .grok/config.toml проекта.',
// OpenCode
'ai.opencode.title': 'OpenCode',
'ai.opencode.description': 'Подключается к OpenCode через официальный SDK. Настройте провайдеров и ключи в OpenCode, затем выберите его как внешнего агента для программирования.',
'ai.opencode.detecting': 'Поиск…',
'ai.opencode.detected': 'Найден',
'ai.opencode.notFound': 'Не найден',
'ai.opencode.path': 'Путь:',
'ai.opencode.notFoundHint': 'Не удалось найти opencode в PATH. Установите OpenCode или укажите путь к исполняемому файлу ниже.',
'ai.opencode.customPathPlaceholder': 'например, /usr/local/bin/opencode',
'ai.opencode.check': 'Проверить',
'ai.opencode.resetPath': 'Сбросить',
'ai.opencode.v2.startupTimeout': 'OpenCode 2 не успел запуститься. Убедитесь, что команда `opencode serve` работает в терминале, и повторите попытку.',
'ai.opencode.v2.exited': 'OpenCode 2 завершил работу до запуска чата.',
'ai.opencode.v2.unauthorized': 'OpenCode 2 отклонил подключение. Повторите попытку в чате.',
'ai.opencode.v2.unavailable': 'Не удалось подключиться к OpenCode 2. Проверьте, установлен ли он, и повторите попытку.',
'ai.opencode.v2.sessionFailed': 'OpenCode 2 не смог завершить обработку запроса.',
'ai.opencode.v2.empty': 'OpenCode 2 вернул пустой ответ. Запустите `opencode` в терминале, чтобы настроить вход и модели.',
'ai.opencode.v2.contextSkipped': 'OpenCode 2 не смог использовать контекст чата Netcatty.',
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
// MiMo Code
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
'ai.mimo.detecting': 'Поиск…',
'ai.mimo.detected': 'Найден',
'ai.mimo.notFound': 'Не найден',
'ai.mimo.path': 'Путь:',
'ai.mimo.notFoundHint': 'Не удалось найти mimo в PATH. Установите MiMo Code или укажите путь к исполняемому файлу ниже.',
'ai.mimo.customPathPlaceholder': 'например, /usr/local/bin/mimo',
'ai.mimo.check': 'Проверить',
'ai.mimo.resetPath': 'Сбросить',
// AI Default Agent
'ai.defaultAgent': 'Агент по умолчанию',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске нового сеанса ИИ',
'ai.defaultAgent.catty': 'Catty (встроенный)',
'ai.defaultAgent.unavailable': 'Недоступен',
'ai.toolAccess.title': 'Доступ к инструментам',
'ai.toolAccess.mode': 'Режим доступа Netcatty',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сеансам Netcatty. MCP предоставляет встроенный сервер, а режим «Навыки + CLI» указывает агентам на локальный навык Netcatty и команды CLI.',
'ai.toolAccess.mode.mcp': 'MCP',
'ai.toolAccess.mode.skills': 'Skills + CLI',
'ai.toolAccess.mode.skills': 'Навыки + CLI',
'ai.toolAccess.mcpPrompt.title': 'Промпт для вашего ИИ-клиента',
'ai.toolAccess.mcpPrompt.description': 'Вставьте этот промпт в ИИ-клиент (Codex, Claude Code и т. д.), и он сам зарегистрирует MCP Netcatty.',
'ai.toolAccess.mcpPrompt.enableHint': 'Включите внешний MCP ниже, чтобы в промпт попал путь к лаунчеру.',
'ai.toolAccess.skills.file': 'Файл skill',
'ai.toolAccess.skills.description': 'В режиме Skills + CLI агенты автоматически получают путь к этому локальному skill-файлу. Путь к лаунчеру Netcatty CLI передаётся агенту в каждой сессии.',
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
'ai.toolAccess.skills.file': 'Файл навыка',
'ai.toolAccess.skills.description': 'В режиме «Навыки + CLI» агенты автоматически получают путь к локальному файлу навыка. Путь к файлу запуска Netcatty CLI передаётся агенту в каждом сеансе.',
'ai.toolAccess.skills.unavailable': 'Путь к файлу навыка недоступен',
'ai.externalMcp.title': 'Внешний MCP',
'ai.externalMcp.allowCommandOnHost': 'Всегда',
@@ -323,13 +383,13 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.sessionIdleTimeout': 'Тайм-аут открытого сеанса',
'ai.externalMcp.sessionIdleTimeout.description': 'Автоматически закрывать сеансы, открытые ИИ, после указанного числа минут без операций терминала или файлов.',
'ai.externalMcp.usage.title': 'Как пользоваться',
'ai.externalMcp.usage.keepRunning': '1. Включите External MCP и держите Netcatty запущенным.',
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный launcher (только 127.0.0.1). Discovery удаляется при отключении.',
'ai.externalMcp.usage.permissions': '3. Запись следует Settings → AI → Safety и списку блокировки команд.',
'ai.externalMcp.usage.capabilities': '4. Доступен полный catalog: терминал, SFTP, Vault и проброс портов. Секреты не возвращаются.',
'ai.externalMcp.help.ariaLabel': 'Справка External MCP',
'ai.externalMcp.usage.keepRunning': '1. Включите внешний MCP и оставьте Netcatty запущенным.',
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный файл запуска (только 127.0.0.1). При отключении файл обнаружения удаляется.',
'ai.externalMcp.usage.permissions': '3. Для операций записи действуют параметры в разделе «Настройки → ИИ → Безопасность» и список заблокированных команд.',
'ai.externalMcp.usage.capabilities': '4. Доступен полный каталог: терминал, SFTP, хранилище и проброс портов. Секреты не возвращаются.',
'ai.externalMcp.help.ariaLabel': 'Справка по внешнему MCP',
'ai.externalMcp.security': 'Безопасность',
'ai.externalMcp.security.description': 'Слушает только 127.0.0.1 с ротацией token, использует AI Permission Mode для записи и удаляет discovery при отключении.',
'ai.externalMcp.security.description': 'Принимает подключения только на 127.0.0.1, обновляет токен, применяет режим разрешений ИИ к операциям записи и удаляет файл обнаружения при отключении. Локальный мост приложения работает без OAuth.',
"ai.privacy.title": "Конфиденциальность ИИ",
"ai.privacy.description": "Фильтрует известные шаблоны конфиденциального текста в контексте и результатах инструментов, управляемых Netcatty, для Catty, встроенных агентов и внешних MCP-клиентов. По умолчанию отключено. Не обнаруживает все секреты. При включении двоичные ответы инструментов блокируются.",
"ai.privacy.boundary": "Защищаются только данные и инструменты, управляемые Netcatty. Собственные инструменты сторонних агентов, их прямой доступ к файлам и другие MCP-серверы не входят в эту область.",
@@ -362,11 +422,11 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.http.invalidClientHost': 'Адрес клиента должен быть доступным IP, а не 0.0.0.0 или ::.',
'ai.externalMcp.http.warning': 'Прослушивание не только 127.0.0.1 открывает External MCP другим машинам, которые могут достичь этого адреса. Храните bearer token в секрете и не публикуйте этот порт.',
'ai.externalMcp.http.url': 'URL',
'ai.externalMcp.http.token': 'Bearer token',
'ai.externalMcp.http.token': 'Токен Bearer',
'ai.externalMcp.http.regenerate': 'Создать заново',
'ai.externalMcp.http.regenerateHint': 'Выпускает новый bearer token. HTTP-клиенты должны использовать новый token. Файл discovery для stdio обновляется; уже подключенные stdio-клиенты остаются подключенными.',
'ai.externalMcp.http.wslHint': 'При mirrored networking в WSL достаточно localhost. Иначе слушайте 0.0.0.0 или IP vEthernet и укажите IP узла Windows как адрес клиента.',
'ai.externalMcp.http.codexSnippet': 'Codex config.toml',
'ai.externalMcp.http.codexSnippet': 'Файл config.toml для Codex',
'ai.externalMcp.http.claudeCommand': 'Claude Code',
'ai.externalMcp.http.genericSnippet': 'Общий JSON',
'ai.externalMcp.http.envLine': 'Переменная окружения token для Codex',
@@ -380,12 +440,12 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.http.legacySseNote': 'Устаревший HTTP+SSE (2024-11-05) не предоставляется. Используйте этот URL Streamable HTTP.',
'ai.externalMcp.permissionMode': 'Текущий режим разрешений: {mode}',
'ai.externalMcp.permissionMode.label': 'Режим разрешений на запись',
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что Settings → AI → Safety. Auto выполняет write-инструменты Netcatty без запросов; Confirm спрашивает каждый раз. Внешние клиенты (Codex / Claude / Grok) могут показывать своё подтверждение инструментов.',
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что в разделе «Настройки → ИИ → Безопасность». В режиме «Авто» Netcatty выполняет операции записи без запроса. В режиме «Подтверждение» Netcatty запрашивает разрешение каждый раз. Внешние клиенты (Codex, Claude, Grok) могут запрашивать собственное подтверждение.',
'ai.externalMcp.permissionMode.unknown': 'Неизвестно',
'ai.externalMcp.discovery': 'Discovery',
'ai.externalMcp.launcher': 'Launcher',
'ai.externalMcp.discovery': 'Файл обнаружения',
'ai.externalMcp.launcher': 'Файл запуска',
'ai.externalMcp.unavailable': 'Недоступно',
'ai.externalMcp.bridgeUnavailable': 'Мост External MCP недоступен',
'ai.externalMcp.bridgeUnavailable': 'Мост внешнего MCP недоступен',
'ai.externalMcp.copy': 'Копировать',
'ai.externalMcp.copied': 'Скопировано',
'ai.externalMcp.copyFailed': 'Не удалось скопировать. Скопируйте вручную.',
@@ -440,7 +500,7 @@ export const ruAiMessages: Messages = {
// AI Quick Messages
'ai.quickMessages.title': 'Быстрые сообщения',
'ai.quickMessages.description': 'Создавайте часто используемые подсказки и вставляйте их в AI-чат через / или кнопку быстрых сообщений. В отличие от user skills, быстрые сообщения заполняют поле ввода текстом.',
'ai.quickMessages.description': 'Создавайте подсказки для повторного использования. Чтобы вставить текст подсказки в поле ввода чата с ИИ, наберите / или нажмите кнопку быстрых сообщений.',
'ai.quickMessages.add': 'Добавить быстрое сообщение',
'ai.quickMessages.createTitle': 'Новое быстрое сообщение',
'ai.quickMessages.editTitle': 'Редактировать быстрое сообщение',
@@ -462,14 +522,14 @@ export const ruAiMessages: Messages = {
'ai.quickMessages.error.maxItems': 'Можно сохранить не более {max} быстрых сообщений.',
// AI Chat
'ai.chat.noProvider': 'AI-провайдер не настроен. Перейдите в **Настройки → AI → Провайдеры**, чтобы добавить и включить провайдера.',
'ai.chat.noProvider': 'Провайдер ИИ не настроен. Перейдите в **Настройки → ИИ → Провайдеры**, чтобы добавить и включить провайдера.',
'ai.chat.toolDenied': 'Действие было отклонено пользователем.',
'ai.chat.toolApproved': 'Одобрено',
'ai.chat.toolApprovalHint': 'Enter — разрешить один раз, Escape — отклонить',
'ai.chat.approve': 'Одобрить',
'ai.chat.approveOnce': 'Разрешить один раз',
'ai.chat.alwaysAllow': 'Всегда разрешать',
'ai.chat.slashStopDesc': 'Остановить текущий ход AI и отменить выполняющиеся инструменты',
'ai.chat.slashStopDesc': 'Остановить текущий ход ИИ и отменить выполняющиеся инструменты',
'ai.chat.slashCompactDesc': 'Сжать ранний контекст разговора',
'ai.chat.slashRenameDesc': 'Переименовать текущий чат (/rename <название>)',
'ai.chat.slashChatsDesc': 'Показать чаты, видимые в этой панели',
@@ -480,12 +540,12 @@ export const ruAiMessages: Messages = {
'ai.chat.copyCommand': 'Копировать',
'ai.chat.commandCopied': 'Скопировано',
'ai.chat.approvalSession': 'Сессия',
'ai.chat.approvalShell': 'Shell',
'ai.chat.approvalShell': 'Оболочка',
'ai.chat.approvalCwd': 'Каталог',
'ai.chat.approvalReason': 'Причина',
'ai.chat.approvalInvocation': 'Вызов',
'ai.chat.permissionRequired': 'Требуется разрешение',
'ai.chat.permissionDescription': 'AI-агент хочет выполнить вызов инструмента, для которого требуется ваше одобрение.',
'ai.chat.permissionDescription': 'Агент ИИ хочет вызвать инструмент, для которого требуется ваше разрешение.',
'ai.chat.commandBlocked': 'Эта команда заблокирована вашей политикой безопасности и не может быть выполнена.',
'ai.chat.recommendAllow': 'Разрешить',
'ai.chat.recommendConfirm': 'Подтвердить',
@@ -511,7 +571,7 @@ export const ruAiMessages: Messages = {
'ai.chat.placeholder': 'Сообщение {agent} — @ для добавления контекста, / для команд',
'ai.chat.placeholderDefault': 'Сообщение агенту Catty...',
'ai.chat.noModel': 'Нет модели',
'ai.chat.noProviderModel': 'Модель по умолчанию не задана — настройте её в Настройки → AI → Провайдеры.',
'ai.chat.noProviderModel': 'Модель по умолчанию не задана. Выберите её в разделе «Настройки → ИИ → Провайдеры».',
'ai.chat.selectProvider': 'Выберите провайдера',
'ai.chat.selectProviderAndModel': 'Выберите провайдера и модель',
'ai.chat.selectModel': 'Выберите модель',
@@ -548,7 +608,7 @@ export const ruAiMessages: Messages = {
'ai.chat.importNone': 'В выбранном файле не найдено чатов ИИ.',
'ai.chat.chatsHeader': 'Чаты, видимые в этой панели:',
'ai.chat.chatsEmpty': 'В этой панели нет видимых чатов.',
'ai.chat.chatsScopeWorkspace': 'Workspace',
'ai.chat.chatsScopeWorkspace': 'Рабочая область',
'ai.chat.chatsScopeTerminal': 'Терминал',
'ai.chat.chatsScopeGlobal': 'Глобально',
'ai.chat.chatsScopeDangling': 'Связь потеряна',
@@ -568,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}ч назад',
@@ -617,16 +684,25 @@ export const ruAiMessages: Messages = {
'ai.chat.slashUserSkills': 'Пользовательские навыки',
'ai.chat.quickMessages': 'Команды /',
'ai.chat.slashNoResults': 'Нет подходящих команд',
'ai.chat.slashEmptyHint': 'Добавьте подсказки в Настройки → AI → Быстрые сообщения.',
'ai.chat.slashEmptyHint': 'Добавьте подсказки в разделе «Настройки → ИИ → Быстрые сообщения».',
// AI Chat Shortcuts
'ai.chatShortcuts.title': 'Быстрые действия чата',
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку AI рядом с выделенным текстом терминала.',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
'ai.chatHistory.title': 'История чата',
'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 и попробуйте снова.',
@@ -634,7 +710,7 @@ export const ruAiMessages: Messages = {
// AI Web Search
'ai.webSearch.title': 'Веб-поиск',
'ai.webSearch.enable': 'Включить веб-поиск',
'ai.webSearch.enable.description': 'Разрешить AI-агенту искать в интернете актуальную информацию.',
'ai.webSearch.enable.description': 'Разрешить агенту ИИ искать в интернете актуальную информацию.',
'ai.webSearch.provider': 'Провайдер поиска',
'ai.webSearch.provider.description': 'Выберите провайдера API веб-поиска.',
'ai.webSearch.apiKey': 'API-ключ',
@@ -649,7 +725,7 @@ export const ruAiMessages: Messages = {
// AI Safety Settings
'ai.safety.title': 'Безопасность',
'ai.safety.permissionMode': 'Режим разрешений',
'ai.safety.permissionMode.description': 'Управляет тем, как AI взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
'ai.safety.permissionMode.description': 'Управляет тем, как ИИ взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
'ai.safety.permissionMode.observer': 'Наблюдатель — только чтение, без действий',
'ai.safety.permissionMode.confirm': 'Подтверждение — спрашивать перед действиями',
'ai.safety.permissionMode.auto': 'Авто — выполнять свободно',
@@ -660,7 +736,7 @@ export const ruAiMessages: Messages = {
'ai.safety.responseIdleTimeout.description': 'Отменяет запрос встроенного ИИ после указанного числа секунд без нового ответа. Не управляет общей длительностью ответа и выполнением команд.',
'ai.safety.responseIdleTimeout.unit': 'с',
'ai.safety.maxIterations': 'Макс. число итераций',
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов ИИ, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
'ai.safety.toolOutputMaxChars.unit': 'симв.',
@@ -693,12 +769,15 @@ export const ruAiMessages: Messages = {
'terminal.layer.history': 'История',
'terminal.layer.theme': 'Тема',
'terminal.layer.notes': 'Заметки',
'terminal.layer.aiChat': 'AI-чат',
'terminal.layer.aiChat': 'Чат с ИИ',
'terminal.layer.choosePanelPosition': 'Изменить положение',
'terminal.layer.dockLeft': 'Слева',
'terminal.layer.dockRight': 'Справа',
'terminal.layer.dockBottom': 'Снизу',
'terminal.layer.closePanel': 'Закрыть панель',
'terminal.layer.saveLayoutAsDefault': 'Сохранить расположение панелей по умолчанию',
'terminal.layer.layoutSavedAsDefault': 'Расположение панелей по умолчанию сохранено',
'terminal.layer.layoutSaveFailed': 'Не удалось сохранить расположение панелей',
'terminal.layer.closePane': 'Закрыть область',
'terminal.layer.resizeSplit': 'Изменить размер области',
'terminal.layer.splitHorizontal': 'Разделить сверху и снизу',
@@ -718,9 +797,15 @@ export const ruAiMessages: Messages = {
'terminal.layer.hostTree.collapse': 'Свернуть список хостов',
'terminal.layer.hostTree.expand': 'Развернуть список хостов',
'terminal.layer.hostTree.empty': 'Хосты не найдены',
'terminal.layer.hostTree.details.host': 'Хост',
'terminal.layer.hostTree.details.user': 'Пользователь',
'terminal.layer.hostTree.details.port': 'Порт',
'terminal.layer.hostTree.details.protocol': 'Протокол',
'terminal.layer.hostTree.details.group': 'Группа',
'terminal.layer.hostTree.details.tags': 'Теги',
'topTabs.openQuickSwitcher': 'Открыть быстрый переключатель',
'topTabs.moreTabs': 'Больше вкладок',
'topTabs.aiAssistant': 'AI-помощник',
'topTabs.aiAssistant': 'ИИ-помощник',
'topTabs.controlPanel': 'Быстрые настройки',
'topTabs.controlPanel.externalMcp': 'Внешний MCP',
'topTabs.controlPanel.theme': 'Тема',
+170 -33
View File
@@ -8,7 +8,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.github.busy": "Загрузка, проверка или установка пакета...",
"settings.plugins.github.review": "Источник и целостность пакета не подтверждают доверие к издателю. Скрипты сборки не запускаются. Плагин устанавливается выключенным; проверьте разрешения перед включением.",
"settings.plugins.github.accept": "Я доверяю этому репозиторию и проверил заявленные разрешения.",
"settings.plugins.github.confirm": "Установить выключенным",
"settings.plugins.github.confirm": "Установить",
"settings.plugins.github.download": "Загрузить и проверить",
"settings.plugins.github.error.invalidRepository": "Введите https://github.com/owner/repo, github.com/owner/repo или owner/repo. Укажите только репозиторий, без учётных данных, параметров, фрагментов и дополнительных путей.",
"settings.plugins.github.error.unavailable": "Установка плагинов из GitHub недоступна в этом сеансе.",
@@ -38,6 +38,33 @@ export const ruCoreMessages: Messages = {
"settings.plugins.github.error.failed": "Не удалось проверить или установить плагин. Изучите технические подробности перед повторной попыткой.",
"settings.plugins.github.error.details": "Технические подробности",
"settings.plugins.landing.checkUpdates": "Проверить обновления",
"settings.plugins.landing.checkingUpdates": "Проверка…",
"settings.plugins.landing.updateSummary": "Проверено: {checked} · Опубликовано обновлений: {updates} · Пропущено: {skipped}.",
"settings.plugins.landing.updateSourcesFailed": "Недоступных источников: {count}.",
"settings.plugins.landing.updateReview": "Перед установкой проверьте обновления в менеджере плагинов.",
"settings.plugins.landing.updateAvailable": "Доступна версия {version}",
"settings.plugins.landing.loading": "Загрузка установленных плагинов…",
"settings.plugins.landing.settingsUnavailable": "Здесь настройки плагинов недоступны.",
"settings.plugins.landing.options": "Параметры плагина",
"settings.plugins.landing.manager": "Менеджер плагинов",
"settings.plugins.landing.managerDescription": "Просматривайте плагины и управляйте установленными пакетами и источниками.",
"settings.plugins.landing.browse": "Обзор",
"settings.plugins.landing.refresh": "Обновить список установленных плагинов",
"settings.plugins.landing.unavailable": "Управление плагинами недоступно в этом сеансе.",
"settings.plugins.landing.empty": "Плагины ещё не установлены. Откройте менеджер плагинов, чтобы посмотреть доступные варианты.",
"settings.plugins.landing.search": "Поиск установленных плагинов",
"settings.plugins.landing.settingsFor": "Настройки плагина {name}",
"settings.plugins.landing.enableSettings": "Включите плагин, чтобы открыть его настройки.",
"settings.plugins.landing.sourceUnknown": "Источник неизвестен",
"settings.plugins.landing.status.running": "Работает",
"settings.plugins.landing.status.starting": "Запускается",
"settings.plugins.landing.status.stopping": "Останавливается",
"settings.plugins.landing.status.error": "Ошибка",
"settings.plugins.landing.status.quarantined": "В карантине",
"settings.plugins.landing.status.unknown": "Состояние неизвестно",
"settings.plugins.landing.status.idle": "Включён, не запущен",
// Common
'common.save': 'Сохранить',
'common.cancel': 'Отмена',
@@ -150,7 +177,7 @@ export const ruCoreMessages: Messages = {
'settings.tab.appearance': 'Внешний вид',
'settings.tab.terminal': 'Терминал',
'settings.tab.shortcuts': 'Горячие клавиши',
'settings.tab.ai': 'AI',
'settings.tab.ai': 'ИИ',
'settings.tab.syncCloud': 'Синхронизация и облако',
'settings.tab.system': 'Система',
'settings.search.open': 'Поиск настроек',
@@ -245,7 +272,7 @@ export const ruCoreMessages: Messages = {
// Settings > System > Network Proxy
'settings.system.networkProxy.title': 'Сетевой прокси',
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и AI-провайдеров. Не связан с SSH ProxyJump / ProxyCommand.',
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и провайдеров ИИ. Не связан с SSH ProxyJump / ProxyCommand.',
'settings.system.networkProxy.mode': 'Режим прокси',
'settings.system.networkProxy.mode.system': 'Системный прокси',
'settings.system.networkProxy.mode.direct': 'Напрямую (без прокси)',
@@ -256,7 +283,7 @@ export const ruCoreMessages: Messages = {
'settings.system.networkProxy.bypass': 'Список исключений',
'settings.system.networkProxy.bypass.placeholder': '<local>,localhost,127.0.0.1',
'settings.system.networkProxy.bypass.desc': 'Хосты через запятую, для которых прокси не используется. <local> — localhost и локальные имена.',
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive / OneDrive / GitHub sync и запросы к AI-провайдерам. SSH-подключения не меняет.',
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive, OneDrive и GitHub для синхронизации и на запросы к провайдерам ИИ. SSH-подключения не меняет.',
// Settings > System > Crash Logs
'settings.system.crashLogs.title': 'Журналы сбоев',
@@ -296,6 +323,21 @@ export const ruCoreMessages: Messages = {
'settings.update.autoUpdateEnabled': 'Автоматические обновления',
'settings.update.autoUpdateEnabledDesc': 'Автоматически проверять и загружать обновления, когда они доступны.',
// Settings > Session Restore
'settings.sessionRestore.title': 'Восстановление сеансов',
'settings.sessionRestore.startupLanding': 'При запуске',
'settings.sessionRestore.startupLandingDesc': 'Выберите, что открывать при запуске Netcatty, если сеансы не восстановлены: главную страницу с хостами или локальный терминал.',
'settings.sessionRestore.startupLanding.vault': 'Главная (хосты)',
'settings.sessionRestore.startupLanding.localTerminal': 'Локальный терминал',
'settings.sessionRestore.restorePreviousSession': 'Восстанавливать вкладки и рабочие области',
'settings.sessionRestore.restorePreviousSessionDesc': 'Открывать вкладки терминала и восстанавливать расположение панелей в рабочих областях из предыдущего сеанса приложения.',
'settings.sessionRestore.restoreTerminalCwd': 'Восстанавливать рабочий каталог терминала',
'settings.sessionRestore.restoreTerminalCwdDesc': 'При переподключении восстановленного терминала пытаться перейти в последний известный рабочий каталог, не задерживая подключение.',
'terminal.restore.placeholder.title': 'Восстановленный сеанс',
'terminal.restore.placeholder.desc': 'Терминал отключён. Подключитесь снова, чтобы запустить новую оболочку в этой вкладке.',
'terminal.restore.placeholder.reconnect': 'Переподключиться',
'terminal.restore.cwdLog': 'Восстановление рабочего каталога: {cwd}',
// Settings > Session Logs
'settings.sessionLogs.title': 'Журналы сессий',
'settings.sessionLogs.description': 'Настройка экспорта журналов сессий и параметров автосохранения.',
@@ -388,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 отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
@@ -495,7 +539,7 @@ export const ruCoreMessages: Messages = {
### Боковая панель терминала
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / AI (только пока открыта)
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / ИИ (только пока открыта)
- \`terminal-side-panel-tabs\`
- \`terminal-side-panel-content\`
@@ -597,6 +641,7 @@ export const ruCoreMessages: Messages = {
'settings.terminal.section.keyboard': 'Клавиатура',
'settings.terminal.section.accessibility': 'Доступность',
'settings.terminal.section.behavior': 'Поведение',
'settings.terminal.section.sidePanel': 'Боковая панель',
'settings.terminal.section.scrollback': 'Буфер прокрутки',
'settings.terminal.section.keywordHighlight': 'Подсветка ключевых слов',
'settings.terminal.font.family': 'Шрифт',
@@ -822,6 +867,18 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShell.startDir.placeholder': 'Домашний каталог',
'settings.terminal.localShell.startDir.notFound': 'Каталог не найден',
'settings.terminal.localShell.startDir.isFile': 'Путь указывает на файл, а не на каталог',
'settings.terminal.sidePanel.autoOpen': 'Открывать боковую панель при подключении',
'settings.terminal.sidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после подключения терминала.',
'settings.terminal.sidePanel.autoOpenPane': 'Боковая панель по умолчанию',
'settings.terminal.sidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.sidePanel.pane.sftp': 'SFTP',
'settings.terminal.sidePanel.pane.scripts': 'Скрипты',
'settings.terminal.sidePanel.pane.history': 'История',
'settings.terminal.sidePanel.pane.theme': 'Тема',
'settings.terminal.sidePanel.pane.system': 'Система',
'settings.terminal.sidePanel.pane.notes': 'Заметки',
'settings.terminal.sidePanel.pane.ai': 'ИИ',
'settings.terminal.section.localShellSidePanel': 'Боковая панель локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen': 'Развернуть боковую панель при открытии локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
@@ -829,10 +886,14 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.localShellSidePanel.pane.files': 'Файлы',
'settings.terminal.section.connection': 'Подключение',
'settings.terminal.connection.verifyHostKeys': 'Проверять ключи SSH-хостов',
'settings.terminal.connection.verifyHostKeys.desc': 'Запрашивать подтверждение при подключении к SSH-хосту с новым или изменившимся ключом. Отключайте проверку только в доверенных частных сетях.',
'settings.terminal.connection.temporaryLegacyAlgorithms': 'Устаревшие алгоритмы для временных подключений',
'settings.terminal.connection.temporaryLegacyAlgorithms.desc': 'SSH-подключения без сохранённого хоста, включая запуск в стиле PuTTY и быстрое подключение, предлагают те же устаревшие алгоритмы, что и настройка хоста. Сохранённые хосты используют свою настройку. По умолчанию выключено: у этих алгоритмов есть известные слабости.',
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Режим сетевого устройства для временных подключений',
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'SSH-подключения без сохранённого хоста, включая внешний запуск и быстрое подключение, открываются в режиме сетевого устройства. Сохранённые хосты и группы сохраняют свой тип устройства. По умолчанию выключено.',
'settings.terminal.connection.sshAutoReconnectEnabled': 'Автоматически переподключать SSH-сеансы',
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'При неожиданном разрыве SSH-соединения повторять попытки с заданным интервалом, пока соединение не восстановится или вкладка не будет закрыта.',
'settings.terminal.connection.sshAutoReconnectInterval': 'Интервал переподключения SSH (секунды)',
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Ожидание между попытками: 5–3600 секунд (по умолчанию 5). Изменение применяется к следующему ожиданию; уже запущенный таймер не меняется.',
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
@@ -872,6 +933,18 @@ export const ruCoreMessages: Messages = {
'settings.terminal.rendering.renderer': 'Рендерер',
'settings.terminal.rendering.renderer.desc': 'Выберите технологию рендеринга терминала. В режиме "Авто" на устройствах с малым объёмом памяти будет использоваться DOM. Изменения применяются к новым терминальным сессиям.',
'settings.terminal.rendering.auto': 'Авто',
'settings.terminal.rendering.hibernateHiddenTabs': 'Переводить скрытые вкладки в спящий режим',
'settings.terminal.rendering.hibernateHiddenTabs.desc': 'В спящем режиме скрытые вкладки освобождают память, занятую рендерером, и сохраняют SSH-соединение. Во время передачи файлов режим не включается.',
'settings.terminal.rendering.hibernateHiddenTabsDelay': 'Задержка перед переходом в спящий режим',
'settings.terminal.rendering.hibernateHiddenTabsDelay.desc': 'Сколько времени вкладка должна оставаться скрытой до освобождения рендерера (5–600 секунд).',
'settings.terminal.rendering.hibernateSkipAltScreen': 'Отключать спящий режим для полноэкранных приложений',
'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'Сохранять рендерер терминала, пока vim, htop или агенты с текстовым интерфейсом используют альтернативный экранный буфер.',
'settings.terminal.rendering.hibernateKeepRendererCount': 'Сохранять рендереры скрытых вкладок',
'settings.terminal.rendering.hibernateKeepRendererCount.desc': 'Количество скрытых вкладок, для которых рендерер сохраняется с приостановленным WebGL перед переходом в спящий режим.',
'settings.terminal.rendering.hibernateReplayChunkBytes': 'Объём вывода за кадр при восстановлении',
'settings.terminal.rendering.hibernateReplayChunkBytes.desc': 'Сколько данных вывода восстанавливать за один кадр анимации при выходе терминала из спящего режима (4–64 КБ).',
'settings.terminal.rendering.hibernatePreferWasmSerialize': 'Предпочитать сериализацию через WASM',
'settings.terminal.rendering.hibernatePreferWasmSerialize.desc': 'По возможности сериализовать состояние терминала через WASM. Если WASM недоступен, использовать JavaScript.',
// Settings > Terminal > Inline Images
'settings.terminal.section.inlineImages': 'Встроенные изображения',
@@ -975,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': 'Переключить прозрачность окна',
@@ -1087,6 +1161,16 @@ export const ruCoreMessages: Messages = {
'vault.nav.notes': 'Заметки',
'vault.nav.knownHosts': 'Известные хосты',
'vault.nav.logs': 'Журналы',
'vault.nav.customize': 'Настроить боковую панель',
'vault.nav.customizeHint': 'Перетаскивайте элементы для сортировки или переключения видимости.',
'vault.nav.hideItem': 'Скрыть «{label}»',
'vault.nav.moveUp': 'Переместить выше',
'vault.nav.moveDown': 'Переместить ниже',
'vault.nav.resetDefault': 'Сбросить по умолчанию',
'vault.nav.alwaysVisible': 'Всегда видно',
'vault.nav.pluginBadge': 'Плагин',
'vault.nav.dragToReorder': 'Перетащите, чтобы изменить порядок «{label}»',
'vault.nav.toggleVisibility': 'Переключить видимость «{label}»',
'proxyProfiles.action.add': 'Добавить прокси',
'proxyProfiles.search.placeholder': 'Поиск прокси…',
@@ -1129,6 +1213,7 @@ export const ruCoreMessages: Messages = {
'vault.groups.selectedCount': 'Выбрано групп: {count}',
'vault.groups.deleteMultiple.success': 'Удалено выбранных элементов: {count}',
'vault.groups.ungrouped': 'Без группы',
'vault.groups.unnamed': 'Группа без имени',
'vault.groups.field.name': 'Имя группы',
'vault.groups.placeholder.example': 'например, Production',
'vault.groups.parentLabel': 'Родитель',
@@ -1137,7 +1222,10 @@ export const ruCoreMessages: Messages = {
'vault.groups.details': 'Сведения о группе',
'vault.groups.details.general': 'Общие',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'Параметры {protocol} по умолчанию для этой группы ещё не настроены.',
'vault.groups.details.advanced': 'Дополнительно',
'vault.groups.details.appearance': 'Внешний вид',
'vault.groups.details.mosh': 'Mosh',
@@ -1163,6 +1251,7 @@ export const ruCoreMessages: Messages = {
'vault.hosts.header.entries': 'Записей: {count}',
'vault.hosts.header.live': 'Активных: {count}',
'vault.hosts.errors.nameRequired': 'Укажите имя хоста.',
'deepLink.ssh.invalid': 'Недопустимая ссылка ssh://',
'deepLink.telnet.invalid': 'Недопустимая ссылка telnet://',
'deepLink.jms.invalid': 'Недопустимая ссылка JumpServer',
@@ -1185,7 +1274,12 @@ export const ruCoreMessages: Messages = {
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
"plugins.sidebar.loading": "Загрузка страницы расширения…",
"plugins.vault.loading": "Загрузка страницы плагина…",
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
"plugins.vault.retry": "Повторить",
"plugins.interaction.title": "Запрос плагина",
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
"plugins.interaction.openUrlAction": "Открыть URL",
"plugins.interaction.sharing": "Переданный текст доступен плагину и его разрешённым возможностям, включая сеть. Чтение не разрешает новый сетевой адрес.",
"plugins.interaction.input": "Ввести текст",
"plugins.interaction.filter": "Фильтр вариантов",
@@ -1196,15 +1290,19 @@ export const ruCoreMessages: Messages = {
"plugins.interaction.copy": "Копировать в буфер обмена",
"plugins.interaction.failed": "Запрос истёк или не выполнен.",
"plugins.command.failed": "Не удалось выполнить команду плагина. Проверьте необходимые выбранные объекты и разрешения.",
"plugins.interaction.terminalDisclosure": "Only the current selection from this terminal is shared, up to 4096 UTF-8 bytes. Terminal text can contain passwords, tokens, and other secrets. Inspect the exact preview before sharing. No redaction guarantee is made.",
"plugins.interaction.terminalTarget": "Selected terminal",
"plugins.interaction.terminalPreview": "Preview terminal selection",
"plugins.interaction.draftNote": "Editable draft for review only. This dialog sends no terminal input or Enter. Copy text yourself and use the normal terminal UI if you choose to send it. Your edits stay in this dialog.",
"plugins.interaction.draft": "Terminal input draft",
"plugins.interaction.exactText": "Exact text with escaped controls",
"plugins.interaction.closeDraft": "Close draft",
"plugins.interaction.terminalDisclosure": "Плагину передаётся только выделенный в этом терминале текст (до 4096 байт в UTF-8). Он может содержать пароли, токены и другие секреты. Перед передачей проверьте текст целиком. Автоматическое скрытие секретов не гарантируется.",
"plugins.interaction.terminalTarget": "Выбранный терминал",
"plugins.interaction.terminalPreview": "Предпросмотр выделенного текста",
"plugins.interaction.draftNote": "Здесь можно просмотреть и отредактировать черновик. Диалог не отправляет в терминал текст или нажатие Enter. Чтобы отправить текст, скопируйте его и вставьте в терминал. Изменения сохраняются только в этом диалоге.",
"plugins.interaction.draft": "Черновик ввода в терминал",
"plugins.interaction.exactText": "Исходный текст с экранированными управляющими символами",
"plugins.interaction.closeDraft": "Закрыть черновик",
"settings.plugins.permissions.current": "Соответствует текущему запуску",
"settings.plugins.permissions.inactive": "Не действует для текущего запуска",
"settings.plugins.permissions.note": "Заявленные возможности по умолчанию разрешены. В режиме «Спрашивать» Netcatty запрашивает разрешение с ограниченной областью действия. Режим «Запретить» сразу блокирует доступ. Цель можно выбрать, а черновик отредактировать в интерфейсе Netcatty.",
"settings.plugins.permissions.allow": "Разрешить",
"settings.plugins.permissions.ask": "Спрашивать",
"settings.plugins.permissions.deny": "Запретить",
"settings.plugins.permissions.title": "Сохранённые разрешения",
"settings.plugins.permissions.refresh": "Обновить",
"settings.plugins.permissions.loading": "Загрузка разрешений...",
@@ -1214,7 +1312,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.permissions.session": "До закрытия сеанса",
"settings.plugins.permissions.audit": "Последние события безопасности (до 100)",
"settings.plugins.permissions.revoke": "Отключить и отозвать все разрешения",
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения удалены. Включите его для нового запроса доступа.",
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения отозваны. Выбранные режимы «Разрешить», «Спрашивать» и «Запретить» сохранятся.",
"settings.plugins.permissions.unavailable": "Управление разрешениями недоступно",
"settings.plugins.manager.permissions": "Заявленные разрешения",
"settings.plugins.manager.permissionNote": "Заявленные поддерживаемые возможности по умолчанию разрешены. Для каждой можно выбрать запрос или запрет в настройках разрешений. Проверки приложения и область ресурсов действуют всегда.",
@@ -1255,7 +1353,10 @@ export const ruCoreMessages: Messages = {
"settings.plugins.market.title": "Каталог",
"settings.plugins.market.note": "Отобранные плагины с открытым кодом. Проверка не гарантирует безопасность. Обновления выполняются вручную.",
"settings.plugins.market.back": "Все плагины",
"settings.plugins.market.install": "Установить эту версию (отключённой)",
"settings.plugins.market.install": "Установить",
"settings.plugins.market.installing": "Установка...",
"settings.plugins.market.update": "Обновить",
"settings.plugins.market.updating": "Обновление...",
"settings.plugins.market.installNote": "Установленная версия будет заменена и остановлена. Проверьте разрешения перед включением.",
"settings.plugins.market.sourceOnly": "Пример из этого проекта. Соберите локальной CLI и импортируйте .ncpkg; готовый пакет для скачивания не опубликован.",
"settings.plugins.market.readmeNote": "Зафиксирован указанный коммит. HTML не выполняется, внешние изображения не загружаются. Текст автора плагина.",
@@ -1272,28 +1373,28 @@ export const ruCoreMessages: Messages = {
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверки приложения и выбранный режим разрешений продолжают действовать.",
"settings.plugins.openView": "Открыть",
"settings.plugins.openManager": "Открыть управление плагинами",
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
"settings.plugins.sources.conflict": "Плагин с этим идентификатором установлен из другого источника. Перед сменой источника удалите плагин и очистите его приватные данные. Текущий источник:",
"settings.plugins.sources.clearPrivate": "Также удалить приватные данные, выданные разрешения и секреты этого источника, чтобы установить плагин из другого источника. Это действие нельзя отменить.",
"settings.plugins.sources.short.official": "Официальный",
"settings.plugins.sources.short.thirdparty": "Сторонний",
"settings.plugins.sources.short.local": "Локальный",
"settings.plugins.sources.official": "Official marketplace",
"settings.plugins.sources.thirdparty": "Third-party marketplace",
"settings.plugins.sources.manage": "Manage sources",
"settings.plugins.sources.select": "Select a source",
"settings.plugins.sources.empty": "Choose or add a third-party source.",
"settings.plugins.sources.add": "Add source",
"settings.plugins.sources.remove": "Remove source",
"settings.plugins.sources.name": "Source name",
"settings.plugins.sources.address": "HTTPS source address",
"settings.plugins.sources.risk": "Third-party sources are not maintained or endorsed by Netcatty. Review the real domain, package permissions and author before installing.",
"settings.plugins.sources.accept": "I trust this domain to supply plugin metadata and packages. This does not grant plugin permissions.",
"settings.plugins.sources.removeNote": "Installed plugins and their data remain. Updates from this source stop; another source will not replace it.",
"settings.plugins.sources.disablePlugins": "Also disable plugins installed from this source",
"settings.plugins.sources.installConfirm": "Review third-party installation",
"settings.plugins.sources.source": "Source",
"settings.plugins.sources.local": "Local import",
"settings.plugins.sources.all": "All sources",
"settings.plugins.sources.official": "Официальный каталог",
"settings.plugins.sources.thirdparty": "Сторонний каталог",
"settings.plugins.sources.manage": "Управление источниками",
"settings.plugins.sources.select": "Выбрать источник",
"settings.plugins.sources.empty": "Выберите или добавьте сторонний источник.",
"settings.plugins.sources.add": "Добавить источник",
"settings.plugins.sources.remove": "Удалить источник",
"settings.plugins.sources.name": "Название источника",
"settings.plugins.sources.address": "HTTPS-адрес источника",
"settings.plugins.sources.risk": "Netcatty не поддерживает и не рекомендует сторонние источники. Перед установкой проверьте фактический домен, разрешения пакета и сведения об авторе.",
"settings.plugins.sources.accept": "Я доверяю этому домену как источнику метаданных и пакетов плагинов. Это не выдаёт плагинам разрешений.",
"settings.plugins.sources.removeNote": "Установленные плагины и их данные сохранятся. Обновления из этого источника прекратятся. Другой источник не заменит его.",
"settings.plugins.sources.disablePlugins": "Также отключить плагины из этого источника",
"settings.plugins.sources.installConfirm": "Проверка установки из стороннего источника",
"settings.plugins.sources.source": "Источник",
"settings.plugins.sources.local": "Импорт из файла",
"settings.plugins.sources.all": "Все источники",
"settings.plugins.title": "Плагины",
"settings.plugins.configuration": "Настройки плагина",
"settings.plugins.description": "Управляйте плагинами и просматривайте каталог.",
@@ -1341,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': 'Политика',
};
+18 -1
View File
@@ -26,6 +26,9 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.errors.loadDockerImages': 'Не удалось загрузить образы',
'systemManager.errors.loadKubernetes': 'Не удалось загрузить ресурсы Kubernetes',
'systemManager.errors.loadPods': 'Не удалось загрузить поды',
'systemManager.errors.nerdctlUnreachable': 'nerdctl не может подключиться к containerd',
'systemManager.errors.clusterUnreachable': 'Не удалось подключиться к кластеру для контекста {{context}}',
'systemManager.errors.clusterUnreachableGeneric': 'Не удалось подключиться к кластеру',
'systemManager.errors.loadGpu': 'Не удалось загрузить статистику GPU / NPU',
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
@@ -187,6 +190,20 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.k8s.restarts': '{{count}} перезапусков',
'systemManager.k8s.chooseContainer': 'Выберите контейнер',
'systemManager.k8s.noContext': 'На этом хосте нет контекста Kubernetes',
'systemManager.k8s.status.Running': 'Работает',
'systemManager.k8s.status.Pending': 'Ожидает запуска',
'systemManager.k8s.status.Completed': 'Завершён',
'systemManager.k8s.status.Succeeded': 'Завершён успешно',
'systemManager.k8s.status.Failed': 'Завершён с ошибкой',
'systemManager.k8s.status.Unknown': 'Состояние неизвестно',
'systemManager.k8s.status.CrashLoopBackOff': 'Циклические сбои',
'systemManager.k8s.status.ContainerCreating': 'Создаётся контейнер',
'systemManager.k8s.status.Terminating': 'Завершается',
'systemManager.k8s.status.ImagePullBackOff': 'Повтор загрузки',
'systemManager.k8s.status.ErrImagePull': 'Ошибка загрузки образа',
'systemManager.k8s.status.Error': 'Ошибка',
'systemManager.k8s.status.Evicted': 'Вытеснен',
'systemManager.k8s.status.OOMKilled': 'Нехватка памяти',
'systemManager.ports.unavailable': 'На этом хосте не обнаружены инструменты портов (ss / netstat).',
'systemManager.ports.loading': 'Загрузка слушающих портов…',
@@ -232,7 +249,7 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.services.enable': 'Включить автозапуск',
'systemManager.services.disable': 'Отключить автозапуск',
'systemManager.services.reload': 'Перезагрузить',
'systemManager.services.scope.user': 'user',
'systemManager.services.scope.user': 'Пользовательская служба',
'systemManager.services.confirmAction': '{{action}} {{name}}?',
'systemManager.gpu.unavailable': 'На этом хосте не обнаружены инструменты NVIDIA GPU или Ascend NPU.',
+33 -9
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': 'Каталоги',
@@ -15,14 +17,16 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
'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': 'Дождитесь пустой командной строки.',
'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.',
'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.',
'terminal.directory.unsupportedPath': 'Это имя каталога нельзя безопасно передать в терминал.',
'settings.terminal.behavior.contextChips': 'Context Chips',
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами.',
'settings.terminal.behavior.contextChips': 'Панель контекста',
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами в области ввода.',
'terminal.toolbar.openSessionLog': 'Открыть журнал сессии',
'terminal.toolbar.sessionLogActions': 'Действия с журналом',
@@ -75,13 +79,13 @@ export const ruTerminalMessages: Messages = {
'terminal.browser.title': 'Браузер',
'terminal.browser.sshOnly': 'Выберите SSH-терминал, чтобы открыть его браузер.',
'terminal.browser.open': 'Открыть браузер',
'terminal.toolbar.availableAfterConnect': 'Доступно после подключения',
'terminal.toolbar.availableAfterConnect': 'Нужно подключение',
'terminal.toolbar.sendYmodem': 'Отправить через YMODEM',
'terminal.toolbar.receiveYmodem': 'Получить через YMODEM',
'terminal.toolbar.more': 'Другие действия',
'terminal.toolbar.scripts': 'Скрипты',
'terminal.toolbar.history': 'История команд',
'terminal.toolbar.configureOsc7': 'Настроить отслеживание каталога',
'terminal.toolbar.configureOsc7': 'Отслеживание каталога',
'history.scope.label': 'Область истории',
'history.tab.host': 'Хост',
'history.tab.global': 'Глобальная',
@@ -236,7 +240,7 @@ export const ruTerminalMessages: Messages = {
'terminal.clipboardImageUpload.noImage': 'В буфере обмена нет изображения',
'terminal.clipboardImageUpload.failed': 'Не удалось загрузить изображение из буфера обмена',
'terminal.selection.addToAI': 'Добавить в чат',
'terminal.selection.addToAIDesc': 'Прикрепить выбранный вывод терминала к черновику AI',
'terminal.selection.addToAIDesc': 'Прикрепить выделенный вывод терминала к черновику сообщения для ИИ',
'terminal.auth.password': 'Пароль',
'terminal.auth.sshKey': 'SSH-ключ',
'terminal.auth.username': 'Имя пользователя',
@@ -273,8 +277,11 @@ export const ruTerminalMessages: Messages = {
'terminal.connection.protocol.ssh': 'SSH',
'terminal.connection.protocol.telnet': 'Telnet',
'terminal.connection.protocol.mosh': 'Mosh',
'terminal.connection.protocol.et': 'EternalTerminal',
'terminal.connection.protocol.plugin': 'Подключение плагина',
'terminal.connection.protocol.serial': 'Serial',
'terminal.et.proxyUnsupported': 'EternalTerminal пока не поддерживает настройки прокси Netcatty. Используйте SSH или уберите прокси для этого хоста.',
'terminal.et.multiJumpUnsupported': 'В Netcatty EternalTerminal пока поддерживает только один промежуточный хост.',
'terminal.connection.protocol.serial': 'Последовательный порт',
'terminal.connection.protocol.local': 'Локальная оболочка',
'terminal.hostKey.unknownTitle': 'Подтвердите этот ключ хоста',
'terminal.hostKey.changedTitle': 'Ключ хоста изменился',
@@ -485,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': 'Ошибка восстановления',
@@ -632,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': 'Ошибка экспорта',
@@ -708,6 +718,7 @@ export const ruTerminalMessages: Messages = {
'tabs.logPrefix': 'Журнал:',
'tabs.logLocal': 'Локальный',
'tabs.copyTab': 'Копировать вкладку',
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
'tabs.duplicateSession': 'Дублировать сессию',
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
@@ -736,6 +747,8 @@ export const ruTerminalMessages: Messages = {
'snippets.action.selectSnippets': 'Выбрать сниппеты',
'snippets.panel.newTitle': 'Новый сниппет',
'snippets.panel.editTitle': 'Редактировать сниппет',
'snippets.panel.newAutomationTitle': 'Новый скрипт автоматизации',
'snippets.panel.editAutomationTitle': 'Редактировать скрипт автоматизации',
'snippets.panel.resizeWidth': 'Изменить ширину панели',
'snippets.field.description': 'Описание действия',
'snippets.field.descriptionPlaceholder': 'Например: проверить сетевую нагрузку',
@@ -762,6 +775,9 @@ export const ruTerminalMessages: Messages = {
'snippets.targets.selectHosts': 'Хосты',
'snippets.targets.selectGroups': 'Группы',
'snippets.targets.noGroups': 'Группы не найдены',
'snippets.targets.allHosts': 'Применять ко всем хостам',
'snippets.targets.allHostsShort': 'Все хосты',
'snippets.targets.allHostsActive': 'Применяется ко всем хостам, к которым можно подключиться.',
'snippets.history.title': 'История оболочки',
'snippets.history.subtitle': '{count} команд',
'snippets.history.emptyTitle': 'История оболочки пока пуста',
@@ -844,7 +860,7 @@ export const ruTerminalMessages: Messages = {
'snippets.shortkey.error.snippetConflict': 'Это сочетание уже используется сниппетом: {name}',
// Serial Port
'serial.button': 'Серийный',
'serial.button': 'Serial',
'serial.modal.title': 'Подключение к последовательному порту',
'serial.modal.desc': 'Настройте параметры подключения к последовательному порту',
'serial.field.port': 'Последовательный порт',
@@ -862,8 +878,8 @@ export const ruTerminalMessages: Messages = {
'serial.parity.none': 'Нет',
'serial.parity.even': 'Чётная',
'serial.parity.odd': 'Нечётная',
'serial.parity.mark': 'Mark',
'serial.parity.space': 'Space',
'serial.parity.mark': 'Всегда 1 (Mark)',
'serial.parity.space': 'Всегда 0 (Space)',
'serial.flowControl.none': 'Нет',
'serial.flowControl.xon/xoff': 'XON/XOFF (программный)',
'serial.flowControl.rts/cts': 'RTS/CTS (аппаратный)',
@@ -995,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})',
};
+23 -5
View File
@@ -861,6 +861,9 @@ export const ruVaultMessages: Messages = {
'hostDetails.distro.option.zyxel': 'ZyXEL',
'hostDetails.distro.option.ruijie': 'Ruijie',
'hostDetails.section.mosh': 'Mosh',
'hostDetails.section.et': 'EternalTerminal',
'hostDetails.et.port': 'Порт сервера ET',
'hostDetails.et.port.desc': 'Порт, на котором etserver принимает подключения (по умолчанию 2022)',
'hostDetails.username.placeholder': 'Имя пользователя',
'hostDetails.password.placeholder': 'Пароль',
'hostDetails.password.show': 'Показать пароль',
@@ -939,7 +942,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.section.deviceType': 'Тип устройства',
'hostDetails.deviceType': 'Режим сетевого устройства',
'hostDetails.deviceType.desc': 'Включайте для сетевого оборудования (коммутаторов, маршрутизаторов, межсетевых экранов), подключённого по SSH. Команды отправляются как есть, без обёртки оболочки, что совместимо с CLI вендоров вроде Huawei VRP и Cisco IOS.',
'hostDetails.deviceType.warning': 'Команды AI-агента будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
'hostDetails.deviceType.warning': 'Команды агента ИИ будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
'hostDetails.section.sshAlgorithms': 'SSH-алгоритмы',
'hostDetails.section.terminalBehavior': 'Поведение терминала',
'hostDetails.lineTimestamps': 'Показывать время вывода',
@@ -1025,7 +1028,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.startupCommand': 'Команда запуска',
'hostDetails.startupCommand.placeholder': 'Команда для запуска при подключении (например, cd /app && ls)',
'hostDetails.startupCommand.help':
'This command will be executed automatically after SSH connection is established.',
'Команда выполняется автоматически после подключения по SSH.',
'hostDetails.startupCommand.runMode': 'Многострочный запуск',
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
@@ -1331,8 +1334,8 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.cert.rejected': 'TLS-сертификат отклонён пользователем.',
'remoteDesktop.step.bastion': 'Бастион',
'remoteDesktop.step.network': 'Сеть',
'remoteDesktop.step.nla': 'NLA Auth',
'remoteDesktop.step.rfb': 'RFB Auth',
'remoteDesktop.step.nla': 'Аутентификация NLA',
'remoteDesktop.step.rfb': 'Аутентификация RFB',
'remoteDesktop.step.desktop': 'Рабочий стол',
'remoteDesktop.display.resolutionPresets': 'Пресеты разрешения',
'remoteDesktop.display.customWidth': 'Ширина',
@@ -1394,6 +1397,7 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Записать сессию',
'remoteDesktop.toolbar.stopRecording': 'Остановить запись',
'remoteDesktop.toolbar.savingRecording': 'Сохранение...',
'remoteDesktop.toolbar.recording': 'Запись',
'remoteDesktop.toolbar.askAi': 'Спросить ИИ',
'remoteDesktop.toolbar.askAiFull': 'Снять экран и спросить ИИ',
@@ -1440,7 +1444,18 @@ export const ruVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Начало',
'logView.remoteDesktop.ended': 'Окончание',
'logView.remoteDesktop.duration': 'Длительность',
'logView.remoteDesktop.resolution': 'Разрешение',
'logView.remoteDesktop.security': 'Безопасность',
'logView.remoteDesktop.disconnectReason': 'Причина отключения',
'logView.remoteDesktop.timeline': 'Хронология сессии',
'logView.remoteDesktop.recordingTip': 'Нажмите «Записать сессию» на панели удалённого рабочего стола или включите автозапись в Настройки → Система, чтобы сохранять повторы .webm.',
'logs.recording.clipsCount': 'Клипов: {count}',
'logs.filter.all': 'Все',
'logs.filter.terminal': 'Терминал',
'logs.filter.remoteDesktop': 'Удалённый рабочий стол',
'logs.filter.recorded': 'С записью',
'logs.filter.emptyTitle': 'Нет подходящих журналов',
'logs.filter.emptyDesc': 'Для выбранного фильтра пока нет записей подключений.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Записи удалённого рабочего стола',
@@ -1448,7 +1463,7 @@ export const ruVaultMessages: Messages = {
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
'settings.remoteDesktopRecordings.fpsOption': '{fps} кадр/с',
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
@@ -1467,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 开发进程,然后重试。',
+61 -2
View File
@@ -8,7 +8,7 @@ export const zhCNCoreMessages: Messages = {
"settings.plugins.github.busy": "正在下载、验证或安装插件包…",
"settings.plugins.github.review": "确认仓库来源并通过完整性校验,并不代表发布者值得信任。安装过程不会运行构建脚本,插件安装后默认禁用。启用前,请确认来源可信并检查各项权限的授权方式。",
"settings.plugins.github.accept": "已审查并信任此仓库,且已查看声明的权限。",
"settings.plugins.github.confirm": "安装并保持禁用",
"settings.plugins.github.confirm": "安装",
"settings.plugins.github.download": "下载并审查",
"settings.plugins.github.error.invalidRepository": "请输入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。请只填写仓库地址,不要包含账号密码、查询参数、片段或额外路径。",
"settings.plugins.github.error.unavailable": "当前会话无法从 GitHub 安装插件。",
@@ -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 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
@@ -734,6 +736,16 @@ Vaults 标签保持扁平,不使用这块背景。
'vault.nav.notes': '笔记',
'vault.nav.knownHosts': '已知主机',
'vault.nav.logs': '日志',
'vault.nav.customize': '自定义侧边栏',
'vault.nav.customizeHint': '拖动项目以调整顺序,或切换显示状态。',
'vault.nav.hideItem': '隐藏「{label}」',
'vault.nav.moveUp': '上移',
'vault.nav.moveDown': '下移',
'vault.nav.resetDefault': '恢复默认',
'vault.nav.alwaysVisible': '始终显示',
'vault.nav.pluginBadge': '插件',
'vault.nav.dragToReorder': '拖动以调整「{label}」的顺序',
'vault.nav.toggleVisibility': '切换「{label}」的显示状态',
'proxyProfiles.action.add': '添加代理',
'proxyProfiles.search.placeholder': '搜索代理…',
@@ -785,7 +797,10 @@ Vaults 标签保持扁平,不使用这块背景。
'vault.groups.details': '分组详情',
'vault.groups.details.general': '常规',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': '当前分组尚未配置 {protocol} 默认协议设置。',
'vault.groups.details.advanced': '高级',
'vault.groups.details.appearance': '外观',
'vault.groups.details.mosh': 'Mosh',
@@ -1234,7 +1249,12 @@ Vaults 标签保持扁平,不使用这块背景。
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
"plugins.sidebar.loading": "正在加载扩展页面…",
"plugins.vault.loading": "正在加载插件页面…",
"plugins.vault.viewError": "插件页面渲染失败。",
"plugins.vault.retry": "重试",
"plugins.interaction.title": "插件请求",
"plugins.interaction.openUrlTitle": "打开外部链接?",
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
"plugins.interaction.openUrlAction": "打开链接",
"plugins.interaction.sharing": "分享的文本将交给此插件及其已授权的能力(包括网络访问)。读取文本不代表批准新的网络目标。",
"plugins.interaction.input": "输入文本",
"plugins.interaction.filter": "筛选选项",
@@ -1308,7 +1328,10 @@ Vaults 标签保持扁平,不使用这块背景。
"settings.plugins.market.title": "插件市场",
"settings.plugins.market.note": "精选开源插件。审核不代表安全认证,更新由你手动确认。",
"settings.plugins.market.back": "所有插件",
"settings.plugins.market.install": "安装此版本(保持停用)",
"settings.plugins.market.install": "安装",
"settings.plugins.market.installing": "安装中...",
"settings.plugins.market.update": "更新",
"settings.plugins.market.updating": "更新中...",
"settings.plugins.market.installNote": "这会替换并停止已安装版本。请在已安装列表检查权限后再启用。",
"settings.plugins.market.sourceOnly": "第一方源码示例。请用本地 CLI 构建并导入 .ncpkg;尚未发布可下载发行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不执行,远程图片不加载。内容由插件作者提供。",
@@ -1394,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': '目录',
@@ -15,6 +17,8 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
'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': '请等待终端回到空命令提示符。',
@@ -629,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': '切换窗口透明度',
@@ -718,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': '导出失败',
@@ -794,6 +801,7 @@ export const zhCNTerminalMessages: Messages = {
'tabs.logPrefix': '日志:',
'tabs.logLocal': '本地',
'tabs.copyTab': '复制标签页',
'tabs.addSessionToWorkspace': '在此工作区添加会话',
'tabs.duplicateSession': '复制会话',
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
@@ -1087,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})',
};
+16
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': '恢复失败',
@@ -1283,6 +1284,7 @@ export const zhCNVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '录制会话',
'remoteDesktop.toolbar.stopRecording': '停止录制',
'remoteDesktop.toolbar.savingRecording': '保存中...',
'remoteDesktop.toolbar.recording': '录制中',
'remoteDesktop.toolbar.askAi': '问 AI',
'remoteDesktop.toolbar.askAiFull': '截全屏问 AI',
@@ -1388,7 +1390,18 @@ export const zhCNVaultMessages: Messages = {
'logView.remoteDesktop.started': '开始时间',
'logView.remoteDesktop.ended': '结束时间',
'logView.remoteDesktop.duration': '持续时长',
'logView.remoteDesktop.resolution': '分辨率',
'logView.remoteDesktop.security': '安全协议',
'logView.remoteDesktop.disconnectReason': '断开原因',
'logView.remoteDesktop.timeline': '会话时间轴',
'logView.remoteDesktop.recordingTip': '点击远程桌面工具栏的录制按钮,或在「设置 → 系统」中开启自动录制,即可在此回放 .webm 录屏。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '终端',
'logs.filter.remoteDesktop': '远程桌面',
'logs.filter.recorded': '有录屏',
'logs.filter.emptyTitle': '没有匹配的日志',
'logs.filter.emptyDesc': '当前筛选条件下暂无连接日志记录。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '远程桌面录屏',
@@ -1415,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 開發行程,然後重試。',
+61 -2
View File
@@ -8,7 +8,7 @@ export const zhTWCoreMessages: Messages = {
"settings.plugins.github.busy": "正在下載、驗證或安裝套件…",
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置指令碼,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
"settings.plugins.github.accept": "已審查並信任此儲存庫,且已查看宣告的權限。",
"settings.plugins.github.confirm": "安裝並保持停用",
"settings.plugins.github.confirm": "安裝",
"settings.plugins.github.download": "下載並審查",
"settings.plugins.github.error.invalidRepository": "請輸入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。請只填寫儲存庫位址,不要包含帳號密碼、查詢參數、片段或額外路徑。",
"settings.plugins.github.error.unavailable": "目前的工作階段無法從 GitHub 安裝外掛。",
@@ -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 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
@@ -734,6 +736,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
'vault.nav.notes': '筆記',
'vault.nav.knownHosts': '已知主機',
'vault.nav.logs': '日誌',
'vault.nav.customize': '自訂側邊欄',
'vault.nav.customizeHint': '拖曳項目以調整順序,或切換顯示狀態。',
'vault.nav.hideItem': '隱藏「{label}」',
'vault.nav.moveUp': '上移',
'vault.nav.moveDown': '下移',
'vault.nav.resetDefault': '恢復預設',
'vault.nav.alwaysVisible': '始終顯示',
'vault.nav.pluginBadge': '外掛',
'vault.nav.dragToReorder': '拖曳以調整「{label}」的順序',
'vault.nav.toggleVisibility': '切換「{label}」的顯示狀態',
'proxyProfiles.action.add': '新增代理',
'proxyProfiles.search.placeholder': '搜尋代理…',
@@ -785,7 +797,10 @@ Vaults 分頁維持扁平,不使用這塊背景。
'vault.groups.details': '群組詳情',
'vault.groups.details.general': '常規',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': '目前群組尚未設定 {protocol} 預設協定設定。',
'vault.groups.details.advanced': '高階',
'vault.groups.details.appearance': '外觀',
'vault.groups.details.mosh': 'Mosh',
@@ -1235,7 +1250,12 @@ Vaults 分頁維持扁平,不使用這塊背景。
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
"plugins.vault.loading": "正在載入擴充功能頁面…",
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
"plugins.vault.retry": "重試",
"plugins.interaction.title": "外掛請求",
"plugins.interaction.openUrlTitle": "開啟外部連結?",
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
"plugins.interaction.openUrlAction": "開啟連結",
"plugins.interaction.sharing": "分享的文字會交給此外掛及其已授權能力(包括網路存取)。讀取文字不代表核准新的網路目的地。",
"plugins.interaction.input": "輸入文字",
"plugins.interaction.filter": "篩選選項",
@@ -1338,7 +1358,10 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.market.title": "外掛市集",
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有外掛",
"settings.plugins.market.install": "安裝此版本(保持停用)",
"settings.plugins.market.install": "安裝",
"settings.plugins.market.installing": "安裝中...",
"settings.plugins.market.update": "更新",
"settings.plugins.market.updating": "更新中...",
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
@@ -1395,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': '目錄',
@@ -15,6 +17,8 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
'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': '請等待終端回到空白命令提示字元。',
@@ -629,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': '切換視窗透明度',
@@ -718,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': '匯出失敗',
@@ -794,6 +801,7 @@ export const zhTWTerminalMessages: Messages = {
'tabs.logPrefix': '日誌:',
'tabs.logLocal': '本機',
'tabs.copyTab': '複製分頁',
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
'tabs.duplicateSession': '複製工作階段',
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
@@ -1087,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})',
};
+16
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': '恢復失敗',
@@ -1218,6 +1219,7 @@ export const zhTWVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '錄製工作階段',
'remoteDesktop.toolbar.stopRecording': '停止錄製',
'remoteDesktop.toolbar.savingRecording': '儲存中...',
'remoteDesktop.toolbar.recording': '錄製中',
'remoteDesktop.toolbar.askAi': '詢問 AI',
'remoteDesktop.toolbar.askAiFull': '擷取全螢幕詢問 AI',
@@ -1388,7 +1390,18 @@ export const zhTWVaultMessages: Messages = {
'logView.remoteDesktop.started': '開始時間',
'logView.remoteDesktop.ended': '結束時間',
'logView.remoteDesktop.duration': '持續時間',
'logView.remoteDesktop.resolution': '解析度',
'logView.remoteDesktop.security': '安全協定',
'logView.remoteDesktop.disconnectReason': '斷線原因',
'logView.remoteDesktop.timeline': '工作階段時間軸',
'logView.remoteDesktop.recordingTip': '點擊遠端桌面工具列的錄製按鈕,或在「設定 → 系統」中開啟自動錄製,即可在此重播 .webm 錄影。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '終端機',
'logs.filter.remoteDesktop': '遠端桌面',
'logs.filter.recorded': '含錄影',
'logs.filter.emptyTitle': '沒有符合的日誌',
'logs.filter.emptyDesc': '目前篩選條件下尚無連線日誌記錄。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '遠端桌面錄影',
@@ -1415,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;
};
}
+5 -1
View File
@@ -70,7 +70,11 @@ export function pruneInactiveScopedSessions(
orphanedSessionIds: string[];
} {
const orphanedSessionIds = sessions
.filter((session) => session.scope.targetId && !activeTargetIds.has(session.scope.targetId))
.filter((session) => (
(session.scope.type === "terminal" || session.scope.type === "workspace")
&& session.scope.targetId
&& !activeTargetIds.has(session.scope.targetId)
))
.filter((session) => !activeSessionIds.has(session.id))
.map((session) => session.id);
+3
View File
@@ -116,6 +116,9 @@ function isScopeKeyActive(scopeKey: string, activeTargetIds: Set<string>) {
const separatorIndex = scopeKey.indexOf(':');
if (separatorIndex === -1) return true;
const scopeType = scopeKey.slice(0, separatorIndex);
if (scopeType === 'global') return true;
const targetId = scopeKey.slice(separatorIndex + 1);
if (!targetId) return true;
+1 -1
View File
@@ -9,7 +9,7 @@ export type ConnectionLogsSnapshot = {
};
export type ConnectionLogsActions = {
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void;
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void | Promise<unknown>;
toggleConnectionLogSaved: (id: string) => void;
deleteConnectionLog: (id: string) => void;
clearUnsavedConnectionLogs: () => void;
@@ -9,7 +9,7 @@ test('selected metadata projects only the allowlist and replacement invalidates
const resources = new PluginHostActionResources();
resources.observe([first]);
const metadata = resources.metadata(first.id);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags']);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags', 'os']);
assert.equal(JSON.stringify(metadata).includes('synthetic-password'), false);
resources.observe([first]);
assert.equal(resources.resolve(first.id, metadata.revision), first);
@@ -24,11 +24,22 @@ export class PluginHostActionResources {
const entry = this.entries.get(id);
if (!entry) throw new Error('Selected host is unavailable');
const host = entry.host;
const osValue = typeof host.os === 'string'
? Array.from(host.os).filter((ch) => {
const code = ch.charCodeAt(0);
return code >= 0x20 && code !== 0x7f;
}).join('').slice(0, 128)
: '';
const notesValue = typeof host.notes === 'string'
? host.notes.split('\0').join('').slice(0, 4096)
: '';
return {
resourceId: host.id, revision: entry.revision,
label: host.label, hostname: host.hostname, username: host.username,
...(host.port === undefined ? {} : { port: host.port }), protocol: host.protocol ?? 'ssh',
group: host.group ?? '', tags: [...host.tags],
...(osValue ? { os: osValue } : {}),
...(notesValue ? { notes: notesValue } : {}),
};
}
}
+406
View File
@@ -65,3 +65,409 @@ test('inserting a child into an existing void element fails the view', async ()
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
});
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
// Inserting an existing id at a later sibling index replaces the existing node in place.
const replaced = tree.apply([
[3, 'a', 'class', 'stale'],
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(replaced, {
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
});
// Follow-up mutations must apply against the replaced live node (desync gate).
const afterFollowUp = tree.apply([
[3, 'a', 'class', 'after-sort'],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
]);
assert.deepEqual(afterFollowUp, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
],
});
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
const movedForward = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
]);
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
const movedBack = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
]);
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
assert.deepEqual(postMoveAttr, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
],
});
});
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', {
id: 'old-parent',
type: 1,
element: 'div',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'unsorted' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 0],
]);
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
const reparented = tree.apply([
[0, '~', {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(reparented, {
children: [
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
{
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
},
],
});
// A subsequent sort-like incremental update on the moved child applies cleanly.
const secondSort = tree.apply([
[3, 'cell-1', 'class', 'sorted-desc'],
[2, 'cell-text', 'omega'],
]);
assert.deepEqual(secondSort.children[1], {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-desc' },
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
}],
});
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
const sameBatch = tree.apply([
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
[0, '~', {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
}, 2],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
assert.deepEqual(sameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
});
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
assert.deepEqual(afterSameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
});
});
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
assert.throws(
() => tree.apply([
[3, 'a', 'class', 'rejected'],
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
]),
/Duplicate view node/,
);
assert.equal(tree.isFailed(), false);
assert.deepEqual(tree.snapshot(), {
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
});
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
assert.deepEqual(updated, {
children: [
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
{ id: 'b', type: 3, data: 'second' },
],
});
});
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
// projected tree actually contains both the policy violation and a later duplicate id.
assert.throws(
() => tree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
]),
/Void view elements/,
);
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
// Even when the duplicate node appears earlier in root order than the void-element violation,
// unique-id revalidation must still hard-fail instead of rewriting the batch.
const duplicateFirstTree = createPluginRemoteTree();
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
assert.throws(
() => duplicateFirstTree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
]),
/Void view elements/,
);
assert.equal(duplicateFirstTree.isFailed(), true);
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
// must still surface the void-element violation instead of treating it as recoverable.
const mixed = {
children: [
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
],
};
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
});
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const staged = createPluginRemoteTree();
const batches: unknown[][][] = [];
const observer = new RemoteMutationObserver({
mutate(records) {
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
batches.push(cloned);
staged.apply(cloned);
},
call() { throw new Error('Host method calls are unavailable'); },
});
const container = document.getElementById('remote')!;
observer.observe(container);
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
try {
const a = document.createElement('div');
a.id = 'a';
const aText = document.createTextNode('Alpha');
a.appendChild(aText);
const b = document.createElement('div');
b.id = 'b';
b.appendChild(document.createTextNode('Beta'));
container.appendChild(a);
container.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
assert.equal(staged.snapshot().children.length, 2);
// Same-tick wrap: append wrapper and move b into it.
const wrapper = document.createElement('section');
wrapper.id = 'wrapper';
container.appendChild(wrapper);
wrapper.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
const afterWrap = staged.snapshot();
assert.deepEqual(
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const [aNode, wrapperNode] = afterWrap.children;
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
assert.deepEqual(
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['b'],
);
const bNode = wrapperNode.children[0];
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
// Desync gate: a subsequent text update to a must apply cleanly.
aText.data = 'Alpha updated';
await flush();
assert.equal(staged.isFailed(), false);
const afterText = staged.snapshot();
assert.deepEqual(
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const updatedANode = afterText.children[0];
assert.ok(updatedANode && updatedANode.type === 1);
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
wrapper.remove();
await flush();
assert.equal(staged.isFailed(), false);
const afterRemove = staged.snapshot();
assert.deepEqual(
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a'],
);
aText.data = 'Alpha after remove';
await flush();
assert.equal(staged.isFailed(), false);
const afterRemoveText = staged.snapshot();
const survivingANode = afterRemoveText.children[0];
assert.ok(survivingANode && survivingANode.type === 1);
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
assert.ok(batches.length >= 5);
} finally {
observer.disconnect();
for (const [key, value] of saved) {
if (value) Object.defineProperty(globalThis, key, value);
else Reflect.deleteProperty(globalThis, key);
}
dom.window.close();
}
});
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
]);
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
const wrapped = tree.apply([
[0, '~', {
id: '4',
type: 1,
element: 'section',
attributes: { id: 'wrapper' },
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
}, 0],
[1, '~', 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
const wrapperNode = wrapped.children[1];
assert.equal(wrapperNode.type, 1);
if (wrapperNode.type === 1) {
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
}
// Subsequent text update to a must still apply.
const updated = tree.apply([[2, '1', 'Alpha updated']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(updated.children[0], {
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
});
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
const afterRemove = tree.apply([[1, '~', 1]]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemoveUpdate, {
children: [{
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
}],
});
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
const remapTree = createPluginRemoteTree();
remapTree.apply([
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
]);
const remapped = remapTree.apply([
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
[1, '~', 2],
// Producer then removes a at original index 0 (already detached -> skipped).
[1, '~', 0],
]);
assert.equal(remapTree.isFailed(), false);
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
assert.deepEqual(followUp.children[0], {
id: 'b',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
});
});
+211 -5
View File
@@ -6,16 +6,201 @@ type WireNode = { id: string; type: 3 | 8; data: string } | {
};
type WireTree = { children: WireNode[] };
const validatedTrees = new WeakSet<object>();
export function isValidatedPluginRemoteTree(tree: unknown): boolean {
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
}
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
return error instanceof TypeError && error.message === 'Duplicate view node';
}
function withUniqueViewIds(tree: WireTree): WireTree {
let n = 0;
const rewrite = (node: WireNode): WireNode => {
const id = `n${n++}`;
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
};
return { children: tree.children.map(rewrite) };
}
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
validatePluginRemoteTree(withUniqueViewIds(tree));
}
type WorkingNode = {
id: string;
parentId: string | null;
children: WorkingNode[];
};
type RewriteDetach = {
parentId: string;
index: number;
id: string;
};
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
out.push(node.id);
if (node.type === 1) {
for (const child of node.children) collectSubtreeIds(child, out);
}
return out;
}
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
const working: WorkingNode = { id: node.id, parentId, children: [] };
nodes.set(node.id, working);
if (node.type === 1) {
for (const child of node.children) {
working.children.push(buildWorkingNode(child, node.id, nodes));
}
}
return working;
}
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
nodes.delete(node.id);
node.parentId = null;
for (const child of node.children) detachWorkingSubtree(child, nodes);
}
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
let cursor: string | null = startId;
while (cursor !== null) {
if (ids.has(cursor)) return true;
cursor = nodes.get(cursor)?.parentId ?? null;
}
return false;
}
/**
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
* attached in the tree first emit explicit removals from their previous parents.
* Returns null if an insert would detach its own destination parent (cycle).
*/
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
const root: WorkingNode = { id: '~', parentId: null, children: [] };
const nodes = new Map<string, WorkingNode>([['~', root]]);
for (const child of current.children) {
root.children.push(buildWorkingNode(child, '~', nodes));
}
const rewritten: unknown[][] = [];
const rewriteDetaches: RewriteDetach[] = [];
for (const record of batch) {
const type = record[0];
if (type === 0) {
const parentId = record[1] as string;
const node = record[2] as WireNode;
let insertIndex = record[3] as number;
const parent = nodes.get(parentId);
if (!parent) {
// Detached parent: RemoteReceiver drops this insert as a no-op.
rewritten.push(record);
continue;
}
const subtreeIds = collectSubtreeIds(node);
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
return null;
}
for (const existingId of subtreeIds) {
const existing = nodes.get(existingId);
if (!existing || existing.parentId === null) continue;
const oldParent = nodes.get(existing.parentId);
if (!oldParent) continue;
const oldIndex = oldParent.children.indexOf(existing);
if (oldIndex < 0) continue;
rewritten.push([1, oldParent.id, oldIndex]);
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
oldParent.children.splice(oldIndex, 1);
detachWorkingSubtree(existing, nodes);
if (oldParent.id === parentId) {
if (oldIndex < insertIndex) {
insertIndex -= 1;
} else if (existing.id !== node.id && oldIndex > insertIndex) {
insertIndex = oldIndex;
}
}
}
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
const inserted = buildWorkingNode(node, parentId, nodes);
if (insertIndex >= parent.children.length) {
parent.children.push(inserted);
} else {
parent.children.splice(insertIndex, 0, inserted);
}
} else if (type === 1) {
const parentId = record[1] as string;
const removeIndex = record[2] as number;
const exactMatchIndex = rewriteDetaches.findIndex(
(detach) => detach.parentId === parentId && detach.index === removeIndex,
);
if (exactMatchIndex !== -1) {
rewriteDetaches.splice(exactMatchIndex, 1);
continue;
}
let smallerCount = 0;
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index < removeIndex) {
smallerCount += 1;
}
}
const remappedIndex = removeIndex - smallerCount;
const parent = nodes.get(parentId);
if (!parent) {
if (smallerCount === 0) rewritten.push(record);
continue;
}
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
continue;
}
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
const [removed] = parent.children.splice(remappedIndex, 1);
if (removed) detachWorkingSubtree(removed, nodes);
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index > removeIndex) {
detach.index -= 1;
}
}
} else {
rewritten.push(record);
}
}
return rewritten;
}
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
export function createPluginRemoteTree() {
const receiver = new RemoteReceiver();
let current: WireTree = { children: [] };
validatedTrees.add(current);
let failed = false;
const project = (node: unknown): WireNode => {
const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record<string, string>; children?: unknown[] };
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
};
const applyToScratch = (records: unknown[][]): WireTree => {
const scratch = new RemoteReceiver();
if (current.children.length > 0) {
scratch.connection.mutate(
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
);
}
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
return { children: scratch.root.children.map(project) };
};
return {
apply(input: unknown): WireTree {
if (failed) throw new Error('Plugin view has been closed after an invalid update');
@@ -24,14 +209,35 @@ export function createPluginRemoteTree() {
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
// defaults those to properties, so explicitly mark them as attributes.
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
const next = { children: receiver.root.children.map(project) };
validatePluginRemoteTree(next);
let appliedBatch = batch;
let next = applyToScratch(batch);
try {
validatePluginRemoteTree(next);
} catch (error) {
if (!isDuplicatePluginViewNodeError(error)) throw error;
assertDuplicateOnlyPluginRemoteTree(next);
const rewritten = rewriteDuplicateInsertBatch(current, batch);
if (!rewritten) throw error;
const rewrittenNext = applyToScratch(rewritten);
try {
validatePluginRemoteTree(rewrittenNext);
} catch (rewrittenError) {
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
throw rewrittenError;
}
appliedBatch = rewritten;
next = rewrittenNext;
}
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
validatedTrees.add(next);
current = next;
return next;
} catch (error) {
failed = true;
current = { children: [] };
if (!isDuplicatePluginViewNodeError(error)) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
}
throw error;
}
},
@@ -0,0 +1,269 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import type { Host, PortForwardingRule } from '../../domain/models';
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import type { PortForwardingConnection } from '../../infrastructure/services/portForwardingService';
import {
handlePluginVaultDataRequest,
type PluginPortForwardRuntimeDeps,
type PluginVaultDataContext,
} from './pluginVaultDataHandlers';
function installMemoryLocalStorage() {
const store = new Map<string, string>();
const previous = (globalThis as Record<string, unknown>).localStorage;
const mockStorage = {
get length() { return store.size; },
clear() { store.clear(); },
getItem(key: string) { return store.has(key) ? store.get(key)! : null; },
key(index: number) { return Array.from(store.keys())[index] ?? null; },
removeItem(key: string) { store.delete(key); },
setItem(key: string, value: string) { store.set(key, String(value)); },
};
Object.defineProperty(globalThis, 'localStorage', {
value: mockStorage,
configurable: true,
writable: true,
});
return () => {
Object.defineProperty(globalThis, 'localStorage', {
value: previous,
configurable: true,
writable: true,
});
};
}
const sampleHost: Host = {
id: 'host-1',
label: 'Prod Bastion',
hostname: '10.0.0.10',
port: 22,
username: 'ubuntu',
os: 'linux',
group: '',
tags: [],
protocol: 'ssh',
};
const sampleRules: PortForwardingRule[] = [
{
id: 'rule-active',
label: 'DB Tunnel',
type: 'local',
localPort: 15432,
bindAddress: '127.0.0.1',
remoteHost: '127.0.0.1',
remotePort: 5432,
hostId: 'host-1',
status: 'inactive',
createdAt: 1000,
},
{
id: 'rule-err',
label: 'Redis Tunnel',
type: 'local',
localPort: 16379,
bindAddress: '127.0.0.1',
remoteHost: '127.0.0.1',
remotePort: 6379,
hostId: 'host-1',
status: 'inactive',
createdAt: 2000,
},
];
function makeContext(portForwardRuntime: PluginPortForwardRuntimeDeps): PluginVaultDataContext {
return {
getVault: () => ({
hosts: [sampleHost],
keys: [],
identities: [],
knownHosts: [],
groupConfigs: [],
proxyProfiles: [],
snippets: [],
customGroups: [],
updateHosts: () => {},
updateSnippets: () => {},
readCurrentHostActionState: () => ({
hosts: [sampleHost],
keys: [],
identities: [],
knownHosts: [],
groupConfigs: [],
proxyProfiles: [],
snippets: [],
customGroups: [],
}),
}) as never,
resources: {} as never,
portForwardRuntime,
};
}
test('portForward.list overlays live runtime status and error over persisted inactive rules', async () => {
const restore = installMemoryLocalStorage();
try {
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, sampleRules);
const activeConns = new Map<string, PortForwardingConnection>([
['rule-active', { ruleId: 'rule-active', tunnelId: 't-1', status: 'active' }],
]);
const runtimeRules: PortForwardingRule[] = [
{ ...sampleRules[0], status: 'active' },
{ ...sampleRules[1], status: 'error', error: 'EADDRINUSE: port 16379 busy' },
];
const ctx = makeContext({
getActiveConnection: (id) => activeConns.get(id),
getRuntimeRules: () => runtimeRules,
});
const result = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
rules: Array<{ id: string; status: string; error?: string }>;
};
const byId = new Map(result.rules.map((r) => [r.id, r]));
assert.equal(byId.get('rule-active')?.status, 'active');
assert.equal(byId.get('rule-active')?.error, undefined);
assert.equal(byId.get('rule-err')?.status, 'error');
assert.equal(byId.get('rule-err')?.error, 'EADDRINUSE: port 16379 busy');
} finally {
restore();
}
});
test('portForward.start and portForward.stop return live runtime status instead of stripped storage inactive', async () => {
const restore = installMemoryLocalStorage();
try {
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[0]]);
const activeConns = new Map<string, PortForwardingConnection>();
const appliedStatuses: Array<{ ruleId: string; status: string; error?: string }> = [];
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[0], status: 'inactive' }];
const ctx = makeContext({
getActiveConnection: (id) => activeConns.get(id),
getRuntimeRules: () => runtimeRules,
applyRuntimeStatus: (ruleId, status, error) => {
appliedStatuses.push({ ruleId, status, error });
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
},
startPortForward: async (rule, _host, _hosts, _keys, _ids, onStatusChange) => {
onStatusChange?.('connecting');
activeConns.set(rule.id, { ruleId: rule.id, tunnelId: 't-live', status: 'active' });
onStatusChange?.('active');
return { success: true };
},
stopAndCleanupRule: async (ruleId) => {
activeConns.delete(ruleId);
return { success: true };
},
});
const started = await handlePluginVaultDataRequest(
'portForward.start',
{ ruleId: 'rule-active' },
ctx,
) as { ok: boolean; rule: { id: string; status: string; error?: string } };
assert.equal(started.ok, true);
assert.equal(started.rule.status, 'active');
assert.equal(started.rule.error, undefined);
assert.ok(appliedStatuses.some((entry) => entry.ruleId === 'rule-active' && entry.status === 'active'));
// Subsequent list also reports active
const listed = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
rules: Array<{ id: string; status: string }>;
};
assert.equal(listed.rules[0]?.status, 'active');
// Stop transitions cleanly back to inactive
const stopped = await handlePluginVaultDataRequest(
'portForward.stop',
{ ruleId: 'rule-active' },
ctx,
) as { ok: boolean; rule: { id: string; status: string } };
assert.equal(stopped.ok, true);
assert.equal(stopped.rule.status, 'inactive');
} finally {
restore();
}
});
test('portForward.start surfaces live error status and message when tunnel start fails', async () => {
const restore = installMemoryLocalStorage();
try {
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[1]]);
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[1], status: 'inactive' }];
const ctx = makeContext({
getActiveConnection: () => undefined,
getRuntimeRules: () => runtimeRules,
applyRuntimeStatus: (ruleId, status, error) => {
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
},
startPortForward: async (_rule, _host, _hosts, _keys, _ids, onStatusChange) => {
onStatusChange?.('error', 'Connection refused');
return { success: false, error: 'Connection refused' };
},
});
const started = await handlePluginVaultDataRequest(
'portForward.start',
{ ruleId: 'rule-err' },
ctx,
) as { ok: boolean; rule: { id: string; status: string; error?: string }; error?: string };
assert.equal(started.ok, false);
assert.equal(started.rule.status, 'error');
assert.equal(started.rule.error, 'Connection refused');
assert.equal(started.error, 'Connection refused');
} finally {
restore();
}
});
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
const queries: unknown[] = [];
const ctx: PluginVaultDataContext = {
...makeContext({}),
viewOpenRuntime: {
getPluginContributions: async (query) => {
queries.push(query);
return {
locale: 'en',
plugins: [{
id: 'com.example.db',
version: '1.0.0',
displayName: 'Database',
commands: [],
keybindings: [],
menus: [],
settings: [],
views: [
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
],
}],
};
},
requestOpenPluginView: (detail) => { opened.push(detail); },
},
};
const result = await handlePluginVaultDataRequest(
'views.open',
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
ctx,
);
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
await assert.rejects(
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
/not available/,
);
await assert.rejects(
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
/not available/,
);
assert.equal(opened.length, 1);
});
@@ -0,0 +1,521 @@
import type { Host, PortForwardingRule, Snippet } from '../../domain/models';
import { applyGroupDefaults, resolveGroupDefaults } from '../../domain/groupConfig';
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
import {
migratePortForwardingRulesFromStorage,
toPersistedPortForwardingRules,
} from '../../domain/portForwardingPersistence';
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { preparePluginHostStream } from '../../infrastructure/services/pluginHostStreamService';
import {
getActiveConnection,
startPortForward,
stopAndCleanupRule,
} from '../../infrastructure/services/portForwardingService';
import { captureScreenSnapshot } from '../../infrastructure/scripts/screenSnapshotRegistry';
import { activeTabStore } from './activeTabStore';
import {
getAppSessionRuntime,
getAppSettingsRuntime,
type AppVaultRuntime,
} from './appRuntimeBridge';
import type { PluginHostActionResources } from './pluginHostActionResources';
import {
applyPortForwardingRuntimeStatus,
getPortForwardingRuntimeRules,
} from './usePortForwardingState';
import { requestOpenPluginView } from './usePluginViewLifecycle';
export interface PluginPortForwardRuntimeDeps {
startPortForward?: typeof startPortForward;
stopAndCleanupRule?: typeof stopAndCleanupRule;
getActiveConnection?: typeof getActiveConnection;
getRuntimeRules?: typeof getPortForwardingRuntimeRules;
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
}
export interface PluginViewOpenRuntimeDeps {
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
requestOpenPluginView?: typeof requestOpenPluginView;
}
export type PluginVaultDataContext = {
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
resources: PluginHostActionResources;
portForwardRuntime?: PluginPortForwardRuntimeDeps;
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
};
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
function normalizePortForwardSummaryStatus(
status: PortForwardingRule['status'] | undefined,
): PortForwardSummaryStatus {
if (status === 'active' || status === 'connecting' || status === 'error' || status === 'inactive') {
return status;
}
return 'inactive';
}
function overlayPortForwardRuntimeStatus(
rule: PortForwardingRule,
runtime?: PluginPortForwardRuntimeDeps,
): PortForwardingRule {
const resolveConnection = runtime?.getActiveConnection ?? getActiveConnection;
const liveConn = resolveConnection(rule.id);
if (liveConn) {
return {
...rule,
status: normalizePortForwardSummaryStatus(liveConn.status),
error: liveConn.error,
};
}
const runtimeRules = (runtime?.getRuntimeRules ?? getPortForwardingRuntimeRules)();
const runtimeRule = runtimeRules.find((candidate) => candidate.id === rule.id);
if (runtimeRule && (runtimeRule.status === 'active' || runtimeRule.status === 'connecting' || runtimeRule.status === 'error')) {
return {
...rule,
status: runtimeRule.status,
error: runtimeRule.error,
};
}
return {
...rule,
status: normalizePortForwardSummaryStatus(rule.status),
};
}
function readPortForwardRules(): PortForwardingRule[] {
const raw = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
return migratePortForwardingRulesFromStorage(Array.isArray(raw) ? raw : []);
}
function writePortForwardRules(rules: PortForwardingRule[]): void {
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, toPersistedPortForwardingRules(rules));
}
function summarizePortForwardRule(rule: PortForwardingRule, hosts: readonly Host[]) {
const host = rule.hostId ? hosts.find((candidate) => candidate.id === rule.hostId) : undefined;
return {
id: rule.id,
label: rule.label,
type: rule.type,
localPort: rule.localPort,
bindAddress: rule.bindAddress || '127.0.0.1',
...(rule.remoteHost ? { remoteHost: rule.remoteHost } : {}),
...(typeof rule.remotePort === 'number' && rule.remotePort >= 1 ? { remotePort: rule.remotePort } : {}),
...(host?.label ? { hostLabel: host.label } : {}),
...(host?.hostname ? { hostname: host.hostname } : {}),
status: rule.status ?? 'inactive',
...(rule.error ? { error: rule.error.slice(0, 512) } : {}),
};
}
function summarizeSnippet(snippet: Snippet) {
return {
id: snippet.id,
label: snippet.label,
command: snippet.command,
...(snippet.package ? { package: snippet.package } : {}),
...(Array.isArray(snippet.tags) && snippet.tags.length > 0 ? { tags: [...snippet.tags] } : {}),
...(snippet.shortcut ? { shortcut: snippet.shortcut } : {}),
};
}
function effectiveHost(
host: Host,
vault: Pick<AppVaultRuntime, 'groupConfigs' | 'proxyProfiles'>,
): Host {
const validProxyProfileIds = new Set(vault.proxyProfiles.map((p) => p.id));
const defaults = host.group
? resolveGroupDefaults(host.group, vault.groupConfigs, { validProxyProfileIds })
: {};
return materializeHostProxyProfile(
applyGroupDefaults(host, defaults, { validProxyProfileIds }),
vault.proxyProfiles,
);
}
export async function handlePluginVaultDataRequest(
kind: string,
payload: Record<string, unknown>,
ctx: PluginVaultDataContext,
): Promise<unknown> {
const vault = ctx.getVault();
switch (kind) {
case 'resolveMetadata': {
const hostIds = Array.isArray(payload.hostIds) ? payload.hostIds : [];
const hosts: Record<string, Record<string, unknown>> = {};
for (const hostId of hostIds) {
if (typeof hostId !== 'string') continue;
const found = vault.hosts.find((candidate) => candidate.id === hostId);
if (!found) continue;
const { resourceId: _resourceId, revision: _revision, ...meta } = ctx.resources.metadata(found.id);
hosts[hostId] = meta;
}
return { hosts };
}
case 'prepareConnection': {
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
const host = vault.hosts.find((candidate) => candidate.id === hostId);
if (!host) throw new Error('Saved SSH host no longer exists');
const settings = getAppSettingsRuntime();
if (!settings) throw new Error('Terminal settings unavailable');
const connectionOptions = await preparePluginHostStream(host, vault, settings.terminalSettings);
return { connectionOptions };
}
case 'prepareProbeTarget': {
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
const rawHost = vault.hosts.find((candidate) => candidate.id === hostId);
if (!rawHost) throw new Error('Saved host no longer exists');
const host = effectiveHost(rawHost, vault);
const defaultProtocol = resolveEffectiveTerminalProtocol(host);
const rdpPort = host.rdpConfig?.port ?? (defaultProtocol === 'rdp' ? (host.port || 3389) : undefined);
const vncPort = host.vncConfig?.port ?? (defaultProtocol === 'vnc' ? (host.port || 5900) : undefined);
const isRemoteDesktopOnly = defaultProtocol === 'rdp' || defaultProtocol === 'vnc';
return {
hostname: host.hostname,
...(!isRemoteDesktopOnly ? { sshPort: host.port || 22 } : {}),
...(rdpPort ? { rdpPort } : {}),
...(vncPort ? { vncPort } : {}),
defaultProtocol,
...(host.rdpConfig?.securityMode ? { rdpSecurityMode: host.rdpConfig.securityMode } : {}),
};
}
case 'listGroups': {
const counts = new Map<string, number>();
for (const groupPath of vault.customGroups) {
if (groupPath) counts.set(groupPath, counts.get(groupPath) ?? 0);
}
for (const host of vault.hosts) {
if (host.group) counts.set(host.group, (counts.get(host.group) ?? 0) + 1);
}
const groups = [...counts.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.slice(0, 1000)
.map(([path, hostCount]) => ({ path, hostCount }));
return { groups };
}
case 'updateHostNotes': {
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
const notes = typeof payload.notes === 'string' ? payload.notes.slice(0, 4096) : '';
const host = vault.hosts.find((candidate) => candidate.id === hostId);
if (!host) throw new Error('Saved host no longer exists');
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, notes } : item)));
return { updated: true };
}
case 'updateHostTags': {
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
const tags = Array.isArray(payload.tags)
? payload.tags.filter((t): t is string => typeof t === 'string' && t.length > 0).slice(0, 128)
: [];
const host = vault.hosts.find((candidate) => candidate.id === hostId);
if (!host) throw new Error('Saved host no longer exists');
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, tags } : item)));
return { updated: true };
}
case 'portForward.list': {
const rules = readPortForwardRules()
.slice(0, 500)
.map((rule) => overlayPortForwardRuntimeStatus(rule, ctx.portForwardRuntime));
return { rules: rules.map((rule) => summarizePortForwardRule(rule, vault.hosts)) };
}
case 'portForward.create': {
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
const host = vault.hosts.find((candidate) => candidate.id === hostId);
if (!host) throw new Error('Bound host no longer exists');
const rule: PortForwardingRule = {
id: crypto.randomUUID(),
label: String(payload.label ?? '').slice(0, 256),
type: (payload.type === 'remote' || payload.type === 'dynamic' ? payload.type : 'local'),
localPort: Number(payload.localPort),
bindAddress: typeof payload.bindAddress === 'string' && payload.bindAddress ? payload.bindAddress : '127.0.0.1',
...(typeof payload.remoteHost === 'string' ? { remoteHost: payload.remoteHost } : {}),
...(typeof payload.remotePort === 'number' ? { remotePort: payload.remotePort } : {}),
hostId: host.id,
status: 'inactive',
createdAt: Date.now(),
};
const existing = readPortForwardRules();
writePortForwardRules([...existing, rule]);
return { ok: true, rule: summarizePortForwardRule(rule, vault.hosts) };
}
case 'portForward.start': {
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
const rules = readPortForwardRules();
const rule = rules.find((item) => item.id === ruleId);
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
const rawHost = rule.hostId ? vault.hosts.find((h) => h.id === rule.hostId) : undefined;
if (!rawHost) return { ok: false, error: 'Target host for port forwarding rule not found' };
const settings = getAppSettingsRuntime();
const resolvedHost = effectiveHost(rawHost, vault);
const resolvedHosts = vault.hosts.map((h) => effectiveHost(h, vault));
const pfStart = ctx.portForwardRuntime?.startPortForward ?? startPortForward;
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
const pfGetConnection = ctx.portForwardRuntime?.getActiveConnection ?? getActiveConnection;
let observedStatus: PortForwardingRule['status'] | undefined;
let observedError: string | undefined;
const res = await pfStart(
rule,
resolvedHost,
resolvedHosts,
vault.keys,
vault.identities,
(status, error) => {
observedStatus = status;
observedError = error;
pfApplyStatus(ruleId, status, error);
},
false,
settings?.terminalSettings,
vault.knownHosts,
);
const liveConn = pfGetConnection(ruleId);
const fallbackStatus: PortForwardSummaryStatus = res.success ? 'active' : 'error';
const finalStatus = normalizePortForwardSummaryStatus(liveConn?.status ?? observedStatus ?? fallbackStatus);
const finalError = finalStatus === 'active'
? undefined
: (liveConn?.error ?? observedError ?? (res.error ? String(res.error) : undefined));
pfApplyStatus(ruleId, finalStatus, finalError);
const latestRule = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
const liveRule: PortForwardingRule = {
...latestRule,
status: finalStatus,
error: finalError,
};
return {
ok: Boolean(res.success),
rule: summarizePortForwardRule(liveRule, vault.hosts),
...(res.error ? { error: String(res.error).slice(0, 512) } : {}),
};
}
case 'portForward.stop': {
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
const rules = readPortForwardRules();
const rule = rules.find((item) => item.id === ruleId);
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
await pfStop(ruleId);
pfApplyStatus(ruleId, 'inactive', undefined);
const latestRules = readPortForwardRules();
const updated = overlayPortForwardRuntimeStatus(
latestRules.find((item) => item.id === ruleId) ?? { ...rule, status: 'inactive', error: undefined },
ctx.portForwardRuntime,
);
return { ok: true, rule: summarizePortForwardRule(updated, vault.hosts) };
}
case 'portForward.delete': {
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
const rules = readPortForwardRules();
if (!rules.some((item) => item.id === ruleId)) {
return { ok: false, error: 'Port forwarding rule not found' };
}
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
await pfStop(ruleId).catch(() => {});
const latestRules = readPortForwardRules();
writePortForwardRules(latestRules.filter((item) => item.id !== ruleId));
return { ok: true };
}
case 'snippets.list': {
const query = typeof payload.query === 'string' ? payload.query.trim().toLowerCase() : '';
const tag = typeof payload.tag === 'string' ? payload.tag : '';
const pkg = typeof payload.package === 'string' ? payload.package : '';
const filtered = vault.snippets.filter((snippet) => {
if (pkg && snippet.package !== pkg) return false;
if (tag && !(snippet.tags ?? []).includes(tag)) return false;
if (query) {
const hay = `${snippet.label} ${snippet.command} ${(snippet.tags ?? []).join(' ')}`.toLowerCase();
if (!hay.includes(query)) return false;
}
return true;
});
return { snippets: filtered.slice(0, 1000).map(summarizeSnippet) };
}
case 'snippets.get': {
const id = typeof payload.id === 'string' ? payload.id : '';
const found = vault.snippets.find((item) => item.id === id);
return found ? { found: true, snippet: summarizeSnippet(found) } : { found: false };
}
case 'snippets.save': {
const id = typeof payload.id === 'string' && payload.id ? payload.id : crypto.randomUUID();
const existing = vault.snippets.find((item) => item.id === id);
const nextSnippet: Snippet = {
...(existing ?? {}),
id,
label: String(payload.label ?? '').slice(0, 256),
command: String(payload.command ?? '').slice(0, 65536),
...(typeof payload.package === 'string' ? { package: payload.package } : {}),
...(Array.isArray(payload.tags) ? { tags: payload.tags.filter((t): t is string => typeof t === 'string') } : {}),
...(typeof payload.shortcut === 'string' ? { shortcut: payload.shortcut } : {}),
};
const nextList = existing
? vault.snippets.map((item) => (item.id === id ? nextSnippet : item))
: [...vault.snippets, nextSnippet];
vault.updateSnippets(nextList);
return { snippet: summarizeSnippet(nextSnippet) };
}
case 'snippets.delete': {
const id = typeof payload.id === 'string' ? payload.id : '';
const exists = vault.snippets.some((item) => item.id === id);
if (exists) {
vault.updateSnippets(vault.snippets.filter((item) => item.id !== id));
}
return { deleted: exists };
}
case 'terminals.listSessions': {
const sessionRuntime = getAppSessionRuntime();
const activeId = activeTabStore.getActiveTabId();
const sessions = (sessionRuntime?.sessions ?? []).slice(0, 200).map((session) => ({
sessionId: session.id,
label: session.hostLabel || session.hostname || session.id,
hostname: session.hostname || '',
...(session.username ? { username: session.username } : {}),
protocol: session.protocol || 'ssh',
status: session.status || 'connecting',
...(session.workspaceId ? { workspaceId: session.workspaceId } : {}),
active: session.id === activeId || (Boolean(session.workspaceId) && session.workspaceId === activeId),
}));
return { sessions };
}
case 'terminals.readScreen': {
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
const maxRows = typeof payload.maxRows === 'number' ? Math.max(1, Math.min(300, payload.maxRows)) : 80;
const sessionRuntime = getAppSessionRuntime();
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
throw new Error('Terminal session not found');
}
const snapshot = captureScreenSnapshot(sessionId);
const lines = (snapshot.lines ?? []).slice(-maxRows);
return {
sessionId,
rows: snapshot.rows ?? lines.length,
cols: snapshot.cols ?? 80,
lines,
};
}
case 'terminals.sendInput': {
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
const data = typeof payload.data === 'string' ? payload.data : '';
const sessionRuntime = getAppSessionRuntime();
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
throw new Error('Terminal session not found');
}
const bridge = netcattyBridge.get();
if (!bridge?.writeToSession) throw new Error('Terminal input bridge is unavailable');
bridge.writeToSession(sessionId, data);
return { sent: true };
}
case 'terminals.openLocal': {
const sessionRuntime = getAppSessionRuntime();
if (!sessionRuntime?.createLocalTerminal) throw new Error('Local terminal is unavailable');
const sessionId = sessionRuntime.createLocalTerminal();
return { opened: true, ...(typeof sessionId === 'string' ? { sessionId } : {}) };
}
case 'workspace.listTabs': {
const sessionRuntime = getAppSessionRuntime();
const activeTabId = activeTabStore.getActiveTabId();
const tabs: Array<{ id: string; kind: 'vault' | 'sftp' | 'session' | 'workspace' | 'log'; title: string; active: boolean }> = [
{ id: 'vault', kind: 'vault', title: 'Vault', active: activeTabId === 'vault' },
{ id: 'sftp', kind: 'sftp', title: 'SFTP', active: activeTabId === 'sftp' },
];
for (const workspace of sessionRuntime?.workspaces ?? []) {
tabs.push({ id: workspace.id, kind: 'workspace', title: workspace.title || 'Workspace', active: activeTabId === workspace.id });
}
for (const session of sessionRuntime?.sessions ?? []) {
if (session.workspaceId) continue;
tabs.push({ id: session.id, kind: 'session', title: session.hostLabel || session.hostname || 'Terminal', active: activeTabId === session.id });
}
for (const logView of sessionRuntime?.logViews ?? []) {
tabs.push({ id: logView.id, kind: 'log', title: logView.title || 'Log', active: activeTabId === logView.id });
}
return { activeTabId, tabs: tabs.slice(0, 200) };
}
case 'workspace.focusTab': {
const tabId = typeof payload.tabId === 'string' ? payload.tabId : '';
const sessionRuntime = getAppSessionRuntime();
const known = new Set<string>(['vault', 'sftp']);
for (const workspace of sessionRuntime?.workspaces ?? []) known.add(workspace.id);
for (const session of sessionRuntime?.sessions ?? []) {
if (!session.workspaceId) known.add(session.id);
}
for (const logView of sessionRuntime?.logViews ?? []) known.add(logView.id);
let resolvedTabId = known.has(tabId) ? tabId : null;
if (!resolvedTabId) {
const memberSession = (sessionRuntime?.sessions ?? []).find((s) => s.id === tabId && s.workspaceId);
if (memberSession?.workspaceId && known.has(memberSession.workspaceId)) {
resolvedTabId = memberSession.workspaceId;
}
}
if (!resolvedTabId) return { focused: false };
if (sessionRuntime?.setActiveTabId) sessionRuntime.setActiveTabId(resolvedTabId);
else activeTabStore.setActiveTabId(resolvedTabId);
return { focused: true };
}
case 'views.open': {
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
const location = typeof payload.location === 'string' ? payload.location : '';
if (!viewId) throw new Error('Plugin view ID is required');
const queryContext = location === 'vault-page'
? { 'netcatty.surface': 'vault-page' }
: location === 'terminal-sidebar'
? { 'netcatty.surface': 'terminal-sidebar' }
: { 'netcatty.surface': 'view' };
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
if (!getContributions) {
throw new Error('Plugin contributions are unavailable');
}
const snapshot = await getContributions({ context: queryContext });
const resolved = snapshot.plugins
.flatMap((plugin) => plugin.views)
.find((view) => view.id === viewId && view.visible);
if (!resolved) {
throw new Error(`Plugin view is not available: ${viewId}`);
}
if (resolved.location === 'terminal-sidebar') {
const sessionRuntime = getAppSessionRuntime();
const activeTabId = activeTabStore.getActiveTabId();
const isTerminalTab = Boolean(
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
);
if (!isTerminalTab) {
throw new Error('An active terminal tab is required to open a terminal sidebar view');
}
}
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
openView({ viewId: resolved.id });
return { opened: true, focused: true, location: resolved.location };
}
default:
throw new Error(`Unsupported Vault data request: ${kind}`);
}
}
+338
View File
@@ -39,3 +39,341 @@ test('idle instances are evicted while active instances are never silently repla
assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release();
const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose();
});
test('cssUnchanged updates retain previously validated stylesheet and peek returns live session synchronously', () => {
const f = fixture(); const store = new PluginViewSessions();
assert.equal(store.peek('view'), null);
const view = store.acquire('view', f.bridge, request); const id = f.opened[0].instanceId;
assert.equal(store.peek('view'), view);
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.a{display:flex}', mutations: [] });
assert.equal(view.getSnapshot().css, '.a{display:flex}');
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, css: '', cssUnchanged: true, mutations: [[0, '~', { id: 't', type: 3, data: 'hi' }, 0]] } as Update);
assert.equal(view.getSnapshot().css, '.a{display:flex}');
assert.deepEqual(view.getSnapshot().tree.children[0], { id: 't', type: 3, data: 'hi' });
store.dispose();
});
test('empty first update holds loading briefly to prevent blank-frame flash then completes cleanly', async () => {
const f = fixture(); const store = new PluginViewSessions();
const view = store.acquire('empty-grace', f.bridge, request); const id = f.opened[0].instanceId;
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '', mutations: [] });
assert.equal(view.getSnapshot().loading, true, 'empty first update holds loading briefly');
await new Promise((resolve) => setTimeout(resolve, 90));
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
store.dispose();
});
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f1 = fixture();
const store = new PluginViewSessions();
const view1 = store.acquire('bad-seq', f1.bridge, request);
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
assert.equal(view1.getSnapshot().error, true);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Invalid plugin update order/);
assert.ok(warns[0][1] instanceof Error);
const f2 = fixture();
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
const view2 = store.acquire('bad-send', f2.bridge, request);
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
await Promise.resolve();
assert.equal(view2.getSnapshot().error, true);
assert.equal(warns.length, 2);
assert.match(String(warns[1][0]), /IPC channel closed/);
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-move', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
// is normalized as a move and published immediately with zero warnings.
const movedNode = {
id: 'group-1',
type: 1 as const,
element: 'section',
attributes: { class: 'sorted' },
children: [{
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
}],
};
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.sorted{color:blue}',
mutations: [[0, '~', movedNode, 1]],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true);
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-move'), view);
// A subsequent incremental update applies cleanly against the moved nodes.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{
...movedNode,
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
},
{ id: 'row-2', type: 3, data: 'second' },
]);
// Forbidden mutations still dispose the session.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-recovery', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '',
cssUnchanged: true,
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Duplicate view node/);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-recovery'), view);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
{ id: 'row-2', type: 3, data: 'second' },
]);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-pending', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-supersede', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '.row{color:red}',
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'again']],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
assert.equal(view.getSnapshot().css.includes('blue'), false);
store.dispose();
} finally {
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;
}
});
+100 -6
View File
@@ -1,11 +1,24 @@
import { createPluginRemoteTree } from './pluginRemoteTree';
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
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;
function hasRenderableTreeContent(tree: PluginViewSnapshot['tree']): boolean {
for (const child of tree.children) {
if (child.type === 3 && child.data.trim().length > 0) return true;
if (child.type === 1) {
if (child.element !== 'div' || child.children.length > 0) return true;
}
}
return false;
}
/** Owns a window's bounded, retained UI instances independently of React mounts. */
export class PluginViewSessions {
@@ -15,13 +28,18 @@ 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;
let timer: ReturnType<typeof setTimeout> | undefined;
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
const listeners = new Set<() => void>();
const publish = (next: PluginViewSnapshot) => { state = next; for (const listener of listeners) listener(); };
const cleanup: Array<() => void> = [];
const dispose = (failed = false) => {
if (disposed) return;
disposed = true; clearTimeout(timer); cleanup.forEach((stop) => stop());
disposed = true; clearTimeout(timer); clearTimeout(emptyFrameTimer); cleanup.forEach((stop) => stop());
this.sessions.delete(key);
publish({ ...empty(), loading: false, error: failed });
void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
@@ -29,10 +47,72 @@ export class PluginViewSessions {
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
let stagedCss: string | null = null;
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId });
} catch { dispose(true); }
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.
pendingCss = null;
pendingRawCss = null;
} else {
stagedCss = validatePluginStylesheet(update.css);
stagedRawCss = update.css;
}
const nextCss = stagedCss ?? pendingCss ?? state.css;
const nextTree = tree.apply(update.mutations);
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
pendingCss = null;
pendingRawCss = null;
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
if (state.loading && !hasRenderableTreeContent(nextTree)) {
// Hold the host loading surface briefly while an older SDK flushes its
// initial React commit so users never see an empty blank frame flash.
publish({ tree: nextTree, css: nextCss, loading: true, error: false, settled });
if (emptyFrameTimer === undefined) {
emptyFrameTimer = setTimeout(() => {
emptyFrameTimer = undefined;
if (!disposed && state.loading) publish({ ...state, loading: false });
}, EMPTY_FIRST_FRAME_GRACE_MS);
}
return;
}
if (emptyFrameTimer !== undefined) {
clearTimeout(emptyFrameTimer);
emptyFrameTimer = undefined;
}
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
} 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 (duplicateNode) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
}
return;
}
dispose(true);
}
}));
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
@@ -64,11 +144,25 @@ export class PluginViewSessions {
send: (event: HostDrawnViewEvent) => {
if (disposed || users === 0) return;
publish({ ...state, settled: false });
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
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);
});
},
dispose,
};
}
peek(key: string) {
return this.sessions.get(key) ?? null;
}
acquire(key: string, bridge: Bridge, request: Omit<import('@netcatty/plugin-contract').HostDrawnViewOpenRequest, 'instanceId'>) {
let session = this.sessions.get(key);
if (!session) {
@@ -1,3 +1,5 @@
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
type CloseablePluginViewSessions = {
closeView(viewId: string): void;
};
@@ -16,3 +18,7 @@ export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSe
export function closePluginViewSessionIfLoaded(viewId: string): void {
loadedSessions?.closeView(viewId);
}
export function prewarmHostDrawnPluginView(viewId: string): void {
void netcattyBridge.get()?.prewarmHostDrawnPluginView?.(viewId)?.catch?.(() => {});
}
@@ -0,0 +1,215 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import type { ConnectionLog } from '../../domain/models';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import {
publishConnectionLogsSnapshot,
registerConnectionLogsActions,
} from './connectionLogsStore';
import {
clearAllRemoteDesktopRecordingsAndSyncLogs,
collectProtectedRemoteDesktopMediaIds,
} from './remoteDesktopLogActions';
import { withVaultImportLock } from './vaultManagedImportLock';
function installDomEnv() {
const dom = new JSDOM('', { url: 'http://localhost' });
const heldLocks = new Set<string>();
const fakeLocks = {
request: async <T>(name: string, cb: () => Promise<T>): Promise<T> => {
if (heldLocks.has(name)) {
throw new Error(`DEADLOCK: re-entrant lock acquisition on ${name}`);
}
heldLocks.add(name);
try {
return await cb();
} finally {
heldLocks.delete(name);
}
},
};
const keys = ['window', 'document', 'localStorage', 'navigator'] as const;
const previous = new Map<string, PropertyDescriptor | undefined>(
keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
);
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
document: { value: dom.window.document, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
navigator: { value: { locks: fakeLocks }, configurable: true },
});
return {
restore: () => {
dom.window.close();
for (const key of keys) {
const desc = previous.get(key);
if (desc) Object.defineProperty(globalThis, key, desc);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
test('clearAllRemoteDesktopRecordingsAndSyncLogs protects saved logs and clears unsaved metadata even in detached Settings window', async () => {
const env = installDomEnv();
const savedClipId = '11111111-1111-4111-8111-111111111111';
const unsavedClipId = '22222222-2222-4222-8222-222222222222';
const unsavedThumbId = '33333333-3333-4333-8333-333333333333';
const persistedLogs: ConnectionLog[] = [
{
id: 'log-saved',
hostId: 'h1',
hostLabel: 'Saved RDP',
hostname: '10.0.0.1',
username: 'admin',
protocol: 'rdp',
startTime: 1000,
endTime: 2000,
localUsername: 'u',
localHostname: 'l',
saved: true,
recordingId: savedClipId,
recordings: [
{
id: savedClipId,
startedAt: 1000,
endedAt: 2000,
durationMs: 1000,
bytes: 500,
mimeType: 'video/webm',
hasAudio: false,
},
],
},
{
id: 'log-unsaved',
hostId: 'h2',
hostLabel: 'Unsaved RDP',
hostname: '10.0.0.2',
username: 'admin',
protocol: 'rdp',
startTime: 3000,
endTime: 4000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 3000,
endedAt: 4000,
durationMs: 1000,
bytes: 600,
mimeType: 'video/webm',
hasAudio: false,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
thumbnailId: unsavedThumbId,
},
},
];
globalThis.localStorage.setItem(STORAGE_KEY_CONNECTION_LOGS, JSON.stringify(persistedLogs));
// Simulate detached Settings window: connectionLogsStore is unmounted/empty.
publishConnectionLogsSnapshot({ connectionLogs: [] });
registerConnectionLogsActions(null);
const clearAllCalls: Array<{ protectedIds?: string[] }> = [];
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async (opts: { protectedIds?: string[] }) => {
clearAllCalls.push(opts);
return { deleted: 1 };
},
},
};
try {
assert.deepEqual(collectProtectedRemoteDesktopMediaIds(), [savedClipId]);
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(clearAllCalls.length, 1);
assert.deepEqual(clearAllCalls[0].protectedIds, [savedClipId]);
const after = JSON.parse(
globalThis.localStorage.getItem(STORAGE_KEY_CONNECTION_LOGS) || '[]',
) as ConnectionLog[];
assert.equal(after.length, 2);
assert.equal(after[0].recordingId, savedClipId);
assert.equal(after[0].recordings?.length, 1);
assert.equal(after[1].recordingId, undefined);
assert.equal(after[1].recordings, undefined);
assert.equal(after[1].remoteDesktopMeta?.thumbnailId, undefined);
assert.deepEqual(after[1].remoteDesktopMeta?.resolution, { width: 1920, height: 1080 });
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
test('clearAllRemoteDesktopRecordingsAndSyncLogs does not deadlock when updateConnectionLog acquires connection-logs lock', async () => {
const env = installDomEnv();
const unsavedClipId = '44444444-4444-4444-8444-444444444444';
const liveLog: ConnectionLog = {
id: 'log-live-unsaved',
hostId: 'h3',
hostLabel: 'Live RDP',
hostname: '10.0.0.3',
username: 'admin',
protocol: 'rdp',
startTime: 5000,
endTime: 6000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 5000,
endedAt: 6000,
durationMs: 1000,
bytes: 700,
mimeType: 'video/webm',
hasAudio: false,
},
],
};
let updatedCount = 0;
publishConnectionLogsSnapshot({ connectionLogs: [liveLog] });
registerConnectionLogsActions({
updateConnectionLog: async () => {
await withVaultImportLock('connection-logs', async () => {
updatedCount += 1;
});
},
toggleConnectionLogSaved: () => {},
deleteConnectionLog: () => {},
clearUnsavedConnectionLogs: () => {},
});
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async () => ({ deleted: 1 }),
},
};
try {
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(updatedCount, 1);
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
@@ -0,0 +1,207 @@
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type {
ConnectionLog,
RemoteDesktopRecordingClip,
RemoteDesktopSessionEvent,
RemoteDesktopSessionMetadata,
} from '../../domain/models';
import {
buildAppendRecordingClipUpdate,
buildClearRecordingsUpdate,
getConnectionLogMediaIds,
} from '../../domain/remoteDesktopRecording';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
listRemoteDesktopAuditEntries,
subscribeRemoteDesktopAuditLog,
type RemoteDesktopAuditEntry,
} from '../../infrastructure/remoteDesktop/remoteDesktopAuditLog';
import {
netcattyBridge,
type RemoteDesktopRecordingsBridgeApi,
} from '../../infrastructure/services/netcattyBridge';
import {
getConnectionLogsActions,
getConnectionLogsSnapshot,
} from './connectionLogsStore';
import { withVaultImportLock } from './vaultManagedImportLock';
export type { RemoteDesktopAuditEntry };
export function getRemoteDesktopRecordingsBridge(): RemoteDesktopRecordingsBridgeApi | null {
return netcattyBridge.get()?.remoteDesktopRecordings ?? null;
}
export function registerSessionLogFinalizer(
finalize: () => void | Promise<void>,
): (() => void) | undefined {
const unsub = netcattyBridge.get()?.onFinalizeSessionLogs?.(finalize);
return typeof unsub === 'function' ? unsub : undefined;
}
export async function getSystemUserHostInfo(): Promise<{ username: string; hostname: string }> {
try {
const info = await netcattyBridge.get()?.getSystemInfo?.();
return {
username: info?.username || 'user',
hostname: info?.hostname || 'localhost',
};
} catch {
return { username: 'user', hostname: 'localhost' };
}
}
export function listRemoteDesktopSessionAuditEntries(
sessionId?: string,
): RemoteDesktopAuditEntry[] {
return listRemoteDesktopAuditEntries(sessionId);
}
export function subscribeRemoteDesktopSessionAuditLog(listener: () => void): () => void {
return subscribeRemoteDesktopAuditLog(listener);
}
function readPersistedConnectionLogs(): ConnectionLog[] {
try {
const stored = localStorageAdapter.read<ConnectionLog[]>(STORAGE_KEY_CONNECTION_LOGS);
return Array.isArray(stored) ? stored : [];
} catch {
return [];
}
}
/**
* Collect all protected media IDs (video clips + thumbnails) across bookmarked
* connection logs from BOTH the in-memory store and persisted localStorage.
* Works identically in the main window and detached Settings window.
*/
export function collectProtectedRemoteDesktopMediaIds(): string[] {
const protectedSet = new Set<string>();
const { connectionLogs } = getConnectionLogsSnapshot();
for (const log of connectionLogs) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
for (const log of readPersistedConnectionLogs()) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
return Array.from(protectedSet);
}
export async function appendRemoteDesktopClipToConnectionLog(
sessionId: string,
clip: RemoteDesktopRecordingClip,
options?: { stampEndTime?: boolean },
): Promise<boolean> {
const { connectionLogs } = getConnectionLogsSnapshot();
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const updates = buildAppendRecordingClipUpdate(matchingLog, clip, {
stampEndTime: options?.stampEndTime ? Date.now() : undefined,
});
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, updates));
return true;
}
export async function updateRemoteDesktopConnectionLogActivity(
sessionId: string,
updater: (current: {
events: RemoteDesktopSessionEvent[];
meta: RemoteDesktopSessionMetadata | undefined;
}) => {
events?: RemoteDesktopSessionEvent[];
meta?: RemoteDesktopSessionMetadata;
},
): Promise<boolean> {
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const next = updater({
events: Array.isArray(matchingLog.remoteDesktopEvents) ? matchingLog.remoteDesktopEvents : [],
meta: matchingLog.remoteDesktopMeta,
});
const patch: Partial<ConnectionLog> = {};
if (next.events) patch.remoteDesktopEvents = next.events;
if (next.meta) patch.remoteDesktopMeta = next.meta;
if (Object.keys(patch).length === 0) return false;
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, patch));
return true;
}
export async function saveRemoteDesktopThumbnail(options: {
id?: string;
data: Uint8Array;
}): Promise<{ ok: boolean; id?: string; url?: string; bytes?: number } | null> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.saveThumbnail) return null;
return bridge.saveThumbnail(options);
}
/**
* Clear all unprotected remote desktop recordings on disk and atomically clear
* their references from connection logs. Safe to invoke from detached windows
* (such as Settings -> System) where `useVaultState` is not mounted.
*/
export async function clearAllRemoteDesktopRecordingsAndSyncLogs(): Promise<{ deleted: number }> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.clearAll) return { deleted: 0 };
const protectedIds = collectProtectedRemoteDesktopMediaIds();
const protectedSet = new Set(protectedIds);
const res = await bridge.clearAll({ protectedIds });
const actions = getConnectionLogsActions();
if (actions?.updateConnectionLog) {
// Call `actions.updateConnectionLog` OUTSIDE `withVaultImportLock('connection-logs')`
// because `useVaultState.commitConnectionLogs` acquires that same non-reentrant Web Lock.
const { connectionLogs } = getConnectionLogsSnapshot();
const persistedById = new Map(readPersistedConnectionLogs().map((log) => [log.id, log]));
const targets = new Map<string, ConnectionLog>();
for (const log of connectionLogs) targets.set(log.id, log);
for (const [id, log] of persistedById) {
if (!targets.has(id)) targets.set(id, log);
}
for (const log of targets.values()) {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (updates) {
await Promise.resolve(actions.updateConnectionLog(log.id, updates));
}
}
} else {
// Detached window (e.g. Settings -> System without Sync tab mounted): update
// localStorage atomically under the shared cross-window Web Lock.
await withVaultImportLock('connection-logs', async () => {
const persisted = readPersistedConnectionLogs();
let changed = false;
const nextPersisted = persisted.map((log) => {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (!updates) return log;
changed = true;
return { ...log, ...updates };
});
if (changed) {
localStorageAdapter.write(STORAGE_KEY_CONNECTION_LOGS, nextPersisted);
}
});
}
return { deleted: res?.deleted ?? 0 };
}
+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';
@@ -16,19 +16,33 @@ export function createTerminalDirectoryController(options: {
target?: DirectoryTarget;
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 valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
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');
}
@@ -57,7 +71,7 @@ export function createTerminalDirectoryController(options: {
if (!capabilities.readCwd) throw new DirectoryPickerError('unavailable');
const activeShellCwd = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision)
? cwd : null;
};
@@ -66,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.
@@ -79,20 +93,24 @@ export function createTerminalDirectoryController(options: {
cwd = await bounded(options.io.cwd());
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
} catch (error) {
if (current() && target.pathFlavor === 'win32') {
confirmed = false;
if (current() && !trustsOsc7) {
verifiedCwd = null;
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
options.publish('');
notifyCwd();
}
throw error;
}
check();
const reported = activeShellCwd();
const live = terminalCwdStore.getCwd(options.sessionId);
confirmed = true;
const verifiedCwdChanged = verifiedCwd !== cwd;
verifiedCwd = cwd;
cwdError = null;
if (reported) return reported;
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd);
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|| verifiedCwdChanged) options.publish(cwd);
if (verifiedCwdChanged) notifyCwd();
return cwd;
})();
refreshing = pending;
@@ -119,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 && 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');
@@ -127,7 +145,7 @@ export function createTerminalDirectoryController(options: {
const deadline = Date.now() + (options.confirmationMs ?? 8000);
const hasFreshOsc7 = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
&& terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (same(cwd, path) || same(cwd, canonical));
};
@@ -165,15 +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,
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(() => {});
}
/**
+3 -1
View File
@@ -109,7 +109,8 @@ export interface UseAIChatStreamingReturn {
export interface SendToCattyContext {
activeProvider: ProviderConfig | undefined;
activeModelId: string;
scopeType: 'terminal' | 'workspace';
reasoningEffort?: string;
scopeType: 'terminal' | 'workspace' | 'global';
scopeTargetId?: string;
scopeLabel?: string;
globalPermissionMode: AIPermissionMode;
@@ -125,6 +126,7 @@ export interface SendToCattyContext {
selectedUserSkillSlugs?: string[];
permissionMode?: AIPermissionMode;
forceCompaction?: boolean;
pluginContext?: import('../../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
}
export interface SendToExternalContext {
+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,
+15 -1
View File
@@ -16,5 +16,19 @@ export const useClipboardBackend = () => {
return await bridge.writeClipboardText(text) === true;
}, []);
return { readClipboardText, writeClipboardText };
const readClipboardImagePng = useCallback(async (): Promise<Uint8Array | null> => {
const bridge = netcattyBridge.get();
if (bridge?.readClipboardImagePng) return await bridge.readClipboardImagePng();
// Browser fallback when the native clipboard bridge is unavailable.
const items = await navigator.clipboard?.read();
for (const item of items ?? []) {
if (!item.types.includes("image/png")) continue;
const blob = await item.getType("image/png");
return new Uint8Array(await blob.arrayBuffer());
}
return null;
}, []);
return { readClipboardText, writeClipboardText, readClipboardImagePng };
};
+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();
+17 -20
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,13 +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 observedCwd = terminalCwdStore.getCwd(sessionId);
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && 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);
@@ -45,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;
@@ -61,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;
@@ -77,7 +74,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
for (let attempt = 0; attempt < 3; attempt++) {
const revision = terminalCwdStore.getSessionRevision(sessionId);
const result = await controller.list(cwd, task.signal);
if (task.signal.aborted || id !== generation.current || terminalCwdStore.getCwd(sessionId) !== cwd) return;
if (task.signal.aborted || id !== generation.current || getCurrentCwd() !== cwd) return;
if (terminalCwdStore.getSessionRevision(sessionId) !== revision) continue;
listingBase.current = cwd; listingRevision.current = revision; setEntries(result.entries); setHome(result.home);
return;
@@ -86,7 +83,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
} catch (failure) {
if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed');
} finally { if (!task.signal.aborted && id === generation.current) setLoading(false); }
}, [controller, cwd, report, sessionId, setHome]);
}, [controller, cwd, getCurrentCwd, report, sessionId, setHome]);
useEffect(() => {
if (!cwd) {
@@ -102,8 +99,8 @@ export function useComposeDirectoryPicker(sessionId: string) {
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
if (sending.current) return;
if (!cwd || terminalCwdStore.getCwd(sessionId) !== cwd
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
if (!cwd || getCurrentCwd() !== 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;
@@ -115,14 +112,14 @@ export function useComposeDirectoryPicker(sessionId: string) {
finally {
if (id === generation.current) { sending.current = false; setPending(false); }
}
}, [controller, report, cwd, sessionId, pathFlavor]);
}, [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 === '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',
+33 -7
View File
@@ -11,23 +11,39 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
}) {
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const scopeId = typeof window !== 'undefined'
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
: '';
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
image?: (path: string) => Promise<string>;
}>({ key: '', snapshot: initial() });
}>(() => (
cachedSession
? { key, snapshot: cachedSession.getSnapshot(), image: cachedSession.image }
: { key: '', snapshot: initial() }
));
const [hidden, setHidden] = useState(false);
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
useEffect(() => {
if (!active) return;
if (!active) {
setHidden(false);
return;
}
const bridge = netcattyBridge.get();
if (!bridge) { unavailableRef.current(); return; }
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) });
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
sessionRef.current = { key, send: session.send, image: session.image };
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
@@ -37,11 +53,21 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const loadImage = active && state.key === key && state.image ? state.image : fallbackLoadImage;
const hasCurrentState = active
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
? state.snapshot
: cachedSession
? cachedSession.getSnapshot()
: initial();
const loadImage = hasCurrentState && state.image
? state.image
: (cachedSession?.image ?? fallbackLoadImage);
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
// A newly selected plugin must never receive values from the previous tree,
// even during the render before effect cleanup and the next activation.
return { ...(state.key === key ? state.snapshot : initial()), visible: active && !hidden, loadImage, sendEvent };
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
}
+144
View File
@@ -0,0 +1,144 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import type {
PluginAISidebarContextSnapshot,
PluginAISidebarToolSpec,
PluginAISidebarTurnContext,
} from '../../infrastructure/ai/pluginAiSidebarTypes';
const WIDTH_STORAGE_KEY = 'netcatty:plugin-ai-sidebar-width';
export const DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH = 400;
export const MIN_PLUGIN_AI_SIDEBAR_WIDTH = 320;
export const MAX_PLUGIN_AI_SIDEBAR_WIDTH = 680;
export function readPluginAiSidebarWidth(): number {
const parsed = localStorageAdapter.readNumber(WIDTH_STORAGE_KEY);
if (
typeof parsed === 'number'
&& Number.isFinite(parsed)
&& parsed >= MIN_PLUGIN_AI_SIDEBAR_WIDTH
&& parsed <= MAX_PLUGIN_AI_SIDEBAR_WIDTH
) {
return Math.round(parsed);
}
return DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH;
}
export function writePluginAiSidebarWidth(width: number): void {
const clamped = Math.max(
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
Math.min(MAX_PLUGIN_AI_SIDEBAR_WIDTH, Math.round(width)),
);
localStorageAdapter.writeNumber(WIDTH_STORAGE_KEY, clamped);
}
const EMPTY_STATE: NetcattyPluginAiSidebarState = Object.freeze({
contexts: Object.freeze([]),
tools: Object.freeze([]),
});
export interface PendingPluginSidebarPrompt {
readonly id: number;
readonly prompt: string;
readonly autoSend?: boolean;
}
let nextPromptSeq = 1;
export function usePluginAiSidebarForView(options: {
pluginId: string;
pluginName: string;
viewId: string;
enabled?: boolean;
onCommand?: (command: NetcattyPluginAiSidebarCommand) => void;
}) {
const { pluginId, pluginName, viewId, enabled = true, onCommand } = options;
const [state, setState] = useState<NetcattyPluginAiSidebarState>(EMPTY_STATE);
useEffect(() => {
if (!enabled) {
setState(EMPTY_STATE);
return;
}
const bridge = netcattyBridge.get();
if (!bridge?.getPluginAiSidebarState && !bridge?.onPluginAiSidebarStateChanged) {
setState(EMPTY_STATE);
return;
}
let active = true;
let receivedPush = false;
const unsubscribeState = bridge.onPluginAiSidebarStateChanged?.((next) => {
if (!active) return;
receivedPush = true;
setState(next ?? EMPTY_STATE);
});
void bridge.getPluginAiSidebarState?.().then((next) => {
if (!active || receivedPush) return;
setState(next ?? EMPTY_STATE);
}).catch(() => {
if (!active || receivedPush) return;
setState(EMPTY_STATE);
});
return () => {
active = false;
unsubscribeState?.();
};
}, [enabled]);
useEffect(() => {
if (!enabled || !onCommand) return;
const bridge = netcattyBridge.get();
if (!bridge?.onPluginAiSidebarCommand) return;
return bridge.onPluginAiSidebarCommand((command) => {
if (!command || command.pluginId !== pluginId) return;
if (command.viewId && command.viewId !== viewId) return;
onCommand(command);
});
}, [enabled, onCommand, pluginId, viewId]);
const contextSnapshot: PluginAISidebarContextSnapshot | null = useMemo(() => {
const match = state.contexts.find(
(entry) => entry.pluginId === pluginId && entry.viewId === viewId,
);
return match ?? null;
}, [pluginId, state.contexts, viewId]);
const tools: readonly PluginAISidebarToolSpec[] = useMemo(() => (
state.tools.filter(
(tool) => tool.pluginId === pluginId && (!tool.viewId || tool.viewId === viewId),
)
), [pluginId, state.tools, viewId]);
const turnContext: PluginAISidebarTurnContext | null = useMemo(() => {
if (!contextSnapshot && tools.length === 0) return null;
return {
pluginId,
pluginName: contextSnapshot?.pluginName || pluginName,
viewId,
...(contextSnapshot?.title ? { title: contextSnapshot.title } : {}),
...(contextSnapshot?.subtitle ? { subtitle: contextSnapshot.subtitle } : {}),
...(contextSnapshot?.summary ? { summary: contextSnapshot.summary } : {}),
tools,
};
}, [contextSnapshot, pluginId, pluginName, tools, viewId]);
const suggestedPrompts = contextSnapshot?.suggestedPrompts;
const createPendingPrompt = useCallback(
(prompt: string, autoSend?: boolean): PendingPluginSidebarPrompt => ({
id: nextPromptSeq++,
prompt,
autoSend,
}),
[],
);
return {
contextSnapshot,
tools,
turnContext,
suggestedPrompts,
createPendingPrompt,
};
}
+74
View File
@@ -2,6 +2,28 @@ import { useEffect, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
type Raster = { light: string; dark?: string };
const MAX_CATALOG_BRAND_ICON_CACHE = 256;
const SAFE_PNG_DATA_URI = /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/;
const catalogBrandIconCache = new Map<string, Raster | null>();
const catalogBrandIconPending = new Map<string, Promise<Raster | null>>();
function normalizeCatalogBrandIcon(value: { light?: string | null; dark?: string | null } | null | undefined): Raster | null {
if (!value || typeof value !== 'object') return null;
const isSafe = (uri: unknown): uri is string =>
typeof uri === 'string' && uri.length <= 700_000 && SAFE_PNG_DATA_URI.test(uri);
const light = isSafe(value.light) ? value.light : null;
const dark = isSafe(value.dark) ? value.dark : null;
if (light) return dark ? { light, dark } : { light };
if (dark) return { light: dark, dark };
return null;
}
export function clearCatalogBrandIconCacheForTests(): void {
catalogBrandIconCache.clear();
catalogBrandIconPending.clear();
}
export function usePluginBrandIcon(plugin?: NetcattyInstalledPlugin): Raster | null {
const pluginId = plugin?.id;
const kind = plugin?.manifest?.icon?.kind;
@@ -17,3 +39,55 @@ export function usePluginBrandIcon(plugin?: NetcattyInstalledPlugin): Raster | n
}, [key, pluginId, kind]);
return loaded?.key === key ? loaded.value : null;
}
export function useCatalogBrandIcon(entry?: NetcattyPluginCatalogEntry, sourceId = 'official'): Raster | null {
const entryId = entry?.id;
const selectionToken = entry?.selectionToken;
const iconKind = entry?.manifest?.icon?.kind;
const cacheKey = entryId && selectionToken && iconKind !== 'theme'
? JSON.stringify([sourceId, entryId, selectionToken])
: null;
const cached = cacheKey && catalogBrandIconCache.has(cacheKey)
? catalogBrandIconCache.get(cacheKey) ?? null
: undefined;
const [loaded, setLoaded] = useState<{ key: string; value: Raster | null } | null>(null);
useEffect(() => {
if (!cacheKey || !entryId || !selectionToken) return;
if (catalogBrandIconCache.has(cacheKey)) {
setLoaded({ key: cacheKey, value: catalogBrandIconCache.get(cacheKey) ?? null });
return;
}
const fetchIcon = netcattyBridge.get()?.getPluginCatalogBrandIcon;
if (!fetchIcon) return;
let cancelled = false;
let request = catalogBrandIconPending.get(cacheKey);
if (!request) {
request = Promise.resolve(fetchIcon(entryId, selectionToken, sourceId))
.then((raw) => {
const normalized = normalizeCatalogBrandIcon(raw);
if (catalogBrandIconCache.size >= MAX_CATALOG_BRAND_ICON_CACHE) {
catalogBrandIconCache.clear();
}
catalogBrandIconCache.set(cacheKey, normalized);
return normalized;
})
.finally(() => {
if (catalogBrandIconPending.get(cacheKey) === request) {
catalogBrandIconPending.delete(cacheKey);
}
});
catalogBrandIconPending.set(cacheKey, request);
}
void request.then((value) => {
if (!cancelled) setLoaded({ key: cacheKey, value });
}).catch(() => {
if (!cancelled) setLoaded({ key: cacheKey, value: null });
});
return () => { cancelled = true; };
}, [cacheKey, entryId, selectionToken, sourceId]);
if (!cacheKey) return null;
if (cached !== undefined) return cached;
return loaded?.key === cacheKey ? loaded.value : null;
}
+63 -6
View File
@@ -6,6 +6,8 @@ import { getAppHandlers } from '../app/appHandlersBridge';
import { getAppAppLockRuntime, getAppVaultRuntime, getAppSettingsRuntime } from './appRuntimeBridge';
import { PluginHostActionResources } from './pluginHostActionResources';
import { executePluginHostAction, type PluginHostAction } from './pluginHostActionExecution';
import { handlePluginVaultDataRequest } from './pluginVaultDataHandlers';
import { requestOpenDualPaneSftp } from './sftp/sftpDualPaneOpenStore';
import { pluginHostRunsSavedScripts, type PluginHostDraftFields } from '../../domain/pluginHostActions';
import type { Host, GroupConfig, ManagedSource, Snippet } from '../../domain/models';
@@ -120,6 +122,27 @@ export function usePluginHostActions() {
});
return;
}
const openHostSession = (host: Host) => {
const mode = request.kind === 'vault.requestConnect' ? (request.mode ?? 'terminal') : 'terminal';
if (mode === 'sftp') {
requestOpenDualPaneSftp(host.id);
return;
}
const connect = getAppHandlers()?.handleConnectToHost;
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
return connect(host);
};
if (request.kind === 'vault.requestConnect' && entry.prompt.durableHostId && entry.host) {
assertCurrent(entry);
const receipt = await bridge.respondPluginInteraction!({ requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' });
if (!receipt || typeof receipt !== 'object' || !receipt.completionToken) throw new Error('Host action was revoked');
entry.completionToken = receipt.completionToken;
entry.claimed = true;
assertCurrent(entry);
await openHostSession(entry.host);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
return;
}
let action: PluginHostAction;
if (request.kind === 'vault.requestConnect' && target) action = { kind: 'connect', target };
else if (request.kind === 'vault.requestHostDraft' && entry.prompt.reviewedDraft) {
@@ -136,11 +159,7 @@ export function usePluginHostActions() {
entry.claimed = true;
assertCurrent(entry);
},
connect: (host) => {
const connect = getAppHandlers()?.handleConnectToHost;
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
return connect(host);
},
connect: openHostSession,
});
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
} catch { await fail(entry); }
@@ -191,7 +210,12 @@ export function usePluginHostActions() {
}
const vault = getVault();
const candidates = [...vault.hosts];
const host = prompt.vaultTarget ? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision) : undefined;
const host = prompt.durableHostId
? vault.hosts.find((candidate) => candidate.id === prompt.durableHostId)
: prompt.vaultTarget
? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision)
: undefined;
if (prompt.durableHostId && !host) throw new Error('Saved SSH host no longer exists');
const entry: Review = {
prompt, candidates, candidateRevisions: new Map(candidates.map((candidate) => [candidate.id, resources.current.metadata(candidate.id).revision])),
customGroups: vault.customGroups, host, groups: vault.groupConfigs, snippets: vault.snippets,
@@ -220,6 +244,39 @@ export function usePluginHostActions() {
};
}, [execute, fail, getVault]);
useEffect(() => {
const bridge = netcattyBridge.get();
if (!bridge?.onPluginVaultDataRequest || !bridge.respondPluginVaultData || !bridge.setPluginVaultDataReady) return;
const unsubscribe = bridge.onPluginVaultDataRequest((request) => {
void (async () => {
try {
const data = await handlePluginVaultDataRequest(request.kind, request.payload ?? {}, {
getVault,
resources: resources.current,
});
await bridge.respondPluginVaultData!({
requestId: request.requestId,
actionToken: request.actionToken,
ok: true,
data,
});
} catch (err) {
await bridge.respondPluginVaultData!({
requestId: request.requestId,
actionToken: request.actionToken,
ok: false,
error: err instanceof Error ? err.message : 'Vault data request failed',
}).catch(() => {});
}
})();
});
void bridge.setPluginVaultDataReady(true).catch(() => {});
return () => {
unsubscribe();
void bridge.setPluginVaultDataReady?.(false).catch(() => {});
};
}, [getVault]);
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
const entry = current.current;
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
+60 -23
View File
@@ -1,42 +1,32 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { checkPluginUpdates, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
import { checkPluginUpdates, type PluginUpdateCandidate, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
/** Manual catalog checks only; no scheduler, install or permission mutation. */
export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]) {
/** Automatic update checks on plugin view entry and package changes; explicit installUpdate runs only on user click. */
export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[], onUpdated?: () => Promise<unknown> | void) {
const [result, setResult] = useState<PluginUpdateCheckResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [updatingId, setUpdatingId] = useState<string | null>(null);
const [updateError, setUpdateError] = useState<string | null>(null);
const pending = useRef(false);
const updating = useRef(false);
const mounted = useRef(false);
const onUpdatedRef = useRef(onUpdated);
onUpdatedRef.current = onUpdated;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const generation = useRef(0);
const pluginsCount = plugins.length;
const identityKey = useMemo(() => JSON.stringify(plugins.map((plugin) => [
plugin.id, plugin.activeVersion, plugin.archiveSha256, plugin.source?.id,
plugin.source?.kind, plugin.source?.origin,
])), [plugins]);
useEffect(() => {
generation.current++;
setResult(null);
setError(null);
const requests = generation;
return () => { requests.current++; };
}, [identityKey]);
useEffect(() => {
const invalidate = () => {
generation.current++;
setResult(null);
setError(null);
};
const unsubscribe = netcattyBridge.get()?.onPluginContributionsChanged?.(invalidate);
window.addEventListener('netcatty:plugin-packages-changed', invalidate);
return () => { unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', invalidate); };
}, []);
const check = useCallback(async () => {
const check = useCallback(async (options?: { silent?: boolean }) => {
if (pending.current) return;
pending.current = true;
const current = generation.current;
setBusy(true); setError(null); setResult(null);
setBusy(true); setError(null); setUpdateError(null);
if (!options?.silent) setResult(null);
try {
const value = await checkPluginUpdates(netcattyBridge.require());
if (mounted.current && current === generation.current) setResult(value);
@@ -48,5 +38,52 @@ export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]
if (mounted.current) setBusy(false);
}
}, []);
return { result, error, busy, check };
useEffect(() => {
generation.current++;
setResult(null);
setError(null);
const requests = generation;
if (pluginsCount > 0 && netcattyBridge.get()?.listPluginCatalog) {
void check();
}
return () => { requests.current++; };
}, [identityKey, pluginsCount, check]);
useEffect(() => {
const invalidate = () => {
generation.current++;
setResult(null);
setError(null);
};
const unsubscribe = netcattyBridge.get()?.onPluginContributionsChanged?.(invalidate);
window.addEventListener('netcatty:plugin-packages-changed', invalidate);
return () => { unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', invalidate); };
}, []);
const installUpdate = useCallback(async (candidate: PluginUpdateCandidate, wasEnabled = false) => {
if (updating.current) return;
updating.current = true;
setUpdatingId(candidate.pluginId);
setUpdateError(null);
try {
const bridge = netcattyBridge.require();
if (!bridge.listPluginCatalog || !bridge.installCatalogPlugin) throw new Error('Catalog installation unavailable');
const catalog = await bridge.listPluginCatalog(candidate.sourceId);
if (catalog.error || catalog.source !== 'registry') {
throw new Error(catalog.error ?? 'Registry refresh failed');
}
const entry = catalog.entries.find((item) => item.id === candidate.pluginId && item.artifact);
if (!entry) throw new Error('Published update is no longer available');
await bridge.installCatalogPlugin(candidate.pluginId, entry.selectionToken, candidate.sourceId, candidate.sourceId);
if (wasEnabled && bridge.setPluginEnabled) {
await bridge.setPluginEnabled(candidate.pluginId, true);
}
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
await onUpdatedRef.current?.();
} catch (cause) {
if (mounted.current) setUpdateError(cause instanceof Error ? cause.message : String(cause));
} finally {
updating.current = false;
if (mounted.current) setUpdatingId(null);
}
}, []);
return { result, error, busy, check, updatingId, updateError, installUpdate };
}
+53
View File
@@ -0,0 +1,53 @@
import { useEffect, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
const EMPTY_BADGES: ReadonlyMap<string, NetcattyPluginViewBadge> = new Map();
function buildBadgeMap(
badges: ReadonlyArray<NetcattyPluginViewBadge> | null | undefined,
): ReadonlyMap<string, NetcattyPluginViewBadge> {
if (!Array.isArray(badges) || badges.length === 0) return EMPTY_BADGES;
const map = new Map<string, NetcattyPluginViewBadge>();
for (const badge of badges) {
if (badge && typeof badge.viewId === 'string' && badge.viewId.length > 0) {
map.set(badge.viewId, badge);
}
}
return map.size > 0 ? map : EMPTY_BADGES;
}
export function usePluginViewBadges(enabled = true): ReadonlyMap<string, NetcattyPluginViewBadge> {
const [badgesByViewId, setBadgesByViewId] = useState<ReadonlyMap<string, NetcattyPluginViewBadge>>(EMPTY_BADGES);
useEffect(() => {
if (!enabled) {
setBadgesByViewId(EMPTY_BADGES);
return;
}
const bridge = netcattyBridge.get();
if (!bridge?.listPluginViewBadges && !bridge?.onPluginViewBadgesChanged) {
setBadgesByViewId(EMPTY_BADGES);
return;
}
let active = true;
let receivedPush = false;
const unsubscribe = bridge.onPluginViewBadgesChanged?.((badges) => {
if (!active) return;
receivedPush = true;
setBadgesByViewId(buildBadgeMap(badges));
});
void bridge.listPluginViewBadges?.().then((badges) => {
if (!active || receivedPush) return;
setBadgesByViewId(buildBadgeMap(badges));
}).catch(() => {
if (!active || receivedPush) return;
setBadgesByViewId(EMPTY_BADGES);
});
return () => {
active = false;
unsubscribe?.();
};
}, [enabled]);
return badgesByViewId;
}
@@ -26,6 +26,7 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
export interface OpenPluginViewDetail {
viewId: string;
context?: Record<string, unknown>;
params?: unknown;
}
export type ResolvedPluginView = {
@@ -58,6 +58,7 @@ export const isAutoStartProxyReady = (
host.proxyProfileId && !validProxyProfileIds.has(host.proxyProfileId),
);
const missingGroupProxyProfile = Boolean(
!host.directProxy &&
!host.proxyConfig &&
!host.proxyProfileId &&
rawGroupDefaults.proxyProfileId &&
@@ -242,6 +242,9 @@ const persistPortForwardingConfig = (rules: PortForwardingRule[]) => {
);
};
/** Read-only snapshot of the in-memory runtime port-forwarding rules projection. */
export const getPortForwardingRuntimeRules = (): readonly PortForwardingRule[] => globalRules;
/** Persist configuration only — never write runtime phases to storage. */
const setGlobalRules = (newRules: PortForwardingRule[]) => {
globalRules = normalizeVaultOrder(newRules);
+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,15 +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: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: !sessionFilesystem,
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
@@ -60,8 +63,14 @@ export function useTerminalDirectorySession(options: {
if (windowsShell) register('win32', windowsShell);
else if (shellType === 'posix' && host.localShell) {
const shells = await bridge.discoverShells?.();
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
const command = host.localShell.toLowerCase();
if (shells?.some(shell => shell.id.startsWith('wsl-')
&& (command === shell.id.toLowerCase() || command === shell.command.toLowerCase()))) {
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,
};
}
@@ -0,0 +1,251 @@
import assert from 'node:assert/strict';
import test from 'node:test';
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' });
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 DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
let pluginsLoading = false;
let pluginsAvailable = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
return <div />;
}
const root = createRoot(document.getElementById('root')!);
const render = async () => {
await act(async () => {
root.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
};
try {
await render();
assert.equal(model.isCustomized, false);
assert.ok(model.visibleIds.includes(DB_PLUGIN));
assert.ok(model.visibleIds.includes(MONITOR_PLUGIN));
// Back-to-back mutations in the same act batch under StrictMode return fresh
// synchronous configs and preserve both mutations without updater side effects.
let afterReorder!: ReturnType<typeof model.reorder>;
let afterHide!: ReturnType<typeof model.setVisible>;
await act(async () => {
afterReorder = model.reorder(MONITOR_PLUGIN, 'hosts', 'after');
afterHide = model.setVisible('logs', false);
});
assert.equal(afterReorder.order[1], MONITOR_PLUGIN);
assert.equal(afterHide.order[1], MONITOR_PLUGIN);
assert.deepEqual(afterHide.hidden, ['logs']);
assert.equal(model.visibleIds[1], MONITOR_PLUGIN);
assert.equal(model.isHidden('logs'), true);
assert.equal(model.visibleIds.includes('logs'), false);
assert.equal(model.isCustomized, true);
// Locked 'hosts' cannot be hidden.
await act(async () => {
model.setVisible('hosts', false);
});
assert.equal(model.isHidden('hosts'), false);
// Simulate cold start: unmount, remount with pluginsLoading = true & activePluginIds = [].
await act(async () => {
root.unmount();
});
const coldRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
pluginsLoading = true;
pluginsAvailable = false;
await act(async () => {
coldRoot.render(<Fixture />);
});
// Plugin preferences stay preserved in config while loading, but don't show in visibleIds yet.
assert.equal(model.visibleIds.includes(MONITOR_PLUGIN), false);
assert.ok(model.config.order.includes(MONITOR_PLUGIN));
// Plugins finish loading, but DB_PLUGIN was uninstalled.
activePluginIds = [MONITOR_PLUGIN];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
coldRoot.render(<Fixture />);
});
assert.equal(model.visibleIds[1], MONITOR_PLUGIN, 'custom slot of remaining plugin survives cold start');
assert.equal(model.config.order.includes(DB_PLUGIN), false, 'uninstalled plugin is pruned cleanly');
const persisted = JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}');
assert.equal(persisted.order.includes(DB_PLUGIN), false, 'pruned plugin is also removed from storage');
assert.deepEqual(persisted.hidden, ['logs']);
// Reset restores defaults.
await act(async () => {
model.reset();
});
assert.equal(model.isCustomized, false);
assert.equal(model.isHidden('logs'), false);
assert.equal(model.visibleIds.at(-1), MONITOR_PLUGIN);
await act(async () => {
coldRoot.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();
}
});
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();
}
});
+257
View File
@@ -0,0 +1,257 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
areVaultNavConfigsEqual,
canHideVaultNavItem,
getManageableVaultNavIds,
getVisibleVaultNavIds,
isCustomVaultNavConfig,
moveVaultNavItem,
normalizeVaultNavConfig,
reconcileVaultNavConfig,
reorderVaultNavItems,
resetVaultNavConfig,
setVaultNavItemVisibility,
toggleVaultNavItemVisibility,
type PluginVaultNavId,
type VaultNavConfig,
type VaultNavDropPosition,
type VaultNavItemId,
} from '../../domain/vaultNavConfig';
import { STORAGE_KEY_VAULT_NAV_CONFIG } from '../../infrastructure/config/storageKeys';
import {
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
localStorageAdapter,
} from '../../infrastructure/persistence/localStorageAdapter';
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 {
config: VaultNavConfig;
visibleIds: VaultNavItemId[];
manageableIds: VaultNavItemId[];
hiddenSet: ReadonlySet<VaultNavItemId>;
isCustomized: boolean;
isHidden: (id: VaultNavItemId) => boolean;
canHide: (id: VaultNavItemId) => boolean;
setVisible: (id: VaultNavItemId, visible: boolean) => VaultNavConfig;
toggleVisible: (id: VaultNavItemId) => VaultNavConfig;
reorder: (
draggedId: VaultNavItemId,
targetId: VaultNavItemId,
position?: VaultNavDropPosition,
) => VaultNavConfig;
move: (
id: VaultNavItemId,
direction: 'up' | 'down',
scopeIds?: readonly VaultNavItemId[],
) => VaultNavConfig;
reset: () => VaultNavConfig;
}
function readStoredVaultNavConfig(
activePluginIds: readonly PluginVaultNavId[],
pruneMissingPlugins: boolean,
): VaultNavConfig {
try {
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
} catch {
return resetVaultNavConfig(activePluginIds);
}
}
function writeStoredVaultNavConfig(config: VaultNavConfig): void {
try {
localStorageAdapter.write(STORAGE_KEY_VAULT_NAV_CONFIG, config);
} catch {
// Best effort; in-memory state still applies for the current session.
}
}
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 && pluginsAvailable;
const [config, setConfig] = useState<VaultNavConfig>(() =>
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
);
const configRef = useRef<VaultNavConfig>(config);
configRef.current = config;
// Reconcile when active plugin list changes or cold-start loading finishes.
// Kept strictly outside React state updaters so storage writes and sync events
// never execute re-entrantly during rendering or StrictMode double-invocations.
useEffect(() => {
const current = configRef.current;
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
pruneMissingPlugins,
});
if (!areVaultNavConfigsEqual(current, reconciled)) {
configRef.current = reconciled;
setConfig(reconciled);
}
if (pruneMissingPlugins) {
try {
const rawStored = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
if (rawStored != null) {
const normalizedStored = normalizeVaultNavConfig(rawStored, stablePluginIds, {
pruneMissingPlugins: false,
});
if (!areVaultNavConfigsEqual(normalizedStored, reconciled)) {
writeStoredVaultNavConfig(reconciled);
}
}
} catch {
// Ignore storage read errors.
}
}
}, [pruneMissingPlugins, stablePluginIds]);
// Cross-window and adapter sync.
useEffect(() => {
const sync = (event: Event) => {
if (event instanceof StorageEvent && event.key !== STORAGE_KEY_VAULT_NAV_CONFIG) {
return;
}
if (
event instanceof CustomEvent
&& event.detail?.key !== STORAGE_KEY_VAULT_NAV_CONFIG
) {
return;
}
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
if (!areVaultNavConfigsEqual(configRef.current, next)) {
configRef.current = next;
setConfig(next);
}
};
window.addEventListener('storage', sync);
window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
return () => {
window.removeEventListener('storage', sync);
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
};
}, [pruneMissingPlugins, stablePluginIds]);
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
if (areVaultNavConfigsEqual(configRef.current, next)) {
return configRef.current;
}
configRef.current = next;
setConfig(next);
writeStoredVaultNavConfig(next);
return next;
}, []);
const setVisible = useCallback(
(id: VaultNavItemId, visible: boolean): VaultNavConfig =>
commit(setVaultNavItemVisibility(configRef.current, id, visible, stablePluginIds)),
[commit, stablePluginIds],
);
const toggleVisible = useCallback(
(id: VaultNavItemId): VaultNavConfig =>
commit(toggleVaultNavItemVisibility(configRef.current, id, stablePluginIds)),
[commit, stablePluginIds],
);
const reorder = useCallback(
(
draggedId: VaultNavItemId,
targetId: VaultNavItemId,
position: VaultNavDropPosition = 'before',
): VaultNavConfig =>
commit(reorderVaultNavItems(configRef.current, draggedId, targetId, position)),
[commit],
);
const move = useCallback(
(
id: VaultNavItemId,
direction: 'up' | 'down',
scopeIds?: readonly VaultNavItemId[],
): VaultNavConfig =>
commit(moveVaultNavItem(configRef.current, id, direction, scopeIds)),
[commit],
);
const reset = useCallback((): VaultNavConfig => {
const next = resetVaultNavConfig(stablePluginIds);
configRef.current = next;
setConfig(next);
writeStoredVaultNavConfig(next);
return next;
}, [stablePluginIds]);
const visibleIds = useMemo(
() => getVisibleVaultNavIds(config, stablePluginIds),
[config, stablePluginIds],
);
const manageableIds = useMemo(
() => getManageableVaultNavIds(config, stablePluginIds),
[config, stablePluginIds],
);
const hiddenSet = useMemo(
() => new Set<VaultNavItemId>(config.hidden),
[config.hidden],
);
const isCustomized = useMemo(
() => isCustomVaultNavConfig(config, stablePluginIds),
[config, stablePluginIds],
);
const isHidden = useCallback(
(id: VaultNavItemId) => hiddenSet.has(id),
[hiddenSet],
);
const canHide = useCallback(
(id: VaultNavItemId) => canHideVaultNavItem(config, id, stablePluginIds),
[config, stablePluginIds],
);
return useMemo(
() => ({
config,
visibleIds,
manageableIds,
hiddenSet,
isCustomized,
isHidden,
canHide,
setVisible,
toggleVisible,
reorder,
move,
reset,
}),
[
canHide,
config,
hiddenSet,
isCustomized,
isHidden,
manageableIds,
move,
reorder,
reset,
setVisible,
toggleVisible,
visibleIds,
],
);
}
+24 -15
View File
@@ -12,6 +12,7 @@ import { retainLocalHostLastConnectedAt } from "../../domain/sync";
import { sanitizeGroupConfig } from "../../domain/groupConfig";
import { normalizeKnownHosts } from "../../domain/knownHosts";
import { normalizeNoteGroups, normalizeVaultNotes } from "../../domain/notes";
import { getConnectionLogMediaIds } from "../../domain/remoteDesktopRecording";
import {
applyPluginImporterDestination,
mergePluginImporterDrafts,
@@ -634,16 +635,18 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
}
const remainingRecordingIds = new Set<string>();
for (const log of next) {
if (log.recordingId) remainingRecordingIds.add(log.recordingId);
for (const mediaId of getConnectionLogMediaIds(log)) {
remainingRecordingIds.add(mediaId);
}
}
const removedRecordingIds: string[] = [];
for (const log of prev) {
if (
!nextIds.has(log.id)
&& log.recordingId
&& !remainingRecordingIds.has(log.recordingId)
) {
removedRecordingIds.push(log.recordingId);
if (!nextIds.has(log.id)) {
for (const mediaId of getConnectionLogMediaIds(log)) {
if (!remainingRecordingIds.has(mediaId)) {
removedRecordingIds.push(mediaId);
}
}
}
}
if (removedRecordingIds.length > 0) {
@@ -1586,19 +1589,25 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
// One-time startup GC to sweep orphaned / expired / over-quota remote desktop recordings
// while preserving all bookmarked/saved connection log recordings.
// CRITICAL: Must wait for `isInitialized` so `connectionLogsRef.current` has been hydrated
// from storage; running before boot hydration would pass `referencedIds: []` and wipe files!
const hasRunRecordingStartupGcRef = useRef(false);
useEffect(() => {
if (!syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
if (!isInitialized || !syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
hasRunRecordingStartupGcRef.current = true;
const bridge = netcattyBridge.get();
if (!bridge?.remoteDesktopRecordings?.runGc) return;
const logs = connectionLogsRef.current;
const referencedIds = logs
.map((log) => log.recordingId)
.filter((id): id is string => typeof id === "string" && id.length > 0);
const protectedIds = logs
.filter((log) => log.saved && typeof log.recordingId === "string" && log.recordingId.length > 0)
.map((log) => log.recordingId as string);
const referencedSet = new Set<string>();
const protectedSet = new Set<string>();
for (const log of logs) {
for (const mediaId of getConnectionLogMediaIds(log)) {
referencedSet.add(mediaId);
if (log.saved) protectedSet.add(mediaId);
}
}
const referencedIds = Array.from(referencedSet);
const protectedIds = Array.from(protectedSet);
const storedMaxMb = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
const maxMb = storedMaxMb != null && storedMaxMb >= 64 ? storedMaxMb : 1024;
const storedRetention = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
@@ -1611,7 +1620,7 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
protectedIds,
})
.catch(() => {});
}, [syncConnectionLogTerminalData]);
}, [isInitialized, syncConnectionLogTerminalData]);
useLayoutEffect(() => {
registerConnectionLogsActions({
@@ -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"
+112 -3
View File
@@ -1,6 +1,10 @@
import React, { type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Undo2, X } from 'lucide-react';
import React, { useState, type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Sparkles, Undo2, Wrench, X } from 'lucide-react';
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
import type {
PluginAISidebarPrompt,
PluginAISidebarTurnContext,
} from '../infrastructure/ai/pluginAiSidebarTypes';
import type { Host, VaultNote } from '../types';
import type { UserSkillOption } from './ai/userSkillsState';
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
@@ -55,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;
@@ -135,6 +140,11 @@ interface AIChatPanelContentProps {
parked?: boolean;
/** Disable header transitions while send preflight is in flight. */
sending?: boolean;
/** Contextual plugin view metadata & registered tools injected into Catty Agent. */
pluginContext?: PluginAISidebarTurnContext | null;
pluginSuggestedPrompts?: readonly PluginAISidebarPrompt[];
onClosePanel?: () => void;
borderlessChrome?: boolean;
}
export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
@@ -162,6 +172,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
activeCompaction = null,
contextUsage = null,
inputValue,
inputValueRevision,
setInputValue,
handleSend,
handleSendQuickPrompt,
@@ -224,7 +235,12 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
onOpenVaultSection,
parked = false,
sending = false,
pluginContext = null,
pluginSuggestedPrompts,
onClosePanel,
borderlessChrome = false,
}) => {
const [showPluginTools, setShowPluginTools] = useState(false);
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
const mentionHosts = React.useMemo(
() => terminalSessions.map((session) => ({
@@ -269,7 +285,9 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Header')}>
<div className={cn(
TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS,
'px-2 flex items-center justify-between border-b border-border/50',
borderlessChrome
? 'px-2.5 flex items-center justify-between'
: 'px-2 flex items-center justify-between border-b border-border/50',
)}>
<AgentSelector
currentAgentId={currentAgentId}
@@ -334,11 +352,79 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
</TooltipTrigger>
<TooltipContent>{t('ai.chat.newChat')}</TooltipContent>
</Tooltip>
{onClosePanel && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 rounded-md text-muted-foreground/62 hover:bg-white/[0.05] hover:text-foreground"
aria-label={t('common.close')}
onClick={onClosePanel}
>
<X size={13} />
</Button>
</TooltipTrigger>
<TooltipContent>{t('common.close')}</TooltipContent>
</Tooltip>
)}
</div>
</div>
</React.Profiler>
)}
{/* ── Borderless Plugin Context Strip ── */}
{!parked && pluginContext && !showHistory && (
<div
data-section="plugin-ai-context-strip"
className="shrink-0 px-3 pt-2 pb-1"
>
<div className="rounded-xl bg-muted/30 dark:bg-white/[0.035] px-2.5 py-2">
<div className="flex items-center justify-between gap-2 min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
<Sparkles size={12} className="shrink-0 text-primary/80" />
<span className="truncate text-[12px] font-medium text-foreground/90">
{pluginContext.title || pluginContext.pluginName}
</span>
</div>
{pluginContext.tools.length > 0 && (
<button
type="button"
onClick={() => setShowPluginTools((prev) => !prev)}
className={cn(
'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-medium transition-colors cursor-pointer',
showPluginTools
? 'bg-primary/15 text-primary'
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
)}
>
<Wrench size={10} />
<span>{pluginContext.tools.length} tools</span>
</button>
)}
</div>
{pluginContext.subtitle && (
<p className="mt-0.5 truncate text-[11px] text-muted-foreground/75">
{pluginContext.subtitle}
</p>
)}
{showPluginTools && pluginContext.tools.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1 pt-1.5 border-t border-border/20">
{pluginContext.tools.map((tool) => (
<span
key={tool.qualifiedName}
title={tool.description}
className="inline-flex items-center gap-1 rounded-md bg-background/65 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground"
>
<span>{tool.name}</span>
</span>
))}
</div>
)}
</div>
</div>
)}
{/* ── Main content ── */}
{!parked && showHistory && !hideHistory ? (
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.History')}>
@@ -376,6 +462,28 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
</React.Profiler>
)}
{/* Borderless Plugin Starter Prompt Chips (when chat is empty) */}
{!parked && messages.length === 0 && pluginSuggestedPrompts && pluginSuggestedPrompts.length > 0 && (
<div
data-section="plugin-ai-suggested-prompts"
className="shrink-0 px-3 pb-2"
>
<div className="flex flex-wrap gap-1.5">
{pluginSuggestedPrompts.map((item, idx) => (
<button
key={`${item.label}-${idx}`}
type="button"
disabled={sending || isStreaming || !canSendCurrentAgent}
onClick={() => handleSend(item.prompt)}
className="rounded-lg bg-muted/35 dark:bg-white/[0.045] hover:bg-muted/65 dark:hover:bg-white/[0.09] px-2.5 py-1.5 text-left text-[11.5px] leading-snug text-foreground/80 hover:text-foreground transition-colors cursor-pointer disabled:pointer-events-none disabled:opacity-45"
>
{item.label}
</button>
))}
</div>
</div>
)}
{/* Recent sessions (Zed-style, shown when no messages) */}
{!parked && messages.length === 0 && historySessions.length > 0 && !hideRecent && (
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Recent')}>
@@ -462,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">
+123 -54
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,
@@ -346,6 +353,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onOpenVaultHost,
onOpenVaultSnippet,
onOpenVaultSection,
pluginContext = null,
pluginSuggestedPrompts,
pendingPluginPrompt = null,
onPendingPluginPromptConsumed,
onClosePanel,
borderlessChrome = false,
}) => {
const { t } = useI18n();
const scopeKey = `${scopeType}:${scopeTargetId ?? ''}`;
@@ -622,7 +635,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const liveTargets = new Set(liveScopeTargetIds ?? workspaceMemberTerminalIds ?? []);
for (const workspace of workspaces) liveTargets.add(workspace.id);
liveTargets.add(scopeTargetId);
if (canRebindChat(session, liveTargets)) {
if (canRebindChat(session, liveTargets) && (scopeType === 'terminal' || scopeType === 'workspace')) {
// Same race as the manager rebind: stop any in-flight turn first so the
// scope rewrite never happens under a live stream.
await stopActiveTurnBeforeScopeRebind(target.sessionId, {
@@ -817,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 }) => {
@@ -1032,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;
@@ -1674,20 +1683,12 @@ 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';
type: 'terminal' | 'workspace' | 'global';
targetId?: string;
label?: string;
}): ExecutorContext => {
@@ -1869,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() });
@@ -1977,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,
@@ -1999,11 +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);
@@ -2015,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,
@@ -2024,6 +2036,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
clearScopeDraft, showScopeSessionView, setActiveSessionId,
flushDraftText, currentAgentConfig, buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog, collectCustomModelIds,
pluginContext,
]);
const handleCompact = useCallback(async () => {
@@ -2074,6 +2087,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
autoTitleSession: () => {},
selectedUserSkillSlugs: [],
forceCompaction: true,
pluginContext,
},
);
} finally {
@@ -2096,6 +2110,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
selectedCattyThinking,
globalPermissionMode,
isStreaming,
pluginContext,
scopeKey,
scopeLabel,
scopeTargetId,
@@ -2318,7 +2333,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
&& session.scope.type === scopeType
&& session.scope.targetId === scopeTargetId,
);
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope) {
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope || scopeType === 'global') {
handleSelectSession(sessionId);
return;
}
@@ -2420,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) {
@@ -2435,24 +2467,30 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}, [exportSessionsBackup, t]);
const globalManagerNode = useMemo(() => (
<GlobalAIChatSessionManager
sessions={sessions}
activeSessionIdMap={activeSessionIdMap}
currentScopeType={scopeType}
currentScopeTargetId={scopeTargetId}
currentScopeHostIds={scopeHostIds}
workspaces={workspaces}
terminalInfos={managerTerminalInfos}
hosts={hosts}
externalAgents={externalAgents}
rebindTargets={managerRebindTargets}
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
onRebind={handleManagerRebind}
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onExport={handleManagerExport}
/>
scopeType === 'global'
? undefined
: (
<GlobalAIChatSessionManager
sessions={sessions}
activeSessionIdMap={activeSessionIdMap}
currentScopeType={scopeType}
currentScopeTargetId={scopeTargetId}
currentScopeHostIds={scopeHostIds}
workspaces={workspaces}
terminalInfos={managerTerminalInfos}
hosts={hosts}
externalAgents={externalAgents}
rebindTargets={managerRebindTargets}
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
onRebind={handleManagerRebind}
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
onExport={handleManagerExport}
/>
)
), [
sessions,
activeSessionIdMap,
@@ -2469,6 +2507,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
handleManagerRebind,
handleRenameSession,
handleManagerDelete,
handleManagerDeleteMany,
handleManagerRegenerateTitle,
handleManagerExport,
onFocusAIScopeTarget,
]);
@@ -2486,6 +2526,22 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
setShowHistory(false);
}, [ensureScopeDraft, showScopeDraftView, updateScopeDraft]);
const consumedPluginPromptIdRef = useRef<number | null>(null);
useEffect(() => {
if (!pendingPluginPrompt) return;
if (consumedPluginPromptIdRef.current === pendingPluginPrompt.id) return;
consumedPluginPromptIdRef.current = pendingPluginPrompt.id;
onPendingPluginPromptConsumed?.(pendingPluginPrompt.id);
const trimmedPrompt = pendingPluginPrompt.prompt.trim();
if (!trimmedPrompt) return;
setShowHistory(false);
if (pendingPluginPrompt.autoSend && !isStreaming) {
void handleSend(trimmedPrompt);
} else {
setInputValue(trimmedPrompt);
}
}, [handleSend, isStreaming, onPendingPluginPromptConsumed, pendingPluginPrompt, setInputValue]);
// Hidden retained panels keep the composer mounted (parent is `hidden` +
// inert) so reopen does not remount ChatInput. Skip the message list.
return (
@@ -2526,6 +2582,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
contextUsage={contextUsage}
canCompact={canCompact}
inputValue={inputValue}
inputValueRevision={composerValueRevision}
setInputValue={setInputValue}
handleSend={handleSend}
handleSendQuickPrompt={handleSendQuickPrompt}
@@ -2609,6 +2666,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onOpenVaultHost={onOpenVaultHost}
onOpenVaultSnippet={onOpenVaultSnippet}
onOpenVaultSection={onOpenVaultSection}
pluginContext={pluginContext}
pluginSuggestedPrompts={pluginSuggestedPrompts}
onClosePanel={onClosePanel}
borderlessChrome={borderlessChrome}
/>
</div>
</React.Profiler>
@@ -2632,6 +2693,8 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
'createSession',
'deleteSession',
'updateSessionTitle',
'autoTitleSession',
'regenerateSessionTitle',
'rebindSessionScope',
'exportSessionsBackup',
'importSessionsBackup',
@@ -2698,6 +2761,12 @@ export function aiChatSidePanelPropsAreEqual(
if (prev.onOpenVaultSnippet !== next.onOpenVaultSnippet) return false;
if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false;
if (prev.onFocusAIScopeTarget !== next.onFocusAIScopeTarget) return false;
if (prev.pluginContext !== next.pluginContext) return false;
if (prev.pluginSuggestedPrompts !== next.pluginSuggestedPrompts) return false;
if (prev.pendingPluginPrompt !== next.pendingPluginPrompt) return false;
if (prev.onPendingPluginPromptConsumed !== next.onPendingPluginPromptConsumed) return false;
if (prev.onClosePanel !== next.onClosePanel) return false;
if (prev.borderlessChrome !== next.borderlessChrome) return false;
const scopeKey = `${prev.scopeType}:${prev.scopeTargetId ?? ''}`;
if (
+14 -3
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. */
@@ -104,7 +107,7 @@ export interface AIChatSidePanelProps {
quickMessages?: AIQuickMessage[];
// Context
scopeType: 'terminal' | 'workspace';
scopeType: 'terminal' | 'workspace' | 'global';
scopeTargetId?: string;
scopeHostIds?: string[];
scopeLabel?: string;
@@ -143,7 +146,7 @@ export interface AIChatSidePanelProps {
connected: boolean;
}>;
resolveExecutorContext?: (scope: {
type: 'terminal' | 'workspace';
type: 'terminal' | 'workspace' | 'global';
targetId?: string;
label?: string;
}) => ExecutorContext;
@@ -151,6 +154,14 @@ export interface AIChatSidePanelProps {
// Visibility
isVisible?: boolean;
// Plugin contextual sidebar integration (native Catty Agent + plugin tools)
pluginContext?: import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
pluginSuggestedPrompts?: readonly import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarPrompt[];
pendingPluginPrompt?: { id: number; prompt: string; autoSend?: boolean } | null;
onPendingPluginPromptConsumed?: (id: number) => void;
onClosePanel?: () => void;
borderlessChrome?: boolean;
// Vault artifact navigation (from AI chat tool results)
notes?: VaultNote[];
hosts?: Host[];
+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));
+60
View File
@@ -81,4 +81,64 @@ test("ConnectionLogsManager renders RDP/VNC icons and compact recording pill whe
assert.match(markup, /vnc, 10\.0\.0\.20/);
assert.match(markup, /bg-blue-500\/15 text-blue-600/);
assert.match(markup, /bg-teal-500\/15 text-teal-600/);
assert.match(markup, /data-testid="logs-filter-bar"/);
assert.match(markup, /data-logs-filter="remoteDesktop"/);
assert.match(markup, /data-logs-filter="recorded"/);
});
test("ConnectionLogsManager renders multi-clip count and remote desktop resolution metadata", () => {
const logs: ConnectionLog[] = [
{
id: "log-multi-rec",
hostId: "h-1",
hostLabel: "Windows Multi",
hostname: "10.0.0.10",
username: "Administrator",
protocol: "rdp",
startTime: 1_700_000_000_000,
endTime: 1_700_000_200_000,
localUsername: "alice",
localHostname: "macbook",
saved: false,
recordings: [
{
id: "11111111-1111-4111-8111-111111111111",
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_040_000,
durationMs: 30_000,
bytes: 1_048_576,
mimeType: "video/webm",
hasAudio: false,
},
{
id: "22222222-2222-4222-8222-222222222222",
startedAt: 1_700_000_060_000,
endedAt: 1_700_000_120_000,
durationMs: 60_000,
bytes: 2_097_152,
mimeType: "video/webm",
hasAudio: true,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
securityLabel: "TLS / NLA",
},
},
];
const markup = renderWithI18n(
React.createElement(ConnectionLogsManager, {
logs,
hosts: [],
onToggleSaved: () => {},
onDelete: () => {},
onClearUnsaved: () => {},
onOpenLogView: () => {},
}),
);
assert.match(markup, /2 clips · 01:30 · 3 MB/);
assert.match(markup, /1920×1080/);
assert.match(markup, /TLS \/ NLA/);
});
+116 -21
View File
@@ -2,6 +2,7 @@ import {
Bookmark,
ChevronDown,
CircleUserRound,
Monitor,
Server,
Terminal,
Trash2,
@@ -11,7 +12,8 @@ import {
import React, { memo, useCallback, useMemo, useState } from "react";
import { useI18n } from "../application/i18n/I18nProvider";
import { resolveHostIconAppearance } from "../domain/hostIcon";
import { isRdpProtocol, isVncProtocol } from "../domain/remoteDesktop";
import { isRdpProtocol, isRemoteDesktopProtocol, isVncProtocol } from "../domain/remoteDesktop";
import { getConnectionLogRecordingSummary } from "../domain/remoteDesktopRecording";
import { cn } from "../lib/utils";
import { ConnectionLog, Host } from "../types";
import { DistroAvatar } from "./DistroAvatar";
@@ -28,6 +30,8 @@ interface ConnectionLogsManagerProps {
onOpenLogView: (log: ConnectionLog) => void;
}
export type ConnectionLogFilter = "all" | "terminal" | "remoteDesktop" | "recorded";
export function formatRecordingDuration(durationMs?: number): string {
if (!durationMs || !Number.isFinite(durationMs) || durationMs <= 0) {
return "00:00";
@@ -110,8 +114,28 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
iconColorCustom: log.hostIconColorCustom,
});
const hasPersistedHostIcon = !isLocal && !isSerial && !isRemoteDesktop && (!!log.hostDistro || !!customHostIcon);
const recordingSizeText = formatRecordingBytes(log.recordingBytes);
const recordingDurationText = formatRecordingDuration(log.recordingDurationMs);
const recordingSummary = getConnectionLogRecordingSummary(log);
const recordingSizeText = formatRecordingBytes(recordingSummary.totalBytes);
const recordingDurationText = formatRecordingDuration(recordingSummary.totalDurationMs);
const resolutionText = log.remoteDesktopMeta?.resolution
? `${log.remoteDesktopMeta.resolution.width}\u00d7${log.remoteDesktopMeta.resolution.height}`
: "";
const subtitleParts: string[] = [];
if (isLocal) {
subtitleParts.push("local");
} else if (isSerial) {
subtitleParts.push(`serial, ${log.hostname}`);
} else if (log.username) {
subtitleParts.push(`${log.protocol}, ${log.username}`);
} else {
subtitleParts.push(`${log.protocol}, ${log.hostname}`);
}
if (isRemoteDesktop && resolutionText) {
subtitleParts.push(resolutionText);
}
if (isRemoteDesktop && log.remoteDesktopMeta?.securityLabel) {
subtitleParts.push(log.remoteDesktopMeta.securityLabel);
}
return (
<div
@@ -185,13 +209,16 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
<div className="text-sm font-medium truncate">
{isLocal ? t("logs.localTerminal") : log.hostLabel}
</div>
{log.recordingId && (
{recordingSummary.primaryClip && (
<span
data-recording-badge={log.recordingId}
data-recording-badge={recordingSummary.primaryClip.id}
className="inline-flex items-center gap-1 rounded-md border border-primary/25 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-primary shrink-0"
>
<Video size={12} />
<span>
{recordingSummary.clipCount > 1
? `${t("logs.recording.clipsCount", { count: recordingSummary.clipCount })} · `
: ""}
{recordingDurationText}
{recordingSizeText ? ` · ${recordingSizeText}` : ""}
</span>
@@ -199,13 +226,7 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
)}
</div>
<div className="text-xs text-muted-foreground truncate">
{isLocal
? "local"
: isSerial
? `serial, ${log.hostname}`
: log.username
? `${log.protocol}, ${log.username}`
: `${log.protocol}, ${log.hostname}`}
{subtitleParts.join(" · ")}
</div>
</div>
</div>
@@ -264,20 +285,52 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
const INITIAL_RENDER_LIMIT = 30;
const LOAD_MORE_COUNT = 30;
// Track how many items to show
const [filter, setFilter] = useState<ConnectionLogFilter>("all");
const [renderLimit, setRenderLimit] = useState(INITIAL_RENDER_LIMIT);
// Sort logs by newest first
const filteredLogs = useMemo(() => {
return [...logs].sort((a, b) => b.startTime - a.startTime);
const filterCounts = useMemo(() => {
let terminal = 0;
let remoteDesktop = 0;
let recorded = 0;
for (const log of logs) {
if (isRemoteDesktopProtocol(log.protocol)) {
remoteDesktop += 1;
} else {
terminal += 1;
}
if (getConnectionLogRecordingSummary(log).clipCount > 0) {
recorded += 1;
}
}
return { all: logs.length, terminal, remoteDesktop, recorded };
}, [logs]);
const showFilterBar = logs.length > 0 && (filterCounts.remoteDesktop > 0 || filterCounts.recorded > 0);
const effectiveFilter: ConnectionLogFilter = showFilterBar ? filter : "all";
// Filter and sort logs by newest first
const filteredLogs = useMemo(() => {
const subset = effectiveFilter === "all"
? logs
: logs.filter((log) => {
if (effectiveFilter === "remoteDesktop") return isRemoteDesktopProtocol(log.protocol);
if (effectiveFilter === "terminal") return !isRemoteDesktopProtocol(log.protocol);
return getConnectionLogRecordingSummary(log).clipCount > 0;
});
return [...subset].sort((a, b) => b.startTime - a.startTime);
}, [effectiveFilter, logs]);
const displayedLogs = useMemo(() => {
return filteredLogs.slice(0, renderLimit);
}, [filteredLogs, renderLimit]);
const hasMore = filteredLogs.length > renderLimit;
const handleChangeFilter = useCallback((next: ConnectionLogFilter) => {
setFilter(next);
setRenderLimit(INITIAL_RENDER_LIMIT);
}, []);
const handleLoadMore = useCallback(() => {
setRenderLimit(prev => prev + LOAD_MORE_COUNT);
}, []);
@@ -292,7 +345,6 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
[onDelete],
);
// Rendered items
const renderedItems = useMemo(() => {
return displayedLogs.map((log) => (
<LogItem
@@ -307,9 +359,46 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
return (
<div className="h-full flex flex-col">
{/* Protocol / Recording Filter Bar */}
{showFilterBar && (
<div
data-testid="logs-filter-bar"
className="flex flex-wrap items-center gap-1.5 px-4 py-2 border-b border-border/30 bg-background shrink-0"
>
{(
[
{ id: "all" as const, label: t("logs.filter.all"), count: filterCounts.all, icon: null },
{ id: "terminal" as const, label: t("logs.filter.terminal"), count: filterCounts.terminal, icon: <Terminal size={12} /> },
{ id: "remoteDesktop" as const, label: t("logs.filter.remoteDesktop"), count: filterCounts.remoteDesktop, icon: <Monitor size={12} /> },
{ id: "recorded" as const, label: t("logs.filter.recorded"), count: filterCounts.recorded, icon: <Video size={12} /> },
]
).map((item) => {
const active = effectiveFilter === item.id;
return (
<button
key={item.id}
type="button"
data-logs-filter={item.id}
onClick={() => handleChangeFilter(item.id)}
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
active
? "bg-primary/12 text-primary border border-primary/25"
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
)}
>
{item.icon}
<span>{item.label}</span>
<span className="font-mono text-[10px] opacity-75 tabular-nums">{item.count}</span>
</button>
);
})}
</div>
)}
{/* Table Header */}
{displayedLogs.length > 0 && (
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30">
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30 shrink-0">
<div className="w-32 shrink-0 flex items-center gap-1">
{t("logs.table.date")}
<ChevronDown size={12} />
@@ -329,13 +418,19 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
{displayedLogs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<div className="h-16 w-16 rounded-2xl bg-secondary/80 flex items-center justify-center mb-4">
<Terminal size={32} className="opacity-60" />
{effectiveFilter === "recorded" ? (
<Video size={32} className="opacity-60" />
) : effectiveFilter === "remoteDesktop" ? (
<Monitor size={32} className="opacity-60" />
) : (
<Terminal size={32} className="opacity-60" />
)}
</div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{t("logs.empty.title")}
{effectiveFilter === "all" ? t("logs.empty.title") : t("logs.filter.emptyTitle")}
</h3>
<p className="text-sm text-center max-w-sm">
{t("logs.empty.desc")}
{effectiveFilter === "all" ? t("logs.empty.desc") : t("logs.filter.emptyDesc")}
</p>
</div>
) : (
@@ -0,0 +1,167 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { GroupConfig } from "../types.ts";
import GroupDetailsPanel from "./GroupDetailsPanel.tsx";
import { ProxyPanel } from "./host-details/ProxyPanel.tsx";
import { AsidePanel } from "./ui/aside-panel.tsx";
import { Badge } from "./ui/badge.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
async function mountGroupDetails(config: GroupConfig | undefined) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let saved: GroupConfig | undefined;
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath={config?.path ?? "corp/local"}
config={config}
availableKeys={[]}
identities={[]}
proxyProfiles={[]}
allHosts={[]}
groups={["corp", "corp/local"]}
groupConfigs={[
{ path: "corp", proxyConfig: { type: "http", host: "corp-proxy.example.com", port: 8080 } },
...(config ? [config] : []),
]}
terminalThemeId="default"
terminalFontSize={14}
onSave={(value) => { saved = value; }}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const cleanup = async () => {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
environment.IS_REACT_ACT_ENVIRONMENT = previous;
};
return {
get root() {
return renderer!.root;
},
getSaved: () => saved,
cleanup,
};
}
const findProxySummaryButton = (root: ReactTestRenderer["root"]) =>
root.findAllByType("button").find((button) => {
const badges = button.findAllByType(Badge);
return badges.some((badge) =>
badge.props.children === "HTTP" || badge.props.children === "Direct (no proxy)",
);
});
test("GroupDetailsPanel lets a child group choose Direct (no proxy) and persists directProxy", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
protocol: "ssh",
proxyConfig: { type: "http", host: "old-proxy.example.com", port: 8080 },
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "Proxy summary button should be rendered");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(typeof proxyPanel.props.onSelectDirectProxy, "function");
assert.equal(proxyPanel.props.directProxy, undefined);
await act(async () => {
proxyPanel.props.onSelectDirectProxy!();
});
const updatedPanel = harness.root.findByType(ProxyPanel);
assert.equal(updatedPanel.props.directProxy, true);
assert.equal(updatedPanel.props.proxyConfig, undefined);
assert.equal(updatedPanel.props.selectedProxyProfileId, undefined);
await act(async () => {
updatedPanel.props.onBack();
});
const proxyButtonAfter = findProxySummaryButton(harness.root);
assert.ok(proxyButtonAfter);
const badge = proxyButtonAfter.findByType(Badge);
assert.equal(badge.props.children, "Direct (no proxy)");
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, true);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
test("GroupDetailsPanel clears directProxy when removed in ProxyPanel so parent proxy applies again", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
directProxy: true,
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "SSH section and Proxy summary should open automatically for directProxy groups");
assert.equal(proxyButton.findByType(Badge).props.children, "Direct (no proxy)");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(proxyPanel.props.directProxy, true);
await act(async () => {
proxyPanel.props.onClearProxy();
});
assert.equal(harness.root.findByType(ProxyPanel).props.directProxy, undefined);
await act(async () => {
harness.root.findByType(ProxyPanel).props.onBack();
});
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, undefined);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
+310 -1
View File
@@ -1,14 +1,27 @@
import test from "node:test";
import assert from "node:assert/strict";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import {
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { GroupConfig, Identity } from "../types.ts";
import GroupDetailsPanel, {
hasGroupRdpFields,
hasGroupSshFields,
hasGroupTelnetFields,
hasGroupVncFields,
includeMissingIdentityOption,
resolveGroupFormIdentityId,
selectGroupRdpIdentity,
selectGroupSshIdentity,
selectGroupTelnetIdentity,
selectGroupVncIdentity,
} from "./GroupDetailsPanel.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
import { AsidePanelFooter } from "./ui/aside-panel.tsx";
import { Button } from "./ui/button.tsx";
import { Input } from "./ui/input.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
test("GroupDetailsPanel treats an empty SSH identity as an explicit setting", () => {
assert.equal(hasGroupSshFields({ identityId: "" }), true);
@@ -20,6 +33,11 @@ test("GroupDetailsPanel keeps the SSH section when X11 forwarding is set", () =>
assert.equal(hasGroupSshFields({ x11Forwarding: false }), true);
});
test("GroupDetailsPanel keeps the SSH section when directProxy is set", () => {
assert.equal(hasGroupSshFields({ directProxy: true }), true);
assert.equal(hasGroupSshFields({ directProxy: false }), false);
});
test("GroupDetailsPanel treats cleared telnet credentials as explicit settings", () => {
assert.equal(hasGroupTelnetFields({ telnetUsername: "" }), true);
assert.equal(hasGroupTelnetFields({ telnetPassword: "" }), true);
@@ -114,4 +132,295 @@ test("GroupDetailsPanel shows saved child manual credentials instead of a parent
),
undefined,
);
assert.equal(
resolveGroupFormIdentityId(
{ rdpConfig: { enabled: true, username: "child-rdp-user" } },
"parent-rdp-identity",
"rdp",
),
undefined,
);
assert.equal(
resolveGroupFormIdentityId(
{ vncConfig: { enabled: true, useHostCredentials: true } },
"parent-vnc-identity",
"vnc",
),
undefined,
);
});
test("GroupDetailsPanel detects RDP and VNC configs without falsely enabling SSH on RDP-only groups with proxy/chain", () => {
assert.equal(hasGroupRdpFields({ rdpConfig: { enabled: true } }), true);
assert.equal(hasGroupRdpFields({}), false);
assert.equal(hasGroupVncFields({ vncConfig: { enabled: true } }), true);
assert.equal(hasGroupVncFields({}), false);
// RDP-only group with proxy/chain stays RDP-only.
assert.equal(
hasGroupSshFields({
rdpConfig: { enabled: true, port: 3389 },
proxyProfileId: "corp-proxy",
hostChain: { hostIds: ["bastion-1"] },
}),
false,
);
// Legacy group with only proxy/chain still shows SSH enabled.
assert.equal(hasGroupSshFields({ proxyProfileId: "corp-proxy" }), true);
// Telnet-only group with startupCommand does not falsely enable SSH.
assert.equal(
hasGroupSshFields({ telnetEnabled: true, startupCommand: "enable" }),
false,
);
});
test("GroupDetailsPanel selects and clears RDP and VNC identities cleanly", () => {
const identity: Identity = {
id: "win-admin",
label: "Windows Admin",
username: "Administrator",
domain: "CORP",
authMethod: "password",
password: "secret",
created: 1,
};
const withRdp = selectGroupRdpIdentity({}, identity, identity.id);
assert.equal(withRdp.rdpConfig?.identityId, "win-admin");
assert.equal(withRdp.rdpConfig?.domain, "CORP");
assert.equal(withRdp.rdpConfig?.useHostCredentials, false);
const clearedRdp = selectGroupRdpIdentity({}, undefined, "", "parent-rdp-id");
assert.equal(clearedRdp.rdpConfig?.identityId, "");
const withVnc = selectGroupVncIdentity({}, identity, identity.id);
assert.equal(withVnc.vncConfig?.identityId, "win-admin");
assert.equal(withVnc.vncConfig?.useHostCredentials, false);
const clearedVnc = selectGroupVncIdentity({}, undefined, "", "parent-vnc-id");
assert.equal(clearedVnc.vncConfig?.identityId, "");
});
test("GroupDetailsPanel unifies 4-protocol tabs, adds RDP/VNC defaults, and saves via footer without plaintext passwords", async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let savedConfig: GroupConfig | undefined;
const createdIdentities: Identity[] = [];
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath="Windows"
config={undefined}
availableKeys={[]}
identities={[]}
onCreateIdentity={(identity) => createdIdentities.push(identity)}
allHosts={[]}
groups={["Windows"]}
terminalThemeId="default"
terminalFontSize={14}
layout="inline"
onSave={(value) => {
savedConfig = value;
}}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const protocolTabs = renderer!.root.findAll(
(node) => node.type === "button" && typeof node.props["data-group-protocol"] === "string",
);
assert.deepEqual(
protocolTabs.map((node) => node.props["data-group-protocol"]),
["ssh", "rdp", "vnc", "telnet"],
);
const collectText = (node: unknown): string => {
if (typeof node === "string") return node;
if (Array.isArray(node)) return node.map(collectText).join("");
if (node && typeof node === "object" && "children" in node) {
return collectText((node as { children: unknown }).children);
}
return "";
};
const buttonText = (btn: { children: unknown[] }) => collectText(btn.children);
// Switch to RDP tab and enable RDP
const rdpTab = protocolTabs.find((node) => node.props["data-group-protocol"] === "rdp")!;
await act(async () => {
rdpTab.props.onClick();
});
const addRdpBtn = renderer!.root.findAllByType(Button).find((btn) =>
buttonText(btn).includes("Add RDP"),
);
assert.ok(addRdpBtn, "expected Add RDP button when RDP is not enabled");
await act(async () => {
addRdpBtn.props.onClick();
});
// Set RDP port, domain, username, and password (password must become a Keychain identity)
const rdpPortInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "3389",
);
const rdpDomainInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "CORP (optional)",
);
const rdpUserInput = renderer!.root.findAllByType(Input).find(
(input) => typeof input.props.placeholder === "string" && input.props.placeholder.includes("DOMAIN"),
);
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(rdpPortInput && rdpDomainInput && rdpUserInput && rdpPasswordInput);
await act(async () => {
rdpPortInput.props.onChange({ target: { value: "13389" } });
rdpDomainInput.props.onChange({ target: { value: "CORP" } });
rdpUserInput.props.onChange({ target: { value: "admin" } });
rdpPasswordInput.props.onChange({ target: { value: "rdp-secret" } });
});
// Switch to VNC tab and enable VNC with :2 display port
const vncTab = renderer!.root.findAll(
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
)[0];
await act(async () => {
vncTab.props.onClick();
});
const addVncBtn = renderer!.root.findAllByType(Button).find((btn) =>
buttonText(btn).includes("Add VNC"),
);
assert.ok(addVncBtn, "expected Add VNC button when VNC is not enabled");
await act(async () => {
addVncBtn.props.onClick();
});
const vncPortInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "5900 or :0",
);
assert.ok(vncPortInput);
await act(async () => {
vncPortInput.props.onChange({ target: { value: ":2" } });
});
// Save via the unified AsidePanelFooter Save button
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
await act(async () => {
footerSaveBtn.props.onClick();
});
assert.ok(savedConfig, "expected GroupDetailsPanel footer save button to emit GroupConfig");
assert.equal(savedConfig.protocol, undefined, "SSH should remain disabled");
assert.equal(createdIdentities.length, 1);
assert.equal(createdIdentities[0].username, "admin");
assert.equal(createdIdentities[0].domain, "CORP");
assert.equal(createdIdentities[0].password, "rdp-secret");
assert.equal(savedConfig.rdpConfig?.enabled, true);
assert.equal(savedConfig.rdpConfig?.port, 13389);
assert.equal(savedConfig.rdpConfig?.domain, "CORP");
assert.equal(savedConfig.rdpConfig?.identityId, createdIdentities[0].id);
assert.equal("password" in (savedConfig.rdpConfig ?? {}), false);
assert.equal(savedConfig.vncConfig?.enabled, true);
assert.equal(savedConfig.vncConfig?.port, 5902);
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
test("GroupDetailsPanel preserves inherited parent RDP/VNC username and domain when creating a password-only identity", async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let savedConfig: GroupConfig | undefined;
const createdIdentities: Identity[] = [];
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath="Corp/EU"
config={{ path: "Corp/EU", rdpConfig: { enabled: true }, vncConfig: { enabled: true } }}
availableKeys={[]}
identities={[]}
onCreateIdentity={(identity) => createdIdentities.push(identity)}
allHosts={[]}
groups={["Corp", "Corp/EU"]}
groupConfigs={[
{
path: "Corp",
rdpConfig: { enabled: true, username: "corp-admin", domain: "CORP" },
vncConfig: { enabled: true, username: "corp-vnc" },
},
]}
terminalThemeId="default"
terminalFontSize={14}
layout="inline"
onSave={(value) => {
savedConfig = value;
}}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(rdpPasswordInput);
await act(async () => {
rdpPasswordInput.props.onChange({ target: { value: "eu-rdp-secret" } });
});
const vncTab = renderer!.root.findAll(
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
)[0];
await act(async () => {
vncTab.props.onClick();
});
const vncPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(vncPasswordInput);
await act(async () => {
vncPasswordInput.props.onChange({ target: { value: "eu-vnc-secret" } });
});
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
await act(async () => {
footerSaveBtn.props.onClick();
});
assert.ok(savedConfig);
assert.equal(createdIdentities.length, 2);
assert.equal(createdIdentities[0].username, "corp-admin");
assert.equal(createdIdentities[0].domain, "CORP");
assert.equal(createdIdentities[0].password, "eu-rdp-secret");
assert.equal(createdIdentities[1].username, "corp-vnc");
assert.equal(createdIdentities[1].password, "eu-vnc-secret");
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 475 files, more files were not shown because too many files have changed in this diff. Show more