Compare commits

...
Author SHA1 Message Date
陈奇 8d729da9eb fix(ai): recognize the two-line Starship SSH prompt 2026-12-04 12:43:34 +08:00
陈大猫 569b05e7fa fix(vault): inline known hosts tabs in header and drop logs filter pill border (#4685) 2026-12-04 11:39:05 +08:00
陈大猫 180a1427be feat(terminal): recognize Antigravity CLI sessions in tabs (#4688)
* feat(terminal): recognize Antigravity CLI sessions in tabs

* fix(terminal): exclude shell paths from Antigravity tab matching

* fix(terminal): wait for complete Antigravity version headers

* fix(terminal): preserve agent signals when tasks mention agy
2026-12-04 11:02:05 +08:00
陈大猫 5c4c7e3fa8 fix(ai): let users choose the Grok ACP session mode before sending (#4692) 2026-12-04 10:30:02 +08:00
HarLin 1c41aad9ff fix(vault-backups): gzip protective backups before encryption (#4683)
* fix(vault-backups): gzip protective backups before encryption

Protective backups include AI chat history, so a realistic vault can
exceed the 25 MiB raw-JSON cap. When that happens cloud sync aborts with
VaultBackupTooLargeError before it can apply a merged payload, leaving
sync stuck even though the vault itself is healthy.

Compress the serialized payload before encryption and enforce the cap on
the gzip output, which is what is actually stored. Stored size (and the
existing 50 MiB file cap) stays bounded, while large but compressible
chat history now fits. Existing safeStorage-v1 backups remain readable.

* fix(vault-backups): bound decompression and gzip off the main thread

Cap the raw UTF-8 payload at 128 MiB on create and enforce the same bound
with maxOutputLength on restore, so a highly compressible payload cannot
expand without limit. Use async zlib for gzip/gunzip so compression of a
large AI history no longer blocks main-process IPC.
2026-12-04 10:22:22 +08:00
Netcatty-Botandgithub-actions[bot] 516314f8ef Update Nix release metadata for v1.2.1 (#4681)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-12-04 10:14:58 +08:00
陈大猫 43dd7a43b3 fix(ai): show MCP authorization challenges during Grok ACP turns (#4686)
* fix(ai): surface MCP authorization challenges during Grok ACP turns

* fix(ai): omit OAuth challenge headers repeated in Grok RPC errors
2026-12-04 10:07:24 +08:00
陈大猫 0a389e760e fix(ssh): explain agent-only login when no identity is selected (#4687) 2026-12-04 10:06:13 +08:00
Caijinglong 897c3e23e6 feat(tabs): convert a live terminal tab to a workspace (#4684) 2026-12-04 09:52:35 +08:00
陈大猫 12531fbcc5 fix(vault): keep plugin sidebar order across plugin updates (#4679)
* fix(vault): keep plugin sidebar order across plugin updates

Preserve saved plugin-vault:* sidebar slots while an installed plugin is temporarily disabled during an in-place version update, and prune saved entries only when the owning plugin is no longer installed.

Related to binaricat/netcatty-database-plugin#23
Complements #4593

* fix(plugins): notify renderers after plugin uninstall completes
2026-12-04 00:38:27 +08:00
Radwan Selo a64029bc0b fix(dev): build plugin workspace packages before starting dev server (#4674)
@netcatty/plugin-contract resolves to packages/plugin-contract/dist, which
is not committed. On a fresh clone Vite failed with 'Failed to resolve entry
for package @netcatty/plugin-contract'. Build the plugin runtime deps as
part of npm run dev.
2026-12-03 23:30:34 +08:00
陈大猫 b5815c3064 feat(settings): measure local AI history on demand (#4678) 2026-12-03 19:10:43 +08:00
陈大猫 1f91fd54f1 fix(sync): preserve recovery history when saving or migrating a baseline (#4677)
* fix(sync): commit each baseline and its recovery history atomically

* fix(sync): preserve competing writes during lazy migration
2026-12-03 19:10:39 +08:00
陈大猫andGOUKI9999 2f76061ec8 fix(sync): require a recovery checkpoint before applying vault data (#4676)
Extract the two pre-apply checks and their regressions from #4605.

Co-authored-by: GOUKI9999 <gouki9999@Hotmail.com>
2026-12-03 19:10:36 +08:00
Joseph Hauand陈奇 dd9f6e862a feat(terminal): switch Git branches from the compose bar (#4625)
* feat(terminal): switch Git branches from the compose bar

* docs(terminal): organize compose bar and chip documentation

* fix(terminal): bind macOS prompt matching to the session directory

* fix(terminal): switch branches only in the selected worktree

* fix(terminal): preserve the boundary of colon-only prompts

* fix(terminal): bound macOS prompt matching before shell edits

* test(terminal): supply macOS prompt helpers to the paste runtime fixture

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 19:10:32 +08:00
GOUKI9999and陈奇 f688a17f14 feat(ai): add Antigravity CLI (agy) ACP agent support (Beta) and reorder agent cards (#4664)
* feat(ai): add Antigravity CLI (agy) ACP agent support and reorder agent cards

* chore(i18n): label Antigravity CLI (agy) ACP integration as Beta with risk notice

* fix(ai): address Codex review findings in Antigravity ACP driver

* fix(ai): preserve Antigravity state and honor native approval decisions

* fix(ai): stop Antigravity process groups and report failed tools

* fix(ai): keep Antigravity outside the plugin backend contract

* fix(ai): decode ACP content blocks for Antigravity tool output

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 19:10:27 +08:00
e6d3047d0a fix(ai): 识别 Kali 两行提示符并清洗 zle 键盘模式转义序列 (#4637)
* fix(ai): recognize Kali two-line prompts and strip zle keypad escapes

Kali's default bash/zsh prompt (┌──(user㉿host)-[path] / └─$) was never
treated as idle, so AI and MCP terminal execution could not detect a
ready shell on Kali hosts.

- Match the Kali host line, including bash/zsh chroot and venv groups,
  paired only with a └─$/└─# marker line. Accept the optional zsh
  RPROMPT exit-code (⨯) and background-job (⚙) indicators.
- stripAnsi now also removes short escapes such as ESC = / ESC > emitted
  by zle after every prompt; previously the leftover "=" kept zsh prompts
  from ever matching.

Verified against bytes captured from a Kali 2026.2 host (zsh and bash)
and via External MCP on a local test build.

* fix(ai): classify nested Kali prompts as POSIX and strip control strings whole

- isPosixPrompt now also accepts the Kali two-line prompt, so a Windows
  OpenSSH session with a cmd/PowerShell login hint that enters Kali (e.g.
  via WSL) gets the POSIX wrapper instead of a Windows one.
- stripAnsi removes DCS/SOS/PM/APC strings as a unit; previously only the
  introducer and ST were dropped, leaving the payload as visible text that
  could pass as an idle prompt.

* fix(ai): end non-OSC control strings only at ST and keep the scan linear

DCS/SOS/PM/APC now require ST (BEL terminates only OSC), and the payload
match stops at the next ESC so a run of unterminated introducers no longer
makes stripAnsi quadratic on large PTY captures.

* fix(ai): restore Kali prompt readiness after erasing typed input

---------

Co-authored-by: rinchao0721 <214155009+rinchao0721@users.noreply.github.com>
Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:56 +08:00
GOUKI9999andbinaricat f50c18e5c7 fix(ai): sync providers, honor UI language, preserve timestamps, and show feedback when regenerating chat titles (#4649)
* fix(ai): fix AI title regeneration provider sync, locale prompt, timestamp preservation, and UI feedback

* fix(ai): preserve queued renames and scoped conversation order

* fix(ai): isolate privacy sessions for repeated title generation

---------

Co-authored-by: binaricat <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:52 +08:00
GOUKI9999andbinaricat 33b4bd1a43 fix(ai): prevent sent composer text from lingering due to async batching, blur race, and steer ref equality (#4647)
* fix(ai): fix React 18 batching in clearDraftForScope, blur resurrection, and steer clear

* fix(ai): preserve replacement drafts after late steer replies

---------

Co-authored-by: binaricat <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:46 +08:00
Caijinglongand陈奇 31458b00a4 feat(shortcuts): allow adding secondary chords to a shortcut (#4658)
* feat(shortcuts): allow adding secondary chords to a shortcut

Each shortcut row only accepted one chord, so binding a second, easier chord meant overwriting the default one.

Settings > Shortcuts now offers an add button per row. Secondary chords are stored in the existing custom-binding record as `extra`, expanded into real bindings that carry `extraOf`, and matched by the same dispatcher. They render under their base row and can be re-recorded or removed individually. A secondary chord that a default already occupies disables that default, following the existing custom-binding conflict rule; resetting one scheme keeps the secondary chords.

* fix(shortcuts): honor secondary chords in editor close and SFTP paste

The editor's capture-phase close-tab handler and the SFTP native-paste eligibility check still read only the first binding for their action, so a secondary chord added in Settings matched the global dispatcher but did nothing in those paths. Both now scan every binding for the action.

* fix(shortcuts): show recording feedback and honor native close chords

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:37:25 +08:00
陈大猫 f68570d942 fix(win): refresh existing desktop shortcut icon on NSIS update (#4672) (#4673)
Fixes #4672.

Regression from #4597: ensureDesktopShortcut previously skipped CreateShortCut when $newDesktopLink already existed, leaving existing desktop shortcuts stale with a blank icon after in-app NSIS updates. Always rewrite the existing .lnk from the newly installed $appExe when ensureDesktopShortcut runs, while preserving all caller gates so deleted or opted-out shortcuts are still not recreated.
2026-12-03 16:22:37 +08:00
GOUKI9999 9474601fdf feat(ai): show native Grok ACP questions in chat (#4651)
* feat(ai): show native Grok ACP questions in chat

* fix(ai): validate Grok answers before privacy masking

* refactor(ai): keep Grok question cleanup independently mergeable

* fix(i18n): complete Grok question translations
2026-12-03 16:20:26 +08:00
GOUKI9999 4cef084e99 fix(ai): route Grok ACP plan review to the user (#4650)
* fix(ai): route Grok ACP plan review to the user

* fix(ai): restore private plan text for Grok review

* fix(i18n): complete Grok plan review translations
2026-12-03 16:20:21 +08:00
Caijinglong 58eeefb4c1 fix(import): merge repeated ssh_config Host blocks for one alias (#4657)
OpenSSH applies every Host block whose pattern matches an alias and keeps the first obtained value, so one alias may be declared in several blocks (for example HostName/User in one block and IdentityFile in another). The importer created one host per block, so such a config produced a second host whose hostname was the alias itself with no username.

Managed dedupe only compares endpoints, so the alias copy survived next to the resolved host, and the config serializer omits HostName when the hostname equals the alias, so the split was written back and re-imported unchanged on every sync.

Accumulate options per literal pattern instead (first obtained wins, IdentityFile paths are unioned) and create one host per pattern.
2026-12-03 13:53:48 +08:00
Caijinglong 6f8211481c feat(ai): add DeepSeek as a web search provider (#4660) 2026-12-03 13:52:36 +08:00
陈大猫 6458dbe039 fix(mcp): redact tcpdump-style ip.port addresses in external MCP output (#4668)
Fixes #4665

Recognize a trailing dotted port (0-65535) after IPv4/IPv6 so tcpdump-style
addresses are masked while the port is preserved. Colon forms and hostname
suffixes are unchanged. Single-digit IPv4 ports still require a tcpdump-like
delimiter so identifiers such as 1.2.3.4.5 stay intact.
2026-12-03 13:49:17 +08:00
陈大猫 6e0eacc6ae fix(cloud-sync): persist sync base and snapshots in IndexedDB (#4663)
Fixes #4661

Persist encrypted sync baseline and snapshots in IndexedDB so large vaults are no longer blocked by localStorage quota (Unable to persist sync base).

CI: lint-and-test green, run 47032340860 attempt 3.
Real Electron smoke: PASS on tip 758bbec0ac (production saveSyncBase under localStorage pressure; reload/hash/Settings Sync/SSH verified).
Codex residual P2 concurrency races judged out of scope for this quota fix.
2026-12-03 12:44:16 +08:00
陈大猫 73ee6c0f31 fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps (#4655)
* fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps

Fixes #4653. macOS Pinyin halfwidth punctuation reports a fullwidth keydown before committing halfwidth insertText, the inverse of #2833. Defer non-ASCII punctuation and keep unchanged CJK glyphs on the literal/composition path rather than Kitty physical-key encoding.

Credit AiHyo for diagnosing the event sequence and root cause.

* fix(terminal): avoid control-character regex in IME punctuation deferral
2026-12-02 20:04:41 +08:00
陈大猫 905aed61ad fix(terminal): keep workspace sessions removed across queued updates (#4652) 2026-12-02 19:36:39 +08:00
GOUKI9999 13d05b0ea4 fix(cloud-sync): keep local backup AI/settings counts inline when width allows (#4645) 2026-12-02 17:16:44 +08:00
陈大猫 1045737c68 feat(terminal): add autocomplete setting to show or hide code snippets (#4641) 2026-12-02 17:16:00 +08:00
陈大猫 909d3e5ed2 fix(startup): open local terminal landing after lazy App mount (#4640) (#4646)
#4476 split App into a lazy chunk, so AppLockGate could send rendererReady
while Suspense still showed a fallback. The cold-start settled event then
fired before AppSideEffects subscribed, and the "open local terminal on
launch" landing never ran when tab restore was off.

Defer rendererReady until the lazy route reports it has mounted, and latch
the settled event in preload so late subscribers still receive it.
2026-12-02 17:00:35 +08:00
陈大猫 cb7e49c409 fix(terminal): prevent autocomplete crash from double-sending keys (#4539) (#4632) 2026-12-02 14:49:08 +08:00
Netcatty-Bot 02be8a2e0a Update Nix release metadata for v1.2.0 (#4631) 2026-12-02 13:38:39 +08:00
陈大猫 ca2cdcbd12 fix(terminal): show sudo password hint for bare Password: prompts (#4628) (#4629) 2026-12-02 12:20:18 +08:00
陈大猫 f7fed5fd6f fix(plugins): systematic reliability hardening across transports, streams, RPC lifecycle, and UI (#4630) 2026-12-02 12:17:21 +08:00
陈大猫 25aa27bbf8 fix(plugins): settle pending SSH dial coordination and isolate plugin exec transport (#4627) 2026-12-02 11:34:05 +08:00
Netcatty-Botandgithub-actions[bot] 7e44b774f8 Update Nix release metadata for v1.1.99 (#4623)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-12-02 09:36:35 +08:00
陈大猫 c5c7cfdae3 fix(ai): loop-strip stacked decorative prompt prefixes (#4620)
* fix(ai): loop-strip stacked decorative prompt prefixes

Related #4354

After a non-zero exit, p10k (and similar) may prefix a status glyph
such as ✘ before the existing theme decoration (⚡). Recognition only
stripped one 1-4 char decorative token, so the leftover ⚡ still missed
the idle-prompt matchers and MCP terminal_execute never sent the command.

* fix(ai): match decorative prefix candidates after each strip

Related #4354

isDefaultPosixPromptLine must try the original line and each
intermediate strip so a status glyph in front of an Oh My Zsh
➜ prompt does not drop the ➜ before matching.
2026-12-02 08:35:18 +08:00
陈大猫 62085cb3c2 fix(plugins): cancel stuck SSH exec dials before the plugin RPC deadline (#4622)
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 08:15:51 +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
441 changed files with 34705 additions and 2054 deletions

No files matched your search

+8 -2
View File
@@ -25,6 +25,7 @@ import { SessionPublisher } from './application/app/publishers/SessionPublisher'
import { SettingsPublisher } from './application/app/publishers/SettingsPublisher';
import { VaultPublisher } from './application/app/publishers/VaultPublisher';
import { AppLockRuntimePublisher } from './application/app/publishers/AppLockRuntimePublisher';
import { useReportRendererReady } from './components/AppLockGate';
// Initialize fonts eagerly at app startup
initializeFonts();
@@ -61,8 +62,10 @@ function App() {
/**
* `AppLockGate` (index.tsx) owns `useSettingsState` / `useAppLockState` so the
* lock overlay can render before app children mount, and it owns the
* splash-removal + rendererReady signal (deep links must wait for unlock).
* lock overlay can render before app children mount, and owns splash removal
* plus the lock-gated `rendererReady` policy. This lazy route reports ready
* after `AppSideEffects` and bridge listeners have mounted so cold-start
* intents and deep links never race a suspended chunk.
* App forwards the gate's settings instance into SettingsPublisher so the
* runtime slot/context still publish a single settings runtime.
*/
@@ -78,6 +81,9 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
}, []);
useExternalMcpGrantPersister();
// Signal rendererReady after child effects (AppSideEffects) and bridge setup
// have registered in this commit's effect flush.
useReportRendererReady();
return (
<SettingsPublisher settings={settings}>
+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 トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
+7
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" />
@@ -65,6 +67,8 @@
- 🔥 **Intelligent context awareness** — understands your server environment and provides tailored responses
- 🚀 **One-click complex operations** — set up clusters, deploy services, and more with simple instructions
To search the web with DeepSeek, open **Settings → AI → Web Search**, enable web search, select **DeepSeek**, and enter your DeepSeek API key. You can use it with your current chat model. [DeepSeek Search API and pricing](https://api-docs.deepseek.com/guides/search/)
### 🎬 AI in Action
#### 🔥 Single Host — Intelligent Server Diagnostics
@@ -86,6 +90,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
@@ -160,6 +166,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
- **Fast search** — locate hosts and groups quickly
### 🖥️ Terminal Workspaces
- Right-click a standalone terminal tab and choose **Convert to Workspace** to keep your running shell as the first pane.
- **Split panes** — horizontal and vertical splits for multi-tasking
- **Session management** — run multiple connections side-by-side
- **Save current screen** — right-click a terminal to save the visible final text, without replaying keystrokes or overwritten output; scroll first to save an earlier screen.
+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' }]);
});
+29 -13
View File
@@ -270,7 +270,7 @@ export function flushQueuedTrayPanelConnectHostsImpl(getCtx: AppContextGetter) {
}
export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEvent) {
const { HOTKEY_DEBUG, closeTabKeyStr, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
const { HOTKEY_DEBUG, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
{
if (
isTargetInsideRemoteDesktopCapture(e.target, e.composedPath?.bind(e))
@@ -280,8 +280,14 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
}
const isMac = hotkeyScheme === 'mac';
// Secondary chords added in Settings share the action of their default
// binding, so every "is this action's shortcut?" check must scan all of them.
const matchesActionHotkey = (action: string): boolean => keyBindings.some((binding) => (
binding.action === action
&& matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
));
const target = e.target as HTMLElement;
const isCloseTabHotkey = closeTabKeyStr ? matchesKeyBinding(e, closeTabKeyStr, isMac) : false;
const isCloseTabHotkey = matchesActionHotkey('closeTab');
const dialogHotkeyScope = target.closest?.('[data-hotkey-close-tab="true"]');
if (isCloseTabHotkey && dialogHotkeyScope) {
@@ -308,15 +314,9 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
target instanceof HTMLElement &&
!!target.closest?.(".xterm, .xterm-helper-textarea, .xterm-screen, .xterm-viewport");
const quickSwitchBinding = keyBindings.find((binding) => binding.action === 'quickSwitch');
const quickSwitchKeyStr = quickSwitchBinding ? (isMac ? quickSwitchBinding.mac : quickSwitchBinding.pc) : null;
const isQuickSwitchHotkey = quickSwitchKeyStr ? matchesKeyBinding(e, quickSwitchKeyStr, isMac) : false;
const paneZoomBinding = keyBindings.find((binding) => binding.action === 'togglePaneZoom');
const paneZoomKeyStr = paneZoomBinding ? (isMac ? paneZoomBinding.mac : paneZoomBinding.pc) : null;
const isPaneZoomHotkey = paneZoomKeyStr ? matchesKeyBinding(e, paneZoomKeyStr, isMac) : false;
const hostTreeBinding = keyBindings.find((binding) => binding.action === 'toggleHostTree');
const hostTreeKeyStr = hostTreeBinding ? (isMac ? hostTreeBinding.mac : hostTreeBinding.pc) : null;
const isHostTreeHotkey = hostTreeKeyStr ? matchesKeyBinding(e, hostTreeKeyStr, isMac) : false;
const isQuickSwitchHotkey = matchesActionHotkey('quickSwitch');
const isPaneZoomHotkey = matchesActionHotkey('togglePaneZoom');
const isHostTreeHotkey = matchesActionHotkey('toggleHostTree');
if (
(isFormElement || isMonacoElement)
@@ -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');
+5 -11
View File
@@ -66,7 +66,7 @@ import type { PaneMagnificationController } from '../../domain/paneMagnification
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
import { resolveCloseIntent } from '../state/resolveCloseIntent';
import { resolveSnippetsShortcutIntent } from '../state/resolveSnippetsShortcutIntent';
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
import { isNativeCloseTabBound, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
import type { SyncPayload } from '../../domain/sync';
import { prepareSyncPayloadApply, buildLocalVaultPayloadAsync, hasMeaningfulSyncData } from '../syncPayload';
import {
@@ -651,7 +651,7 @@ export function AppSideEffects() {
const _handleTrayTogglePortForward = useEffectEvent((ruleId: string, start: boolean) => { return handleTrayTogglePortForwardImpl(() => ({ hasRuntimeTunnel, hosts, identities, keys, knownHosts: effectiveKnownHosts, portForwardingRules, resolveEffectiveHost, ruleId, start, startTunnel, stopTunnel, t, terminalSettings, toast, undefined }), ruleId, start); });
const _handleTrayPanelConnect = useEffectEvent((hostId: string) => { return handleTrayPanelConnectImpl(() => ({ addConnectionLog, connectToHost, hostId, hosts, identities, keys, resolveEffectiveHost, resolveHostAuth, systemInfoRef, t, toast }), hostId); });
const _handleTrayPanelConnectRequest = useEffectEvent((hostId: string) => { return handleTrayPanelConnectRequestImpl(() => ({ connectNow: _handleTrayPanelConnect, hostId, isVaultInitialized, queueConnect: (queuedHostId: string) => setPendingTrayPanelConnectHostIds((prev) => [...prev, queuedHostId]) }), hostId); });
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, closeTabKeyStr, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
const _handleEscapeKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleEscapeKeyDownImpl(() => ({ e, isQuickSwitcherOpen, setIsQuickSwitcherOpen }), e); });
// Vault hosts for tray / auto-start; terminalHosts (vault + ephemeral) only for
@@ -1082,13 +1082,6 @@ export function AppSideEffects() {
setSessionPoppedOut(sessionId, false);
}), [setSessionPoppedOut]);
const closeTabKeyStr = useMemo(() => {
if (hotkeyScheme === 'disabled') return null;
const closeTabBinding = keyBindings.find((binding) => binding.action === 'closeTab');
if (!closeTabBinding) return null;
return hotkeyScheme === 'mac' ? closeTabBinding.mac : closeTabBinding.pc;
}, [hotkeyScheme, keyBindings]);
const confirmIfBusyLocalTerminal = useCallback(
async (sessionIds: string[]): Promise<boolean> => { return confirmIfBusyLocalTerminalImpl(() => ({ netcattyBridge, sessionIds, sessions, t }), sessionIds); },
[sessions, t],
@@ -1228,7 +1221,7 @@ export function AppSideEffects() {
logViewIds: logViews.map((logView) => logView.id),
pluginViewTabIds: pluginViewTabs.map((tab) => tab.id),
hasOpenDialog: Boolean(topmostDialogClose),
closeTabShortcutEnabled: isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true),
closeTabShortcutEnabled: isNativeCloseTabBound(hotkeyScheme, keyBindings, true),
});
if (intent.kind === 'forwardShortcut') {
@@ -1261,7 +1254,7 @@ export function AppSideEffects() {
}
await netcattyBridge.get()?.windowClose?.();
}, [closeLogView, closeTabKeyStr, editorTabs, executeHotkeyAction, logViews, pluginViewTabs, sessions, workspaces]);
}, [closeLogView, editorTabs, executeHotkeyAction, hotkeyScheme, keyBindings, logViews, pluginViewTabs, sessions, workspaces]);
useEffect(() => {
// Cmd/Ctrl+W from the app menu arrives via IPC, not the keydown listener.
@@ -1847,6 +1840,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,
+3 -1
View File
@@ -274,7 +274,7 @@ function AppViewInner({ domains }: AppViewProps) {
const {
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
convertKnownHostToHost, convertSessionToWorkspace, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
followAppTerminalTheme,
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
@@ -569,9 +569,11 @@ function AppViewInner({ domains }: AppViewProps) {
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
onMoveSessionToNewWindow={moveSessionToNewWindow}
onConvertSessionToWorkspace={convertSessionToWorkspace}
onEditHost={handleEditHostFromOverlay}
onRenameWorkspace={startWorkspaceRename}
onCopyWorkspace={copyWorkspaceWithCurrentShell}
onRequestAddToWorkspace={handleRequestAddToWorkspace}
onCloseWorkspace={closeWorkspace}
onCloseLogView={closeLogView}
onCloseTabsBatch={closeTabsBatch}
+1
View File
@@ -131,6 +131,7 @@ export function ChromeHost() {
sessionRenameTarget: session.sessionRenameTarget,
setActiveTabId: sessionActions?.setActiveTabId,
startSessionRename: sessionActions?.startSessionRename,
convertSessionToWorkspace: sessionActions?.convertSessionToWorkspace,
renameSessionInline: sessionActions?.renameSessionInline,
startWorkspaceRename: sessionActions?.startWorkspaceRename,
submitSessionRename: sessionActions?.submitSessionRename,
@@ -59,6 +59,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
clearSessionFontSizeOverride,
createWorkspaceWithHosts,
createWorkspaceFromSessions,
convertSessionToWorkspace,
addSessionToWorkspace,
moveWorkspacePane,
appendHostToWorkspace,
@@ -148,6 +149,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
clearSessionFontSizeOverride,
createWorkspaceWithHosts,
createWorkspaceFromSessions,
convertSessionToWorkspace,
addSessionToWorkspace,
moveWorkspacePane,
appendHostToWorkspace,
@@ -197,6 +199,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
createSerialSession,
createSessionFromCloneSource,
createWorkspaceFromSessions,
convertSessionToWorkspace,
createWorkspaceFromTargets,
createWorkspaceWithHosts,
getOrderedWorkTabs,
+46
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const enAiMessages: Messages = {
'ai.grok.chooseModeAndSend': 'Choose Grok mode and send…',
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
'ai.chat.continue': 'Continue',
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
@@ -117,6 +118,9 @@ export const enAiMessages: Messages = {
'ai.codex.appServer.available': 'App Server is available for this Codex CLI.',
'ai.codex.appServer.modelCatalogWarning': 'The live Codex model catalog is unavailable. Using the built-in model list.',
'ai.codex.appServer.approval.allowSession': 'Allow for session',
'ai.planReview.title': 'Review implementation plan',
'ai.planReview.keepPlanning': 'Keep planning',
'ai.planReview.approveAndImplement': 'Approve and implement',
'ai.codex.appServer.userInput.title': 'Codex needs your input',
'ai.codex.appServer.userInput.description': 'Answer these questions to continue the current turn.',
'ai.codex.appServer.userInput.other': 'Enter another answer',
@@ -305,6 +309,16 @@ export const enAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 could not attach an MCP tool. The chat will continue without it.',
// AI MiMo Code (Xiaomi MiMo Code CLI — OpenCode fork)
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': "Experimental Beta: Google's Antigravity coding agent CLI connected via the official Agent Client Protocol (agy acp --stdio). Feature coverage is still limited and not yet thoroughly tested — use at your own risk. Sign in with agy in your terminal, then select it as an external coding agent.",
'ai.agy.detecting': 'Detecting...',
'ai.agy.detected': 'Detected',
'ai.agy.notFound': 'Not found',
'ai.agy.path': 'Path:',
'ai.agy.notFoundHint': 'Could not find agy in PATH. Install Antigravity CLI or specify the executable path below.',
'ai.agy.customPathPlaceholder': 'e.g. /usr/local/bin/agy',
'ai.agy.check': 'Check',
'ai.agy.resetPath': 'Reset',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': "Xiaomi's MiMo Code CLI, an OpenCode fork. Install it and configure providers in its own config, then select it as an external coding agent.",
'ai.mimo.detecting': 'Detecting...',
@@ -328,6 +342,9 @@ export const enAiMessages: Messages = {
'ai.grok.check': 'Check',
'ai.grok.resetPath': 'Reset',
'ai.grok.runtime.acp.title': 'Use Grok ACP (agent stdio)',
'ai.grok.userQuestion.title': 'Grok needs your input',
'ai.grok.userQuestion.description': 'Answers do not grant permissions. Do not include passwords or tokens.',
'ai.grok.userQuestion.submit': 'Send answers',
'ai.grok.runtime.acp.default': 'Default',
'ai.grok.runtime.acp.description':
'Talk to Grok over Agent Client Protocol (grok agent stdio). Injects Netcatty MCP on session/new. Turn off to use the original headless streaming-json CLI path.',
@@ -629,12 +646,25 @@ 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.managerRegenerateTitleUpdated': 'Chat title updated.',
'ai.chat.managerRegenerateTitleUnchanged': 'Chat title is already up to date.',
'ai.chat.managerRegenerateTitleNoModel': 'No AI provider/model is configured for title generation. Configure a provider or title model in AI Settings.',
'ai.chat.managerRegenerateTitleFailed': 'Failed to regenerate title: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Updated {n} chat title(s).',
'ai.chat.managerRegenerateTitleBatchPartial': 'Updated {updated} title(s), {failed} failed.',
'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',
@@ -685,9 +715,25 @@ export const enAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Show Add to Conversation when selecting terminal text',
'ai.chatShortcuts.selectionAction.description': 'Show a small AI button next to selected terminal text.',
'ai.chatHistory.title': 'Chat History',
'ai.chatHistory.storageUsage': 'Local chat history size',
'ai.chatHistory.storageUsage.description': 'Estimate the size of saved chat records as UTF-8 JSON.',
'ai.chatHistory.storageUsage.measure': 'Measure',
'ai.chatHistory.storageUsage.measuring': 'Measuring…',
'ai.chatHistory.storageUsage.result': 'Saved records · {count}. Estimated JSON size · {size}.',
'ai.chatHistory.storageUsage.partial': 'Records excluded from the size estimate · {count}.',
'ai.chatHistory.storageUsage.error': 'Could not read the local chat history. Try again.',
'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.',
+47
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.',
@@ -999,6 +1001,9 @@ Highlight the focused split pane:
'Choose whether autocomplete history suggestions come from the current host only, or from commands recorded on all hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Current host',
'settings.terminal.autocomplete.historyScope.global': 'All hosts',
'settings.terminal.autocomplete.showSnippets': 'Show code snippets',
'settings.terminal.autocomplete.showSnippets.desc':
'Include matching code snippets in the autocomplete list. Turn this off if snippets crowd out command and history suggestions.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Password prompt assist',
@@ -1027,6 +1032,9 @@ Highlight the focused split pane:
'settings.shortcuts.recording': 'Press keys...',
'settings.shortcuts.none': 'None',
'settings.shortcuts.setDisabled': 'Set to disabled',
'settings.shortcuts.addExtra': 'Add shortcut',
'settings.shortcuts.additional': 'Additional shortcut',
'settings.shortcuts.removeExtra': 'Remove shortcut',
'settings.shortcuts.category.tabs': 'Tabs',
'settings.shortcuts.category.terminal': 'Terminal',
'settings.shortcuts.category.navigation': 'Navigation',
@@ -1061,6 +1069,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 +1339,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 +1507,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',
};
+24
View File
@@ -2,6 +2,14 @@ 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.gitBranch.search': 'Search local branches...',
'terminal.gitBranch.branches': 'Local branches',
'terminal.gitBranch.loading': 'Reading branches...',
'terminal.gitBranch.empty': 'No local branches yet',
'terminal.gitBranch.noMatches': 'No matching branches',
'terminal.gitBranch.unavailable': 'Could not read branches for this session.',
'terminal.directory.unknown': 'Directory unknown',
'terminal.directory.search': 'Search child directories...',
'terminal.directory.directories': 'Directories',
@@ -16,6 +24,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 +478,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 +629,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,9 +709,11 @@ 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',
'tabs.convertToWorkspace': 'Convert to Workspace',
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
'tabs.closeOthers': 'Close Others',
@@ -988,4 +1004,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})',
};
+4 -1
View File
@@ -882,7 +882,7 @@ export const enVaultMessages: Messages = {
'hostDetails.systemSshAgent.socket': 'Agent Socket',
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Do not try unrelated keys currently loaded in the agent',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
'hostDetails.systemSshAgent.notRunningHint': 'Start or unlock your SSH agent, or provide its socket path above.',
'hostDetails.keys.search': 'Search keys...',
@@ -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.',
};
+46
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const esAiMessages: Messages = {
'ai.grok.chooseModeAndSend': 'Elegir el modo de Grok y enviar…',
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
'ai.chat.continue': 'Continuar',
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
@@ -117,6 +118,9 @@ export const esAiMessages: Messages = {
'ai.codex.appServer.available': 'App Server está disponible para esta Codex CLI.',
'ai.codex.appServer.modelCatalogWarning': 'El catálogo de modelos de Codex en vivo no está disponible. Se usa la lista de modelos integrada.',
'ai.codex.appServer.approval.allowSession': 'Permitir por sesión',
'ai.planReview.title': 'Revisar el plan de implementación',
'ai.planReview.keepPlanning': 'Seguir planificando',
'ai.planReview.approveAndImplement': 'Aprobar e implementar',
'ai.codex.appServer.userInput.title': 'Codex necesita tu aporte',
'ai.codex.appServer.userInput.description': 'Responde estas preguntas para continuar el turno actual.',
'ai.codex.appServer.userInput.other': 'Ingresa otra respuesta',
@@ -305,6 +309,16 @@ export const esAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 no pudo adjuntar una herramienta MCP. El chat continuará sin ella.',
// AI MiMo Code (CLI de Xiaomi MiMo Code — fork de OpenCode)
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': 'Beta experimental: CLI del agente de codificación Antigravity de Google conectado mediante el Agent Client Protocol oficial (agy acp --stdio). El soporte aún es limitado y no ha sido probado a fondo; úsalo bajo tu propia responsabilidad. Inicia sesión con agy en tu terminal y selecciónalo como agente externo.',
'ai.agy.detecting': 'Detectando...',
'ai.agy.detected': 'Detectado',
'ai.agy.notFound': 'No encontrado',
'ai.agy.path': 'Ruta:',
'ai.agy.notFoundHint': 'No se pudo encontrar agy en el PATH. Instala Antigravity CLI o especifica la ruta del ejecutable a continuación.',
'ai.agy.customPathPlaceholder': 'p. ej. /usr/local/bin/agy',
'ai.agy.check': 'Verificar',
'ai.agy.resetPath': 'Restablecer',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'CLI de MiMo Code de Xiaomi, un fork de OpenCode. Instálalo y configura los proveedores en su propia configuración, luego selecciónalo como agente de codificación externo.',
'ai.mimo.detecting': 'Detectando...',
@@ -328,6 +342,9 @@ export const esAiMessages: Messages = {
'ai.grok.check': 'Verificar',
'ai.grok.resetPath': 'Restablecer',
'ai.grok.runtime.acp.title': 'Usar Grok ACP (agente stdio)',
'ai.grok.userQuestion.title': 'Grok necesita tu respuesta',
'ai.grok.userQuestion.description': 'Las respuestas no conceden permisos. No incluyas contraseñas ni tokens.',
'ai.grok.userQuestion.submit': 'Enviar respuestas',
'ai.grok.runtime.acp.default': 'Predeterminado',
'ai.grok.runtime.acp.description':
'Habla con Grok mediante el Protocolo de Cliente de Agente (grok agent stdio). Inyecta el MCP de Netcatty en session/new. Apágalo para usar la ruta original de CLI headless con streaming-json.',
@@ -629,12 +646,25 @@ 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.managerRegenerateTitleUpdated': 'Título del chat actualizado.',
'ai.chat.managerRegenerateTitleUnchanged': 'El título del chat ya está actualizado.',
'ai.chat.managerRegenerateTitleNoModel': 'No hay un proveedor o modelo de IA configurado para generar títulos. Configúralo en Ajustes de IA.',
'ai.chat.managerRegenerateTitleFailed': 'Error al regenerar el título: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Se actualizaron {n} título(s) de chat.',
'ai.chat.managerRegenerateTitleBatchPartial': 'Se actualizaron {updated} título(s) y fallaron {failed}.',
'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',
@@ -685,9 +715,25 @@ export const esAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Mostrar "Agregar a la conversación" al seleccionar texto de la terminal',
'ai.chatShortcuts.selectionAction.description': 'Muestra un pequeño botón de IA junto al texto seleccionado de la terminal.',
'ai.chatHistory.title': 'Historial de chat',
'ai.chatHistory.storageUsage': 'Tamaño del historial de chats local',
'ai.chatHistory.storageUsage.description': 'Calcula el tamaño de los registros guardados como JSON UTF-8.',
'ai.chatHistory.storageUsage.measure': 'Calcular',
'ai.chatHistory.storageUsage.measuring': 'Calculando…',
'ai.chatHistory.storageUsage.result': 'Registros guardados · {count}. Tamaño estimado del JSON · {size}.',
'ai.chatHistory.storageUsage.partial': 'Registros excluidos del cálculo · {count}.',
'ai.chatHistory.storageUsage.error': 'No se pudo leer el historial de chats local. Vuelve a intentarlo.',
'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.',
+47
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.',
@@ -999,6 +1001,9 @@ Resalta el panel dividido enfocado:
'Elige si las sugerencias de autocompletado del historial provienen solo del host actual o de los comandos registrados en todos los hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Host actual',
'settings.terminal.autocomplete.historyScope.global': 'Todos los hosts',
'settings.terminal.autocomplete.showSnippets': 'Mostrar fragmentos de código',
'settings.terminal.autocomplete.showSnippets.desc':
'Incluye fragmentos de código coincidentes en la lista de autocompletado. Desactiva esta opción si los fragmentos desplazan las sugerencias de comandos e historial.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Asistencia para solicitud de contraseña',
@@ -1027,6 +1032,9 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.recording': 'Presiona teclas...',
'settings.shortcuts.none': 'Ninguno',
'settings.shortcuts.setDisabled': 'Configurar como desactivado',
'settings.shortcuts.addExtra': 'Añadir atajo',
'settings.shortcuts.additional': 'Atajo adicional',
'settings.shortcuts.removeExtra': 'Eliminar atajo',
'settings.shortcuts.category.tabs': 'Pestañas',
'settings.shortcuts.category.terminal': 'Terminal',
'settings.shortcuts.category.navigation': 'Navegación',
@@ -1062,6 +1070,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 +1339,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 +1507,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',
};
+24
View File
@@ -2,6 +2,14 @@ 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.gitBranch.search': 'Buscar ramas locales...',
'terminal.gitBranch.branches': 'Ramas locales',
'terminal.gitBranch.loading': 'Leyendo ramas...',
'terminal.gitBranch.empty': 'Aún no hay ramas locales',
'terminal.gitBranch.noMatches': 'No hay ramas coincidentes',
'terminal.gitBranch.unavailable': 'No se pudieron leer las ramas de esta sesión.',
'terminal.directory.unknown': 'Directorio desconocido',
'terminal.directory.search': 'Buscar subdirectorios...',
'terminal.directory.directories': 'Directorios',
@@ -16,6 +24,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 +478,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 +629,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,9 +711,11 @@ 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',
'tabs.convertToWorkspace': 'Convertir en espacio de trabajo',
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
'tabs.closeOthers': 'Cerrar las demás',
@@ -990,4 +1006,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})',
};
+4 -1
View File
@@ -878,7 +878,7 @@ export const esVaultMessages: Messages = {
'hostDetails.systemSshAgent.socket': 'Socket del agente',
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'No intentar con claves no relacionadas actualmente cargadas en el agente',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
'hostDetails.systemSshAgent.notRunningHint': 'Inicia o desbloquea tu agente SSH, o proporciona la ruta de su socket arriba.',
'hostDetails.keys.search': 'Buscar claves...',
@@ -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`);
}
}
}
});
+46
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const ruAiMessages: Messages = {
'ai.grok.chooseModeAndSend': 'Выбрать режим Grok и отправить…',
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
'ai.chat.continue': 'Продолжить',
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
@@ -117,6 +118,9 @@ export const ruAiMessages: Messages = {
'ai.codex.appServer.available': 'Эта версия Codex CLI поддерживает App Server.',
'ai.codex.appServer.modelCatalogWarning': 'Динамический каталог моделей Codex недоступен. Используется встроенный список моделей.',
'ai.codex.appServer.approval.allowSession': 'Разрешить для сеанса',
'ai.planReview.title': 'Проверить план реализации',
'ai.planReview.keepPlanning': 'Продолжить планирование',
'ai.planReview.approveAndImplement': 'Одобрить и приступить к реализации',
'ai.codex.appServer.userInput.title': 'Codex требуется ваш ответ',
'ai.codex.appServer.userInput.description': 'Ответьте на вопросы, чтобы продолжить текущую задачу.',
'ai.codex.appServer.userInput.other': 'Введите другой ответ',
@@ -296,6 +300,9 @@ export const ruAiMessages: Messages = {
'ai.grok.check': 'Проверить',
'ai.grok.resetPath': 'Сбросить',
'ai.grok.runtime.acp.title': 'Использовать Grok ACP (agent stdio)',
'ai.grok.userQuestion.title': 'Grok ждёт вашего ответа',
'ai.grok.userQuestion.description': 'Ответы не предоставляют разрешений. Не указывайте пароли и токены.',
'ai.grok.userQuestion.submit': 'Отправить ответы',
'ai.grok.runtime.acp.default': 'По умолчанию',
'ai.grok.runtime.acp.description':
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
@@ -323,6 +330,16 @@ export const ruAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
// MiMo Code
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': 'Экспериментальная бета-версия: CLI агента Google Antigravity через официальный протокол ACP (agy acp --stdio). Поддержка пока ограничена и не прошла полноценного тестирования — используйте на свой страх и риск. Выполните вход через agy в терминале и выберите его как внешнего агента.',
'ai.agy.detecting': 'Поиск…',
'ai.agy.detected': 'Найден',
'ai.agy.notFound': 'Не найден',
'ai.agy.path': 'Путь:',
'ai.agy.notFoundHint': 'Не удалось найти agy в PATH. Установите Antigravity CLI или укажите путь к исполняемому файлу ниже.',
'ai.agy.customPathPlaceholder': 'например, /usr/local/bin/agy',
'ai.agy.check': 'Проверить',
'ai.agy.resetPath': 'Сбросить',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
'ai.mimo.detecting': 'Поиск…',
@@ -628,12 +645,25 @@ 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.managerRegenerateTitleUpdated': 'Заголовок чата обновлён.',
'ai.chat.managerRegenerateTitleUnchanged': 'Заголовок чата уже актуален.',
'ai.chat.managerRegenerateTitleNoModel': 'Не настроен провайдер/модель ИИ для генерации заголовков. Настройте модель в настройках ИИ.',
'ai.chat.managerRegenerateTitleFailed': 'Не удалось пересоздать заголовок: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Обновлено заголовков: {n}.',
'ai.chat.managerRegenerateTitleBatchPartial': 'Обновлено {updated}, ошибок: {failed}.',
'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}ч назад',
@@ -684,9 +714,25 @@ export const ruAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
'ai.chatHistory.title': 'История чата',
'ai.chatHistory.storageUsage': 'Размер локальной истории чатов',
'ai.chatHistory.storageUsage.description': 'Оценивает размер сохранённых записей чатов в формате JSON (UTF-8).',
'ai.chatHistory.storageUsage.measure': 'Рассчитать',
'ai.chatHistory.storageUsage.measuring': 'Расчёт…',
'ai.chatHistory.storageUsage.result': 'Сохранено записей — {count}. Примерный размер JSON — {size}.',
'ai.chatHistory.storageUsage.partial': 'Записей, исключённых из расчёта размера, — {count}.',
'ai.chatHistory.storageUsage.error': 'Не удалось прочитать локальную историю чатов. Повторите попытку.',
'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 и попробуйте снова.',
+47
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 отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
@@ -984,6 +986,9 @@ export const ruCoreMessages: Messages = {
'Выберите, брать ли подсказки истории автодополнения только с текущего хоста или со всех хостов.',
'settings.terminal.autocomplete.historyScope.host': 'Текущий хост',
'settings.terminal.autocomplete.historyScope.global': 'Все хосты',
'settings.terminal.autocomplete.showSnippets': 'Показывать сниппеты',
'settings.terminal.autocomplete.showSnippets.desc':
'Включать подходящие сниппеты в список автодополнения. Отключите, если сниппеты вытесняют подсказки команд и истории.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Подсказки пароля',
@@ -1012,6 +1017,9 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.recording': 'Нажмите клавиши...',
'settings.shortcuts.none': 'Нет',
'settings.shortcuts.setDisabled': 'Отключить',
'settings.shortcuts.addExtra': 'Добавить сочетание',
'settings.shortcuts.additional': 'Дополнительное сочетание',
'settings.shortcuts.removeExtra': 'Удалить сочетание',
'settings.shortcuts.category.tabs': 'Вкладки',
'settings.shortcuts.category.terminal': 'Терминал',
'settings.shortcuts.category.navigation': 'Навигация',
@@ -1046,6 +1054,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 +1280,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 +1448,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': 'Политика',
};
+22
View File
@@ -2,6 +2,14 @@ import type { Messages } from '../types';
export const ruTerminalMessages: Messages = {
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
'terminal.gitBranch.search': 'Поиск локальных веток...',
'terminal.gitBranch.branches': 'Локальные ветки',
'terminal.gitBranch.loading': 'Чтение веток...',
'terminal.gitBranch.empty': 'Локальных веток пока нет',
'terminal.gitBranch.noMatches': 'Ветки не найдены',
'terminal.gitBranch.unavailable': 'Не удалось прочитать ветки для этого сеанса.',
'terminal.directory.unknown': 'Каталог неизвестен',
'terminal.directory.search': 'Поиск подкаталогов...',
'terminal.directory.directories': 'Каталоги',
@@ -16,6 +24,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 +498,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 +646,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,9 +724,11 @@ export const ruTerminalMessages: Messages = {
'tabs.logPrefix': 'Журнал:',
'tabs.logLocal': 'Локальный',
'tabs.copyTab': 'Копировать вкладку',
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
'tabs.duplicateSession': 'Дублировать сессию',
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
'tabs.convertToWorkspace': 'Преобразовать в рабочую область',
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
'tabs.closeOthers': 'Закрыть остальные',
@@ -1004,4 +1018,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})',
};
+4 -1
View File
@@ -924,7 +924,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.systemSshAgent.socket': 'Сокет агента',
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Не пробовать другие ключи, загруженные в агент',
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
'hostDetails.systemSshAgent.notRunningHint': 'Запустите или разблокируйте SSH-агент либо укажите путь к его сокету выше.',
'hostDetails.keys.search': 'Поиск ключей...',
@@ -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.',
};
@@ -304,3 +304,20 @@ test("localized settings include SFTP tree folder double-click labels across all
}
}
});
test("localized settings include autocomplete show code snippets labels across all locales", () => {
const keys = [
"settings.terminal.autocomplete.showSnippets",
"settings.terminal.autocomplete.showSnippets.desc",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing autocomplete showSnippets labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
+46
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const zhCNAiMessages: Messages = {
'ai.grok.chooseModeAndSend': '选择 Grok 模式并发送…',
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
'ai.chat.continue': '继续',
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
@@ -117,6 +118,9 @@ export const zhCNAiMessages: Messages = {
'ai.codex.appServer.available': '当前 Codex CLI 支持 App Server。',
'ai.codex.appServer.modelCatalogWarning': 'Codex 动态模型目录暂不可用,当前将使用内置模型列表。',
'ai.codex.appServer.approval.allowSession': '本会话允许',
'ai.planReview.title': '审核实施方案',
'ai.planReview.keepPlanning': '继续规划',
'ai.planReview.approveAndImplement': '批准并实施',
'ai.codex.appServer.userInput.title': 'Codex 需要你的输入',
'ai.codex.appServer.userInput.description': '回答以下问题以继续当前任务。',
'ai.codex.appServer.userInput.other': '输入其他答案',
@@ -305,6 +309,16 @@ export const zhCNAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 无法接入 MCP 工具,对话会继续,但没有该工具。',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.agy.title': 'Antigravity CLI(Beta)',
'ai.agy.description': 'Beta 测试中:通过官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。当前支持程度有限且未经充分测试,使用请自担风险。请在终端完成 agy 登录后再作为外部编程 Agent 使用。',
'ai.agy.detecting': '检测中...',
'ai.agy.detected': '已检测到',
'ai.agy.notFound': '未找到',
'ai.agy.path': '路径:',
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。请安装 Antigravity CLI 或在下方指定可执行文件路径。',
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
'ai.agy.check': '检查',
'ai.agy.resetPath': '重置',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安装后在它自己的配置里配置 provider 和密钥,检测到后即可作为外部编程 Agent 使用。',
'ai.mimo.detecting': '检测中...',
@@ -328,6 +342,9 @@ export const zhCNAiMessages: Messages = {
'ai.grok.check': '检查',
'ai.grok.resetPath': '重置',
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
'ai.grok.userQuestion.description': '回答不会改变权限。请勿填写密码或令牌。',
'ai.grok.userQuestion.submit': '发送回答',
'ai.grok.runtime.acp.default': '默认',
'ai.grok.runtime.acp.description':
'通过 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。关闭后使用原始 headless streaming-json CLI 路径。',
@@ -629,12 +646,25 @@ 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.managerRegenerateTitleUpdated': '会话标题已更新。',
'ai.chat.managerRegenerateTitleUnchanged': '会话标题已是最新。',
'ai.chat.managerRegenerateTitleNoModel': '未配置用于生成标题的 AI 模型,请在 AI 设置中配置提供商或标题模型。',
'ai.chat.managerRegenerateTitleFailed': '重新生成标题失败:{error}',
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 个会话标题。',
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 个标题,{failed} 个失败。',
'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}小时前',
@@ -685,9 +715,25 @@ export const zhCNAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': '选中终端内容时显示“添加到对话”',
'ai.chatShortcuts.selectionAction.description': '在终端里选中文本后显示 AI 快捷按钮。',
'ai.chatHistory.title': '聊天历史',
'ai.chatHistory.storageUsage': '本地聊天历史大小',
'ai.chatHistory.storageUsage.description': '按 UTF-8 JSON 估算已保存的聊天记录大小。',
'ai.chatHistory.storageUsage.measure': '估算',
'ai.chatHistory.storageUsage.measuring': '正在估算…',
'ai.chatHistory.storageUsage.result': '已保存 {count} 条记录,JSON 大小约为 {size}。',
'ai.chatHistory.storageUsage.partial': '其中 {count} 条记录未计入大小估算。',
'ai.chatHistory.storageUsage.error': '无法读取本地聊天历史,请重试。',
'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,14 @@ import type { Messages } from '../types';
export const zhCNTerminalMessages: Messages = {
'terminal.directory.open': '当前目录:{path}。更改目录',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
'terminal.gitBranch.search': '搜索本地分支…',
'terminal.gitBranch.branches': '本地分支',
'terminal.gitBranch.loading': '正在读取分支…',
'terminal.gitBranch.empty': '还没有本地分支',
'terminal.gitBranch.noMatches': '没有匹配的分支',
'terminal.gitBranch.unavailable': '无法读取此会话的分支。',
'terminal.directory.unknown': '目录未知',
'terminal.directory.search': '搜索当前目录下的文件夹…',
'terminal.directory.directories': '目录',
@@ -16,6 +24,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': '请等待终端回到空命令提示符。',
@@ -571,6 +580,9 @@ export const zhCNTerminalMessages: Messages = {
'选择自动补全的历史建议来自当前主机,还是所有主机上执行过的命令。',
'settings.terminal.autocomplete.historyScope.host': '当前主机',
'settings.terminal.autocomplete.historyScope.global': '全部主机',
'settings.terminal.autocomplete.showSnippets': '显示代码片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在补全列表中显示匹配的代码片段。若片段较多、排在列表前面,可关闭此项。',
'settings.terminal.section.passwordPromptAssist': '密码提示辅助',
'settings.terminal.passwordPromptAssist.mode': '辅助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
@@ -597,6 +609,9 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.recording': '请按键...',
'settings.shortcuts.none': '无',
'settings.shortcuts.setDisabled': '设为禁用',
'settings.shortcuts.addExtra': '添加快捷键',
'settings.shortcuts.additional': '附加快捷键',
'settings.shortcuts.removeExtra': '移除快捷键',
'settings.shortcuts.category.tabs': '标签页',
'settings.shortcuts.category.terminal': '终端',
'settings.shortcuts.category.navigation': '导航',
@@ -630,6 +645,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 +735,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,9 +813,11 @@ export const zhCNTerminalMessages: Messages = {
'tabs.logPrefix': '日志:',
'tabs.logLocal': '本地',
'tabs.copyTab': '复制标签页',
'tabs.addSessionToWorkspace': '在此工作区添加会话',
'tabs.duplicateSession': '复制会话',
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
'tabs.convertToWorkspace': '转为工作区',
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
'tabs.closeOthers': '关闭其他标签',
@@ -1088,4 +1108,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})',
};
+5 -1
View File
@@ -309,7 +309,7 @@ export const zhCNVaultMessages: Messages = {
'hostDetails.systemSshAgent.socket': '代理地址',
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
'hostDetails.systemSshAgent.identitiesOnly.desc': '不尝试代理中其他无关密钥',
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
'hostDetails.systemSshAgent.notRunningHint': '请启动或解锁密钥服务,或者在上方填写它的地址。',
'hostDetails.keys.search': '搜索密钥…',
@@ -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。',
};
+46
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const zhTWAiMessages: Messages = {
'ai.grok.chooseModeAndSend': '選擇 Grok 模式並傳送…',
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
'ai.chat.continue': '繼續',
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
@@ -117,6 +118,9 @@ export const zhTWAiMessages: Messages = {
'ai.codex.appServer.available': '目前 Codex CLI 支援 App Server。',
'ai.codex.appServer.modelCatalogWarning': 'Codex 動態模型目錄暫時無法使用,目前將使用內建模型清單。',
'ai.codex.appServer.approval.allowSession': '本工作階段允許',
'ai.planReview.title': '審核實作方案',
'ai.planReview.keepPlanning': '繼續規劃',
'ai.planReview.approveAndImplement': '批准並實作',
'ai.codex.appServer.userInput.title': 'Codex 需要你的輸入',
'ai.codex.appServer.userInput.description': '回答以下問題以繼續目前任務。',
'ai.codex.appServer.userInput.other': '輸入其他答案',
@@ -305,6 +309,16 @@ export const zhTWAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 無法掛接 MCP 工具,對話會繼續,但沒有該工具。',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.agy.title': 'Antigravity CLI(Beta)',
'ai.agy.description': 'Beta 測試中:透過官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。目前支援程度有限且未經充分測試,使用請自負風險。請在終端完成 agy 登入後再作為外部程式設計 Agent 使用。',
'ai.agy.detecting': '偵測中...',
'ai.agy.detected': '已偵測到',
'ai.agy.notFound': '未找到',
'ai.agy.path': '路徑:',
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。請安裝 Antigravity CLI 或在下方指定執行檔路徑。',
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
'ai.agy.check': '檢查',
'ai.agy.resetPath': '重設',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安裝後在它自己的設定裡設定 provider 和金鑰,偵測到後即可作為外部程式設計 Agent 使用。',
'ai.mimo.detecting': '偵測中...',
@@ -328,6 +342,9 @@ export const zhTWAiMessages: Messages = {
'ai.grok.check': '檢查',
'ai.grok.resetPath': '重設',
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
'ai.grok.userQuestion.description': '回答不會變更權限。請勿填寫密碼或權杖。',
'ai.grok.userQuestion.submit': '傳送回答',
'ai.grok.runtime.acp.default': '預設',
'ai.grok.runtime.acp.description':
'透過 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。關閉後使用原始 headless streaming-json CLI 路徑。',
@@ -628,12 +645,25 @@ 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.managerRegenerateTitleUpdated': '會話標題已更新。',
'ai.chat.managerRegenerateTitleUnchanged': '會話標題已是最新。',
'ai.chat.managerRegenerateTitleNoModel': '未設定用於產生標題的 AI 模型,請在 AI 設定中設定供應商或標題模型。',
'ai.chat.managerRegenerateTitleFailed': '重新產生標題失敗:{error}',
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 個會話標題。',
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 個標題,{failed} 個失敗。',
'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}小時前',
@@ -684,9 +714,25 @@ export const zhTWAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': '選取終端內容時顯示「新增到對話」',
'ai.chatShortcuts.selectionAction.description': '在終端裡選取文字後顯示 AI 快捷按鈕。',
'ai.chatHistory.title': '聊天歷史',
'ai.chatHistory.storageUsage': '本機聊天記錄大小',
'ai.chatHistory.storageUsage.description': '以 UTF-8 JSON 估算已儲存的聊天記錄大小。',
'ai.chatHistory.storageUsage.measure': '估算',
'ai.chatHistory.storageUsage.measuring': '正在估算…',
'ai.chatHistory.storageUsage.result': '已儲存 {count} 筆記錄,JSON 大小約為 {size}。',
'ai.chatHistory.storageUsage.partial': '其中 {count} 筆記錄未計入大小估算。',
'ai.chatHistory.storageUsage.error': '無法讀取本機聊天記錄,請再試一次。',
'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,14 @@ import type { Messages } from '../types';
export const zhTWTerminalMessages: Messages = {
'terminal.directory.open': '目前目錄:{path}。變更目錄',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
'terminal.gitBranch.search': '搜尋本機分支…',
'terminal.gitBranch.branches': '本機分支',
'terminal.gitBranch.loading': '正在讀取分支…',
'terminal.gitBranch.empty': '還沒有本機分支',
'terminal.gitBranch.noMatches': '沒有符合的分支',
'terminal.gitBranch.unavailable': '無法讀取此工作階段的分支。',
'terminal.directory.unknown': '目錄未知',
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
'terminal.directory.directories': '目錄',
@@ -16,6 +24,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': '請等待終端回到空白命令提示字元。',
@@ -571,6 +580,9 @@ export const zhTWTerminalMessages: Messages = {
'選擇自動補全的歷史建議來自目前主機,還是所有主機上執行過的指令。',
'settings.terminal.autocomplete.historyScope.host': '目前主機',
'settings.terminal.autocomplete.historyScope.global': '全部主機',
'settings.terminal.autocomplete.showSnippets': '顯示程式碼片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在補全列表中顯示符合的程式碼片段。若片段較多、排在列表前面,可關閉此項。',
'settings.terminal.section.passwordPromptAssist': '密碼提示輔助',
'settings.terminal.passwordPromptAssist.mode': '輔助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
@@ -597,6 +609,9 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.recording': '請按鍵...',
'settings.shortcuts.none': '無',
'settings.shortcuts.setDisabled': '設為停用',
'settings.shortcuts.addExtra': '新增快速鍵',
'settings.shortcuts.additional': '附加快速鍵',
'settings.shortcuts.removeExtra': '移除快速鍵',
'settings.shortcuts.category.tabs': '分頁',
'settings.shortcuts.category.terminal': '終端',
'settings.shortcuts.category.navigation': '導航',
@@ -630,6 +645,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 +735,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,9 +813,11 @@ export const zhTWTerminalMessages: Messages = {
'tabs.logPrefix': '日誌:',
'tabs.logLocal': '本機',
'tabs.copyTab': '複製分頁',
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
'tabs.duplicateSession': '複製工作階段',
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
'tabs.convertToWorkspace': '轉為工作區',
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
'tabs.closeOthers': '關閉其他分頁',
@@ -1088,4 +1108,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})',
};
+5 -1
View File
@@ -309,7 +309,7 @@ export const zhTWVaultMessages: Messages = {
'hostDetails.systemSshAgent.socket': '代理位址',
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
'hostDetails.systemSshAgent.identitiesOnly.desc': '不嘗試代理中其他無關金鑰',
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
'hostDetails.systemSshAgent.notRunningHint': '請啟動或解鎖金鑰服務,或在上方填寫其位址。',
'hostDetails.keys.search': '搜尋金鑰…',
@@ -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。',
};
+38
View File
@@ -79,6 +79,44 @@ test('prepared apply callback runs after the snapshot with sentinel protection',
assert.equal(readInterruptedVaultApply(), null);
});
test('protected sync does not apply anything if storage cannot persist its interruption marker', async (t) => {
const storage = globalThis.localStorage;
const originalSetItem = storage.setItem;
t.after(() => { storage.setItem = originalSetItem; });
storage.setItem = () => { throw new DOMException('No storage space', 'QuotaExceededError'); };
let applied = false;
await assert.rejects(() => applyProtectedSyncPayload({
buildPreApplyPayload: emptyPayload,
applyPayload: () => { applied = true; },
translateProtectiveBackupFailure: (message) => message,
}), /interruption marker/);
assert.equal(applied, false);
assert.equal(readInterruptedVaultApply(), null);
});
test('protected sync rejects a missing backup even when the backup bridge resolves', async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
else Reflect.deleteProperty(globalThis, 'window');
});
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
netcatty: { createVaultBackup: async () => ({ backup: null }) },
} });
let applied = false;
await assert.rejects(() => applyProtectedSyncPayload({
buildPreApplyPayload: () => ({ ...emptyPayload(), settings: { theme: 'light' } }),
applyPayload: () => { applied = true; },
translateProtectiveBackupFailure: (message) => message,
}), /no recoverable backup/);
assert.equal(applied, false);
assert.equal(readInterruptedVaultApply(), null);
});
for (const localRestore of [false, true]) {
for (const encryptionFails of [false, true]) {
test(`protected header preparation (${localRestore ? 'restore' : 'sync'}, ${encryptionFails ? 'failure' : 'success'})`, async () => {
+12 -11
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;
};
}
@@ -238,7 +241,10 @@ export async function createRequiredProtectiveLocalVaultBackup(
reason: 'before_restore',
maxCount: getLocalVaultBackupMaxCount(),
});
return result?.backup ?? null;
if (!result?.backup?.id) {
throw new Error('Vault backup service returned no recoverable backup');
}
return result.backup;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ProtectiveBackupUnavailableError(message);
@@ -378,16 +384,11 @@ export function clearInterruptedVaultApply(): void {
}
function writeApplyInProgressSentinel(record: VaultApplyInProgressRecord): void {
try {
localStorageAdapter.writeString(
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
JSON.stringify(record),
);
} catch (error) {
// Sentinel write is best-effort: a failure here means a later crash
// won't be detected, but does NOT compromise the apply itself.
// Log so a systematic storage outage is diagnosable.
console.warn('[localVaultBackups] Failed to set apply-in-progress sentinel:', error);
if (!localStorageAdapter.writeString(
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
JSON.stringify(record),
)) {
throw new Error('Cannot persist the sync interruption marker; local data was not changed');
}
}
@@ -15,6 +15,7 @@ import {
idbPutSessions,
isIndexedDbAvailable,
loadOrMigrateAiSessions,
measureAiSessionStorageUsage,
mirrorActiveSessionMapToIdb,
openAiSessionsIdb,
readActiveSessionMapFromIdb,
@@ -57,6 +58,27 @@ test('module wrapper roundtrips sessions through the object stores', async () =>
}
});
test('usage reads UTF-8 JSON sizes without changing unreadable or healthy records', async () => {
const idb = installFakeIndexedDb();
try {
const signal = new AbortController().signal;
assert.deepEqual(await measureAiSessionStorageUsage(signal), { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 });
const db = await openAiSessionsIdb();
const session = { ...makeSession('old-chat', 1), title: '旧聊天 🐈' };
const bad = { ...makeSession('cycle', 2), data: {} };
bad.data = bad;
await idbPutSessions(db, [session, bad]);
assert.deepEqual(await measureAiSessionStorageUsage(signal), {
recordCount: 2, jsonBytes: Buffer.byteLength(JSON.stringify(session)), unmeasuredCount: 1,
});
assert.deepEqual(idb.db.opCounts.get('sessions'), { put: 2, delete: 0 });
await assert.rejects(measureAiSessionStorageUsage(AbortSignal.abort()), { name: 'AbortError' });
} finally {
idb.restore();
resetAiSessionsIdbForTests();
}
});
test('meta store roundtrips schema and active-map records', async () => {
const idb = installFakeIndexedDb();
try {
+41
View File
@@ -108,6 +108,47 @@ export async function idbGetAllSessions(db?: IDBDatabase): Promise<AISession[]>
return Array.isArray(result) ? result : [];
}
export interface AiSessionStorageUsage {
recordCount: number;
jsonBytes: number;
unmeasuredCount: number;
}
/** Size of the JSON payloads in a consistent read-only snapshot of local history. */
export async function measureAiSessionStorageUsage(signal: AbortSignal): Promise<AiSessionStorageUsage> {
signal.throwIfAborted();
const db = await openAiSessionsIdb();
signal.throwIfAborted();
const tx = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readonly');
const request = tx.objectStore(AI_SESSIONS_IDB_SESSION_STORE).openCursor();
const usage = { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 };
const encoder = new TextEncoder();
return new Promise((resolve, reject) => {
tx.onabort = () => reject(tx.error ?? new Error('History scan aborted'));
request.onerror = () => reject(request.error);
request.onsuccess = () => {
if (signal.aborted) {
reject(signal.reason);
return;
}
const cursor = request.result;
if (!cursor) {
resolve(usage);
return;
}
usage.recordCount++;
try {
usage.jsonBytes += encoder.encode(JSON.stringify(cursor.value)).byteLength;
} catch {
// Structured clone also accepts cycles and BigInts, which JSON cannot represent.
usage.unmeasuredCount++;
}
cursor.continue();
};
});
}
export async function idbPutSessions(db: IDBDatabase, sessions: AISession[]): Promise<void> {
if (sessions.length === 0) return;
const transaction = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readwrite');
+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,
};
@@ -90,6 +90,7 @@ test('session actions register and unregister', () => {
clearSessionFontSizeOverride: noop,
createWorkspaceWithHosts: noop,
createWorkspaceFromSessions: noop,
convertSessionToWorkspace: noop,
addSessionToWorkspace: noop,
appendHostToWorkspace: noop,
appendHostToWorkspaceConfirmed: noop,
@@ -57,6 +57,7 @@ export type SessionSnapshotActions = Pick<
| 'clearSessionFontSizeOverride'
| 'createWorkspaceWithHosts'
| 'createWorkspaceFromSessions'
| 'convertSessionToWorkspace'
| 'addSessionToWorkspace'
| 'moveWorkspacePane'
| 'appendHostToWorkspace'
+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,
@@ -5,6 +5,8 @@ import { terminalCwdStore } from './terminalCwdStore';
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
import { gitSwitchCommand } from '../../domain/terminalGitHead';
function setup(overrides: Partial<TerminalDirectoryIO> = {}) {
let cwd = '/old'; let ready = true; let current = true;
const writes: string[] = [];
@@ -47,6 +49,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 +210,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');
});
}
@@ -268,3 +271,40 @@ for (const cancellation of ['abort', 'dispose'] as const) {
await assert.rejects(controller.change('/next', abort.signal, () => {}), { code: 'unavailable' });
});
}
test('local command submission rechecks cwd and prompt readiness before writing', async t => {
const sessionId = 'local-command';
const writes: string[] = [];
let ready = true;
let finishCwd!: (cwd: string) => void;
const controller = createTerminalDirectoryController({
sessionId, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => ready,
io: { cwd: () => new Promise(resolve => { finishCwd = resolve; }), list: async () => ({ entries: [], home: null }),
realpath: async value => value, write: data => { writes.push(data); } },
publish() {},
});
terminalCwdStore.setCwd(sessionId, '/repo', 'osc7');
t.after(() => { controller.dispose(); terminalCwdStore.setCwd(sessionId, null); });
const command = gitSwitchCommand("/repo", "topic/it's-$special");
assert.ok(command);
const send = (signal = new AbortController().signal) => controller.sendLocalCommand(command, '/repo', signal);
const moved = send();
finishCwd('/other');
await assert.rejects(moved, { code: 'unavailable' });
const busy = send();
ready = false;
finishCwd('/repo');
await assert.rejects(busy, { code: 'busy' });
ready = true;
const request = new AbortController();
const cancelled = send(request.signal);
request.abort();
finishCwd('/repo');
await assert.rejects(cancelled, { code: 'unavailable' });
assert.deepEqual(writes, []);
const sent = send();
finishCwd('/repo');
await sent;
assert.deepEqual(writes, [command + '\r']);
});
@@ -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,47 @@ export function createTerminalDirectoryController(options: {
};
await Promise.race([confirmFromProbe(), confirmFromOsc7()]);
check(signal);
confirmed = true;
} finally { confirmationFinished = true; changing = false; }
}
async function sendLocalCommand(command: string, expectedCwd: string, signal: AbortSignal) {
ready();
check(signal);
if (!options.localPosixSessionId || getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (changing) throw new DirectoryPickerError('busy');
changing = true;
try {
const revision = terminalCwdStore.getSessionRevision(options.sessionId);
const liveCwd = await bounded(options.io.cwd(), signal);
if (!same(liveCwd, expectedCwd)) {
const [livePath, expectedPath] = await bounded(Promise.all([
options.io.realpath(liveCwd, signal), options.io.realpath(expectedCwd, signal),
]), signal);
if (!same(livePath, expectedPath)) throw new DirectoryPickerError('unavailable');
}
check(signal);
ready();
if (getConfirmedCwd() !== expectedCwd || terminalCwdStore.getSessionRevision(options.sessionId) !== revision) {
throw new DirectoryPickerError('unavailable');
}
options.io.write(command + '\r');
} finally { changing = false; }
}
return {
target,
localPosixSessionId: options.localPosixSessionId,
capabilities,
trustsOsc7,
getVerifiedCwd: () => verifiedCwd,
getConfirmedCwd,
sendLocalCommand,
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(() => {});
}
/**
+19 -1
View File
@@ -1,7 +1,7 @@
/**
* Minimal in-memory IndexedDB stub covering the exact subset used by
* `aiSessionIdbStorage.ts`: open + upgrade (createObjectStore), readonly
* getAll/get, readwrite put/delete/clear, and meta-store records. Not a
* getAll/get/openCursor, readwrite put/delete/clear, and meta-store records. Not a
* general-purpose IDB implementation — extend deliberately if the wrapper
* grows new usage.
*/
@@ -70,6 +70,24 @@ export class FakeObjectStore {
return new FakeRequest(this.records.get(String(key)));
}
openCursor() {
const entries = this.records.values();
type Cursor = { value: unknown; continue: () => void };
const next = (): Cursor | null => {
const entry = entries.next();
if (entry.done) return null;
return {
value: entry.value,
continue: () => queueMicrotask(() => {
request.result = next();
request.onsuccess?.(request);
}),
};
};
const request: FakeRequest<Cursor | null> = new FakeRequest(next());
return request;
}
getAll(): FakeRequest<unknown[]> {
return new FakeRequest(Array.from(this.records.values()));
}
+1
View File
@@ -139,6 +139,7 @@ export interface SendToExternalContext {
defaultTargetSession?: DefaultTargetSessionHint;
providers: ProviderConfig[];
selectedAgentModel?: string;
chooseGrokMode?: boolean;
toolIntegrationMode: AIToolIntegrationMode;
selectedUserSkillSlugs?: string[];
permissionMode: AIPermissionMode;
+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,365 @@
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();
}
});
test('a queued regeneration preserves a title renamed before its request starts', async () => {
const session = untitledSession();
let calls = 0;
const { capture, cleanup } = await setupHook({
sessions: [session],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async () => { calls += 1; return 'Generated'; },
});
try {
await act(async () => { capture.ai!.updateSessionTitle(session.id, 'Manual'); });
const result = await capture.ai!.regenerateSessionTitle(session.id, session.title);
assert.deepEqual(result, { status: 'unchanged', title: 'Manual' });
assert.equal(calls, 0);
assert.equal(capture.sessions[0].title, 'Manual');
} finally {
await cleanup();
}
});
@@ -128,3 +128,64 @@ test('restored workspace enters a blank draft when New Chat is clicked', async (
container.remove();
dom.window.close();
});
test('async clearDraftForScope propagates draft removal to sibling useAIState subscribers', async () => {
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
url: 'http://localhost',
});
Object.defineProperty(globalThis, 'window', { configurable: true, value: dom.window });
Object.defineProperty(globalThis, 'document', { configurable: true, value: dom.window.document });
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: dom.window.localStorage });
Object.defineProperty(globalThis, 'CustomEvent', { configurable: true, value: dom.window.CustomEvent });
Object.defineProperty(globalThis, 'Event', { configurable: true, value: dom.window.Event });
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
let writer: ReturnType<typeof useAIState> | null = null;
let readerDraftText: string | undefined;
function Writer() {
writer = useAIState();
return null;
}
function Reader() {
useAIState();
const state = useAISessionsStore();
readerDraftText = state.draftsByScope[SCOPE_KEY]?.text;
return <span data-draft={readerDraftText ?? ''} />;
}
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(
<>
<Writer />
<Reader />
</>,
);
});
await act(async () => {
writer!.updateDraft(SCOPE_KEY, 'catty', () => ({
text: 'sent message',
agentId: 'catty',
attachments: [],
selectedUserSkillSlugs: [],
updatedAt: Date.now(),
}));
});
await act(async () => {
await Promise.resolve();
writer!.clearDraftForScope(SCOPE_KEY);
});
assert.equal(readerDraftText, undefined);
assert.equal(container.querySelector('span')?.dataset.draft, '');
await act(async () => root.unmount());
container.remove();
dom.window.close();
});
+381 -89
View File
@@ -10,6 +10,7 @@ import {
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
STORAGE_KEY_AI_AGENT_THINKING_MAP,
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
STORAGE_KEY_UI_LANGUAGE,
} from '../../infrastructure/config/storageKeys';
import type {
AIDraft,
@@ -18,6 +19,7 @@ import type {
HostAIPermission,
ChatMessage,
AISessionScope,
ProviderConfig,
} from '../../infrastructure/ai/types';
import {
activateDraftView,
@@ -98,8 +100,41 @@ 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 type RegenerateSessionTitleResult =
| { status: 'updated'; title: string }
| { status: 'unchanged'; title: string }
| { status: 'busy' }
| { status: 'no-model' }
| { status: 'empty' }
| { status: 'error'; error: string };
function readConfiguredUiLanguage(): string | undefined {
try {
const stored = localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE);
if (stored && stored.trim()) return stored.trim();
} catch {
// Ignore storage read errors.
}
if (typeof navigator !== 'undefined' && typeof navigator.language === 'string' && navigator.language.trim()) {
return navigator.language.trim();
}
return undefined;
}
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 +437,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 +783,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 +806,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 +871,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 +919,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 +954,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 +968,221 @@ 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 bridge = getAIBridge() as {
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
} | undefined;
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
await bridge.aiSyncProviders(providersRef.current);
}
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
{ messages: sourceMessages },
{
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: requestController.signal,
language: readConfiguredUiLanguage(),
},
);
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, expectedTitle?: string): Promise<RegenerateSessionTitleResult> => {
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) {
return { status: 'busy' };
}
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const session = snapshot.find((s) => s.id === sessionId);
if (!session || session.messages.length === 0) {
return { status: 'empty' };
}
if (expectedTitle !== undefined && session.title !== expectedTitle) {
return { status: 'unchanged', title: session.title };
}
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
activeProviderId: activeProviderIdRef.current,
activeModelId: activeModelIdRef.current,
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) {
return { status: 'no-model' };
}
const controller = new AbortController();
titleAbortControllersRef.current.set(sessionId, controller);
let capturedError: unknown = null;
try {
const bridge = getAIBridge() as {
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
} | undefined;
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
await bridge.aiSyncProviders(providersRef.current);
}
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,
language: readConfiguredUiLanguage(),
onError: (err) => { capturedError = err; },
},
);
if (controller.signal.aborted) {
return { status: 'error', error: 'Aborted' };
}
if (!generated) {
const message = capturedError instanceof Error
? capturedError.message
: (capturedError ? String(capturedError) : 'Model returned an empty title');
return { status: 'error', error: message };
}
if (generated === session.title) {
return { status: 'unchanged', title: generated };
}
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;
}
return { status: 'updated', title: generated };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { status: 'error', error: message };
} 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 +1207,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;
});
@@ -1089,20 +1399,12 @@ export function useAIState() {
}, [persistSessions]);
const ensureDraftForScope = useCallback((scopeKey: string, agentId: string): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
setDraftsByScopeRaw((prev) => {
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
if (next === prev) return prev;
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
const prev = latestAIDraftsByScopeSnapshot;
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
if (next === prev) return;
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1113,31 +1415,24 @@ export function useAIState() {
fallbackAgentId: string,
updater: (draft: AIDraft) => AIDraft,
): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
setDraftsByScopeRaw((prev) => {
const next = updateDraftForScope(
prev,
scopeKey,
fallbackAgentId,
(draft) => {
const updated = updater(draft);
if (updated === draft) return draft;
return {
...updated,
updatedAt: Date.now(),
};
},
);
if (next === prev) return prev;
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
const prev = latestAIDraftsByScopeSnapshot;
const next = updateDraftForScope(
prev,
scopeKey,
fallbackAgentId,
(draft) => {
const updated = updater(draft);
if (updated === draft) return draft;
return {
...updated,
updatedAt: Date.now(),
};
},
);
if (next === prev) return;
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1147,32 +1442,25 @@ export function useAIState() {
scopeKey: string,
updater: (draft: AIDraft) => AIDraft,
): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
const prev = latestAIDraftsByScopeSnapshot;
const currentDraft = prev[scopeKey];
if (!currentDraft) return;
setDraftsByScopeRaw((prev) => {
const currentDraft = prev[scopeKey];
if (!currentDraft) return prev;
const updated = updater(currentDraft);
const nextDraft = updated === currentDraft
? currentDraft
: {
...updated,
updatedAt: Date.now(),
};
if (nextDraft === currentDraft) return prev;
const next = {
...prev,
[scopeKey]: nextDraft,
const updated = updater(currentDraft);
const nextDraft = updated === currentDraft
? currentDraft
: {
...updated,
updatedAt: Date.now(),
};
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
if (nextDraft === currentDraft) return;
const next: DraftsByScope = {
...prev,
[scopeKey]: nextDraft,
};
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1207,38 +1495,30 @@ export function useAIState() {
}, [setPanelViewByScope]);
const clearDraftForScope = useCallback((scopeKey: string) => {
const currentPanelViewByScope = panelViewByScope;
let nextDraftsByScope: DraftsByScope | null = null;
let nextPanelViewByScope: PanelViewByScope | null = null;
let draftsChanged = false;
let panelViewChanged = false;
setDraftsByScopeRaw((prevDraftsByScope) => {
const next = clearScopeDraftState(
prevDraftsByScope,
currentPanelViewByScope,
scopeKey,
);
draftsChanged = next.draftsByScope !== prevDraftsByScope;
panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
nextDraftsByScope = next.draftsByScope;
nextPanelViewByScope = next.panelViewByScope;
return draftsChanged ? next.draftsByScope : prevDraftsByScope;
});
const prevDraftsByScope = latestAIDraftsByScopeSnapshot;
const currentPanelViewByScope = latestAIPanelViewByScopeSnapshot ?? panelViewByScope;
const next = clearScopeDraftState(
prevDraftsByScope,
currentPanelViewByScope,
scopeKey,
);
const draftsChanged = next.draftsByScope !== prevDraftsByScope;
const panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
if (!draftsChanged && !panelViewChanged) return;
bumpDraftMutationVersion(scopeKey);
bumpDraftUploadGeneration(scopeKey);
if (draftsChanged && nextDraftsByScope) {
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
if (draftsChanged) {
setLatestAIDraftsByScopeSnapshot(next.draftsByScope);
setDraftsByScopeRaw(next.draftsByScope);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
}
if (panelViewChanged && nextPanelViewByScope) {
setLatestAIPanelViewByScopeSnapshot(nextPanelViewByScope);
setPanelViewByScopeRaw(nextPanelViewByScope);
if (panelViewChanged) {
setLatestAIPanelViewByScopeSnapshot(next.panelViewByScope);
setPanelViewByScopeRaw(next.panelViewByScope);
emitAIStateChanged(AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE);
}
}, [panelViewByScope]);
@@ -1453,6 +1733,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 +1752,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -1522,6 +1808,10 @@ export function useAIState() {
setWebSearchConfig,
quickMessages,
setQuickMessages,
autoLlmTitle,
setAutoLlmTitle,
titleModel,
setTitleModel,
setActiveSessionId,
ensureDraftForScope,
updateDraft,
@@ -1535,6 +1825,8 @@ export function useAIState() {
deleteSession,
deleteSessionsByTarget,
updateSessionTitle,
autoTitleSession,
regenerateSessionTitle,
rebindSessionScope,
exportSessionsBackup,
importSessionsBackup,
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from 'react';
import { measureAiSessionStorageUsage, type AiSessionStorageUsage } from './aiSessionIdbStorage';
type Measurement =
| { status: 'idle' | 'loading' | 'error' }
| { status: 'ready'; usage: AiSessionStorageUsage };
export function useAiSessionStorageUsage() {
const [measurement, setMeasurement] = useState<Measurement>({ status: 'idle' });
const active = useRef<AbortController | null>(null);
useEffect(() => () => active.current?.abort(), []);
async function measure() {
if (active.current) return;
const controller = new AbortController();
active.current = controller;
setMeasurement({ status: 'loading' });
try {
const usage = await measureAiSessionStorageUsage(controller.signal);
if (!controller.signal.aborted) setMeasurement({ status: 'ready', usage });
} catch {
if (!controller.signal.aborted) setMeasurement({ status: 'error' });
} finally {
active.current = null;
}
}
return { measurement, measure };
}
+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>['head'];
function Harness() { head = useComposeGitBranch(id).head; 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);
});
+98
View File
@@ -0,0 +1,98 @@
import { DirectoryPickerError } from '../../domain/directoryPicker';
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { gitSwitchCommand, 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) {
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);
const scope = useMemo(() => controller && backendId && cwd ? { controller, backendId, cwd, sessionId } : null,
[backendId, controller, cwd, sessionId]);
const isCurrent = () => scope !== null && getTerminalDirectory(sessionId) === scope.controller
&& scope.controller.getConfirmedCwd() === scope.cwd;
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]);
const head = result?.controller === controller && result.cwd === cwd ? result.head : null;
const bridge = netcattyBridge.get();
return {
head,
scope,
canSwitch: Boolean(bridge?.listLocalSessionGitBranches),
async list(worktreeRoot: string) {
try {
if (scope && isCurrent()) {
const next = await bridge?.listLocalSessionGitBranches?.(scope.backendId, scope.cwd, worktreeRoot);
if (isCurrent() && next) return next;
}
} catch { /* The menu displays the unavailable state. */ }
return { kind: 'unavailable' } as const;
},
async switchBranch(worktreeRoot: string, name: string, signal: AbortSignal): Promise<'sent' | 'busy' | 'unavailable'> {
const command = gitSwitchCommand(worktreeRoot, name);
if (!command || !scope || !isCurrent()) return 'unavailable';
try {
await scope.controller.sendLocalCommand(command, scope.cwd, signal);
return 'sent';
} catch (error) {
return error instanceof DirectoryPickerError && error.code === 'busy' ? 'busy' : 'unavailable';
}
},
};
}
@@ -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',
+31 -13
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { useAppLockChrome } from './appRuntimeBridge';
import { resolvePluginViewWindowScope } from './pluginViewScopes';
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -7,15 +8,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
subscribeHidden(listener: () => void): () => void; unavailable(): void;
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
}) {
const { locked } = useAppLockChrome();
const effectiveActive = active && !locked;
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const scopeId = typeof window !== 'undefined'
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
: '';
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
@@ -29,7 +32,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
useEffect(() => {
if (!active) {
if (!effectiveActive) {
setHidden(false);
return;
}
@@ -38,18 +41,33 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([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 activeHandle = { key, send: session.send, image: session.image };
sessionRef.current = activeHandle;
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); });
const stopHidden = subscribeHidden((nextHidden = true) => {
if (nextHidden) {
sessionRef.current = null;
setHidden(true);
} else {
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
setHidden(false);
}
});
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
} catch { unavailableRef.current(); }
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
const fallbackLoadImage = useCallback((path: string) => {
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [effectiveActive, key]);
const hasCurrentState = effectiveActive
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
? state.snapshot
: cachedSession
@@ -59,9 +77,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
? state.image
: (cachedSession?.image ?? fallbackLoadImage);
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
}, [effectiveActive, key]);
// A newly selected plugin must never receive values from the previous tree,
// even during the render before effect cleanup and the next activation.
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
}
+40 -10
View File
@@ -73,15 +73,31 @@ export function usePluginHostActions() {
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
}, [getVault]);
const clearReview = useCallback((entry: Review) => {
if (current.current !== entry) return;
current.current = null;
responding.current = false;
setReview(null);
setRemember(false);
setBusy(false);
setError(false);
}, []);
const fail = useCallback(async (entry: Review) => {
if (current.current !== entry) return;
setError(true);
try {
await netcattyBridge.get()?.respondPluginInteraction?.({
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
});
} catch { /* A stopped runtime or closed window already invalidates it. */ }
}, []);
if (accepted === false) {
clearReview(entry);
}
} catch {
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
clearReview(entry);
}
}, [clearReview]);
const execute = useCallback(async (entry: Review) => {
const bridge = netcattyBridge.get();
@@ -140,7 +156,8 @@ export function usePluginHostActions() {
entry.claimed = true;
assertCurrent(entry);
await openHostSession(entry.host);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
return;
}
let action: PluginHostAction;
@@ -161,9 +178,16 @@ export function usePluginHostActions() {
},
connect: openHostSession,
});
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
} catch { await fail(entry); }
}, [assertCurrent, fail, getVault]);
finally {
if (current.current === entry) {
responding.current = false;
setBusy(false);
}
}
}, [assertCurrent, clearReview, fail, getVault]);
useEffect(() => {
const bridge = netcattyBridge.get();
@@ -282,7 +306,7 @@ export function usePluginHostActions() {
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
try {
assertCurrent(entry);
if (action !== 'cancel') assertCurrent(entry);
const request = entry.prompt.request;
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
const revision = entry.candidateRevisions.get(id);
@@ -296,18 +320,24 @@ export function usePluginHostActions() {
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
await netcattyBridge.require().respondPluginInteraction?.({
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
} catch { await fail(entry); }
if (accepted === false) {
clearReview(entry);
}
} catch {
if (action === 'cancel') clearReview(entry);
else await fail(entry);
}
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, fail, remember, selectedIds]);
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
if (current.current?.requestId !== event.requestId) return;
current.current = null; setPrompt(null);
} else {
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
current.current = event as UiPrompt;
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
setPrompt(null);
+9 -3
View File
@@ -68,9 +68,15 @@ export function usePluginManager() {
if (!bridge.uninstallPlugin) throw new Error('Plugin management unavailable');
const source = clearSource ? await bridge.getPluginSourceBinding?.(id) : null;
await bridge.uninstallPlugin(id);
if (clearSource && source) {
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
await bridge.resetPluginSource(id, source.id);
try {
if (clearSource && source) {
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
await bridge.resetPluginSource(id, source.id);
}
} finally {
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
}
}
}, true),
};
+50 -2
View File
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { activeTabStore, useIsVaultActive } from './activeTabStore';
import { collectPluginVaultPages, PLUGIN_VAULT_PAGE_PREFIX, resolvePluginVaultPage } from './pluginVaultPages';
import { usePluginContributions } from './usePluginContributions';
@@ -6,6 +7,18 @@ import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginVi
const CONTEXT = Object.freeze({ 'netcatty.surface': 'vault-page' });
function areStringArraysEqual(
left: readonly string[] | undefined,
right: readonly string[] | undefined,
): boolean {
if (left === right) return true;
if (!left || !right || left.length !== right.length) return false;
for (let i = 0; i < left.length; i += 1) {
if (left[i] !== right[i]) return false;
}
return true;
}
export function usePluginVaultPages({ locale, section, select }: {
locale: string;
section: string;
@@ -18,6 +31,41 @@ export function usePluginVaultPages({ locale, section, select }: {
useEffect(() => () => { if (focusFrame.current !== null) cancelAnimationFrame(focusFrame.current); }, []);
const contributions = usePluginContributions({ locale, context: CONTEXT });
const pages = useMemo(() => collectPluginVaultPages(contributions.snapshot.plugins), [contributions.snapshot.plugins]);
const [installedPluginIds, setInstalledPluginIds] = useState<readonly string[] | undefined>(undefined);
useEffect(() => {
const bridge = typeof window === 'undefined' ? undefined : netcattyBridge.get();
if (!contributions.available || !bridge?.listPlugins) {
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
return;
}
let cancelled = false;
let generation = 0;
const loadInstalled = () => {
const requestId = ++generation;
void bridge.listPlugins!()
.then((plugins) => {
if (cancelled || requestId !== generation) return;
const next = Array.from(
new Set(
plugins
.map((plugin) => plugin.id)
.filter((id): id is string => typeof id === 'string' && id.length > 0),
),
).sort();
setInstalledPluginIds((current) => (areStringArraysEqual(current, next) ? current : next));
})
.catch(() => {
if (cancelled || requestId !== generation) return;
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
});
};
loadInstalled();
window.addEventListener('netcatty:plugin-packages-changed', loadInstalled);
return () => {
cancelled = true;
window.removeEventListener('netcatty:plugin-packages-changed', loadInstalled);
};
}, [contributions.available, contributions.snapshot]);
const selected = resolvePluginVaultPage(pages, section);
const fallback = useCallback(() => {
select('hosts');
@@ -43,5 +91,5 @@ export function usePluginVaultPages({ locale, section, select }: {
window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
return () => window.removeEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
}, [pages, select]);
return { pages, selected, active, select, fallback, contributions, context: CONTEXT };
return { pages, selected, active, select, fallback, contributions, installedPluginIds, context: CONTEXT };
}
+8 -2
View File
@@ -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 = {
@@ -148,7 +149,12 @@ export function usePluginViewLifecycle({
}, [contributions.loading, contributions.snapshot.plugins]);
useEffect(() => {
if (!requested || activeView?.view.location !== 'tab') return;
if (!requested || viewContributions.loading) return;
if (!resolvedActiveView) {
setRequested(null);
return;
}
if (activeView?.view.location !== 'tab') return;
pluginViewTabStore.open({
pluginId: activeView.plugin.id,
pluginName: activeView.plugin.displayName,
@@ -158,7 +164,7 @@ export function usePluginViewLifecycle({
context: requested.context,
});
setRequested(null);
}, [activeView, requested]);
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
useEffect(() => {
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
@@ -57,6 +57,40 @@ async function mountSessionState(t: test.TestContext) {
return () => latestState;
}
test('converting a standalone tab keeps the live session, tab position and focus', async (t) => {
const getState = await mountSessionState(t);
let first = '';
let target = '';
let last = '';
await act(async () => {
first = getState().createLocalTerminal();
target = getState().createLocalTerminal({ shellName: 'Build shell' });
last = getState().createLocalTerminal();
});
await act(async () => { getState().updateSessionStatus(target, 'connected'); });
const before = getState().sessions;
await act(async () => {
getState().convertSessionToWorkspace(target);
getState().convertSessionToWorkspace(target);
});
assert.equal(getState().workspaces.length, 1);
const [workspace] = getState().workspaces;
assert.equal(workspace.root.type, 'pane');
assert.equal(workspace.root.sessionId, target);
assert.equal(workspace.focusedSessionId, target);
assert.deepEqual(getState().sessions, before.map(session =>
session.id === target ? { ...session, workspaceId: workspace.id } : session));
assert.deepEqual(getState().orderedTabs, [first, workspace.id, last]);
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
// A reordered editor tab must keep its place alongside terminal tabs.
const editor = 'editor:test';
await act(async () => { getState().reorderTabs(editor, last, 'before', [editor]); });
await act(async () => { getState().convertSessionToWorkspace(last); });
const secondWorkspace = getState().workspaces[1];
assert.deepEqual(getState().getOrderedWorkTabs([editor]), [first, workspace.id, editor, secondWorkspace.id]);
});
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
const getState = await mountSessionState(t);
+28 -2
View File
@@ -766,13 +766,14 @@ export const useSessionState = ({
const preferredTabId = activeTabStore.getPreviousActiveTabId();
const tabOrderSnapshot = tabOrderRef.current;
const sessionsSnapshot = sessionsRef.current;
// Queue removal outside the workspace updater so React retains it when
// lower-priority session updates are rebased after this close.
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
setTabOrder(prevTabOrder => prevTabOrder.filter(id => id !== workspaceId));
setWorkspaces(prevWorkspaces => {
const remainingWorkspaces = prevWorkspaces.filter(w => w.id !== workspaceId);
const remainingSessions = sessionsSnapshot.filter(s => s.workspaceId !== workspaceId);
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
currentActiveTabId: activeTabStore.getActiveTabId(),
closedWorkspaceId: workspaceId,
@@ -1502,6 +1503,30 @@ export const useSessionState = ({
});
}, [setActiveTabId]);
const convertSessionToWorkspace = useCallback((sessionId: string) => {
const standaloneIds = orphanSessionsRef.current.map(session => session.id);
const workspace = createWorkspaceFromSessionIds([sessionId], {
title: DEFAULT_WORKSPACE_TITLE,
autoTitle: true,
viewMode: 'focus',
});
setSessions(prev => {
const source = prev.find(session => session.id === sessionId);
if (!source || source.workspaceId || source.hiddenFromTabs) return prev;
setWorkspaces(current => addWorkspaceIfMissing(current, workspace));
setTabOrder(current => {
if (current.includes(workspace.id)) return current;
// Unreordered terminal tabs may only have an implicit position.
const order = current.includes(sessionId) ? current : [...new Set([...current, ...standaloneIds])];
return order.map(id => id === sessionId ? workspace.id : id);
});
setActiveTabId(workspace.id);
return prev.map(session => session === source ? { ...session, workspaceId: workspace.id } : session);
});
}, [setActiveTabId]);
// Copy a session - creates a new session with the same host connection
const copySession = useCallback((sessionId: string, options?: {
localShellType?: TerminalSession['shellType'];
@@ -1793,6 +1818,7 @@ export const useSessionState = ({
createWorkspaceWithHosts,
createWorkspaceFromTargets,
createWorkspaceFromSessions,
convertSessionToWorkspace,
addSessionToWorkspace,
moveWorkspacePane,
removeSessionFromWorkspace,
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';
import { JSDOM } from 'jsdom';
import { activeTabStore } from './activeTabStore';
import { useSessionState } from './useSessionState';
import type { Host } from '../../domain/models';
const settle = (ms = 20) => new Promise<void>(resolve => setTimeout(resolve, ms));
test('workspace Close does not restore removed panes when a queued session update is rebased', async () => {
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of Object.entries({
window: dom.window, document: dom.window.document,
localStorage: dom.window.localStorage, CustomEvent: dom.window.CustomEvent,
Event: dom.window.Event,
})) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
const root = createRoot(document.getElementById('root')!);
let state!: ReturnType<typeof useSessionState>;
let closingId = '';
const mounts = new Map<string, number>();
function Pane({ id }: { id: string }) {
useEffect(() => { mounts.set(id, (mounts.get(id) ?? 0) + 1); }, [id]);
return null;
}
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return <>
<button onClick={() => state.closeWorkspace(closingId)}>Close</button>
{state.sessions.map(s => <Pane key={s.id} id={s.id} />)}
</>;
}
async function connect(name: string, count: number) {
const hosts = Array.from({ length: count }, (_, i) => ({
id: `${name}-${i}`, label: `${name}-${i}`, hostname: 'host.test',
username: 'alice', protocol: 'ssh',
} as Host));
flushSync(() => state.createWorkspaceWithHosts(name, hosts));
await settle();
const workspace = state.workspaces.at(-1)!;
flushSync(() => {
for (const s of state.sessions.filter(s => s.workspaceId === workspace.id)) {
state.updateSessionStatus(s.id, 'connected');
}
});
await settle();
return workspace;
}
async function close(id: string, queueCwd = false) {
closingId = id;
// A cwd observation without pendingInitialCwd queues a no-op update at
// default priority. The discrete Close runs first; React later rebases
// that queue. Wrapping this preparation in act would hide the schedule.
const session = state.sessions.find(s => s.workspaceId === id)!;
if (queueCwd) state.updateSessionRestoreCwd(session.id, '/home/alice');
document.querySelector('button')!.click();
await settle(100);
assert(!state.workspaces.some(w => w.id === id));
assert(!state.sessions.some(s => s.workspaceId === id), 'closed workspace sessions must stay removed after queued updates settle');
}
try {
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
flushSync(() => root.render(<Probe />));
const left = await connect('left', 2);
const target = await connect('target', 6);
const targetIds = state.sessions.filter(s => s.workspaceId === target.id).map(s => s.id);
// Keep the target mounted while other connected workspaces are used.
for (let i = 0; i < 3; i++) await close((await connect(`warm-${i}`, 2)).id);
const right = await connect('right', 2);
await close(right.id);
await close(left.id);
assert.deepEqual(state.sessions.map(s => s.id), targetIds);
assert(state.sessions.every(s => s.status === 'connected'));
assert.equal(activeTabStore.getActiveTabId(), target.id);
await close(target.id, true);
assert.equal(state.sessions.length, 0);
assert.equal(state.workspaces.length, 0);
assert.equal(activeTabStore.getActiveTabId(), 'vault');
assert([...mounts.values()].every(count => count === 1), 'Close must not remount any closed pane');
} finally {
flushSync(() => root.unmount());
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
await settle();
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+42 -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,
@@ -98,14 +99,17 @@ import {
} from '../../infrastructure/config/storageKeys';
import { resolveDefaultUiLocale, resolveSupportedLocale } from '../../infrastructure/config/i18n';
import {
addCustomKeyBindingExtra,
areCustomKeyBindingsEqual,
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
removeCustomKeyBindingExtra,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding as updateCustomKeyBindingRecord,
updateCustomKeyBindingExtra,
} from '../../domain/customKeyBindings';
import { resolveGlobalTerminalAppearance, idleThemeUserIntent } from '../../domain/terminalAppearanceRuntime';
import { DEFAULT_FONT_SIZE, TERMINAL_FONT_AUTO } from '../../infrastructure/config/fonts';
@@ -145,6 +149,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 +477,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 +1195,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 +1500,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 +1512,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 +1658,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);
@@ -2116,6 +2134,21 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setCustomKeyBindings(prev => resetCustomKeyBinding(prev, bindingId, scheme));
}, [setCustomKeyBindings]);
// Add a secondary chord that triggers the same action as the default binding
const addKeyBindingExtra = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => {
setCustomKeyBindings(prev => addCustomKeyBindingExtra(prev, bindingId, scheme, newKey));
}, [setCustomKeyBindings]);
// Re-record an existing secondary chord
const updateKeyBindingExtra = useCallback((bindingId: string, index: number, scheme: 'mac' | 'pc', newKey: string) => {
setCustomKeyBindings(prev => updateCustomKeyBindingExtra(prev, bindingId, index, scheme, newKey));
}, [setCustomKeyBindings]);
// Remove a secondary chord
const removeKeyBindingExtra = useCallback((bindingId: string, index: number) => {
setCustomKeyBindings(prev => removeCustomKeyBindingExtra(prev, bindingId, index));
}, [setCustomKeyBindings]);
// Reset all key bindings to defaults
const resetAllKeyBindings = useCallback(() => {
setCustomKeyBindings({});
@@ -2181,6 +2214,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
windowOpacity,
showSftpTab,
showHostTreeSidebar,
removeTopTabsDragArea,
showRecentHosts,
hostClickBehavior,
showOnlyUngroupedHostsInRoot,
@@ -2205,6 +2239,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
restoreTerminalCwd,
shellOnlyTabNumberShortcuts,
showHostTreeSidebar,
removeTopTabsDragArea,
showOnlyUngroupedHostsInRoot,
showRecentHosts,
showSftpTab,
@@ -2353,6 +2388,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
keyBindings,
customKeyBindings,
updateKeyBinding,
updateKeyBindingExtra,
addKeyBindingExtra,
removeKeyBindingExtra,
resetKeyBinding,
resetAllKeyBindings,
isHotkeyRecording,
@@ -2385,6 +2423,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,
};
}
+469 -1
View File
@@ -4,6 +4,10 @@ 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;
const DB_PLUGIN_ID = 'com.binaricat.netcatty-database';
const MONITOR_PLUGIN_ID = 'com.binaricat.netcatty-monitor';
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' });
@@ -29,10 +33,17 @@ 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 installedPluginIds: string[] | undefined = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
let pluginsLoading = false;
let pluginsAvailable = true;
function Fixture() {
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
model = useVaultNavConfig({
activePluginIds,
pluginsLoading,
pluginsAvailable,
installedPluginIds,
});
return <div />;
}
@@ -82,7 +93,9 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
});
const coldRoot = createRoot(document.getElementById('root')!);
activePluginIds = [];
installedPluginIds = undefined;
pluginsLoading = true;
pluginsAvailable = false;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -92,7 +105,9 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
// Plugins finish loading, but DB_PLUGIN was uninstalled.
activePluginIds = [MONITOR_PLUGIN];
installedPluginIds = [MONITOR_PLUGIN_ID];
pluginsLoading = false;
pluginsAvailable = true;
await act(async () => {
coldRoot.render(<Fixture />);
});
@@ -122,3 +137,456 @@ 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();
}
});
test('useVaultNavConfig preserves custom plugin order across in-place plugin update gap and prunes only after uninstall', 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 installedPluginIds: string[] = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
let pluginOwnerByNavId: Record<string, string> = {
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
};
let pluginsLoading = false;
let pluginsAvailable = true;
function Fixture() {
model = useVaultNavConfig({
activePluginIds,
pluginsLoading,
pluginsAvailable,
installedPluginIds,
pluginOwnerByNavId,
});
return <div />;
}
const root = createRoot(document.getElementById('root')!);
const render = async () => {
await act(async () => {
root.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
});
};
try {
await render();
await act(async () => {
model.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
model.setVisible('logs', false);
});
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
// Mid-update gap: beforeActivate disables the plugin while it remains installed.
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
pluginsLoading = false;
pluginsAvailable = true;
await render();
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
const persistedDuringGap = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedDuringGap.order[1], OFFICIAL_DB_PLUGIN);
assert.deepEqual(persistedDuringGap.hidden, ['logs']);
// Updated version re-enables and returns the same workbench nav key.
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
pluginOwnerByNavId = {
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
};
await render();
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
assert.equal(model.isHidden('logs'), true);
const persistedAfterUpdate = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedAfterUpdate.order[1], OFFICIAL_DB_PLUGIN);
// True uninstall removes the plugin from installedPluginIds and prunes its nav slot.
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
installedPluginIds = [MONITOR_PLUGIN_ID];
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
await render();
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), false);
const persistedAfterUninstall = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
assert.deepEqual(persistedAfterUninstall.hidden, ['logs']);
await act(async () => {
root.unmount();
});
} finally {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});
test('usePluginVaultPages + useVaultNavConfig preserve custom order across simulated 0.3.5 -> 0.3.6 update', 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],
});
}
for (const [key, value] of Object.entries({
requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
cancelAnimationFrame: (id: number) => clearTimeout(id),
IS_REACT_ACT_ENVIRONMENT: true,
})) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
const dbEntry = (version: string) => ({
id: DB_PLUGIN_ID,
version,
displayName: 'Database',
commands: [],
keybindings: [],
menus: [],
settings: [],
views: [
{ id: `${DB_PLUGIN_ID}.workbench`, title: 'Database', location: 'vault-page', visible: true },
],
});
const monitorEntry = {
id: MONITOR_PLUGIN_ID,
version: '1.0.0',
displayName: 'Monitor',
commands: [],
keybindings: [],
menus: [],
settings: [],
views: [
{ id: `${MONITOR_PLUGIN_ID}.workbench`, title: 'Monitor', location: 'vault-page', visible: true },
],
};
let snapshot = { locale: 'en', plugins: [dbEntry('0.3.5'), monitorEntry] };
let installed = [
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.5' },
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
const listeners = new Set<() => void>();
Object.assign(dom.window, {
netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return { ...snapshot, plugins: [...snapshot.plugins] }; },
async listPlugins() { return [...installed]; },
onPluginContributionsChanged(cb: () => void) {
listeners.add(cb);
return () => { listeners.delete(cb); };
},
},
});
const { default: React, act, useMemo, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { usePluginVaultPages } = await import('./usePluginVaultPages');
const { useVaultNavConfig } = await import('./useVaultNavConfig');
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
let nav!: ReturnType<typeof useVaultNavConfig>;
function Fixture() {
const [section, setSection] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
const pluginVault = usePluginVaultPages({ locale: 'en', section, select: setSection });
const activePluginIds = useMemo(
() => pluginVault.pages.map((page) => page.key),
[pluginVault.pages],
);
const pluginOwnerByNavId = useMemo(
() => Object.fromEntries(pluginVault.pages.map((page) => [page.key, page.pluginId])),
[pluginVault.pages],
);
nav = useVaultNavConfig({
activePluginIds,
pluginsLoading: pluginVault.contributions.loading,
pluginsAvailable: pluginVault.contributions.available,
installedPluginIds: pluginVault.installedPluginIds,
pluginOwnerByNavId,
});
return <div />;
}
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise((resolve) => setTimeout(resolve, 25));
try {
await act(async () => {
root.render(
<React.StrictMode>
<Fixture />
</React.StrictMode>,
);
await settle();
});
assert.ok(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN));
assert.ok(nav.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN));
await act(async () => {
nav.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
await settle();
});
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
// beforeActivate disables Database 0.3.5 (still installed) and emits contributions-changed.
snapshot = { locale: 'en', plugins: [monitorEntry] };
installed = [
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.5' },
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
await act(async () => {
for (const listener of listeners) listener();
await settle();
});
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
const persistedMidUpdate = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedMidUpdate.order[1], OFFICIAL_DB_PLUGIN);
// Database 0.3.6 activates and emits contributions-changed.
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
installed = [
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
await act(async () => {
for (const listener of listeners) listener();
await settle();
});
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
// Hide Database, then simulate uninstall where plugin-disabled arrives before package removal
// followed by post-uninstall contributions-changed once listPlugins no longer contains it.
await act(async () => {
nav.setVisible(OFFICIAL_DB_PLUGIN, false);
await settle();
});
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), true);
snapshot = { locale: 'en', plugins: [monitorEntry] };
installed = [
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.6' },
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
await act(async () => {
for (const listener of listeners) listener();
await settle();
});
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), true);
// Post-uninstall refresh (from onPluginUninstalled) sees DB removed and prunes slot + hidden flag.
installed = [
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
await act(async () => {
for (const listener of listeners) listener();
await settle();
});
assert.equal(nav.config.order.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), false);
const persistedAfterUninstall = JSON.parse(
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
);
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
assert.equal(persistedAfterUninstall.hidden.includes(OFFICIAL_DB_PLUGIN), false);
// Reinstalling in the same session restores the page visible by default at the end.
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
installed = [
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
];
await act(async () => {
for (const listener of listeners) listener();
await settle();
});
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), false);
await act(async () => {
root.unmount();
});
} finally {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
dom.window.close();
}
});
+49 -7
View File
@@ -6,6 +6,7 @@ import {
getManageableVaultNavIds,
getVisibleVaultNavIds,
isCustomVaultNavConfig,
isPluginVaultNavId,
moveVaultNavItem,
normalizeVaultNavConfig,
reconcileVaultNavConfig,
@@ -14,6 +15,7 @@ import {
setVaultNavItemVisibility,
toggleVaultNavItemVisibility,
type PluginVaultNavId,
type ReconcileVaultNavOptions,
type VaultNavConfig,
type VaultNavDropPosition,
type VaultNavItemId,
@@ -28,6 +30,19 @@ 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;
/**
* Installed plugin package IDs (including disabled/updating plugins).
* When omitted, saved plugin-vault:* entries are preserved rather than pruned
* solely because they are absent from `activePluginIds`.
*/
installedPluginIds?: readonly string[];
/**
* Optional nav-key to owning plugin package ID map for currently active pages.
* Cached across renders so a vanished page can still be attributed to its plugin.
*/
pluginOwnerByNavId?: Readonly<Record<string, string>>;
}
export interface UseVaultNavConfigResult {
@@ -55,11 +70,11 @@ export interface UseVaultNavConfigResult {
function readStoredVaultNavConfig(
activePluginIds: readonly PluginVaultNavId[],
pruneMissingPlugins: boolean,
options: ReconcileVaultNavOptions,
): VaultNavConfig {
try {
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
return normalizeVaultNavConfig(raw, activePluginIds, options);
} catch {
return resetVaultNavConfig(activePluginIds);
}
@@ -76,16 +91,37 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
export function useVaultNavConfig({
activePluginIds,
pluginsLoading = false,
pluginsAvailable = false,
installedPluginIds,
pluginOwnerByNavId,
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
const pluginKey = activePluginIds.join('\0');
const stablePluginIds = useMemo<PluginVaultNavId[]>(
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
[pluginKey],
);
const pruneMissingPlugins = !pluginsLoading;
const installedKey = installedPluginIds ? installedPluginIds.join('\0') : null;
const stableInstalledPluginIds = useMemo<readonly string[] | undefined>(
() => (installedKey === null ? undefined : installedKey ? installedKey.split('\0') : []),
[installedKey],
);
const pluginOwnerCacheRef = useRef<Map<PluginVaultNavId, string>>(new Map());
if (pluginOwnerByNavId) {
for (const [navId, ownerId] of Object.entries(pluginOwnerByNavId)) {
if (isPluginVaultNavId(navId) && ownerId) {
pluginOwnerCacheRef.current.set(navId, ownerId);
}
}
}
const pruneMissingPlugins =
!pluginsLoading && pluginsAvailable && stableInstalledPluginIds !== undefined;
const [config, setConfig] = useState<VaultNavConfig>(() =>
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
readStoredVaultNavConfig(stablePluginIds, {
pruneMissingPlugins,
installedPluginIds: stableInstalledPluginIds,
pluginOwnerByNavId: pluginOwnerCacheRef.current,
}),
);
const configRef = useRef<VaultNavConfig>(config);
configRef.current = config;
@@ -97,6 +133,8 @@ export function useVaultNavConfig({
const current = configRef.current;
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
pruneMissingPlugins,
installedPluginIds: stableInstalledPluginIds,
pluginOwnerByNavId: pluginOwnerCacheRef.current,
});
if (!areVaultNavConfigsEqual(current, reconciled)) {
configRef.current = reconciled;
@@ -117,7 +155,7 @@ export function useVaultNavConfig({
// Ignore storage read errors.
}
}
}, [pruneMissingPlugins, stablePluginIds]);
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
// Cross-window and adapter sync.
useEffect(() => {
@@ -131,7 +169,11 @@ export function useVaultNavConfig({
) {
return;
}
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
const next = readStoredVaultNavConfig(stablePluginIds, {
pruneMissingPlugins,
installedPluginIds: stableInstalledPluginIds,
pluginOwnerByNavId: pluginOwnerCacheRef.current,
});
if (!areVaultNavConfigsEqual(configRef.current, next)) {
configRef.current = next;
setConfig(next);
@@ -143,7 +185,7 @@ export function useVaultNavConfig({
window.removeEventListener('storage', sync);
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
};
}, [pruneMissingPlugins, stablePluginIds]);
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
if (areVaultNavConfigsEqual(configRef.current, next)) {
+10 -1
View File
@@ -2,7 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import { matchesKeyBinding } from "../../domain/models.ts";
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
import { isNativeCloseTabBound, isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
test("primary-modifier W only belongs to the matching close-tab binding", () => {
assert.equal(isPrimaryModifierWBinding("⌘ + W", matchesKeyBinding, true), true);
@@ -176,3 +176,12 @@ test("Cmd+W closes the window when nothing else is active", () => {
{ kind: "closeWindow" },
);
});
test("native close matches a secondary Command-W for the active Close Tab action", () => {
const primary = { id: "close-tab", action: "closeTab", label: "Close", category: "tabs" as const, mac: "F9", pc: "F9" };
const secondary = { ...primary, id: "close-tab::extra-0", mac: "⌘ + W", pc: "Disabled" };
assert.equal(isNativeCloseTabBound("mac", [primary, secondary], true), true);
assert.equal(isNativeCloseTabBound("pc", [primary, secondary], true), false);
assert.equal(isNativeCloseTabBound("disabled", [primary, secondary], true), false);
assert.equal(isNativeCloseTabBound("mac", [primary, { ...secondary, action: "quickSwitch" }], true), false);
});
+12
View File
@@ -1,3 +1,5 @@
import { matchesKeyBinding, type HotkeyScheme, type KeyBinding } from '../../domain/models/keyBindings';
export type WindowCommandCloseIntent =
| { kind: 'forwardShortcut' }
| { kind: 'closeDialog' }
@@ -25,6 +27,16 @@ export function isPrimaryModifierWBinding(
);
}
export function isNativeCloseTabBound(
scheme: HotkeyScheme,
bindings: readonly KeyBinding[],
isMac: boolean,
): boolean {
return scheme !== 'disabled' && bindings.some((binding) =>
binding.action === 'closeTab' && isPrimaryModifierWBinding(binding[scheme], matchesKeyBinding, isMac)
);
}
interface ResolveWindowCommandCloseIntentInput {
activeTabId: string | null;
editorTabIds: string[];
@@ -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");
});
}
+1 -1
View File
@@ -309,7 +309,7 @@ const SYNCABLE_TERMINAL_KEYS = [
'inlineImagesEnabled', 'inlineImageKittyEnabled', 'inlineImageSixelEnabled', 'inlineImageIipEnabled',
'autocompleteEnabled', 'autocompleteGhostText', 'autocompletePopupMenu',
'autocompleteDebounceMs', 'autocompleteMinChars', 'autocompleteMaxSuggestions',
'autocompleteHistoryScope',
'autocompleteHistoryScope', 'autocompleteShowSnippets',
] as const;
export const SYNCABLE_SETTING_STORAGE_KEYS = [
+278
View File
@@ -1,3 +1,266 @@
!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"
${endif}
; #4672: Always rewrite the .lnk from the newly installed $appExe so in-app
; updates do not leave an existing desktop shortcut with a stale/blank icon.
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
ClearErrors
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x00002000, i 0x0005, w "$newDesktopLink", i 0)'
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
!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 +270,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 +321,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"
+6
View File
@@ -59,8 +59,10 @@ 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;
onSendWithGrokMode?: (text: string) => void;
handleSendQuickPrompt?: (promptText: string) => void;
handleCompact: () => void;
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
@@ -171,9 +173,11 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
activeCompaction = null,
contextUsage = null,
inputValue,
inputValueRevision,
setInputValue,
handleSend,
handleSendQuickPrompt,
onSendWithGrokMode,
handleCompact,
onRenameSession,
onRenameActiveChat,
@@ -568,9 +572,11 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<ChatInput
parked={parked}
value={inputValue}
valueRevision={inputValueRevision}
onChange={setInputValue}
onSend={handleSend}
onSendQuickPrompt={handleSendQuickPrompt}
onSendWithGrokMode={onSendWithGrokMode}
onCompact={handleCompact}
onRenameSession={onRenameActiveChat}
onListChats={onListChats}
+51 -5
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,8 @@ 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 { getSessionLastMessageAt } from './ai/globalSessionManagerRows';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
// -------------------------------------------------------------------
@@ -52,6 +54,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 +73,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 +151,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 +163,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 +228,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">
@@ -250,7 +296,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
{displayedSessions.map((session) => {
const isActive = session.id === activeSessionId;
const time = new Date(session.updatedAt);
const time = new Date(getSessionLastMessageAt(session));
const timeStr = formatRelativeTime(time, t);
return (
+139 -36
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,11 +830,19 @@ 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 draftGenerationRef = useRef(0);
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
draftGenerationRef.current += 1;
if (!options?.keepPendingText) discardPendingComposerText();
clearDraftForScope(scopeKey);
}, [clearDraftForScope, discardPendingComposerText, scopeKey]);
@@ -1038,26 +1053,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 +1685,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;
@@ -1742,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const handleSend = useCallback(async (
textOverride?: string,
options?: { includeDraftAttachments?: boolean },
options?: { includeDraftAttachments?: boolean; chooseGrokMode?: boolean },
) => {
const draft = currentDraftRef.current;
const currentPanelView = panelViewRef.current;
@@ -1875,7 +1872,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() });
@@ -1967,6 +1964,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
scopeType,
scopeTargetId,
existingSessionId: existingExternalSessionId,
chooseGrokMode: options?.chooseGrokMode,
updateExternalSessionId: updateSessionExternalSessionId,
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
terminalSessions,
@@ -1983,7 +1981,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 +2002,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 +2030,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,
@@ -2122,7 +2130,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
if (!sessionId || !draft || steeringSessionId || !canSteerCurrentTurn) return;
if (!validateNoteMentions(draft.attachments)) return;
const trimmed = draft.text.trim();
const submittedText = draft.text;
const draftGeneration = draftGenerationRef.current;
const trimmed = submittedText.trim();
const attachments = draft.attachments.map((file) => ({
base64Data: file.base64Data,
mediaType: file.mediaType,
@@ -2156,7 +2166,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
attachedImages: modelAttachments,
});
if (result.status === 'accepted') {
if (currentDraftRef.current === draft) clearScopeDraft();
if (draftGenerationRef.current !== draftGeneration || activeSessionRef.current?.id !== sessionId) return;
const pending = pendingComposerTextRef.current;
const keepPendingText = pending != null && pending !== submittedText;
clearScopeDraft({ keepPendingText });
return;
}
if (result.status !== 'cancelled') {
@@ -2177,6 +2190,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
return registerGrantPersister((rule) => { addGrant(rule); });
}, [addGrant]);
const handleSendWithGrokMode = useCallback((text: string) => {
void handleSend(text, { includeDraftAttachments: true, chooseGrokMode: true });
}, [handleSend]);
const handleSendQuickPrompt = useCallback((promptText: string) => {
void handleSend(promptText, { includeDraftAttachments: true });
}, [handleSend]);
@@ -2430,6 +2447,82 @@ 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(async (sessionId: string) => {
if (!regenerateSessionTitle) return;
const result = await regenerateSessionTitle(sessionId);
if (!result) return;
if (result.status === 'updated') {
toast.success(t('ai.chat.managerRegenerateTitleUpdated'));
} else if (result.status === 'unchanged') {
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
} else if (result.status === 'no-model') {
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
} else if (result.status === 'error') {
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', result.error));
}
}, [regenerateSessionTitle, t]);
const handleManagerRegenerateTitles = useCallback(async (sessionIds: string[]) => {
if (!regenerateSessionTitle || sessionIds.length === 0) return;
let updated = 0;
let unchanged = 0;
let noModel = 0;
let failed = 0;
let lastError = '';
const expectedTitles = new Map(sessionsRef.current.map(session => [session.id, session.title]));
const concurrency = 2;
let cursor = 0;
const workers = Array.from({ length: Math.min(concurrency, sessionIds.length) }, async () => {
while (cursor < sessionIds.length) {
const currentId = sessionIds[cursor];
cursor += 1;
const expectedTitle = expectedTitles.get(currentId);
if (expectedTitle === undefined) continue;
const result = await regenerateSessionTitle(currentId, expectedTitle);
if (!result) continue;
if (result.status === 'updated') updated += 1;
else if (result.status === 'unchanged') unchanged += 1;
else if (result.status === 'no-model') noModel += 1;
else if (result.status === 'error') {
failed += 1;
lastError = result.error;
}
}
});
await Promise.all(workers);
if (noModel === sessionIds.length) {
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
return;
}
if (updated > 0 && failed === 0) {
toast.success(t('ai.chat.managerRegenerateTitleBatchDone').replace('{n}', String(updated)));
} else if (updated > 0 && failed > 0) {
toast.warning(
t('ai.chat.managerRegenerateTitleBatchPartial')
.replace('{updated}', String(updated))
.replace('{failed}', String(failed)),
);
} else if (failed > 0) {
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', lastError || 'Unknown error'));
} else if (unchanged > 0) {
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
}
}, [regenerateSessionTitle, t]);
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 +2557,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onRebind={handleManagerRebind}
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
onRegenerateTitle={(sessionId) => handleManagerRegenerateTitle(sessionId)}
onRegenerateTitles={(ids) => handleManagerRegenerateTitles(ids)}
onExport={handleManagerExport}
/>
)
@@ -2483,6 +2579,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
handleManagerRebind,
handleRenameSession,
handleManagerDelete,
handleManagerDeleteMany,
handleManagerRegenerateTitle,
handleManagerRegenerateTitles,
handleManagerExport,
onFocusAIScopeTarget,
]);
@@ -2556,9 +2655,11 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
contextUsage={contextUsage}
canCompact={canCompact}
inputValue={inputValue}
inputValueRevision={composerValueRevision}
setInputValue={setInputValue}
handleSend={handleSend}
handleSendQuickPrompt={handleSendQuickPrompt}
onSendWithGrokMode={getExternalAgentSdkBackend(currentAgentConfig ?? undefined) === 'grok' && currentAgentConfig?.grokRuntime !== 'streaming-json' ? handleSendWithGrokMode : undefined}
handleCompact={handleCompact}
onRenameSession={handleRenameSession}
onRenameActiveChat={handleRenameSlashCommand}
@@ -2666,6 +2767,8 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
'createSession',
'deleteSession',
'updateSessionTitle',
'autoTitleSession',
'regenerateSessionTitle',
'rebindSessionScope',
'exportSessionsBackup',
'importSessionsBackup',
+5 -1
View File
@@ -13,6 +13,7 @@ import type {
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import type { Host, Snippet, VaultNote } from '../types';
import type { RegenerateSessionTitleResult } from '../application/state/useAIState';
// -------------------------------------------------------------------
// Props
@@ -36,7 +37,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 +45,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, expectedTitle?: string) => void | Promise<RegenerateSessionTitleResult | 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. */
+1
View File
@@ -400,6 +400,7 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
return sdkBackend === 'codex'
|| sdkBackend === 'claude'
|| sdkBackend === 'copilot'
|| sdkBackend === 'agy'
|| sdkBackend === 'cursor'
|| sdkBackend === 'codebuddy'
|| sdkBackend === 'opencode'
+283 -1
View File
@@ -4,7 +4,7 @@ import React from "react";
import { useAppLockBridge } from "../application/state/useAppLockBridge.ts";
import { useAppLockState } from "../application/state/useAppLockState.ts";
import { createAppLockGate } from "./AppLockGate.tsx";
import { ReportRendererReady, createAppLockGate } from "./AppLockGate.tsx";
import { APP_LOCK_AUTO_PROMPT_DELAY_MS } from "./AppLockOverlay.tsx";
import { createAppLockBridgeHarness } from "./test-support/createAppLockBridgeHarness.ts";
import {
@@ -1024,3 +1024,285 @@ test("reopen resync does not unlock a gate when runtime is still locked", async
dom.cleanup();
}
});
test("rendererReady waits for lazy route mount and runs after child effects", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const events: string[] = [];
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const baseBridge = bridgeHarness.bridge;
const wrappedBridge: NetcattyBridge = {
...baseBridge,
rendererReady: () => {
events.push("rendererReady");
baseBridge.rendererReady?.();
},
};
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const ChildSubscriber: React.FC = () => {
React.useEffect(() => {
events.push("childSubscribed");
}, []);
return React.createElement("div", { id: "lazy-route-content" }, "Mounted");
};
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = wrappedBridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Gate allowed children, but LazyRoute is still suspended -> must NOT signal ready.
assert.equal(dom.document.getElementById("lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
assert.deepEqual(events, []);
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement(ChildSubscriber),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("lazy-route-content")?.textContent, "Mounted");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
assert.deepEqual(events, ["childSubscribed", "rendererReady"]);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("startup-locked gate withholds rendererReady until unlock and lazy route mount", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: true,
reason: "startup",
version: 1,
lastLockedAt: 1_000,
lastUnlockedAt: null,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: true,
timeoutMinutes: 15,
passwordVerifier: {
version: 1,
algorithm: "PBKDF2-SHA256",
iterations: 210000,
salt: "AAAAAAAAAAAAAAAAAAAAAA==",
hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
},
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "locked-lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Locked first paint: children withheld, must not notify.
assert.equal(dom.document.getElementById("locked-lazy-fallback"), null);
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Unlock: children allowed, but LazyRoute still suspended -> still must not notify.
await runWithAct(async () => {
bridgeHarness.setRuntimeState({
locked: false,
reason: null,
lastUnlockedAt: 2_000,
lastActivityAt: 2_000,
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Resolve lazy chunk -> mounts real page and reports ready once.
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "locked-lazy-mounted" }, "Ready"),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-mounted")?.textContent, "Ready");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("notifyRendererReady=false suppresses ReportRendererReady signals", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: false,
children: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "opt-out-content" }, "OptOut"),
React.createElement(ReportRendererReady),
),
}),
);
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("opt-out-content")?.textContent, "OptOut");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
+39
View File
@@ -5,6 +5,7 @@ import {
shouldDeferExternalActionWhileAppLocked,
shouldNotifyAppLockGateRendererReady,
shouldRenderAppLockGateChildren,
shouldReportAppLockGateRendererReady,
} from "./AppLockGate.tsx";
test("shouldRenderAppLockGateChildren withholds startup-locked route children until unlock", () => {
@@ -140,6 +141,44 @@ test("shouldNotifyAppLockGateRendererReady waits until locked children can mount
);
});
test("shouldReportAppLockGateRendererReady requires gate permission and mounted content", () => {
// Gate allowing children (e.g. Suspense fallback) is not sufficient.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: false,
}),
false,
);
// Locked first paint must not notify even if contentMounted were true.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: false,
contentMounted: true,
}),
false,
);
// Routes that opt out (terminal-popup / editor-window) must not notify.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: false,
renderChildren: true,
contentMounted: true,
}),
false,
);
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: true,
}),
true,
);
});
test("shouldDeferExternalActionWhileAppLocked queues actions only while locked", () => {
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: true }), true);
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: false }), false);
+74 -22
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { I18nProvider } from '../application/i18n/I18nProvider';
import { useAppLockBridge } from '../application/state/useAppLockBridge';
@@ -67,6 +67,33 @@ export function shouldNotifyAppLockGateRendererReady(input: {
return input.notifyRendererReady && input.renderChildren;
}
/**
* Lazy route chunks suspend after AppLockGate allows children to render.
* Only emit rendererReady once the gate permits it and the lazy route's real
* content has mounted (so AppSideEffects / IPC listeners are registered).
*/
export function shouldReportAppLockGateRendererReady(input: {
notifyRendererReady: boolean;
renderChildren: boolean;
contentMounted: boolean;
}): boolean {
return shouldNotifyAppLockGateRendererReady(input) && input.contentMounted;
}
const RendererReadyContext = createContext<(() => void) | null>(null);
export function useReportRendererReady(): void {
const reportRendererReady = useContext(RendererReadyContext);
useEffect(() => {
reportRendererReady?.();
}, [reportRendererReady]);
}
export const ReportRendererReady: React.FC = () => {
useReportRendererReady();
return null;
};
/** Queue external actions (e.g. ssh:// deep links) while the app lock is held. */
export function shouldDeferExternalActionWhileAppLocked(input: {
locked: boolean;
@@ -88,6 +115,8 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
onAppLockReopen,
} = deps.useAppLockBridge();
const hasRenderedChildrenRef = useRef(false);
const contentMountedRef = useRef(false);
const hasNotifiedRendererReadyRef = useRef(false);
const [reopenSignal, setReopenSignal] = useState(0);
const renderChildren = shouldRenderAppLockGateChildren({
initialized: appLock.initialized,
@@ -99,10 +128,31 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
if (renderChildren) {
hasRenderedChildrenRef.current = true;
}
const shouldNotifyRendererReady = shouldNotifyAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
});
const emitRendererReadyIfAllowed = useCallback(() => {
if (hasNotifiedRendererReadyRef.current) return;
if (
!shouldReportAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
contentMounted: contentMountedRef.current,
})
) {
return;
}
hasNotifiedRendererReadyRef.current = true;
try {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
} catch {
// ignore
}
}, [notifyAppLockRendererReady, notifyRendererReady, renderChildren]);
const reportRendererReady = useCallback(() => {
contentMountedRef.current = true;
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
try {
@@ -111,14 +161,14 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
splash.classList.add('fade-out');
setTimeout(() => splash.remove(), 200);
}
if (shouldNotifyRendererReady) {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
}
} catch {
// ignore
}
}, [notifyAppLockRendererReady, shouldNotifyRendererReady]);
}, []);
useEffect(() => {
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
const unsubscribe = onAppLockReopen(() => {
@@ -149,18 +199,20 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
<I18nProvider locale={settings.uiLanguage}>
<ToastProvider>
<TooltipProvider delayDuration={300}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
<RendererReadyContext.Provider value={reportRendererReady}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
</RendererReadyContext.Provider>
<AppLockOverlay
locked={appLock.locked}
reason={appLock.lockReason}
+10
View File
@@ -31,3 +31,13 @@ test("terminal popups wait for app-lock initialization before starting a termina
/allowTerminalStart=\{appLock\.initialized\s*&&\s*!appLock\.locked\}/,
);
});
test("lazy routes gated by AppLockGate report rendererReady after mounting", () => {
const appSource = readComponentSource("../App.tsx");
const settingsPage = readComponentSource("./SettingsPage.tsx");
const trayPanel = readComponentSource("./TrayPanel.tsx");
assert.match(appSource, /\buseReportRendererReady\s*\(\)/);
assert.match(settingsPage, /<ReportRendererReady\s*\/>/);
assert.match(trayPanel, /<ReportRendererReady\s*\/>/);
});
+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));
+2 -2
View File
@@ -383,8 +383,8 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
active
? "bg-primary/12 text-primary border border-primary/25"
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
? "bg-primary/12 text-primary"
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60",
)}
>
{item.icon}
@@ -4,6 +4,7 @@ import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
import React from "react";
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
import { customThemeStore } from "../application/state/customThemeStore";
import { useExternalEditorSettings } from "../application/state/useExternalEditorSettings";
import { clearHostFontSizeOverride, clearHostThemeOverride } from "../domain/terminalAppearance";
import { resolveSshAgentToggleUpdate } from "../domain/sshAuth";
import { MAX_FONT_SIZE, MIN_FONT_SIZE } from "../infrastructure/config/fonts";
@@ -67,6 +68,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxyInherited = false,
clearProxyConfig,
}) => {
const { settings: externalEditorSettings } = useExternalEditorSettings();
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
@@ -550,6 +552,39 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
enabled={!!form.showLineTimestamps}
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
/>
{isSshView && (
<HostDetailsSettingRow
label={t("hostDetails.externalEditorShellIntegration")}
hint={t("hostDetails.externalEditorShellIntegration.desc")}
>
<Select
value={
form.externalEditorShellIntegration === true
? "enabled"
: form.externalEditorShellIntegration === false
? "disabled"
: "default"
}
onValueChange={(v) =>
update(
"externalEditorShellIntegration",
v === "enabled" ? true : v === "disabled" ? false : undefined,
)
}
>
<SelectTrigger className="h-8 w-36 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
{`${t("hostDetails.backspaceBehavior.default")} (${externalEditorSettings.autoSetupShellIntegration ? t("common.enabled") : t("common.disabled")})`}
</SelectItem>
<SelectItem value="enabled">{t("common.enabled")}</SelectItem>
<SelectItem value="disabled">{t("common.disabled")}</SelectItem>
</SelectContent>
</Select>
</HostDetailsSettingRow>
)}
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
<>
<ToggleRow
Loaded 100 of 441 files, more files were not shown because too many files have changed in this diff. Show more