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
312 changed files with 27691 additions and 1108 deletions

No files matched your search

+4
View File
@@ -46,6 +46,8 @@
<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" />
@@ -84,6 +86,8 @@ 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 トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
+4
View File
@@ -46,6 +46,8 @@
<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" />
@@ -86,6 +88,8 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
<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
+4
View File
@@ -46,6 +46,8 @@
<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" />
@@ -84,6 +86,8 @@
<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 隧道代理)呈现原生手感界面。
### ✨ 核心亮点
+4
View File
@@ -46,6 +46,8 @@
<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" />
@@ -84,6 +86,8 @@
<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 通道代理)呈現原生體驗。
### ✨ 核心亮點
@@ -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}
+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.',
+41
View File
@@ -431,6 +431,8 @@ export const enCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Show SFTP tab',
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
'settings.vault.removeTopTabsDragArea': 'Remove the top window-drag area',
'settings.vault.removeTopTabsDragAreaDesc': 'When enabled, remove the draggable space above the tabs so the top edge is available for clicks.',
'settings.vault.showHostTreeSidebarDesc': 'Display the host list sidebar and its top-bar toggle on terminal and editor tabs.',
'settings.vault.autoImportSystemKnownHosts': 'Auto-import system known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': 'When Vault loads, silently import entries from the OpenSSH known_hosts file. Turn this off to keep Netcatty known hosts separate; Scan System still imports on demand.',
@@ -1061,6 +1063,7 @@ Highlight the focused split pane:
'settings.shortcuts.binding.command-palette': 'Open Command Palette',
'settings.shortcuts.binding.quick-switch': 'Quick Switch',
'settings.shortcuts.binding.new-workspace': 'New Workspace',
'settings.shortcuts.binding.add-session-to-workspace': 'Add Session to Workspace',
'settings.shortcuts.binding.snippets': 'Open Snippets',
'settings.shortcuts.binding.broadcast': 'Switch the Broadcast Mode',
'settings.shortcuts.binding.toggle-side-panel': 'Toggle Side Panel',
@@ -1330,6 +1333,8 @@ 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:",
@@ -1496,5 +1501,41 @@ Highlight the focused split pane:
'plugins.hostActions.managedUnsupported': 'Managed SSH config changes require the Vault host editor.',
'plugins.hostActions.failed': 'The request expired, was revoked, or the host changed. Select the host again.',
'plugins.hostActions.selectionLimit': 'Select up to 50 current hosts.',
'settings.externalEditor.title': 'External Remote Editor',
'settings.externalEditor.desc': 'Open remote SSH projects and files directly in local editors such as Zed, VS Code, or Cursor.',
'settings.externalEditor.preferredEditor': 'Preferred editor',
'settings.externalEditor.preferredEditor.desc': 'Default local editor used for SFTP context menu actions and terminal open requests.',
'settings.externalEditor.executablePath': 'Editor executable',
'settings.externalEditor.executablePath.desc': 'Leave empty to auto-detect, or choose the local binary manually.',
'settings.externalEditor.executablePath.placeholder': 'Auto-detect executable path',
'settings.externalEditor.status.configured': 'Custom path',
'settings.externalEditor.status.detected': 'Auto-detected',
'settings.externalEditor.status.notFound': 'Not detected',
'settings.externalEditor.browse': 'Browse…',
'settings.externalEditor.resetPath': 'Reset to auto-detect',
'settings.externalEditor.redetect': 'Re-detect installed editors',
'settings.externalEditor.customArgs': 'Custom arguments',
'settings.externalEditor.customArgs.desc': 'Space-separated arguments (placeholders: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'SSH connection mode',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH Bridge reuses your active authenticated session without exposing vault keys or host lists.',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH Bridge (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'Direct OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty bridge rule',
'settings.externalEditor.sshBridge.desc': 'Adds a single static Host *.netcatty block to your OpenSSH config without writing any hostnames, keys, or passwords.',
'settings.externalEditor.sshBridge.install': 'Install bridge rule',
'settings.externalEditor.sshBridge.reinstall': 'Reinstall rule',
'settings.externalEditor.sshBridge.update': 'Update rule',
'settings.externalEditor.sshBridge.remove': 'Remove rule',
'settings.externalEditor.terminalRequests': 'Allow terminal open requests (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Let remote shells open paths in your configured local editor via commands like `zed .`.',
'settings.externalEditor.autoSetup': 'Enable remote editor commands for Netcatty sessions',
'settings.externalEditor.autoSetup.desc': 'Install `zed` / `ncedit` helpers into ~/.netcatty/bin and activate them in PATH for this Netcatty terminal session only, without modifying ~/.bashrc or ~/.zshrc (can also be toggled per host).',
'settings.externalEditor.defaultTrust': 'Default host trust',
'settings.externalEditor.defaultTrust.desc': 'Permission policy when an unrecognized remote host requests opening a local editor.',
'settings.externalEditor.trust.ask': 'Ask every time',
'settings.externalEditor.trust.allow': 'Always allow',
'settings.externalEditor.trust.deny': 'Always deny',
'settings.externalEditor.trustedHosts.host': 'Host',
'settings.externalEditor.trustedHosts.policy': 'Policy',
};
+17
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const enTerminalMessages: Messages = {
'terminal.directory.open': 'Current directory: {path}. Change directory',
'terminal.gitBranch.current': 'Git branch: {{value}}',
'terminal.gitBranch.detached': 'Detached HEAD: {{value}}',
'terminal.directory.unknown': 'Directory unknown',
'terminal.directory.search': 'Search child directories...',
'terminal.directory.directories': 'Directories',
@@ -16,6 +18,7 @@ export const enTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
'terminal.directory.cygwinIntegrationUnavailable': 'Waiting for Cygwin Bash to return to an idle prompt.',
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
'terminal.directory.busy': 'Wait for an empty shell prompt.',
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
@@ -469,6 +472,7 @@ export const enTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Before restore',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} keys, {snippets} snippets, {notes} notes',
'cloudSync.localBackups.aiCounts': '{sessions} AI chats, {settings} settings',
'cloudSync.localBackups.restore': 'Restore',
'cloudSync.localBackups.restoreSuccess': 'Local backup restored.',
'cloudSync.localBackups.restoreFailedTitle': 'Restore failed',
@@ -619,6 +623,10 @@ export const enTerminalMessages: Messages = {
'keychain.export.scriptPlaceholder': 'Export script...',
'keychain.export.missingCredentials':
'Host has no saved password or key. Please add password credentials to the host first.',
'keychain.export.missingPublicKey':
'This key has no public key. Open Edit, paste the public key, then try Export and Attach again.',
'keychain.export.missingPublicKeyNote':
'This key has no public key. Paste it in the key editor before exporting.',
'keychain.export.successTitle': 'Export Successful',
'keychain.export.successMessage': 'Public key exported and attached to {host}',
'keychain.export.failedTitle': 'Export Failed',
@@ -695,6 +703,7 @@ export const enTerminalMessages: Messages = {
'tabs.logPrefix': 'Log:',
'tabs.logLocal': 'Local',
'tabs.copyTab': 'Copy Tab',
'tabs.addSessionToWorkspace': 'Add Session to Workspace',
'tabs.duplicateSession': 'Duplicate Session',
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
@@ -988,4 +997,12 @@ export const enTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'Show in every host’s browser.',
'terminal.browser.downloadLocation': 'Saved to your Downloads folder',
'terminal.browser.saveAs': 'Save as…',
'terminal.externalEditor.opened': 'Opened {path} in {editor}',
'terminal.externalEditor.failed': 'Failed to open in {editor}',
'terminal.externalEditor.prompt.title': 'Open in {editor}?',
'terminal.externalEditor.prompt.desc': 'Remote host {host} requested opening this remote path in {editor}:',
'terminal.externalEditor.prompt.deny': 'Deny',
'terminal.externalEditor.prompt.allowOnce': 'Allow Once',
'terminal.externalEditor.prompt.alwaysTrust': 'Always Trust Host',
'terminal.externalEditor.autoSetupConfigured': 'Remote editor commands configured ({editor})',
};
+3
View File
@@ -1463,5 +1463,8 @@ export const enVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
'sftp.context.openInExternalEditor': 'Open in {editor}',
'hostDetails.externalEditorShellIntegration': 'Enable external editor commands in this session',
'hostDetails.externalEditorShellIntegration.desc': 'Expose `zed` / `ncedit` via ~/.netcatty/bin for this Netcatty terminal session only (including tmux) without modifying ~/.bashrc or ~/.zshrc.',
};
+16
View File
@@ -629,12 +629,19 @@ export const esAiMessages: Messages = {
'ai.chat.managerRebindPick': 'Elegir terminal o espacio de trabajo…',
'ai.chat.managerRebindHere': 'Panel actual',
'ai.chat.managerRebindDone': 'Se movió «{title}» a {target}.',
'ai.chat.managerToggleSelection': 'Seleccionar chats',
'ai.chat.managerSelectAll': 'Seleccionar todo',
'ai.chat.managerSelectedCount': '{n} seleccionados',
'ai.chat.managerSelectRow': 'Seleccionar este chat',
'ai.chat.managerRegenerateTitle': 'Regenerar título con IA',
'ai.chat.managerExportOne': 'Exportar este chat',
'ai.chat.managerBadgeActive': 'Activo',
'ai.chat.managerBadgeIdle': 'Inactivo',
'ai.chat.managerMessagesCount': '{n} mensajes',
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.justNow': 'Ahora mismo',
'ai.chat.minutesAgo': 'hace {n} min',
'ai.chat.hoursAgo': 'hace {n} h',
@@ -688,6 +695,15 @@ export const esAiMessages: Messages = {
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
'ai.chatHistory.messageCap.unit': 'mensajes',
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
'ai.chatHistory.titleModel': 'Modelo de título',
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
'ai.chatHistory.titleModel.unavailable': 'No disponible',
'ai.chatHistory.titleModel.providerPlaceholder': 'Seleccionar proveedor',
'ai.chatHistory.titleModel.modelPlaceholder': 'Seleccionar modelo',
// AI Error
'ai.codex.bridgeError': 'Los controladores del proceso principal de Codex aún no están cargados. Reinicia Netcatty por completo o reinicia el proceso de desarrollo de Electron y vuelve a intentarlo.',
+41
View File
@@ -431,6 +431,8 @@ export const esCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
'settings.vault.removeTopTabsDragArea': 'Quitar el área superior para arrastrar la ventana',
'settings.vault.removeTopTabsDragAreaDesc': 'Al activarla, quita el espacio de arrastre sobre las pestañas para poder hacer clic en el borde superior.',
'settings.vault.showHostTreeSidebarDesc': 'Muestra la barra lateral de lista de hosts y su alternador en la barra superior en las pestañas de terminal y editor.',
'settings.vault.autoImportSystemKnownHosts': 'Importar automáticamente known_hosts del sistema',
'settings.vault.autoImportSystemKnownHostsDesc': 'Cuando se carga el Vault, importa en silencio las entradas del archivo known_hosts de OpenSSH. Desactívalo para mantener los hosts conocidos de Netcatty separados; Escanear sistema sigue importando a pedido.',
@@ -1062,6 +1064,7 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.binding.command-palette': 'Abrir paleta de comandos',
'settings.shortcuts.binding.quick-switch': 'Cambio rápido',
'settings.shortcuts.binding.new-workspace': 'Nuevo espacio de trabajo',
'settings.shortcuts.binding.add-session-to-workspace': 'Añadir sesión al espacio de trabajo',
'settings.shortcuts.binding.snippets': 'Abrir fragmentos',
'settings.shortcuts.binding.broadcast': 'Alternar modo de transmisión',
'settings.shortcuts.binding.toggle-opacity': 'Alternar la transparencia de la ventana',
@@ -1330,6 +1333,8 @@ 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:",
@@ -1496,5 +1501,41 @@ Resalta el panel dividido enfocado:
'plugins.hostActions.managedUnsupported': 'Los cambios de configuración SSH administrada requieren el editor de equipos de Vault.',
'plugins.hostActions.failed': 'La solicitud caducó, se revocó o el equipo cambió. Selecciona el equipo de nuevo.',
'plugins.hostActions.selectionLimit': 'Selecciona hasta 50 equipos actuales.',
'settings.externalEditor.title': 'Editor remoto externo',
'settings.externalEditor.desc': 'Abre proyectos y archivos SSH remotos directamente en editores locales como Zed, VS Code o Cursor.',
'settings.externalEditor.preferredEditor': 'Editor preferido',
'settings.externalEditor.preferredEditor.desc': 'Editor local predeterminado para el menú contextual de SFTP y las solicitudes desde el terminal.',
'settings.externalEditor.executablePath': 'Ejecutable del editor',
'settings.externalEditor.executablePath.desc': 'Déjalo vacío para detectarlo automáticamente o elige el binario local manualmente.',
'settings.externalEditor.executablePath.placeholder': 'Detectar ruta del ejecutable automáticamente',
'settings.externalEditor.status.configured': 'Ruta personalizada',
'settings.externalEditor.status.detected': 'Detectado automáticamente',
'settings.externalEditor.status.notFound': 'No detectado',
'settings.externalEditor.browse': 'Examinar…',
'settings.externalEditor.resetPath': 'Restablecer a detección automática',
'settings.externalEditor.redetect': 'Volver a detectar editores instalados',
'settings.externalEditor.customArgs': 'Argumentos personalizados',
'settings.externalEditor.customArgs.desc': 'Argumentos separados por espacios (marcadores: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'Modo de conexión SSH',
'settings.externalEditor.connectionMode.desc': 'El puente SSH de Netcatty reutiliza tu sesión autenticada activa sin exponer claves ni listas de equipos.',
'settings.externalEditor.connectionMode.bridge': 'Puente SSH de Netcatty (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'OpenSSH directo (usuario@host:puerto)',
'settings.externalEditor.sshBridge.title': 'Regla OpenSSH *.netcatty',
'settings.externalEditor.sshBridge.desc': 'Añade un único bloque estático Host *.netcatty a tu configuración de OpenSSH sin escribir nombres de equipo, claves ni contraseñas.',
'settings.externalEditor.sshBridge.install': 'Instalar regla',
'settings.externalEditor.sshBridge.reinstall': 'Reinstalar regla',
'settings.externalEditor.sshBridge.update': 'Actualizar regla',
'settings.externalEditor.sshBridge.remove': 'Eliminar regla',
'settings.externalEditor.terminalRequests': 'Permitir solicitudes desde el terminal (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Permite que las shells remotas abran rutas en tu editor local configurado mediante comandos como `zed .`.',
'settings.externalEditor.autoSetup': 'Habilitar comandos de editor remoto en sesiones de Netcatty',
'settings.externalEditor.autoSetup.desc': 'Instala helpers `zed` / `ncedit` en ~/.netcatty/bin y los activa en el PATH solo para esta sesión de Netcatty, sin modificar ~/.bashrc ni ~/.zshrc (también configurable por equipo).',
'settings.externalEditor.defaultTrust': 'Confianza predeterminada del equipo',
'settings.externalEditor.defaultTrust.desc': 'Política de permisos cuando un equipo remoto no reconocido solicita abrir un editor local.',
'settings.externalEditor.trust.ask': 'Preguntar siempre',
'settings.externalEditor.trust.allow': 'Permitir siempre',
'settings.externalEditor.trust.deny': 'Denegar siempre',
'settings.externalEditor.trustedHosts.host': 'Equipo',
'settings.externalEditor.trustedHosts.policy': 'Política',
};
+17
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const esTerminalMessages: Messages = {
'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio',
'terminal.gitBranch.current': 'Rama de Git: {{value}}',
'terminal.gitBranch.detached': 'HEAD separado: {{value}}',
'terminal.directory.unknown': 'Directorio desconocido',
'terminal.directory.search': 'Buscar subdirectorios...',
'terminal.directory.directories': 'Directorios',
@@ -16,6 +18,7 @@ export const esTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
'terminal.directory.cygwinIntegrationUnavailable': 'Esperando que Bash de Cygwin vuelva a un indicador inactivo.',
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
@@ -469,6 +472,7 @@ export const esTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Antes de la restauración',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} claves, {snippets} snippets, {notes} notas',
'cloudSync.localBackups.aiCounts': '{sessions} chats de IA, {settings} ajustes',
'cloudSync.localBackups.restore': 'Restaurar',
'cloudSync.localBackups.restoreSuccess': 'Copia de seguridad local restaurada.',
'cloudSync.localBackups.restoreFailedTitle': 'Falló la restauración',
@@ -619,6 +623,10 @@ export const esTerminalMessages: Messages = {
'keychain.export.scriptPlaceholder': 'Script de exportación...',
'keychain.export.missingCredentials':
'El host no tiene contraseña ni clave guardadas. Primero agrega credenciales de contraseña al host.',
'keychain.export.missingPublicKey':
'Esta clave no tiene clave pública. Ábrela en Editar, pega la clave pública y vuelve a intentar Exportar y adjuntar.',
'keychain.export.missingPublicKeyNote':
'Esta clave no tiene clave pública. Pégala en el editor de claves antes de exportar.',
'keychain.export.successTitle': 'Exportación exitosa',
'keychain.export.successMessage': 'Clave pública exportada y adjuntada a {host}',
'keychain.export.failedTitle': 'Falló la exportación',
@@ -697,6 +705,7 @@ export const esTerminalMessages: Messages = {
'tabs.logPrefix': 'Registro:',
'tabs.logLocal': 'Local',
'tabs.copyTab': 'Copiar pestaña',
'tabs.addSessionToWorkspace': 'Añadir sesión al espacio de trabajo',
'tabs.duplicateSession': 'Duplicar sesión',
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
@@ -990,4 +999,12 @@ export const esTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'Mostrar en el navegador de todos los hosts.',
'terminal.browser.downloadLocation': 'Guardado en la carpeta Descargas',
'terminal.browser.saveAs': 'Guardar como…',
'terminal.externalEditor.opened': 'Se abrió {path} en {editor}',
'terminal.externalEditor.failed': 'No se pudo abrir en {editor}',
'terminal.externalEditor.prompt.title': '¿Abrir en {editor}?',
'terminal.externalEditor.prompt.desc': 'El equipo remoto {host} solicitó abrir esta ruta remota en {editor}:',
'terminal.externalEditor.prompt.deny': 'Denegar',
'terminal.externalEditor.prompt.allowOnce': 'Permitir una vez',
'terminal.externalEditor.prompt.alwaysTrust': 'Confiar siempre en este equipo',
'terminal.externalEditor.autoSetupConfigured': 'Comandos de editor remoto configurados ({editor})',
};
+3
View File
@@ -1463,5 +1463,8 @@ export const esVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
'sftp.context.openInExternalEditor': 'Abrir en {editor}',
'hostDetails.externalEditorShellIntegration': 'Habilitar comandos de editor externo en esta sesión',
'hostDetails.externalEditorShellIntegration.desc': 'Activa `zed` / `ncedit` desde ~/.netcatty/bin solo para esta sesión de terminal de Netcatty (incluido tmux), sin modificar ~/.bashrc ni ~/.zshrc.',
};
@@ -228,3 +228,25 @@ test("AI tool output limit settings copy is localized across all five locales",
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
});
test("LLM chat title settings copy is localized across all five locales", () => {
const keys = [
"ai.chatHistory.autoLlmTitle",
"ai.chatHistory.autoLlmTitle.description",
"ai.chatHistory.titleModel",
"ai.chatHistory.titleModel.description",
"ai.chatHistory.titleModel.none",
"ai.chatHistory.titleModel.useCurrentCatty",
"ai.chatHistory.titleModel.unavailable",
"ai.chatHistory.titleModel.providerPlaceholder",
"ai.chatHistory.titleModel.modelPlaceholder",
] as const;
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
for (const key of keys) {
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
if (locale !== "en") {
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
}
}
}
});
+16
View File
@@ -628,12 +628,19 @@ export const ruAiMessages: Messages = {
'ai.chat.managerRebindPick': 'Выберите терминал или рабочее пространство…',
'ai.chat.managerRebindHere': 'Текущая панель',
'ai.chat.managerRebindDone': 'Чат «{title}» перемещён в {target}.',
'ai.chat.managerToggleSelection': 'Выбрать чаты',
'ai.chat.managerSelectAll': 'Выбрать все',
'ai.chat.managerSelectedCount': 'Выбрано: {n}',
'ai.chat.managerSelectRow': 'Выбрать этот чат',
'ai.chat.managerRegenerateTitle': 'Пересоздать заголовок через ИИ',
'ai.chat.managerExportOne': 'Экспортировать этот чат',
'ai.chat.managerBadgeActive': 'Активен',
'ai.chat.managerBadgeIdle': 'Простой',
'ai.chat.managerMessagesCount': '{n} сообщений',
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.justNow': 'Только что',
'ai.chat.minutesAgo': '{n}м назад',
'ai.chat.hoursAgo': '{n}ч назад',
@@ -687,6 +694,15 @@ export const ruAiMessages: Messages = {
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
'ai.chatHistory.messageCap.unit': 'сообщений',
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
'ai.chatHistory.titleModel': 'Модель для заголовков',
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
'ai.chatHistory.titleModel.providerPlaceholder': 'Выбрать провайдер',
'ai.chatHistory.titleModel.modelPlaceholder': 'Выбрать модель',
// AI Error
'ai.codex.bridgeError': 'Обработчики главного процесса Codex ещё не загружены. Полностью перезапустите Netcatty или dev-процесс Electron и попробуйте снова.',
+41
View File
@@ -430,6 +430,8 @@ export const ruCoreMessages: Messages = {
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
'settings.vault.removeTopTabsDragArea': 'Убрать верхнюю область перетаскивания окна',
'settings.vault.removeTopTabsDragAreaDesc': 'При включении удаляется область перетаскивания над вкладками, чтобы по верхнему краю можно было нажимать.',
'settings.vault.showHostTreeSidebarDesc': 'Показывать список хостов и кнопку в верхней панели для вкладок терминала и редактора.',
'settings.vault.autoImportSystemKnownHosts': 'Автоимпорт системного known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': 'При открытии хранилища тихо импортировать записи из OpenSSH known_hosts. Отключите, чтобы держать известные хосты Netcatty отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
@@ -1046,6 +1048,7 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.binding.command-palette': 'Открыть палитру команд',
'settings.shortcuts.binding.quick-switch': 'Быстрое переключение',
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
'settings.shortcuts.binding.add-session-to-workspace': 'Добавить сессию в рабочую область',
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
@@ -1271,6 +1274,8 @@ 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-адреса в браузере по умолчанию:",
@@ -1437,4 +1442,40 @@ export const ruCoreMessages: Messages = {
'plugins.hostActions.managedUnsupported': 'Изменяйте управляемые настройки SSH в редакторе хостов Vault.',
'plugins.hostActions.failed': 'Запрос истёк, был отозван или хост изменился. Выберите хост заново.',
'plugins.hostActions.selectionLimit': 'Выберите не более 50 текущих хостов.',
'settings.externalEditor.title': 'Внешний удалённый редактор',
'settings.externalEditor.desc': 'Открывайте удалённые SSH-проекты и файлы напрямую в локальных редакторах, таких как Zed, VS Code или Cursor.',
'settings.externalEditor.preferredEditor': 'Предпочитаемый редактор',
'settings.externalEditor.preferredEditor.desc': 'Локальный редактор по умолчанию для контекстного меню SFTP и запросов из терминала.',
'settings.externalEditor.executablePath': 'Исполняемый файл редактора',
'settings.externalEditor.executablePath.desc': 'Оставьте пустым для автоопределения или выберите локальный файл вручную.',
'settings.externalEditor.executablePath.placeholder': 'Автоопределение пути к файлу',
'settings.externalEditor.status.configured': 'Указан вручную',
'settings.externalEditor.status.detected': 'Определён автоматически',
'settings.externalEditor.status.notFound': 'Не найден',
'settings.externalEditor.browse': 'Обзор…',
'settings.externalEditor.resetPath': 'Сбросить на автоопределение',
'settings.externalEditor.redetect': 'Повторить поиск редакторов',
'settings.externalEditor.customArgs': 'Пользовательские аргументы',
'settings.externalEditor.customArgs.desc': 'Аргументы через пробел (подстановки: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
'settings.externalEditor.connectionMode': 'Режим SSH-подключения',
'settings.externalEditor.connectionMode.desc': 'SSH-мост Netcatty переиспользует активную аутентифицированную сессию без раскрытия ключей или списка хостов.',
'settings.externalEditor.connectionMode.bridge': 'SSH-мост Netcatty (*.netcatty)',
'settings.externalEditor.connectionMode.direct': 'Прямой OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'Правило OpenSSH *.netcatty',
'settings.externalEditor.sshBridge.desc': 'Добавляет один статический блок Host *.netcatty в конфиг OpenSSH без записи хостов, ключей и паролей.',
'settings.externalEditor.sshBridge.install': 'Установить правило',
'settings.externalEditor.sshBridge.reinstall': 'Переустановить правило',
'settings.externalEditor.sshBridge.update': 'Обновить правило',
'settings.externalEditor.sshBridge.remove': 'Удалить правило',
'settings.externalEditor.terminalRequests': 'Разрешить запросы из терминала (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': 'Позволяет удалённой оболочке открывать пути в локальном редакторе командами вроде `zed .`.',
'settings.externalEditor.autoSetup': 'Включить команды редактора только в сессиях Netcatty',
'settings.externalEditor.autoSetup.desc': 'Устанавливает утилиты `zed` / `ncedit` в ~/.netcatty/bin и добавляет их в PATH только для этой сессии Netcatty, не изменяя ~/.bashrc и ~/.zshrc (можно задать отдельно для хоста).',
'settings.externalEditor.defaultTrust': 'Доверие хостам по умолчанию',
'settings.externalEditor.defaultTrust.desc': 'Политика разрешений, когда неизвестный удалённый хост запрашивает открытие локального редактора.',
'settings.externalEditor.trust.ask': 'Спрашивать каждый раз',
'settings.externalEditor.trust.allow': 'Всегда разрешать',
'settings.externalEditor.trust.deny': 'Всегда запрещать',
'settings.externalEditor.trustedHosts.host': 'Хост',
'settings.externalEditor.trustedHosts.policy': 'Политика',
};
+15
View File
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const ruTerminalMessages: Messages = {
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
'terminal.directory.unknown': 'Каталог неизвестен',
'terminal.directory.search': 'Поиск подкаталогов...',
'terminal.directory.directories': 'Каталоги',
@@ -16,6 +18,7 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
'terminal.directory.cygwinIntegrationUnavailable': 'Ожидание готовности Bash в Cygwin.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
@@ -489,6 +492,7 @@ export const ruTerminalMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': 'Перед восстановлением',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} хостов, {keys} ключей, {snippets} сниппетов, {notes} заметок',
'cloudSync.localBackups.aiCounts': '{sessions} чатов ИИ, {settings} настроек',
'cloudSync.localBackups.restore': 'Восстановить',
'cloudSync.localBackups.restoreSuccess': 'Локальная резервная копия восстановлена.',
'cloudSync.localBackups.restoreFailedTitle': 'Ошибка восстановления',
@@ -636,6 +640,8 @@ export const ruTerminalMessages: Messages = {
'keychain.export.script': 'Скрипт *',
'keychain.export.scriptPlaceholder': 'Скрипт экспорта...',
'keychain.export.missingCredentials': 'У хоста нет сохранённого пароля или ключа. Сначала добавьте в хост учётные данные с паролем.',
'keychain.export.missingPublicKey': 'У этого ключа нет публичного ключа. Откройте «Редактировать», вставьте публичный ключ и снова нажмите «Экспортировать и привязать».',
'keychain.export.missingPublicKeyNote': 'У этого ключа нет публичного ключа. Вставьте его в редакторе ключа перед экспортом.',
'keychain.export.successTitle': 'Экспорт выполнен успешно',
'keychain.export.successMessage': 'Публичный ключ экспортирован и привязан к {host}',
'keychain.export.failedTitle': 'Ошибка экспорта',
@@ -712,6 +718,7 @@ export const ruTerminalMessages: Messages = {
'tabs.logPrefix': 'Журнал:',
'tabs.logLocal': 'Локальный',
'tabs.copyTab': 'Копировать вкладку',
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
'tabs.duplicateSession': 'Дублировать сессию',
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
@@ -1004,4 +1011,12 @@ export const ruTerminalMessages: Messages = {
'terminal.browser.allScopeHint': 'В браузерах всех хостов.',
'terminal.browser.downloadLocation': 'Файлы сохраняются в папку «Загрузки»',
'terminal.browser.saveAs': 'Сохранить как…',
'terminal.externalEditor.opened': 'Открыто {path} в {editor}',
'terminal.externalEditor.failed': 'Не удалось открыть в {editor}',
'terminal.externalEditor.prompt.title': 'Открыть в {editor}?',
'terminal.externalEditor.prompt.desc': 'Удалённый хост {host} запросил открытие этого пути в {editor}:',
'terminal.externalEditor.prompt.deny': 'Отклонить',
'terminal.externalEditor.prompt.allowOnce': 'Разрешить один раз',
'terminal.externalEditor.prompt.alwaysTrust': 'Всегда доверять хосту',
'terminal.externalEditor.autoSetupConfigured': 'Команды удалённого редактора настроены ({editor})',
};
+3
View File
@@ -1482,5 +1482,8 @@ export const ruVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
'sftp.context.openInExternalEditor': 'Открыть в {editor}',
'hostDetails.externalEditorShellIntegration': 'Включить команды внешнего редактора в этой сессии',
'hostDetails.externalEditorShellIntegration.desc': 'Добавляет `zed` / `ncedit` из ~/.netcatty/bin в PATH только для этой сессии терминала Netcatty (включая tmux), не изменяя ~/.bashrc и ~/.zshrc.',
};
+16
View File
@@ -629,12 +629,19 @@ export const zhCNAiMessages: Messages = {
'ai.chat.managerRebindPick': '选择目标终端或工作区…',
'ai.chat.managerRebindHere': '当前面板',
'ai.chat.managerRebindDone': '已将“{title}”移动到 {target}。',
'ai.chat.managerToggleSelection': '选择会话',
'ai.chat.managerSelectAll': '全选',
'ai.chat.managerSelectedCount': '已选 {n} 个',
'ai.chat.managerSelectRow': '选择此会话',
'ai.chat.managerRegenerateTitle': '用 AI 重新生成标题',
'ai.chat.managerExportOne': '导出此会话',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '空闲',
'ai.chat.managerMessagesCount': '{n} 条消息',
'ai.chat.managerDeleteTitle': '删除此会话?',
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.justNow': '刚刚',
'ai.chat.minutesAgo': '{n}分钟前',
'ai.chat.hoursAgo': '{n}小时前',
@@ -688,6 +695,15 @@ export const zhCNAiMessages: Messages = {
'ai.chatHistory.messageCap': '每个会话保留的消息数',
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
'ai.chatHistory.messageCap.unit': '条消息',
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
'ai.chatHistory.titleModel': '标题模型',
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
'ai.chatHistory.titleModel.unavailable': '不可用',
'ai.chatHistory.titleModel.providerPlaceholder': '选择 provider',
'ai.chatHistory.titleModel.modelPlaceholder': '选择模型',
// AI Error
'ai.codex.bridgeError': 'Codex 主进程处理器尚未加载。请完全重启 Netcatty 或重启 Electron 开发进程,然后重试。',
+40
View File
@@ -438,6 +438,8 @@ export const zhCNCoreMessages: Messages = {
'settings.vault.showSftpTab': '显示 SFTP 标签页',
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
'settings.vault.removeTopTabsDragArea': '移除顶部窗口拖动区域',
'settings.vault.removeTopTabsDragAreaDesc': '开启后移除标签页上方的拖动空白区域,让顶部可用于点击标签页和窗口按钮。',
'settings.vault.showHostTreeSidebarDesc': '在终端和编辑器标签页显示主机列表侧栏及顶部开关。',
'settings.vault.autoImportSystemKnownHosts': '自动导入系统 known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': '打开主机库时静默导入 OpenSSH known_hosts 中的记录。关闭后,Netcatty 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
@@ -1247,6 +1249,8 @@ 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 链接:",
@@ -1413,5 +1417,41 @@ Vaults 标签保持扁平,不使用这块背景。
'plugins.hostActions.managedUnsupported': '受管理的 SSH 配置变更需在 Vault 主机编辑器中完成。',
'plugins.hostActions.failed': '请求已过期、被撤销或主机已改变。请重新选择主机。',
'plugins.hostActions.selectionLimit': '最多选择 50 个当前主机。',
'settings.externalEditor.title': '外部远程编辑器',
'settings.externalEditor.desc': '直接在本地编辑器(如 Zed、VS Code 或 Cursor)中打开远程 SSH 项目和文件。',
'settings.externalEditor.preferredEditor': '首选编辑器',
'settings.externalEditor.preferredEditor.desc': 'SFTP 右键菜单和终端打开请求默认使用的本地编辑器。',
'settings.externalEditor.executablePath': '编辑器可执行文件',
'settings.externalEditor.executablePath.desc': '留空以自动检测,或手动选择本地程序路径。',
'settings.externalEditor.executablePath.placeholder': '自动检测可执行文件路径',
'settings.externalEditor.status.configured': '已自定义路径',
'settings.externalEditor.status.detected': '已自动检测',
'settings.externalEditor.status.notFound': '未检测到',
'settings.externalEditor.browse': '浏览…',
'settings.externalEditor.resetPath': '重置为自动检测',
'settings.externalEditor.redetect': '重新检测已安装的编辑器',
'settings.externalEditor.customArgs': '自定义参数',
'settings.externalEditor.customArgs.desc': '以空格分隔的参数列表(支持占位符:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
'settings.externalEditor.connectionMode': 'SSH 连接模式',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 桥接会直接复用当前已认证会话,无需向磁盘导出私钥或主机列表。',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 桥接 (*.netcatty)',
'settings.externalEditor.connectionMode.direct': '直连 OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 桥接规则',
'settings.externalEditor.sshBridge.desc': '仅在 OpenSSH 配置中写入单个静态 Host *.netcatty 规则块,不包含任何主机名、私钥或密码。',
'settings.externalEditor.sshBridge.install': '安装桥接规则',
'settings.externalEditor.sshBridge.reinstall': '重新安装规则',
'settings.externalEditor.sshBridge.update': '更新规则',
'settings.externalEditor.sshBridge.remove': '移除规则',
'settings.externalEditor.terminalRequests': '允许终端发起打开请求 (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': '允许远程 Shell 通过 `zed .` 等命令在本地编辑器中打开远程路径。',
'settings.externalEditor.autoSetup': '仅在 Netcatty 会话中启用远程编辑器命令',
'settings.externalEditor.autoSetup.desc': '将 `zed` / `ncedit` 脚本安装到 ~/.netcatty/bin,并仅在当前 Netcatty 终端会话的 PATH 中生效,不修改 ~/.bashrc 或 ~/.zshrc(也可按主机单独开关)。',
'settings.externalEditor.defaultTrust': '默认主机信任策略',
'settings.externalEditor.defaultTrust.desc': '未单独配置信任规则的远程主机发起打开编辑器请求时的处理方式。',
'settings.externalEditor.trust.ask': '每次询问',
'settings.externalEditor.trust.allow': '始终允许',
'settings.externalEditor.trust.deny': '始终拒绝',
'settings.externalEditor.trustedHosts.host': '主机',
'settings.externalEditor.trustedHosts.policy': '策略',
};
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const zhCNTerminalMessages: Messages = {
'terminal.directory.open': '当前目录:{path}。更改目录',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
'terminal.directory.unknown': '目录未知',
'terminal.directory.search': '搜索当前目录下的文件夹…',
'terminal.directory.directories': '目录',
@@ -16,6 +18,7 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回空闲提示符。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
@@ -630,6 +633,7 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.binding.command-palette': '打开命令面板',
'settings.shortcuts.binding.quick-switch': '快速切换',
'settings.shortcuts.binding.new-workspace': '新建工作区',
'settings.shortcuts.binding.add-session-to-workspace': '添加会话到工作区',
'settings.shortcuts.binding.snippets': '打开代码片段',
'settings.shortcuts.binding.broadcast': '切换广播模式',
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
@@ -719,6 +723,8 @@ export const zhCNTerminalMessages: Messages = {
'keychain.export.script': '脚本 *',
'keychain.export.scriptPlaceholder': '导出脚本...',
'keychain.export.missingCredentials': '主机未保存密码或密钥。请先为该主机添加密码凭据。',
'keychain.export.missingPublicKey': '此密钥没有公钥。请先在编辑页粘贴公钥,然后再试「导出并绑定」。',
'keychain.export.missingPublicKeyNote': '此密钥没有公钥。请先在密钥编辑页粘贴公钥,然后再导出。',
'keychain.export.successTitle': '导出成功',
'keychain.export.successMessage': '已导出公钥并绑定到 {host}',
'keychain.export.failedTitle': '导出失败',
@@ -795,6 +801,7 @@ export const zhCNTerminalMessages: Messages = {
'tabs.logPrefix': '日志:',
'tabs.logLocal': '本地',
'tabs.copyTab': '复制标签页',
'tabs.addSessionToWorkspace': '在此工作区添加会话',
'tabs.duplicateSession': '复制会话',
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
@@ -1088,4 +1095,12 @@ export const zhCNTerminalMessages: Messages = {
'terminal.browser.allScopeHint': '在每台主机的浏览器中显示。',
'terminal.browser.downloadLocation': '文件保存在系统“下载”文件夹',
'terminal.browser.saveAs': '另存为…',
'terminal.externalEditor.opened': '已在 {editor} 中打开 {path}',
'terminal.externalEditor.failed': '无法在 {editor} 中打开',
'terminal.externalEditor.prompt.title': '在 {editor} 中打开?',
'terminal.externalEditor.prompt.desc': '远程主机 {host} 请求在 {editor} 中打开以下远程路径:',
'terminal.externalEditor.prompt.deny': '拒绝',
'terminal.externalEditor.prompt.allowOnce': '仅允许本次',
'terminal.externalEditor.prompt.alwaysTrust': '始终信任此主机',
'terminal.externalEditor.autoSetupConfigured': '已配置远程编辑器命令 ({editor})',
};
+4
View File
@@ -848,6 +848,7 @@ export const zhCNVaultMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': '恢复前',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} 台主机,{keys} 个密钥,{snippets} 个代码片段,{notes} 条笔记',
'cloudSync.localBackups.aiCounts': '{sessions} 个 AI 会话,{settings} 项设置',
'cloudSync.localBackups.restore': '恢复',
'cloudSync.localBackups.restoreSuccess': '已恢复本地备份。',
'cloudSync.localBackups.restoreFailedTitle': '恢复失败',
@@ -1427,5 +1428,8 @@ export const zhCNVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
'sftp.context.openInExternalEditor': '在 {editor} 中打开',
'hostDetails.externalEditorShellIntegration': '在此会话中启用外部编辑器命令',
'hostDetails.externalEditorShellIntegration.desc': '通过 ~/.netcatty/bin 仅在当前 Netcatty 终端会话中启用 `zed` / `ncedit`(支持 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
};
+16
View File
@@ -628,12 +628,19 @@ export const zhTWAiMessages: Messages = {
'ai.chat.managerRebindPick': '選擇目標終端或工作區…',
'ai.chat.managerRebindHere': '目前面板',
'ai.chat.managerRebindDone': '已將「{title}」移動到 {target}。',
'ai.chat.managerToggleSelection': '選擇工作階段',
'ai.chat.managerSelectAll': '全選',
'ai.chat.managerSelectedCount': '已選 {n} 個',
'ai.chat.managerSelectRow': '選擇此工作階段',
'ai.chat.managerRegenerateTitle': '用 AI 重新產生標題',
'ai.chat.managerExportOne': '匯出此會話',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '閒置',
'ai.chat.managerMessagesCount': '{n} 則訊息',
'ai.chat.managerDeleteTitle': '刪除此會話?',
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.justNow': '剛剛',
'ai.chat.minutesAgo': '{n}分鐘前',
'ai.chat.hoursAgo': '{n}小時前',
@@ -687,6 +694,15 @@ export const zhTWAiMessages: Messages = {
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
'ai.chatHistory.messageCap.unit': '則訊息',
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
'ai.chatHistory.titleModel': '標題模型',
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
'ai.chatHistory.titleModel.unavailable': '無法使用',
'ai.chatHistory.titleModel.providerPlaceholder': '選擇 provider',
'ai.chatHistory.titleModel.modelPlaceholder': '選擇模型',
// AI Error
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
+40
View File
@@ -438,6 +438,8 @@ export const zhTWCoreMessages: Messages = {
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
'settings.vault.removeTopTabsDragArea': '移除頂部視窗拖曳區域',
'settings.vault.removeTopTabsDragAreaDesc': '開啟後移除分頁上方的拖曳空白區域,讓頂部可供點擊分頁與視窗按鈕。',
'settings.vault.showHostTreeSidebarDesc': '在終端和編輯器分頁顯示主機列表側欄及頂部開關。',
'settings.vault.autoImportSystemKnownHosts': '自動匯入系統 known_hosts',
'settings.vault.autoImportSystemKnownHostsDesc': '開啟主機庫時靜默匯入 OpenSSH known_hosts 中的記錄。關閉後,Netcatty 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
@@ -1248,6 +1250,8 @@ 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 連結:",
@@ -1414,4 +1418,40 @@ Vaults 分頁維持扁平,不使用這塊背景。
'plugins.hostActions.managedUnsupported': '受管理的 SSH 設定變更需在 Vault 主機編輯器中完成。',
'plugins.hostActions.failed': '請求已過期、被撤銷或主機已變更。請重新選擇主機。',
'plugins.hostActions.selectionLimit': '最多選擇 50 部目前的主機。',
'settings.externalEditor.title': '外部遠端編輯器',
'settings.externalEditor.desc': '直接在本機編輯器(如 Zed、VS Code 或 Cursor)中開啟遠端 SSH 專案與檔案。',
'settings.externalEditor.preferredEditor': '偏好編輯器',
'settings.externalEditor.preferredEditor.desc': 'SFTP 右鍵選單與終端機開啟請求預設使用的本機編輯器。',
'settings.externalEditor.executablePath': '編輯器執行檔',
'settings.externalEditor.executablePath.desc': '留空以自動偵測,或手動選擇本機程式路徑。',
'settings.externalEditor.executablePath.placeholder': '自動偵測執行檔路徑',
'settings.externalEditor.status.configured': '已自訂路徑',
'settings.externalEditor.status.detected': '已自動偵測',
'settings.externalEditor.status.notFound': '未偵測到',
'settings.externalEditor.browse': '瀏覽…',
'settings.externalEditor.resetPath': '重設為自動偵測',
'settings.externalEditor.redetect': '重新偵測已安裝的編輯器',
'settings.externalEditor.customArgs': '自訂參數',
'settings.externalEditor.customArgs.desc': '以空白分隔的參數清單(支援預留位置:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
'settings.externalEditor.connectionMode': 'SSH 連線模式',
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 橋接會直接重複使用目前已完成驗證的連線,無需將私鑰或主機清單匯出至磁碟。',
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 橋接 (*.netcatty)',
'settings.externalEditor.connectionMode.direct': '直連 OpenSSH (user@host:port)',
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 橋接規則',
'settings.externalEditor.sshBridge.desc': '僅在 OpenSSH 設定中寫入單一靜態 Host *.netcatty 規則區塊,不包含任何主機名稱、私鑰或密碼。',
'settings.externalEditor.sshBridge.install': '安裝橋接規則',
'settings.externalEditor.sshBridge.reinstall': '重新安裝規則',
'settings.externalEditor.sshBridge.update': '更新規則',
'settings.externalEditor.sshBridge.remove': '移除規則',
'settings.externalEditor.terminalRequests': '允許終端機發起開啟請求 (OSC 7337)',
'settings.externalEditor.terminalRequests.desc': '允許遠端 Shell 透過 `zed .` 等指令在本機編輯器中開啟遠端路徑。',
'settings.externalEditor.autoSetup': '僅在 Netcatty 工作階段啟用遠端編輯器指令',
'settings.externalEditor.autoSetup.desc': '將 `zed` / `ncedit` 指令稿安裝至 ~/.netcatty/bin,並僅於目前 Netcatty 終端機工作階段的 PATH 生效,不修改 ~/.bashrc 或 ~/.zshrc(亦可依主機個別切換)。',
'settings.externalEditor.defaultTrust': '預設主機信任原則',
'settings.externalEditor.defaultTrust.desc': '尚未單獨設定信任原則的遠端主機請求開啟編輯器時的處理方式。',
'settings.externalEditor.trust.ask': '每次詢問',
'settings.externalEditor.trust.allow': '一律允許',
'settings.externalEditor.trust.deny': '一律拒絕',
'settings.externalEditor.trustedHosts.host': '主機',
'settings.externalEditor.trustedHosts.policy': '原則',
};
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
export const zhTWTerminalMessages: Messages = {
'terminal.directory.open': '目前目錄:{path}。變更目錄',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
'terminal.directory.unknown': '目錄未知',
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
'terminal.directory.directories': '目錄',
@@ -16,6 +18,7 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回閒置提示字元。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -630,6 +633,7 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.binding.command-palette': '開啟指令面板',
'settings.shortcuts.binding.quick-switch': '快速切換',
'settings.shortcuts.binding.new-workspace': '新增工作區',
'settings.shortcuts.binding.add-session-to-workspace': '新增工作階段至工作區',
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
'settings.shortcuts.binding.broadcast': '切換廣播模式',
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
@@ -719,6 +723,8 @@ export const zhTWTerminalMessages: Messages = {
'keychain.export.script': '指令碼 *',
'keychain.export.scriptPlaceholder': '匯出指令碼...',
'keychain.export.missingCredentials': '主機未儲存密碼或金鑰。請先為該主機新增密碼憑證。',
'keychain.export.missingPublicKey': '此金鑰沒有公鑰。請先在編輯頁貼上公鑰,然後再試「匯出並繫結」。',
'keychain.export.missingPublicKeyNote': '此金鑰沒有公鑰。請先在金鑰編輯頁貼上公鑰,然後再匯出。',
'keychain.export.successTitle': '匯出成功',
'keychain.export.successMessage': '已匯出公鑰並繫結到 {host}',
'keychain.export.failedTitle': '匯出失敗',
@@ -795,6 +801,7 @@ export const zhTWTerminalMessages: Messages = {
'tabs.logPrefix': '日誌:',
'tabs.logLocal': '本機',
'tabs.copyTab': '複製分頁',
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
'tabs.duplicateSession': '複製工作階段',
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
@@ -1088,4 +1095,12 @@ export const zhTWTerminalMessages: Messages = {
'terminal.browser.allScopeHint': '在每台主機的瀏覽器中顯示。',
'terminal.browser.downloadLocation': '檔案儲存在系統「下載項目」資料夾',
'terminal.browser.saveAs': '另存新檔…',
'terminal.externalEditor.opened': '已在 {editor} 中開啟 {path}',
'terminal.externalEditor.failed': '無法在 {editor} 中開啟',
'terminal.externalEditor.prompt.title': '在 {editor} 中開啟?',
'terminal.externalEditor.prompt.desc': '遠端主機 {host} 請求在 {editor} 中開啟以下遠端路徑:',
'terminal.externalEditor.prompt.deny': '拒絕',
'terminal.externalEditor.prompt.allowOnce': '僅允許這次',
'terminal.externalEditor.prompt.alwaysTrust': '一律信任此主機',
'terminal.externalEditor.autoSetupConfigured': '已設定遠端編輯器指令 ({editor})',
};
+4
View File
@@ -848,6 +848,7 @@ export const zhTWVaultMessages: Messages = {
'cloudSync.localBackups.reason.beforeRestore': '恢復前',
'cloudSync.localBackups.versionChange': '{from} -> {to}',
'cloudSync.localBackups.counts': '{hosts} 台主機,{keys} 個金鑰,{snippets} 個程式碼片段,{notes} 條筆記',
'cloudSync.localBackups.aiCounts': '{sessions} 個 AI 工作階段,{settings} 項設定',
'cloudSync.localBackups.restore': '恢復',
'cloudSync.localBackups.restoreSuccess': '已恢復本機備份。',
'cloudSync.localBackups.restoreFailedTitle': '恢復失敗',
@@ -1427,5 +1428,8 @@ export const zhTWVaultMessages: Messages = {
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
'sftp.context.openInExternalEditor': '在 {editor} 中開啟',
'hostDetails.externalEditorShellIntegration': '於此工作階段啟用外部編輯器指令',
'hostDetails.externalEditorShellIntegration.desc': '透過 ~/.netcatty/bin 僅於目前 Netcatty 終端機工作階段啟用 `zed` / `ncedit`(支援 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
};
+3
View File
@@ -57,6 +57,9 @@ export interface LocalVaultBackupPreview {
noteCount: number;
identityCount: number;
portForwardingRuleCount: number;
/** Optional so backups written before these counters existed still load. */
aiSessionCount?: number;
settingCount?: number;
};
}
+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' }],
});
});
+203 -6
View File
@@ -12,6 +12,174 @@ 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();
@@ -23,6 +191,16 @@ export function createPluginRemoteTree() {
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');
@@ -31,16 +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: [] };
validatedTrees.add(current);
if (!isDuplicatePluginViewNodeError(error)) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
}
throw error;
}
},
@@ -218,3 +218,52 @@ test('portForward.start surfaces live error status and message when tunnel start
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);
});
@@ -27,6 +27,7 @@ import {
applyPortForwardingRuntimeStatus,
getPortForwardingRuntimeRules,
} from './usePortForwardingState';
import { requestOpenPluginView } from './usePluginViewLifecycle';
export interface PluginPortForwardRuntimeDeps {
startPortForward?: typeof startPortForward;
@@ -36,10 +37,16 @@ export interface PluginPortForwardRuntimeDeps {
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';
@@ -472,6 +479,42 @@ export async function handlePluginVaultDataRequest(
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}`);
}
+317
View File
@@ -60,3 +60,320 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
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;
}
});
+64 -9
View File
@@ -1,9 +1,11 @@
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;
@@ -26,7 +28,10 @@ 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>();
@@ -42,14 +47,26 @@ 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');
const nextCss = update.cssUnchanged
? state.css
: (lastRawCss !== null && update.css === lastRawCss)
? state.css
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
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
@@ -68,7 +85,34 @@ export class PluginViewSessions {
emptyFrameTimer = undefined;
}
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
} catch { dispose(true); }
} 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(() => {
@@ -100,7 +144,18 @@ 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,
};
+3
View File
@@ -25,6 +25,7 @@ export type SettingsChromeSnapshot = {
windowOpacity: number;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
removeTopTabsDragArea: boolean;
showRecentHosts: boolean;
hostClickBehavior: HostClickBehavior;
showOnlyUngroupedHostsInRoot: boolean;
@@ -59,6 +60,7 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
windowOpacity: 1,
showSftpTab: true,
showHostTreeSidebar: true,
removeTopTabsDragArea: false,
showRecentHosts: true,
hostClickBehavior: 'connect',
showOnlyUngroupedHostsInRoot: false,
@@ -86,6 +88,7 @@ export function settingsChromeSnapshotsEqual(
&& a.windowOpacity === b.windowOpacity
&& a.showSftpTab === b.showSftpTab
&& a.showHostTreeSidebar === b.showHostTreeSidebar
&& a.removeTopTabsDragArea === b.removeTopTabsDragArea
&& a.showRecentHosts === b.showRecentHosts
&& a.hostClickBehavior === b.hostClickBehavior
&& a.showOnlyUngroupedHostsInRoot === b.showOnlyUngroupedHostsInRoot
@@ -137,6 +137,7 @@ export type { HostClickBehavior } from '../../domain/hostClickBehavior';
export const DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = false;
export const DEFAULT_SHOW_SFTP_TAB = true;
export const DEFAULT_SHOW_HOST_TREE_SIDEBAR = true;
export const DEFAULT_REMOVE_TOP_TABS_DRAG_AREA = false;
export const DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = false;
export const DEFAULT_SHOW_TAB_NUMBER_BADGES = true;
export const DEFAULT_DISABLE_TERMINAL_FONT_ZOOM = false;
+14 -4
View File
@@ -35,6 +35,7 @@ import {
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
@@ -136,6 +137,7 @@ interface UseSettingsStorageSyncParams {
showOnlyUngroupedHostsInRoot: boolean;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
removeTopTabsDragArea: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
@@ -194,6 +196,7 @@ interface UseSettingsStorageSyncParams {
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setRemoveTopTabsDragAreaState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
@@ -238,7 +241,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -249,7 +252,7 @@ export function useSettingsStorageSync({
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
@@ -266,7 +269,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -278,7 +281,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -548,6 +551,12 @@ export function useSettingsStorageSync({
setShowHostTreeSidebarState(newValue);
}
}
if (e.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.removeTopTabsDragArea) {
setRemoveTopTabsDragAreaState(newValue);
}
}
if (e.key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.terminalSidePanelAutoOpen) {
@@ -701,6 +710,7 @@ export function useSettingsStorageSync({
setSftpSkipUnchanged,
setShowOnlyUngroupedHostsInRootState,
setShowHostTreeSidebarState,
setRemoveTopTabsDragAreaState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
+20 -3
View File
@@ -1,21 +1,38 @@
import {
buildSftpDownloadDialogDirectoryOptions,
normalizeSftpDefaultDownloadDirectory,
type SftpDownloadDialogDirectoryOptions,
} from "../../../domain/sftpDownloadLocation";
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
import {
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
} from "../../../infrastructure/config/storageKeys";
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
/**
* Read the device-local default download folder at call time so every SFTP
* Read the device-local download folders at call time so every SFTP
* surface (main view, terminal side panel, other windows) sees the latest
* value without threading it through props.
*/
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
let stored: string | null = null;
let lastUsed: string | null = null;
try {
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
lastUsed = localStorageAdapter.readString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
} catch {
// Storage unavailable (non-browser host); fall back to system Downloads.
}
return buildSftpDownloadDialogDirectoryOptions(stored);
return buildSftpDownloadDialogDirectoryOptions(stored, lastUsed);
};
/** Remember a confirmed download destination without changing the setting. */
export const rememberSftpDownloadDirectory = (directory: string): void => {
const normalized = normalizeSftpDefaultDownloadDirectory(directory);
if (!normalized) return;
try {
localStorageAdapter.writeString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR, normalized);
} catch {
// Unavailable storage must not interrupt the download.
}
};
@@ -1022,6 +1022,9 @@ export const useSftpConnections = ({
id: connectionId,
hostId: host.id,
hostLabel: host.label,
hostname: host.hostname,
port: host.port,
username: host.username,
isLocal: false,
status: "connecting",
currentPath: normalizedCachedStartPath,
@@ -47,6 +47,7 @@ test('Win32 adapters confirm actual native cwd and reject stale revisions or for
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
});
t.after(() => controller.dispose());
assert.equal(await controller.refresh(), cwd);
const revision = terminalCwdStore.getSessionRevision(id);
terminalCwdStore.setCwd(id, 'C:\\other', 'backend-strict');
terminalCwdStore.setCwd(id, 'C:\\base', 'backend-strict');
@@ -207,7 +208,7 @@ for (const probe of ['fails', 'stalls'] as const) {
t.after(() => controller.dispose());
await controller.change('/next', new AbortController().signal, () => {});
assert.deepEqual(writes, ["cd -- '/next'\r"]);
assert.equal(controller.hasConfirmedCwd(), true);
assert.equal(controller.getConfirmedCwd(), '/next');
});
}
@@ -1,5 +1,5 @@
import { DirectoryPickerError, directoryChangeCommand, isDirectoryPath, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
import { sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
import { DirectoryPickerError, directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
import { isAbsoluteDirectoryPath, sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { terminalCwdStore } from './terminalCwdStore';
@@ -17,21 +17,32 @@ export function createTerminalDirectoryController(options: {
capabilities?: DirectoryCapabilities;
buildChangeCommand?: (path: string) => string | null;
trustOsc7?: boolean;
localPosixSessionId?: string;
}) {
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
const valid = (path: string | null | undefined): path is string => isAbsoluteDirectoryPath(path, target.pathFlavor);
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
let disposed = false;
let changing = false;
let confirmed = false;
let verifiedCwd: string | null = null;
const cwdListeners = new Set<() => void>();
const notifyCwd = () => cwdListeners.forEach(listener => listener());
let refreshing: Promise<string> | null = null;
let refreshAgain = false;
let cwdError: DirectoryPickerError | null = null;
const lifetime = new AbortController();
const current = () => !disposed && options.isCurrent();
function getConfirmedCwd(): string | null {
if (!current() || !capabilities.readCwd) return null;
const cwd = terminalCwdStore.getCwd(options.sessionId);
const source = terminalCwdStore.getSource(options.sessionId);
if (source === 'stale') return null;
if (trustsOsc7 && source === 'osc7' && valid(cwd)) return cwd;
if (options.trustOsc7 === false && target.pathFlavor === 'posix') return verifiedCwd;
return verifiedCwd !== null && cwd === verifiedCwd ? verifiedCwd : null;
}
function check(signal?: AbortSignal) {
if (!current() || signal?.aborted) throw new DirectoryPickerError('unavailable');
}
@@ -69,7 +80,7 @@ export function createTerminalDirectoryController(options: {
// events and picker remounts. Only a cd submission may probe past its own
// pre-write report while waiting for fresh confirmation.
const reported = activeShellCwd();
if (reported) { confirmed = true; cwdError = null; return reported; }
if (reported) { cwdError = null; return reported; }
if (refreshing) {
// Output may settle while a pre-cd query is still in flight. Keep one
// follow-up query so that its older result cannot be the last update.
@@ -83,10 +94,10 @@ export function createTerminalDirectoryController(options: {
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
} catch (error) {
if (current() && !trustsOsc7) {
confirmed = false;
verifiedCwd = null;
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
options.publish('');
notifyCwd();
}
throw error;
}
@@ -94,12 +105,12 @@ export function createTerminalDirectoryController(options: {
const reported = activeShellCwd();
const live = terminalCwdStore.getCwd(options.sessionId);
const verifiedCwdChanged = verifiedCwd !== cwd;
confirmed = true;
verifiedCwd = cwd;
cwdError = null;
if (reported) return reported;
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|| (options.trustOsc7 === false && verifiedCwdChanged)) options.publish(cwd);
|| verifiedCwdChanged) options.publish(cwd);
if (verifiedCwdChanged) notifyCwd();
return cwd;
})();
refreshing = pending;
@@ -126,7 +137,7 @@ export function createTerminalDirectoryController(options: {
check(signal);
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
ready(); // The shell can become busy while resolving a remote symlink.
if (expectedCwd && (options.trustOsc7 === false ? verifiedCwd : terminalCwdStore.getCwd(options.sessionId)) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedCwd && getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
options.io.write(command + '\r');
@@ -172,17 +183,23 @@ export function createTerminalDirectoryController(options: {
};
await Promise.race([confirmFromProbe(), confirmFromOsc7()]);
check(signal);
confirmed = true;
} finally { confirmationFinished = true; changing = false; }
}
return {
target,
localPosixSessionId: options.localPosixSessionId,
capabilities,
trustsOsc7,
getVerifiedCwd: () => verifiedCwd,
getConfirmedCwd,
subscribeCwd(listener: () => void) {
const unsubscribe = terminalCwdStore.subscribe(listener);
cwdListeners.add(listener);
return () => {
unsubscribe();
cwdListeners.delete(listener);
};
},
getCwdError: () => cwdError?.code ?? null,
refresh: () => refresh(),
hasConfirmedCwd: () => confirmed,
async home() {
check();
const result = await bounded(options.io.home?.() ?? Promise.resolve(null));
+16 -1
View File
@@ -2,6 +2,7 @@ import type { TerminalDirectoryController } from './terminalDirectoryController'
const sessions = new Map<string, TerminalDirectoryController>();
const consumers = new Map<string, number>();
const refreshListeners = new Map<string, Set<() => void>>();
const scheduledRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
const OUTPUT_SETTLE_MS = 150;
@@ -36,10 +37,24 @@ export function observeTerminalDirectory(id: string) {
else { consumers.delete(id); cancelScheduledRefresh(id); }
};
}
export function subscribeTerminalDirectoryRefresh(id: string, listener: () => void) {
const listeners = refreshListeners.get(id) ?? new Set<() => void>();
listeners.add(listener);
refreshListeners.set(id, listeners);
return () => {
listeners.delete(listener);
if (!listeners.size) refreshListeners.delete(id);
};
}
/** Called by the existing command completion path, only while chips are visible. */
export function refreshObservedTerminalDirectory(id: string) {
cancelScheduledRefresh(id);
if (consumers.has(id)) void sessions.get(id)?.refresh().catch(() => {});
const controller = consumers.has(id) ? sessions.get(id) : undefined;
if (!controller) return;
void controller.refresh().then(() => {
if (sessions.get(id) === controller) refreshListeners.get(id)?.forEach(listener => listener());
}).catch(() => {});
}
/**
+88 -12
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
STORAGE_KEY_AI_PROVIDERS,
@@ -19,6 +19,8 @@ import {
STORAGE_KEY_AI_WEB_SEARCH,
STORAGE_KEY_AI_QUICK_MESSAGES,
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
STORAGE_KEY_AI_AUTO_LLM_TITLE,
STORAGE_KEY_AI_TITLE_MODEL,
} from '../../infrastructure/config/storageKeys';
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
@@ -46,6 +48,7 @@ import {
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
normalizeAiToolOutputMaxChars,
} from '../../domain/aiToolOutputLimit';
import type { TitleModelConfig } from '../../domain/aiSessionTitle';
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
import { getAIBridge } from './aiStateSnapshots';
import { useStoredBoolean } from './useStoredBoolean';
@@ -54,6 +57,25 @@ import {
readCommandBlocklistSetting,
} from './commandBlocklistSettings';
export type { TitleModelConfig };
function readTitleModelSetting(): TitleModelConfig | null {
const stored = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_TITLE_MODEL);
if (!stored || typeof stored !== 'object') return null;
const providerId = (stored as TitleModelConfig).providerId;
const modelId = (stored as TitleModelConfig).modelId;
return typeof providerId === 'string' && providerId.trim()
&& typeof modelId === 'string' && modelId.trim()
? { providerId: providerId.trim(), modelId: modelId.trim() }
: null;
}
function readAgentStringMap(key: string): Record<string, string> {
const stored = localStorageAdapter.read<unknown>(key);
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
return stored as Record<string, string>;
}
function readPermissionMode(): AIPermissionMode {
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
@@ -150,6 +172,25 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
);
const [autoLlmTitle, setAutoLlmTitle] = useStoredBoolean(STORAGE_KEY_AI_AUTO_LLM_TITLE, true);
const [titleModel, setTitleModelRaw] = useState<TitleModelConfig | null>(() =>
readTitleModelSetting(),
);
const titleModelRef = useRef(titleModel);
titleModelRef.current = titleModel;
const setTitleModel = useCallback((config: TitleModelConfig | null) => {
const normalized = config
&& typeof config.providerId === 'string' && config.providerId.trim()
&& typeof config.modelId === 'string' && config.modelId.trim()
? { providerId: config.providerId.trim(), modelId: config.modelId.trim() }
: null;
titleModelRef.current = normalized;
setTitleModelRaw(normalized);
if (normalized) localStorageAdapter.write(STORAGE_KEY_AI_TITLE_MODEL, normalized);
else localStorageAdapter.remove(STORAGE_KEY_AI_TITLE_MODEL);
emitAIStateChanged(STORAGE_KEY_AI_TITLE_MODEL);
}, []);
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
setProvidersRaw((prev) => {
@@ -183,6 +224,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, '');
return '';
});
if (titleModelRef.current?.providerId === id) {
setTitleModel(null);
}
if (onRemoveProvider) {
onRemoveProvider(id);
@@ -196,11 +240,13 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
const cleanup = removeProviderReferences(id, agentProviderMap, agentModelMap);
if (cleanup.providerMapChanged) {
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
emitAIStateChanged(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
}
if (cleanup.modelMapChanged) {
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
emitAIStateChanged(STORAGE_KEY_AI_AGENT_MODEL_MAP);
}
}, [onRemoveProvider, setProviders]);
}, [onRemoveProvider, setProviders, setTitleModel]);
const setActiveProviderId = useCallback((id: string) => {
setActiveProviderIdRaw(id);
@@ -375,6 +421,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
case STORAGE_KEY_AI_QUICK_MESSAGES:
setQuickMessagesRaw(sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)));
break;
case STORAGE_KEY_AI_TITLE_MODEL:
setTitleModelRaw(readTitleModelSetting());
break;
}
} catch (err) {
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
@@ -438,6 +487,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
}), [
providers,
setProviders,
@@ -471,6 +524,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
]);
}
@@ -486,6 +543,12 @@ export function useAISettingsState() {
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
true,
);
const [agentProviderMap, setAgentProviderMapRaw] = useState<Record<string, string>>(() =>
readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP),
);
const [agentModelMap, setAgentModelMapRaw] = useState<Record<string, string>>(() =>
readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP),
);
const setAiSessionMessageCap = useCallback((value: number) => {
const normalizedValue = normalizeAiSessionMessageCap(value);
@@ -494,23 +557,32 @@ export function useAISettingsState() {
}, []);
useEffect(() => {
const syncMessageCap = (key: string | null) => {
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
const syncSettingsOnlyKey = (key: string | null) => {
try {
setAiSessionMessageCapRaw(
normalizeAiSessionMessageCap(
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
),
);
switch (key) {
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
setAiSessionMessageCapRaw(
normalizeAiSessionMessageCap(
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
),
);
break;
case STORAGE_KEY_AI_AGENT_PROVIDER_MAP:
setAgentProviderMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP));
break;
case STORAGE_KEY_AI_AGENT_MODEL_MAP:
setAgentModelMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP));
break;
}
} catch (err) {
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
}
};
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
const handleStorage = (event: StorageEvent) => syncSettingsOnlyKey(event.key);
const handleLocalStateChanged = (event: Event) => {
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
syncSettingsOnlyKey((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
};
window.addEventListener('storage', handleStorage);
@@ -527,11 +599,15 @@ export function useAISettingsState() {
setAiSessionMessageCap,
showTerminalSelectionAIAction,
setShowTerminalSelectionAIAction,
agentProviderMap,
agentModelMap,
}), [
shared,
aiSessionMessageCap,
setAiSessionMessageCap,
showTerminalSelectionAIAction,
setShowTerminalSelectionAIAction,
agentProviderMap,
agentModelMap,
]);
}
@@ -0,0 +1,345 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import type { AISession, ProviderConfig } from '../../infrastructure/ai/types.ts';
import {
STORAGE_KEY_AI_ACTIVE_PROVIDER,
STORAGE_KEY_AI_AGENT_MODEL_MAP,
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
STORAGE_KEY_AI_AUTO_LLM_TITLE,
STORAGE_KEY_AI_PROVIDERS,
STORAGE_KEY_AI_TITLE_MODEL,
} from '../../infrastructure/config/storageKeys.ts';
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
import { useAISessionsStore } from './aiSessionsStore.ts';
import {
__resetIdbPersistenceForTests,
markAiSessionsHydrationComplete,
setLatestAISessionsSnapshot,
} from './aiStateSnapshots.ts';
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
type Capture = {
ai: ReturnType<typeof useAIState> | null;
sessions: AISession[];
};
function Harness({
capture,
options,
}: {
capture: Capture;
options?: UseAIStateOptions;
}) {
capture.ai = useAIState(options);
capture.sessions = useAISessionsStore().sessions as AISession[];
return null;
}
async function setupHook(options?: {
sessions?: AISession[];
providers?: ProviderConfig[];
activeProviderId?: string;
agentProviderMap?: Record<string, string>;
agentModelMap?: Record<string, string>;
autoLlmTitle?: boolean;
titleModel?: { providerId: string; modelId: string } | null;
generateSessionTitle?: UseAIStateOptions['generateSessionTitle'];
}) {
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
const prevDescriptors = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of [
['window', dom.window],
['document', dom.window.document],
['localStorage', dom.window.localStorage],
['CustomEvent', dom.window.CustomEvent],
['Event', dom.window.Event],
['IS_REACT_ACT_ENVIRONMENT', true],
] as const) {
prevDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
__resetIdbPersistenceForTests();
markAiSessionsHydrationComplete();
if (options?.providers) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify(options.providers));
}
if (options?.activeProviderId) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, options.activeProviderId);
}
if (options?.agentProviderMap) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify(options.agentProviderMap));
}
if (options?.agentModelMap) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify(options.agentModelMap));
}
if (options?.autoLlmTitle !== undefined) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_AUTO_LLM_TITLE, String(options.autoLlmTitle));
}
if (options?.titleModel) {
dom.window.localStorage.setItem(STORAGE_KEY_AI_TITLE_MODEL, JSON.stringify(options.titleModel));
}
const initialSessions = options?.sessions ?? [];
setLatestAISessionsSnapshot(initialSessions);
dom.window.localStorage.setItem('netcatty_ai_sessions_v1', JSON.stringify(initialSessions));
const container = dom.window.document.createElement('div');
dom.window.document.body.appendChild(container);
const root = createRoot(container);
const capture: Capture = { ai: null, sessions: [] };
await act(async () => {
root.render(
React.createElement(Harness, {
capture,
options: { generateSessionTitle: options?.generateSessionTitle },
}),
);
});
return {
capture,
cleanup: async () => {
await act(async () => root.unmount());
container.remove();
dom.window.close();
__resetIdbPersistenceForTests();
for (const [key, desc] of prevDescriptors) {
if (desc) Object.defineProperty(globalThis, key, desc);
else delete (globalThis as Record<string, unknown>)[key];
}
},
};
}
const providerA: ProviderConfig = {
id: 'p-catty',
providerId: 'openai',
name: 'Main OpenAI',
enabled: true,
defaultModel: 'gpt-5.4',
};
const providerB: ProviderConfig = {
id: 'p-title',
providerId: 'openai',
name: 'Cheap Title',
enabled: true,
defaultModel: 'gpt-4o-mini',
};
const untitledSession = (id = 's-1'): AISession => ({
id,
title: 'New Chat',
agentId: 'catty',
scope: { type: 'terminal', targetId: 'term-1' },
messages: [{ id: 'm-1', role: 'user', content: 'Check slow SSH handshake on prod', timestamp: 1 }],
createdAt: 1,
updatedAt: 1,
});
test('autoTitleSession preserves a user rename that happens while LLM title generation is pending', async () => {
const pending = deferred<string>();
let capturedSignal: AbortSignal | undefined;
const { capture, cleanup } = await setupHook({
sessions: [untitledSession()],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async (_source, opts) => {
capturedSignal = opts.signal;
return pending.promise;
},
});
try {
let titleTask!: Promise<void>;
await act(async () => {
titleTask = capture.ai!.autoTitleSession('s-1', 'Check slow SSH handshake on prod');
});
// Deterministic fallback landed immediately.
assert.equal(capture.sessions[0].title, 'Check slow SSH handshake on prod');
assert.equal(capturedSignal?.aborted, false);
// User renames the session (e.g. after closing & reopening the side panel).
await act(async () => {
capture.ai!.updateSessionTitle('s-1', 'Prod SSH Debug');
});
assert.equal(capturedSignal?.aborted, true, 'manual rename aborts pending LLM call');
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
// Even if the LLM promise resolves with a generated title afterwards, it
// must not overwrite the user's title.
await act(async () => {
pending.resolve('Slow SSH Handshake');
await titleTask;
});
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
} finally {
await cleanup();
}
});
test('autoTitleSession promotes the LLM title when unrenamed and passes Catty or explicit titleModel config', async () => {
const seenConfigs: Array<ProviderConfig | null | undefined> = [];
const pending = deferred<string>();
const { capture, cleanup } = await setupHook({
sessions: [untitledSession('s-catty'), untitledSession('s-explicit')],
providers: [providerB, providerA],
activeProviderId: providerB.id,
agentProviderMap: { catty: providerA.id },
agentModelMap: { catty: 'gpt-5.4-turbo' },
generateSessionTitle: async (_source, opts) => {
seenConfigs.push(opts.config);
return pending.promise;
},
});
try {
let task!: Promise<void>;
await act(async () => {
task = capture.ai!.autoTitleSession('s-catty', 'Check slow SSH handshake on prod');
});
assert.equal(seenConfigs[0]?.id, providerA.id);
assert.equal(seenConfigs[0]?.defaultModel, 'gpt-5.4-turbo');
await act(async () => {
pending.resolve('SSH Handshake Audit');
await task;
});
assert.equal(capture.sessions.find((s) => s.id === 's-catty')?.title, 'SSH Handshake Audit');
// Explicit titleModel overrides Catty model.
await act(async () => {
capture.ai!.setTitleModel({ providerId: providerB.id, modelId: 'gpt-4o-mini' });
});
await act(async () => {
await capture.ai!.autoTitleSession('s-explicit', 'Inspect nginx error logs');
});
assert.equal(seenConfigs[1]?.id, providerB.id);
assert.equal(seenConfigs[1]?.defaultModel, 'gpt-4o-mini');
assert.equal(capture.sessions.find((s) => s.id === 's-explicit')?.title, 'SSH Handshake Audit');
} finally {
await cleanup();
}
});
test('autoTitleSession aborts and ignores deleted sessions, deduplicates concurrent calls, and skips titled chats', async () => {
const pending = deferred<string>();
let calls = 0;
let signalRef: AbortSignal | undefined;
const { capture, cleanup } = await setupHook({
sessions: [
untitledSession('s-del'),
untitledSession('s-dup'),
{ ...untitledSession('s-titled'), title: 'Already named' },
],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async (_source, opts) => {
calls += 1;
signalRef = opts.signal;
return pending.promise;
},
});
try {
// Titled chat skips both fallback and LLM.
await act(async () => {
await capture.ai!.autoTitleSession('s-titled', 'New prompt text');
});
assert.equal(calls, 0);
assert.equal(capture.sessions.find((s) => s.id === 's-titled')?.title, 'Already named');
// Deleting a session aborts in-flight generation and never resurrects it.
let delTask!: Promise<void>;
await act(async () => {
delTask = capture.ai!.autoTitleSession('s-del', 'Delete me mid-flight');
});
assert.equal(calls, 1);
await act(async () => {
capture.ai!.deleteSession('s-del');
});
assert.equal(signalRef?.aborted, true);
await act(async () => {
pending.resolve('Ghost title');
await delTask;
});
assert.equal(capture.sessions.some((s) => s.id === 's-del'), false);
// Duplicate concurrent call for the same session only invokes LLM once.
const pendingDup = deferred<string>();
const dupHarness = await setupHook({
sessions: [untitledSession('s-dup2')],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async () => {
calls += 1;
return pendingDup.promise;
},
});
try {
let t1!: Promise<void>;
let t2!: Promise<void>;
await act(async () => {
t1 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'First call');
t2 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'Second call');
});
assert.equal(calls, 2);
await act(async () => {
pendingDup.resolve('Single Title');
await Promise.all([t1, t2]);
});
assert.equal(dupHarness.capture.sessions.find((s) => s.id === 's-dup2')?.title, 'Single Title');
} finally {
await dupHarness.cleanup();
}
} finally {
await cleanup();
}
});
test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dangling titleModel', async () => {
let calls = 0;
const { capture, cleanup } = await setupHook({
sessions: [untitledSession('s-off')],
providers: [providerA, providerB],
activeProviderId: providerA.id,
autoLlmTitle: false,
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
generateSessionTitle: async () => {
calls += 1;
return 'Should not run';
},
});
try {
await act(async () => {
await capture.ai!.autoTitleSession('s-off', 'Fallback only please');
});
assert.equal(calls, 0);
assert.equal(capture.sessions[0].title, 'Fallback only please');
assert.deepEqual(capture.ai!.titleModel, { providerId: providerB.id, modelId: 'gpt-4o-mini' });
await act(async () => {
capture.ai!.removeProvider(providerB.id);
});
assert.equal(capture.ai!.titleModel, null);
} finally {
await cleanup();
}
});
+263 -3
View File
@@ -98,8 +98,20 @@ import {
buildUndoLastTurnBranch,
type UndoLastTurnRestoredDraft,
} from '../../domain/aiUndoLastTurn';
import {
applySessionTitleIfCurrent,
buildFallbackTitle,
canAutoTitleSession,
resolveEffectiveTitleModelConfig,
} from '../../domain/aiSessionTitle';
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
export function useAIState() {
export interface UseAIStateOptions {
/** Optional test injection for one-shot LLM title generation. */
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
}
export function useAIState(options?: UseAIStateOptions) {
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
);
@@ -402,11 +414,35 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
} = useSharedAISettingsState({
ignoreInvalidPermissionModeOnStorage: true,
onRemoveProvider: handleRemoveProviderReferences,
});
const providersRef = useRef(providers);
providersRef.current = providers;
const activeProviderIdRef = useRef(activeProviderId);
activeProviderIdRef.current = activeProviderId;
const activeModelIdRef = useRef(activeModelId);
activeModelIdRef.current = activeModelId;
const autoLlmTitleRef = useRef(autoLlmTitle);
autoLlmTitleRef.current = autoLlmTitle;
const titleModelRef = useRef(titleModel);
titleModelRef.current = titleModel;
const generateSessionTitleRef = useRef(options?.generateSessionTitle);
generateSessionTitleRef.current = options?.generateSessionTitle;
const pendingCreatedSessionIdsRef = useRef<Set<string>>(new Set());
const titleAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
useEffect(() => {
for (const session of sessions) {
pendingCreatedSessionIdsRef.current.delete(session.id);
}
}, [sessions]);
useEffect(() => {
setLatestAISessionsSnapshot(sessions);
}, [sessions]);
@@ -724,6 +760,14 @@ export function useAIState() {
createdAt: now,
updatedAt: now,
};
// Keep the source workspace name when the fork stays in that workspace;
// a fork into a different/terminal scope must not inherit a stale name.
if (
source.workspaceNameSnapshot
&& (!viewingScope || (viewingScope.type === 'workspace' && viewingScope.targetId === source.scope.targetId))
) {
fork.workspaceNameSnapshot = source.workspaceNameSnapshot;
}
if (plan.contextCompaction) {
fork.contextCompaction = plan.contextCompaction;
}
@@ -739,17 +783,25 @@ export function useAIState() {
return fork;
}, [persistSessions, setActiveSessionId]);
const createSession = useCallback((scope: AISessionScope, agentId?: string): AISession => {
const createSession = useCallback((
scope: AISessionScope,
agentId?: string,
workspaceNameSnapshot?: string,
): AISession => {
const now = Date.now();
const session: AISession = {
id: `ai_${now}_${Math.random().toString(36).slice(2, 8)}`,
title: 'New Chat',
agentId: agentId || defaultAgentId,
scope,
...(scope.type === 'workspace' && workspaceNameSnapshot
? { workspaceNameSnapshot }
: {}),
messages: [],
createdAt: now,
updatedAt: now,
};
pendingCreatedSessionIdsRef.current.add(session.id);
setSessionsRaw(prev => {
const next = [session, ...prev];
setLatestAISessionsSnapshot(next);
@@ -796,6 +848,12 @@ export function useAIState() {
}, [persistSessions, setActiveSessionId]);
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
pendingCreatedSessionIdsRef.current.delete(sessionId);
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(sessionId);
pendingTitleController.abort();
}
cleanupDeletedAIChatSessions([sessionId]);
if (persistTimerRef.current) {
clearTimeout(persistTimerRef.current);
@@ -838,6 +896,14 @@ export function useAIState() {
const removedSessionIds = sessionsRef.current
.filter(s => s.scope.type === scopeType && s.scope.targetId === targetId)
.map(s => s.id);
for (const removedId of removedSessionIds) {
pendingCreatedSessionIdsRef.current.delete(removedId);
const pendingTitleController = titleAbortControllersRef.current.get(removedId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(removedId);
pendingTitleController.abort();
}
}
cleanupDeletedAIChatSessions(removedSessionIds);
if (persistTimerRef.current) {
clearTimeout(persistTimerRef.current);
@@ -865,6 +931,12 @@ export function useAIState() {
}, [persistSessions]);
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
// Manual rename supersedes any in-flight automatic title generation.
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
if (pendingTitleController) {
titleAbortControllersRef.current.delete(sessionId);
pendingTitleController.abort();
}
setSessionsRaw(prev => {
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
setLatestAISessionsSnapshot(next);
@@ -873,12 +945,182 @@ export function useAIState() {
});
}, [persistSessions]);
/**
* Auto-title a session if it still carries the placeholder title. Writes a
* deterministic fallback immediately, then (when enabled and a model is
* configured) upgrades it with a one-shot LLM summary. Lives in application
* state so panel close/reopen cannot break the in-flight lifecycle, and
* compares against live state atomically so a user rename always wins.
*/
const autoTitleSession = useCallback(async (
sessionId: string,
text: string,
callerSignal?: AbortSignal,
): Promise<void> => {
if (!sessionId) return;
if (titleAbortControllersRef.current.has(sessionId)) return;
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const existing = snapshot.find((s) => s.id === sessionId);
if (existing && !canAutoTitleSession(existing)) return;
if (!existing && !pendingCreatedSessionIdsRef.current.has(sessionId)) return;
const fallback = buildFallbackTitle(text);
// Phase 1: Atomically apply the deterministic fallback while still untitled.
setSessionsRaw((prev) => {
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
if (!result.updated) return prev;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
});
if (!autoLlmTitleRef.current || callerSignal?.aborted) return;
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
activeProviderId: activeProviderIdRef.current,
activeModelId: activeModelIdRef.current,
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) return;
const requestController = new AbortController();
titleAbortControllersRef.current.set(sessionId, requestController);
const onCallerAbort = () => requestController.abort();
if (callerSignal) {
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
}
try {
const latestBeforeCall = (latestAISessionsSnapshot ?? sessionsRef.current)
.find((s) => s.id === sessionId);
if (
latestBeforeCall
&& !canAutoTitleSession(latestBeforeCall)
&& latestBeforeCall.title !== fallback
) {
return;
}
const sourceMessages = latestBeforeCall?.messages?.length
? latestBeforeCall.messages
: (text ? [{ role: 'user' as const, content: text }] : []);
if (sourceMessages.length === 0) return;
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
{ messages: sourceMessages },
{
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: requestController.signal,
},
);
if (requestController.signal.aborted || !generated || generated === fallback) {
return;
}
// Phase 2: Atomically promote the LLM title only if the session still
// exists and still holds the exact fallback title applied in Phase 1.
if (mountedRef.current) {
setSessionsRaw((prev) => {
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
if (!result.updated) return prev;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
});
} else {
const current = latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot();
const result = applySessionTitleIfCurrent(current, sessionId, generated, fallback);
if (result.updated) {
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
}
}
} catch {
// Generation never throws; fallback was already applied above.
} finally {
if (callerSignal) {
callerSignal.removeEventListener('abort', onCallerAbort);
}
if (titleAbortControllersRef.current.get(sessionId) === requestController) {
titleAbortControllersRef.current.delete(sessionId);
}
}
}, [persistSessions]);
/**
* Explicitly regenerate an existing chat's title with the configured LLM
* (session-history management: no placeholder gate). The old title is the
* expected value, so a user rename during generation still wins.
*/
const regenerateSessionTitle = useCallback(async (sessionId: string): Promise<void> => {
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) return;
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const session = snapshot.find((s) => s.id === sessionId);
if (!session || session.messages.length === 0) return;
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
activeProviderId: activeProviderIdRef.current,
activeModelId: activeModelIdRef.current,
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) return;
const controller = new AbortController();
titleAbortControllersRef.current.set(sessionId, controller);
try {
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
{ messages: session.messages },
{
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: controller.signal,
fallbackOnFailure: false,
},
);
if (controller.signal.aborted || !generated || generated === session.title) return;
const previousTitle = session.title;
const commit = (sessions: AISession[]) => {
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
if (!result.updated) return sessions;
setLatestAISessionsSnapshot(result.sessions);
persistSessions(result.sessions);
return result.sessions;
};
if (mountedRef.current) setSessionsRaw(commit);
else {
const result = commit(latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot());
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
void result;
}
} catch {
// Title generation never throws; keep the existing title on failure.
} finally {
if (titleAbortControllersRef.current.get(sessionId) === controller) {
titleAbortControllersRef.current.delete(sessionId);
}
}
}, [persistSessions]);
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
// Rewrites `scope`, clears the dangling marker and makes the chat the
// active session of its new scope so it shows in the scoped history again.
const rebindSessionScope = useCallback((
sessionId: string,
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
workspaceNameSnapshot?: string,
) => {
const scopeKey = `${scope.type}:${scope.targetId}`;
// Capture the PRE-rebind active map before rebindActiveSessionMap drops the
@@ -903,9 +1145,15 @@ export function useAIState() {
if (scope.hostIds && scope.hostIds.length > 0) {
nextScope.hostIds = [...scope.hostIds];
}
// Snapshot follows the binding: keep it only for workspace scopes.
// `rest` may still carry a stale snapshot from a previous workspace.
const { workspaceNameSnapshot: _staleSnapshot, ...withoutSnapshot } = rest;
return {
...rest,
...withoutSnapshot,
scope: nextScope,
...(scope.type === 'workspace' && workspaceNameSnapshot
? { workspaceNameSnapshot }
: {}),
updatedAt: Date.now(),
} as AISession;
});
@@ -1453,6 +1701,10 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
// sessions / activeSessionIdMap / draftsByScope / panelViewByScope live in
// aiSessionsStore so streaming updates do not rebuild this config object.
setActiveSessionId,
@@ -1468,6 +1720,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -1522,6 +1776,10 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
setActiveSessionId,
ensureDraftForScope,
updateDraft,
@@ -1535,6 +1793,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
+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();
+13 -18
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
import { DirectoryPickerError, filterDirectories, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
import { parentDirectoryPath } from '../../domain/directoryPath';
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
import { terminalCwdStore } from './terminalCwdStore';
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
@@ -7,15 +8,9 @@ import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirect
export function useComposeDirectoryPicker(sessionId: string) {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const getCurrentCwd = useCallback(() => controller?.trustsOsc7 === false && pathFlavor === 'posix'
? controller.getVerifiedCwd() : terminalCwdStore.getCwd(sessionId), [controller, pathFlavor, sessionId]);
const observedCwd = getCurrentCwd();
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (controller.trustsOsc7 && terminalCwdStore.getSource(sessionId) === 'osc7'))
? observedCwd : null;
const subscribeCwd = controller?.subscribeCwd ?? terminalCwdStore.subscribe;
const getCurrentCwd = useCallback(() => controller?.getConfirmedCwd() ?? null, [controller]);
const cwd = useSyncExternalStore(subscribeCwd, getCurrentCwd, () => null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [showHidden, setShowHidden] = useState(false);
@@ -47,11 +42,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
const stopObserving = observeTerminalDirectory(sessionId);
lifetime.current = new AbortController();
sending.current = false;
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
listingBase.current = null;
listingRevision.current = null;
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
if (generation.current === id) setHome(nextHome);
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
return () => {
generation.current = id + 1;
@@ -63,9 +58,9 @@ export function useComposeDirectoryPicker(sessionId: string) {
if (!controller) { setError('unavailable'); return; }
const id = generation.current;
setError(null);
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
try { await controller.refresh(); }
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
}, [controller, report, sessionId]);
}, [controller, report]);
const load = useCallback(async () => {
if (!controller || !cwd) return;
@@ -105,7 +100,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
if (!controller) { setError('unavailable'); return; }
if (sending.current) return;
if (!cwd || getCurrentCwd() !== cwd
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|| (path !== parentDirectoryPath(cwd, pathFlavor) && (listingBase.current !== cwd
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
sending.current = true; setPending(true); setError(null);
const id = generation.current;
@@ -120,11 +115,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const cwdError = useSyncExternalStore(subscribeCwd, () => controller?.getCwdError() ?? null, () => null);
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'cygwinIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
parent: cwd ? parentDirectoryPath(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
refresh, reload: load, change };
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import type { TerminalGitHeadResult } from '../../domain/terminalGitHead';
import { useComposeGitBranch } from './useComposeGitBranch';
import { createTerminalDirectoryController } from './terminalDirectoryController';
import { observeTerminalDirectory, refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry';
import { terminalCwdStore } from './terminalCwdStore';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
test('Git chip follows confirmed cwd and ignores an old worktree result', async t => {
const id = 'git-chip-test';
const calls: { id: string; cwd: string; resolve: (head: TerminalGitHeadResult) => void }[] = [];
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
netcatty: { readLocalSessionGitHead: (backendId: string, cwd: string) => new Promise<TerminalGitHeadResult>(resolve => {
calls.push({ id: backendId, cwd, resolve });
}) },
} });
const controller = createTerminalDirectoryController({
sessionId: id, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => true,
io: { cwd: async () => '/other', list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} },
publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'),
});
const unregister = registerTerminalDirectory(id, controller);
const stopObserving = observeTerminalDirectory(id);
let root!: ReactTestRenderer;
let head: ReturnType<typeof useComposeGitBranch>;
function Harness() { head = useComposeGitBranch(id); return null; }
const waitForCalls = async (count: number) => {
for (let i = 0; calls.length < count && i < 100; i++) await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(calls.length, count);
};
t.after(async () => {
await act(async () => { root?.unmount(); });
stopObserving(); unregister(); terminalCwdStore.setCwd(id, null);
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
else Reflect.deleteProperty(globalThis, 'window');
});
terminalCwdStore.setCwd(id, '/old', 'inferred');
await act(async () => { root = create(React.createElement(Harness)); });
assert.equal(head!, null);
assert.deepEqual(calls, []);
await act(async () => { terminalCwdStore.setCwd(id, '/old', 'osc7'); });
await waitForCalls(1);
assert.equal(calls[0].id, 'local-pty');
assert.equal(calls[0].cwd, '/old');
await act(async () => { terminalCwdStore.setCwd(id, '/other', 'osc7'); });
await waitForCalls(2);
await act(async () => { calls[1].resolve({ kind: 'branch', name: 'current', worktreeRoot: '/other' }); });
await act(async () => { calls[0].resolve({ kind: 'branch', name: 'old', worktreeRoot: '/old' }); });
assert.deepEqual(head!, { kind: 'branch', name: 'current', worktreeRoot: '/other' });
refreshObservedTerminalDirectory(id);
await waitForCalls(3);
await act(async () => { calls[2].resolve({ kind: 'detached', hash: '123abcd', worktreeRoot: '/other' }); });
assert.deepEqual(head!, { kind: 'detached', hash: '123abcd', worktreeRoot: '/other' });
await act(async () => { terminalCwdStore.setCwd(id, null); });
assert.equal(head!, null);
});
+67
View File
@@ -0,0 +1,67 @@
import { useEffect, useState, useSyncExternalStore } from 'react';
import type { TerminalGitHead } from '../../domain/terminalGitHead';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
import type { TerminalDirectoryController } from './terminalDirectoryController';
const noCwd = () => null;
const noSubscription = () => () => {};
const REFRESH_DELAY_MS = 150;
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const backendId = controller?.localPosixSessionId;
const cwd = useSyncExternalStore(
backendId ? controller.subscribeCwd : noSubscription,
backendId ? controller.getConfirmedCwd : noCwd,
noCwd,
);
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
useEffect(() => {
const bridge = netcattyBridge.get();
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
let active = true;
let pending = false;
let refreshAgain = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const isCurrent = () => active && getTerminalDirectory(sessionId) === controller && controller.getConfirmedCwd() === cwd;
const read = async () => {
if (!isCurrent()) return;
pending = true;
try {
const next = await bridge.readLocalSessionGitHead?.(backendId, cwd);
if (isCurrent() && !refreshAgain) {
setResult({ controller, cwd, head: next?.kind === 'branch' || next?.kind === 'detached' ? next : null });
}
} catch {
if (isCurrent() && !refreshAgain) setResult({ controller, cwd, head: null });
} finally {
pending = false;
if (refreshAgain && active) {
refreshAgain = false;
schedule();
}
}
};
const schedule = () => {
if (pending) {
refreshAgain = true;
return;
}
clearTimeout(timer);
timer = setTimeout(() => { void read(); }, REFRESH_DELAY_MS);
};
schedule();
const unsubscribe = subscribeTerminalDirectoryRefresh(sessionId, schedule);
return () => {
active = false;
clearTimeout(timer);
unsubscribe();
setResult(current => current?.controller === controller && current.cwd === cwd ? null : current);
};
}, [backendId, controller, cwd, sessionId]);
return result?.controller === controller && result.cwd === cwd ? result.head : null;
}
@@ -0,0 +1,480 @@
/**
* useExternalEditorSettings - Reactive store & launcher for External Editor integration
*
* Device-local (not cloud-synced because executable paths differ across machines).
* Uses useSyncExternalStore + window `storage` events so the Settings window and
* main Terminal/SFTP windows stay immediately in sync.
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import {
buildDirectSshTarget,
buildSshBridgeHostname,
getHostKeyForExternalEditor,
normalizeExternalEditorSettings,
validateAndNormalizeRemotePath,
type ExternalEditorConnectionMode,
type ExternalEditorHostIdentity,
type ExternalEditorHostTrustPolicy,
type ExternalEditorPresetId,
type ExternalEditorSettings,
type ExternalEditorTargetKind,
} from '../../domain/externalEditor';
import { STORAGE_KEY_EXTERNAL_EDITOR } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
netcattyBridge,
type ExternalEditorBridgeConfigStatus,
type ExternalEditorDetectEntry,
type ExternalEditorOpenRemoteResult,
} from '../../infrastructure/services/netcattyBridge';
export type {
ExternalEditorBridgeConfigStatus,
ExternalEditorDetectEntry,
ExternalEditorOpenRemoteResult,
};
const subscribers = new Set<() => void>();
function hasBrowserStorage(): boolean {
return typeof window !== 'undefined' && 'localStorage' in window;
}
function loadExternalEditorSettings(): ExternalEditorSettings {
if (!hasBrowserStorage()) {
return normalizeExternalEditorSettings(undefined);
}
try {
const stored = localStorageAdapter.read<Partial<ExternalEditorSettings>>(STORAGE_KEY_EXTERNAL_EDITOR);
return normalizeExternalEditorSettings(stored);
} catch {
return normalizeExternalEditorSettings(undefined);
}
}
let currentSettings: ExternalEditorSettings = loadExternalEditorSettings();
let storageListenerAttached = false;
function ensureStorageListener() {
if (storageListenerAttached || typeof window === 'undefined' || typeof window.addEventListener !== 'function') {
return;
}
storageListenerAttached = true;
window.addEventListener('storage', (event: StorageEvent) => {
if (event.key === STORAGE_KEY_EXTERNAL_EDITOR) {
writeSettings(loadExternalEditorSettings(), false);
}
});
}
ensureStorageListener();
function notifySubscribers() {
subscribers.forEach((cb) => cb());
}
function writeSettings(next: ExternalEditorSettings, persist = true) {
currentSettings = normalizeExternalEditorSettings(next);
if (persist && hasBrowserStorage()) {
try {
localStorageAdapter.write(STORAGE_KEY_EXTERNAL_EDITOR, currentSettings);
} catch {
// ignore storage write failures in restricted contexts
}
}
notifySubscribers();
}
function subscribe(callback: () => void) {
subscribers.add(callback);
return () => {
subscribers.delete(callback);
};
}
export function getExternalEditorSettingsSnapshot(): ExternalEditorSettings {
return currentSettings;
}
export function updateExternalEditorSettings(
updater: (prev: ExternalEditorSettings) => ExternalEditorSettings,
): ExternalEditorSettings {
const next = updater(currentSettings);
writeSettings(next, true);
return currentSettings;
}
export function setExternalEditorHostTrust(
host: ExternalEditorHostIdentity,
policy: ExternalEditorHostTrustPolicy,
): void {
const hostKey = getHostKeyForExternalEditor(host);
if (!hostKey) return;
updateExternalEditorSettings((prev) => ({
...prev,
trustedHosts: {
...prev.trustedHosts,
[hostKey]: policy,
},
}));
}
export function removeExternalEditorHostTrust(hostKey: string): void {
updateExternalEditorSettings((prev) => {
if (!Object.prototype.hasOwnProperty.call(prev.trustedHosts, hostKey)) return prev;
const nextTrusted = { ...prev.trustedHosts };
delete nextTrusted[hostKey];
return {
...prev,
trustedHosts: nextTrusted,
};
});
}
export interface LaunchRemoteExternalEditorParams {
editorId?: ExternalEditorPresetId;
host: ExternalEditorHostIdentity;
remotePath: string;
fallbackCwd?: string;
kind?: ExternalEditorTargetKind;
sessionId?: string;
sftpId?: string;
settings?: ExternalEditorSettings;
}
/**
* Shared application-layer launcher invoked by both Terminal OSC 7337 handlers
* and SFTP context menus.
*/
export async function launchRemoteExternalEditor(
params: LaunchRemoteExternalEditorParams,
): Promise<ExternalEditorOpenRemoteResult> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.openRemote) {
throw new Error('External editor integration requires the desktop application.');
}
const settings = params.settings ?? getExternalEditorSettingsSnapshot();
const editorId = params.editorId ?? settings.defaultEditor;
const editorConfig = settings.editors[editorId];
const validated = validateAndNormalizeRemotePath(params.remotePath, params.fallbackCwd);
if (!validated.ok) {
throw new Error('error' in validated ? validated.error : 'Invalid remote path');
}
const connectionMode = settings.connectionMode;
const bridgeHost = connectionMode === 'bridge'
? buildSshBridgeHostname(params.host)
: undefined;
const directSshTarget = connectionMode === 'direct'
? buildDirectSshTarget(params.host) ?? undefined
: undefined;
if (connectionMode === 'direct' && !directSshTarget) {
throw new Error('Cannot construct a valid OpenSSH target for this host.');
}
return bridge.externalEditor.openRemote({
editorId,
executablePath: editorConfig?.executablePath || undefined,
customArgs: editorId === 'custom' ? editorConfig?.customArgs : undefined,
connectionMode,
bridgeHost,
directSshTarget,
sessionId: params.sessionId,
sftpId: params.sftpId,
hostId: params.host.hostId,
hostname: params.host.hostname,
port: params.host.port,
username: params.host.username,
remotePath: validated.path,
kind: params.kind ?? 'auto',
});
}
export async function detectInstalledExternalEditors(): Promise<Record<string, ExternalEditorDetectEntry>> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.detect) return {};
return (await bridge.externalEditor.detect()) || {};
}
export async function getExternalEditorBridgeConfigStatus(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.getBridgeConfigStatus) return null;
return (await bridge.externalEditor.getBridgeConfigStatus()) || null;
}
export async function installExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.installBridgeConfig) return null;
return bridge.externalEditor.installBridgeConfig();
}
export async function removeExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
const bridge = netcattyBridge.get();
if (!bridge?.externalEditor?.removeBridgeConfig) return null;
return bridge.externalEditor.removeBridgeConfig();
}
export async function selectExternalEditorApplication(): Promise<{ path: string; name?: string } | null> {
const bridge = netcattyBridge.get();
if (!bridge?.selectApplication) return null;
return (await bridge.selectApplication()) || null;
}
function getTerminalAutoSetupSnapshotKey(): string {
const s = currentSettings;
return `${s.terminalRequestsEnabled ? 1 : 0}:${s.autoSetupShellIntegration ? 1 : 0}:${s.defaultEditor}`;
}
/**
* Narrow selector for Terminal panes so edits to unrelated External Editor settings
* (executable paths, custom args, trust list, bridge mode) never re-render open terminals.
*/
export function useExternalEditorTerminalAutoSetupConfig(): {
terminalRequestsEnabled: boolean;
autoSetupShellIntegration: boolean;
defaultEditor: ExternalEditorPresetId;
} {
const key = useSyncExternalStore(
subscribe,
getTerminalAutoSetupSnapshotKey,
getTerminalAutoSetupSnapshotKey,
);
useEffect(() => {
ensureStorageListener();
}, []);
const [reqFlag, autoFlag, defaultEditor] = key.split(':');
return {
terminalRequestsEnabled: reqFlag === '1',
autoSetupShellIntegration: autoFlag === '1',
defaultEditor: defaultEditor as ExternalEditorPresetId,
};
}
export function useExternalEditorSettings() {
const settings = useSyncExternalStore(
subscribe,
getExternalEditorSettingsSnapshot,
getExternalEditorSettingsSnapshot,
);
useEffect(() => {
ensureStorageListener();
}, []);
const setDefaultEditor = useCallback((editorId: ExternalEditorPresetId) => {
updateExternalEditorSettings((prev) => ({
...prev,
defaultEditor: editorId,
}));
}, []);
const setEditorExecutablePath = useCallback((editorId: ExternalEditorPresetId, executablePath: string) => {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
[editorId]: {
...prev.editors[editorId],
executablePath,
},
},
}));
}, []);
const setCustomEditorArgs = useCallback((customArgs: string[]) => {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
custom: {
...prev.editors.custom,
customArgs,
},
},
}));
}, []);
const setTerminalRequestsEnabled = useCallback((enabled: boolean) => {
updateExternalEditorSettings((prev) => ({
...prev,
terminalRequestsEnabled: enabled,
}));
}, []);
const setAutoSetupShellIntegration = useCallback((enabled: boolean) => {
updateExternalEditorSettings((prev) => ({
...prev,
autoSetupShellIntegration: enabled,
}));
}, []);
const setDefaultTrustPolicy = useCallback((policy: ExternalEditorHostTrustPolicy) => {
updateExternalEditorSettings((prev) => ({
...prev,
defaultTrustPolicy: policy,
}));
}, []);
const setConnectionMode = useCallback((mode: ExternalEditorConnectionMode) => {
updateExternalEditorSettings((prev) => ({
...prev,
connectionMode: mode,
}));
}, []);
const setHostTrustPolicy = useCallback((hostKey: string, policy: ExternalEditorHostTrustPolicy) => {
updateExternalEditorSettings((prev) => ({
...prev,
trustedHosts: {
...prev.trustedHosts,
[hostKey]: policy,
},
}));
}, []);
const removeHostTrustPolicy = useCallback((hostKey: string) => {
removeExternalEditorHostTrust(hostKey);
}, []);
return {
settings,
setDefaultEditor,
setEditorExecutablePath,
setCustomEditorArgs,
setTerminalRequestsEnabled,
setAutoSetupShellIntegration,
setDefaultTrustPolicy,
setConnectionMode,
setHostTrustPolicy,
removeHostTrustPolicy,
};
}
/**
* Application-state hook owning external editor detection, `~/.ssh/config` bridge
* installation/removal, and application picker lifecycle so UI settings sections
* stay presentation-only.
*/
export function useExternalEditorEnvironment() {
const [detectedEditors, setDetectedEditors] = useState<Record<string, ExternalEditorDetectEntry>>({});
const [detecting, setDetecting] = useState(false);
const [selectingApp, setSelectingApp] = useState(false);
const [bridgeStatus, setBridgeStatus] = useState<ExternalEditorBridgeConfigStatus | null>(null);
const [bridgeBusy, setBridgeBusy] = useState(false);
const [bridgeError, setBridgeError] = useState<string | null>(null);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const refreshStatus = useCallback(async () => {
setDetecting(true);
try {
const [detected, cfg] = await Promise.all([
detectInstalledExternalEditors(),
getExternalEditorBridgeConfigStatus(),
]);
if (!mountedRef.current) return;
setDetectedEditors(detected);
setBridgeStatus(cfg);
setBridgeError(null);
} catch (err) {
if (!mountedRef.current) return;
setBridgeError(err instanceof Error ? err.message : String(err));
} finally {
if (mountedRef.current) {
setDetecting(false);
}
}
}, []);
useEffect(() => {
void refreshStatus();
}, [refreshStatus]);
const browseExecutable = useCallback(async (editorId: ExternalEditorPresetId): Promise<string | null> => {
setSelectingApp(true);
try {
const picked = await selectExternalEditorApplication();
if (picked?.path) {
updateExternalEditorSettings((prev) => ({
...prev,
editors: {
...prev.editors,
[editorId]: {
...prev.editors[editorId],
executablePath: picked.path,
},
},
}));
return picked.path;
}
return null;
} catch (err) {
console.error('[ExternalEditor] Failed to select executable:', err);
return null;
} finally {
if (mountedRef.current) {
setSelectingApp(false);
}
}
}, []);
const installBridgeConfig = useCallback(async () => {
setBridgeBusy(true);
setBridgeError(null);
try {
const status = await installExternalEditorBridgeConfig();
if (mountedRef.current && status) {
setBridgeStatus(status);
}
} catch (err) {
if (mountedRef.current) {
setBridgeError(err instanceof Error ? err.message : String(err));
}
} finally {
if (mountedRef.current) {
setBridgeBusy(false);
}
}
}, []);
const removeBridgeConfig = useCallback(async () => {
setBridgeBusy(true);
setBridgeError(null);
try {
const status = await removeExternalEditorBridgeConfig();
if (mountedRef.current && status) {
setBridgeStatus(status);
}
} catch (err) {
if (mountedRef.current) {
setBridgeError(err instanceof Error ? err.message : String(err));
}
} finally {
if (mountedRef.current) {
setBridgeBusy(false);
}
}
}, []);
return {
detectedEditors,
detecting,
selectingApp,
bridgeStatus,
bridgeBusy,
bridgeError,
refreshStatus,
browseExecutable,
installBridgeConfig,
removeBridgeConfig,
};
}
+4 -1
View File
@@ -16,7 +16,10 @@ export const checkAppShortcut = (
return null;
};
// Get list of key bindings that should be handled at app level (not by terminal)
// Get list of key bindings that should be handled at app level (not by terminal).
// Conditional shortcuts that pass through to the terminal when unavailable
// (like toggleHostTree and addSessionToWorkspace) stay out so an unconsumed
// chord still gets full Kitty/Win32/broadcast handling in xterm.
export const getAppLevelActions = (): Set<string> => {
return new Set([
'switchToTab',
+8 -2
View File
@@ -39,7 +39,11 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
try {
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(); };
@@ -49,7 +53,9 @@ 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 hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
const hasCurrentState = active
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
? state.snapshot
: cachedSession
@@ -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 &&
+21 -2
View File
@@ -88,6 +88,7 @@ import {
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
@@ -145,6 +146,7 @@ import {
DEFAULT_HOST_CLICK_BEHAVIOR,
DEFAULT_SHOW_SFTP_TAB,
DEFAULT_SHOW_HOST_TREE_SIDEBAR,
DEFAULT_REMOVE_TOP_TABS_DRAG_AREA,
DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
DEFAULT_SHOW_TAB_NUMBER_BADGES,
DEFAULT_DISABLE_TERMINAL_FONT_ZOOM,
@@ -472,6 +474,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
return stored ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR;
});
const [removeTopTabsDragArea, setRemoveTopTabsDragAreaState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
return stored ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA;
});
const [terminalSidePanelAutoOpen, setTerminalSidePanelAutoOpenState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
return stored ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED;
@@ -1186,6 +1192,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
setShowHostTreeSidebarState(storedShowHostTreeSidebar ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR);
const storedRemoveTopTabsDragArea = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
setRemoveTopTabsDragAreaState(storedRemoveTopTabsDragArea ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA);
const storedTerminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
setTerminalSidePanelAutoOpenState(storedTerminalSidePanelAutoOpen ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED);
const storedTerminalSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
@@ -1489,7 +1497,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
@@ -1501,7 +1509,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
@@ -1647,6 +1655,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
notifySettingsChanged(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, enabled);
}, [notifySettingsChanged]);
const setRemoveTopTabsDragArea = useCallback((enabled: boolean) => {
setRemoveTopTabsDragAreaState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
}, [notifySettingsChanged]);
const setTerminalSidePanelAutoOpen = useCallback((enabled: boolean) => {
setTerminalSidePanelAutoOpenState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, enabled);
@@ -2181,6 +2196,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
windowOpacity,
showSftpTab,
showHostTreeSidebar,
removeTopTabsDragArea,
showRecentHosts,
hostClickBehavior,
showOnlyUngroupedHostsInRoot,
@@ -2205,6 +2221,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
restoreTerminalCwd,
shellOnlyTabNumberShortcuts,
showHostTreeSidebar,
removeTopTabsDragArea,
showOnlyUngroupedHostsInRoot,
showRecentHosts,
showSftpTab,
@@ -2385,6 +2402,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setShowSftpTab,
showHostTreeSidebar,
setShowHostTreeSidebar,
removeTopTabsDragArea,
setRemoveTopTabsDragArea,
terminalSidePanelAutoOpen,
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
@@ -11,11 +11,11 @@ type SessionProps = Parameters<typeof useTerminalDirectorySession>[0];
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) {
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo'], discoverShells?: NetcattyBridge['discoverShells']) {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
let probes = 0; let lists = 0;
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
getAppInfo,
getAppInfo, discoverShells,
getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; },
listLocalDir: async () => { lists++; return []; },
} } });
@@ -55,6 +55,19 @@ for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) {
});
}
test('a discovered Cygwin terminal registers its own POSIX directory controller', async t => {
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }), async () => [
{ id: 'cygwin', name: 'Cygwin', command: 'C:/cygwin64/bin/bash.exe', args: ['--login', '-i'], icon: 'cygwin' },
]);
const props = options('cygwin-tab');
props.host = { ...props.host, localShell: 'cygwin' };
function Harness() { useTerminalDirectorySession(props); return null; }
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness)); });
t.after(async () => { await act(async () => { root.unmount(); }); });
assert.deepEqual(getTerminalDirectory(props.sessionId)?.target, { authority: 'cygwin:cygwin-tab', pathFlavor: 'posix' });
});
for (const platform of ['linux', 'darwin']) {
test(`local POSIX directory controller registers on ${platform}`, async t => {
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform }));
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell';
import { isDiscoveredCygwin, isDiscoveredGitBash } from '../../lib/localShell';
export function useTerminalDirectorySession(options: {
sessionId: string;
@@ -36,16 +36,18 @@ export function useTerminalDirectorySession(options: {
let unregister = () => {};
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
if (!isCurrent()) return;
const sessionFilesystem = integration === 'wsl' || integration === 'cygwin';
const controller = createTerminalDirectoryController({
sessionId,
localPosixSessionId: local && !integration ? backendId : undefined,
io: createTerminalDirectoryIO(bridge, backendId, {
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
encoding: host.sftpEncoding,
pathFlavor,
windowsShell: integration,
}, isCurrent),
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: integration !== 'wsl',
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: !sessionFilesystem,
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
@@ -67,6 +69,8 @@ export function useTerminalDirectorySession(options: {
register('posix', 'wsl');
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
} else if (isDiscoveredCygwin(host.localShell, shells?.find(item => item.id === 'cygwin')?.command)) {
register('posix', 'cygwin');
}
}
}).catch(() => {});
@@ -0,0 +1,169 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX,
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
} from '../../domain/externalEditor';
import { createExternalEditorSessionProvisioner } from './useTerminalExternalEditor';
function flushMicrotasks(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
test('provisions initial editor helpers and activates PATH once, then installs newly selected editor without re-injecting PATH', async () => {
const execCalls: { sessionId: string; command: string }[] = [];
const writeCalls: { sessionId: string; data: string; opts?: { automated?: boolean } }[] = [];
const configuredLabels: string[] = [];
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (sessionId, command) => {
execCalls.push({ sessionId, command });
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
};
},
writeToSession: (sessionId, data, opts) => {
writeCalls.push({ sessionId, data, opts });
},
getCurrentSessionId: () => 'sess-1',
isReadyForCommandInjection: () => true,
onConfigured: (label) => configuredLabels.push(label),
});
// 1. Initial connection with Zed
const cancelZed = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.match(execCalls[0].command, /write_bin '\\''zed'\\''/);
assert.doesNotMatch(execCalls[0].command, /write_bin '\\''code'\\''/);
assert.equal(writeCalls.length, 1);
assert.match(writeCalls[0].data, /export PATH="\$HOME\/\.netcatty\/bin:\$PATH" NETCATTY_EXTERNAL_EDITOR=1/);
assert.deepEqual(writeCalls[0].opts, { automated: true });
assert.deepEqual(configuredLabels, ['Zed']);
// 2. Switching preferred editor to VS Code in the same live session installs `code`
// without injecting a duplicate PATH activation command into the terminal.
cancelZed();
const cancelVscode = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'vscode' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.match(execCalls[1].command, /write_bin '\\''code'\\''/);
assert.equal(writeCalls.length, 1);
assert.deepEqual(configuredLabels, ['Zed', 'VS Code']);
// 3. Switching back to Zed in the same session is a no-op (already provisioned + activated).
cancelVscode();
const cancelZedAgain = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.equal(writeCalls.length, 1);
cancelZedAgain();
});
test('polls until terminal prompt is ready and cancels cleanly if editor changes before prompt settles', async () => {
const execCalls: string[] = [];
const writeCalls: string[] = [];
const timers = new Map<number, () => void>();
let nextTimerId = 1;
let ready = false;
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (_sessionId, command) => {
execCalls.push(command);
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}fish\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
};
},
writeToSession: (_sessionId, data) => {
writeCalls.push(data);
},
getCurrentSessionId: () => 'sess-2',
isReadyForCommandInjection: () => ready,
scheduleTimer: (fn) => {
const id = nextTimerId++;
timers.set(id, fn);
return id as unknown as ReturnType<typeof setTimeout>;
},
clearTimer: (handle) => {
timers.delete(handle as unknown as number);
},
});
// Start with Zed while prompt is still busy with MOTD.
const cancelZed = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.equal(writeCalls.length, 0);
assert.equal(timers.size, 1);
// Switch to Cursor before prompt becomes ready: old poll is cancelled, Cursor is provisioned.
cancelZed();
assert.equal(timers.size, 0);
const cancelCursor = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'cursor' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.match(execCalls[1], /write_bin '\\''cursor'\\''/);
assert.equal(writeCalls.length, 0);
assert.equal(timers.size, 1);
// Prompt becomes ready -> fish PATH activation executes once.
ready = true;
const scheduled = [...timers.values()];
timers.clear();
scheduled.forEach((fn) => fn());
assert.equal(writeCalls.length, 1);
assert.match(writeCalls[0], /set -gx PATH "\$HOME\/\.netcatty\/bin" \$PATH/);
cancelCursor();
});
test('resets per-session tracking on disconnect so reconnect re-activates PATH', async () => {
let activeSessionId = 'sess-3';
const execCalls: string[] = [];
const writeCalls: string[] = [];
const provisioner = createExternalEditorSessionProvisioner({
setupExec: async (sessionId) => {
execCalls.push(sessionId);
return {
success: true,
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n`,
};
},
writeToSession: (sessionId) => {
writeCalls.push(sessionId);
},
getCurrentSessionId: () => activeSessionId,
isReadyForCommandInjection: () => true,
});
const cancelFirst = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 1);
assert.equal(writeCalls.length, 1);
cancelFirst();
// Disconnect resets session state even if the same sessionId reconnects.
provisioner.reset();
const cancelSecond = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 2);
assert.equal(writeCalls.length, 2);
cancelSecond();
// New backend sessionId also provisions and activates fresh.
activeSessionId = 'sess-4';
const cancelThird = provisioner.sync({ sessionId: 'sess-4', defaultEditor: 'zed' });
await flushMicrotasks();
assert.equal(execCalls.length, 3);
assert.equal(writeCalls.length, 3);
cancelThird();
});
@@ -0,0 +1,387 @@
/**
* useTerminalExternalEditor - Application-state hook & session provisioner for
* Terminal External Editor integration (OSC 7337 requests, per-host trust prompts,
* and session-scoped ~/.netcatty/bin helper provisioning + one-time PATH activation).
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import {
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
buildExternalEditorAutoSetupCommand,
buildExternalEditorSessionActivateCommand,
getExternalEditorLabel,
parseExternalEditorAutoSetupShell,
resolveExternalEditorTrustPolicy,
shouldAutoSetupExternalEditorShell,
validateAndNormalizeRemotePath,
type ExternalEditorOscRequest,
type ExternalEditorPresetId,
type ExternalEditorTargetKind,
} from '../../domain/externalEditor';
import type { Host } from '../../domain/models';
import { logger } from '../../lib/logger';
import {
getExternalEditorSettingsSnapshot,
launchRemoteExternalEditor,
setExternalEditorHostTrust,
useExternalEditorTerminalAutoSetupConfig,
} from './useExternalEditorSettings';
export interface PendingExternalEditorRequest {
editorId: ExternalEditorPresetId;
editorLabel: string;
remotePath: string;
kind: ExternalEditorTargetKind;
}
export interface ExternalEditorSessionSetupResult {
success?: boolean;
stdout?: string;
stderr?: string;
error?: string;
}
export interface ExternalEditorSessionProvisionerDeps {
setupExec: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
getCurrentSessionId: () => string | null;
isReadyForCommandInjection: () => boolean;
onConfigured?: (editorLabel: string) => void;
onWarn?: (message: string, detail?: unknown) => void;
scheduleTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
clearTimer?: (handle: ReturnType<typeof setTimeout>) => void;
pollIntervalMs?: number;
maxPollAttempts?: number;
}
export interface ExternalEditorSessionProvisioner {
reset: () => void;
sync: (params: {
sessionId: string;
defaultEditor: ExternalEditorPresetId;
}) => () => void;
}
/**
* Stateful session helper provisioner separated from React so lifecycle
* transitions (initial setup, preferred-editor switching without re-injecting
* PATH, disconnect reset, and cancellation) can be tested deterministically.
*/
export function createExternalEditorSessionProvisioner(
deps: ExternalEditorSessionProvisionerDeps,
): ExternalEditorSessionProvisioner {
const scheduleTimer = deps.scheduleTimer ?? ((fn, ms) => setTimeout(fn, ms));
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
const pollIntervalMs = deps.pollIntervalMs ?? 100;
const maxPollAttempts = deps.maxPollAttempts ?? 60;
let trackedSessionId: string | null = null;
let provisionedEditors = new Set<ExternalEditorPresetId>();
let pathActivated = false;
const reset = () => {
trackedSessionId = null;
provisionedEditors = new Set();
pathActivated = false;
};
const sync = ({
sessionId,
defaultEditor,
}: {
sessionId: string;
defaultEditor: ExternalEditorPresetId;
}): (() => void) => {
if (trackedSessionId !== sessionId) {
trackedSessionId = sessionId;
provisionedEditors = new Set();
pathActivated = false;
}
if (provisionedEditors.has(defaultEditor) && pathActivated) {
return () => {};
}
let cancelled = false;
let pollTimer: ReturnType<typeof setTimeout> | null = null;
const setupCmd = buildExternalEditorAutoSetupCommand(defaultEditor);
void deps.setupExec(sessionId, setupCmd).then((result) => {
if (cancelled) return;
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
if (!result?.success) {
deps.onWarn?.(
'[Terminal] External editor session helper setup failed:',
result?.error || result?.stderr,
);
return;
}
provisionedEditors.add(defaultEditor);
const updated = typeof result.stdout === 'string'
&& result.stdout.includes(EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER);
// PATH is already active in this shell session (e.g. user changed preferred
// editor while connected); the new wrapper in ~/.netcatty/bin is immediately
// available without injecting another PATH command into the running terminal.
if (pathActivated) {
if (updated) {
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
}
return;
}
const shellKind = parseExternalEditorAutoSetupShell(result.stdout);
const activateCmd = buildExternalEditorSessionActivateCommand(shellKind);
let attempts = 0;
const tryActivateInSession = () => {
if (cancelled) return;
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
if (pathActivated) return;
if (deps.isReadyForCommandInjection()) {
pathActivated = true;
deps.writeToSession(sessionId, activateCmd, { automated: true });
if (updated) {
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
}
return;
}
attempts += 1;
if (attempts < maxPollAttempts) {
pollTimer = scheduleTimer(tryActivateInSession, pollIntervalMs);
}
};
tryActivateInSession();
}).catch((err) => {
if (cancelled) return;
deps.onWarn?.('[Terminal] External editor session helper setup error:', err);
});
return () => {
cancelled = true;
if (pollTimer !== null) {
clearTimer(pollTimer);
pollTimer = null;
}
};
};
return { reset, sync };
}
export interface UseTerminalExternalEditorOptions {
sessionId: string;
status: string;
host: Pick<
Host,
'id' | 'hostname' | 'port' | 'username' | 'label' | 'protocol' | 'externalEditorShellIntegration'
>;
isLocalConnection: boolean;
isSerialConnection: boolean;
getBackendSessionId: () => string | null;
isVisible: () => boolean;
getFallbackCwd: () => string | undefined;
isReadyForCommandInjection: () => boolean;
setupOsc7Tracking?: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
focusTerminal: () => void;
onOpened: (editorLabel: string, remotePath: string) => void;
onOpenFailed: (message: string) => void;
formatFallbackOpenError: (editorLabel: string) => string;
onAutoSetupConfigured: (editorLabel: string) => void;
}
export function useTerminalExternalEditor(options: UseTerminalExternalEditorOptions) {
const liveRef = useRef(options);
liveRef.current = options;
const {
sessionId,
status,
host,
isLocalConnection,
isSerialConnection,
} = options;
const hostProtocol = host.protocol || 'ssh';
const [pendingExternalEditorRequest, setPendingExternalEditorRequest] =
useState<PendingExternalEditorRequest | null>(null);
const pendingExternalEditorRequestRef = useRef(pendingExternalEditorRequest);
pendingExternalEditorRequestRef.current = pendingExternalEditorRequest;
const lastExternalEditorLaunchRef = useRef<{ key: string; at: number } | null>(null);
const executeExternalEditorLaunch = useCallback((req: PendingExternalEditorRequest) => {
const launchKey = `${req.editorId}:${req.kind}:${req.remotePath}`;
const now = Date.now();
const prev = lastExternalEditorLaunchRef.current;
if (prev && prev.key === launchKey && now - prev.at < 800) {
return;
}
lastExternalEditorLaunchRef.current = { key: launchKey, at: now };
const current = liveRef.current;
void launchRemoteExternalEditor({
editorId: req.editorId,
host: {
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
},
remotePath: req.remotePath,
kind: req.kind,
sessionId: current.getBackendSessionId() ?? current.sessionId,
}).then(() => {
liveRef.current.onOpened(req.editorLabel, req.remotePath);
}).catch((err) => {
liveRef.current.onOpenFailed(
err instanceof Error
? err.message
: liveRef.current.formatFallbackOpenError(req.editorLabel),
);
});
}, []);
const handleOscExternalEditorRequest = useCallback((request: ExternalEditorOscRequest) => {
const current = liveRef.current;
// Strictly scope OSC 7337 remote editor opens to live SSH sessions on visible tabs.
if (current.isLocalConnection || current.isSerialConnection) return;
if (!current.isVisible()) return;
if ((current.host.protocol || 'ssh') !== 'ssh') return;
const settings = getExternalEditorSettingsSnapshot();
if (!settings.terminalRequestsEnabled) return;
const fallbackCwd = current.getFallbackCwd();
const normalized = validateAndNormalizeRemotePath(request.path, fallbackCwd);
if (!normalized.ok) {
logger.warn(
'[Terminal] Rejected invalid OSC 7337 remote path:',
'error' in normalized ? normalized.error : 'invalid path',
);
return;
}
const editorId: ExternalEditorPresetId = request.editorId ?? settings.defaultEditor;
const editorLabel = getExternalEditorLabel(editorId);
const hostIdentity = {
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
};
const trust = resolveExternalEditorTrustPolicy(settings, hostIdentity);
if (trust === 'deny') {
logger.debug('[Terminal] Ignored OSC 7337 external editor request (host denied)');
return;
}
const launchPayload: PendingExternalEditorRequest = {
editorId,
editorLabel,
remotePath: normalized.path,
kind: request.kind,
};
if (trust === 'allow') {
executeExternalEditorLaunch(launchPayload);
return;
}
// Untrusted host: show explicit inline confirmation prompt (do not overwrite an active prompt).
setPendingExternalEditorRequest((prev) => prev ?? launchPayload);
}, [executeExternalEditorLaunch]);
const handleExternalEditorPromptResponse = useCallback((decision: 'deny' | 'once' | 'always') => {
const currentRequest = pendingExternalEditorRequestRef.current;
pendingExternalEditorRequestRef.current = null;
setPendingExternalEditorRequest(null);
if (currentRequest) {
const current = liveRef.current;
if (decision === 'always') {
setExternalEditorHostTrust({
hostId: current.host.id,
hostname: current.host.hostname,
port: current.host.port,
username: current.host.username,
label: current.host.label,
}, 'allow');
executeExternalEditorLaunch(currentRequest);
} else if (decision === 'once') {
executeExternalEditorLaunch(currentRequest);
}
}
liveRef.current.focusTerminal();
}, [executeExternalEditorLaunch]);
// Session-scoped external editor shell commands: install standalone helpers into
// ~/.netcatty/bin over the silent exec channel (never modifying shell rc files)
// and prepend ~/.netcatty/bin to PATH once per connected terminal session.
const autoSetupConfig = useExternalEditorTerminalAutoSetupConfig();
const shouldEnableSessionCommands = shouldAutoSetupExternalEditorShell(
autoSetupConfig,
{ externalEditorShellIntegration: host.externalEditorShellIntegration },
);
const defaultExternalEditor = autoSetupConfig.defaultEditor;
const provisionerRef = useRef<ExternalEditorSessionProvisioner | null>(null);
if (!provisionerRef.current) {
provisionerRef.current = createExternalEditorSessionProvisioner({
setupExec: (activeSessionId, command) => {
const fn = liveRef.current.setupOsc7Tracking;
if (!fn) return Promise.resolve({ success: false, error: 'setupOsc7Tracking unavailable' });
return fn(activeSessionId, command);
},
writeToSession: (activeSessionId, data, opts) => {
liveRef.current.writeToSession(activeSessionId, data, opts);
},
getCurrentSessionId: () => liveRef.current.getBackendSessionId() ?? liveRef.current.sessionId,
isReadyForCommandInjection: () => liveRef.current.isReadyForCommandInjection(),
onConfigured: (editorLabel) => liveRef.current.onAutoSetupConfigured(editorLabel),
onWarn: (message, detail) => logger.warn(message, detail),
scheduleTimer: (fn, ms) => window.setTimeout(fn, ms) as unknown as ReturnType<typeof setTimeout>,
clearTimer: (handle) => window.clearTimeout(handle as unknown as number),
});
}
useEffect(() => {
const provisioner = provisionerRef.current;
if (!provisioner) return;
if (status !== 'connected') {
provisioner.reset();
return;
}
if (isLocalConnection || isSerialConnection) return;
if (hostProtocol !== 'ssh') return;
if (!shouldEnableSessionCommands) return;
if (!liveRef.current.setupOsc7Tracking) return;
const activeSessionId = liveRef.current.getBackendSessionId() ?? sessionId;
if (!activeSessionId) return;
return provisioner.sync({
sessionId: activeSessionId,
defaultEditor: defaultExternalEditor,
});
}, [
status,
isLocalConnection,
isSerialConnection,
hostProtocol,
shouldEnableSessionCommands,
defaultExternalEditor,
sessionId,
]);
return {
pendingExternalEditorRequest,
handleOscExternalEditorRequest,
handleExternalEditorPromptResponse,
};
}
+128 -1
View File
@@ -4,6 +4,8 @@ import { JSDOM } from 'jsdom';
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
@@ -30,9 +32,10 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
let model!: ReturnType<typeof useVaultNavConfig>;
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
let pluginsLoading = false;
let pluginsAvailable = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
return <div />;
}
@@ -83,6 +86,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
const coldRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
pluginsLoading = true;
pluginsAvailable = false;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -93,6 +97,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
// Plugins finish loading, but DB_PLUGIN was uninstalled.
activePluginIds = [MONITOR_PLUGIN];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -122,3 +127,125 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
dom.window.close();
}
});
test('useVaultNavConfig preserves saved plugin order when settled with pluginsAvailable=false and restores slots once plugins become available', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
});
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
configurable: true,
writable: true,
value: true,
});
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { useVaultNavConfig } = await import('./useVaultNavConfig');
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
let model!: ReturnType<typeof useVaultNavConfig>;
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
OFFICIAL_DB_PLUGIN,
OFFICIAL_MONITOR_PLUGIN,
];
let pluginsLoading = false;
let pluginsAvailable: boolean | undefined = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
return <div />;
}
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
await act(async () => {
model.reorder(OFFICIAL_MONITOR_PLUGIN, 'hosts', 'after');
model.setVisible('logs', false);
});
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.isHidden('logs'), true);
await act(async () => {
root.unmount();
});
const restartedRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
pluginsLoading = false;
pluginsAvailable = false;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
assert.equal(model.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN), false);
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(model.config.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), true);
const persistedUnavailable = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedUnavailable.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(persistedUnavailable.order.includes(OFFICIAL_DB_PLUGIN), true);
assert.deepEqual(persistedUnavailable.hidden, ['logs']);
pluginsAvailable = undefined;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
const persistedDefault = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedDefault.order[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(persistedDefault.order.includes(OFFICIAL_DB_PLUGIN), true);
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
restartedRoot.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
assert.equal(model.isHidden('logs'), true);
await act(async () => {
restartedRoot.unmount();
});
} finally {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});
+4 -1
View File
@@ -28,6 +28,8 @@ export interface UseVaultNavConfigOptions {
activePluginIds: readonly PluginVaultNavId[];
/** Pass true while plugin contributions are still loading on cold start. */
pluginsLoading?: boolean;
/** Pass true once plugin contributions are available from the plugin runtime. */
pluginsAvailable?: boolean;
}
export interface UseVaultNavConfigResult {
@@ -76,13 +78,14 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
export function useVaultNavConfig({
activePluginIds,
pluginsLoading = false,
pluginsAvailable = false,
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
const pluginKey = activePluginIds.join('\0');
const stablePluginIds = useMemo<PluginVaultNavId[]>(
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
[pluginKey],
);
const pruneMissingPlugins = !pluginsLoading;
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
const [config, setConfig] = useState<VaultNavConfig>(() =>
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
@@ -440,3 +440,43 @@ test('changed remote transcript resets the local native SDK thread before contin
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
delete (window as unknown as { netcatty?: unknown }).netcatty;
});
test('cloud apply keeps receiver workspaceNameSnapshot when workspace binding is unchanged and drops it on rebind', async () => {
const local: AISession = {
...session(),
id: 'ws-chat',
scope: { type: 'workspace', targetId: 'ws-1', hostIds: ['h-1'] },
workspaceNameSnapshot: 'Prod Cluster (this Mac)',
updatedAt: 10,
};
save([local]);
// Never uploaded to cloud.
const uploaded = await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined });
assert.equal(Object.hasOwn(uploaded.aiSessions?.[0] ?? {}, 'workspaceNameSnapshot'), false);
// Newer remote update on the same workspace (stripped by remote device, or even
// carrying a foreign snapshot that must be stripped on apply) keeps local name.
const remoteSameWs: AISession = {
...local,
updatedAt: 20,
title: 'Updated title from peer',
workspaceNameSnapshot: 'Peer stale name',
};
await applySyncPayload({ ...vault, aiSessions: [remoteSameWs], syncedAt: 20 }, { importVaultData: () => undefined });
const afterSameWs = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
assert.equal(afterSameWs?.title, 'Updated title from peer');
assert.equal(afterSameWs?.workspaceNameSnapshot, 'Prod Cluster (this Mac)');
// Newer remote update that rebinds to another workspace drops the old local name.
const remoteRebound: AISession = {
...local,
updatedAt: 30,
scope: { type: 'workspace', targetId: 'ws-2', hostIds: ['h-2'] },
workspaceNameSnapshot: undefined,
};
await applySyncPayload({ ...vault, aiSessions: [remoteRebound], syncedAt: 30 }, { importVaultData: () => undefined });
const afterRebound = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
assert.equal(afterRebound?.scope.targetId, 'ws-2');
assert.equal(afterRebound?.workspaceNameSnapshot, undefined);
});
+14 -10
View File
@@ -2422,13 +2422,17 @@ test('sync prepares header encryption once before importing and leaves input unc
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed });
});
test("SFTP default download folder stays device-local and is never synced", async () => {
const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR;
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
localStorage.clear();
localStorage.setItem(key, "/Users/me/server-files");
const payload = buildSyncPayload(vault());
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
});
for (const key of [
storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
storageKeys.STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
]) {
test(`SFTP download folder ${key} stays device-local and is never synced`, async () => {
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
localStorage.clear();
localStorage.setItem(key, "/Users/me/server-files");
const payload = buildSyncPayload(vault());
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
});
}
+277
View File
@@ -1,3 +1,265 @@
!ifndef BUILD_UNINSTALLER
Var /GLOBAL CreateDesktopShortcutPref
!endif
!macro customHeader
!ifndef BUILD_UNINSTALLER
!ifdef LANG_ENGLISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ENGLISH} "Create &desktop shortcut"
!endif
!ifdef LANG_SIMPCHINESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SIMPCHINESE} "创建桌面快捷方式(&D)"
!endif
!ifdef LANG_TRADCHINESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TRADCHINESE} "建立桌面捷徑(&D)"
!endif
!ifdef LANG_RUSSIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_RUSSIAN} "Создать ярлык на &рабочем столе"
!endif
!ifdef LANG_JAPANESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_JAPANESE} "デスクトップにショートカットを作成する(&D)"
!endif
!ifdef LANG_KOREAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_KOREAN} "바탕 화면에 바로 가기 만들기(&D)"
!endif
!ifdef LANG_GERMAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_GERMAN} "&Desktopverknüpfung erstellen"
!endif
!ifdef LANG_FRENCH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FRENCH} "Créer un raccourci sur le &bureau"
!endif
!ifdef LANG_SPANISHINTERNATIONAL
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SPANISHINTERNATIONAL} "Crear acceso directo en el &escritorio"
!endif
!ifdef LANG_ITALIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ITALIAN} "Crea collegamento sul &desktop"
!endif
!ifdef LANG_DUTCH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DUTCH} "&Bureaublad-snelkoppeling maken"
!endif
!ifdef LANG_DANISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DANISH} "Opret genvej på &skrivebordet"
!endif
!ifdef LANG_SWEDISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SWEDISH} "Skapa genväg på &skrivbordet"
!endif
!ifdef LANG_NORWEGIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_NORWEGIAN} "Opprett snarvei på &skrivebordet"
!endif
!ifdef LANG_FINNISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FINNISH} "Luo pikakuvake &työpöydälle"
!endif
!ifdef LANG_PORTUGUESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESE} "Criar atalho na &área de trabalho"
!endif
!ifdef LANG_PORTUGUESEBR
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESEBR} "Criar atalho na &Área de Trabalho"
!endif
!ifdef LANG_POLISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_POLISH} "Utwórz skrót na &pulpicie"
!endif
!ifdef LANG_UKRAINIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_UKRAINIAN} "Створити ярлик на &робочому столі"
!endif
!ifdef LANG_CZECH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_CZECH} "Vytvořit zástupce na &ploše"
!endif
!ifdef LANG_SLOVAK
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SLOVAK} "Vytvoriť odkaz na &ploche"
!endif
!ifdef LANG_HUNGARIAN
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_HUNGARIAN} "Parancsikon létrehozása az &asztalon"
!endif
!ifdef LANG_ARABIC
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ARABIC} "إنشاء اختصار على سطح ال&مكتب"
!endif
!ifdef LANG_TURKISH
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TURKISH} "&Masaüstü kısayolu oluştur"
!endif
!ifdef LANG_THAI
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_THAI} "สร้างทางลัดบน&เดสก์ท็อป"
!endif
!ifdef LANG_VIETNAMESE
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_VIETNAMESE} "Tạo lối tắt trên &màn hình nền"
!endif
; Determine whether the desktop shortcut should be checked/created.
; Must run before uninstallOldVersion deletes the old registry key or shortcut.
Function CaptureDesktopShortcutState
${if} ${isNoDesktopShortcut}
StrCpy $CreateDesktopShortcutPref "false"
Return
${endif}
!insertmacro setLinkVars
ReadRegStr $0 SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
${if} $0 == "false"
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
Return
${endif}
ReadRegStr $1 SHCTX "${INSTALL_REGISTRY_KEY}" InstallLocation
${if} $1 != ""
; Existing install: only preserve the shortcut if it still exists on the desktop.
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
Return
${endif}
; Migrating from per-user to all-users: inspect the previous per-user desktop shortcut.
${if} $installMode == "all"
ReadRegStr $2 HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation
${if} $2 != ""
ReadRegStr $3 HKCU "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
SetShellVarContext current
!insertmacro setLinkVars
${if} ${FileExists} "$newDesktopLink"
${orIf} ${FileExists} "$oldDesktopLink"
StrCpy $CreateDesktopShortcutPref "true"
${elseif} $3 == "false"
StrCpy $CreateDesktopShortcutPref "false"
${else}
StrCpy $CreateDesktopShortcutPref "false"
${endif}
SetShellVarContext all
!insertmacro setLinkVars
Return
${endif}
${endif}
; Fresh installation: default to creating the desktop shortcut (user can uncheck on finish page).
StrCpy $CreateDesktopShortcutPref "true"
FunctionEnd
Function InstFilesShowCaptureDesktopShortcut
Call CaptureDesktopShortcutState
FunctionEnd
!endif
!macroend
!macro ensureDesktopShortcut
${if} $appExe == ""
StrCpy $appExe "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
${endif}
${if} $newDesktopLink == ""
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
${endif}
${if} $oldDesktopLink != ""
${andIf} $oldDesktopLink != $newDesktopLink
${andIf} ${FileExists} "$oldDesktopLink"
Rename "$oldDesktopLink" "$newDesktopLink"
WinShell::UninstShortcut "$oldDesktopLink"
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${elseIfNot} ${FileExists} "$newDesktopLink"
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
ClearErrors
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
!macroend
!macro removeDesktopShortcut
${if} $newDesktopLink == ""
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
${endif}
${if} ${FileExists} "$newDesktopLink"
WinShell::UninstShortcut "$newDesktopLink"
Delete "$newDesktopLink"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
${if} $oldDesktopLink != ""
${andIf} $oldDesktopLink != $newDesktopLink
${andIf} ${FileExists} "$oldDesktopLink"
WinShell::UninstShortcut "$oldDesktopLink"
Delete "$oldDesktopLink"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
!macroend
!macro customPageAfterChangeDir
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstFilesShowCaptureDesktopShortcut
!macroend
!macro customFinishPage
!ifndef HIDE_RUN_AFTER_FINISH
Function StartApp
${if} ${isUpdated}
StrCpy $1 "--updated"
${else}
StrCpy $1 ""
${endif}
${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "$1"
FunctionEnd
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_FUNCTION "StartApp"
!endif
!define MUI_FINISHPAGE_SHOWREADME ""
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(CREATE_DESKTOP_SHORTCUT_TEXT)"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION "FinishDesktopShortcutNoop"
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
!define MUI_PAGE_CUSTOMFUNCTION_SHOW FinishPageShow
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE FinishPageLeave
!insertmacro MUI_PAGE_FINISH
Function FinishPageShow
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${ifNot} ${RebootFlag}
!endif
${if} $CreateDesktopShortcutPref == "true"
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_CHECKED} 0
${else}
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_UNCHECKED} 0
${endif}
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${endif}
!endif
FunctionEnd
Function FinishPageLeave
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
${if} ${RebootFlag}
${if} $CreateDesktopShortcutPref == "true"
!insertmacro ensureDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
${else}
!insertmacro removeDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
${endif}
Return
${endif}
!endif
SendMessage $mui.FinishPage.ShowReadme ${BM_GETCHECK} 0 0 $0
${if} $0 = ${BST_CHECKED}
StrCpy $CreateDesktopShortcutPref "true"
!insertmacro ensureDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
${else}
StrCpy $CreateDesktopShortcutPref "false"
!insertmacro removeDesktopShortcut
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
${endif}
FunctionEnd
Function FinishDesktopShortcutNoop
FunctionEnd
!macroend
!macro customInit
; #3946: external MCP hosts launch Netcatty.exe with ELECTRON_RUN_AS_NODE=1
; via netcatty-external-mcp.cmd. Those processes can outlive the host UI as
@@ -7,9 +269,17 @@
; and /T would terminate the installer itself. Ignore a missing process.
nsExec::ExecToLog "taskkill /F /IM Netcatty.exe"
Pop $0
Call CaptureDesktopShortcutState
!macroend
!macro customInstall
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "$CreateDesktopShortcutPref"
${if} ${Silent}
${andIf} $CreateDesktopShortcutPref == "true"
${andIfNot} ${isNoDesktopShortcut}
!insertmacro ensureDesktopShortcut
${endif}
; Open a selected folder in a new Netcatty local terminal.
; Args go after `--` so Electron/Chromium does not swallow them. Use
; `--open-terminal-path="%1."` so paths with spaces stay one token and drive
@@ -50,6 +320,13 @@
!macroend
!macro customUnInstall
; DO_NOT_CREATE_DESKTOP_SHORTCUT is set so electron-builder never auto-creates
; the desktop shortcut; remove an existing shortcut here on real uninstall.
${ifNot} ${isKeepShortcuts}
WinShell::UninstShortcut "$oldDesktopLink"
Delete "$oldDesktopLink"
${endif}
DeleteRegKey SHCTX "Software\Classes\Directory\shell\Netcatty"
DeleteRegKey SHCTX "Software\Classes\Directory\Background\shell\Netcatty"
DeleteRegKey SHCTX "Software\Classes\Netcatty.SSH"
+3
View File
@@ -59,6 +59,7 @@ interface AIChatPanelContentProps {
activeCompaction?: import('../application/state/useAgentCompactionUi').ActiveCompactionUi | null;
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
inputValue: string;
inputValueRevision?: number;
setInputValue: (value: string) => void;
handleSend: (textOverride?: string) => void;
handleSendQuickPrompt?: (promptText: string) => void;
@@ -171,6 +172,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
activeCompaction = null,
contextUsage = null,
inputValue,
inputValueRevision,
setInputValue,
handleSend,
handleSendQuickPrompt,
@@ -568,6 +570,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<ChatInput
parked={parked}
value={inputValue}
valueRevision={inputValueRevision}
onChange={setInputValue}
onSend={handleSend}
onSendQuickPrompt={handleSendQuickPrompt}
+49 -4
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import type { AISession } from '../infrastructure/ai/types';
import { useI18n } from '../application/i18n/I18nProvider';
import { cn } from '../lib/utils';
@@ -9,6 +9,7 @@ import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
// -------------------------------------------------------------------
@@ -52,6 +53,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
const { t } = useI18n();
const [view, setView] = useState<'scoped' | 'global'>('scoped');
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
const [searchQuery, setSearchQuery] = useState('');
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
@@ -70,6 +72,22 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
setRenderCount(SESSION_RENDER_BATCH);
}, [sessions, searchQuery]);
useEffect(() => {
if (view !== 'global' || !globalManager) {
setGlobalSelectionMode(false);
}
}, [view, globalManager]);
const selectionContextValue = useMemo(
() => ({
selectionMode: globalSelectionMode,
setSelectionMode: setGlobalSelectionMode,
}),
[globalSelectionMode],
);
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
const displayedSessions = filteredSessions.slice(0, renderCount);
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
@@ -132,7 +150,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
</div>
<div className="flex items-center gap-2">
{(onImportSessions || onExportSessions) && (
{hasHeaderMenu && (
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
<DropdownTrigger asChild>
<button
@@ -144,6 +162,31 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</button>
</DropdownTrigger>
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
{canSelectGlobalChats && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setHeaderMenuOpen(false);
setGlobalSelectionMode((prev) => !prev);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<CheckSquare
size={12}
className={cn(
'shrink-0',
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
)}
/>
<span>{t('ai.chat.managerToggleSelection')}</span>
</button>
{(onImportSessions || onExportSessions) && (
<div className="my-1 h-px bg-border/50" />
)}
</>
)}
{onImportSessions && (
<button
type="button"
@@ -184,7 +227,9 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</div>
</div>
{view === 'global' && globalManager ? (
globalManager
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
{globalManager}
</GlobalSessionSelectionContext.Provider>
) : (
<>
<div className="px-3 py-2 shrink-0 border-b border-border/30">
+62 -33
View File
@@ -14,6 +14,11 @@ import type {
ExternalAgentConfig,
} from '../infrastructure/ai/types';
import type { VaultNote } from '../domain/models';
import {
buildFallbackTitle,
canAutoTitleSession,
resolveCattyEffectiveModel,
} from '../domain/aiSessionTitle';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import {
DEFAULT_MAX_ITERATIONS,
@@ -294,6 +299,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
undoLastTurnInSession,
deleteSession,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -823,8 +830,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
showSessionView(scopeKey, sessionId);
}, [scopeKey, showSessionView]);
const [composerValueRevision, setComposerValueRevision] = useState(0);
const discardPendingComposerText = useCallback(() => {
pendingComposerTextRef.current = null;
if (currentDraftRef.current) {
currentDraftRef.current = { ...currentDraftRef.current, text: '' };
}
setComposerValueRevision((rev) => rev + 1);
}, []);
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
@@ -1038,26 +1051,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
[providers, activeProviderId],
);
const cattyAgentProvider = useMemo(() => {
const overrideId = agentProviderMap['catty'];
if (overrideId) {
const p = providers.find((cfg) => cfg.id === overrideId);
if (p) return p;
}
return activeProvider;
}, [agentProviderMap, providers, activeProvider]);
const cattyAgentModelId = useMemo(() => {
const trim = (s: string | undefined | null): string => (s ?? '').trim();
const overrideId = agentProviderMap['catty'];
const overrideProvider = overrideId
? providers.find((cfg) => cfg.id === overrideId)
: undefined;
if (overrideProvider) {
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
}
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
const { provider: cattyAgentProvider, modelId: cattyAgentModelId } = useMemo(
() => resolveCattyEffectiveModel({
providers,
activeProviderId,
activeModelId,
agentProviderMap,
agentModelMap,
}),
[providers, activeProviderId, activeModelId, agentProviderMap, agentModelMap],
);
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
@@ -1680,18 +1683,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}, [openSettingsWindow]);
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
/** Ref to always access latest sessions inside async send callbacks. */
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
/** Auto-title a session from the first user message if untitled. */
const autoTitleSession = useCallback((sessionId: string, text: string) => {
const s = sessionsRef.current.find(x => x.id === sessionId);
if (s && (!s.title || s.title === 'New Chat')) {
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
}
}, [updateSessionTitle]);
const buildExecutorContextForScope = useCallback((scope: {
type: 'terminal' | 'workspace' | 'global';
targetId?: string;
@@ -1875,7 +1870,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
let currentSession = currentSessionView ?? null;
if (isDraftMode) {
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
const createdSession = createSession(scope, sendAgentId);
const createdSession = createSession(scope, sendAgentId, scopeLabel);
sessionId = createdSession.id;
currentSession = createdSession;
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
@@ -1983,7 +1978,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
setStreamingForScope(sessionId, false);
abortControllersRef.current.delete(sessionId);
autoTitleSession(sessionId, titleText);
} else {
const toolScope = {
type: scopeType,
@@ -2005,12 +1999,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
terminalSessions,
webSearchConfig,
getExecutorContext: () => buildExecutorContextForScope(toolScope),
autoTitleSession,
// Title generation is triggered once, below, for both agent branches.
autoTitleSession: () => {},
selectedUserSkillSlugs: selectedSkillSlugs,
titleText,
pluginContext,
}, modelAttachments.length > 0 ? modelAttachments : undefined);
}
// Single title-generation trigger for both agent branches. Pass the
// signal explicitly: sendToCattyAgent's finally removes its controller.
if (autoTitleSession) {
void autoTitleSession(sessionId, titleText, abortController.signal);
} else {
const current = sessionsRef.current.find((s) => s.id === sessionId);
if (canAutoTitleSession(current)) {
updateSessionTitle(sessionId, buildFallbackTitle(titleText));
}
}
} finally {
setIsSending(false);
endSendForKey(sendGateKey);
@@ -2022,7 +2027,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
validateNoteMentions, loadCodexConfigModel,
isStreaming, isUndoingLastTurn, activeProvider, effectiveActiveProvider, effectiveActiveModelId, selectedCattyThinking, scopeKey, currentAgentId,
activeModelId, externalAgents,
createSession, addMessageToSession, updateMessageById, updateLastMessage,
createSession, addMessageToSession, updateMessageById, updateLastMessage, updateSessionTitle,
setStreamingForScope,
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
@@ -2430,6 +2435,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
deleteSession(sessionId);
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
// Regeneration lives in useAIState so it can reuse the maintainer's
// title-model resolution and atomic title-write helpers.
const handleManagerRegenerateTitle = useCallback((sessionId: string) => {
void regenerateSessionTitle?.(sessionId);
}, [regenerateSessionTitle]);
const handleManagerDeleteMany = useCallback(async (sessionIds: string[]) => {
for (const sessionId of sessionIds) {
if (abortControllersRef.current.has(sessionId) || streamingSessionIds.has(sessionId)) {
await stopStreamingForSession(sessionId);
}
// Each delete records an intentional tombstone so sync can propagate
// the removal (the "decrease" side of session-history sync).
deleteSession(sessionId);
}
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
const handleManagerExport = useCallback((sessionId: string) => {
void exportSessionsBackup?.([sessionId]).then((filePath) => {
if (filePath == null) {
@@ -2464,6 +2486,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onRebind={handleManagerRebind}
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
onExport={handleManagerExport}
/>
)
@@ -2483,6 +2507,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
handleManagerRebind,
handleRenameSession,
handleManagerDelete,
handleManagerDeleteMany,
handleManagerRegenerateTitle,
handleManagerExport,
onFocusAIScopeTarget,
]);
@@ -2556,6 +2582,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
contextUsage={contextUsage}
canCompact={canCompact}
inputValue={inputValue}
inputValueRevision={composerValueRevision}
setInputValue={setInputValue}
handleSend={handleSend}
handleSendQuickPrompt={handleSendQuickPrompt}
@@ -2666,6 +2693,8 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
'createSession',
'deleteSession',
'updateSessionTitle',
'autoTitleSession',
'regenerateSessionTitle',
'rebindSessionScope',
'exportSessionsBackup',
'importSessionsBackup',
+4 -1
View File
@@ -36,7 +36,7 @@ export interface AIChatSidePanelProps {
clearDraftForScope: (scopeKey: string) => void;
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
createSession: (scope: AISessionScope, agentId?: string) => AISession;
createSession: (scope: AISessionScope, agentId?: string, workspaceNameSnapshot?: string) => AISession;
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
undoLastTurnInSession?: (
sessionId: string,
@@ -44,6 +44,9 @@ export interface AIChatSidePanelProps {
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
deleteSession: (sessionId: string, scopeKey?: string) => void;
updateSessionTitle: (sessionId: string, title: string) => void;
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
/** Explicitly regenerate an existing chat title with the configured LLM. */
regenerateSessionTitle?: (sessionId: string) => void | Promise<void>;
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
+7 -3
View File
@@ -690,11 +690,15 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
if (!ensureSyncablePayload(payload)) return;
const result = await sync.syncToProvider(provider, payload, {
applyConvergentPayload: onApplyConvergentPayload,
// A per-provider button must sync only that provider: skip the
// convergent fan-out even when convergent mode is active.
// Auto-sync / top-bar Sync Now still use syncAllProviders.
forceSingleProvider: true,
});
// Convergent sync fans out to every provider. Even if the
// requested provider fails, another provider can verify a newer
// joined replica that must be applied before reporting the error.
// The selected provider may still carry a newer joined replica
// (e.g. written by another device); apply it locally before
// reporting the result. This is per-provider only now.
if (result.mergedPayload && !result.mergedPayloadApplied && onApplyPayload) {
const portableMerged = stripSyncPayloadEncryptedCredentials(result.mergedPayload);
await Promise.resolve(onApplyPayload(portableMerged));
@@ -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();
}
});
+5
View File
@@ -33,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);
+47 -24
View File
@@ -121,6 +121,7 @@ export const hasGroupSshFields = (c: Partial<GroupConfig>): boolean => {
return Boolean(
c.proxyProfileId ||
c.proxyConfig ||
c.directProxy === true ||
c.hostChain ||
c.startupCommand ||
c.startupCommandRunMode !== undefined,
@@ -350,23 +351,29 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
[form.proxyProfileId, proxyProfiles],
);
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
const hasMissingProxyProfile = Boolean(!form.directProxy && form.proxyProfileId && !selectedProxyProfile);
const hasProxyConfig = Boolean(
form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
form.directProxy || form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const proxySummaryType = form.directProxy
? t("hostDetails.proxy.direct")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = form.directProxy
? t("hostDetails.proxy.directHint")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = form.directProxy
? `${t("hostDetails.proxy.direct")} - ${t("hostDetails.proxy.directHint")}`
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const update = <K extends keyof GroupConfig>(key: K, value: GroupConfig[K] | undefined) => {
setForm((prev) => ({ ...prev, [key]: value }));
@@ -463,6 +470,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -479,6 +487,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -494,6 +503,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -513,6 +523,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -525,7 +536,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const updateProxyConfig = useCallback(
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
setForm((prev) => {
const { proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return {
...rest,
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
@@ -537,19 +548,26 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const clearProxyConfig = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return rest;
});
}, []);
const selectProxyProfile = useCallback((profileId: string | undefined) => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) return rest;
return { ...rest, proxyProfileId: profileId };
});
}, []);
const selectDirectProxy = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
return { ...rest, directProxy: true };
});
}, []);
// Chain helpers
const chainedHosts = useMemo(() => {
const ids = form.hostChain?.hostIds || [];
@@ -751,7 +769,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
setNameError(t("vault.groups.errors.invalidChars"));
return;
}
const newPath = parentGroup ? `${parentGroup}/${trimmedName}` : trimmedName;
if (newPath !== groupPath && groups.includes(newPath)) {
setNameError(t("vault.groups.errors.duplicatePath"));
@@ -772,7 +789,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const anyProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled || telnetEnabled;
const anyRoutingProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled;
const proxySave = anyProtocolEnabled
const proxySave = anyProtocolEnabled && !form.directProxy
? prepareProxyConfigForSave({
proxyConfig: form.proxyConfig,
proxyProfileId: form.proxyProfileId,
@@ -917,10 +934,14 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
}),
...(finalRdpConfig && { rdpConfig: finalRdpConfig }),
...(finalVncConfig && { vncConfig: finalVncConfig }),
...(anyProtocolEnabled && {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}),
...(anyProtocolEnabled && (
form.directProxy === true
? { directProxy: true }
: {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}
)),
...(anyRoutingProtocolEnabled && {
...(form.hostChain !== undefined && { hostChain: form.hostChain }),
}),
@@ -954,8 +975,10 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={form.proxyProfileId}
directProxy={form.directProxy}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
onSelectDirectProxy={selectDirectProxy}
onClearProxy={clearProxyConfig}
onBack={() => setActiveSubPanel("none")}
onCancel={onCancel}
+40 -1
View File
@@ -4,6 +4,7 @@ import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
import React from "react";
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
import { customThemeStore } from "../application/state/customThemeStore";
import { useExternalEditorSettings } from "../application/state/useExternalEditorSettings";
import { clearHostFontSizeOverride, clearHostThemeOverride } from "../domain/terminalAppearance";
import { resolveSshAgentToggleUpdate } from "../domain/sshAuth";
import { MAX_FONT_SIZE, MIN_FONT_SIZE } from "../infrastructure/config/fonts";
@@ -63,9 +64,11 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxySummaryType,
proxySummaryLabel,
proxySummaryTooltip,
displayDirectProxy = Boolean(form.directProxy),
proxyInherited = false,
clearProxyConfig,
}) => {
const { settings: externalEditorSettings } = useExternalEditorSettings();
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
@@ -549,6 +552,39 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{isSshView && (
<HostDetailsSettingRow
label={t("hostDetails.externalEditorShellIntegration")}
hint={t("hostDetails.externalEditorShellIntegration.desc")}
>
<Select
value={
form.externalEditorShellIntegration === true
? "enabled"
: form.externalEditorShellIntegration === false
? "disabled"
: "default"
}
onValueChange={(v) =>
update(
"externalEditorShellIntegration",
v === "enabled" ? true : v === "disabled" ? false : undefined,
)
}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
{`${t("hostDetails.backspaceBehavior.default")} (${externalEditorSettings.autoSetupShellIntegration ? t("common.enabled") : t("common.disabled")})`}
</SelectItem>
<SelectItem value="enabled">{t("common.enabled")}</SelectItem>
<SelectItem value="disabled">{t("common.disabled")}</SelectItem>
</SelectContent>
</Select>
</HostDetailsSettingRow>
)}
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
<>
<ToggleRow
@@ -784,7 +820,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
title={t("hostDetails.proxy")}
className="overflow-hidden"
>
{form.directProxy ? (
{displayDirectProxy ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<button
type="button"
@@ -796,8 +832,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
<span className="block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{t("hostDetails.proxy.directHint")}
{proxyInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</button>
{!proxyInherited && (
<Button
type="button"
variant="ghost"
@@ -808,6 +846,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<X size={14} />
</Button>
)}
</div>
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId || proxyInherited ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
@@ -691,6 +691,34 @@ test("HostDetailsPanel direct proxy hides inherited group proxy", () => {
assert.match(markup, /Direct \(no proxy\)/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel displays inherited group directProxy and hides global default proxy", () => {
const previous = getActiveGlobalDefaultProxyProfileId();
try {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
const markup = renderHostDetailsWithGroup(networkSshHost, {
directProxy: true,
});
assert.match(markup, /Direct \(no proxy\)/);
assert.match(markup, /Inherited from group/);
assert.doesNotMatch(markup, /Configure proxy/);
const overridden = renderHostDetailsWithGroup({
...networkSshHost,
proxyConfig: { type: "http", host: "host-proxy.example.com", port: 9090 },
}, {
directProxy: true,
});
assert.match(overridden, /host-proxy\.example\.com/);
assert.doesNotMatch(overridden, /Direct \(no proxy\)/);
assert.doesNotMatch(overridden, /Inherited from group/);
} finally {
publishActiveGlobalDefaultProxyProfileId(previous);
}
});
test("HostDetailsPanel displays inherited group jump hosts", () => {
+6 -3
View File
@@ -517,8 +517,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasHostProxyOverride = form.directProxy === true
|| form.proxyProfileId !== undefined
|| form.proxyConfig !== undefined;
const displayDirectProxy = form.directProxy === true
|| (!hasHostProxyOverride && effectiveAuthHost.directProxy === true);
const displayProxyProfileId = resolveDisplayProxyProfileId(form, effectiveAuthHost.proxyProfileId);
const displayProxyConfig = form.directProxy
const displayProxyConfig = displayDirectProxy
? undefined
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
const selectedProxyProfile = useMemo(
@@ -527,7 +529,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
displayDirectProxy || displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
@@ -1518,7 +1520,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={displayProxyProfileId}
directProxy={form.directProxy}
directProxy={displayDirectProxy}
allowClear={hasHostProxyOverride}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
@@ -1902,6 +1904,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxySummaryType={proxySummaryType}
proxySummaryLabel={proxySummaryLabel}
proxySummaryTooltip={proxySummaryTooltip}
displayDirectProxy={displayDirectProxy}
proxyInherited={proxyInherited}
clearProxyConfig={clearProxyConfig}
/>
+37 -8
View File
@@ -2,6 +2,11 @@ import React from "react";
import { ChevronRight, Info } from "lucide-react";
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
import { sanitizeCredentialValue } from "../domain/credentials";
import {
getExportablePublicKey,
hasExportablePublicKey,
isKeychainExportDisabled,
} from "../domain/keychainExport";
import { hasBridgeSshCredentials, resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../domain/sshAuth";
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
import { connectionTotpFields } from "../domain/totpConfig";
@@ -41,6 +46,15 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
onSaveHost,
closePanel,
}) => {
const hasPublicKey = hasExportablePublicKey(panel.key?.publicKey);
const exportDisabled = isKeychainExportDisabled({
exportHost,
exportLocation,
exportFilename,
publicKey: panel.key?.publicKey,
isExporting,
});
return (
<>
{/* Key info card */}
@@ -159,17 +173,32 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
</CollapsibleContent>
</Collapsible>
{!hasPublicKey && (
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
<Info
size={14}
className="mt-0.5 text-muted-foreground shrink-0"
/>
<p className="text-xs text-muted-foreground">
{t("keychain.export.missingPublicKeyNote")}
</p>
</div>
)}
{/* Export button */}
<Button
className="w-full h-11"
disabled={
!exportHost ||
!exportLocation ||
!exportFilename ||
isExporting
}
disabled={exportDisabled}
onClick={async () => {
if (!exportHost || !panel.key.publicKey) return;
if (!exportHost) return;
const publicKey = getExportablePublicKey(panel.key?.publicKey);
if (!publicKey) {
toast.error(
t("keychain.export.missingPublicKey"),
t("keychain.export.failedTitle"),
);
return;
}
setIsExporting(true);
@@ -216,7 +245,7 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
}
// Escape the public key for shell (single quotes, escape existing quotes)
const escapedPublicKey = panel.key.publicKey.replace(
const escapedPublicKey = publicKey.replace(
/'/g,
"'\\''",
);
+93 -1
View File
@@ -73,8 +73,12 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
assert.equal(opens.length, 2);
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
await act(async () => { selectSection('hosts'); await settle(); });
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
} finally {
@@ -82,3 +86,91 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', '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 Window] });
}
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
const { act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
const { activeTabStore } = await import('../application/state/activeTabStore');
const { I18nProvider } = await import('../application/i18n/I18nProvider');
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
let changed: (() => void) | undefined;
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
Object.assign(dom.window, { netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return snapshot; },
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
onHostDrawnPluginViewUpdate() { return () => {}; },
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
async closeHostDrawnPluginView(id: string) { closes.push(id); },
} });
function Fixture() {
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
const model = usePluginVaultPages({ locale: 'en', section, select });
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
}
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
try {
activeTabStore.setActiveTabId('vault');
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
await act(async () => {
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
await import('./plugins/PluginHostDrawnPage');
await settle();
});
assert.equal(opens.length, 1);
assert.ok(document.querySelector('[data-plugin-vault-page]'));
// Session fails while plugin contribution remains active.
await act(async () => {
for (const listener of listeners) {
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
}
await settle();
});
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
assert.ok(alert, 'renders in-page error alert');
assert.equal(alert!.textContent, 'The plugin page failed to render.');
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
.find((btn) => btn.textContent === 'Retry');
assert.ok(retryButton, 'renders Retry control');
await act(async () => {
retryButton!.click();
await settle();
});
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
// Removing the contribution still falls back to Hosts.
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
await act(async () => { await settle(); });
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
} finally {
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
+12
View File
@@ -226,3 +226,15 @@ test("ProxyPanel offers keychain identities for HTTP and SOCKS5 proxy credential
assert.match(markup, /Proxy login/);
assert.match(markup, /proxy-user/);
});
test("ProxyPanel shows saved proxy selector and enables saving without profiles when directProxy is selected", () => {
const markup = renderPanel({
directProxy: true,
onSelectDirectProxy: () => {},
});
assert.match(markup, /Saved proxy/);
assert.match(markup, /Remove Proxy/);
assert.doesNotMatch(markup, /Proxy host/);
assert.doesNotMatch(markup, /disabled=""/);
});
+8
View File
@@ -258,6 +258,12 @@ const SettingsAITabContainer: React.FC = () => {
setQuickMessages={aiState.setQuickMessages}
showTerminalSelectionAIAction={aiState.showTerminalSelectionAIAction}
setShowTerminalSelectionAIAction={aiState.setShowTerminalSelectionAIAction}
autoLlmTitle={aiState.autoLlmTitle}
setAutoLlmTitle={aiState.setAutoLlmTitle}
titleModel={aiState.titleModel}
setTitleModel={aiState.setTitleModel}
agentProviderMap={aiState.agentProviderMap}
agentModelMap={aiState.agentModelMap}
/>
</AITabErrorBoundary>
);
@@ -581,6 +587,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
setShowSftpTab={settings.setShowSftpTab}
showHostTreeSidebar={settings.showHostTreeSidebar}
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
removeTopTabsDragArea={settings.removeTopTabsDragArea}
setRemoveTopTabsDragArea={settings.setRemoveTopTabsDragArea}
windowOpacity={settings.windowOpacity}
setWindowOpacity={settings.setWindowOpacity}
windowBackgroundBlur={settings.windowBackgroundBlur}
+30 -2
View File
@@ -1,4 +1,5 @@
import { terminalCwdStore } from '../application/state/terminalCwdStore';
import { useTerminalExternalEditor } from '../application/state/useTerminalExternalEditor';
import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession';
import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
@@ -1411,6 +1412,32 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const osc52ReadResolverRef = useRef<((allowed: boolean) => void) | null>(null);
const [osc7SetupOpen, setOsc7SetupOpen] = useState(false);
const [osc7SetupRunning, setOsc7SetupRunning] = useState(false);
const {
pendingExternalEditorRequest,
handleOscExternalEditorRequest,
handleExternalEditorPromptResponse,
} = useTerminalExternalEditor({
sessionId,
status,
host,
isLocalConnection,
isSerialConnection,
getBackendSessionId: () => sessionRef.current ?? sessionId,
isVisible: () => isVisibleRef.current,
getFallbackCwd: () => terminalCwdTracker.getRendererCwd() ?? knownCwdRef.current ?? undefined,
isReadyForCommandInjection: () => isTerminalReadyForCommandInjection(sessionId),
setupOsc7Tracking: terminalBackend.setupOsc7Tracking,
writeToSession: terminalBackend.writeToSession,
focusTerminal: () => termRef.current?.focus(),
onOpened: (editor, path) =>
toast.success(t("terminal.externalEditor.opened", { editor, path })),
onOpenFailed: (message) => toast.error(message),
formatFallbackOpenError: (editor) =>
t("terminal.externalEditor.failed", { editor }),
onAutoSetupConfigured: (editor) =>
toast.success(t("terminal.externalEditor.autoSetupConfigured", { editor })),
});
const handleOsc52ReadRequest = useCallback((): Promise<boolean> => {
// Reject if terminal is not visible (background tab) — user can't see the prompt
if (!isVisibleRef.current) return Promise.resolve(false);
@@ -4812,6 +4839,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
});
},
onOsc52ReadRequest: handleOsc52ReadRequest,
onOscExternalEditorRequest: handleOscExternalEditorRequest,
onAutocompleteKeyEvent: (e: KeyboardEvent) => autocompleteKeyEventRef.current?.(e) ?? true,
onAutocompleteInput: (data: string) => autocompleteInputRef.current?.(data),
onAutocompleteReposition: () => autocompleteRepositionRef.current?.(),
@@ -5078,11 +5106,11 @@ const TerminalComponent: React.FC<TerminalProps> = ({
onWake: wakeFromHibernateRuntime,
});
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleOscExternalEditorRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
return (
<>
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleExternalEditorPromptResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, pendingExternalEditorRequest, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
<ScriptExecutionOverlay
run={activeScriptRun}
onPause={() => { void pauseScriptRun(activeScriptRun.runId); }}
+88 -57
View File
@@ -137,8 +137,10 @@ import {
} from '../domain/sidePanelLayout';
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
import {
isPaneMagnificationSelectionValid,
canMagnifyPaneSurface,
pruneMagnifiedPanesByTab,
resolvePaneMagnificationCandidate,
setTabMagnifiedPane,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../domain/paneMagnification';
@@ -318,12 +320,11 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onRemoveSessionFromWorkspace,
}) => {
const { t } = useI18n();
const [magnifiedPane, setMagnifiedPane] = useState<{
tabId: string;
target: PaneMagnificationTarget;
} | null>(null);
const magnifiedPaneRef = useRef(magnifiedPane);
magnifiedPaneRef.current = magnifiedPane;
const [magnifiedPanesByTab, setMagnifiedPanesByTab] = useState<
ReadonlyMap<string, PaneMagnificationTarget>
>(() => new Map());
const magnifiedPanesByTabRef = useRef(magnifiedPanesByTab);
magnifiedPanesByTabRef.current = magnifiedPanesByTab;
const lastInteractedPaneRef = useRef<Map<string, PaneMagnificationTarget>>(new Map());
// Side panel state must be initialized before any callbacks reference its
// setters or refs in their dependency arrays.
@@ -345,8 +346,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}, [sessions]);
useEffect(() => {
setMagnifiedPane((current) => {
if (!current) return current;
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
const terminalPanes = sessions.map((session) => ({
tabId: session.workspaceId ?? session.id,
sessionId: session.id,
@@ -354,9 +355,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const sidePanelPanes = Array.from(sidePanelLayouts.entries()).flatMap(([tabId, layout]) => (
collectSidePanelPanes(layout.root).map((pane) => ({ tabId, paneId: pane.id }))
));
return isPaneMagnificationSelectionValid(current, terminalPanes, sidePanelPanes)
? current
: null;
return pruneMagnifiedPanesByTab(current, terminalPanes, sidePanelPanes);
});
}, [sessions, sidePanelLayouts]);
const terminalRendererCwdBySessionRef = useRef<Map<string, string>>(new Map());
@@ -475,11 +474,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
// Stable callback references for Terminal components
const handleCloseSession = useCallback((sessionId: string) => {
setMagnifiedPane((current) => (
current?.target.kind === 'terminal' && current.target.sessionId === sessionId
? null
: current
));
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
let changed = false;
const next = new Map(current);
for (const [tabId, target] of next) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
next.delete(tabId);
changed = true;
}
}
return changed ? next : current;
});
for (const [tabId, target] of lastInteractedPaneRef.current) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
lastInteractedPaneRef.current.delete(tabId);
@@ -1491,6 +1497,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!shouldProbeCommandCwd({
restoreTerminalCwd,
visibleSftpHost,
latestVisibleSftpHost: visibleSftpHost
? hostsRef.current.find((host) => host.id === visibleSftpHost.id)
: undefined,
sessionHost,
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
@@ -1773,9 +1782,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleCloseSidePanel = useCallback(() => {
const activeTabId = activeTabIdRef.current;
if (!activeTabId) return;
setMagnifiedPane((current) => (
current?.tabId === activeTabId && current.target.kind === 'side-panel'
? null
setMagnifiedPanesByTab((current) => (
current.get(activeTabId)?.kind === 'side-panel'
? setTabMagnifiedPane(current, activeTabId, null)
: current
));
const sessionIdToRefocus = getActiveTerminalSessionId();
@@ -1906,14 +1915,27 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleMagnifyTerminalPane = useCallback((tabId: string, sessionId: string) => {
const target: PaneMagnificationTarget = { kind: 'terminal', sessionId };
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'terminal'
&& current.target.sessionId === sessionId
? null
: { tabId, target }
));
}, []);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'terminal' && existing.sessionId === sessionId) {
return setTabMagnifiedPane(current, tabId, null);
}
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
candidate.id === tabId && !candidate.workspaceId
));
const terminalCount = workspaceSessionIds.length > 0
? workspaceSessionIds.length
: standaloneSession ? 1 : 0;
const layout = sidePanelLayoutsRef.current.get(tabId);
const sidePanelCount = layout ? collectSidePanelPanes(layout.root).length : 0;
if (!canMagnifyPaneSurface(terminalCount, sidePanelCount)) {
return current;
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleMagnifySidePanelPane = useCallback((paneId: string) => {
const tabId = activeTabIdRef.current;
@@ -1929,18 +1951,19 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
tool: pane.tool,
};
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: { tabId, target }
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'side-panel' && existing.paneId === paneId) {
return setTabMagnifiedPane(current, tabId, null);
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleRestoreMagnifiedPane = useCallback(() => {
const tabId = activeTabIdRef.current;
setMagnifiedPane((current) => current?.tabId === tabId ? null : current);
if (!tabId) return;
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, tabId, null));
}, []);
useEffect(() => {
@@ -1949,7 +1972,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const tabId = activeTabStore.getActiveTabId();
if (!tabId) return null;
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const hasCurrentMagnification = magnifiedPaneRef.current?.tabId === tabId;
const currentTarget = magnifiedPanesByTabRef.current.get(tabId);
const hasCurrentMagnification = !!currentTarget;
if (workspace?.viewMode === 'focus' && !hasCurrentMagnification) return null;
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
@@ -1971,7 +1995,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
? [focusedSidePanelPane, ...sidePanelPanes.filter((pane) => pane !== focusedSidePanelPane)]
: sidePanelPanes,
lastTarget: lastInteractedPaneRef.current.get(tabId),
current: magnifiedPaneRef.current,
current: currentTarget ? { tabId, target: currentTarget } : null,
});
return candidate ? { tabId, ...candidate } : null;
};
@@ -1983,19 +2007,23 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
focus: () => {
const target = getTarget();
if (!target || target.focused) return false;
setMagnifiedPane({ tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, target.target));
return true;
},
restore: () => {
const target = getTarget();
if (!target?.focused) return false;
setMagnifiedPane(null);
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, null));
return true;
},
toggle: () => {
const target = getTarget();
if (!target) return false;
setMagnifiedPane(target.focused ? null : { tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(
current,
target.tabId,
target.focused ? null : target.target,
));
return true;
},
};
@@ -2029,13 +2057,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const closingPane = layout
? collectSidePanelPanes(layout.root).find((pane) => pane.id === paneId)
: undefined;
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
const closesWholePanel = closeSidePanelPaneForTab(tabId, paneId);
if (closesWholePanel) {
handleCloseSidePanel();
@@ -2063,8 +2090,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const layout = sidePanelLayoutsRef.current.get(tabId);
const pane = layout && collectSidePanelPanes(layout.root).find((item) => item.id === paneId);
if (pane?.tool !== expectedTool) return;
setMagnifiedPane((current) => current?.tabId === tabId && current.target.kind === 'side-panel'
&& current.target.paneId === paneId ? null : current);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
closeSidePanelPaneForTab(tabId, paneId);
}, [closeSidePanelPaneForTab, sidePanelLayoutsRef]);
@@ -2151,12 +2182,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false;
tabId = terminal.id;
}
setMagnifiedPane((current) => (
current?.tabId === tabId
&& !(current.target.kind === 'side-panel' && current.target.tool === 'ai')
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing && !(existing.kind === 'side-panel' && existing.tool === 'ai')
? setTabMagnifiedPane(current, tabId, null)
: current;
});
activeTabStore.setActiveTabId(tabId);
if (prepareSidePanelTool(tabId, 'ai')) {
startTransition(() => {
@@ -2886,7 +2917,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
lastSidePanelTabRef,
mountedAiTabIds: aiMountedTabIds,
mountedSftpTabIds,
magnifiedPane,
magnifiedPanesByTab,
notesMountedTabIds,
browserMountedTabIds,
notesOpenNoteByTab,
+10 -2
View File
@@ -217,6 +217,7 @@ interface TopTabsProps {
tabInsertionTarget?: { tabId: string; position: 'before' | 'after'; additionalTabIds?: readonly string[] },
) => void;
onAppendHostToWorkspace?: (workspaceId: string, hostId: string) => void;
onRequestAddToWorkspace?: (workspaceId: string) => void;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
switchTabKeyBinding: Pick<KeyBinding, 'mac' | 'pc'> | null;
@@ -270,6 +271,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
onReorderTabs,
onRemoveSessionFromWorkspace,
onAppendHostToWorkspace,
onRequestAddToWorkspace,
showSftpTab,
showHostTreeSidebar,
switchTabKeyBinding,
@@ -288,6 +290,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
const {
hotkeyScheme,
showTabNumberBadges,
removeTopTabsDragArea,
shellOnlyTabNumberShortcuts,
} = useSettingsChromeStore();
const switchTabKey = hotkeyScheme === 'mac'
@@ -1031,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
onTabDrop={handleTabDrop}
onRenameWorkspace={onRenameWorkspace}
onCopyWorkspace={onCopyWorkspace}
onRequestAddToWorkspace={onRequestAddToWorkspace}
onCloseWorkspace={onCloseWorkspace}
onDetachSessionFromWorkspace={handleDetachSessionFromWorkspace}
renderBulkCloseItems={renderBulkCloseItems}
@@ -1087,6 +1091,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
<div
data-top-tabs-root
data-section="top-tabs"
data-remove-top-tabs-drag-area={removeTopTabsDragArea ? 'true' : undefined}
className="relative w-full bg-secondary app-drag"
style={{
...dragRegionNoSelect,
@@ -1099,9 +1104,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
tabsContainerRef={tabsContainerRef}
updateScrollState={updateScrollState}
/>
{/* Always-on drag stripe so the window can be moved even when tabs fill the bar */}
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
{!removeTopTabsDragArea && (
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
)}
<div
data-section="top-tabs-toolbar-row"
className="h-9 flex items-end gap-0 app-drag overflow-visible"
style={{
...dragRegionStyle,
@@ -1387,6 +1394,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
prev.onEditHost === next.onEditHost &&
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
prev.onRequestAddToWorkspace === next.onRequestAddToWorkspace &&
prev.onCopyWorkspace === next.onCopyWorkspace &&
prev.onOpenSettings === next.onOpenSettings &&
prev.onLockApp === next.onLockApp &&
+1
View File
@@ -394,6 +394,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
const vaultNavConfig = useVaultNavConfig({
activePluginIds: activePluginNavIds,
pluginsLoading: pluginVault.contributions.loading,
pluginsAvailable: pluginVault.contributions.available,
});
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
useEffect(() => {
+14
View File
@@ -412,3 +412,17 @@ test('renders vault note attachment chips with the note title', () => {
assert.match(source, /file\.vaultNoteId \? \(/);
assert.match(source, /\{file\.vaultNoteTitle \|\| file\.filename\}/);
});
test('valueRevision clears the uncontrolled textarea even when value stays empty across renders', () => {
const chatInputSource = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8');
const sidePanelSource = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
const contentSource = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
assert.match(chatInputSource, /valueRevision\?: number/);
assert.match(chatInputSource, /prev\.valueRevision === next\.valueRevision/);
assert.match(chatInputSource, /const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
assert.match(chatInputSource, /if \(!revisionChanged && value === pushedParentTextRef\.current\) return/);
assert.match(sidePanelSource, /setComposerValueRevision\(\(rev\) => rev \+ 1\)/);
assert.match(sidePanelSource, /inputValueRevision=\{composerValueRevision\}/);
assert.match(contentSource, /valueRevision=\{inputValueRevision\}/);
});
+13 -2
View File
@@ -207,6 +207,12 @@ const ComposerSendUi = React.memo(function ComposerSendUi({
interface ChatInputProps {
value: string;
/**
* Monotonic revision bumped by the parent whenever an authoritative reset
* (e.g. post-send draft clear) must be applied to the uncontrolled textarea
* even when `value` stayed equal across renders (such as `""` -> `""`).
*/
valueRevision?: number;
onChange: (value: string) => void;
onSend: (textOverride?: string) => void;
onCompact?: () => void;
@@ -303,6 +309,7 @@ interface ChatInputProps {
const ChatInput: React.FC<ChatInputProps> = ({
value,
valueRevision = 0,
onChange,
onSend,
onCompact,
@@ -548,15 +555,18 @@ const ChatInput: React.FC<ChatInputProps> = ({
textareaRef.current?.value ?? composerTextRef.current
), []);
const lastValueRevisionRef = useRef(valueRevision);
useEffect(() => {
if (value === pushedParentTextRef.current) return;
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
lastValueRevisionRef.current = valueRevision;
if (!revisionChanged && value === pushedParentTextRef.current) return;
pushedParentTextRef.current = value;
composerTextRef.current = value;
if (textareaRef.current && textareaRef.current.value !== value) {
textareaRef.current.value = value;
}
syncHasComposerText(value);
}, [syncHasComposerText, value]);
}, [syncHasComposerText, value, valueRevision]);
const commitComposerText = useCallback((next: string) => {
composerTextRef.current = next;
@@ -1977,6 +1987,7 @@ function contextUsageEqual(
function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boolean {
return (
prev.value === next.value
&& prev.valueRevision === next.valueRevision
&& prev.onChange === next.onChange
&& prev.onSend === next.onSend
&& prev.onCompact === next.onCompact
@@ -52,6 +52,8 @@ function baseProps() {
onRebind: (_sessionId: string, _target: { type: string; targetId: string; hostIds?: string[] }) => {},
onRename: undefined as ((_sessionId: string, _title: string) => void) | undefined,
onDelete: (_sessionId: string) => {},
onDeleteMany: undefined as ((_ids: string[]) => void) | undefined,
onRegenerateTitle: undefined as ((_sessionId: string) => void) | undefined,
onExport: (_sessionId: string) => {},
};
}
@@ -542,3 +544,185 @@ test("clicking an active-elsewhere chat falls back to opening locally when focus
dom.cleanup();
}
});
test("subtitle styling keeps agent label emphasized and message count normal when scopeLabel is empty", async () => {
const dom = installDomEnvironment();
try {
const props = baseProps();
props.sessions = [
makeSession({ id: "no-scope-label", title: "Orphan chat", scope: { type: "terminal", targetId: "t-gone" } }),
];
const renderer = await renderManager(dom, props);
const row = rows(renderer)[0];
const spans = Array.from(row.querySelectorAll("span")).filter((el) => !el.getAttribute("aria-hidden"));
const agentSpan = spans.find((el) => el.textContent === "Catty Agent");
const countSpan = spans.find((el) => (el.textContent ?? "").includes("1"));
assert.ok(agentSpan?.className.includes("font-medium"));
assert.ok(!agentSpan?.className.includes("truncate"));
assert.ok(countSpan);
assert.ok(!countSpan.className.includes("font-medium"));
} finally {
dom.cleanup();
}
});
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
const dom = installDomEnvironment();
const restoreGlobals = installRadixGlobals(dom);
try {
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const renderer = await createDomRenderer(dom.document);
const props = baseProps();
props.sessions = [
makeSession({ id: "s-a", title: "A" }),
makeSession({ id: "s-b", title: "B" }),
];
const deletedMany: string[][] = [];
const regenerated: string[] = [];
const activated: string[] = [];
props.onDeleteMany = (ids) => deletedMany.push(ids);
props.onRegenerateTitle = (id) => regenerated.push(id);
props.onSelect = (id) => activated.push(id);
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<SessionHistoryDrawer
sessions={props.sessions}
activeSessionId="s-a"
onSelect={() => {}}
onDelete={() => {}}
onExportSessions={() => {}}
onClose={() => {}}
globalManager={<GlobalAIChatSessionManager {...props} />}
/>
</TooltipProvider>
</I18nProvider>,
);
const openHeaderMenu = async () => {
const trigger = renderer.container.querySelector<HTMLButtonElement>(
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
);
assert.ok(trigger, "drawer overflow trigger present");
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
};
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
await openHeaderMenu();
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
// Close header menu before switching tabs.
await openHeaderMenu();
// Switch to the "All chats" tab.
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
// Search/filter bar must not contain an inline selection toggle button.
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
null,
"no standalone selection button in filter bar",
);
// Trigger selection mode from the drawer's top-right overflow menu.
await openHeaderMenu();
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.ok(selectItem, "Select chats menu item present on All chats tab");
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection action bar opens",
);
// Clicking Cancel exits selection mode cleanly.
const cancelBtn = Array.from(
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.trim() === t("common.cancel"));
assert.ok(cancelBtn, "Cancel button present in selection bar");
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Cancel exits selection mode",
);
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
await openHeaderMenu();
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Escape exits selection mode",
);
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
await openHeaderMenu();
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection bar open before tab switch",
);
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"switching away from All chats resets selection mode",
);
await openHeaderMenu();
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
assert.deepEqual(activated, []);
const bulkRegen = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
assert.ok(bulkRegen, "bulk regenerate button present");
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
// Bulk delete is confirm-gated.
const bulkDelete = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("common.delete")));
assert.ok(bulkDelete, "bulk delete button present");
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"selection mode exits after confirmed bulk delete",
);
} finally {
restoreGlobals();
dom.cleanup();
}
});
+268 -61
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Download, FolderInput, MoreHorizontal, Pencil, Search, Trash2, X } from 'lucide-react';
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
import { useI18n } from '../../application/i18n/I18nProvider';
import { cn } from '../../lib/utils';
@@ -15,6 +15,7 @@ import {
} from '../ui/select';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
import {
buildGlobalManagerRows,
@@ -56,7 +57,13 @@ interface GlobalAIChatSessionManagerProps {
onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void;
onRename?: (sessionId: string, title: string) => void;
onDelete: (sessionId: string) => void;
onDeleteMany?: (sessionIds: string[]) => void;
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
onRegenerateTitle?: (sessionId: string) => void;
onExport: (sessionId: string) => void;
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
selectionMode?: boolean;
onSelectionModeChange?: (active: boolean) => void;
}
const MANAGER_RENDER_BATCH = 80;
@@ -78,19 +85,44 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
onRebind,
onRename,
onDelete,
onDeleteMany,
onRegenerateTitle,
onExport,
selectionMode: controlledSelectionMode,
onSelectionModeChange,
}) => {
const { t } = useI18n();
const selectionContext = useContext(GlobalSessionSelectionContext);
const [searchQuery, setSearchQuery] = useState('');
const [agentFilter, setAgentFilter] = useState<string>('all');
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
const [moveSession, setMoveSession] = useState<AISession | null>(null);
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [renameDraft, setRenameDraft] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
const selectionMode =
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
const setSelectionMode = useCallback(
(active: boolean) => {
if (controlledSelectionMode !== undefined) {
onSelectionModeChange?.(active);
} else if (selectionContext) {
selectionContext.setSelectionMode(active);
onSelectionModeChange?.(active);
} else {
setUncontrolledSelectionMode(active);
onSelectionModeChange?.(active);
}
},
[controlledSelectionMode, onSelectionModeChange, selectionContext],
);
const rows = useMemo(
() => buildGlobalManagerRows({
sessions,
@@ -129,6 +161,26 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
if (renamingSessionId) renameInputRef.current?.focus();
}, [renamingSessionId]);
useEffect(() => {
if (!selectionMode) {
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}
}, [selectionMode]);
const rowSessionIds = useMemo(
() => new Set(rows.map((row) => row.session.id)),
[rows],
);
const activeSelectedIds = useMemo(() => {
if (selectedIds.size === 0) return selectedIds;
const next = new Set<string>();
selectedIds.forEach((id) => {
if (rowSessionIds.has(id)) next.add(id);
});
return next;
}, [selectedIds, rowSessionIds]);
const displayedRows = filteredRows.slice(0, renderCount);
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
@@ -152,6 +204,50 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
setRenameDraft('');
};
const toggleSelected = (sessionId: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(sessionId)) next.delete(sessionId); else next.add(sessionId);
return next;
});
};
const exitSelectionMode = useCallback(() => {
setSelectionMode(false);
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}, [setSelectionMode]);
useEffect(() => {
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
exitSelectionMode();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
const toggleSelectAll = () => {
const visibleIds = displayedRows.map((row) => row.session.id);
setSelectedIds((prev) => {
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => prev.has(id));
return allSelected ? new Set() : new Set(visibleIds);
});
};
const commitBulkDelete = () => {
if (activeSelectedIds.size === 0) return;
const ids = [...activeSelectedIds];
if (onDeleteMany) onDeleteMany(ids);
else ids.forEach((id) => onDelete(id));
exitSelectionMode();
};
const commitBulkRegenerate = () => {
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
};
const getOtherMoveTargets = (session: AISession) =>
rebindTargets.filter(
(target) =>
@@ -236,6 +332,54 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</Select>
)}
</div>
{selectionMode && (
<div
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
data-section="ai-global-session-selection-bar"
>
<button
type="button"
onClick={toggleSelectAll}
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
>
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
{t('ai.chat.managerSelectAll')}
</button>
<span className="text-muted-foreground/60 whitespace-nowrap">
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
</span>
<div className="ml-auto flex items-center gap-1">
{onRegenerateTitle && (
<button
type="button"
disabled={activeSelectedIds.size === 0}
onClick={commitBulkRegenerate}
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<RefreshCw size={12} />
{t('ai.chat.managerRegenerateTitle')}
</button>
)}
<button
type="button"
disabled={activeSelectedIds.size === 0}
onClick={() => setBulkDeleteConfirmOpen(true)}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<Trash2 size={12} />
{t('common.delete')}
</button>
<button
type="button"
onClick={exitSelectionMode}
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
>
{t('common.cancel')}
</button>
</div>
</div>
)}
<ScrollArea className="flex-1">
<div className="px-3">
{filteredRows.length === 0 ? (
@@ -260,28 +404,43 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
const canMoveElsewhere = otherMoveTargets.length > 0;
const isRenaming = renamingSessionId === row.session.id;
const isMenuOpen = openMenuSessionId === row.session.id;
const subtitleParts: string[] = [];
if (row.scopeLabel) subtitleParts.push(row.scopeLabel);
if (showAgentMeta) subtitleParts.push(row.agentLabel);
const subtitleParts: Array<{ text: string; bold: boolean; truncate: boolean }> = [];
if (row.scopeLabel) {
subtitleParts.push({ text: row.scopeLabel, bold: true, truncate: true });
}
subtitleParts.push({ text: row.agentLabel, bold: true, truncate: false });
if (row.messageCount > 0) {
subtitleParts.push(
t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
);
subtitleParts.push({
text: t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
bold: false,
truncate: false,
});
}
return (
<React.Fragment key={row.session.id}>
<div
role="button"
tabIndex={row.canActivate ? 0 : -1}
tabIndex={selectionMode || row.canActivate ? 0 : -1}
onClick={() => {
if (selectionMode) {
toggleSelected(row.session.id);
return;
}
if (!isRenaming && row.canActivate) activateRow(row);
}}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (!isRenaming && row.canActivate && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
activateRow(row);
if (e.key === 'Enter' || e.key === ' ') {
if (selectionMode) {
e.preventDefault();
toggleSelected(row.session.id);
return;
}
if (!isRenaming && row.canActivate) {
e.preventDefault();
activateRow(row);
}
}
}}
className={cn(
@@ -289,69 +448,91 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
row.isCurrentActive
? 'text-foreground'
: 'text-foreground/75 hover:text-foreground',
!row.canActivate && 'cursor-default',
!selectionMode && !row.canActivate && 'cursor-default',
)}
data-session-id={row.session.id}
data-scope-state={row.scopeState}
>
<div className="min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
)}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
{selectionMode && (
<button
type="button"
aria-label={t('ai.chat.managerSelectRow')}
aria-pressed={activeSelectedIds.has(row.session.id)}
onClick={(e) => {
e.stopPropagation();
toggleSelected(row.session.id);
}}
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
>
{activeSelectedIds.has(row.session.id)
? <CheckSquare size={14} className="text-primary" />
: <Square size={14} />}
</button>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
</span>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/50 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={index === 0 ? 'truncate' : 'shrink-0'}>
{part}
</span>
</React.Fragment>
))}
</div>
)}
</div>
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
{formatRelativeTime(new Date(row.session.updatedAt), t)}
</span>
{!selectionMode && (
<Dropdown
open={isMenuOpen}
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
@@ -387,6 +568,20 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
<span>{t('ai.chat.renameChat')}</span>
</button>
)}
{onRegenerateTitle && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setOpenMenuSessionId(null);
onRegenerateTitle(row.session.id);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<RefreshCw size={12} className="shrink-0 text-muted-foreground" />
<span>{t('ai.chat.managerRegenerateTitle')}</span>
</button>
)}
<button
type="button"
onClick={(e) => {
@@ -430,6 +625,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
</DropdownContent>
</Dropdown>
)}
</div>
</div>
{moveSession?.id === row.session.id && (
@@ -490,6 +686,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
}}
onConfirm={commitDelete}
/>
<ConfirmDialog
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
confirmLabel={t('common.delete')}
destructive
onOpenChange={(open) => {
if (!open) setBulkDeleteConfirmOpen(false);
}}
onConfirm={commitBulkDelete}
/>
</div>
);
};
@@ -96,6 +96,39 @@ test("global rows cover every scope: live terminal, other terminal, workspace, c
assert.equal(byId.get("s-global")!.scopeLabel, t("ai.chat.chatsScopeGlobal"));
});
test("workspace name snapshot is the fallback for a dangling workspace, but live title wins", () => {
const input = {
...baseInput(),
hosts: [{ id: "h-old", label: "old-host", hostname: "10.0.0.5" }],
};
input.sessions = [
// Workspace gone: the captured name wins over the host fallback.
baseSession({
id: "s-snap",
scope: { type: "workspace", targetId: "w-gone", hostIds: ["h-old"] },
workspaceNameSnapshot: "Prod (old)",
}),
// Workspace still live: the live title wins even if a stale snapshot exists.
baseSession({
id: "s-live",
scope: { type: "workspace", targetId: "w-1" },
workspaceNameSnapshot: "Stale name",
}),
// Dangling flag with a live workspace present still falls back to the snapshot.
baseSession({
id: "s-flagged",
scope: { type: "workspace", targetId: "w-1" },
scopeDangling: true,
workspaceNameSnapshot: "Prod (archived)",
}),
];
const byId = new Map(buildGlobalManagerRows(input).map((row) => [row.session.id, row]));
assert.equal(byId.get("s-snap")!.scopeLabel, "Prod (old)");
assert.equal(byId.get("s-snap")!.scopeState, "dangling");
assert.equal(byId.get("s-live")!.scopeLabel, "Prod");
assert.equal(byId.get("s-flagged")!.scopeLabel, "Prod (archived)");
});
test("active marker distinguishes current panel active chat vs active elsewhere", () => {
const input = baseInput();
input.sessions = [
+5 -1
View File
@@ -165,10 +165,14 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
if (session.scope.type === 'workspace') {
const title = workspaceTitles.get(session.scope.targetId ?? '');
if (title != null && !session.scopeDangling) {
// Live title wins so a rename is reflected immediately.
scopeLabel = title;
isDangling = false;
} else {
scopeLabel = resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
// Workspace is gone/dangling: prefer the name captured at bind time,
// then fall back to the historical host labels.
scopeLabel = session.workspaceNameSnapshot
|| resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
isDangling = true;
}
} else if (session.scope.type === 'terminal') {
@@ -0,0 +1,9 @@
import { createContext } from 'react';
export interface GlobalSessionSelectionContextValue {
selectionMode: boolean;
setSelectionMode: (active: boolean) => void;
}
export const GlobalSessionSelectionContext =
createContext<GlobalSessionSelectionContextValue | null>(null);
@@ -345,6 +345,14 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<div className="text-xs text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
})}
</div>
) : null}
</div>
{restoreAllowed && (
<Button
@@ -443,6 +451,14 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<div className="text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
})}
</div>
) : null}
</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
+7 -7
View File
@@ -77,7 +77,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
const hasManualProxyCommand = Boolean(proxyConfig?.command?.trim());
const hasManualProxyValue = isCommandProxy ? hasManualProxyCommand : hasManualProxyHost;
const hasInvalidManualProxyPort = !isCommandProxy && hasManualProxyHost && !isValidProxyPort(proxyConfig?.port);
const effectiveProxyConfig = selectedProfile?.config ?? proxyConfig;
const effectiveProxyConfig = directProxy ? undefined : (selectedProfile?.config ?? proxyConfig);
const hasMissingIdentity = hasMissingProxyIdentity(effectiveProxyConfig, identities);
const hasIncompleteIdentity = hasIncompleteProxyIdentity(effectiveProxyConfig, identities);
const hasUnreadableIdentity = hasUnreadableProxyCredential(effectiveProxyConfig, identities);
@@ -92,9 +92,9 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
);
const selectedIdentityValue = selectedIdentity?.id || (hasMissingIdentity ? missingIdentityValue : manualCredentialsValue);
const handleBack = useCallback(() => {
if (hasInvalidManualProxyPort || hasInvalidIdentity) return;
if (!directProxy && (hasInvalidManualProxyPort || hasInvalidIdentity)) return;
onBack();
}, [hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
}, [directProxy, hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
return (
<AsidePanel
@@ -153,7 +153,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
{t('hostDetails.proxyPanel.missingSaved')}
</div>
)}
{selectedProfile && (
{isUsingProfile && selectedProfile && (
<div className="min-w-0 rounded-md bg-secondary/50 p-2 text-sm">
<div className="flex min-w-0 items-center gap-2">
<Badge variant="secondary" className="text-xs shrink-0">
@@ -165,17 +165,17 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
</div>
</div>
)}
{selectedProfile && hasMissingIdentity && (
{isUsingProfile && selectedProfile && hasMissingIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.missingIdentity')}
</div>
)}
{selectedProfile && hasIncompleteIdentity && (
{isUsingProfile && selectedProfile && hasIncompleteIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.incompleteIdentity')}
</div>
)}
{selectedProfile && hasUnreadableIdentity && (
{isUsingProfile && selectedProfile && hasUnreadableIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.unreadableIdentity')}
</div>
+35 -3
View File
@@ -1,4 +1,7 @@
import { useCallback, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
import { Button } from '../ui/button';
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
import { PluginSettingsEntry } from './PluginSettingsEntry';
import { PluginRemoteSurface } from './PluginRemoteSurface';
@@ -30,12 +33,33 @@ function hasFullBleedChrome(tree: unknown): boolean {
return check(children, 0);
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
function PluginHostDrawnPageSession({
onRetry,
...props
}: PluginHostDrawnPageProps & { onRetry: () => void }) {
const { t } = useI18n();
const view = useHostDrawnPluginView(props);
if (!view.visible) return null;
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
const slotName = props.slot.split(':')[0];
if (view.loading) return <PluginViewLoadingSurface slot={slotName} loadingLabel={props.loadingLabel} />;
if (view.error) {
return (
<div
className="relative isolate flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-3 bg-background p-6 text-center"
data-plugin-view-slot={slotName}
data-plugin-view-error=""
>
<p role="alert" className="text-sm text-destructive">
{t('plugins.vault.viewError')}
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
{t('plugins.vault.retry')}
</Button>
</div>
);
}
const fullBleed = hasFullBleedChrome(view.tree);
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={slotName} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
{!fullBleed && (
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
@@ -44,3 +68,11 @@ export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
)}
</div>;
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const [generation, setGeneration] = useState(0);
const handleRetry = useCallback(() => {
setGeneration((n) => n + 1);
}, []);
return <PluginHostDrawnPageSession key={generation} {...props} onRetry={handleRetry} />;
}
@@ -704,3 +704,897 @@ test('RemoteImageElement renders a transparent placeholder while loading and nev
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid clears stale editingCell and pending blur timer when insertedRows shrink or row is deleted', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
});
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const makeTree = (insertedRows: Array<Record<string, unknown>>, deletedRowIndices: number[] = []) => ({
children: [
{
id: 'grid',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'data-grid',
'data-plugin-widget-props': JSON.stringify({
columns: [
{ name: 'id', type: 'INTEGER', primaryKey: true },
{ name: 'name', type: 'TEXT' },
],
rows: [[1, 'Alice']],
insertedRows,
deletedRowIndices,
editable: true,
}),
},
children: [],
},
],
});
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
const insertedNameCell = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"]') as HTMLElement;
assert.ok(insertedNameCell, 'inserted row cell rendered');
await act(async () => {
insertedNameCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const input = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input') as HTMLInputElement;
assert.ok(input, 'cell input opened on inserted row');
await act(async () => {
input.dispatchEvent(new dom.window.FocusEvent('blur', { bubbles: false }));
});
// Discard insertedRows immediately after blur and before blurTimeout(0) fires
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 25));
});
assert.equal(
events.some((e) => e.widgetEvent === 'cellEdit' && (e.detail as { rowIndex?: number })?.rowIndex === 1),
false,
'discarding inserted row must cancel pending blur cellEdit for removed row',
);
// Re-adding an inserted row must NOT reopen the stale editing input
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
assert.equal(
gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input'),
null,
're-adding inserted row starts clean without stale editingCell input',
);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface forwards pointer gestures with capture/coalescing and wheel zoom without breaking scroll or widgets', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const capturedPointers: Array<{ target: Element; pointerId: number }> = [];
const releasedPointers: Array<{ target: Element; pointerId: number }> = [];
dom.window.HTMLElement.prototype.setPointerCapture = function (pointerId: number) {
capturedPointers.push({ target: this, pointerId });
};
dom.window.HTMLElement.prototype.releasePointerCapture = function (pointerId: number) {
releasedPointers.push({ target: this, pointerId });
};
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const makePointerEvent = (
type: string,
opts: { clientX: number; clientY: number; pointerId?: number; button?: number; buttons?: number; pointerType?: string; shiftKey?: boolean; composed?: boolean },
) => {
const evt = new dom.window.MouseEvent(type, {
bubbles: true,
cancelable: true,
composed: opts.composed ?? true,
clientX: opts.clientX,
clientY: opts.clientY,
button: opts.button ?? 0,
buttons: opts.buttons ?? 0,
shiftKey: opts.shiftKey ?? false,
});
if (opts.pointerId !== undefined) Object.defineProperty(evt, 'pointerId', { value: opts.pointerId });
if (opts.pointerType !== undefined) Object.defineProperty(evt, 'pointerType', { value: opts.pointerType });
return evt;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [{ name: 'id', type: 'int4', primaryKey: true }],
rows: [{ id: 1 }],
editable: false,
};
const tree = {
children: [
{
id: 'stage',
type: 1,
element: 'div',
attributes: { class: 'graph-stage', style: 'overflow:hidden;touch-action:none' },
children: [
{
id: 'node-1',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'graph-node', style: 'touch-action:none' },
children: [{ id: 'n1t', type: 3, data: 'Alpha' }],
},
{
id: 'plain-btn',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'plain-btn' },
children: [{ id: 'pbt', type: 3, data: 'Click me' }],
},
],
},
{
id: 'scroll-box',
type: 1,
element: 'div',
attributes: { class: 'scroll-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'scroll-row', type: 1, element: 'div', attributes: { class: 'scroll-row' }, children: [{ id: 'srt', type: 3, data: 'Item' }] },
],
},
{
id: 'fit-box',
type: 1,
element: 'div',
attributes: { class: 'fit-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'fit-row', type: 1, element: 'div', attributes: { class: 'fit-row' }, children: [{ id: 'frt', type: 3, data: 'Short' }] },
],
},
{
id: 'split',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'split-pane',
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 200, minSize: 100, maxSize: 400 }),
},
children: [
{ id: 'pane-node', type: 1, element: 'div', attributes: { class: 'pane-node' }, children: [{ id: 'pn', type: 3, data: 'Pane' }] },
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
],
},
{
id: 'grid',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
children: [],
},
],
};
const root = createRoot(document.getElementById('root')!);
const renderSurface = async (settled = true) => {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={tree}
css=""
settled={settled}
onEvent={(e) => {
assert.equal(validateEvent(e), true, `Emitted event must satisfy contract schema: ${JSON.stringify(e)} -> ${JSON.stringify(validateEvent.errors)}`);
events.push(e as unknown as Record<string, unknown>);
}}
/>,
);
});
};
try {
await renderSurface(true);
const mainShadow = shadows[0]!;
const stage = mainShadow.querySelector('.graph-stage') as HTMLElement;
const nodeBtn = mainShadow.querySelector('.graph-node') as HTMLElement;
const plainBtn = mainShadow.querySelector('.plain-btn') as HTMLElement;
const scrollBox = mainShadow.querySelector('.scroll-box') as HTMLElement;
const scrollRow = mainShadow.querySelector('.scroll-row') as HTMLElement;
const fitBox = mainShadow.querySelector('.fit-box') as HTMLElement;
const fitRow = mainShadow.querySelector('.fit-row') as HTMLElement;
const paneNode = mainShadow.querySelector('.pane-node') as HTMLElement;
const splitHandle = mainShadow.querySelector('[data-split-handle]') as HTMLElement;
// 1. Hover pointermove before any pointerdown must NOT forward
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointermove', { clientX: 150, clientY: 90, pointerId: 3, button: -1, buttons: 0 }));
});
assert.equal(events.length, 0, 'idle hover pointermove must not flood plugin IPC');
// 2. pointerdown -> move (including outside node/surface) -> coalesce -> flush before pointerup
const downEvt = makePointerEvent('pointerdown', { clientX: 140, clientY: 90, pointerId: 7, button: 0, buttons: 1, pointerType: 'mouse' });
await act(async () => {
nodeBtn.dispatchEvent(downEvt);
});
assert.equal(downEvt.defaultPrevented, false, 'pointerdown must not preventDefault so focus/click/text-selection remain intact');
assert.deepEqual(capturedPointers, [{ target: nodeBtn, pointerId: 7 }], 'touch-action:none node engages host pointer capture');
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointerdown',
x: 40,
y: 40,
pointerId: 7,
button: 0,
buttons: 1,
pointerType: 'mouse',
});
// Unchanged coordinate move is skipped; first changed move forwards immediately (leading edge)
// and rapid subsequent moves outside the surface coalesce and flush right before pointerup.
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 140, clientY: 90, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 200, clientY: 130, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 215, clientY: 140, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 80, clientY: 20, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 80, clientY: 20, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' }));
});
assert.deepEqual(releasedPointers, [{ target: nodeBtn, pointerId: 7 }], 'pointer capture released on pointerup');
assert.deepEqual(events.slice(1), [
{ nodeId: 'node-1', type: 'pointermove', x: 100, y: 80, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true },
{ nodeId: 'node-1', type: 'pointermove', x: -20, y: -30, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' },
{ nodeId: 'node-1', type: 'pointerup', x: -20, y: -30, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' },
]);
// Moves after pointerup are ignored
const countAfterUp = events.length;
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 300, clientY: 300, pointerId: 7, button: -1, buttons: 0 }));
});
assert.equal(events.length, countAfterUp);
// 3. Backpressure via settled={false} holds coalesced pointermove until settled flips true
events.length = 0;
await renderSurface(false);
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 100, pointerId: 9, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 190, clientY: 120, pointerId: 9, button: -1, buttons: 1 }));
});
assert.deepEqual(events.map((e) => e.type), ['pointerdown'], 'unsettled move waits for acknowledgement');
await renderSurface(true);
assert.deepEqual(events.map((e) => ({ type: e.type, x: e.x, y: e.y })), [
{ type: 'pointerdown', x: 50, y: 50 },
{ type: 'pointermove', x: 90, y: 70 },
], 'move flushes immediately once settled becomes true');
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointercancel', { clientX: 95, clientY: 75, pointerId: 9, button: -1, buttons: 0 }));
});
assert.equal(events.at(-1)?.type, 'pointercancel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 4. Plain button does not engage setPointerCapture and still forwards normal click
events.length = 0;
const captureCountBeforePlain = capturedPointers.length;
await act(async () => {
plainBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 1 }));
plainBtn.dispatchEvent(makePointerEvent('pointerup', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 0 }));
plainBtn.click();
});
assert.equal(capturedPointers.length, captureCountBeforePlain, 'plain button without touch-action:none skips setPointerCapture');
assert.deepEqual(events.map((e) => e.type), ['pointerdown', 'pointerup', 'click']);
// 5. Wheel over non-scrollable remote node prevents default and forwards deltas; rapid ticks coalesce by summing deltas
events.length = 0;
const wheel1 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 260,
clientY: 190,
deltaX: 0,
deltaY: -120,
deltaMode: 0,
ctrlKey: true,
});
const wheel2 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 265,
clientY: 195,
deltaX: 4,
deltaY: -60,
deltaMode: 0,
ctrlKey: true,
});
const wheel3 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 270,
clientY: 200,
deltaX: 6,
deltaY: -40,
deltaMode: 0,
ctrlKey: true,
});
await act(async () => {
stage.dispatchEvent(wheel1);
stage.dispatchEvent(wheel2);
stage.dispatchEvent(wheel3);
});
assert.equal(wheel1.defaultPrevented, true, 'non-scrollable wheel must preventDefault');
assert.equal(wheel2.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.equal(wheel3.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.deepEqual([...events], [
{ nodeId: 'stage', type: 'wheel', x: 160, y: 140, deltaX: 0, deltaY: -120, deltaMode: 0, ctrlKey: true },
]);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 40));
});
assert.deepEqual(events.at(-1), {
nodeId: 'stage',
type: 'wheel',
x: 170,
y: 150,
deltaX: 10,
deltaY: -100,
deltaMode: 0,
ctrlKey: true,
});
// 6. Wheel over scrollable overflow container allows native scroll (no preventDefault, no wheel event)
events.length = 0;
Object.defineProperty(scrollBox, 'scrollHeight', { value: 600, configurable: true });
Object.defineProperty(scrollBox, 'clientHeight', { value: 120, configurable: true });
const scrollWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 100,
deltaMode: 0,
});
await act(async () => {
scrollRow.dispatchEvent(scrollWheel);
});
assert.equal(scrollWheel.defaultPrevented, false, 'scrollable overflow ancestor must keep native wheel scrolling');
assert.equal(events.length, 0, 'wheel over scrollable overflow ancestor must not forward wheel');
// Non-overflowing overflow:auto container still forwards wheel
Object.defineProperty(fitBox, 'scrollHeight', { value: 120, configurable: true });
Object.defineProperty(fitBox, 'clientHeight', { value: 120, configurable: true });
const fitWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: -80,
deltaMode: 0,
});
await act(async () => {
fitRow.dispatchEvent(fitWheel);
await new Promise((resolve) => setTimeout(resolve, 35));
});
assert.equal(fitWheel.defaultPrevented, true, 'non-overflowing overflow:auto box forwards wheel');
assert.equal(events.length, 1);
assert.equal(events[0].nodeId, 'fit-row');
assert.equal(events[0].type, 'wheel');
// 7. touch-action:none canvas inside a scrollable surface host still claims wheel zoom
events.length = 0;
const hostDiv = mainShadow.host as HTMLElement;
hostDiv.style.overflowY = 'auto';
Object.defineProperty(hostDiv, 'scrollHeight', { value: 1400, configurable: true });
Object.defineProperty(hostDiv, 'clientHeight', { value: 600, configurable: true });
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 35));
});
const stageWheelInScrollableHost = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 220,
clientY: 160,
deltaX: 0,
deltaY: -90,
deltaMode: 0,
});
await act(async () => {
nodeBtn.dispatchEvent(stageWheelInScrollableHost);
});
assert.equal(stageWheelInScrollableHost.defaultPrevented, true, 'touch-action:none graph node claims wheel even when outer host is scrollable');
assert.equal(events.at(-1)?.type, 'wheel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 8. Slotted widget pointer & wheel events are never forwarded as generic plugin events
events.length = 0;
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement;
const gridCell = gridHost.querySelector('[role="gridcell"]') as HTMLElement;
const widgetWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
composed: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 120,
deltaMode: 0,
});
await act(async () => {
gridCell.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 150, pointerId: 21, button: 0, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointermove', { clientX: 240, clientY: 170, pointerId: 21, button: -1, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointerup', { clientX: 240, clientY: 170, pointerId: 21, button: 0, buttons: 0 }));
gridCell.dispatchEvent(widgetWheel);
});
assert.equal(widgetWheel.defaultPrevented, false, 'slotted widget wheel must not be intercepted by surface');
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup', 'wheel'].includes(String(e.type))),
false,
'slotted widget pointer and wheel events must not forward as generic surface events',
);
// 9. SplitPane handle drag does not forward generic pointer events, while remote nodes inside its panes do
events.length = 0;
await act(async () => {
splitHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 100, pointerId: 31, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 250, clientY: 100, pointerId: 31, button: -1, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 250, clientY: 100, pointerId: 31, button: 0, buttons: 0 }));
});
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup'].includes(String(e.type))),
false,
'split-pane handle must not forward generic pointer events',
);
assert.ok(events.some((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), 'split-pane resize still works');
events.length = 0;
await act(async () => {
paneNode.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 0 }));
});
assert.deepEqual(events.map((e) => ({ nodeId: e.nodeId, type: e.type, x: e.x, y: e.y })), [
{ nodeId: 'pane-node', type: 'pointerdown', x: 60, y: 60 },
{ nodeId: 'pane-node', type: 'pointerup', x: 60, y: 60 },
]);
// 10. Unmounting the surface mid-drag emits pointercancel so a retained plugin session does not stay in a drag.
events.length = 0;
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 41, button: 0, buttons: 1, pointerType: 'mouse' }));
});
assert.equal(events[0]?.type, 'pointerdown');
assert.equal(events[0]?.pointerId, 41);
await act(async () => { root.unmount(); });
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointercancel',
x: 60,
y: 60,
pointerId: 41,
button: -1,
buttons: 0,
});
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface leaves wheel to a scrollable host-owned popover panel', async () => {
const { JSDOM } = await import('jsdom');
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
observe() {}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const events: Array<Record<string, unknown>> = [];
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={{
children: [
{
id: 'menu',
type: 1,
element: 'div',
attributes: {
'data-plugin-popover': 'true',
'data-plugin-anchor-x': '40',
'data-plugin-anchor-y': '20',
'data-plugin-popover-width': '240',
'data-plugin-popover-max-height': '160',
open: '',
},
children: [
{
id: 'row',
type: 1,
element: 'button',
attributes: { type: 'button' },
children: [{ id: 'row-t', type: 3, data: 'A tall menu item' }],
},
],
},
],
}}
css=""
settled={true}
onEvent={(e) => { events.push(e as unknown as Record<string, unknown>); }}
/>,
);
});
const popover = dom.window.document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
assert.ok(popover, 'host-owned popover panel is present');
popover!.style.overflow = 'auto';
Object.defineProperty(popover!, 'scrollHeight', { configurable: true, value: 400 });
Object.defineProperty(popover!, 'clientHeight', { configurable: true, value: 160 });
const popoverShadow = shadows.find((s) => popover!.contains((s as ShadowRoot).host)) ?? shadows.at(-1);
const row = popoverShadow!.querySelector('button') as HTMLElement;
assert.ok(row, 'popover row is present');
const wheel = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaX: 0, deltaY: 80, deltaMode: 0, clientX: 120, clientY: 80 });
await act(async () => { row.dispatchEvent(wheel); });
assert.equal(wheel.defaultPrevented, false, 'scrollable popover panel must keep native wheel scrolling');
assert.equal(events.some((e) => e.type === 'wheel'), false, 'wheel over a scrollable popover panel must not be forwarded');
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface + hostDom end-to-end round-trip supports node drag, incident edge tracking, background pan, and wheel zoom', async () => {
const dom = new JSDOM('<!doctype html><div id="host-root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'CustomEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, { PointerEvent: dom.window.MouseEvent });
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 40, y: 20, width: 600, height: 400, top: 20, left: 40, right: 640, bottom: 420, toJSON() {},
});
// In Electron the visible host renderer and hidden plugin runtime run in separate
// BrowserWindows. Guard host window capture listeners while forwarding into hostDom
// so plugin-side synthetic dispatches do not loop back into the host in a shared JSDOM.
let forwardingToPlugin = false;
const origAdd = dom.window.addEventListener.bind(dom.window);
const origRemove = dom.window.removeEventListener.bind(dom.window);
const wrappedListeners = new WeakMap<EventListenerOrEventListenerObject, EventListener>();
dom.window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
if (type === 'pointermove' || type === 'pointerup' || type === 'pointercancel') {
const wrapped: EventListener = (evt) => {
if (capture ? forwardingToPlugin : !forwardingToPlugin) return;
if (typeof listener === 'function') listener(evt);
else listener.handleEvent(evt);
};
wrappedListeners.set(listener, wrapped);
return origAdd(type, wrapped, options);
}
return origAdd(type, listener, options);
}) as typeof dom.window.addEventListener;
dom.window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
return origRemove(type, wrappedListeners.get(listener) ?? listener, options);
}) as typeof dom.window.removeEventListener;
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act, useEffect, useRef, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createPluginRemoteTree } = await import('../../application/state/pluginRemoteTree');
const { registerHostReactView } = await import('../../packages/plugin-sdk/src/hostReact');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const remoteTree = createPluginRemoteTree();
const hostRoot = createRoot(document.getElementById('host-root')!);
let pluginReceive: (message: unknown) => void = () => {};
let latestEventId = 0;
let latestAck = 0;
const renderHostSurface = () => {
hostRoot.render(
<PluginRemoteSurface
tree={remoteTree.snapshot()}
css=""
settled={latestAck >= latestEventId}
onEvent={(event) => {
const stamped = { ...event, eventId: ++latestEventId };
assert.equal(validateEvent(stamped), true, `Host event failed contract schema: ${JSON.stringify(validateEvent.errors)}`);
forwardingToPlugin = true;
try {
pluginReceive({ kind: 'host-ui.event', instanceId: 'e2e-1', event: stamped });
} finally {
forwardingToPlugin = false;
}
}}
/>,
);
};
const views = {
onDidReceiveMessage(_id: string, listener: (value: unknown) => void) {
pluginReceive = listener;
return { dispose() {} };
},
postMessage(_id: string, value: unknown) {
const msg = value as { kind?: string; mutations?: unknown[]; acknowledgedEvent?: number };
if (msg.kind !== 'host-ui.update') return;
if (Array.isArray(msg.mutations) && msg.mutations.length > 0) {
remoteTree.apply(msg.mutations);
}
if (typeof msg.acknowledgedEvent === 'number') {
latestAck = msg.acknowledgedEvent;
}
renderHostSurface();
},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
function MiniGraphCanvas() {
const stageRef = useRef<HTMLDivElement | null>(null);
const [nodePos, setNodePos] = useState({ x: 80, y: 100 });
const fixedPos = { x: 280, y: 100 };
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [dragging, setDragging] = useState(false);
const dragRef = useRef<{ kind: 'node' | 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (event: WheelEvent) => {
event.preventDefault();
setViewport((prev) => ({
...prev,
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.2 : 0.8) * 100) / 100,
}));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
// Mirror real canvas window-level drag listeners inside the plugin runtime.
useEffect(() => {
if (!dragging) return;
const onMove = (event: PointerEvent) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (drag.kind === 'node') {
setNodePos({ x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) });
} else {
setViewport((prev) => ({ ...prev, x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) }));
}
};
const onUp = (event: PointerEvent) => {
if (dragRef.current?.pointerId === event.pointerId) {
dragRef.current = null;
setDragging(false);
}
};
window.addEventListener('pointermove', onMove as unknown as EventListener);
window.addEventListener('pointerup', onUp as unknown as EventListener);
return () => {
window.removeEventListener('pointermove', onMove as unknown as EventListener);
window.removeEventListener('pointerup', onUp as unknown as EventListener);
};
}, [dragging]);
const edgeLen = Math.round(Math.hypot(fixedPos.x - nodePos.x, fixedPos.y - nodePos.y));
return (
<div
className="e2e-stage"
ref={stageRef}
style={{ overflow: 'hidden', touchAction: 'none' }}
onPointerDown={(e) => {
if (e.button !== 0) return;
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
setDragging(true);
}}
>
<div className="e2e-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
<div className="e2e-edge" style={{ width: `${edgeLen}px`, transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }} />
<button
type="button"
className="e2e-node"
style={{ touchAction: 'none', transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodePos.x, originY: nodePos.y };
setDragging(true);
}}
>
N1
</button>
</div>
</div>
);
}
const makePointer = (type: string, clientX: number, clientY: number, pointerId: number, button: number, buttons: number) => {
const evt = new dom.window.MouseEvent(type, { bubbles: true, cancelable: true, composed: true, clientX, clientY, button, buttons });
Object.defineProperty(evt, 'pointerId', { value: pointerId });
return evt;
};
const registration = registerHostReactView(views as never, 'com.example.e2e-graph', () => <MiniGraphCanvas />);
try {
await act(async () => {
pluginReceive({ kind: 'host-ui.open', instanceId: 'e2e-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
const shadow = shadows[0]!;
const stageEl = shadow.querySelector('.e2e-stage') as HTMLElement;
const worldEl = shadow.querySelector('.e2e-world') as HTMLElement;
const edgeEl = shadow.querySelector('.e2e-edge') as HTMLElement;
const nodeEl = shadow.querySelector('.e2e-node') as HTMLElement;
assert.equal(nodeEl.style.transform, 'translate(80px, 100px)');
assert.equal(edgeEl.style.width, '200px');
// Drag node across the visible host surface (pointermove/up dispatched on host window outside the node)
await act(async () => {
nodeEl.dispatchEvent(makePointer('pointerdown', 120, 120, 1, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 170, 160, 1, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 170, 160, 1, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(nodeEl.style.transform, 'translate(130px, 140px)', 'visible host shadow DOM node must move by (+50, +40)');
assert.equal(edgeEl.style.width, `${Math.round(Math.hypot(280 - 130, 100 - 140))}px`, 'visible host incident edge must follow node');
// Pan background stage and wheel-zoom
await act(async () => {
stageEl.dispatchEvent(makePointer('pointerdown', 300, 200, 2, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 340, 230, 2, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 340, 230, 2, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
const wheelEvt = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 250, clientY: 180, deltaX: 0, deltaY: -120, deltaMode: 0 });
await act(async () => {
stageEl.dispatchEvent(wheelEvt);
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(wheelEvt.defaultPrevented, true);
assert.equal(worldEl.style.transform, 'translate(40px, 30px) scale(1.2)', 'visible host shadow DOM world must pan and wheel-zoom');
await act(async () => {
pluginReceive({ kind: 'host-ui.close', instanceId: 'e2e-1' });
});
} finally {
await act(async () => {
registration.dispose();
hostRoot.unmount();
});
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+523 -11
View File
@@ -19,8 +19,13 @@ export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnVi
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const POINTER_MOVE_THROTTLE_MS = 24;
const POINTER_MOVE_BACKPRESSURE_MAX_MS = 96;
const WHEEL_THROTTLE_MS = 24;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'pointerdown', 'pointermove', 'pointerup', 'pointercancel',
'wheel',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
@@ -337,6 +342,163 @@ function readSelectionRange(
return undefined;
}
function readSurfacePoint(
event: MouseEvent,
surfaceEl: HTMLElement | null,
): { x: number; y: number } {
const rect = surfaceEl?.getBoundingClientRect();
const rawX = rect ? event.clientX - rect.left : event.clientX;
const rawY = rect ? event.clientY - rect.top : event.clientY;
return {
x: Number.isFinite(rawX) ? Math.round(rawX) : 0,
y: Number.isFinite(rawY) ? Math.round(rawY) : 0,
};
}
function readModifierKeys(event: MouseEvent | WheelEvent): {
ctrlKey?: true;
metaKey?: true;
altKey?: true;
shiftKey?: true;
} {
return {
...(event.ctrlKey ? { ctrlKey: true as const } : {}),
...(event.metaKey ? { metaKey: true as const } : {}),
...(event.altKey ? { altKey: true as const } : {}),
...(event.shiftKey ? { shiftKey: true as const } : {}),
};
}
function readPointerId(event: Event): number {
const raw = (event as PointerEvent).pointerId;
if (typeof raw === 'number' && Number.isFinite(raw)) {
return Math.max(-2147483648, Math.min(2147483647, Math.trunc(raw)));
}
return 1;
}
function readPointerType(event: Event): 'mouse' | 'pen' | 'touch' | undefined {
const raw = (event as PointerEvent).pointerType;
return raw === 'mouse' || raw === 'pen' || raw === 'touch' ? raw : undefined;
}
function readPointerButton(event: MouseEvent): number {
return typeof event.button === 'number' && Number.isFinite(event.button)
? Math.max(-1, Math.min(32, Math.trunc(event.button)))
: 0;
}
function readPointerButtons(event: MouseEvent): number {
return typeof event.buttons === 'number' && Number.isFinite(event.buttons)
? Math.max(0, Math.min(65535, Math.trunc(event.buttons)))
: 0;
}
function roundWheelDelta(value: number): number {
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
}
function isScrollableOverflowValue(value: string | undefined): boolean {
return value === 'auto' || value === 'scroll' || value === 'overlay';
}
function readOverflowToken(value: string | undefined, axis: 'x' | 'y'): string | undefined {
if (!value) return undefined;
const parts = value.trim().split(/\s+/);
return axis === 'y' ? (parts[1] ?? parts[0]) : parts[0];
}
function readAxisOverflow(
el: HTMLElement,
style: CSSStyleDeclaration | undefined,
axis: 'x' | 'y',
): string | undefined {
// Prefer a scrollable value from computed or inline styles. Some test DOMs
// report the initial `visible` computed overflow even when the element has
// an inline `overflow: auto` shorthand.
const candidates = [
axis === 'y' ? style?.overflowY : style?.overflowX,
axis === 'y' ? el.style.overflowY : el.style.overflowX,
readOverflowToken(style?.overflow, axis),
readOverflowToken(el.style.overflow, axis),
];
for (const value of candidates) {
if (isScrollableOverflowValue(value)) return value;
}
return candidates.find((value) => value && value !== 'visible') ?? candidates[0];
}
function canElementScrollForWheel(
el: HTMLElement,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
const style = view.getComputedStyle?.(el);
const canScrollY = deltaY !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'y'))
&& el.scrollHeight > el.clientHeight + 1;
const canScrollX = deltaX !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'x'))
&& el.scrollWidth > el.clientWidth + 1;
return canScrollY || canScrollX;
}
/**
* Wheel vs native scroll rule:
* Walk ancestors inside the shadow root (and then the surface's own scroll host
* unless a non-scrollable element declares `touch-action: none` to claim canvas
* gestures). If an ancestor has `overflow: auto|scroll|overlay` with actual
* overflow along the wheel axis, leave the event to native scrolling (existing
* throttled `scroll` events still forward). Otherwise `preventDefault()` so the
* surrounding workbench does not steal the gesture, and forward coalesced `wheel`.
*/
function hasScrollableAncestorForWheel(
target: HTMLElement,
shadow: ShadowRoot,
host: HTMLElement | null,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
let current: HTMLElement | null = target;
let hitGestureBoundary = false;
while (current) {
if (canElementScrollForWheel(current, view, deltaX, deltaY)) return true;
const touchAction = view.getComputedStyle?.(current)?.touchAction || current.style.touchAction;
if (touchAction === 'none') {
hitGestureBoundary = true;
break;
}
const parent = current.parentElement;
if (!parent || parent.getRootNode() !== shadow) break;
current = parent;
}
if (!hitGestureBoundary && host && canElementScrollForWheel(host, view, deltaX, deltaY)) {
return true;
}
// Nested popover surfaces live in a portaled PluginViewPopover panel. That
// panel (not the inner overflow-auto host) is often the only element with a
// bounded max-height, so include it when deciding who owns the wheel.
if (!hitGestureBoundary) {
const popover = (host ?? target).closest?.('[data-plugin-view-popover]') as HTMLElement | null;
if (popover && canElementScrollForWheel(popover, view, deltaX, deltaY)) return true;
}
return false;
}
type ActivePointerGesture = {
nodeId: string;
pointerId: number;
capturedElement: HTMLElement | null;
lastSentX: number;
lastSentY: number;
lastMoveSentAt: number;
pendingMove: PluginSurfaceEvent | null;
pendingMoveSince: number;
moveTimer: ReturnType<typeof setTimeout> | null;
};
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checkedTree = useMemo(() => {
@@ -373,6 +535,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
const surfaceRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const settledRef = useRef(settled); settledRef.current = settled;
const flushPendingMovesRef = useRef<(() => void) | null>(null);
const shadowRef = useRef<ShadowRoot | null>(null);
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
@@ -387,6 +551,10 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
setShadowHost(host);
}, []);
useEffect(() => {
if (settled) flushPendingMovesRef.current?.();
}, [settled]);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
@@ -394,8 +562,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
useEffect(() => {
if (!shadow) return;
const view = shadow.ownerDocument.defaultView;
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingScroll = new Map<string, PluginSurfaceEvent>();
const activeGestures = new Map<number, ActivePointerGesture>();
const handledPointerEvents = new WeakSet<Event>();
let windowPointerListenersAttached = false;
let wheelTimer: ReturnType<typeof setTimeout> | null = null;
let pendingWheel: PluginSurfaceEvent | null = null;
let lastWheelSentAt = 0;
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
@@ -406,10 +581,203 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
};
const flushWheel = () => {
if (wheelTimer !== null) {
clearTimeout(wheelTimer);
wheelTimer = null;
}
const evt = pendingWheel;
pendingWheel = null;
if (!evt || ((evt.deltaX ?? 0) === 0 && (evt.deltaY ?? 0) === 0)) return;
lastWheelSentAt = Date.now();
onEventRef.current(evt);
};
const emitGestureMove = (gesture: ActivePointerGesture, moveEvent: PluginSurfaceEvent, now: number) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (moveEvent.x === gesture.lastSentX && moveEvent.y === gesture.lastSentY) return;
gesture.lastSentX = moveEvent.x ?? gesture.lastSentX;
gesture.lastSentY = moveEvent.y ?? gesture.lastSentY;
gesture.lastMoveSentAt = now;
onEventRef.current(moveEvent);
};
const scheduleGestureMoveFlush = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null || !gesture.pendingMove) return;
const now = Date.now();
const throttleWait = Math.max(0, POINTER_MOVE_THROTTLE_MS - (now - gesture.lastMoveSentAt));
const backpressureWait = settledRef.current
? 0
: Math.max(0, POINTER_MOVE_BACKPRESSURE_MAX_MS - (now - gesture.pendingMoveSince));
const delay = Math.max(1, throttleWait, backpressureWait);
gesture.moveTimer = setTimeout(() => {
gesture.moveTimer = null;
if (activeGestures.get(gesture.pointerId) !== gesture || !gesture.pendingMove) return;
const tickNow = Date.now();
const elapsed = tickNow - gesture.lastMoveSentAt;
const waitedEnough = settledRef.current || tickNow - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS;
if (elapsed >= POINTER_MOVE_THROTTLE_MS && waitedEnough) {
emitGestureMove(gesture, gesture.pendingMove, tickNow);
} else {
scheduleGestureMoveFlush(gesture);
}
}, delay);
};
const releaseGesture = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (gesture.capturedElement) {
try {
gesture.capturedElement.releasePointerCapture?.(gesture.pointerId);
} catch {
// Capture may already have been released natively.
}
gesture.capturedElement = null;
}
activeGestures.delete(gesture.pointerId);
if (activeGestures.size === 0) detachWindowPointerListeners();
};
/**
* Active pointer gestures are tracked at the host surface so plugin drags
* continue after leaving the originating node or surface (plugin-side
* setPointerCapture cannot capture the visible host pointer). Moves skip
* unchanged coordinates, coalesce under POINTER_MOVE_THROTTLE_MS, and adapt
* to host-ui acknowledgedEvent backpressure via `settled`.
*/
const onGesturePointerEvent = (event: Event) => {
if (!view || activeGestures.size === 0 || handledPointerEvents.has(event)) return;
const pointerId = readPointerId(event);
const gesture = activeGestures.get(pointerId);
if (!gesture) return;
handledPointerEvents.add(event);
const isMouseLike = event instanceof view.MouseEvent;
const coords = isMouseLike
? readSurfacePoint(event, surfaceRef.current ?? hostRef.current)
: { x: gesture.lastSentX, y: gesture.lastSentY };
const pointerType = readPointerType(event);
const button = isMouseLike ? readPointerButton(event) : -1;
const buttons = isMouseLike ? readPointerButtons(event) : 0;
const modifiers = isMouseLike ? readModifierKeys(event) : {};
if (event.type === 'pointermove') {
const moveEvent: PluginSurfaceEvent = {
nodeId: gesture.nodeId,
type: 'pointermove',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
};
if (gesture.pendingMove === null && coords.x === gesture.lastSentX && coords.y === gesture.lastSentY) {
return;
}
const now = Date.now();
const elapsed = now - gesture.lastMoveSentAt;
const canSendNow =
elapsed >= POINTER_MOVE_THROTTLE_MS
&& (settledRef.current || (gesture.pendingMoveSince > 0 && now - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS));
if (canSendNow) {
emitGestureMove(gesture, moveEvent, now);
} else {
gesture.pendingMove = moveEvent;
if (gesture.pendingMoveSince === 0) gesture.pendingMoveSince = now;
scheduleGestureMoveFlush(gesture);
}
return;
}
if (event.type === 'pointerup' && gesture.pendingMove) {
emitGestureMove(gesture, gesture.pendingMove, Date.now());
}
releaseGesture(gesture);
onEventRef.current({
nodeId: gesture.nodeId,
type: event.type as 'pointerup' | 'pointercancel',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
};
const onWindowBlur = (event: Event) => {
if (!view || event.target !== view || activeGestures.size === 0) return;
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
};
const attachWindowPointerListeners = () => {
if (!view || windowPointerListenersAttached) return;
windowPointerListenersAttached = true;
view.addEventListener('pointermove', onGesturePointerEvent, true);
view.addEventListener('pointerup', onGesturePointerEvent, true);
view.addEventListener('pointercancel', onGesturePointerEvent, true);
view.addEventListener('blur', onWindowBlur, false);
};
const detachWindowPointerListeners = () => {
if (!view || !windowPointerListenersAttached) return;
windowPointerListenersAttached = false;
view.removeEventListener('pointermove', onGesturePointerEvent, true);
view.removeEventListener('pointerup', onGesturePointerEvent, true);
view.removeEventListener('pointercancel', onGesturePointerEvent, true);
view.removeEventListener('blur', onWindowBlur, false);
};
flushPendingMovesRef.current = () => {
const now = Date.now();
for (const gesture of activeGestures.values()) {
if (!gesture.pendingMove) continue;
const elapsed = now - gesture.lastMoveSentAt;
if (elapsed >= POINTER_MOVE_THROTTLE_MS) {
emitGestureMove(gesture, gesture.pendingMove, now);
} else {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
scheduleGestureMoveFlush(gesture);
}
}
};
const listener = (event: Event) => {
if (!view || !SURFACE_EVENT_SET.has(event.type)) return;
if (event.type === 'pointermove' || event.type === 'pointerup' || event.type === 'pointercancel') {
onGesturePointerEvent(event);
return;
}
const target = event.target;
const view = shadow.ownerDocument.defaultView;
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
if (!(target instanceof view.HTMLElement)) return;
// Closed-shadow events hide their editable target from window capture.
if (event.type === 'focusin') {
@@ -420,8 +788,12 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
if (target.closest('[data-plugin-widget-host]')) return;
// Internal events inside slotted host-rendered widgets or split-pane dividers are handled by the widget itself.
if (
target.closest('[data-plugin-widget-host]')
|| target.closest('[data-split-handle]')
|| SLOTTED_WIDGET_KINDS.has(target.dataset.pluginWidget ?? '')
) return;
if (event.type === 'submit') event.preventDefault();
if (event.type === 'contextmenu') event.preventDefault();
@@ -436,6 +808,120 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
if (!nodeId) return;
if (event.type === 'pointerdown') {
if (!(event instanceof view.MouseEvent)) return;
const pointerId = readPointerId(event);
const existing = activeGestures.get(pointerId);
if (existing) releaseGesture(existing);
const coords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
const pointerType = readPointerType(event);
const button = readPointerButton(event);
const buttons = readPointerButtons(event);
const modifiers = readModifierKeys(event);
// Engage native pointer capture only on non-control elements that explicitly
// declare `touch-action: none` so text selection, native form controls, and
// normal button click cancellation stay intact. Window capture listeners still
// sustain cross-node/cross-surface drags for every remote node.
let capturedElement: HTMLElement | null = null;
if (!target.matches('input, textarea, select, option')) {
const touchAction = view.getComputedStyle?.(target)?.touchAction || target.style.touchAction;
if (touchAction === 'none') {
try {
target.setPointerCapture?.(pointerId);
capturedElement = target;
} catch {
// Synthetic or unsupported pointer capture environments rely on window listeners.
}
}
}
activeGestures.set(pointerId, {
nodeId,
pointerId,
capturedElement,
lastSentX: coords.x,
lastSentY: coords.y,
lastMoveSentAt: 0,
pendingMove: null,
pendingMoveSince: 0,
moveTimer: null,
});
attachWindowPointerListeners();
onEventRef.current({
nodeId,
type: 'pointerdown',
...coords,
pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
return;
}
if (event.type === 'wheel') {
const wheel = event as WheelEvent;
const deltaX = roundWheelDelta(wheel.deltaX);
const deltaY = roundWheelDelta(wheel.deltaY);
if (deltaX === 0 && deltaY === 0) return;
if (hasScrollableAncestorForWheel(target, shadow, hostRef.current, view, deltaX, deltaY)) {
return;
}
event.preventDefault();
const rawMode = wheel.deltaMode;
const deltaMode = typeof rawMode === 'number' && Number.isFinite(rawMode)
? Math.max(0, Math.min(2, Math.trunc(rawMode)))
: 0;
const coords = readSurfacePoint(wheel, surfaceRef.current ?? hostRef.current);
const modifiers = readModifierKeys(wheel);
const nextWheel: PluginSurfaceEvent = {
nodeId,
type: 'wheel',
...coords,
deltaX,
deltaY,
deltaMode,
...modifiers,
};
const now = Date.now();
if (!pendingWheel && now - lastWheelSentAt >= WHEEL_THROTTLE_MS) {
lastWheelSentAt = now;
onEventRef.current(nextWheel);
return;
}
if (
pendingWheel
&& pendingWheel.nodeId === nodeId
&& pendingWheel.deltaMode === deltaMode
&& Boolean(pendingWheel.ctrlKey) === Boolean(modifiers.ctrlKey)
&& Boolean(pendingWheel.metaKey) === Boolean(modifiers.metaKey)
&& Boolean(pendingWheel.altKey) === Boolean(modifiers.altKey)
&& Boolean(pendingWheel.shiftKey) === Boolean(modifiers.shiftKey)
) {
pendingWheel = {
...pendingWheel,
...coords,
deltaX: roundWheelDelta((pendingWheel.deltaX ?? 0) + deltaX),
deltaY: roundWheelDelta((pendingWheel.deltaY ?? 0) + deltaY),
};
} else {
if (pendingWheel) flushWheel();
pendingWheel = nextWheel;
}
if (wheelTimer === null) {
const delay = Math.max(1, WHEEL_THROTTLE_MS - (Date.now() - lastWheelSentAt));
wheelTimer = setTimeout(flushWheel, delay);
}
return;
}
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
@@ -463,11 +949,7 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
pointerCoords = {
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
};
pointerCoords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
}
const selection =
@@ -488,12 +970,21 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
});
};
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
for (const event of SURFACE_EVENTS) {
shadow.addEventListener(event, listener, event === 'wheel' ? { capture: true, passive: false } : true);
}
// Chromium only treats wheel as cancelable when a non-passive listener is
// registered on a real element. A closed ShadowRoot listener alone can see
// `cancelable: false`, so also listen on the shadow host (no-op targeting;
// the shadow capture listener still owns forwarding).
const shadowHostEl = hostRef.current;
const hostWheelOptions: AddEventListenerOptions = { capture: true, passive: false };
const hostWheelListener = (_event: Event) => {};
shadowHostEl?.addEventListener('wheel', hostWheelListener, hostWheelOptions);
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
// into the plugin so its Command Palette and Save shortcuts work reliably.
const view = shadow.ownerDocument.defaultView;
const onWindowKeyDown = (event: KeyboardEvent) => {
if (depth !== 0 || event.defaultPrevented) return;
const surfaceEl = surfaceRef.current;
@@ -531,7 +1022,28 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
view?.addEventListener('keydown', onWindowKeyDown, false);
return () => {
flushPendingMovesRef.current = null;
view?.removeEventListener('keydown', onWindowKeyDown, false);
shadowHostEl?.removeEventListener('wheel', hostWheelListener, hostWheelOptions);
// The retained plugin session keeps its SDK DOM when this surface unmounts
// (tab hide). Send pointercancel so plugin drags do not stay stuck.
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
detachWindowPointerListeners();
if (wheelTimer !== null) clearTimeout(wheelTimer);
wheelTimer = null;
pendingWheel = null;
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
@@ -141,6 +141,8 @@ export const PluginVaultAISidebar: React.FC<PluginVaultAISidebarProps> = ({
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
deleteSession={aiConfig.deleteSession}
updateSessionTitle={aiConfig.updateSessionTitle}
autoTitleSession={aiConfig.autoTitleSession}
regenerateSessionTitle={aiConfig.regenerateSessionTitle}
exportSessionsBackup={aiConfig.exportSessionsBackup}
importSessionsBackup={aiConfig.importSessionsBackup}
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
+2 -2
View File
@@ -1,9 +1,9 @@
[
{
"id": "com.binaricat.netcatty-database",
"version": "0.3.1",
"version": "0.3.2",
"repository": "binaricat/netcatty-database-plugin",
"commit": "84928ba5ca9638e509a11b7a578c400c0a320d06",
"commit": "81c3dd7ad9193b0d3a44df1531daeb6c758b4ee8",
"icon": {
"kind": "package",
"light": "assets/plugin-icon-light.png",
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff. Show more