Compare commits

...
Author SHA1 Message Date
bincxz fd1c2786b3 fix(monitor): label network directions for screen readers 2026-10-17 19:35:28 +08:00
bincxz be43afe31e refine(monitor): keep default cursor until dragging 2026-10-17 19:34:05 +08:00
bincxz e86f38203c refine(vault): remove active host selection outlines 2026-10-17 19:31:32 +08:00
bincxz b7dc61efb0 refine(monitor): simplify navigation and match Vault visuals 2026-10-17 19:27:19 +08:00
bincxz 6e5d08c005 refine(monitor): compact panel controls into the Vault header 2026-10-17 19:15:19 +08:00
陈大猫 3f35872638 Refine monitoring layout, disk details and refresh controls (#3704)
* Polish monitoring panels and preserve host icons

* Simplify monitoring layout and show every disk partition

* Simplify list rows and add resizable monitoring overlays

* feat(monitor): add modal drawers, sampled hover values and faster refresh

* feat(monitor): reset run history and support saved drag ordering

* perf(monitor): stream history deltas and keep fast samples lightweight

* fix(monitor): separate chart histories across connection identities

* refine(monitor): show disk capacity on hover and use inline sidebars

* fix(monitor): omit unchanged stats from polling deltas

* test(monitor): freeze time in full-history delta checks

* perf(monitor): bound chart paths and reuse unchanged histories
2026-10-17 18:59:38 +08:00
陈大猫 bace30578c feat: add synced custom host monitoring panels (#3703)
* feat: add synced custom host monitoring panels

* fix: preserve shared monitoring demand and complete terminal stats

* fix: transfer queued monitoring prompts when a window closes

* fix: keep reused hosts sampling while authentication is queued

* docs: record monitoring acceptance evidence

* fix: transfer pending monitoring auth after panel stop

* fix: release monitor owners in direct SSH runtime

* fix: keep worker monitoring sender compatibility

* fix: include monitoring configuration in automatic sync

* fix: disambiguate independent synced monitoring panel names

* test: assert existing panel order after cloud merge

* test: model browser locks and await monitoring state on Node 22
2026-10-17 15:05:30 +08:00
陈大猫 8aeb6ade6f fix(sftp): report transfer connection setup failures (#3702) 2026-10-17 12:32:11 +08:00
陈大猫andCodex b6bff4df6b feat(browser): browse host services from terminal side panels (#3701)
* Codex worktree snapshot: startup-cleanup

Co-authored-by: Codex

* fix(browser): close malformed proxy connections without a reply

* feat(browser): embed host browsing in terminal side panels

* style(browser): blend compact browser chrome into terminal panels

* feat(browser): open terminal links internally with a system browser preference

* fix(browser): retain the first terminal link during panel mount replay

* fix(browser): release contexts when their split pane closes

* style(browser): remove the downloads panel shadow

* fix(browser): ignore late downloads after panel closure

* fix(browser): mount browser content on terminal auto-open

* fix(browser): preserve empty-vault recovery with bookmarks

* fix(browser): expose actions for supported terminal types

* fix(browser): retain open requests before the panel mounts

* fix(browser): align vault actions with supported hosts

* fix(browser): share download controls across host contexts

* fix(browser): keep vault browser requests on visible sessions

* fix(browser): release contexts after workspace detach

* fix(browser): enforce WebRTC routing on page contents

* fix(browser): skip unsupported sessions in open requests

* style(browser): encode glyphs in ASCII-safe source
2026-10-17 02:26:36 +08:00
Netcatty-Bot 2cfe2a05ea fix(sync-ui): clarify disconnect and preserve failure retry
Make provider disconnect visible and explain the local credentials removed and the vault, backup history, shared sync password and cloud copies retained. Report failed disconnects and preserve a retry path instead of implying success.

Validation: focused sync and dialog checks, isolated Electron cancel/failure/retry/reload against WebDAV, two independent final full-diff reviews, exact-head Codex review and current GitHub checks; the main integration tree also passed focused checks.

Related to #3688. Device handover cleanup remains outside this patch and the issue remains open.
2026-10-16 10:45:01 +08:00
Netcatty-Bot 7ed7250f34 fix(vault): clean deleted jump host references across deletion flows
Deleting saved hosts now removes their jump references from surviving hosts and group defaults in all ordinary deletion flows. Host-only bulk deletion uses the existing vault mutation boundary, and explicit empty chains retain their original group-override meaning.

Validation: 282 focused checks, lint/build, two independent full-diff reviews, latest-head Codex review, current GitHub checks, and actual isolated Electron deletion/restart/native SSH reconnection.

Fixes #3691
2026-10-16 10:38:15 +08:00
陈大猫 2ce0164fa9 Merge pull request #3642 from GOUKI9999/feat/unified-model-catalog-ux
feat(ai): unify SDK model catalog loading and sources
2026-10-15 22:48:27 +08:00
bincxz 2e55b9348f test(ai): keep Copilot fixtures in the managed temp directory 2026-10-15 22:27:11 +08:00
bincxz 1e79dadbe5 fix(ai): let the Copilot SDK own its native runtime directly 2026-10-15 22:13:44 +08:00
bincxz 52e15f8df7 fix(ai): match the official Copilot npm loader package 2026-10-15 21:51:06 +08:00
bincxz 7497e64ab4 fix(ai): preserve custom Copilot JavaScript launchers 2026-10-15 21:48:23 +08:00
bincxz 9888f07cb2 fix(ai): keep Copilot wrapper independent of parent module scope 2026-10-15 21:33:40 +08:00
bincxz 293ca1098e fix(ai): preserve authoritative Grok reasoning capabilities 2026-10-15 21:17:37 +08:00
陈大猫 35a47fe95a Merge pull request #3633 from yuyang2230/feat/cloud-sync-union-merge-and-ai-sessions
feat(sync): non-destructive union merge + AI sessions in cloud sync
2026-10-15 21:09:49 +08:00
bincxz 82add1bda6 test(ai): align Windows Copilot checks with native passthrough 2026-10-15 21:03:04 +08:00
bincxz 239804bf62 fix(ai): retain native Copilot lifecycle and clean undated catalog labels 2026-10-15 21:01:19 +08:00
bincxz 460d9bb7c6 fix(ai): allocate Copilot wrapper through managed temp files 2026-10-15 20:08:44 +08:00
bincxz b7996c58e3 fix(sync): preserve durable chats and stop turns before replacement 2026-10-15 20:05:43 +08:00
bincxz ab50ad93b7 fix(ai): hide irrelevant catalog warnings for configured Codex models 2026-10-15 19:53:28 +08:00
bincxz c86116ac08 fix(ai): keep configured Codex models clear of catalog loading 2026-10-15 19:49:07 +08:00
bincxz 5ac8c8bf1f fix(sync): honor chat deletions and exact backup restoration 2026-10-15 19:33:12 +08:00
bincxz b99de934a3 fix(ai): align catalog source with retained and configured models 2026-10-15 19:30:54 +08:00
bincxz 8e88b99131 fix(sync): preserve chat turn order and recovery boundaries 2026-10-15 19:09:02 +08:00
bincxz d7122683d2 fix(ai): show loading only for pending model catalogs 2026-10-15 19:02:26 +08:00
陈大猫 2c67e3c3ce Merge pull request #2987 from Zeral-Zhang/feature/toggle-window-opacity
feat: toggle window transparency
2026-10-15 19:01:18 +08:00
bincxz 7e9e9b53eb Merge remote-tracking branch 'origin/main' into codex/takeover-pr-3642 2026-10-15 18:58:37 +08:00
陈大猫 e8bbc9a5c9 Merge pull request #3624 from GOUKI9999/fix/model-catalog-blockers
fix(ai): unblock model catalogs for copilot and mimo agents
2026-10-15 18:56:20 +08:00
bincxz 3de34cae5d fix: leave IME processing keys out of transparency toggles 2026-10-15 18:43:56 +08:00
bincxz 7851ddb01e fix(sync): complete chat entity labels and key typing 2026-10-15 18:42:53 +08:00
bincxz de517a6237 fix(sync): honor chat consent during download and initial enable 2026-10-15 18:41:17 +08:00
bincxz aca81953fe fix: keep detached opacity shortcut configuration current 2026-10-15 18:31:34 +08:00
bincxz 9a484ba3cb fix(ai): forward Copilot profile environment to model discovery 2026-10-15 18:30:27 +08:00
bincxz dfc7961b68 fix(sync): complete portable chat and preservation flows 2026-10-15 18:26:17 +08:00
陈大猫 41d2a2d4af Merge pull request #3646 from GOUKI9999/fix/job-startup-diagnostics
feat(ai): instrument job startup pipeline for #3443 diagnostics
2026-10-15 18:23:11 +08:00
bincxz af9ee5d697 fix(ai): preserve completed Grok catalog probes on deadline 2026-10-15 18:17:49 +08:00
bincxz 2aae278d53 fix: isolate settings delivery failures per window 2026-10-15 18:16:28 +08:00
bincxz d9632ab985 Merge latest model catalog fixes from PR 3624 2026-10-15 18:14:00 +08:00
bincxz 82ee429eab fix(ai): distinguish raw probe arrivals from outbound writes 2026-10-15 18:10:01 +08:00
bincxz b70abfd70d test: allow shared opacity in detached settings guard 2026-10-15 18:05:45 +08:00
bincxz 1fe313b229 Merge remote-tracking branch 'origin/main' into codex/pr-2987-takeover 2026-10-15 18:04:15 +08:00
bincxz fd559eb095 fix: keep transparency toggles synchronized and remember opacity 2026-10-15 18:03:47 +08:00
bincxz 3f2b877ba6 Merge commit 'refs/pr-takeover/3633/main' into codex/takeover-pr-3633 2026-10-15 18:02:57 +08:00
bincxz 707a8749c9 fix(ai): keep Copilot selection consistent across discovery states 2026-10-15 18:02:42 +08:00
bincxz 2d5f90ac2e Merge remote-tracking branch 'origin/main' into codex/pr-3624-fix 2026-10-15 18:01:46 +08:00
Fyhax1kiandfyhax1ki d0e024625c feat: add clear-all command history action (#3632)
Add the Global history clear-all action with confirmation and five-language copy. Clear local shell history, autocomplete and compose recall while preserving drafts, keeping peer windows consistent on clears, and allowing new commands afterwards.

Verified with 116 focused checks, two clean independent final reviews, real Electron multi-window SSH-fixture interaction and restart, current-head Codex review, and both required CI jobs.

Co-authored-by: fyhax1ki <fyhax1ki@gmail.com>
2026-10-15 18:00:43 +08:00
bincxz 9a8f9bb0c6 Merge current main into transparency toggle branch 2026-10-15 17:53:14 +08:00
bincxz b512133209 fix(ai): collect worker startup diagnostics in the main log 2026-10-15 17:52:56 +08:00
bincxz 83ee53ba96 Merge remote-tracking branch 'origin/main' into codex/pr-3646-startup-diagnostics
# Conflicts:
#	electron/bridges/ai/ptyExec.cjs
2026-10-15 17:49:45 +08:00
bincxz fa07263628 fix(ai): persist first current-only model catalog 2026-10-15 17:46:59 +08:00
bincxz 08c0ac4f59 fix(ai): preserve model selection on degraded Copilot catalogs 2026-10-15 17:44:32 +08:00
bincxz d298275378 Merge remote-tracking branch 'origin/main' into codex/pr-3624-fix 2026-10-15 17:38:02 +08:00
陈大猫 cdf9b334d5 fix(ai): keep undo branches in the viewing scope (#3686) 2026-10-15 17:22:56 +08:00
陈大猫 158f204baa fix(terminal): withdraw unreleased archive command shortcut
Withdraw the unreleased archive-command shortcut from #3682. Real first-party SFTP locate,auto-run multiline snippets and paste controls showed old filenames preparing commands in a changed directory. The attempted fragment-based tracking required growing state guards,so defer this implementation rather than expand the feature.

The final diff only removes the original seven files/248 added lines.141 related checks,lint,build and real full-app normal-input,SFTP,snippet,existing-link and draft controls passed. Current-head remote review and both required CI jobs passed. Existing AI repairs are untouched.

Related to #3269 and #3682. The feature request stays open. No release.
2026-10-15 16:58:18 +08:00
陈大猫 1c34384651 fix(ai): preserve shell hooks when stopping agent commands
Stopping paced AI input could leave user shell hooks disabled. Remove the unproven PS0 mutation while preserving the existing combined-output fix.

Independent validation:310 checks pass,7 skipped;24 real Bash/SSH normal,cancellation and combined-output controls. Current-head remote review,automated tests and all platform packages passed.

Related to #3683 and #3485. Original reporter acceptance remains pending. No release.
2026-10-15 16:25:25 +08:00
Netcatty-Bot 3e7d871a33 fix(ai): silence bash PS0 around agent PTY command echoes (#3683)
Neutralize bash PS0 around agent PTY wrapper reads, then restore. Skipped Codex P2 on __NCMCP_PS0 collision as edge-case thrash.

Fixes #3485
2026-10-15 15:47:14 +08:00
陈大猫 758966a79c fix(ai): send chat image attachments as data URLs (#3681)
* fix(ai): encode chat image attachments as data URLs

* test(ai): keep image bridge fixture type safe
2026-10-15 15:45:23 +08:00
陈大猫 f0458dd7cc feat(terminal): prepare tar and zip commands from archive links (#3682)
* feat(terminal): prepare tar and zip commands from archive links

* fix(terminal): expire archive links after another command
2026-10-15 15:44:47 +08:00
陈大猫 52797e9edd fix(port-forwarding): preserve exhaustion across duplicate failures (#3679)
* fix(port-forwarding): preserve exhaustion across duplicate failures

* fix(port-forwarding): reset exhausted state on active adoption

* fix(port-forwarding): confirm adoption before clearing exhaustion
2026-10-15 15:26:04 +08:00
陈大猫 cc001c9a4b fix: keep OpenCode plugin errors from stopping resumed chats (#3677)
* fix: keep OpenCode plugin errors from stopping resumed chats

* fix: preserve each OpenCode background warning
2026-10-15 15:04:36 +08:00
陈大猫 b81b27f817 fix(ai): preserve terminal replies between OSC contexts (#3678) 2026-10-15 15:03:21 +08:00
陈大猫 3a2bf6498d feat(vault): move selected hosts to a group (#3675)
Add a Move to group action for the selected hosts, reusing existing group moves and saving the selection once. Omit the hidden synthetic General destination.

Related to #3194; marquee selection and dragging a selection are outside this change.

65 focused checks, lint, build and real grid/list mouse/keyboard/cancel/reload/single-host drag checks pass. Current-head remote review and both CI jobs pass.
2026-10-15 14:52:16 +08:00
陈大猫 53a4bf29b0 fix(terminal): retain absent local shell display snapshots (#3674)
Preserve the original local shell name and icon when a saved host is edited and a terminal is copied.

Related to #3615 and #3616.

Validated with 70 focused checks, lint, production build and actual terminal copy flows. Current-head remote review and CI pass.
2026-10-15 14:44:11 +08:00
GOUKI9999 e8ad5b3d29 Merge remote-tracking branch 'fork/fix/model-catalog-blockers' into pr3642-fix 2026-10-15 10:54:31 +08:00
GOUKI9999andClaude Sonnet 5.5 b7953a6b26 fix(ai): require advertised thinking levels for suffixed current ids; fingerprint ANTHROPIC_BASE_URL
- Last-known-good serving keeps a decorated current id only when the base row
  advertises that level (same rule as the renderer's modelPresetsContainId).
- ANTHROPIC_BASE_URL joins the main-process and renderer catalog cache keys so
  a different Claude endpoint never serves another endpoint's persisted list.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-15 10:54:16 +08:00
GOUKI9999andClaude Sonnet 5.5 0a01af5144 fix(ai): use raw probe byte counter in events; log worker-side job misses
- probe-output-arrived and probe-reply-parsed report the cumulative raw
  byte count, consistent with the startup timeout record.
- A poll/stop that the worker answers with 'Background job not found' while
  the route still exists now emits job-stop-miss (worker-job-missing). The
  route itself is left alone; this PR stays diagnostics-only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-15 10:53:22 +08:00
GOUKI9999 848f201cf9 Merge remote-tracking branch 'fork/fix/model-catalog-blockers' into pr3642-fix 2026-10-14 15:58:44 +08:00
GOUKI9999andClaude Sonnet 5.5 5c901c6b04 fix(ai): keep effort-decorated current id from last-known-good when its base row exists
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 15:58:31 +08:00
GOUKI9999andClaude Sonnet 5.5 de3410f6e1 fix(ai): name the first probe output checkpoint honestly
The first decoded chunk while probing may be only the echoed probe command,
so probe-reply-arrived overstated what was seen. Rename it (and the timeout
stat) to probe-output-arrived; probe-reply-parsed remains the proof of reply.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 15:57:44 +08:00
GOUKI9999andClaude Sonnet 5.5 a76971e2c5 fix(ai): keep Grok effort-decorated current id, ASCII-only sources; merge #3624 fixes
- last-known-good serving keeps grok-4.6/high when the grok-4.6 row exists.
- Replace non-ASCII dashes/middle dot in files that were ASCII-only.
- Merge #3624 (suffixed Copilot row, retry warning on retained catalog).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 15:13:39 +08:00
GOUKI9999andClaude Sonnet 5.5 84bf1cbfff fix(ai): keep suffixed Copilot selection selectable and keep retry warning on retained catalog
- appendRetainedStoredModelPreset appends the exact suffixed id when a
  base-only row exists that does not cover the suffix.
- createSdkRuntimeModelCache carries a degraded refresh's warning onto the
  retained cached catalog so the banner and Retry stay visible.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 15:10:39 +08:00
GOUKI9999andClaude Sonnet 5.5 d4d07d48af fix(ai): report route-removed once and count cmd-write bytes as UTF-8
- deleteWorkerRoute only emits when it actually removes the matching route,
  so a concurrent cancel plus terminal cleanup yields one record.
- cmd-write.bytes uses Buffer.byteLength instead of UTF-16 length.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 15:05:50 +08:00
GOUKI9999andClaude Sonnet 5.5 1ff40e859c fix(ai): return no runtime presets for an empty catalog and sync GROK_CONFIG_DIR
- an empty catalog now yields no runtime presets even when the user has custom
  composer models, so the built-in fallback list stays visible
- add GROK_CONFIG_DIR to the renderer cache env hints (the sync test caught
  the drift after the main-process key was added)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-14 00:01:42 +08:00
GOUKI9999 edf07fc74e Merge branch 'pr3624-fix' into pr3642-fix 2026-10-13 23:59:44 +08:00
GOUKI9999andClaude Sonnet 5.5 6a1bea2bce fix(ai): count raw probe bytes, log lookup misses in the main handlers, keep diagnostics ASCII
- count probe bytes from the raw chunk before decoding, so an incomplete UTF-8
  prefix and multi-byte text are reported in bytes
- log job-stop-miss from the main-process poll/stop handlers too: once the
  worker route is gone the dispatcher falls through to them
- replace the circled numeral in the new diagnostics module

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 23:59:32 +08:00
GOUKI9999andClaude Sonnet 5.5 7a1f415a91 fix(ai): fingerprint the Grok login directory and keep the persistence module ASCII-only
- add GROK_CONFIG_DIR to the model catalog cache env keys so two grok login
  profiles sharing HOME and the binary do not share a catalog
- replace the em dash added in the current-only refresh comment

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 23:57:01 +08:00
GOUKI9999andClaude Sonnet 5.5 745f6a3120 test(ai): expect the Copilot headless wrapper on Windows only
The wrapper is no longer used on POSIX, so the two driver tests that asserted
it on every platform now assert the direct CLI path there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 23:49:21 +08:00
GOUKI9999andClaude Sonnet 5.5 19faa554a4 fix(ai): address review feedback on the unified model catalog UX
- generate the Copilot headless wrapper in the managed temp directory, create it
  exclusively and only reuse an existing file whose content matches; a tampered
  file is not handed to the SDK
- use the headless wrapper on Windows only; POSIX passes the resolved CLI straight
  to the SDK so forceStop() reaches the real process
- keep the renderer model-cache env hints in sync with the main-process keys
  (CODEBUDDY_* and XAI_API_KEY) and guard it with a test
- forward source/fetchedAt from list-models so a last-known-good catalog is not
  labelled live
- do not retain a saved Claude alias on top of an empty catalog, which would turn
  a one-row list into the authoritative one and hide the built-in presets
- ASCII-only comments in the two new modules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 23:40:33 +08:00
GOUKI9999 c0a66f1e88 Merge branch 'pr3624-fix' into pr3642-fix
# Conflicts:
#	components/AIChatSidePanelHelpers.test.tsx
#	electron/bridges/aiBridge/sdk/copilotDriver.test.cjs
2026-10-13 23:32:10 +08:00
GOUKI9999andClaude Sonnet 5.5 6a79400112 fix(ai): address review feedback on the model catalog PR
- keep an already-qualified {provider, model} default in getOpenCodeDefaultModelIds
  instead of prefixing the provider twice
- resolve npm's copilot.ps1 wrapper to the JS entry on Windows like .cmd/.bat
- when serving a last-known-good catalog, remap a persisted current id that has
  no row to the first visible row for every backend (null still means default),
  so the picker and the send preflight agree
- reconcile the catalog warning banner from the result of every refresh, so a
  panel that joined another panel's in-flight load also shows it

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 23:31:08 +08:00
GOUKI9999andClaude Sonnet 5.5 13bcf47282 fix(ai): address review feedback on the job startup diagnostics
- keep jobDiag.stats.probeBytes in sync so the startup-timeout event reports
  the bytes of a partial probe reply
- route every worker route-map deletion through one helper that emits
  route-removed (poll/stop completion, stale check, chat cancel, terminal close)
- label a poll/stop miss as route-missing, scope-mismatch or
  worker-unavailable instead of always route-missing

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SX3d2XMHxBEpU7VqpvXbdm
2026-10-13 21:32:28 +08:00
GOUKI9999 e5abae559c feat(ai): instrument job startup pipeline for #3443 diagnostics
Add read-only [Netcatty JobDiag] timeline emission covering the four
checkpoints requested in #3443: probe write/reply/parse (2), command
write + start marker (3), startup timeout with byte stats, interrupt
delivery with flow-control snapshots, and the MCP background-job route
lifecycle (4). Every payload is keyed by sessionId + jobId (jobId was
previously absent from all logs) and carries monotonic at/sinceStartMs
timestamps.

interrupt-callback-invoked reports finishedAtCallback so the recovery
ordering finding from the #3443 investigation is directly observable;
interrupt-callback-skipped fires when recovery is skipped (no callback
wired or callback threw). Checkpoint 1 (flow-control samples) remains
covered by the existing [Netcatty Ctrl+C] / [Netcatty Terminal Perf]
emitters; session snapshots here reuse the same helpers.

Enabled via NETCATTY_JOB_DIAG=1 or the existing NETCATTY_TERMINAL_DEBUG=1.
Zero behavior change: instrumentation calls only, jobId/sessionId/
diagnosticsSession are optional startPtyJob options defaulting to null.
2026-10-13 11:44:59 +08:00
GOUKI9999 d653180c3c fix(ai): union the grok ACP and CLI catalogs so a session subset cannot shrink the picker
- ACP initialize _meta.modelState reflects the negotiated agent session and
  has been observed to advertise only a subset of the account's models
  (e.g. grok-4.6/4.5 without the 4.7 family), while `grok models` lists the
  full account set; the old short-circuit (non-empty ACP catalog wins) made
  the live picker silently drop models one source knows about
- run both probes together and merge by id: ACP entries win for shared ids
  because they carry live vendor _meta (reasoning efforts, description);
  fields an ACP entry lacks are filled from the CLI row
- tests: mergeGrokCatalogModels unit cases (subset union, dedupe, field
  fill, malformed sides) and registry-level union/no-dupe coverage
2026-10-13 10:43:08 +08:00
GOUKI9999 0006634f6b fix(ai): show build-time presets while the opencode catalog loads
opencode was the only SDK agent whose picker rendered nothing until its
live catalog pull resolved: the #3584 suppression replaced presets with
just the user's custom ids while runtimeModelLoading was set. Align it
with every other backend — presets stay selectable during loading, the
live catalog replaces them on arrival, and #3585's retry/warmer
mechanics are untouched. Adds a regression guard against reintroducing
the opencode gating.
2026-10-12 18:12:34 +08:00
GOUKI9999 729ffcf162 fix(ai): capture dash-bullet grok model entries in the CLI catalog parse
Ground truth from grok 1.0.50 (`grok --no-auto-update models`): the default
model is listed with a "*" bullet but every other entry uses "-", so the
previous ^\*+-only regex silently dropped 3 of 4 live models and the
"live" picker shrank below the build-time presets. Accept any bullet
marker (*/-/*) so separator dashes still cannot match. Adds the captured
raw-output fixture plus an ACP initialize fixture (grok-4.7 / 4.7-build-fast /
4.6 / 4.5) asserting the registry ACP path keeps every availableModels entry.
2026-10-12 18:12:34 +08:00
GOUKI9999 e642c4953f feat(ai): unify model catalog UX across SDK agents
Implements the unified model catalog UX on top of the last-known-good
persistence layer (#3624):

- R1 source provenance end-to-end: list-models now returns
  source: 'live' | 'last-known-good' plus fetchedAt (ISO) on live
  successes and last-known-good serve-outs; the pre-flight cache replays
  the original provenance on hits. The renderer cache persists
  source/fetchedAt alongside the catalog, and the build-time preset
  fallback derives 'presets'.
- R2 loading state for all backends: drop the opencode-only gate on
  modelCatalogLoading so every SDK backend shows the composer loading
  state while its live fetch is in flight (opencode behavior unchanged).
- R3 unified status chip: ComposerModelPicker renders a muted footer chip
  for every backend - live / cached with relative last-success time /
  built-in default list - replaced by the spinner row while loading.
  Keys added to en/es/zh-CN/zh-TW (ru keeps its pre-existing ai.opencode
  gap).
- R4 copilot headless wrapper: generated per-resolve wrapper (baked with
  the platform exe the npm loader would spawn) is handed to
  RuntimeConnection.forStdio, spawning with windowsHide:true so no
  console window flashes in Electron. Falls back to the loader when the
  exe cannot be resolved (window may flash - documented degradation).
2026-10-12 16:53:00 +08:00
GOUKI9999 cb737ba0c9 fix(ai): keep refreshed current rows readable, share the mimo catalog deadline, and isolate grok catalog env
- modelCatalogLastKnown: a current-only refresh to an id absent from the
  persisted list now synthesizes a minimal row (label = the id) instead of
  leaving the persisted current id dangling, so a later live failure serves
  a list whose current row the picker and the send preflight agree on
- mimoDriver: sdkStreamHandlers hands an absolute catalog deadline down
  (outer budget minus 1s headroom); mimo serve readiness and the providers()
  query draw from that one pool instead of re-arming independent 25s caps,
  so the pair can no longer outrun the 30s outer model-list budget
- sdkStreamHandlers: add XAI_API_KEY to SDK_MODEL_CACHE_ENV_KEYS so two
  grok profiles sharing one binary but not credentials never share a
  catalog (MODEL_CACHE_ENV_HINTS does not exist in this tree)
2026-10-12 15:01:19 +08:00
GOUKI9999 c6a1f11fc9 fix(ai): preserve current-only selections, isolate codebuddy catalog env, and robusten copilot auto fallback
- last-known-good store: a current-only catalog (zero visible models,
  valid currentModelId) now refreshes the persisted current id via
  refreshLastKnownCatalogCurrentId instead of being skipped, so the
  user's selection survives a later live failure without clobbering
  the persisted models list
- SDK_MODEL_CACHE_ENV_KEYS: add CODEBUDDY_API_KEY, CODEBUDDY_AUTH_TOKEN
  and CODEBUDDY_INTERNET_ENVIRONMENT so two codebuddy profiles sharing a
  binary but not credentials no longer share one catalog cache key
- isCopilotAutoOnlyFallback: detect the copilot auto row among the
  renderer-appended rows (composer custom ids, retained selections)
  instead of requiring exact single-entry shape, keeping saved explicit
  selections valid when the picker list mixes extra rows
2026-10-12 12:29:36 +08:00
陈奇 5ed58345aa fix(ai): preserve unspecified effort on explicit Claude models 2026-10-12 04:06:53 +00:00
GOUKI9999 5f29d91499 fix(ai): keep effort suffixes on retained copilot preset rows
appendRetainedStoredModelPreset reduced a saved selection to its base id,
so a suffixed saved copilot model (e.g. claude-sonnet-4.5/high) produced
a row that no longer matched the stored id: the picker fell back to auto
while the send preflight passed the saved id. Append the exact stored
spelling when no build-time preset defines the base id.
2026-10-12 11:53:15 +08:00
GOUKI9999 5d9c8f29de fix(ai): qualify provider/model defaults before the model-only branch
getOpenCodeDefaultModelIds checked the bare value.model string before the
provider-aware shapes, so {provider: 'xiaomi', model: 'chosen'} returned
the unqualified 'chosen' and mimo's visibility check could never match
its fully qualified model ids. Mirror the singular resolver's branch
order.
2026-10-12 11:53:15 +08:00
陈奇 355d53abe3 fix(ai): retain degraded catalog warnings through cache copies 2026-10-12 03:40:23 +00:00
GOUKI9999 1ee0f8441c fix(ai): keep preserved saved models visible in the picker and cache fallback warnings
A stored selection preserved through the claude-alias or copilot
auto-only degraded fallback had no preset row, so the picker could show
no selected row while the send preflight passed the hidden value; append
a preset row (reusing the build-time preset when it defines the id).

Last-known-good responses were cached without their warning, so another
panel or a remount within the renderer TTL presented degraded models as
live and hid the Retry action. The warning now travels with the cached
catalog and re-syncs the banner on cached hits.
2026-10-12 11:36:19 +08:00
GOUKI9999 c396fc78ef fix(ai): resolve the mimo default across a multi-key default map
getOpenCodeDefaultModelId returns only the first default entry, so a
catalog declaring the hidden auto channel before the xiaomi provider made
the filtered catalog fall back to the first model instead of the CLI's
configured Xiaomi default. Enumerate every advertised default and select
the first one that survives filtering.
2026-10-12 11:36:19 +08:00
GOUKI9999 c48514381e fix(ai): preserve a saved Copilot model during degraded discovery
The auto-only COPILOT_MODEL_PRESETS fallback is nonempty, so a live
listModels failure invalidated a saved explicit Copilot model selection:
shouldUseStoredAgentModel only preserved unknown stored ids when the
preset list was empty, and picker plus send path silently switched to
auto. A saved id keeps resolving while the presets are exactly the
auto-only fallback.
2026-10-12 11:15:53 +08:00
GOUKI9999 5ae5965556 fix(ai): keep the current model inside the persisted catalog cap
writeLastKnownCatalogEntry sliced models to the 200-entry cap without
checking whether the current model survived the slice, so a huge live
catalog could persist a currentModelId with no picker row and the
last-known-good serve would let the picker and the send preflight
disagree again. Retain the current model in the capped set.
2026-10-12 11:15:52 +08:00
GOUKI9999 0050e895df Merge fork/fix/model-catalog-blockers: adopt upstream fixes and keep complementary catalog hardening
Adopts the PR author's commits for the copilot shutdown race, the mimo
filtered-channel default, and the claude alias fallback presets. Keeps the
complementary pieces: last-known-good mimo read-back normalization and
renderer-side preservation of stored claude aliases against live full-id
catalogs.
2026-10-12 11:07:15 +08:00
GOUKI9999 060fbbb2d1 fix(ai): keep stored claude alias selections when the catalog lists full ids
Preset lists before the 2026-10 claude catalog refresh persisted
sonnet/haiku alias ids. A live catalog of full ids made
shouldAdoptSdkCurrentModel treat such a stored selection as stale and
silently overwrite it, even though the claude CLI still resolves the
alias. Stored aliases now keep resolving (picker and send path) and are
never replaced by the catalog's current model; other backends and
non-alias ids are unchanged.
2026-10-12 11:00:49 +08:00
GOUKI9999 8c64280d87 fix(ai): cancel the losing copilot shutdown timer and force-stop on rejection
stopCopilotClient's 3s grace timer stayed alive whenever stop() won the
race, leaking one handle per turn/catalog load. Clear it in a finally. A
stop() rejection also no longer counts as settled, so the forceStop()
fallback still runs when the graceful handshake fails.
2026-10-12 11:00:49 +08:00
GOUKI9999 422bf120a9 fix(ai): keep the mimo current id off the filtered auto channel
A live default on the filtered mimo auto channel surfaced a currentModelId
the picker could not render or check while sends still went through the
channel. Replace it with the vendor's documented default when the remaining
models offer it, else the first remaining model, else null; ids outside the
filtered channel pass through untouched. Apply the same normalization when
serving a persisted last-known-good catalog captured before filtering.
2026-10-12 11:00:35 +08:00
陈奇 555e911887 fix(ai): preserve saved Claude fallback aliases 2026-10-12 02:45:39 +00:00
陈奇 74b7ce6c8c fix(ai): align MiMo catalog default with visible models 2026-10-12 02:45:39 +00:00
陈奇 3b78e097e6 fix(ai): force Copilot shutdown after stop rejection 2026-10-12 02:45:39 +00:00
xu 6052cbbd1f feat(sync): non-destructive union merge + AI sessions in cloud sync
Cloud sync uploaded the whole encrypted vault as a single payload. Two
problems follow from that, both of which we hit in production:

1. A one-sided deletion propagated to every device. Restoring an older
   local backup is indistinguishable from "the user deleted these 25
   hosts", so the next sync happily overwrote the cloud replica and
   every other machine with the older, smaller vault.

2. AI chat sessions were not part of the sync payload at all, so they
   never travelled between machines and never appeared in any backup.

This change adds an opt-in "keep all" merge and makes sessions syncable.

## Non-destructive merge

`mergeSyncPayloads` gains `{ preserveDeletions }`. When set, an entity
missing on one side is carried forward from the side that still has it;
only entities absent from base *and* both sides are removed. It is
exposed as the new `smartMergePreserve` strategy ("Smart merge (never
delete)") and threaded through every merge call site:

- `providerSyncMethods.syncToProviderImpl`
- `syncAllStorageMethods`
- `useAutoSync`

Default behaviour (`smartMerge`) is unchanged, so existing users see no
behaviour change until they opt in.

## AI sessions in the payload

`SyncPayload.aiSessions` is new and opt-in via the
"Sync AI chat history" switch in Settings → Cloud Sync. Sessions are
unioned by id, and messages are merged **append-only**: a message is
identified by id and the merged transcript is the union of all three
sides ordered by timestamp. Two devices that appended different turns to
the same conversation therefore keep both turns, instead of one device
silently dropping the other's work.

Applying a downloaded payload unions with the local transcript rather
than replacing it, so an older cloud snapshot can never delete turns
that only exist locally.

Inline attachment blobs (`base64Data`) are stripped before upload —
image/PDF payloads would multiply the encrypted vault size and may carry
data the user never intended to leave the device. Attachment metadata
(filename, media type, line count) is kept for context.

## Tests

- `domain/syncMerge.preserveDeletions.test.ts` — one-sided deletions
  (local and remote), both-sides deletion, additions, notes/snippets/
  port-forwarding/string entities, idempotence, summary reporting.
- `domain/syncMerge.aiSessions.test.ts` — session union, append-only
  message merge, timestamp ordering, metadata LWW, strategy-aware
  deletion, attachment stripping, idempotence.

Verified locally: 1939/1939 tests pass across the domain, convergentSync,
i18n, cloudSync and application sync suites; eslint clean on all touched
files.
2026-10-11 15:48:54 +08:00
GOUKI9999 ecd988ea4c fix(ai): resolve last-known catalog path via app.getPath and bound persisted entries
Review feedback on PR #3624:
- resolveLastKnownCatalogPath now reads userData through
  electronModule.app.getPath, matching the real bootstrap where
  electronModule is the require('electron') namespace (previously the
  persistence layer was a silent no-op in production)
- the last-known store now caps entries at LAST_KNOWN_MAX_ENTRIES (32,
  mirroring the in-memory TTL cache) and evicts the least recently
  updated entries, so churned fingerprinted cache keys cannot grow the
  store file without bound
- replace em dashes with ASCII punctuation per repo convention
- test stub now mirrors the real electronModule shape
2026-10-10 19:15:53 +08:00
GOUKI9999 258d72bdca fix(ai): restore copilot loader-first resolution and add copilot/mimo preset fallbacks
Revert d2b1d5fa2's default preference of the native copilot.exe: the
1.0.59-era native CLI bootstraps %LOCALAPPDATA%\copilot\pkg\ on first
start, starts slowly, and leaves a conhost child alive after app-side
timeout/abort (console window stays open; CLI server exited unexpectedly
with code 0). Loader-first (npm-loader.js) is the default again; the
native binary is opt-in via NETCATTY_COPILOT_PREFER_NATIVE=1.

Also:
- Add COPILOT_MODEL_PRESETS (auto) so a live listModels failure no
  longer leaves the Copilot picker empty.
- Sync MIMO_MODEL_PRESETS to the 6 verified live-catalog models
  (v2.6/v2.5 pro-ultraspeed/pro/flash); auto channel stays filtered
  driver-side.
- Reap the Copilot CLI child on abort/stop: stopCopilotClient() races
  graceful client.stop() with a 3s grace and falls back to the SDK's
  forceStop() (SIGKILL) so the spawned process does not linger.
2026-10-10 19:07:11 +08:00
GOUKI9999 157e5f03f0 Merge branch 'fix/model-catalog-blockers' into test/model-catalog-plus-presets 2026-10-10 18:37:56 +08:00
GOUKI9999 d2b1d5fa20 fix(ai): prefer the native copilot.exe over npm-loader.js in SDK resolution
npm-loader.js re-spawns the native binary via spawnSync WITHOUT
windowsHide, flashing a console window when the Copilot SDK runs inside
Electron's GUI main process on Windows. When the platform-native binary
(@github/copilot-<platform>-<arch>/copilot.exe) exists next to the
resolved package, hand it to RuntimeConnection.forStdio directly — the
SDK spawns it itself with windowsHide:true. Fall back to npm-loader.js
when the native package is absent (e.g. optional deps omitted).
2026-10-10 18:33:47 +08:00
GOUKI9999 cc6ba30891 Merge remote-tracking branch 'fork/fix/claude-preset-refresh' into test/model-catalog-plus-presets 2026-10-10 18:21:10 +08:00
GOUKI9999 2fefdf6f0c Merge branch 'fix/model-catalog-blockers' into test/model-catalog-plus-presets 2026-10-10 18:21:09 +08:00
GOUKI9999 01d6c4ceaf fix(ai): filter the mimo auto channel out of the live catalog 2026-10-10 18:20:04 +08:00
GOUKI9999 9b7d2a6a34 fix(ai): expand Claude fallback presets to the full live-generation list 2026-10-10 18:10:40 +08:00
GOUKI9999 d79a4de401 Merge fork/fix/claude-preset-refresh into test/model-catalog-plus-presets 2026-10-10 17:49:19 +08:00
GOUKI9999 9a17691c32 fix(ai): widen the mimo inner catalog setup budget to 25s
The catalog path boots a dedicated `mimo serve` and then queries providers();
the inner awaitMimoSetup race (and the serve readiness timeout) was 10s and
lost on the coldest boots even though the outer mimo budget is now 30s. Give
the catalog path a 25s inner budget (MIMO_CATALOG_SETUP_TIMEOUT_MS, passed as
both the spawn readiness timeout and the providers race). runMimoTurn keeps
the 10s default.
2026-10-10 17:11:21 +08:00
GOUKI9999 c22bf0ab9b feat(ai): fall back to last-known-good model catalogs on live fetch failure
Persist each successful live catalog ({userData}/model-catalog-last-known.json,
keyed by the same backend+binPath+runtime+envHash string as the in-memory TTL
cache) and serve it when a later live fetch fails, before degrading to curated
presets. Copilot has no presets at all, so this is its first real fallback.
Empty catalogs are never persisted; corrupt files and IO errors degrade
gracefully; per-entry models are capped at 200. The response keeps the
warning contract and adds source/fetchedAt markers for the UI.
2026-10-10 17:11:21 +08:00
GOUKI9999 494cd57e25 fix(ai): refresh Claude fallback presets to the 5.x generation
The curated CLAUDE_MODEL_PRESETS fallback still advertised the 4.6
generation while the live CLI catalog serves Opus/Sonnet/Haiku 5.5 and
Fable 5.1. Alias ids (`default`/`sonnet`/`haiku`) are unchanged so the
CLI still resolves them; only display names move: sonnet/haiku now map
to claude-sonnet-5-5 / claude-haiku-5-5 in the Claude CLI alias table
(verified against CLI 2.1.296), and `default` has no fixed alias target,
so it keeps the CLI's own neutral "Default (recommended)" label.
2026-10-10 16:39:45 +08:00
GOUKI9999 f0169ad632 fix(ai): resolve copilot .cmd shim before spawning SDK
RuntimeConnection.forStdio({ path }) makes the Copilot SDK spawn the
CLI through node WITHOUT shell:true. Windows npm installs expose
copilot as a .cmd shim, and Node >= 18.20 throws spawn EINVAL for
.cmd/.bat in milliseconds, so listCopilotModels()/runCopilotTurn()
could never start the runtime via the PATH-resolved shim.

Add resolveCopilotExecutableForSdk() to shellUtils (same per-CLI
resolver pattern as claude/codex/codebuddy): resolve the shim to the
package's real npm-loader.js entry via the npm layout shortcut, then
by parsing the shim, and pass .exe/.js entries through unchanged.
Apply it at both RuntimeConnection.forStdio call sites; unresolvable
shims keep the original path so behavior is unchanged.

Harness: PATH-resolved copilot.cmd -> npm-loader.js, catalog [auto]
returned in 3.0-3.6s (was: EINVAL in 1-2ms, empty catalog).
2026-10-10 15:51:21 +08:00
GOUKI9999 df74164d54 fix(ai): skip skill-path probe in mimo catalog and extend its list timeout
listMimoModels() spawned `mimo debug config` only to seed the server's
skills config, which the provider catalog never reads. That probe alone
costs 6-8s on a cold CLI, pushing the whole chain (probe + serve boot +
config.providers()) past the shared 10s model-list timeout, so the mimo
catalog always degraded to an empty list with a UI warning.

- drop the readMimoSkillPaths() call from listMimoModels(); the turn
  path (runMimoTurn) still reads skill paths unchanged
- add a per-backend catalog timeout override map; mimo gets 30s because
  it cold-boots a dedicated `mimo serve` process per catalog pull
  (unlike OpenCode's pooled server), while every other backend keeps
  the existing 10s (opencode: 10s + server start) budget

Harness: no debug-config spawn, catalog 7 models in 7.7-10.5s (was:
timeout error at 10s, empty catalog every time).
2026-10-10 15:51:07 +08:00
Zeral 565ab504f4 Merge branch 'main' into feature/toggle-window-opacity 2026-08-24 13:13:26 +08:00
Zeral Zhang 9958ee5097 feat: toggle window transparency 2026-08-14 20:11:57 +08:00
288 changed files with 18481 additions and 508 deletions

No files matched your search

+3
View File
@@ -52,6 +52,9 @@ jobs:
- name: Test
run: npm test
- name: Test browser first-link lifecycle
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox electron/hostBrowser/hostBrowser.firstLink.live.test.cjs
- name: Test terminal background rendering
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox --use-angle=swiftshader --enable-unsafe-swiftshader scripts/terminal-background-rendering.live.test.cjs
+4
View File
@@ -1,3 +1,5 @@
import { MonitorHostKeyDialog } from './components/vault/MonitorHostKeyDialog';
import { useMonitorRuntime } from './application/state/useMonitorRuntime';
import React, { useEffect } from 'react';
import { initializeFonts } from './application/state/fontStore';
@@ -45,9 +47,11 @@ function SettingsI18nProvider({ children }: { children: React.ReactNode }) {
* shell bags; AppSideEffects owns reactive effects + local UI publishing.
*/
function App() {
useMonitorRuntime();
return (
<AppLocalStateProvider>
<AppSideEffects />
<MonitorHostKeyDialog />
<AppShell />
</AppLocalStateProvider>
);
@@ -699,6 +699,89 @@ test('connection log host snapshot includes custom host icon fields', () => {
);
});
test('toggleOpacity hotkey invokes toggleWindowOpacity', () => {
let called = false;
const noop = () => {};
executeHotkeyActionImpl(
() => ({
IS_DEV: false,
MOVE_FOCUS_DEBOUNCE_MS: 0,
activeTabStore: { getActiveTabId: () => 'vault' },
addConnectionLogRef: { current: noop },
closeSession: noop,
closeTabInFlightRef: { current: false },
closeWorkspace: noop,
collectSessionIds: () => [],
confirmIfBusyLocalTerminal: async () => true,
createLocalTerminalWithCurrentShell: noop,
editorTabs: [],
fromEditorTabId: () => null,
handleOpenSettingsRef: { current: noop },
handleRequestCloseEditorTabRef: { current: noop },
isEditorTabId: () => false,
isQuickSwitcherOpen: false,
lastMoveFocusTimeRef: { current: 0 },
moveFocusInWorkspace: noop,
orderedTabs: [],
resolveCloseIntent: () => ({ kind: 'noop' }),
resolveSnippetsShortcutIntent: () => ({ kind: 'noop' }),
sessions: [],
setActiveTabId: noop,
setAddToWorkspaceDialog: noop,
setIsQuickSwitcherOpen: noop,
setNavigateToSection: noop,
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
splitSessionWithCurrentShell: noop,
systemInfoRef: { current: { username: 'user', hostname: 'host' } },
toEditorTabId: (id: string) => `editor:${id}`,
toggleBroadcast: noop,
toggleScriptsSidePanelRef: { current: noop },
toggleSidePanelRef: { current: noop },
toggleWindowOpacity: () => { called = true; },
toggleWorkspaceViewMode: noop,
workspaces: [],
}),
'toggleOpacity',
{ key: 'u', code: 'KeyU', ctrlKey: true, shiftKey: true } as KeyboardEvent,
);
assert.equal(called, true);
});
for (const scenario of [
{ name: 'IME process key with its original physical code', key: 'Process', keyCode: 229, isComposing: false, expected: false },
{ name: 'key during composition', key: 'U', keyCode: 85, isComposing: true, expected: false },
{ name: 'ordinary shortcut', key: 'U', keyCode: 85, isComposing: false, expected: true },
]) {
test(`transparency shortcut respects ${scenario.name}`, () => {
const target = new FakeHTMLElement();
const actions: string[] = [];
let prevented = false;
const event = {
...scenario,
code: 'KeyU',
ctrlKey: true,
shiftKey: true,
altKey: false,
metaKey: false,
target,
composedPath: () => [target],
preventDefault: () => { prevented = true; },
stopPropagation: () => {},
} as unknown as KeyboardEvent;
handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: 'Ctrl + W',
executeHotkeyAction: (action: string) => actions.push(action),
hotkeyScheme: 'pc',
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
}), event);
assert.deepEqual(actions, scenario.expected ? ['toggleOpacity'] : []);
assert.equal(prevented, scenario.expected);
});
}
for (const scenario of [
{ name: 'single orphan', active: 'one', sessions: [{ id: 'one' }], available: false, expected: null },
{ name: 'two orphans', active: 'one', sessions: [{ id: 'one' }, { id: 'two' }], available: true, expected: 'global' },
+9 -1
View File
@@ -306,6 +306,11 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
for (const binding of keyBindings) {
const keyStr = isMac ? binding.mac : binding.pc;
if (!matchesKeyBinding(e, keyStr, isMac)) continue;
// IME-filtered keys retain their physical code (e.g. Linux Unicode entry).
// Let composition handle them instead of treating them as opacity toggles.
if (binding.action === 'toggleOpacity' && (e.isComposing || e.keyCode === 229 || e.key === 'Process')) {
return;
}
if (HOTKEY_DEBUG) console.log('[Hotkeys] Matched binding:', binding.action, keyStr);
if (binding.category === 'sftp') {
continue;
@@ -781,7 +786,7 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
}
export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string, e: KeyboardEvent) {
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleScriptsSidePanelRef, toggleSidePanelRef, workspaces } = getCtx();
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
{
const shortcutTabs = buildNumberShortcutTabTargets({
showSftpTab: settings.showSftpTab ?? true,
@@ -971,6 +976,9 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
setNavigateToSection('snippets');
}
break;
case 'toggleOpacity':
toggleWindowOpacity();
break;
case 'toggleSidePanel':
toggleSidePanelRef.current?.();
break;
+13 -4
View File
@@ -42,6 +42,7 @@ import { resolveHostDefaultLocalShell } from '../../domain/localShellHost';
import { resolveGroupDefaults, applyGroupDefaults } from '../../domain/groupConfig';
import { upsertKnownHost } from '../../domain/knownHosts';
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
import { useVaultHostDeletion } from '../state/useVaultHostDeletion';
import { buildSshDeepLinkConnectionHost, buildSshDeepLinkEphemeralHost, buildSshDeepLinkEphemeralHostFromSaved, buildSshDeepLinkHostDraft, findSshDeepLinkHost, parseSshDeepLink } from '../../domain/sshDeepLink';
import { buildTelnetDeepLinkConnectionHost, buildTelnetDeepLinkEphemeralHostFromSaved, buildTelnetDeepLinkOpenHost, findTelnetDeepLinkHost, materializeTelnetDeepLinkMatchHost, parseTelnetDeepLink } from '../../domain/telnetDeepLink';
import { buildJmsDeepLinkEphemeralHost, isSupportedJmsProtocol, parseJmsDeepLink } from '../../domain/jmsDeepLink';
@@ -151,6 +152,7 @@ export function AppSideEffects() {
showSftpTab,
shellOnlyTabNumberShortcuts,
workspaceFocusStyle,
toggleWindowOpacity,
} = settings;
// Always publish terminal keyboard focus to the main process. When font zoom
@@ -1079,6 +1081,7 @@ export function AppSideEffects() {
canUseGlobalBroadcast: canUseGlobalBroadcastRef.current,
toggleScriptsSidePanelRef,
toggleSidePanelRef,
toggleWindowOpacity,
toggleWorkspaceViewMode,
workspaces: workspacesRefForHotkeys.current,
}), action, e);
@@ -1091,6 +1094,7 @@ export function AppSideEffects() {
splitSessionWithCurrentShell,
moveFocusInWorkspace,
toggleBroadcast,
toggleWindowOpacity,
toggleGlobalBroadcast,
toggleWorkspaceViewMode,
confirmIfBusyLocalTerminal,
@@ -1196,11 +1200,16 @@ export function AppSideEffects() {
setDeleteHostConfirm({ hostId, name: target?.label || hostId });
}, [hosts]);
const handleConfirmDeleteHost = useCallback(() => {
const deleteVaultHosts = useVaultHostDeletion(commitVaultGroupMutation);
const handleConfirmDeleteHost = useCallback(async () => {
if (!deleteHostConfirm) return;
updateHosts(hosts.filter(h => h.id !== deleteHostConfirm.hostId));
setDeleteHostConfirm(null);
}, [deleteHostConfirm, hosts, updateHosts]);
try {
await deleteVaultHosts([deleteHostConfirm.hostId]);
setDeleteHostConfirm(null);
} catch {
toast.error(t('common.error'));
}
}, [deleteHostConfirm, deleteVaultHosts, t]);
const handleCancelDeleteHost = useCallback(() => {
setDeleteHostConfirm(null);
+2 -1
View File
@@ -261,7 +261,7 @@ function AppViewInner({ domains }: AppViewProps) {
useMainWindowInputFocusRecovery({ onPageHidden: dismissTransientOverlays });
const {
addShellHistoryEntry, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace,
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace,
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
@@ -749,6 +749,7 @@ function AppViewInner({ domains }: AppViewProps) {
onAddKnownHost={handleAddKnownHost}
onCommandExecuted={handleTerminalCommandExecuted}
onDeleteShellHistoryEntry={removeShellHistoryEntry}
onClearCommandHistory={clearAllCommandHistory}
onTerminalDataCapture={handleTerminalDataCapture}
onCreateWorkspaceFromSessions={createWorkspaceFromSessions}
onAddSessionToWorkspace={addSessionToWorkspace}
+1
View File
@@ -36,6 +36,7 @@ export function VaultHost() {
return {
addShellHistoryEntry: actions?.addShellHistoryEntry,
removeShellHistoryEntry: actions?.removeShellHistoryEntry,
clearAllCommandHistory: actions?.clearAllCommandHistory,
commitPluginImporterData: actions?.commitPluginImporterData,
commitVaultImportTransaction: actions?.commitVaultImportTransaction,
commitVaultGroupMutation: actions?.commitVaultGroupMutation,
@@ -72,6 +72,7 @@ export function VaultPublisher({ children }: VaultPublisherProps) {
updateHostLastConnected,
addShellHistoryEntry,
removeShellHistoryEntry,
clearAllCommandHistory,
} = vault;
useLayoutEffect(() => {
@@ -144,12 +145,14 @@ export function VaultPublisher({ children }: VaultPublisherProps) {
updateHostLastConnected,
addShellHistoryEntry,
removeShellHistoryEntry,
clearAllCommandHistory,
});
return () => {
registerVaultSnapshotActions(null);
};
}, [
addShellHistoryEntry,
clearAllCommandHistory,
commitPluginImporterData,
commitVaultImportTransaction,
commitVaultGroupMutation,
+1 -1
View File
@@ -542,7 +542,7 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
}
return;
}
console.log('[App] Keyboard-interactive request received:', request);
console.log('[App] Keyboard-interactive request received:', { sessionId: request.sessionId, scope: request.scope, promptCount: request.prompts?.length });
// Add to queue instead of replacing - supports multiple concurrent sessions
setKeyboardInteractiveQueue(prev => [...prev, {
requestId: request.requestId,
@@ -1,9 +1,12 @@
import { installBrowserLockFixture } from "./testSupport/browserLockFixture";
import assert from 'node:assert/strict';
import test from 'node:test';
import type { SyncPayload } from '../domain/sync.ts';
import type { CloudSyncManager } from '../infrastructure/services/CloudSyncManager.ts';
installBrowserLockFixture();
const NOW = 1_700_000_000_000;
const localStorageValues = new Map<string, string>();
+2
View File
@@ -14,6 +14,7 @@ import {
type ConvergentMigrationProviderInput,
} from '../domain/convergentSync';
import { isProviderReadyForSync } from '../domain/sync';
import { isPreserveDeletionsStrategy } from '../domain/syncStrategy';
import { getCloudSyncManager, type CloudSyncManager } from '../infrastructure/services/CloudSyncManager';
import { markConvergentSyncInitialized } from '../infrastructure/services/convergentSyncConfig';
import { applyProtectedSyncPayload } from './localVaultBackups';
@@ -113,6 +114,7 @@ export async function prepareConvergentSyncMigration(
providers: inputs,
deviceId: manager.getState().deviceId,
now,
preserveDeletions: isPreserveDeletionsStrategy(manager.getState().syncStrategy),
});
if (plan.state) {
for (const seed of legacyBaselineSeeds) {
+78
View File
@@ -0,0 +1,78 @@
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings } from '../domain/models';
import { netcattyBridge } from '../infrastructure/services/netcattyBridge';
import { startPortForward } from '../infrastructure/services/portForwardingService';
import { requestHostBrowserPanel } from './state/hostBrowserPanelRequests';
import { isValidHslToken } from './state/settingsStateDefaults';
interface OpenHostBrowserOptions {
host: Host;
sessionId?: string;
hosts: Host[];
keys: SSHKey[];
identities: Identity[];
knownHosts?: KnownHost[];
terminalSettings?: Pick<TerminalSettings, 'verifyHostKeys' | 'keepaliveInterval' | 'keepaliveCountMax'>;
}
const pendingOpens = new Map<string, Promise<void>>();
const browserThemeTokens = ['background', 'foreground', 'secondary', 'muted', 'muted-foreground', 'border', 'primary', 'primary-foreground'] as const;
export function currentBrowserThemeTokens(element: Element = document.documentElement): Record<string, string> {
const style = getComputedStyle(element);
return Object.fromEntries(browserThemeTokens.flatMap((token) => {
const value = style.getPropertyValue(`--${token}`).trim();
return isValidHslToken(value) ? [[token, value]] : [];
}));
}
export async function openHostBrowser(options: OpenHostBrowserOptions): Promise<void> {
requestHostBrowserPanel({ host: options.host, sessionId: options.sessionId });
}
export async function openHostBrowserPanelUrl(browserId: string, url: string): Promise<void> {
const bridge = netcattyBridge.get();
if (!bridge?.openHostBrowserUrl) throw new Error('The host browser is unavailable in this build');
await bridge.openHostBrowserUrl({ browserId, url });
}
export function mountHostBrowser(options: OpenHostBrowserOptions & { browserId: string }): Promise<void> {
const { host, hosts, keys, identities, knownHosts, terminalSettings } = options;
const existing = pendingOpens.get(options.browserId);
if (existing) return existing;
const opening = (async () => {
const bridge = netcattyBridge.get();
if (!bridge?.setHostBrowserPanelLayout || !bridge.openHostBrowser || !bridge.startPortForward) {
throw new Error('The host browser is unavailable in this build');
}
const local = host.protocol === 'local';
const result = local ? { success: true, connectionOptions: undefined } : await startPortForward({
id: `host-browser-${crypto.randomUUID()}`,
label: `Browser: ${host.label || host.hostname}`,
type: 'dynamic',
hostId: host.id,
localPort: 0,
bindAddress: '127.0.0.1',
status: 'inactive',
createdAt: Date.now(),
}, host, hosts, keys, identities, () => {}, false, terminalSettings,
knownHosts, { dedicatedTransport: true, prepareOnly: true });
if (!result.success || (!local && !result.connectionOptions)) {
throw new Error(result.error || 'Could not prepare the browser connection');
}
await bridge.openHostBrowser({
browserId: options.browserId,
embedded: true,
local,
hostId: host.id,
label: host.label || host.hostname,
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'light',
themeTokens: currentBrowserThemeTokens(),
connectionOptions: result.connectionOptions,
});
})();
pendingOpens.set(options.browserId, opening);
void opening.finally(() => {
if (pendingOpens.get(options.browserId) === opening) pendingOpens.delete(options.browserId);
}).catch(() => {});
return opening;
}
+23
View File
@@ -0,0 +1,23 @@
import type { BrowserBookmark } from '../domain/browserBookmark';
import { netcattyBridge } from '../infrastructure/services/netcattyBridge';
let cachedBookmarks: BrowserBookmark[] | undefined;
export function getCachedHostBrowserBookmarks(): BrowserBookmark[] | undefined {
return cachedBookmarks?.map((item) => ({ ...item }));
}
export async function collectHostBrowserBookmarks(): Promise<BrowserBookmark[] | undefined> {
const reader = netcattyBridge.get()?.getHostBrowserBookmarks;
if (!reader) return cachedBookmarks;
const items = await reader();
cachedBookmarks = items;
return getCachedHostBrowserBookmarks();
}
export async function applyHostBrowserBookmarks(items: BrowserBookmark[]): Promise<void> {
const writer = netcattyBridge.get()?.applyHostBrowserBookmarks;
if (!writer) return;
await writer(items);
cachedBookmarks = items;
}
@@ -0,0 +1,64 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import en from '../locales/en.ts';
import ru from '../locales/ru.ts';
import es from '../locales/es.ts';
import zhCN from '../locales/zh-CN.ts';
import zhTW from '../locales/zh-TW.ts';
const keys = [
'cloudSync.provider.disconnect',
'cloudSync.provider.disconnect.confirmTitle',
'cloudSync.provider.disconnect.confirmMessage',
'cloudSync.provider.disconnect.confirmAction',
'cloudSync.provider.disconnect.toastTitle',
'cloudSync.provider.disconnect.cloudRemains',
'cloudSync.provider.disconnect.failed',
] as const;
test('disconnect copy exists in every bundled locale', () => {
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
for (const key of keys) {
assert.equal(typeof messages[key], 'string', `${locale} is missing ${key}`);
assert.notEqual(messages[key], '', `${locale} has empty ${key}`);
}
}
});
test('disconnect confirm copy states that saved provider credentials are removed', () => {
// The confirm dialog must explain the data consequence of disconnecting:
// locally saved endpoint + credentials removal, not just "stops syncing".
const expected = [
[en, 'will be removed'],
[es, 'eliminarán'],
[ru, 'будут удалены'],
[zhCN, '删除'],
[zhTW, '刪除'],
] as const;
for (const [messages, fragment] of expected) {
assert.ok(
(messages['cloudSync.provider.disconnect.confirmMessage'] as string).includes(fragment),
`confirmMessage should mention credential removal: ${fragment}`,
);
}
});
test('disconnect toast copy explains the cloud copy is retained', () => {
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
assert.ok(
(messages['cloudSync.provider.disconnect.cloudRemains'] as string).includes(
'{name}',
),
`${locale} cloudRemains hint should reference the provider name`,
);
}
});
test('disconnect copy distinguishes login cleanup from retained local data', () => {
assert.match(en['cloudSync.provider.disconnect.confirmMessage'], /backup history and sync encryption password stay here/);
assert.doesNotMatch(en['cloudSync.provider.disconnect.cloudRemains'], /change.*password/);
for (const messages of [en, ru, es, zhCN, zhTW]) {
assert.ok(messages['cloudSync.provider.disconnect.failed'].includes('{name}'));
}
});
@@ -11,10 +11,16 @@ const strategyKeys = [
"cloudSync.strategy.desc",
"cloudSync.strategy.smartMerge",
"cloudSync.strategy.smartMergeDesc",
"cloudSync.strategy.smartMergePreserve",
"cloudSync.strategy.smartMergePreserveDesc",
"cloudSync.strategy.preferCloud",
"cloudSync.strategy.preferCloudDesc",
"cloudSync.strategy.preferLocal",
"cloudSync.strategy.preferLocalDesc",
"cloudSync.aiSessions.title",
"cloudSync.aiSessions.desc",
"cloudSync.aiSessions.compatibility",
"cloudSync.aiSessions.enableFailed",
] as const;
test("cloud sync strategy copy exists in every bundled locale", () => {
+2
View File
@@ -1,3 +1,4 @@
import { enMonitorMessages } from './en/monitor';
import type { Messages } from './types';
import { enCoreMessages } from './en/core';
import { enVaultMessages } from './en/vault';
@@ -9,6 +10,7 @@ import { enScriptsMessages } from './en/scripts';
export type { Messages } from './types';
const en: Messages = {
...enMonitorMessages,
...enCoreMessages,
...enVaultMessages,
...enTerminalMessages,
+5
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const enAiMessages: Messages = {
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
// AI Settings
'ai.agentSettings': 'Agent Settings',
'ai.chat.preparing': 'Preparing…',
@@ -513,6 +514,10 @@ export const enAiMessages: Messages = {
'ai.chat.pinModel': 'Pin model',
'ai.chat.unpinModel': 'Unpin model',
'ai.chat.loadingModels': 'Loading models...',
'ai.chat.modelCatalogSourceLive': 'Live catalog',
'ai.chat.modelCatalogSourceCached': 'Cached · last success {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'Cached',
'ai.chat.modelCatalogSourcePresets': 'Built-in default list',
'ai.chat.noMatchingModels': 'No matching models',
'ai.chat.recent': 'Recent',
'ai.chat.viewAll': 'View All',
+8
View File
@@ -767,6 +767,11 @@ Highlight the focused split pane:
'settings.terminal.behavior.smoothScrolling': 'Smooth scrolling',
'settings.terminal.behavior.smoothScrolling.desc':
'Animate terminal viewport scrolling instead of jumping instantly',
'settings.terminal.sidePanel.pane.browser': 'Browser',
'settings.terminal.behavior.linkBrowser': 'Open terminal links in',
'settings.terminal.behavior.linkBrowser.desc': 'SSH links use the connected host; local terminal links use this computer.',
'settings.terminal.behavior.linkBrowser.netcatty': 'Netcatty browser (default)',
'settings.terminal.behavior.linkBrowser.system': 'System default browser',
'settings.terminal.behavior.linkModifier': 'Link modifier key',
'settings.terminal.behavior.linkModifier.desc': 'Hold this key to click on links in terminal',
'settings.terminal.behavior.linkModifier.none': 'None (click directly)',
@@ -1149,6 +1154,9 @@ Highlight the focused split pane:
'vault.hosts.deleteMultiple.success': 'Deleted {count} hosts',
'vault.hosts.connectSelected': 'Connect ({count})',
'vault.hosts.connectMultiple.success': 'Connecting {count} hosts',
'vault.hosts.moveSelected': 'Move to group ({count})',
'vault.hosts.moveSelected.description': 'Move the selected hosts to an existing group, or leave them ungrouped. Selected groups are not moved.',
'vault.hosts.moveMultiple.success': 'Moved {count} hosts to {group}',
'vault.hosts.moveToGroup.success': 'Moved {host} to {group}',
'vault.hosts.errors.nameRequired': 'Host name is required.',
'vault.hosts.empty.title': 'Set up your hosts',
+95
View File
@@ -0,0 +1,95 @@
export const enMonitorMessages = {
"monitor.actions": "Panel actions",
"monitor.unavailable": "Monitoring is unavailable. Try starting again when the connection is restored.",
"monitor.username": "Username",
"monitor.password": "Password (this run only)",
"monitor.status.limit":
"Monitoring is limited to 256 unique hosts at a time.",
"sync.entityType.monitorPanels": "monitor panels",
"monitor.title": "Monitoring",
"monitor.create": "New panel",
"monitor.createFirst": "Create your first panel",
"monitor.empty": "Your hosts, at a glance",
"monitor.emptyHint":
"Choose saved hosts from any group. Start monitoring when you are ready.",
"monitor.choosePanel": "Choose a panel",
"monitor.edit": "Edit panel",
"monitor.copy": "Duplicate panel",
"monitor.copyName": "{name} copy",
"monitor.delete": "Delete panel",
"monitor.deleteHint":
"Delete “{name}”? Its monitoring will stop. Saved hosts and other panels are kept.",
"monitor.start": "Start monitoring",
"monitor.stop": "Stop",
"monitor.stopAll": "Stop all",
"monitor.list": "List",
"monitor.charts": "Charts",
"monitor.search": "Search name, address or group",
"monitor.interval": "Update interval",
"monitor.range": "Trend range",
"monitor.seconds": "Every {count}s",
"monitor.minutes": "Last {count} min",
"monitor.sort": "Sort hosts",
"monitor.sort.manual": "Saved order",
"monitor.sort.name": "Name",
"monitor.selectedCount": "Selected hosts: {count}",
"monitor.noMatches": "No matching hosts",
"monitor.host": "Host",
"monitor.hosts": "Hosts",
"monitor.status": "Status",
"monitor.cpu": "CPU",
"monitor.cores": "Cores: {count}",
"monitor.memory": "Memory",
"monitor.diskCapacity": "{used} used / {total} total",
"monitor.diskCapacityUnknown": "Capacity unavailable",
"monitor.rootDisk": "Root partition",
"monitor.network": "Network",
"monitor.download": "Download",
"monitor.upload": "Upload",
"monitor.updated": "Updated",
"monitor.updatedAt": "Updated {time}",
"monitor.noSamples": "Waiting for the first reading",
"monitor.cpuTrend": "CPU trend",
"monitor.memoryTrend": "Memory trend",
"monitor.downloadTrend": "Download trend",
"monitor.uploadTrend": "Upload trend",
"monitor.memoryOnlyHint":
"Readings stay in memory for up to 30 minutes and disappear when the app closes. Gaps mean no reading. Shared connections use the fastest active update interval.",
"monitor.name": "Panel name",
"monitor.description": "Description (optional)",
"monitor.chooseHosts": "Choose hosts",
"monitor.selectionHint":
"Choose across groups. Unsupported connections are shown with a clear status when started.",
"monitor.defaultView": "Default view",
"monitor.saveHint":
"Saving keeps configuration only and does not connect. Copies start stopped too.",
"monitor.nameRequired": "Enter a panel name.",
"monitor.hostRequired": "Select at least one host.",
"monitor.duplicateName": "A panel already uses this name.",
"monitor.saveFailed": "Could not save the panel. Please try again.",
"monitor.deleted":
"This panel was deleted in another window. Close the editor and create a new panel.",
"monitor.moveUp": "Move host up",
"monitor.removeHost": "Remove from panel",
"monitor.missingHost": "Deleted host",
"monitor.observed": "Observed for {count} min this run",
"monitor.disks": "Partitions",
"monitor.system": "System information",
"monitor.loginHint":
"Check the host credentials or connection settings, then retry. Identity and sign-in prompts are handled one host at a time.",
"monitor.retry": "Retry connection",
"monitor.unsupportedHint":
"Monitoring needs Linux or macOS over SSH with support for additional command channels.",
"monitor.openTerminal": "Open terminal",
"monitor.confirmHost": "Confirm host identity",
"monitor.status.stopped": "Not started",
"monitor.status.queued": "Queued",
"monitor.status.connecting": "Connecting",
"monitor.status.live": "Up to date",
"monitor.status.login": "Sign-in needed",
"monitor.status.error": "Collection failed",
"monitor.status.unsupported": "Unavailable",
"monitor.status.disconnected": "Disconnected",
"monitor.status.stale": "Out of date",
"monitor.status.missing": "Host deleted",
};
+18 -1
View File
@@ -20,6 +20,9 @@ export const enTerminalMessages: Messages = {
'terminal.networkDevice.tip.enabled': 'Network Device Mode enabled for {host}',
// Terminal toolbar / search / context menu / auth
'terminal.toolbar.openSftp': 'Open SFTP',
'terminal.browser.title': 'Browser',
'terminal.browser.sshOnly': 'Focus an SSH terminal to open its browser.',
'terminal.browser.open': 'Open Browser',
'terminal.toolbar.availableAfterConnect': 'Available after connect',
'terminal.toolbar.sendYmodem': 'Send with YMODEM',
'terminal.toolbar.receiveYmodem': 'Receive with YMODEM',
@@ -44,6 +47,10 @@ export const enTerminalMessages: Messages = {
'history.action.run': 'Run in terminal',
'history.action.saveAsSnippet': 'Save as snippet',
'history.action.delete': 'Delete from history',
'history.action.clearAll': 'Clear all history',
'history.clearAll.dialog.title': 'Clear all command history?',
'history.clearAll.dialog.desc': 'This permanently deletes all locally recorded command history and autocomplete suggestions. This cannot be undone.',
'history.clearAll.dialog.confirm': 'Clear all',
'terminal.toolbar.library': 'Library',
'terminal.toolbar.noSnippets': 'No snippets available',
'terminal.toolbar.terminalSettings': 'Terminal settings',
@@ -310,8 +317,11 @@ export const enTerminalMessages: Messages = {
'cloudSync.provider.connecting': 'Connecting...',
'cloudSync.provider.disconnect': 'Disconnect',
'cloudSync.provider.disconnect.confirmTitle': 'Disconnect "{name}"?',
'cloudSync.provider.disconnect.confirmMessage': 'This device will stop syncing with {name}. Your local vault stays on this computer.',
'cloudSync.provider.disconnect.confirmMessage': 'This device will stop syncing with {name}. Its saved address and login credentials will be removed. Your local vault, backup history and sync encryption password stay here. If system credential storage is unavailable, plugin credentials may need manual removal.',
'cloudSync.provider.disconnect.confirmAction': 'Disconnect',
'cloudSync.provider.disconnect.toastTitle': 'Disconnected',
'cloudSync.provider.disconnect.cloudRemains': 'Encrypted sync copies may still exist in your {name} storage. To remove them, delete the sync files there. Disconnecting does not clear this device for handover.',
'cloudSync.provider.disconnect.failed': 'Could not finish disconnecting from {name}. Saved connection details may remain. Please try again.',
'cloudSync.provider.webdav': 'WebDAV',
'cloudSync.provider.webdav.desc': 'Connect to a self-hosted WebDAV endpoint',
'cloudSync.provider.s3': 'S3 Compatible',
@@ -381,6 +391,12 @@ export const enTerminalMessages: Messages = {
'cloudSync.strategy.title': 'Sync strategy',
'cloudSync.strategy.desc': 'Choose what happens when local and cloud data both changed.',
'cloudSync.strategy.smartMerge': 'Smart merge (recommended)',
'cloudSync.aiSessions.title': 'Sync AI chat history',
'cloudSync.aiSessions.desc': 'Include AI chat sessions in cloud sync. Messages merge append-only across devices; attachment contents stay on this device.',
'cloudSync.aiSessions.compatibility': 'Older versions may overwrite chat history. Use an updated Netcatty on every synced device.',
'cloudSync.aiSessions.enableFailed': 'Could not update chat sync. Check the cloud connection and available local storage, then try again.',
'cloudSync.strategy.smartMergePreserve': 'Smart merge (never delete)',
'cloudSync.strategy.smartMergePreserveDesc': 'Combine changes from both sides and never propagate a one-sided deletion — an entry survives until it is removed on every device. Recommended when you restore backups or keep several machines in sync.',
'cloudSync.strategy.smartMergeDesc': 'Combine changes from both sides when possible; if Netcatty cannot decide safely, ask you to choose.',
'cloudSync.strategy.preferCloud': 'Cloud wins',
'cloudSync.strategy.preferCloudDesc': 'When both sides changed, download the cloud version and replace local changes.',
@@ -518,6 +534,7 @@ export const enTerminalMessages: Messages = {
'cloudSync.conflict.entity.customGroups': 'Groups',
'cloudSync.conflict.entity.snippetPackages': 'Snippet packages',
'cloudSync.conflict.entity.portForwardingRules': 'Port forwarding',
'cloudSync.conflict.entity.browserBookmarks': 'Browser bookmarks',
'cloudSync.conflict.entity.groupConfigs': 'Group settings',
'cloudSync.conflict.entity.settings': 'Settings',
'cloudSync.conflict.keepLocal': 'Overwrite cloud (keep local)',
+2
View File
@@ -1,3 +1,4 @@
import { esMonitorMessages } from './es/monitor';
import type { Messages } from './types';
import { esCoreMessages } from './es/core';
import { esVaultMessages } from './es/vault';
@@ -9,6 +10,7 @@ import { esScriptsMessages } from './es/scripts';
export type { Messages } from './types';
const es: Messages = {
...esMonitorMessages,
...esCoreMessages,
...esVaultMessages,
...esTerminalMessages,
+5
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const esAiMessages: Messages = {
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
// AI Settings
'ai.agentSettings': 'Configuración del agente',
'ai.chat.preparing': 'Preparando…',
@@ -504,6 +505,10 @@ export const esAiMessages: Messages = {
'ai.chat.pinModel': 'Fijar modelo',
'ai.chat.unpinModel': 'Quitar modelo fijado',
'ai.chat.loadingModels': 'Cargando modelos...',
'ai.chat.modelCatalogSourceLive': 'Catálogo en vivo',
'ai.chat.modelCatalogSourceCached': 'En caché · último éxito {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'En caché',
'ai.chat.modelCatalogSourcePresets': 'Lista predeterminada integrada',
'ai.chat.noMatchingModels': 'No hay modelos coincidentes',
'ai.chat.recent': 'Recientes',
'ai.chat.viewAll': 'Ver todo',
+9
View File
@@ -682,6 +682,11 @@ Resalta el panel dividido enfocado:
'settings.terminal.behavior.smoothScrolling': 'Desplazamiento suave',
'settings.terminal.behavior.smoothScrolling.desc':
'Anima el desplazamiento de la vista de la terminal en lugar de saltar instantáneamente',
'settings.terminal.sidePanel.pane.browser': 'Navegador',
'settings.terminal.behavior.linkBrowser': 'Abrir enlaces de terminal en',
'settings.terminal.behavior.linkBrowser.desc': 'Los enlaces SSH usan el host conectado; los enlaces locales usan este equipo.',
'settings.terminal.behavior.linkBrowser.netcatty': 'Navegador Netcatty (predeterminado)',
'settings.terminal.behavior.linkBrowser.system': 'Navegador del sistema',
'settings.terminal.behavior.linkModifier': 'Tecla modificadora de enlaces',
'settings.terminal.behavior.linkModifier.desc': 'Mantén presionada esta tecla para hacer clic en enlaces de la terminal',
'settings.terminal.behavior.linkModifier.none': 'Ninguna (clic directo)',
@@ -883,6 +888,7 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.binding.new-workspace': 'Nuevo 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',
'settings.shortcuts.binding.toggle-side-panel': 'Alternar panel lateral',
'settings.shortcuts.binding.sftp-copy': 'Copiar archivos',
'settings.shortcuts.binding.sftp-cut': 'Cortar archivos',
@@ -1107,6 +1113,9 @@ Resalta el panel dividido enfocado:
'vault.hosts.deleteMultiple.success': 'Se eliminaron {count} hosts',
'vault.hosts.connectSelected': 'Conectar ({count})',
'vault.hosts.connectMultiple.success': 'Conectando {count} hosts',
'vault.hosts.moveSelected': 'Mover al grupo ({count})',
'vault.hosts.moveSelected.description': 'Mueve los hosts seleccionados a un grupo existente o los deja sin grupo. Los grupos seleccionados no se mueven.',
'vault.hosts.moveMultiple.success': 'Se movieron {count} hosts a {group}',
'vault.hosts.moveToGroup.success': 'Se movió {host} a {group}',
'vault.hosts.errors.nameRequired': 'Se requiere el nombre del host.',
'vault.hosts.empty.title': 'Configura tus hosts',
+95
View File
@@ -0,0 +1,95 @@
export const esMonitorMessages = {
"monitor.actions": "Acciones del panel",
"monitor.unavailable": "La monitorización no está disponible. Iníciala de nuevo cuando se restablezca la conexión.",
"monitor.username": "Usuario",
"monitor.password": "Contraseña (solo esta ejecución)",
"monitor.status.limit":
"Se pueden monitorizar hasta 256 equipos únicos a la vez.",
"sync.entityType.monitorPanels": "paneles de monitorización",
"monitor.title": "Monitorización",
"monitor.create": "Nuevo panel",
"monitor.createFirst": "Crear el primer panel",
"monitor.empty": "Tus equipos de un vistazo",
"monitor.emptyHint":
"Elige equipos guardados de cualquier grupo e inicia cuando quieras.",
"monitor.choosePanel": "Elegir panel",
"monitor.edit": "Editar panel",
"monitor.copy": "Duplicar panel",
"monitor.copyName": "Copia de {name}",
"monitor.delete": "Eliminar panel",
"monitor.deleteHint":
"¿Eliminar «{name}»? Se detendrá su monitorización. Se conservarán los equipos y otros paneles.",
"monitor.start": "Iniciar monitorización",
"monitor.stop": "Detener",
"monitor.stopAll": "Detener todo",
"monitor.list": "Lista",
"monitor.charts": "Gráficos",
"monitor.search": "Buscar nombre, dirección o grupo",
"monitor.interval": "Intervalo de actualización",
"monitor.range": "Rango de tendencias",
"monitor.seconds": "Cada {count} s",
"monitor.minutes": "Últimos {count} min",
"monitor.sort": "Ordenar equipos",
"monitor.sort.manual": "Orden guardado",
"monitor.sort.name": "Nombre",
"monitor.selectedCount": "Equipos seleccionados: {count}",
"monitor.noMatches": "No hay equipos coincidentes",
"monitor.host": "Equipo",
"monitor.hosts": "Equipos",
"monitor.status": "Estado",
"monitor.cpu": "CPU",
"monitor.cores": "Núcleos: {count}",
"monitor.memory": "Memoria",
"monitor.diskCapacity": "{used} usados / {total} en total",
"monitor.diskCapacityUnknown": "Capacidad no disponible",
"monitor.rootDisk": "Partición raíz",
"monitor.network": "Red",
"monitor.download": "Descarga",
"monitor.upload": "Subida",
"monitor.updated": "Actualizado",
"monitor.updatedAt": "Actualizado: {time}",
"monitor.noSamples": "Esperando la primera lectura",
"monitor.cpuTrend": "Tendencia de CPU",
"monitor.memoryTrend": "Tendencia de memoria",
"monitor.downloadTrend": "Tendencia de descarga",
"monitor.uploadTrend": "Tendencia de subida",
"monitor.memoryOnlyHint":
"Las lecturas se conservan en memoria hasta 30 minutos y desaparecen al cerrar. Los huecos indican datos ausentes. Las conexiones compartidas usan el intervalo activo más rápido.",
"monitor.name": "Nombre del panel",
"monitor.description": "Descripción (opcional)",
"monitor.chooseHosts": "Elegir equipos",
"monitor.selectionHint":
"Selecciona entre grupos. Las conexiones no compatibles se indicarán al iniciar.",
"monitor.defaultView": "Vista predeterminada",
"monitor.saveHint":
"Guardar conserva la configuración sin conectar. Las copias también empiezan detenidas.",
"monitor.nameRequired": "Escribe un nombre para el panel.",
"monitor.hostRequired": "Selecciona al menos un equipo.",
"monitor.duplicateName": "Ya existe un panel con ese nombre.",
"monitor.saveFailed": "No se pudo guardar el panel. Inténtalo de nuevo.",
"monitor.deleted":
"El panel se eliminó en otra ventana. Cierra el editor y crea uno nuevo.",
"monitor.moveUp": "Subir equipo",
"monitor.removeHost": "Quitar del panel",
"monitor.missingHost": "Equipo eliminado",
"monitor.observed": "Observado durante {count} min",
"monitor.disks": "Particiones",
"monitor.system": "Información del sistema",
"monitor.loginHint":
"Comprueba las credenciales o la conexión y reintenta. Las solicitudes se procesan equipo por equipo.",
"monitor.retry": "Reintentar conexión",
"monitor.unsupportedHint":
"Se necesita Linux o macOS por SSH con canales de comandos adicionales.",
"monitor.openTerminal": "Abrir terminal",
"monitor.confirmHost": "Confirmar identidad",
"monitor.status.stopped": "Sin iniciar",
"monitor.status.queued": "En cola",
"monitor.status.connecting": "Conectando",
"monitor.status.live": "Actualizado",
"monitor.status.login": "Requiere acceso",
"monitor.status.error": "Error de lectura",
"monitor.status.unsupported": "No disponible",
"monitor.status.disconnected": "Desconectado",
"monitor.status.stale": "Sin actualizar",
"monitor.status.missing": "Equipo eliminado",
};
+18 -1
View File
@@ -20,6 +20,9 @@ export const esTerminalMessages: Messages = {
'terminal.networkDevice.tip.enabled': 'Modo de Dispositivo de Red activado para {host}',
// Terminal toolbar / search / context menu / auth
'terminal.toolbar.openSftp': 'Abrir SFTP',
'terminal.browser.title': 'Navegador',
'terminal.browser.sshOnly': 'Selecciona una terminal SSH para abrir su navegador.',
'terminal.browser.open': 'Abrir navegador',
'terminal.toolbar.availableAfterConnect': 'Disponible después de conectar',
'terminal.toolbar.sendYmodem': 'Enviar con YMODEM',
'terminal.toolbar.receiveYmodem': 'Recibir con YMODEM',
@@ -44,6 +47,10 @@ export const esTerminalMessages: Messages = {
'history.action.run': 'Ejecutar en la terminal',
'history.action.saveAsSnippet': 'Guardar como snippet',
'history.action.delete': 'Eliminar del historial',
'history.action.clearAll': 'Borrar todo el historial',
'history.clearAll.dialog.title': '¿Borrar todo el historial de comandos?',
'history.clearAll.dialog.desc': 'Esto elimina de forma permanente todo el historial de comandos local y las sugerencias de autocompletado. Esta acción no se puede deshacer.',
'history.clearAll.dialog.confirm': 'Borrar todo',
'terminal.toolbar.library': 'Biblioteca',
'terminal.toolbar.noSnippets': 'No hay snippets disponibles',
'terminal.toolbar.terminalSettings': 'Configuración de la terminal',
@@ -309,8 +316,11 @@ export const esTerminalMessages: Messages = {
'cloudSync.provider.connecting': 'Conectando...',
'cloudSync.provider.disconnect': 'Desconectar',
'cloudSync.provider.disconnect.confirmTitle': '¿Desconectar "{name}"?',
'cloudSync.provider.disconnect.confirmMessage': 'Este dispositivo dejará de sincronizar con {name}. La bóveda local permanecerá en este equipo.',
'cloudSync.provider.disconnect.confirmMessage': 'Este dispositivo dejará de sincronizar con {name}. Se eliminarán su dirección y credenciales de acceso guardadas. La bóveda local, las copias de seguridad y la contraseña de cifrado de sincronización permanecerán aquí. Si el almacén de credenciales del sistema no está disponible, puede ser necesario eliminar manualmente las credenciales de los complementos.',
'cloudSync.provider.disconnect.confirmAction': 'Desconectar',
'cloudSync.provider.disconnect.toastTitle': 'Desconectado',
'cloudSync.provider.disconnect.cloudRemains': 'Las copias de sincronización cifradas pueden seguir en tu almacenamiento de {name}. Para eliminarlas, borra los archivos de sincronización allí. Desconectar no prepara este dispositivo para entregarlo a otra persona.',
'cloudSync.provider.disconnect.failed': 'No se pudo completar la desconexión de {name}. Los datos de conexión guardados podrían permanecer. Inténtalo de nuevo.',
'cloudSync.provider.webdav': 'WebDAV',
'cloudSync.provider.webdav.desc': 'Conectar a un endpoint WebDAV autoalojado',
'cloudSync.provider.s3': 'Compatible con S3',
@@ -380,6 +390,12 @@ export const esTerminalMessages: Messages = {
'cloudSync.strategy.title': 'Estrategia de sincronización',
'cloudSync.strategy.desc': 'Elige qué sucede cuando cambian tanto los datos locales como los de la nube.',
'cloudSync.strategy.smartMerge': 'Fusión inteligente (recomendada)',
'cloudSync.aiSessions.title': 'Sincronizar el historial de chats de IA',
'cloudSync.aiSessions.desc': 'Incluye las sesiones de chat de IA en la sincronización en la nube. Los mensajes se combinan de forma incremental entre dispositivos; el contenido de los adjuntos permanece en este dispositivo.',
'cloudSync.aiSessions.compatibility': 'Las versiones antiguas pueden sobrescribir el historial. Actualiza Netcatty en todos los dispositivos sincronizados.',
'cloudSync.aiSessions.enableFailed': 'No se pudo actualizar la sincronización del chat. Comprueba la conexión con la nube y el espacio local disponible e inténtalo de nuevo.',
'cloudSync.strategy.smartMergePreserve': 'Fusión inteligente (sin borrar)',
'cloudSync.strategy.smartMergePreserveDesc': 'Combina los cambios de ambos lados y nunca propaga un borrado de un solo lado: una entrada se conserva hasta que se elimina en todos los dispositivos. Recomendado al restaurar copias de seguridad o al usar varios equipos.',
'cloudSync.strategy.smartMergeDesc': 'Combina los cambios de ambos lados cuando sea posible; si Netcatty no puede decidir con seguridad, te pedirá que elijas.',
'cloudSync.strategy.preferCloud': 'Gana la nube',
'cloudSync.strategy.preferCloudDesc': 'Cuando ambos lados cambiaron, descarga la versión de la nube y reemplaza los cambios locales.',
@@ -517,6 +533,7 @@ export const esTerminalMessages: Messages = {
'cloudSync.conflict.entity.customGroups': 'Grupos',
'cloudSync.conflict.entity.snippetPackages': 'Paquetes de snippets',
'cloudSync.conflict.entity.portForwardingRules': 'Reenvío de puertos',
'cloudSync.conflict.entity.browserBookmarks': 'Marcadores del navegador',
'cloudSync.conflict.entity.groupConfigs': 'Configuración de grupos',
'cloudSync.conflict.entity.settings': 'Configuración',
'cloudSync.conflict.keepLocal': 'Sobrescribir la nube (conservar local)',
@@ -0,0 +1,40 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { enMonitorMessages } from "./en/monitor";
import { esMonitorMessages } from "./es/monitor";
import { ruMonitorMessages } from "./ru/monitor";
import { zhCNMonitorMessages } from "./zh-CN/monitor";
import { zhTWMonitorMessages } from "./zh-TW/monitor";
test("monitoring UI literal message keys exist, including editor-only controls", () => {
for (const name of ["MonitorPanels", "MonitorNavButton", "MonitorDiskUsage"]) {
const source = readFileSync(new URL(`../../../components/vault/${name}.tsx`, import.meta.url), "utf8");
const keys = [...source.matchAll(/\bt\("(monitor\.[^"]+)"/g)].map((match) => match[1]);
for (const key of keys)
assert.ok(Object.hasOwn(enMonitorMessages, key), `${name}: ${key}`);
}
});
for (const [locale, messages] of Object.entries({
es: esMonitorMessages,
ru: ruMonitorMessages,
"zh-CN": zhCNMonitorMessages,
"zh-TW": zhTWMonitorMessages,
})) {
test(`monitoring has translated actions, states and matching placeholders in ${locale}`, () => {
assert.deepEqual(
Object.keys(messages).sort(),
Object.keys(enMonitorMessages).sort(),
);
for (const key of Object.keys(enMonitorMessages)) {
const english = enMonitorMessages[key as keyof typeof enMonitorMessages];
const translated = messages[key as keyof typeof messages];
assert.ok(translated.trim(), key);
assert.deepEqual(
(translated.match(/\{\w+\}/g) ?? []).sort(),
(english.match(/\{\w+\}/g) ?? []).sort(),
key,
);
}
});
}
+2
View File
@@ -1,3 +1,4 @@
import { ruMonitorMessages } from './ru/monitor';
import type { Messages } from './types';
import { ruCoreMessages } from './ru/core';
import { ruVaultMessages } from './ru/vault';
@@ -9,6 +10,7 @@ import { ruScriptsMessages } from './ru/scripts';
export type { Messages } from './types';
const ru: Messages = {
...ruMonitorMessages,
...ruCoreMessages,
...ruVaultMessages,
...ruTerminalMessages,
+5
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const ruAiMessages: Messages = {
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
// AI Settings
'ai.agentSettings': 'Настройки агента',
@@ -460,6 +461,10 @@ export const ruAiMessages: Messages = {
'ai.chat.pinModel': 'Закрепить модель',
'ai.chat.unpinModel': 'Открепить модель',
'ai.chat.loadingModels': 'Загрузка моделей...',
'ai.chat.modelCatalogSourceLive': 'Актуальный список моделей',
'ai.chat.modelCatalogSourceCached': 'Кэш · обновлён {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'Кэш',
'ai.chat.modelCatalogSourcePresets': 'Встроенный список моделей',
'ai.chat.noMatchingModels': 'Нет подходящих моделей',
'ai.chat.recent': 'Недавние',
'ai.chat.viewAll': 'Показать всё',
+6
View File
@@ -718,6 +718,11 @@ export const ruCoreMessages: Messages = {
'settings.terminal.behavior.smoothScrolling': 'Плавная прокрутка',
'settings.terminal.behavior.smoothScrolling.desc':
'Анимировать прокрутку области терминала вместо мгновенного перехода',
'settings.terminal.sidePanel.pane.browser': 'Браузер',
'settings.terminal.behavior.linkBrowser': 'Открывать ссылки терминала в',
'settings.terminal.behavior.linkBrowser.desc': 'SSH-ссылки используют подключённый хост; локальные ссылки — этот компьютер.',
'settings.terminal.behavior.linkBrowser.netcatty': 'Браузер Netcatty (по умолчанию)',
'settings.terminal.behavior.linkBrowser.system': 'Системный браузер',
'settings.terminal.behavior.linkModifier': 'Клавиша-модификатор для ссылок',
'settings.terminal.behavior.linkModifier.desc': 'Удерживайте эту клавишу, чтобы нажимать на ссылки в терминале',
'settings.terminal.behavior.linkModifier.none': 'Нет (нажимать напрямую)',
@@ -908,6 +913,7 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
'settings.shortcuts.binding.toggle-side-panel': 'Переключить боковую панель',
'settings.shortcuts.binding.sftp-copy': 'Копировать файл',
'settings.shortcuts.binding.sftp-cut': 'Вырезать файл',
+94
View File
@@ -0,0 +1,94 @@
export const ruMonitorMessages = {
"monitor.actions": "Действия панели",
"monitor.unavailable": "Мониторинг недоступен. Запустите его снова после восстановления связи.",
"monitor.username": "Пользователь",
"monitor.password": "Пароль (только для этого запуска)",
"monitor.status.limit": "Одновременно можно наблюдать не более 256 серверов.",
"sync.entityType.monitorPanels": "панели мониторинга",
"monitor.title": "Мониторинг",
"monitor.create": "Новая панель",
"monitor.createFirst": "Создать первую панель",
"monitor.empty": "Все серверы перед глазами",
"monitor.emptyHint":
"Выберите сохранённые серверы из любых групп и запустите мониторинг.",
"monitor.choosePanel": "Выбрать панель",
"monitor.edit": "Изменить панель",
"monitor.copy": "Дублировать панель",
"monitor.copyName": "Копия {name}",
"monitor.delete": "Удалить панель",
"monitor.deleteHint":
"Удалить «{name}»? Мониторинг этой панели остановится. Серверы и другие панели сохранятся.",
"monitor.start": "Начать мониторинг",
"monitor.stop": "Остановить",
"monitor.stopAll": "Остановить всё",
"monitor.list": "Список",
"monitor.charts": "Графики",
"monitor.search": "Имя, адрес или группа",
"monitor.interval": "Интервал обновления",
"monitor.range": "Период графика",
"monitor.seconds": "Каждые {count} с",
"monitor.minutes": "Последние {count} мин",
"monitor.sort": "Сортировка серверов",
"monitor.sort.manual": "Сохранённый порядок",
"monitor.sort.name": "Имя",
"monitor.selectedCount": "Выбрано серверов: {count}",
"monitor.noMatches": "Нет подходящих серверов",
"monitor.host": "Сервер",
"monitor.hosts": "Серверы",
"monitor.status": "Состояние",
"monitor.cpu": "ЦП",
"monitor.cores": "Ядер: {count}",
"monitor.memory": "Память",
"monitor.diskCapacity": "Использовано {used} / всего {total}",
"monitor.diskCapacityUnknown": "Данные об объёме недоступны",
"monitor.rootDisk": "Корневой раздел",
"monitor.network": "Сеть",
"monitor.download": "Загрузка",
"monitor.upload": "Отправка",
"monitor.updated": "Обновлено",
"monitor.updatedAt": "Обновлено: {time}",
"monitor.noSamples": "Ожидание первого измерения",
"monitor.cpuTrend": "График ЦП",
"monitor.memoryTrend": "График памяти",
"monitor.downloadTrend": "График приёма",
"monitor.uploadTrend": "График передачи",
"monitor.memoryOnlyHint":
"Измерения хранятся в памяти до 30 минут и удаляются при выходе. Пробелы означают отсутствие данных. Общие соединения используют наименьший активный интервал.",
"monitor.name": "Название панели",
"monitor.description": "Описание (необязательно)",
"monitor.chooseHosts": "Выбрать серверы",
"monitor.selectionHint":
"Можно выбирать из разных групп. Неподдерживаемые подключения будут отмечены при запуске.",
"monitor.defaultView": "Вид по умолчанию",
"monitor.saveHint":
"Сохранение не подключает серверы. Копии также создаются остановленными.",
"monitor.nameRequired": "Введите название панели.",
"monitor.hostRequired": "Выберите хотя бы один сервер.",
"monitor.duplicateName": "Панель с таким названием уже существует.",
"monitor.saveFailed": "Не удалось сохранить панель. Повторите попытку.",
"monitor.deleted":
"Панель удалена в другом окне. Закройте редактор и создайте новую.",
"monitor.moveUp": "Переместить выше",
"monitor.removeHost": "Убрать из панели",
"monitor.missingHost": "Удалённый сервер",
"monitor.observed": "Наблюдение: {count} мин",
"monitor.disks": "Разделы дисков",
"monitor.system": "Информация о системе",
"monitor.loginHint":
"Проверьте данные входа и настройки подключения. Подтверждения обрабатываются по одному серверу.",
"monitor.retry": "Повторить подключение",
"monitor.unsupportedHint":
"Для мониторинга нужен Linux или macOS по SSH с дополнительными каналами команд.",
"monitor.openTerminal": "Открыть терминал",
"monitor.confirmHost": "Подтвердить сервер",
"monitor.status.stopped": "Не запущено",
"monitor.status.queued": "В очереди",
"monitor.status.connecting": "Подключение",
"monitor.status.live": "Актуально",
"monitor.status.login": "Нужен вход",
"monitor.status.error": "Ошибка сбора",
"monitor.status.unsupported": "Недоступно",
"monitor.status.disconnected": "Отключено",
"monitor.status.stale": "Устарело",
"monitor.status.missing": "Сервер удалён",
};
+18 -1
View File
@@ -41,6 +41,9 @@ export const ruTerminalMessages: Messages = {
// Terminal toolbar / search / context menu / auth
'terminal.toolbar.openSftp': 'Открыть SFTP',
'terminal.browser.title': 'Браузер',
'terminal.browser.sshOnly': 'Выберите SSH-терминал, чтобы открыть его браузер.',
'terminal.browser.open': 'Открыть браузер',
'terminal.toolbar.availableAfterConnect': 'Доступно после подключения',
'terminal.toolbar.sendYmodem': 'Отправить через YMODEM',
'terminal.toolbar.receiveYmodem': 'Получить через YMODEM',
@@ -65,6 +68,10 @@ export const ruTerminalMessages: Messages = {
'history.action.run': 'Выполнить в терминале',
'history.action.saveAsSnippet': 'Сохранить как сниппет',
'history.action.delete': 'Удалить из истории',
'history.action.clearAll': 'Очистить всю историю',
'history.clearAll.dialog.title': 'Очистить всю историю команд?',
'history.clearAll.dialog.desc': 'Будет безвозвратно удалена вся локальная история команд и подсказки автодополнения. Это действие нельзя отменить.',
'history.clearAll.dialog.confirm': 'Очистить всё',
'terminal.toolbar.library': 'Библиотека',
'terminal.toolbar.noSnippets': 'Нет доступных сниппетов',
'terminal.toolbar.terminalSettings': 'Настройки терминала',
@@ -328,8 +335,11 @@ export const ruTerminalMessages: Messages = {
'cloudSync.provider.connecting': 'Подключение...',
'cloudSync.provider.disconnect': 'Отключить',
'cloudSync.provider.disconnect.confirmTitle': 'Отключить "{name}"?',
'cloudSync.provider.disconnect.confirmMessage': 'Это устройство перестанет синхронизироваться с {name}. Локальное хранилище останется на этом компьютере.',
'cloudSync.provider.disconnect.confirmMessage': 'Это устройство перестанет синхронизироваться с {name}. Сохранённый адрес и данные для входа будут удалены. Локальное хранилище, резервные копии и пароль шифрования синхронизации останутся здесь. Если системное хранилище учётных данных недоступно, данные для входа плагинов может потребоваться удалить вручную.',
'cloudSync.provider.disconnect.confirmAction': 'Отключить',
'cloudSync.provider.disconnect.toastTitle': 'Отключено',
'cloudSync.provider.disconnect.cloudRemains': 'Зашифрованные копии синхронизации могут остаться в хранилище {name}. Чтобы удалить их, удалите там файлы синхронизации. Отключение не очищает устройство для передачи другому человеку.',
'cloudSync.provider.disconnect.failed': 'Не удалось завершить отключение от {name}. Сохранённые данные подключения могут остаться. Повторите попытку.',
'cloudSync.provider.webdav': 'WebDAV',
'cloudSync.provider.webdav.desc': 'Подключение к самостоятельно размещённому WebDAV endpoint',
'cloudSync.provider.s3': 'Совместимое с S3',
@@ -399,6 +409,12 @@ export const ruTerminalMessages: Messages = {
'cloudSync.strategy.title': 'Стратегия синхронизации',
'cloudSync.strategy.desc': 'Выберите, что делать, когда изменились и локальные, и облачные данные.',
'cloudSync.strategy.smartMerge': 'Умное объединение (рекомендуется)',
'cloudSync.aiSessions.title': 'Синхронизировать историю ИИ-чатов',
'cloudSync.aiSessions.desc': 'Включать сессии ИИ-чатов в облачную синхронизацию. Сообщения объединяются дополнением между устройствами; содержимое вложений остаётся на этом устройстве.',
'cloudSync.aiSessions.compatibility': 'Старые версии могут перезаписать историю. Обновите Netcatty на всех синхронизируемых устройствах.',
'cloudSync.aiSessions.enableFailed': 'Не удалось изменить синхронизацию чатов. Проверьте подключение к облаку и свободное место на устройстве, затем повторите попытку.',
'cloudSync.strategy.smartMergePreserve': 'Умное слияние (без удалений)',
'cloudSync.strategy.smartMergePreserveDesc': 'Объединяет изменения с обеих сторон и никогда не передаёт удаление с одной стороны: запись сохраняется, пока её не убрали на всех устройствах. Рекомендуется при восстановлении из резервных копий или при работе с несколькими машинами.',
'cloudSync.strategy.smartMergeDesc': 'По возможности объединять изменения с обеих сторон; если Netcatty не сможет безопасно выбрать, он попросит вас решить вручную.',
'cloudSync.strategy.preferCloud': 'Приоритет облака',
'cloudSync.strategy.preferCloudDesc': 'Когда изменились обе стороны, скачать облачную версию и заменить локальные изменения.',
@@ -536,6 +552,7 @@ export const ruTerminalMessages: Messages = {
'cloudSync.conflict.entity.customGroups': 'Группы',
'cloudSync.conflict.entity.snippetPackages': 'Пакеты сниппетов',
'cloudSync.conflict.entity.portForwardingRules': 'Проброс портов',
'cloudSync.conflict.entity.browserBookmarks': 'Закладки браузера',
'cloudSync.conflict.entity.groupConfigs': 'Настройки групп',
'cloudSync.conflict.entity.settings': 'Настройки',
'cloudSync.conflict.keepLocal': 'Перезаписать облако (сохранить локальную)',
+3
View File
@@ -128,6 +128,9 @@ export const ruVaultMessages: Messages = {
'vault.hosts.deleteMultiple.success': 'Удалено хостов: {count}',
'vault.hosts.connectSelected': 'Подключить ({count})',
'vault.hosts.connectMultiple.success': 'Подключение хостов: {count}',
'vault.hosts.moveSelected': 'Переместить в группу ({count})',
'vault.hosts.moveSelected.description': 'Переместить выбранные хосты в существующую группу или оставить без группы. Выбранные группы не перемещаются.',
'vault.hosts.moveMultiple.success': 'Перемещено {count} хостов в {group}',
'vault.hosts.moveToGroup.success': 'Хост {host} перемещён в {group}',
'vault.hosts.empty.title': 'Настройте свои хосты',
'vault.hosts.empty.desc': 'Сохраняйте хосты, чтобы быстро подключаться к серверам, виртуальным машинам и контейнерам.',
+2
View File
@@ -1,3 +1,4 @@
import { zhCNMonitorMessages } from './zh-CN/monitor';
import type { Messages } from './types';
import { zhCNCoreMessages } from './zh-CN/core';
import { zhCNVaultMessages } from './zh-CN/vault';
@@ -9,6 +10,7 @@ import { zhCNScriptsMessages } from './zh-CN/scripts';
export type { Messages } from './types';
const zhCN: Messages = {
...zhCNMonitorMessages,
...zhCNCoreMessages,
...zhCNVaultMessages,
...zhCNTerminalMessages,
+5
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const zhCNAiMessages: Messages = {
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
// AI Settings
'ai.agentSettings': 'Agent 设置',
'ai.chat.preparing': '准备中…',
@@ -513,6 +514,10 @@ export const zhCNAiMessages: Messages = {
'ai.chat.pinModel': '固定模型',
'ai.chat.unpinModel': '取消固定',
'ai.chat.loadingModels': '正在加载模型...',
'ai.chat.modelCatalogSourceLive': '实时目录',
'ai.chat.modelCatalogSourceCached': '缓存 · 上次成功 {time}',
'ai.chat.modelCatalogSourceCachedNoTime': '缓存',
'ai.chat.modelCatalogSourcePresets': '内置默认列表',
'ai.chat.noMatchingModels': '没有匹配的模型',
'ai.chat.recent': '最近',
'ai.chat.viewAll': '查看全部',
+3
View File
@@ -766,6 +766,9 @@ export const zhCNCoreMessages: Messages = {
'vault.hosts.deleteMultiple.success': '已删除 {count} 个主机',
'vault.hosts.connectSelected': '连接 ({count})',
'vault.hosts.connectMultiple.success': '正在连接 {count} 个主机',
'vault.hosts.moveSelected': '移动到分组 ({count})',
'vault.hosts.moveSelected.description': '将选中的主机移动到现有分组,也可移出分组。选中的分组本身不会移动。',
'vault.hosts.moveMultiple.success': '已将 {count} 个主机移动到 {group}',
'vault.hosts.moveToGroup.success': '已将 {host} 移动到 {group}',
'vault.hosts.errors.nameRequired': '主机名称不能为空。',
'vault.hosts.empty.title': '设置你的主机',
+90
View File
@@ -0,0 +1,90 @@
export const zhCNMonitorMessages = {
"monitor.actions": "面板操作",
"monitor.unavailable": "监控暂不可用,连接恢复后请重新开始。",
"monitor.username": "用户名",
"monitor.password": "密码(仅本次使用)",
"monitor.status.limit": "同时最多监控 256 台不同主机。",
"sync.entityType.monitorPanels": "监控面板",
"monitor.title": "监控",
"monitor.create": "新建面板",
"monitor.createFirst": "创建第一个监控面板",
"monitor.empty": "一眼查看多台主机",
"monitor.emptyHint": "跨分组选择已有主机,准备好后再开始监控。",
"monitor.choosePanel": "选择面板",
"monitor.edit": "编辑面板",
"monitor.copy": "复制面板",
"monitor.copyName": "{name} 副本",
"monitor.delete": "删除面板",
"monitor.deleteHint":
"删除“{name}”?该面板将停止监控,已有主机和其他面板会保留。",
"monitor.start": "开始监控",
"monitor.stop": "停止",
"monitor.stopAll": "全部停止",
"monitor.list": "列表",
"monitor.charts": "图表",
"monitor.search": "搜索名称、地址或分组",
"monitor.interval": "更新频率",
"monitor.range": "趋势范围",
"monitor.seconds": "每 {count} 秒",
"monitor.minutes": "最近 {count} 分钟",
"monitor.sort": "主机排序",
"monitor.sort.manual": "保存的顺序",
"monitor.sort.name": "名称",
"monitor.selectedCount": "已选 {count} 台主机",
"monitor.noMatches": "没有符合条件的主机",
"monitor.host": "主机",
"monitor.hosts": "主机",
"monitor.status": "状态",
"monitor.cpu": "CPU",
"monitor.cores": "{count} 核",
"monitor.memory": "内存",
"monitor.diskCapacity": "已用 {used} / 总容量 {total}",
"monitor.diskCapacityUnknown": "暂无容量读数",
"monitor.rootDisk": "根分区",
"monitor.network": "网络",
"monitor.download": "下载",
"monitor.upload": "上传",
"monitor.updated": "更新时间",
"monitor.updatedAt": "更新于 {time}",
"monitor.noSamples": "等待第一次读数",
"monitor.cpuTrend": "CPU 趋势",
"monitor.memoryTrend": "内存趋势",
"monitor.downloadTrend": "下载趋势",
"monitor.uploadTrend": "上传趋势",
"monitor.memoryOnlyHint":
"读数只保留在内存中,最多 30 分钟,退出后清空。空白表示没有读数。共享连接按当前最快的更新需求采集。",
"monitor.name": "面板名称",
"monitor.description": "说明(可选)",
"monitor.chooseHosts": "选择主机",
"monitor.selectionHint": "可跨分组选择。开始后会明确标出不支持的连接。",
"monitor.defaultView": "默认展示",
"monitor.saveHint": "保存仅保留配置,不会连接。复制的面板也不会自动开始。",
"monitor.nameRequired": "请输入面板名称。",
"monitor.hostRequired": "请至少选择一台主机。",
"monitor.duplicateName": "已有同名面板,请换个名称。",
"monitor.saveFailed": "面板未能保存,请重试。",
"monitor.deleted": "该面板已在其他窗口删除。请关闭编辑后新建面板。",
"monitor.moveUp": "主机上移",
"monitor.removeHost": "从面板移除",
"monitor.missingHost": "已删除的主机",
"monitor.observed": "本次已观察 {count} 分钟",
"monitor.disks": "磁盘分区",
"monitor.system": "系统信息",
"monitor.loginHint":
"请检查主机的登录信息或连接设置后重试。身份确认和登录提示会逐台处理。",
"monitor.retry": "重试连接",
"monitor.unsupportedHint":
"监控需要支持额外命令通道的 Linux 或 macOS SSH 连接。",
"monitor.openTerminal": "打开终端",
"monitor.confirmHost": "确认主机身份",
"monitor.status.stopped": "未开始",
"monitor.status.queued": "排队中",
"monitor.status.connecting": "连接中",
"monitor.status.live": "已更新",
"monitor.status.login": "需要登录",
"monitor.status.error": "采集失败",
"monitor.status.unsupported": "不支持",
"monitor.status.disconnected": "已断开",
"monitor.status.stale": "读数过期",
"monitor.status.missing": "主机已删除",
};
@@ -63,6 +63,10 @@ export const zhCNTerminalMessages: Messages = {
'history.action.run': '在终端执行',
'history.action.saveAsSnippet': '保存为代码片段',
'history.action.delete': '从历史记录中删除',
'history.action.clearAll': '清空全部历史',
'history.clearAll.dialog.title': '清空全部命令历史?',
'history.clearAll.dialog.desc': '这将永久删除所有本地记录的命令历史及自动补全建议,且无法撤销。',
'history.clearAll.dialog.confirm': '全部清空',
// SFTP File Opener
'sftp.context.copyPath': '复制文件路径',
'sftp.context.openWith': '打开方式...',
@@ -399,6 +403,11 @@ export const zhCNTerminalMessages: Messages = {
'settings.terminal.behavior.scrollOnPaste.desc': '粘贴文本时将终端滚动到底部',
'settings.terminal.behavior.smoothScrolling': '平滑滚动',
'settings.terminal.behavior.smoothScrolling.desc': '滚动终端视口时使用平滑动画',
'settings.terminal.sidePanel.pane.browser': '浏览器',
'settings.terminal.behavior.linkBrowser': '终端链接打开方式',
'settings.terminal.behavior.linkBrowser.desc': 'SSH 终端通过对应主机访问,本地终端通过本机访问。',
'settings.terminal.behavior.linkBrowser.netcatty': 'Netcatty 内置浏览器(默认)',
'settings.terminal.behavior.linkBrowser.system': '系统默认浏览器',
'settings.terminal.behavior.linkModifier': '链接修饰键',
'settings.terminal.behavior.linkModifier.desc': '按住此键再点击终端中的链接',
'settings.terminal.behavior.linkModifier.none': '无(直接点击)',
@@ -594,6 +603,7 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.binding.new-workspace': '新建工作区',
'settings.shortcuts.binding.snippets': '打开代码片段',
'settings.shortcuts.binding.broadcast': '切换广播模式',
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
'settings.shortcuts.binding.toggle-side-panel': '切换侧边栏',
'settings.shortcuts.binding.sftp-copy': '复制文件',
'settings.shortcuts.binding.sftp-cut': '剪切文件',
+14 -1
View File
@@ -468,6 +468,9 @@ export const zhCNVaultMessages: Messages = {
// Terminal toolbar / search / context menu / auth
'terminal.toolbar.openSftp': '打开 SFTP',
'terminal.browser.title': '浏览器',
'terminal.browser.sshOnly': '请聚焦 SSH 终端以打开浏览器。',
'terminal.browser.open': '打开浏览器',
'terminal.toolbar.availableAfterConnect': '连接后可用',
'terminal.toolbar.sendYmodem': 'YMODEM 发送',
'terminal.toolbar.receiveYmodem': 'YMODEM 接收',
@@ -717,8 +720,11 @@ export const zhCNVaultMessages: Messages = {
'cloudSync.provider.connecting': '连接中...',
'cloudSync.provider.disconnect': '断开连接',
'cloudSync.provider.disconnect.confirmTitle': '断开 “{name}”?',
'cloudSync.provider.disconnect.confirmMessage': '此设备将停止与 {name} 同步。本地保险库仍保留在这台电脑上。',
'cloudSync.provider.disconnect.confirmMessage': '此设备将停止与 {name} 同步,并删除本机保存的该服务商地址与登录凭据。本地主机库、备份历史和同步加密密码仍会保留。若系统凭据存储不可用,插件凭据可能需要手动删除。',
'cloudSync.provider.disconnect.confirmAction': '断开连接',
'cloudSync.provider.disconnect.toastTitle': '已断开连接',
'cloudSync.provider.disconnect.cloudRemains': '云端的加密同步副本可能仍保存在 {name} 存储中。如需清除,请到该服务商删除同步文件。断开连接不代表设备已完成交接清理。',
'cloudSync.provider.disconnect.failed': '未能完成与 {name} 的断开连接,保存的连接资料可能仍在,请重试。',
'cloudSync.provider.webdav': 'WebDAV',
'cloudSync.provider.webdav.desc': '连接到自建 WebDAV 端点',
'cloudSync.provider.s3': 'S3 兼容存储',
@@ -788,6 +794,12 @@ export const zhCNVaultMessages: Messages = {
'cloudSync.strategy.title': '同步策略',
'cloudSync.strategy.desc': '当本地和云端都发生变化时,选择如何处理。',
'cloudSync.strategy.smartMerge': '智能合并(推荐)',
'cloudSync.aiSessions.title': '同步 AI 对话记录',
'cloudSync.aiSessions.desc': '把 AI 对话记录纳入云同步。多设备的对话会按追加方式合并,附件内容仍保留在本机。',
'cloudSync.aiSessions.compatibility': '旧版本可能覆盖对话记录,请先更新所有参与同步的设备。',
'cloudSync.aiSessions.enableFailed': '无法更改聊天同步设置,请检查云端连接和本地可用空间,然后重试。',
'cloudSync.strategy.smartMergePreserve': '智能合并(不传播删除)',
'cloudSync.strategy.smartMergePreserveDesc': '合并两边的变化,且单侧删除不会同步到其它设备——只有所有设备都删掉才会真正消失。恢复备份或多台机器同步时推荐使用。',
'cloudSync.strategy.smartMergeDesc': '尽量保留两边的变化;如果无法安全判断,会再让你手动选择。',
'cloudSync.strategy.preferCloud': '云端优先',
'cloudSync.strategy.preferCloudDesc': '两边都有变化时,下载云端版本,并替换本地变化。',
@@ -924,6 +936,7 @@ export const zhCNVaultMessages: Messages = {
'cloudSync.conflict.entity.customGroups': '分组',
'cloudSync.conflict.entity.snippetPackages': '片段包',
'cloudSync.conflict.entity.portForwardingRules': '端口转发',
'cloudSync.conflict.entity.browserBookmarks': '浏览器书签',
'cloudSync.conflict.entity.groupConfigs': '分组设置',
'cloudSync.conflict.entity.settings': '设置',
'cloudSync.conflict.keepLocal': '覆盖云端(保留本地)',
+2
View File
@@ -1,3 +1,4 @@
import { zhTWMonitorMessages } from './zh-TW/monitor';
import type { Messages } from './types';
import { zhTWCoreMessages } from './zh-TW/core';
import { zhTWVaultMessages } from './zh-TW/vault';
@@ -9,6 +10,7 @@ import { zhTWScriptsMessages } from './zh-TW/scripts';
export type { Messages } from './types';
const zhTW: Messages = {
...zhTWMonitorMessages,
...zhTWCoreMessages,
...zhTWVaultMessages,
...zhTWTerminalMessages,
+5
View File
@@ -1,6 +1,7 @@
import type { Messages } from '../types';
export const zhTWAiMessages: Messages = {
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
// AI Settings
'ai.agentSettings': 'Agent 設定',
'ai.chat.preparing': '準備中…',
@@ -503,6 +504,10 @@ export const zhTWAiMessages: Messages = {
'ai.chat.pinModel': '釘選模型',
'ai.chat.unpinModel': '取消釘選',
'ai.chat.loadingModels': '正在載入模型...',
'ai.chat.modelCatalogSourceLive': '即時目錄',
'ai.chat.modelCatalogSourceCached': '快取 · 上次成功 {time}',
'ai.chat.modelCatalogSourceCachedNoTime': '快取',
'ai.chat.modelCatalogSourcePresets': '內建預設清單',
'ai.chat.noMatchingModels': '沒有符合的模型',
'ai.chat.recent': '最近',
'ai.chat.viewAll': '檢視全部',
+3
View File
@@ -768,6 +768,9 @@ export const zhTWCoreMessages: Messages = {
'vault.hosts.deleteMultiple.success': '已刪除 {count} 個主機',
'vault.hosts.connectSelected': '連線 ({count})',
'vault.hosts.connectMultiple.success': '正在連線 {count} 個主機',
'vault.hosts.moveSelected': '移動到群組 ({count})',
'vault.hosts.moveSelected.description': '將選取的主機移動到現有群組,也可移出群組。選取的群組本身不會移動。',
'vault.hosts.moveMultiple.success': '已將 {count} 個主機移動到 {group}',
'vault.hosts.moveToGroup.success': '已將 {host} 移動到 {group}',
'vault.hosts.errors.nameRequired': '主機名稱不能為空。',
'vault.hosts.empty.title': '設定你的主機',
+90
View File
@@ -0,0 +1,90 @@
export const zhTWMonitorMessages = {
"monitor.actions": "面板操作",
"monitor.unavailable": "監控暫時無法使用,連線恢復後請重新開始。",
"monitor.username": "使用者名稱",
"monitor.password": "密碼(僅本次使用)",
"monitor.status.limit": "同時最多監控 256 台不同主機。",
"sync.entityType.monitorPanels": "監控面板",
"monitor.title": "監控",
"monitor.create": "新增面板",
"monitor.createFirst": "建立第一個監控面板",
"monitor.empty": "一眼查看多台主機",
"monitor.emptyHint": "跨群組選擇現有主機,準備好後再開始監控。",
"monitor.choosePanel": "選擇面板",
"monitor.edit": "編輯面板",
"monitor.copy": "複製面板",
"monitor.copyName": "{name} 副本",
"monitor.delete": "刪除面板",
"monitor.deleteHint":
"刪除「{name}」?此面板將停止監控,現有主機和其他面板會保留。",
"monitor.start": "開始監控",
"monitor.stop": "停止",
"monitor.stopAll": "全部停止",
"monitor.list": "列表",
"monitor.charts": "圖表",
"monitor.search": "搜尋名稱、位址或群組",
"monitor.interval": "更新頻率",
"monitor.range": "趨勢範圍",
"monitor.seconds": "每 {count} 秒",
"monitor.minutes": "最近 {count} 分鐘",
"monitor.sort": "主機排序",
"monitor.sort.manual": "儲存的順序",
"monitor.sort.name": "名稱",
"monitor.selectedCount": "已選 {count} 台主機",
"monitor.noMatches": "沒有符合條件的主機",
"monitor.host": "主機",
"monitor.hosts": "主機",
"monitor.status": "狀態",
"monitor.cpu": "CPU",
"monitor.cores": "{count} 核心",
"monitor.memory": "記憶體",
"monitor.diskCapacity": "已用 {used} / 總容量 {total}",
"monitor.diskCapacityUnknown": "暫無容量讀數",
"monitor.rootDisk": "根分割區",
"monitor.network": "網路",
"monitor.download": "下載",
"monitor.upload": "上傳",
"monitor.updated": "更新時間",
"monitor.updatedAt": "更新於 {time}",
"monitor.noSamples": "等待第一次讀數",
"monitor.cpuTrend": "CPU 趨勢",
"monitor.memoryTrend": "記憶體趨勢",
"monitor.downloadTrend": "下載趨勢",
"monitor.uploadTrend": "上傳趨勢",
"monitor.memoryOnlyHint":
"讀數只保留在記憶體中,最多 30 分鐘,結束後清空。空白表示沒有讀數。共用連線依目前最快的更新需求採集。",
"monitor.name": "面板名稱",
"monitor.description": "說明(選填)",
"monitor.chooseHosts": "選擇主機",
"monitor.selectionHint": "可跨群組選擇。開始後會明確標示不支援的連線。",
"monitor.defaultView": "預設檢視",
"monitor.saveHint": "儲存僅保留設定,不會連線。複製的面板也不會自動開始。",
"monitor.nameRequired": "請輸入面板名稱。",
"monitor.hostRequired": "請至少選擇一台主機。",
"monitor.duplicateName": "已有同名面板,請換個名稱。",
"monitor.saveFailed": "面板無法儲存,請重試。",
"monitor.deleted": "此面板已在其他視窗刪除。請關閉編輯後新增面板。",
"monitor.moveUp": "主機上移",
"monitor.removeHost": "從面板移除",
"monitor.missingHost": "已刪除的主機",
"monitor.observed": "本次已觀察 {count} 分鐘",
"monitor.disks": "磁碟分割區",
"monitor.system": "系統資訊",
"monitor.loginHint":
"請檢查主機的登入資訊或連線設定後重試。身分確認與登入提示會逐台處理。",
"monitor.retry": "重試連線",
"monitor.unsupportedHint":
"監控需要支援額外命令通道的 Linux 或 macOS SSH 連線。",
"monitor.openTerminal": "開啟終端機",
"monitor.confirmHost": "確認主機身分",
"monitor.status.stopped": "未開始",
"monitor.status.queued": "排程中",
"monitor.status.connecting": "連線中",
"monitor.status.live": "已更新",
"monitor.status.login": "需要登入",
"monitor.status.error": "採集失敗",
"monitor.status.unsupported": "不支援",
"monitor.status.disconnected": "已中斷",
"monitor.status.stale": "讀數過期",
"monitor.status.missing": "主機已刪除",
};
@@ -63,6 +63,10 @@ export const zhTWTerminalMessages: Messages = {
'history.action.run': '在終端執行',
'history.action.saveAsSnippet': '儲存為程式碼片段',
'history.action.delete': '從歷史記錄中刪除',
'history.action.clearAll': '清空全部歷史',
'history.clearAll.dialog.title': '清空全部指令歷史?',
'history.clearAll.dialog.desc': '這將永久刪除所有本機記錄的指令歷史及自動補全建議,且無法復原。',
'history.clearAll.dialog.confirm': '全部清空',
// SFTP File Opener
'sftp.context.copyPath': '複製檔案路徑',
'sftp.context.openWith': '開啟方式...',
@@ -399,6 +403,11 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.behavior.scrollOnPaste.desc': '貼上文字時將終端捲動到底部',
'settings.terminal.behavior.smoothScrolling': '平滑捲動',
'settings.terminal.behavior.smoothScrolling.desc': '捲動終端可視區域時使用平滑動畫',
'settings.terminal.sidePanel.pane.browser': '瀏覽器',
'settings.terminal.behavior.linkBrowser': '終端連結開啟方式',
'settings.terminal.behavior.linkBrowser.desc': 'SSH 終端透過對應主機存取,本機終端透過本機存取。',
'settings.terminal.behavior.linkBrowser.netcatty': 'Netcatty 內建瀏覽器(預設)',
'settings.terminal.behavior.linkBrowser.system': '系統預設瀏覽器',
'settings.terminal.behavior.linkModifier': '連結修飾鍵',
'settings.terminal.behavior.linkModifier.desc': '按住此鍵再點選終端中的連結',
'settings.terminal.behavior.linkModifier.none': '無(直接點選)',
@@ -594,6 +603,7 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.binding.new-workspace': '新增工作區',
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
'settings.shortcuts.binding.broadcast': '切換廣播模式',
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
'settings.shortcuts.binding.toggle-side-panel': '切換側邊欄',
'settings.shortcuts.binding.sftp-copy': '複製檔案',
'settings.shortcuts.binding.sftp-cut': '剪下檔案',
+14 -1
View File
@@ -468,6 +468,9 @@ export const zhTWVaultMessages: Messages = {
// Terminal toolbar / search / context menu / auth
'terminal.toolbar.openSftp': '開啟 SFTP',
'terminal.browser.title': '瀏覽器',
'terminal.browser.sshOnly': '請聚焦 SSH 終端以開啟瀏覽器。',
'terminal.browser.open': '開啟瀏覽器',
'terminal.toolbar.availableAfterConnect': '連線後可用',
'terminal.toolbar.sendYmodem': 'YMODEM 傳送',
'terminal.toolbar.receiveYmodem': 'YMODEM 接收',
@@ -717,8 +720,11 @@ export const zhTWVaultMessages: Messages = {
'cloudSync.provider.connecting': '連線中...',
'cloudSync.provider.disconnect': '中斷連線',
'cloudSync.provider.disconnect.confirmTitle': '中斷「{name}」?',
'cloudSync.provider.disconnect.confirmMessage': '此裝置將停止與 {name} 同步。本機保險庫仍保留在這台電腦上。',
'cloudSync.provider.disconnect.confirmMessage': '此裝置將停止與 {name} 同步,並刪除本機保存的該服務商位址與登入憑證。本機主機庫、備份歷史和同步加密密碼仍會保留。若系統憑證儲存無法使用,外掛憑證可能需要手動刪除。',
'cloudSync.provider.disconnect.confirmAction': '中斷連線',
'cloudSync.provider.disconnect.toastTitle': '已中斷連線',
'cloudSync.provider.disconnect.cloudRemains': '雲端的加密同步副本可能仍保存在 {name} 儲存空間中。如需清除,請到該服務商刪除同步檔案。中斷連線不代表裝置已完成交接清理。',
'cloudSync.provider.disconnect.failed': '未能完成與 {name} 的中斷連線,保存的連線資料可能仍在,請重試。',
'cloudSync.provider.webdav': 'WebDAV',
'cloudSync.provider.webdav.desc': '連線到自建 WebDAV 端點',
'cloudSync.provider.s3': 'S3 相容儲存',
@@ -788,6 +794,12 @@ export const zhTWVaultMessages: Messages = {
'cloudSync.strategy.title': '同步策略',
'cloudSync.strategy.desc': '當本機和雲端都發生變化時,選擇如何處理。',
'cloudSync.strategy.smartMerge': '智慧合併(推薦)',
'cloudSync.aiSessions.title': '同步 AI 對話記錄',
'cloudSync.aiSessions.desc': '把 AI 對話記錄納入雲同步。多裝置的對話會按追加方式合併,附件內容仍保留在本機。',
'cloudSync.aiSessions.compatibility': '舊版本可能覆寫對話記錄,請先更新所有參與同步的裝置。',
'cloudSync.aiSessions.enableFailed': '無法變更聊天同步設定,請檢查雲端連線與本機可用空間,然後重試。',
'cloudSync.strategy.smartMergePreserve': '智慧合併(不傳播刪除)',
'cloudSync.strategy.smartMergePreserveDesc': '合併兩邊的變化,且單側刪除不會同步到其它裝置——只有所有裝置都刪掉才會真正消失。還原備份或多台機器同步時建議使用。',
'cloudSync.strategy.smartMergeDesc': '儘量保留兩邊的變化;如果無法安全判斷,會再讓你手動選擇。',
'cloudSync.strategy.preferCloud': '雲端優先',
'cloudSync.strategy.preferCloudDesc': '兩邊都有變化時,下載雲端版本,並替換本機變化。',
@@ -924,6 +936,7 @@ export const zhTWVaultMessages: Messages = {
'cloudSync.conflict.entity.customGroups': '群組',
'cloudSync.conflict.entity.snippetPackages': '片段包',
'cloudSync.conflict.entity.portForwardingRules': '埠轉發',
'cloudSync.conflict.entity.browserBookmarks': '瀏覽器書籤',
'cloudSync.conflict.entity.groupConfigs': '群組設定',
'cloudSync.conflict.entity.settings': '設定',
'cloudSync.conflict.keepLocal': '覆蓋雲端(保留本機)',
+155
View File
@@ -0,0 +1,155 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import type { MonitorPanel } from "../domain/monitorPanels";
const store = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => store.set(k, v),
removeItem: (k: string) => store.delete(k),
},
});
const {
buildCloudSyncPayload,
buildLocalVaultPayload,
applySyncPayload,
applyLocalVaultPayload,
} = await import("./syncPayload");
const {
writeMonitorPanels,
readMonitorPanels,
saveMonitorPanel,
deleteMonitorPanel,
} = await import("./state/monitorPanelsStorage");
const panel: MonitorPanel = {
id: "p",
name: "Fleet",
description: "",
hostIds: ["h1", "h2"],
view: "charts",
interval: 10,
range: 15,
sort: "manual",
};
const vault = {
hosts: [],
keys: [],
identities: [],
snippets: [],
customGroups: [],
knownHosts: [],
};
const opts = { collectPluginSidecars: () => undefined };
const importers = { importVaultData: () => {} };
test("real builders and importers round-trip panel configuration through cloud and backups without runtime state", async () => {
store.clear();
writeMonitorPanels([
{
...panel,
stats: { cpu: 42 },
running: true,
points: [1],
error: "never-save",
},
]);
const cloud = await buildCloudSyncPayload(vault, [], opts);
const backup = buildLocalVaultPayload(vault);
assert.deepEqual(cloud.monitorPanels, [panel]);
assert.deepEqual(backup.monitorPanels, [panel]);
assert.ok(!JSON.stringify(cloud).includes("never-save"));
writeMonitorPanels([]);
await applySyncPayload(cloud, importers);
assert.deepEqual(readMonitorPanels(), [panel]);
delete backup.aiSessions;
writeMonitorPanels([]);
await applyLocalVaultPayload(backup, importers);
assert.deepEqual(readMonitorPanels(), [panel]);
const renamed = {
...panel,
name: "Changed",
hostIds: ["h2"],
view: "list" as const,
};
await applySyncPayload({ ...cloud, monitorPanels: [renamed] }, importers);
assert.deepEqual(readMonitorPanels(), [renamed]);
const legacy = { ...cloud };
delete legacy.monitorPanels;
await applySyncPayload(legacy, importers);
assert.deepEqual(readMonitorPanels(), [renamed]);
await applySyncPayload({ ...cloud, monitorPanels: [] }, importers);
assert.deepEqual(readMonitorPanels(), []);
});
test("serialized window mutations rebase stale fields and do not resurrect a deletion", async () => {
store.clear();
writeMonitorPanels([panel]);
await Promise.all([
saveMonitorPanel(panel, { ...panel, name: "Rename" }),
saveMonitorPanel(panel, { ...panel, hostIds: ["h3"], view: "list" }),
]);
assert.deepEqual(readMonitorPanels(), [
{ ...panel, name: "Rename", hostIds: ["h3"], view: "list" },
]);
await deleteMonitorPanel("p");
await assert.rejects(
saveMonitorPanel(panel, { ...panel, name: "Stale" }),
/deleted/,
);
assert.deepEqual(readMonitorPanels(), []);
});
test("cloud apply preserves panel edits committed after preparation", async () => {
store.clear();
writeMonitorPanels([panel]);
const { prepareSyncPayloadApply } = await import("./syncPayload");
const prepared = await prepareSyncPayloadApply(
{
hosts: [],
keys: [],
snippets: [],
customGroups: [],
syncedAt: 1,
monitorPanels: [{ ...panel, name: "From cloud" }],
},
importers,
);
await saveMonitorPanel(panel, { ...panel, hostIds: ["h3"], view: "list" });
await prepared();
assert.deepEqual(readMonitorPanels(), [
{ ...panel, name: "From cloud", hostIds: ["h3"], view: "list" },
]);
});
test("cloud and backup imports preserve both independently created same-name panels", async () => {
store.clear();
const original = { ...panel, id: "a", name: "Fleet" };
const other = { ...panel, id: "b", name: "FLEET" };
writeMonitorPanels([original]);
await applySyncPayload(
{
hosts: [],
keys: [],
snippets: [],
customGroups: [],
syncedAt: 1,
monitorPanels: [other, original],
},
importers,
);
assert.deepEqual(
readMonitorPanels().map((p) => [p.id, p.name]),
[
["a", "Fleet"],
["b", "FLEET (2)"],
],
);
const backup = buildLocalVaultPayload(vault);
delete backup.aiSessions;
writeMonitorPanels([]);
await applyLocalVaultPayload(backup, importers);
assert.equal(readMonitorPanels().length, 2);
assert.equal(
new Set(readMonitorPanels().map((p) => p.name.toLowerCase())).size,
2,
);
});
+8 -4
View File
@@ -2,6 +2,7 @@ import { localStorageAdapter } from '../../infrastructure/persistence/localStora
import {
STORAGE_KEY_AI_ACTIVE_SESSION_MAP,
STORAGE_KEY_AI_SESSIONS,
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
} from '../../infrastructure/config/storageKeys';
import type {
AIDraft,
@@ -47,12 +48,10 @@ export const AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE = 'netcatty:ai-panel-view-by-s
export type DraftsByScope = Partial<Record<string, AIDraft>>;
export type PanelViewByScope = Partial<Record<string, AIPanelView>>;
export function cleanupSdkAgentSessions(sessionIds: string[]) {
export async function cleanupSdkAgentSessions(sessionIds: string[]): Promise<void> {
const bridge = getAIBridge();
if (sessionIds.length === 0) return;
for (const sessionId of sessionIds) {
void bridge?.aiSdkAgentCleanup?.(sessionId).catch(() => {});
}
await Promise.all(sessionIds.map((sessionId) => bridge?.aiSdkAgentCleanup?.(sessionId).catch(() => {})));
}
export function cleanupDeletedAIChatSessions(sessionIds: string[]) {
@@ -471,6 +470,11 @@ export function serializeSessionsForStorage(
* could not be persisted even after escalation (it stays memory-only).
*/
export function writeSessionsForStorage(sessions: AISession[]): boolean {
// Synced records are authoritative after restart: silently evicting a
// session or turn here would turn local retention into cloud deletion.
if (localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled) {
return localStorageAdapter.write(STORAGE_KEY_AI_SESSIONS, sessions);
}
let previousLength = Number.POSITIVE_INFINITY;
for (const configuredBudget of [MAX_SESSIONS_JSON_BYTES, ...RETRY_SESSIONS_JSON_BYTES]) {
// A real quota failure means the next attempt must be smaller even when
@@ -0,0 +1,328 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
STORAGE_KEY_COMMAND_HISTORY,
STORAGE_KEY_COMMAND_HISTORY_CLEARED,
} from "../../infrastructure/config/storageKeys";
type StorageEventLike = { key: string | null; newValue: string | null; oldValue: string | null };
type StorageListener = (event: StorageEventLike) => void;
type DeferredRead = { resolve: (value: string) => void };
const COMMAND_HISTORY_STORAGE_KEY = STORAGE_KEY_COMMAND_HISTORY;
function installLocalStorage(): Map<string, string> {
const store = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: (key: string) => (store.has(key) ? store.get(key)! : null),
setItem: (key: string, value: string) => {
store.set(key, String(value));
},
removeItem: (key: string) => {
store.delete(key);
},
clear: () => {
store.clear();
},
},
configurable: true,
});
return store;
}
/**
* The store registers its cross-window `storage` listener at module load, so
* the DOM globals must exist before the dynamic imports below.
*/
function installWindow(): (key: string, newValue: string | null, oldValue?: string | null) => void {
const listeners = new Set<StorageListener>();
Object.defineProperty(globalThis, "window", {
value: {
addEventListener: (type: string, listener: StorageListener) => {
if (type === "storage") listeners.add(listener);
},
removeEventListener: (type: string, listener: StorageListener) => {
if (type === "storage") listeners.delete(listener);
},
netcatty: undefined as unknown,
},
configurable: true,
});
return (key: string, newValue: string | null, oldValue: string | null = null) => {
for (const listener of listeners) listener({ key, newValue, oldValue });
};
}
async function waitFor(condition: () => boolean, timeoutMs = 2000): Promise<void> {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeoutMs) throw new Error("waitFor timed out");
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
const storage = installLocalStorage();
const dispatchStorageEvent = installWindow();
const {
clearHistory,
flushCommandHistoryStore,
getCommandHistoryClearGeneration,
hasCommandHistoryBeenCleared,
markCommandHistoryCleared,
queryHistory,
recordCommand,
subscribeCommandHistoryCleared,
} = await import("./commandHistoryStore.ts");
const { seedLocalShellHistoryFromHistfiles } = await import(
"../../components/terminal/autocomplete/localShellHistorySeed.ts"
);
function readPersistedCommands(): string[] {
const raw = storage.get(COMMAND_HISTORY_STORAGE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw) as { entries: Array<{ command: string }> };
return parsed.entries.map((entry) => entry.command);
}
function readPersistedGeneration(): number {
const raw = storage.get(COMMAND_HISTORY_STORAGE_KEY);
if (!raw) return 0;
const parsed = JSON.parse(raw) as { clearGeneration?: number };
return typeof parsed.clearGeneration === "number" ? parsed.clearGeneration : 0;
}
test("a fresh popup keeps compose recall on an ordinary peer write after an earlier clear", async () => {
const baseline = JSON.stringify({ entries: [], version: 1, clearGeneration: 3 });
storage.set(COMMAND_HISTORY_STORAGE_KEY, baseline);
const composeBar = await import("./composeBarHistoryStore.ts");
composeBar.recordComposeBarHistory("fresh-popup", "echo popup-current-command");
// No autocomplete query has loaded this renderer's command-history store.
const recorded = JSON.stringify({
entries: [{ command: "peer-command", hostId: "host-2", os: "linux", frequency: 1, createdAt: 1, lastUsedAt: 1 }],
version: 1, clearGeneration: 3,
});
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, recorded, baseline);
assert.deepEqual(composeBar.getComposeBarHistory("fresh-popup"), ["echo popup-current-command"]);
const cleared = JSON.stringify({ entries: [], version: 1, clearGeneration: 4 });
storage.set(COMMAND_HISTORY_STORAGE_KEY, cleared);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, cleared, recorded);
assert.deepEqual(composeBar.getComposeBarHistory("fresh-popup"), []);
});
test("a stale pending write cannot overwrite a peer clear before its storage event arrives", () => {
clearHistory();
recordCommand("old-command", "host-1");
flushCommandHistoryStore();
recordCommand("pending-before-clear", "host-1");
// localStorage is already updated in the peer, but this renderer has not yet
// processed its queued storage event when the pending save runs.
const generation = readPersistedGeneration() + 1;
storage.set(COMMAND_HISTORY_STORAGE_KEY, JSON.stringify({
entries: [], version: 1, clearGeneration: generation,
}));
flushCommandHistoryStore();
assert.deepEqual(readPersistedCommands(), []);
assert.equal(readPersistedGeneration(), generation);
assert.deepEqual(queryHistory("old", { hostId: "host-1" }), []);
recordCommand("new-after-clear", "host-1");
flushCommandHistoryStore();
assert.deepEqual(readPersistedCommands(), ["new-after-clear"]);
});
test("an ordinary peer write does not cancel a locally pending command", async () => {
clearHistory();
recordCommand("local-pending-command", "host-1");
const before = storage.get(COMMAND_HISTORY_STORAGE_KEY)!;
const ordinary = JSON.stringify({
entries: [{ command: "peer-command", hostId: "host-2", os: "linux", frequency: 1, createdAt: 1, lastUsedAt: 1 }],
version: 1, clearGeneration: getCommandHistoryClearGeneration(),
});
storage.set(COMMAND_HISTORY_STORAGE_KEY, ordinary);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, ordinary, before);
await new Promise((resolve) => setTimeout(resolve, 600));
assert.ok(readPersistedCommands().includes("local-pending-command"));
});
test("an external clear invalidates the cached history and cannot be resurrected", () => {
storage.clear();
clearHistory();
recordCommand("stale-command --flag", "host-1");
flushCommandHistoryStore();
assert.ok(queryHistory("stale", { hostId: "host-1" }).length > 0);
// Simulate another renderer (main window or a detached terminal popup)
// clearing the shared localStorage entry.
const cleared = JSON.stringify({ entries: [], version: 1, clearGeneration: 1 });
storage.set(COMMAND_HISTORY_STORAGE_KEY, cleared);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, cleared);
// The stale module-local cache must be dropped immediately.
assert.equal(queryHistory("stale", { hostId: "host-1" }).length, 0);
// A later recordCommand must persist only the new command, never the stale
// snapshot it still held in memory.
recordCommand("fresh-command", "host-1");
flushCommandHistoryStore();
assert.deepEqual(readPersistedCommands(), ["fresh-command"]);
});
test("clearHistory persists synchronously and cancels a pending debounced write", async () => {
storage.clear();
clearHistory();
recordCommand("pending-command", "host-1");
// No flush: the debounced write is still scheduled.
clearHistory();
assert.deepEqual(readPersistedCommands(), []);
// Wait past the debounce window to prove the cancelled write cannot restore
// the entries.
await new Promise((resolve) => setTimeout(resolve, 600));
assert.deepEqual(readPersistedCommands(), []);
});
test("a local clear bumps the generation and notifies subscribers", () => {
storage.clear();
clearHistory();
const before = getCommandHistoryClearGeneration();
let notified = 0;
const unsubscribe = subscribeCommandHistoryCleared(() => {
notified += 1;
});
recordCommand("notify-local", "host-1");
clearHistory();
assert.equal(getCommandHistoryClearGeneration(), before + 1);
assert.equal(readPersistedGeneration(), before + 1);
assert.equal(notified, 1);
unsubscribe();
clearHistory();
assert.equal(notified, 1);
});
test("an external clear notifies subscribers, while an external record does not", () => {
storage.clear();
clearHistory();
const baseline = getCommandHistoryClearGeneration();
let notified = 0;
const unsubscribe = subscribeCommandHistoryCleared(() => {
notified += 1;
});
// A normal record from another renderer keeps the generation: no clear event.
const recorded = JSON.stringify({ entries: [], version: 1, clearGeneration: baseline });
storage.set(COMMAND_HISTORY_STORAGE_KEY, recorded);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, recorded);
assert.equal(notified, 0);
// A clear from another renderer bumps the generation: subscribers fire.
const cleared = JSON.stringify({ entries: [], version: 1, clearGeneration: baseline + 1 });
storage.set(COMMAND_HISTORY_STORAGE_KEY, cleared);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, cleared);
assert.equal(notified, 1);
assert.equal(getCommandHistoryClearGeneration(), baseline + 1);
unsubscribe();
});
test("a histfile import that started before a clear is discarded", async () => {
storage.clear();
clearHistory();
const hostId = `local-seed-clear-${Date.now()}`;
const deferredReads: DeferredRead[] = [];
(window as unknown as { netcatty?: unknown }).netcatty = {
getHomeDir: async () => "/home/demo",
readLocalFile: () =>
new Promise<string>((resolve) => {
deferredReads.push({ resolve });
}),
};
const seedPromise = seedLocalShellHistoryFromHistfiles(hostId, "macos");
// Let the seeder resolve getHomeDir and reach the histfile reads.
await waitFor(() => deferredReads.length === 4);
// The user clears history while the bridge reads are still pending.
clearHistory();
for (const deferred of deferredReads) {
deferred.resolve(": 1700000000:0;echo seeded\n");
}
assert.equal(await seedPromise, 0);
assert.equal(queryHistory("echo", { hostId, limit: 5 }).length, 0);
// The host is marked seeded so a later open cannot re-import the deleted
// commands.
assert.equal(await seedLocalShellHistoryFromHistfiles(hostId, "macos"), 0);
assert.equal(queryHistory("echo", { hostId, limit: 5 }).length, 0);
});
test("markCommandHistoryCleared persists a tombstone for histfile seeding", () => {
storage.clear();
assert.equal(hasCommandHistoryBeenCleared(), false);
markCommandHistoryCleared();
assert.equal(hasCommandHistoryBeenCleared(), true);
assert.equal(storage.get(STORAGE_KEY_COMMAND_HISTORY_CLEARED), "true");
});
test("a first-time histfile import is skipped once history has been cleared", async () => {
storage.clear();
clearHistory();
markCommandHistoryCleared();
const hostId = `local-seed-tombstone-${Date.now()}`;
(window as unknown as { netcatty?: unknown }).netcatty = {
getHomeDir: async () => "/home/demo",
readLocalFile: async () => ": 1700000000:0;echo resurrected\n",
};
assert.equal(await seedLocalShellHistoryFromHistfiles(hostId, "macos"), 0);
assert.equal(queryHistory("echo", { hostId, limit: 5 }).length, 0);
});
test("an external clear also drops in-memory compose-bar recall", async () => {
const composeBar = await import("./composeBarHistoryStore.ts");
storage.clear();
clearHistory();
composeBar.pruneComposeBarHistory([]);
composeBar.recordComposeBarHistory("session-1", "echo compose");
assert.deepEqual(composeBar.getComposeBarHistory("session-1"), ["echo compose"]);
let notified = 0;
const unsubscribe = composeBar.subscribeComposeBarHistoryCleared(() => {
notified += 1;
});
// Simulate another renderer clearing command history. The compose-bar store
// follows the same clear event, so a detached popup drops its recall too.
const cleared = JSON.stringify({
entries: [],
version: 1,
clearGeneration: getCommandHistoryClearGeneration() + 1,
});
storage.set(COMMAND_HISTORY_STORAGE_KEY, cleared);
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, cleared);
assert.deepEqual(composeBar.getComposeBarHistory("session-1"), []);
assert.equal(notified, 1);
unsubscribe();
});
@@ -2,11 +2,19 @@
* Persistent command history store for terminal autocomplete.
* Stores commands per host with frequency tracking and timestamp ordering.
* Uses localStorageAdapter as the persistence layer (works in renderer process).
*
* Lives in application state rather than the UI layer so the vault hook and the
* terminal UI depend on one lower-layer API, and so every renderer (main window
* and detached terminal popups) shares the same clear semantics.
*/
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
import { localStorageAdapter } from "../../infrastructure/persistence/localStorageAdapter";
import {
STORAGE_KEY_COMMAND_HISTORY,
STORAGE_KEY_COMMAND_HISTORY_CLEARED,
} from "../../infrastructure/config/storageKeys";
const STORAGE_KEY = "netcatty:commandHistory";
const STORAGE_KEY = STORAGE_KEY_COMMAND_HISTORY;
const MAX_ENTRIES = 10000;
const MAX_ENTRIES_PER_HOST = 5000;
@@ -26,9 +34,21 @@ export interface HistoryEntry {
interface HistoryStore {
entries: HistoryEntry[];
version: number;
/**
* Monotonic counter bumped by every global clear. Other renderers compare it
* to detect a clear performed elsewhere, and in-flight histfile imports use
* it to discard work that started before the clear.
*/
clearGeneration?: number;
}
let cachedStore: HistoryStore | null = null;
/** Last clear generation this renderer has observed. */
let knownClearGeneration: number | null = null;
function readClearGeneration(store: HistoryStore): number {
return typeof store.clearGeneration === "number" ? store.clearGeneration : 0;
}
function loadStore(): HistoryStore {
if (cachedStore) return cachedStore;
@@ -36,18 +56,29 @@ function loadStore(): HistoryStore {
const parsed = localStorageAdapter.read<HistoryStore>(STORAGE_KEY);
if (parsed) {
cachedStore = parsed;
knownClearGeneration = readClearGeneration(parsed);
return parsed;
}
} catch {
// Corrupted data, reset
}
cachedStore = { entries: [], version: 1 };
cachedStore = { entries: [], version: 1, clearGeneration: 0 };
knownClearGeneration = 0;
return cachedStore;
}
let saveTimer: ReturnType<typeof setTimeout> | null = null;
function persistStoreNow(store: HistoryStore): boolean {
// A peer clear is visible in storage before its queued event is handled.
// Never flush a cached pre-clear snapshot over that newer empty store.
const persisted = localStorageAdapter.read<HistoryStore>(STORAGE_KEY);
if (persisted && readClearGeneration(persisted) > readClearGeneration(store)) {
cachedStore = persisted;
knownClearGeneration = readClearGeneration(persisted);
notifyCommandHistoryCleared();
return true;
}
const ok = localStorageAdapter.write(STORAGE_KEY, store);
if (ok) return true;
// Storage full — evict lowest scored entries (not just oldest by insertion)
@@ -67,6 +98,13 @@ function saveStore(store: HistoryStore): void {
}, 500);
}
function cancelPendingSave(): void {
if (saveTimer) {
clearTimeout(saveTimer);
saveTimer = null;
}
}
/**
* Flush any pending debounced history write immediately.
* Used after bulk imports (e.g. local histfile seeding) so a seed-complete
@@ -75,13 +113,112 @@ function saveStore(store: HistoryStore): void {
*/
export function flushCommandHistoryStore(): boolean {
if (!cachedStore) return true;
if (saveTimer) {
clearTimeout(saveTimer);
saveTimer = null;
}
cancelPendingSave();
return persistStoreNow(cachedStore);
}
/**
* React to a write performed by another renderer (main window or a detached
* terminal popup).
*
* A bumped clear generation drops the cache and pending save, then notifies
* live autocomplete controllers. Ordinary peer writes must not cancel a local
* command that is still waiting for its debounced save.
*/
function applyExternalCommandHistoryWrite(
rawNewValue: string | null,
rawOldValue: string | null,
): void {
let incomingGeneration: number | null = null;
if (rawNewValue) {
try {
incomingGeneration = readClearGeneration(JSON.parse(rawNewValue) as HistoryStore);
} catch {
incomingGeneration = null;
}
}
let previousGeneration = knownClearGeneration;
if (previousGeneration === null) {
// A fresh popup can have compose recall before its first autocomplete query.
// The event's old value is its baseline, even after an earlier global clear.
try {
previousGeneration = rawOldValue
? readClearGeneration(JSON.parse(rawOldValue) as HistoryStore)
: 0;
} catch {
previousGeneration = 0;
}
}
if (incomingGeneration !== null && incomingGeneration > previousGeneration) {
cancelPendingSave();
cachedStore = null;
knownClearGeneration = incomingGeneration;
notifyCommandHistoryCleared();
} else {
if (!saveTimer) cachedStore = null;
if (incomingGeneration !== null && knownClearGeneration === null) {
knownClearGeneration = incomingGeneration;
}
}
}
// The native `storage` event fires in *other* same-origin windows (main window
// and detached terminal popups) when a key changes there.
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("storage", (event) => {
if (event.key === STORAGE_KEY) applyExternalCommandHistoryWrite(event.newValue, event.oldValue);
});
}
/**
* Current clear generation. Callers capture this before async work and compare
* afterwards to detect a clear that happened while they were waiting.
*/
export function getCommandHistoryClearGeneration(): number {
if (knownClearGeneration === null) loadStore();
return knownClearGeneration ?? 0;
}
/**
* Record that the user explicitly cleared all command history.
*
* Histfile seeding honors this tombstone: a clear is a user decision to delete
* locally recorded history, so a later first-time import must not restore the
* commands the user deleted (a pre-clear in-flight check alone cannot catch a
* clear that happened before the import started).
*/
export function markCommandHistoryCleared(): void {
localStorageAdapter.writeBoolean(STORAGE_KEY_COMMAND_HISTORY_CLEARED, true);
}
/** True once the user has cleared all command history at least once. */
export function hasCommandHistoryBeenCleared(): boolean {
return localStorageAdapter.readBoolean(STORAGE_KEY_COMMAND_HISTORY_CLEARED) === true;
}
type CommandHistoryClearedListener = () => void;
const clearedListeners = new Set<CommandHistoryClearedListener>();
/**
* Subscribe to command-history clears, including clears performed in another
* renderer. Live autocomplete controllers use this to drop visible suggestions
* and ghost text and abort in-flight completions, so a stale row cannot be
* accepted and recorded after the history was cleared.
*/
export function subscribeCommandHistoryCleared(
listener: CommandHistoryClearedListener,
): () => void {
clearedListeners.add(listener);
return () => {
clearedListeners.delete(listener);
};
}
function notifyCommandHistoryCleared(): void {
for (const listener of [...clearedListeners]) listener();
}
/**
* Record a command execution. Updates frequency if the command already exists
* for this host, otherwise creates a new entry.
@@ -149,10 +286,7 @@ export function removeCommandHistoryEntry(command: string, hostId: string): bool
if (nextEntries.length === store.entries.length) return false;
store.entries = nextEntries;
if (saveTimer) {
clearTimeout(saveTimer);
saveTimer = null;
}
cancelPendingSave();
return persistStoreNow(store);
}
@@ -427,6 +561,8 @@ function fuzzyScore(query: string, target: string): number {
/**
* Clear all history for a specific host, or all history if no hostId given.
* A global clear also bumps the shared clear generation so other renderers and
* in-flight histfile imports can detect it.
*/
export function clearHistory(hostId?: string): void {
const store = loadStore();
@@ -434,6 +570,12 @@ export function clearHistory(hostId?: string): void {
store.entries = store.entries.filter((e) => e.hostId !== hostId);
} else {
store.entries = [];
store.clearGeneration = readClearGeneration(store) + 1;
}
saveStore(store);
// Destructive clears must be durable: cancel any pending debounced write and
// persist synchronously so a later stale flush cannot restore the entries.
cancelPendingSave();
persistStoreNow(store);
knownClearGeneration = readClearGeneration(store);
if (!hostId) notifyCommandHistoryCleared();
}
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from './composeBarHistoryStore';
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory, clearComposeBarHistory, subscribeComposeBarHistoryCleared } from './composeBarHistoryStore';
test('compose history is isolated per terminal and removed when its session closes', () => {
pruneComposeBarHistory([]);
@@ -40,3 +40,24 @@ test('failed submissions unblock later successes in submission order', async ()
assert.deepEqual(getComposeBarHistory('a'), ['accepted']);
pruneComposeBarHistory([]);
});
test('clearComposeBarHistory drops every session and notifies live compose bars', () => {
pruneComposeBarHistory([]);
recordComposeBarHistory('a', 'echo a');
recordComposeBarHistory('b', 'echo b');
let notified = 0;
const unsubscribe = subscribeComposeBarHistoryCleared(() => {
notified += 1;
});
clearComposeBarHistory();
assert.deepEqual(getComposeBarHistory('a'), []);
assert.deepEqual(getComposeBarHistory('b'), []);
assert.equal(notified, 1);
unsubscribe();
clearComposeBarHistory();
assert.equal(notified, 1);
});
@@ -1,10 +1,14 @@
import { appendComposeBarHistory } from '../../domain/composeBarHistory';
import { subscribeCommandHistoryCleared } from './commandHistoryStore';
// Session-only memory: survives closing the bar and moving a terminal into a
// workspace, but is discarded when that terminal session is removed.
type PendingSend = { settled: boolean; command?: string };
const histories = new Map<string, { entries: readonly string[]; pending: PendingSend[] }>();
type Listener = () => void;
const clearedListeners = new Set<Listener>();
export function getComposeBarHistory(sessionId: string): readonly string[] {
return histories.get(sessionId)?.entries ?? [];
}
@@ -44,3 +48,36 @@ export function pruneComposeBarHistory(sessionIds: readonly string[]): void {
if (!active.has(id)) histories.delete(id);
}
}
/**
* Subscribe to full compose-bar history clears. A live compose bar uses this to
* drop the history walk it cached, so ArrowUp cannot recall deleted commands.
*/
export function subscribeComposeBarHistoryCleared(listener: Listener): () => void {
clearedListeners.add(listener);
return () => {
clearedListeners.delete(listener);
};
}
/**
* Clear the in-memory compose-bar history for every session.
*
* This store is session-only (never persisted), so the "clear all command
* history" action must clear it explicitly. Otherwise a command sent through
* the compose bar stays recallable, and resending it would re-record it into
* shell history and autocomplete after the user deleted it.
*/
export function clearComposeBarHistory(): void {
histories.clear();
// Always notify: a live compose bar can still hold a cached walk even when
// the map is already empty (for example after its session was pruned).
for (const listener of [...clearedListeners]) listener();
}
// The compose bar holds the most recent commands sent through it, so clearing
// command history must drop it too. Subscribing to the command-history clear
// event covers every renderer: a detached terminal popup renders its own
// TerminalComposeBar and learns about a main-window clear through the shared
// clear generation, while the main window is notified synchronously.
subscribeCommandHistoryCleared(clearComposeBarHistory);
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { requestHostBrowserPanel, subscribeHostBrowserPanelRequests, type HostBrowserPanelRequest } from './hostBrowserPanelRequests';
test('detached terminal requests reach the main window instead of being dropped', async () => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
const forwarded: HostBrowserPanelRequest[] = [];
const delivered: HostBrowserPanelRequest[] = [];
let nativeListener: ((request: HostBrowserPanelRequest) => void) | undefined;
let removed = false;
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
requestHostBrowserPanel: async (request: HostBrowserPanelRequest) => { forwarded.push(request); return true; },
onHostBrowserPanelRequest: (listener: typeof nativeListener) => {
nativeListener = listener;
return () => { removed = true; nativeListener = undefined; };
},
} } });
let unsubscribe: (() => void) | undefined;
try {
const request = { host: { id: 'host', hostname: 'host', label: 'Host', username: 'test' }, url: 'http://localhost:3000/' } as HostBrowserPanelRequest;
requestHostBrowserPanel(request);
await Promise.resolve();
assert.deepEqual(forwarded, [request]);
unsubscribe = subscribeHostBrowserPanelRequests((value) => delivered.push(value));
assert.ok(nativeListener);
nativeListener(request);
assert.deepEqual(delivered, [request]);
assert.equal(forwarded.length, 1, 'main-window consumption must not forward the request again');
unsubscribe(); unsubscribe = undefined;
assert.equal(removed, true);
} finally {
unsubscribe?.();
if (previous) Object.defineProperty(globalThis, 'window', previous);
else Reflect.deleteProperty(globalThis, 'window');
}
});
@@ -0,0 +1,35 @@
import type { Host } from '../../domain/models';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
export type HostBrowserPanelRequest = { host: Host; sessionId?: string; url?: string };
type Listener = (request: HostBrowserPanelRequest) => void;
const listeners = new Set<Listener>();
let pending: HostBrowserPanelRequest | null = null;
let unsubscribeNative: (() => void) | undefined;
export function requestHostBrowserPanel(request: HostBrowserPanelRequest): void {
if (!listeners.size) {
const forward = netcattyBridge.get()?.requestHostBrowserPanel;
if (forward) {
void forward(request).catch(() => { pending = request; });
} else pending = request;
return;
}
for (const listener of listeners) listener(request);
}
export function subscribeHostBrowserPanelRequests(listener: Listener): () => void {
listeners.add(listener);
if (!unsubscribeNative) unsubscribeNative = netcattyBridge.get()?.onHostBrowserPanelRequest?.((request) => {
for (const current of listeners) current(request);
});
if (pending) {
const request = pending;
pending = null;
listener(request);
}
return () => {
listeners.delete(listener);
if (!listeners.size) { unsubscribeNative?.(); unsubscribeNative = undefined; }
};
}
+98
View File
@@ -0,0 +1,98 @@
import { mergeSyncPayloads } from "../../domain/syncMerge";
import { useSyncExternalStore } from "react";
import {
normalizeMonitorPanels,
rebaseMonitorPanel,
type MonitorPanel,
} from "../../domain/monitorPanels";
import { STORAGE_KEY_MONITOR_PANELS } from "../../infrastructure/config/storageKeys";
import {
localStorageAdapter,
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
} from "../../infrastructure/persistence/localStorageAdapter";
import { withVaultImportLock } from "./vaultManagedImportLock";
export function readMonitorPanels(): MonitorPanel[] {
return normalizeMonitorPanels(
localStorageAdapter.read(STORAGE_KEY_MONITOR_PANELS),
);
}
export function writeMonitorPanels(value: unknown): void {
if (
!localStorageAdapter.write(
STORAGE_KEY_MONITOR_PANELS,
normalizeMonitorPanels(value),
)
)
throw new Error("monitor.saveFailed");
}
export async function saveMonitorPanel(
base: MonitorPanel | null,
next: MonitorPanel,
): Promise<void> {
return withVaultImportLock("vault", async () =>
writeMonitorPanels(rebaseMonitorPanel(readMonitorPanels(), base, next)),
);
}
export async function deleteMonitorPanel(id: string): Promise<void> {
return withVaultImportLock("vault", async () =>
writeMonitorPanels(readMonitorPanels().filter((p) => p.id !== id)),
);
}
/** Rebase a prepared cloud snapshot against edits committed while it was applying. */
export async function applyMonitorPanels(
value: unknown,
base: MonitorPanel[],
replace = false,
): Promise<void> {
return withVaultImportLock("vault", async () => {
const remote = normalizeMonitorPanels(value);
if (replace) {
writeMonitorPanels(remote);
return;
}
const payload = (panels: MonitorPanel[]) => ({
hosts: [],
keys: [],
snippets: [],
customGroups: [],
syncedAt: 0,
monitorPanels: panels,
});
writeMonitorPanels(
mergeSyncPayloads(
payload(base),
payload(readMonitorPanels()),
payload(remote),
).payload.monitorPanels ?? [],
);
});
}
let cachedRaw: string | null | undefined;
let cached: MonitorPanel[] = [];
function getSnapshot() {
const raw = localStorageAdapter.readString(STORAGE_KEY_MONITOR_PANELS);
if (raw !== cachedRaw) {
cachedRaw = raw;
cached = readMonitorPanels();
}
return cached;
}
function subscribe(listener: () => void) {
const handler = (event: Event) => {
const key =
event instanceof StorageEvent
? event.key
: (event as CustomEvent<{ key: string }>).detail?.key;
if (!key || key === STORAGE_KEY_MONITOR_PANELS) listener();
};
window.addEventListener("storage", handler);
window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, handler);
return () => {
window.removeEventListener("storage", handler);
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, handler);
};
}
export function useMonitorPanels(): MonitorPanel[] {
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
+56
View File
@@ -0,0 +1,56 @@
import { useSyncExternalStore } from "react";
import { mergeMonitorSnapshotHistory, type MonitorSnapshot, type MonitorHistoryCursor } from "../../domain/monitorRuntime";
const empty: MonitorSnapshot = {
historyMode: "replace",
running: [],
count: 0,
hostCount: 0,
epoch: 0,
runtimeId: "",
takenAt: 0,
activeSessions: [],
startedAt: {},
hosts: {},
};
let snapshot = empty;
const listeners = new Set<() => void>();
export function publishMonitorSnapshot(next: MonitorSnapshot) {
snapshot = mergeMonitorSnapshotHistory(snapshot, next);
for (const l of listeners) l();
}
export function getMonitorHistoryCursor(): MonitorHistoryCursor {
return {
runtimeId: snapshot.runtimeId,
epoch: snapshot.epoch,
after: Object.fromEntries(Object.entries(snapshot.hosts).map(([id, host]) => [id, { at: host.points.at(-1)?.at ?? 0, statsAt: host.at, historyId: host.historyId }])),
};
}
export function publishMonitorUnavailable() {
publishMonitorSnapshot({ ...empty, unavailable: true });
}
export function useMonitorSnapshot() {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => {
listeners.delete(l);
};
},
() => snapshot,
() => empty,
);
}
export const monitorActions: {
start: (id: string) => void;
stop: (id: string) => void;
stopAll: () => void;
retry: (
id: string,
credentials?: { username: string; password: string },
) => void;
} = {
start: () => {},
stop: () => {},
stopAll: () => {},
retry: () => {},
};
+14 -1
View File
@@ -4,7 +4,7 @@ import test from "node:test";
import type { Host } from "../../domain/models";
import { prepareSerialConfigForSavedHost } from "../../domain/serialBackspace";
import { buildTelnetDeepLinkConnectionHost } from "../../domain/telnetDeepLink";
import { resolveEffectiveTerminalHost } from "../../domain/terminalHostResolution";
import { resolveEffectiveTerminalHost, resolveTerminalSessionHost } from "../../domain/terminalHostResolution";
import {
createHostTerminalSession,
createSerialTerminalSession,
@@ -171,3 +171,16 @@ test("host session factories snapshot plugin connection configuration", () => {
assert.deepEqual(workspace.pluginConnection, pluginConnection);
assert.notEqual(workspace.pluginConnection, pluginConnection);
});
test("local sessions preserve intentionally absent display metadata when the saved shell changes", () => {
const original = host({ protocol: "local", hostname: "localhost", localShell: "/bin/bash" });
const source = createHostTerminalSession("original-bash", original);
const edited = { ...original, localShell: "/bin/zsh", localShellName: "Zsh", localShellIcon: "zsh" };
const copied = resolveTerminalSessionHost({ session: source, hosts: [edited], groupConfigs: [], proxyProfiles: [], localOs: "macos" });
assert.equal(copied.localShell, "/bin/bash");
assert.equal(copied.localShellName, "");
assert.equal(copied.localShellIcon, "");
const named = createHostTerminalSession("named-zsh", edited);
assert.equal(named.localShellName, "Zsh");
assert.equal(named.localShellIcon, "zsh");
});
+2 -2
View File
@@ -153,8 +153,8 @@ export const createHostTerminalSession = (
// Preserve field presence: an edited host must not contribute its args
// to a session that was launched with an explicit shell and no args.
localShellArgs: host.localShellArgs ?? EMPTY_LOCAL_SHELL_ARGS,
localShellName: host.localShellName,
localShellIcon: host.localShellIcon,
localShellName: host.localShellName ?? "",
localShellIcon: host.localShellIcon ?? "",
// Effective directory from resolveHostDefaultLocalShell, including a
// Settings directory the saved host inherits. Copy Tab overlays this
// snapshot, so a later settings or vault edit cannot move the relaunch.
@@ -148,7 +148,8 @@ test("session peer windows do not run main-window startup effects", () => {
assert.match(settingsStateSource, /const enableSettingsSync = options\.enableSettingsSync !== false/);
assert.match(settingsStateSource, /useSettingsIpcSync\(\{[^}]*enabled: enableSettingsSync/s);
assert.match(settingsStateSource, /useSettingsStorageSync\(\{[^}]*enabled: enableSettingsSync/s);
assert.match(settingsStateSource, /if \(!enableSettingsSync\) return;\s*try \{\s*netcattyBridge\.get\(\)\?\.notifySettingsChanged/s);
// Detached windows share opacity, while general settings broadcasts stay off.
assert.match(settingsStateSource, /if \(!enableSettingsSync && key !== STORAGE_KEY_WINDOW_OPACITY\) return;\s*try \{\s*netcattyBridge\.get\(\)\?\.notifySettingsChanged/s);
assert.match(settingsStateSource, /useSystemSettingsEffects\(\{[^}]*enabled: enableSystemEffects/s);
assert.match(settingsIpcSyncSource, /enabled\?: boolean/);
assert.match(settingsIpcSyncSource, /if \(!enabled\) return;/);
@@ -7,6 +7,55 @@ import { PREFLIGHT_STAT_CONCURRENCY, PREFLIGHT_STAT_MAX_FILES, useSftpTransfers
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
import type { SftpPane } from "./types";
for (const direction of ["download", "upload"] as const) {
test(`failed ${direction} connection replaces Waiting with the actual error (#3698)`, async () => {
let streamStarts = 0;
const restore = installGlobals({
statSftp: async () => ({ type: "file", size: 3626, lastModified: 1758000001000 }),
statLocal: async () => null,
startStreamTransfer: async () => { streamStarts += 1; return {}; },
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
const ownerId = `failed-${direction}-connection-3698`;
function Probe() {
ops = useSftpTransfers({
ownerId,
getActivePane: (side) => makePane(direction === "download" ? side : side === "left" ? "right" : "left"),
getPaneByConnectionId: () => null,
getTabByConnectionId: () => null,
updateTab: () => undefined,
refresh: async () => undefined,
clearCacheForConnection: () => undefined,
handleSessionError: () => undefined,
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
connectionCacheKeyMapRef: { current: new Map() },
listLocalFiles: async () => [],
listRemoteFiles: async () => [],
acquireTransferSession: async () => { throw new Error("SFTP channel open timed out after 10000ms"); },
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
const results = await ops!.startTransfer(
[{ name: "aops_dns_view_demo.sh", isDirectory: false }], "left", "right",
);
assert.equal(results[0]?.status, "failed");
});
const task = sftpTransferCenterStore.getOwnerTasks(ownerId)[0];
assert.equal(task?.status, "failed");
assert.equal(task?.error, "SFTP channel open timed out after 10000ms");
assert.ok(task?.endTime);
assert.equal(streamStarts, 0);
} finally {
await act(async () => { renderer?.unmount(); });
restore();
}
});
}
type StartOptions = {
transferId: string;
sourcePath: string;
@@ -721,7 +721,6 @@ export const useSftpTransfers = ({
}
};
try {
const t0 = performance.now();
logger.debug(`[SFTP:perf] processTransfer START — file=${task.fileName} isDir=${task.isDirectory}`);
@@ -1137,7 +1136,6 @@ export const useSftpTransfers = ({
}
}
return "failed";
}
} finally {
// Walk registry cleanup is owned by transferRuntime.runWalk.
// Drop ephemeral pool holds opened when browse was soft-closed.
@@ -5,6 +5,8 @@ import vm from 'node:vm';
import React, { useCallback, useRef, useSyncExternalStore } from 'react';
import { act, create } from 'react-test-renderer';
import ts from 'typescript';
import { resolveSystemSidebarSession } from '../../domain/systemManager/resolveSystemSession';
import { collectSessionIds } from '../../domain/workspace';
import { getSidePanelLiveSnapshot, subscribeSidePanelLiveSnapshot, sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT, type SidePanelLiveSnapshot } from './sidePanelLiveStore';
// Exercise the production hook without importing the unrelated panel UI modules.
@@ -20,6 +22,60 @@ const useSnapshot = vm.runInNewContext(`${code}; useSidePanelLiveSnapshotForTab`
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
test('workspace browser follows focus without replacing the earlier terminal context', async () => {
const previous = env.IS_REACT_ACT_ENVIRONMENT;
env.IS_REACT_ACT_ENVIRONMENT = true;
const browserSlot = ast.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlot');
assert.ok(browserSlot);
const slotCode = ts.transpile(browserSlot.getText(ast), { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React });
const Slot = vm.runInNewContext(`${slotCode}; SidePanelBrowserSlot`, {
React, useRef, useSidePanelLiveSnapshotForTab: useSnapshot, resolveSystemSidebarSession, collectSessionIds,
sidePanelHiddenPanelClassName: (hidden: boolean) => hidden ? 'hidden' : 'visible',
HostBrowserSidePanel: (props: object) => React.createElement('div', { ...props, 'data-browser-context': true }),
}) as React.ComponentType<{ tabId: string; ctx: object; isVisible: boolean }>;
const sessionA = { id: 'session-a', hostId: 'host-a', protocol: 'ssh' };
const sessionB = { id: 'session-b', hostId: 'host-b', protocol: 'ssh' };
const workspace = { id: 'workspace', focusedSessionId: sessionA.id, root: {
id: 'split', type: 'split', direction: 'vertical', sizes: [0.5, 0.5], children: [
{ id: 'a', type: 'pane', sessionId: sessionA.id }, { id: 'b', type: 'pane', sessionId: sessionB.id },
],
} } as NonNullable<SidePanelLiveSnapshot['activeWorkspace']>;
const ctx = { sessions: [sessionA, sessionB], workspaceById: new Map([['workspace', workspace]]),
sessionHostsMap: new Map([['session-a', { id: 'host-a', hostname: 'a' }], ['session-b', { id: 'host-b', hostname: 'b' }]]),
sftpAuthHostBySessionId: new Map(), effectiveHosts: [], keys: [], identities: [], knownHosts: [], terminalSettings: {}, t: (key: string) => key };
const publish = (session: typeof sessionA) => sidePanelLiveStore.update({ ...SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT,
activeWorkspace: workspace, focusedSessionId: session.id,
activeTerminalSessionForSystem: session as SidePanelLiveSnapshot['activeTerminalSessionForSystem'] });
let renderer: ReturnType<typeof create> | undefined;
try {
publish(sessionA);
await act(async () => { renderer = create(React.createElement(Slot, { tabId: 'workspace', ctx, isVisible: true })); });
const contexts = () => renderer!.root.findAll((node) => node.type === 'div' && node.props['data-browser-context'] === true);
const first = contexts()[0];
assert.equal(first.props.host.id, 'host-a');
await act(async () => publish(sessionB));
assert.equal(contexts().length, 2);
assert.equal(contexts()[0], first, 'the first terminal keeps the same browser mount');
assert.equal(first.props.isVisible, false);
assert.equal(contexts()[1].props.host.id, 'host-b');
assert.equal(contexts()[1].props.isVisible, true);
await act(async () => publish(sessionA));
assert.equal(first.props.isVisible, true);
assert.equal(contexts()[1].props.isVisible, false);
await act(async () => renderer!.update(React.createElement(Slot, { tabId: 'workspace', ctx, isVisible: false })));
assert.ok(contexts().every((context) => !context.props.isVisible), 'hidden tabs hide every native browser context');
ctx.workspaceById.set('workspace', { ...workspace, focusedSessionId: sessionB.id,
root: { id: 'b', type: 'pane', sessionId: sessionB.id } });
await act(async () => renderer!.update(React.createElement(Slot, { tabId: 'workspace', ctx, isVisible: false })));
assert.equal(contexts().length, 1, 'a detached session must leave the old workspace even while it still exists globally');
assert.equal(contexts()[0].props.host.id, 'host-b', 'the remaining workspace browser stays mounted');
} finally {
await act(async () => renderer?.unmount());
sidePanelLiveStore.update(SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT);
env.IS_REACT_ACT_ENVIRONMENT = previous;
}
});
test('returning to a tab never exposes the previous tab snapshot before its publisher catches up', async () => {
const previous = env.IS_REACT_ACT_ENVIRONMENT;
env.IS_REACT_ACT_ENVIRONMENT = true;
+2 -3
View File
@@ -266,9 +266,9 @@ export function useSystemSettingsEffects({
notifySettingsChanged(STORAGE_KEY_HTTP_NETWORK_PROXY, normalized);
}, [enabled, httpNetworkProxy, notifySettingsChanged, persistMountedRef]);
// Persist and sync window opacity
// Window chrome also applies in detached sessions, independently of the
// OS-level effects disabled there (tray, global shortcuts, autolaunch, ...).
useEffect(() => {
if (!enabled) return;
const bridge = netcattyBridge.get();
bridge?.setWindowOpacity?.(windowOpacityRecord.opacity).catch((err) => {
console.warn('[WindowOpacity] Failed to apply window opacity:', err);
@@ -294,7 +294,6 @@ export function useSystemSettingsEffects({
if (!decision.shouldBroadcast) return;
notifySettingsChanged(STORAGE_KEY_WINDOW_OPACITY, windowOpacityRecord);
}, [
enabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
notifySettingsChanged,
@@ -19,6 +19,7 @@ export type TerminalSidePanelTabId = SidePanelTool;
export const TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER: TerminalSidePanelTabId[] = [
'sftp',
'browser',
'scripts',
'history',
'theme',
+11
View File
@@ -18,6 +18,7 @@ import type {
} from '../../infrastructure/ai/types';
import type { ExecutorContext } from '../../infrastructure/ai/cattyAgent/executor';
import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime';
import { stopAgentTurn } from '../../infrastructure/ai/harness/agentStop';
import type {
TurnSteerInput,
TurnSteerResult,
@@ -46,6 +47,16 @@ export function isAIChatSessionStreaming(sessionId: string | null | undefined):
return !!sessionId && sharedStreamingSessionIds.has(sessionId);
}
/** Use the same stop entry and controllers as the UI before replacing history. */
export async function stopAIChatSessionBeforeReplacement(sessionId: string): Promise<void> {
const controller = sharedAbortControllers.get(sessionId);
if (controller || sharedStreamingSessionIds.has(sessionId)) {
await stopAgentTurn({ chatSessionId: sessionId, abortController: controller, bridge: getNetcattyBridge() });
}
await getAgentRuntime().waitForActiveTurn(sessionId);
if (controller && sharedAbortControllers.get(sessionId) === controller) sharedAbortControllers.delete(sessionId);
}
function emitStreamingStoreChange(): void {
streamingSubscribers.forEach(listener => {
try {
+9 -1
View File
@@ -757,7 +757,10 @@ export function useAIState() {
// Non-destructive "undo last turn": branch the session at the boundary
// before the latest user message and keep the original in history intact.
// Returns the new branch id plus the undone user message for the composer.
const undoLastTurnInSession = useCallback(async (sessionId: string): Promise<{
const undoLastTurnInSession = useCallback(async (
sessionId: string,
viewingScope?: Pick<AISessionScope, 'type' | 'targetId'>,
): Promise<{
sessionId: string;
restored: UndoLastTurnRestoredDraft;
} | null> => {
@@ -768,6 +771,11 @@ export function useAIState() {
if (!result) return null;
const branched = result.session;
// Like Fork, Undo belongs to the panel viewing the source, which may have
// resumed a chat from a closed terminal or inherited it after a merge.
if (viewingScope) {
branched.scope = { ...branched.scope, ...viewingScope };
}
setSessionsRaw(prev => {
// Keep both recently used chats within the existing history limit.
const next = [branched, { ...source, updatedAt: branched.updatedAt }, ...prev.filter(session => session.id !== source.id)];
@@ -8,6 +8,7 @@ import type { AISession, UploadedFile } from '../../infrastructure/ai/types.ts';
import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime.ts';
import { useAIState } from './useAIState.ts';
import { useAISessionsStore } from './aiSessionsStore.ts';
import { getSessionScopeMatchRank } from '../../components/ai/sessionScopeMatch.ts';
import { setLatestAISessionsSnapshot } from './aiStateSnapshots.ts';
const SCOPE_KEY = 'terminal:terminal-a';
@@ -192,3 +193,39 @@ for (const newerCount of [49, 50]) {
reloaded.container.remove(); reloaded.dom.window.close();
});
}
for (const viewingScope of [
{ type: 'terminal' as const, targetId: 'terminal-b' },
{ type: 'workspace' as const, targetId: 'workspace-b' },
]) {
test(`undo stays visible when a ${viewingScope.type} views a chat from a closed terminal`, async () => {
const source = {
...structuredClone(SOURCE_SESSION),
scope: { type: 'terminal' as const, targetId: 'terminal-closed', hostIds: ['host-a'] },
};
const { dom, container, root, capture } = await setupAiState([source]);
const sourceBefore = structuredClone(source);
let branchId: string | undefined;
await act(async () => {
capture.ai!.setActiveSessionId('terminal:terminal-b', source.id);
branchId = (await capture.ai!.undoLastTurnInSession(source.id, viewingScope))?.sessionId;
});
assert.ok(branchId);
const branch = capture.sessions.find(item => item.id === branchId)!;
assert.deepEqual(branch.messages, source.messages.slice(0, 2));
assert.deepEqual(branch.scope, { ...source.scope, ...viewingScope });
assert.equal(capture.activeSessionIdMap[`${viewingScope.type}:${viewingScope.targetId}`], branch.id);
// The real history predicate must still include the selected branch after
// the source terminal no longer belongs to the current workspace.
assert.equal(getSessionScopeMatchRank(
branch, viewingScope.type, viewingScope.targetId, ['host-a'],
new Set([branch.id]), new Set(['terminal-b']), new Set([source.id]),
), 3);
const original = capture.sessions.find(item => item.id === source.id)!;
assert.deepEqual({ ...original, updatedAt: sourceBefore.updatedAt }, sourceBefore);
const saved = JSON.parse(dom.window.localStorage.getItem('netcatty_ai_sessions_v1')!) as AISession[];
assert.deepEqual(saved.find(item => item.id === branchId)?.scope, branch.scope);
await act(async () => root.unmount());
container.remove(); dom.window.close();
});
}
@@ -0,0 +1,197 @@
import { installBrowserLockFixture } from "../testSupport/browserLockFixture";
import test from "node:test";
import assert from "node:assert/strict";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { MonitorPanel } from "../../domain/monitorPanels";
import type { CloudProvider, SyncResult, SyncPayload } from "../../domain/sync";
installBrowserLockFixture();
const store = new Map<string, string>();
const storage = {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => {
store.set(key, value);
},
removeItem: (key: string) => {
store.delete(key);
},
};
const events = new EventTarget();
for (const key of [
"addEventListener",
"removeEventListener",
"dispatchEvent",
] as const) {
Object.defineProperty(globalThis, key, {
configurable: true,
value: events[key].bind(events),
});
}
const windowFixture = Object.assign(events, {
localStorage: storage,
CustomEvent,
setInterval,
clearInterval,
});
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: storage,
});
Object.defineProperty(globalThis, "window", {
configurable: true,
value: windowFixture,
});
Object.defineProperty(globalThis, "document", {
configurable: true,
value: Object.assign(new EventTarget(), { visibilityState: "hidden" }),
});
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
const { useAutoSync } = await import("./useAutoSync");
const { getCloudSyncManager } =
await import("../../infrastructure/services/CloudSyncManager");
const { saveMonitorPanel, deleteMonitorPanel, writeMonitorPanels } =
await import("./monitorPanelsStorage");
test("normal manual and debounced auto-sync upload panel creation, edits and deletion", async () => {
const manager = getCloudSyncManager();
const snapshot = {
...manager.getState(),
securityState: "UNLOCKED" as const,
syncState: "IDLE" as const,
autoSyncEnabled: true,
providers: {
...manager.getState().providers,
webdav: { provider: "webdav" as const, status: "connected" as const },
},
};
const uploads: SyncPayload[] = [];
const originals = {
getState: manager.getState,
syncAllProviders: manager.syncAllProviders,
loadSyncBase: manager.loadSyncBase,
inspectProviderRemote: manager.inspectProviderRemote,
setPendingLocalSync: manager.setPendingLocalSync,
setAvailablePluginSyncProviders: manager.setAvailablePluginSyncProviders,
};
manager.getState = () => snapshot;
manager.loadSyncBase = async () => null;
manager.inspectProviderRemote = async () => ({
remoteFile: null,
payload: null,
remoteChanged: false,
});
manager.syncAllProviders = async (payload) => {
uploads.push(structuredClone(payload));
return new Map<CloudProvider, SyncResult>([
["webdav", { provider: "webdav", success: true, action: "upload" }],
]);
};
manager.setPendingLocalSync = () => {};
manager.setAvailablePluginSyncProviders = () => {};
const panel: MonitorPanel = {
id: "p",
name: "Fleet",
description: "",
hostIds: ["h1", "h2"],
view: "charts",
interval: 10,
range: 15,
sort: "manual",
};
let api: ReturnType<typeof useAutoSync> | undefined;
let renderer: ReactTestRenderer | undefined;
const apply = async () => {};
const Probe = () => {
api = useAutoSync({
hosts: [],
keys: [],
snippets: [],
customGroups: ["fixture"],
startupReady: true,
onApplyPayload: apply,
onApplyConvergentPayload: apply,
});
return null;
};
const waitForUpload = async (count: number) => {
// Flush the adapter's batched event, then observe the actual debounced
// upload. Slow CI must not be mistaken for an incomplete collection.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
});
if (uploads.length === count) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 3500));
});
} else {
const deadline = Date.now() + 10000;
while (uploads.length < count && Date.now() < deadline)
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});
}
assert.equal(
uploads.length,
count,
"a panel-only change must alter the auto-sync hash and upload",
);
};
try {
writeMonitorPanels([
{ ...panel, stats: { cpu: 42 }, points: [1], running: true },
]);
await act(async () => {
renderer = create(React.createElement(Probe));
});
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});
await act(async () => {
assert.equal(await api!.syncNow({ trigger: "manual" }), true);
});
assert.deepEqual(uploads[0].monitorPanels, [panel]);
const renamed = { ...panel, name: "Renamed" };
await act(async () => {
await saveMonitorPanel(panel, renamed);
});
await waitForUpload(2);
assert.deepEqual(uploads[1].monitorPanels, [renamed]);
const edited = {
...renamed,
hostIds: ["h2"],
view: "list" as const,
interval: 30 as const,
};
await act(async () => {
await saveMonitorPanel(renamed, edited);
});
await waitForUpload(3);
assert.deepEqual(uploads[2].monitorPanels, [edited]);
await act(async () => {
await deleteMonitorPanel(panel.id);
});
await waitForUpload(4);
assert.deepEqual(uploads[3].monitorPanels, []);
await act(async () => {
await saveMonitorPanel(null, panel);
});
await waitForUpload(5);
assert.deepEqual(uploads[4].monitorPanels, [panel]);
assert.ok(
uploads.every((p) => !JSON.stringify(p.monitorPanels).includes("stats")),
);
await act(async () => {
await saveMonitorPanel(panel, panel);
});
await waitForUpload(5);
} finally {
await act(async () => {
renderer?.unmount();
});
Object.assign(manager, originals);
}
});
+33 -3
View File
@@ -1,3 +1,5 @@
import { readMonitorPanels } from './monitorPanelsStorage';
import { STORAGE_KEY_MONITOR_PANELS } from '../../infrastructure/config/storageKeys';
/**
* useAutoSync - Auto-sync Hook for Cloud Sync
*
@@ -21,12 +23,14 @@ import { isProviderReadyForSync, SYNC_STORAGE_KEYS, type CloudProvider, type Syn
import { mergeSyncPayloads } from '../../domain/syncMerge';
import { materializeSyncPayloadFromConvergentState } from '../../domain/convergentSync';
import {
isPreserveDeletionsStrategy,
resolveCloudSyncConflictAction,
type CloudSyncConflictAction,
} from '../../domain/syncStrategy';
import {
SYNCABLE_SETTING_STORAGE_KEYS,
collectCloudSyncableSettings,
collectAiSessionsForSync,
getEffectivePortForwardingRulesForSync,
hasCloudSyncEntityData,
hasMeaningfulCloudSyncData,
@@ -38,6 +42,8 @@ import { commitPluginSidecarsAfterSuccessfulSync } from '../pluginSyncSidecarBri
import { readInterruptedVaultApply } from '../localVaultBackups';
import {
STORAGE_KEY_VAULT_RESTORE_IN_PROGRESS_UNTIL,
STORAGE_KEY_AI_SESSIONS,
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
} from '../../infrastructure/config/storageKeys';
import {
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
@@ -51,6 +57,7 @@ import {
} from './autoSyncRemoteSchedule';
import { resolveAutoSyncHashDecision } from './autoSyncHashDecision';
import { getNotesSnapshot, subscribeNotes } from './notesStore';
import { collectHostBrowserBookmarks } from '../hostBrowserBookmarks';
/** Prefer dedicated SYNC_PREFERENCES; fall back to legacy SYNC_CONFIG fields. */
function isPersistedAutoSyncEnabled(fallback: boolean): boolean {
@@ -146,6 +153,7 @@ const isRestoreInProgress = (): boolean => {
const getSyncPayloadDataHash = (payload: SyncPayload): string => {
return JSON.stringify({
monitorPanels: payload.monitorPanels,
hosts: sanitizeHostsForSync(payload.hosts),
keys: payload.keys,
identities: payload.identities,
@@ -156,9 +164,11 @@ const getSyncPayloadDataHash = (payload: SyncPayload): string => {
notes: payload.notes,
noteGroups: payload.noteGroups,
portForwardingRules: sanitizePortForwardingRulesForSync(payload.portForwardingRules),
browserBookmarks: payload.browserBookmarks,
groupConfigs: payload.groupConfigs,
settings: payload.settings,
pluginSidecars: payload.pluginSidecars,
aiSessions: payload.aiSessions,
});
};
@@ -219,6 +229,13 @@ export const useAutoSync = (config: AutoSyncConfig) => {
// Listen for SFTP bookmark changes to trigger auto-sync
const [bookmarksVersion, setBookmarksVersion] = useState(0);
const [hostBrowserBookmarksVersion, setHostBrowserBookmarksVersion] = useState(0);
useEffect(() => {
const unsubscribe = netcattyBridge.get()?.onHostBrowserBookmarksChanged?.(() => {
setHostBrowserBookmarksVersion((version) => version + 1);
});
return () => { unsubscribe?.(); };
}, []);
useEffect(() => {
const handler = () => setBookmarksVersion((v) => v + 1);
window.addEventListener('sftp-bookmarks-changed', handler);
@@ -243,7 +260,11 @@ export const useAutoSync = (config: AutoSyncConfig) => {
const [syncableSettingsStorageVersion, setSyncableSettingsStorageVersion] = useState(0);
useEffect(() => {
const bumpIfSyncableSetting = (key: string | null | undefined) => {
if (!key || !SYNCABLE_SETTING_STORAGE_KEY_SET.has(key)) return;
if (!key) return;
const chatChanged = key === STORAGE_KEY_AI_SESSIONS
&& localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
if (!SYNCABLE_SETTING_STORAGE_KEY_SET.has(key)
&& key !== STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS && key !== STORAGE_KEY_MONITOR_PANELS && !chatChanged) return;
setSyncableSettingsStorageVersion((v) => v + 1);
};
@@ -265,6 +286,7 @@ export const useAutoSync = (config: AutoSyncConfig) => {
const getSyncSnapshot = useCallback(() => {
return {
monitorPanels: readMonitorPanels(),
hosts: sanitizeHostsForSync(config.hosts),
keys: config.keys,
identities: config.identities,
@@ -299,8 +321,12 @@ export const useAutoSync = (config: AutoSyncConfig) => {
const buildPayload = useCallback(async (): Promise<SyncPayload> => {
const { withPluginSyncSidecars } = await import('../syncPayload');
const { collectPluginSyncSidecarsFromHost } = await import('../pluginSyncSidecarBridge');
const aiSessions = collectAiSessionsForSync();
const browserBookmarks = await collectHostBrowserBookmarks();
const base: SyncPayload = {
...getSyncSnapshot(),
...(aiSessions !== undefined ? { aiSessions } : {}),
...(browserBookmarks !== undefined ? { browserBookmarks } : {}),
settings: await collectCloudSyncableSettings(),
syncedAt: Date.now(),
};
@@ -781,7 +807,7 @@ export const useAutoSync = (config: AutoSyncConfig) => {
}
const conflictAction = resolveCloudSyncConflictAction(state.syncStrategy, {
hasConflict: inspection.remoteChanged,
hasConflict: inspection.remoteChanged || isPreserveDeletionsStrategy(state.syncStrategy),
hasRemoteFile: Boolean(inspection.remoteFile),
});
@@ -850,7 +876,9 @@ export const useAutoSync = (config: AutoSyncConfig) => {
// upload and wipe usable cloud passwords. Same for remote-side poison.
const localHealed = healPoisonedSecretsForMerge(localPayload, remoteRaw, base);
const remoteHealed = healPoisonedSecretsForMerge(remoteRaw, localPayload, base);
const mergeResult = mergeSyncPayloads(base, localHealed, remoteHealed);
const mergeResult = mergeSyncPayloads(base, localHealed, remoteHealed, {
preserveDeletions: isPreserveDeletionsStrategy(state.syncStrategy),
});
// Apply merged payload to local state BEFORE committing. If the apply
// throws, the next startup will re-run the merge with fresh data.
@@ -1112,6 +1140,7 @@ export const useAutoSync = (config: AutoSyncConfig) => {
config.settingsVersion,
enabled,
bookmarksVersion,
hostBrowserBookmarksVersion,
pluginSidecarsVersion,
convergentSyncPaused,
syncableSettingsStorageVersion,
@@ -1129,6 +1158,7 @@ export const useAutoSync = (config: AutoSyncConfig) => {
config.settingsVersion,
enabled,
bookmarksVersion,
hostBrowserBookmarksVersion,
pluginSidecarsVersion,
syncableSettingsStorageVersion,
]);
+40
View File
@@ -28,6 +28,8 @@ import {
isProviderReadyForSync,
} from '../../domain/sync';
import type { CloudSyncStrategy } from '../../domain/syncStrategy';
import { LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import { STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS } from '../../infrastructure/config/storageKeys';
import type { CloudSyncConflictAction } from '../../domain/syncStrategy';
import {
getCloudSyncManager,
@@ -173,6 +175,9 @@ export interface CloudSyncHook {
setAutoSync: (enabled: boolean, intervalMinutes?: number) => void;
setDeviceName: (name: string) => void;
setSyncStrategy: (strategy: CloudSyncStrategy) => void;
/** Whether AI chat sessions are included in cloud sync payloads (opt-in). */
aiSessionsSyncEnabled: boolean;
setAiSessionsSyncEnabled: (enabled: boolean) => Promise<void>;
setConvergentSyncEnabled: (enabled: boolean) => ConvergentSyncLocalConfig;
refreshConvergentSyncConfig: () => ConvergentSyncLocalConfig;
@@ -249,6 +254,25 @@ const getSnapshot = (): SyncManagerState => {
return manager.getState();
};
function readAiSessionsSyncEnabled(): boolean {
return localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
}
function subscribeAiSessionsSyncEnabled(listener: () => void): () => void {
const storage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS || event.key === null) listener();
};
const local = (event: Event) => {
if ((event as CustomEvent<{ key?: string }>).detail?.key === STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS) listener();
};
window.addEventListener('storage', storage);
window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, local);
return () => {
window.removeEventListener('storage', storage);
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, local);
};
}
export const useCloudSync = (): CloudSyncHook => {
// Use useSyncExternalStore for real-time state sync across all components
const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
@@ -724,6 +748,19 @@ export const useCloudSync = (): CloudSyncHook => {
manager.setDeviceName(name);
}, []);
const aiSessionsSyncEnabled = useSyncExternalStore(
subscribeAiSessionsSyncEnabled, readAiSessionsSyncEnabled, readAiSessionsSyncEnabled,
);
const setAiSessionsSyncEnabled = useCallback(async (enabled: boolean) => {
const { setAiSessionsSyncPreference } = await import('../syncPayload');
await setAiSessionsSyncPreference(enabled, async () => {
const providers = Object.entries(manager.getAllProviders())
.filter(([, connection]) => isProviderReadyForSync(connection));
const remotes = await Promise.all(providers.map(([provider]) => manager.downloadFromProvider(provider as CloudProvider)));
return remotes.filter((remote) => remote !== null).map((remote) => remote.payload);
}, manager.getState().syncStrategy === 'smartMergePreserve');
}, []);
const setSyncStrategy = useCallback((strategy: CloudSyncStrategy) => {
manager.setSyncStrategy(strategy);
}, []);
@@ -864,6 +901,7 @@ export const useCloudSync = (): CloudSyncHook => {
}
return manager.resolveConvergentConflict(addressKey, candidateDot, applyPayload, {
pluginSidecars,
aiSessions: (await import('../syncPayload')).collectAiSessionsForSync(),
});
}, [ensureUnlocked]);
@@ -956,6 +994,8 @@ export const useCloudSync = (): CloudSyncHook => {
setAutoSync,
setDeviceName,
setSyncStrategy,
aiSessionsSyncEnabled,
setAiSessionsSyncEnabled,
setConvergentSyncEnabled,
refreshConvergentSyncConfig,
+33 -1
View File
@@ -3,7 +3,11 @@ import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { useComposeBarHistory } from './useComposeBarHistory';
import { pruneComposeBarHistory, recordComposeBarHistory } from './composeBarHistoryStore';
import {
clearComposeBarHistory,
pruneComposeBarHistory,
recordComposeBarHistory,
} from './composeBarHistoryStore';
test('changing workspace focus resets navigation without replacing the draft', async () => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -47,3 +51,31 @@ test('an in-progress history walk stays stable when a late send evicts the oldes
await act(async () => { root.unmount(); });
pruneComposeBarHistory([]);
});
test('clearing history restores the pre-walk draft instead of leaving the recalled command', async () => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
pruneComposeBarHistory([]);
recordComposeBarHistory('a', 'deleted-command');
const restoredDrafts: string[] = [];
let history!: ReturnType<typeof useComposeBarHistory>;
function Harness() {
history = useComposeBarHistory('a', (draft) => { restoredDrafts.push(draft); });
return null;
}
let root!: ReactTestRenderer;
await act(async () => { root = create(React.createElement(Harness)); });
// Enter a history walk: the textarea now shows the recalled command while the
// hook holds the pre-walk draft.
assert.equal(history.navigate('my unsent draft', 'up'), 'deleted-command');
clearComposeBarHistory();
// The pre-walk draft is put back, so the deleted command is no longer in the
// textarea ready for Enter.
assert.deepEqual(restoredDrafts, ['my unsent draft']);
assert.equal(history.navigate('my unsent draft', 'up'), undefined);
await act(async () => { root.unmount(); });
pruneComposeBarHistory([]);
});
+24 -2
View File
@@ -1,6 +1,10 @@
import { useCallback, useLayoutEffect, useRef } from 'react';
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
import { navigateComposeBarHistory, type ComposeBarHistoryDirection } from '../../domain/composeBarHistory';
import { getComposeBarHistory, createComposeBarHistoryRecorder } from './composeBarHistoryStore';
import {
getComposeBarHistory,
createComposeBarHistoryRecorder,
subscribeComposeBarHistoryCleared,
} from './composeBarHistoryStore';
export function useComposeBarHistory(sessionId: string, restoreDraft?: (draft: string) => void) {
const cursor = useRef<{ index: number; draft: string; entries?: readonly string[] }>({ index: Infinity, draft: '' });
@@ -16,6 +20,24 @@ export function useComposeBarHistory(sessionId: string, restoreDraft?: (draft: s
reset();
}, [reset, restoreDraft, sessionId]);
/**
* Restore the pre-walk draft and drop the cached history walk.
*
* While the user is in an ArrowUp walk the textarea shows the recalled
* command, so resetting the cursor alone would leave a deleted command ready
* for Enter. Put the saved draft back first, exactly like the session-change
* path above.
*/
const handleHistoryCleared = useCallback(() => {
if (cursor.current.entries) restoreDraft?.(cursor.current.draft);
reset();
}, [reset, restoreDraft]);
useEffect(
() => subscribeComposeBarHistoryCleared(handleHistoryCleared),
[handleHistoryCleared],
);
const prepareRecord = useCallback(() => createComposeBarHistoryRecorder(sessionId), [sessionId]);
const navigate = useCallback((currentValue: string, direction: ComposeBarHistoryDirection) => {
+1
View File
@@ -39,6 +39,7 @@ export const getAppLevelActions = (): Set<string> => {
'togglePaneZoom',
'openLocal',
'openSettings',
'toggleOpacity',
]);
};
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { currentBrowserThemeTokens, mountHostBrowser } from '../hostBrowser';
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings } from '../../domain/models';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
interface BrowserPanelOptions {
browserId: string;
host: Host;
hosts: Host[];
keys: SSHKey[];
identities: Identity[];
knownHosts: KnownHost[];
terminalSettings: TerminalSettings;
isVisible: boolean;
}
export function useHostBrowserPanel(options: BrowserPanelOptions) {
const elementRef = useRef<HTMLDivElement>(null);
const optionsRef = useRef(options);
optionsRef.current = options;
const opened = useRef(false);
const mountedBrowserId = useRef<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
const { browserId, isVisible } = options;
useLayoutEffect(() => {
const bridge = netcattyBridge.get();
let frame = 0;
let previous = '';
const update = () => {
const element = elementRef.current;
const rect = element?.getBoundingClientRect();
// Native page views must leave the screen with their owning pane and
// must not cover a renderer dialog or a toolbar's open menu.
const covered = !!document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"][data-state="open"], [data-radix-popper-content-wrapper]');
const visible = isVisible && !!element?.isConnected && !!rect
&& rect.width > 0 && rect.height > 0 && !element?.closest('[inert]') && !covered;
const bounds = rect ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : undefined;
const theme = element && getComputedStyle(element).colorScheme === 'light' ? 'light' : 'dark';
const themeTokens = currentBrowserThemeTokens(element ?? undefined);
const next = JSON.stringify({ browserId, visible, bounds, theme, themeTokens });
if (next !== previous) {
previous = next;
void bridge?.setHostBrowserPanelLayout?.({ browserId, visible, bounds, theme, themeTokens }).catch(() => {});
}
if (isVisible) frame = requestAnimationFrame(update);
};
update();
return () => {
cancelAnimationFrame(frame);
void bridge?.setHostBrowserPanelLayout?.({ browserId, visible: false }).catch(() => {});
};
}, [browserId, isVisible]);
useEffect(() => {
if (!isVisible || opened.current) return;
opened.current = true;
setError(null);
let cancelled = false;
void mountHostBrowser({ ...optionsRef.current, browserId }).catch((reason: unknown) => {
opened.current = false;
if (cancelled) return;
setError(reason instanceof Error ? reason.message : String(reason));
});
return () => { cancelled = true; };
}, [attempt, browserId, isVisible]);
useEffect(() => {
mountedBrowserId.current = browserId;
return () => {
opened.current = false;
mountedBrowserId.current = null;
// StrictMode replays setup immediately. Do not destroy its pending URL
// or native browser unless the owning panel actually remains unmounted.
queueMicrotask(() => {
if (mountedBrowserId.current === browserId) return;
void netcattyBridge.get()?.closeHostBrowserPanel?.(browserId).catch(() => {});
});
};
}, [browserId]);
return { elementRef, error, retry: () => setAttempt((value) => value + 1) };
}
@@ -0,0 +1,61 @@
import { useEffect, useRef, useState } from "react";
import { useAppVaultRuntime } from "./appRuntimeBridge";
import { useMonitorSnapshot } from "./monitorRuntimeStore";
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
import {
createKnownHostFromHostKeyInfo,
upsertKnownHost,
} from "../../domain/knownHosts";
import { toHostKeyInfo } from "../../domain/hostKey";
type Request = Parameters<
Parameters<NonNullable<NetcattyBridge["onHostKeyVerification"]>>[0]
>[0];
export function useMonitorHostKeyVerification() {
const { knownHosts, updateKnownHosts } = useAppVaultRuntime();
const [request, setRequest] = useState<Request | null>(null);
const snapshot = useMonitorSnapshot();
const receivedAt = useRef(0);
useEffect(
() =>
netcattyBridge.get()?.onHostKeyVerification?.((r) => {
if (r.sessionId?.startsWith("monitor-")) {
receivedAt.current = Date.now();
setRequest(r);
}
}),
[],
);
const respond = (accept: boolean, save = false) => {
if (!request) return;
if (accept && save)
updateKnownHosts(
upsertKnownHost(
knownHosts,
createKnownHostFromHostKeyInfo(toHostKeyInfo(request)),
),
);
void netcattyBridge
.get()
?.respondHostKeyVerification?.(request.requestId, accept, save);
setRequest(null);
};
useEffect(() => {
if (
request &&
snapshot.takenAt >= receivedAt.current &&
(!snapshot.running.length ||
!snapshot.activeSessions.includes(request.sessionId ?? ""))
) {
void netcattyBridge
.get()
?.respondHostKeyVerification?.(request.requestId, false, false);
setRequest(null);
}
}, [
request,
snapshot.running.length,
snapshot.takenAt,
snapshot.activeSessions,
]);
return { request, respond };
}
+198
View File
@@ -0,0 +1,198 @@
import { hostRestrictsExtraSshChannels } from "../../domain/host";
import { useEffect, useRef, useState } from "react";
import { buildHostConnectionTestPlan } from "../../domain/hostConnectionTest";
import { resolveEffectiveTerminalHost } from "../../domain/terminalHostResolution";
import { getEffectiveKnownHosts } from "../../infrastructure/syncHelpers";
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
import {
useAppLockChrome,
useAppSettingsRuntime,
useAppVaultRuntime,
} from "./appRuntimeBridge";
import { useMonitorPanels } from "./monitorPanelsStorage";
import {
monitorActions,
getMonitorHistoryCursor,
publishMonitorSnapshot,
publishMonitorUnavailable,
} from "./monitorRuntimeStore";
import type { MonitorPanelDemand } from "../../domain/monitorRuntime";
/** Root lifetime, independent of Vault navigation. No runtime state is persisted. */
export function useMonitorRuntime() {
const panels = useMonitorPanels();
const {
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts,
isInitialized,
} = useAppVaultRuntime();
const { terminalSettings } = useAppSettingsRuntime();
const { locked } = useAppLockChrome();
const [running, setRunning] = useState(() => new Map<string, string>());
const [retryVersion, setRetryVersion] = useState(0);
const epoch = useRef<number | null>(null);
const runtimeId = useRef<string | null>(null);
const credentials = useRef(
new Map<string, { username: string; password: string }>(),
);
useEffect(() => {
monitorActions.start = (id) =>
setRunning((prev) => new Map(prev).set(id, crypto.randomUUID()));
monitorActions.stop = (id) =>
setRunning((prev) => {
const next = new Map(prev);
next.delete(id);
return next;
});
monitorActions.stopAll = () => {
credentials.current.clear();
setRunning(new Map());
void netcattyBridge.get()?.monitorStopAll?.();
};
monitorActions.retry = (id, override) => {
if (override) credentials.current.set(id, override);
void netcattyBridge
.get()
?.monitorRetry?.(id)
.then(() => setRetryVersion((v) => v + 1));
};
const offline = () => monitorActions.stopAll();
window.addEventListener("offline", offline);
return () => {
window.removeEventListener("offline", offline);
void netcattyBridge.get()?.monitorUpdate?.([]);
};
}, []);
useEffect(() => {
if (locked || !isInitialized) {
credentials.current.clear();
setRunning(new Map());
}
}, [locked, isInitialized]);
useEffect(() => {
const bridge = netcattyBridge.get();
if (!bridge?.monitorUpdate) {
publishMonitorUnavailable();
return;
}
const demand: MonitorPanelDemand[] =
locked || !isInitialized
? []
: panels
.filter((p) => running.has(p.id))
.map((panel) => ({
id: panel.id,
runId: running.get(panel.id)!,
interval: panel.interval,
hosts: panel.hostIds.map((id) => {
const host = hosts.find((h) => h.id === id);
if (
!host ||
(host.protocol && host.protocol !== "ssh") ||
hostRestrictsExtraSshChannels(host)
)
return { id };
const effective = resolveEffectiveTerminalHost({
host,
groupConfigs,
proxyProfiles,
});
const plan = buildHostConnectionTestPlan({
host,
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts: getEffectiveKnownHosts(knownHosts) ?? [],
terminalSettings,
sessionId: `monitor-${id}`,
bootEpoch: 0,
authOverride: credentials.current.has(id)
? { ...credentials.current.get(id), authMethod: "password" }
: null,
});
if (!plan.ok) return { id, status: "error" as const };
if (plan.needsCredentialReentry)
return { id, status: "login" as const };
return {
id,
options: {
...plan.options,
singleChannelSsh: hostRestrictsExtraSshChannels(effective),
sshAuthReadyTimeoutMs: 120000,
agentForwarding: effective.agentForwarding,
},
};
}),
}));
const activeHostIds = new Set(
demand.flatMap((p) => p.hosts.map((h) => h.id)),
);
for (const id of credentials.current.keys())
if (!activeHostIds.has(id)) credentials.current.delete(id);
void bridge
.monitorUpdate(demand)
.then(publishMonitorSnapshot)
.catch(() => {
credentials.current.clear();
setRunning((prev) => (prev.size ? new Map() : prev));
publishMonitorUnavailable();
});
}, [
panels,
running,
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts,
terminalSettings,
locked,
isInitialized,
retryVersion,
]);
useEffect(() => {
const bridge = netcattyBridge.get();
let disposed = false;
let pending = false;
const poll = async () => {
if (pending || !bridge?.monitorSnapshot) return;
pending = true;
try {
const snapshot = await bridge.monitorSnapshot(getMonitorHistoryCursor());
if (disposed) return;
if (
(epoch.current !== null && epoch.current !== snapshot.epoch) ||
(runtimeId.current !== null &&
runtimeId.current !== snapshot.runtimeId)
) {
credentials.current.clear();
setRunning(new Map());
}
epoch.current = snapshot.epoch;
runtimeId.current = snapshot.runtimeId;
publishMonitorSnapshot(snapshot);
} catch {
credentials.current.clear();
setRunning((prev) => (prev.size ? new Map() : prev));
publishMonitorUnavailable();
} finally {
pending = false;
}
};
void poll();
const timer = setInterval(() => {
void poll();
}, 1000);
return () => {
disposed = true;
clearInterval(timer);
};
}, []);
}
+41 -5
View File
@@ -141,7 +141,6 @@ import {
DEFAULT_TERMINAL_THEME,
DEFAULT_THEME,
DEFAULT_WINDOW_OPACITY,
clampWindowOpacity,
applyThemeTokens,
areTerminalSettingsEqual,
createCustomKeyBindingsSyncOrigin,
@@ -180,6 +179,8 @@ import {
import {
parseWindowOpacityRecord,
shouldApplyWindowOpacityRecord,
updateWindowOpacityRecord,
toggleWindowOpacityRecord,
type WindowOpacityMutationSource,
type WindowOpacityRecord,
} from './windowOpacitySync';
@@ -608,9 +609,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const candidate = typeof nextValue === 'function'
? (nextValue as (prevState: number) => number)(prev.opacity)
: nextValue;
const nextOpacity = clampWindowOpacity(candidate);
if (nextOpacity === prev.opacity) return prev;
return { opacity: nextOpacity, version: prev.version + 1 };
return updateWindowOpacityRecord(prev, candidate);
});
}, []);
const applyIncomingWindowOpacity = useCallback((raw: unknown) => {
@@ -625,6 +624,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
return incoming;
});
}, []);
const toggleWindowOpacity = useCallback(() => {
windowOpacityMutationSourceRef.current = 'local';
setWindowOpacityRecord(toggleWindowOpacityRecord);
}, []);
const [appIconVariant, setAppIconVariantState] = useState<AppIconVariant>(() => {
const stored = readStoredString(STORAGE_KEY_APP_ICON_VARIANT);
return resolveAppIconVariant(stored ?? DEFAULT_APP_ICON_VARIANT);
@@ -785,7 +788,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
// Helper to notify other windows about settings changes via IPC
const notifySettingsChanged = useCallback((key: string, value: unknown) => {
if (!enableSettingsSync) return;
if (!enableSettingsSync && key !== STORAGE_KEY_WINDOW_OPACITY) return;
try {
netcattyBridge.get()?.notifySettingsChanged?.({ key, value });
} catch {
@@ -1241,6 +1244,38 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setSshTransportIdleTtlMsState,
});
// Detached sessions share opacity and the shortcut configuration needed to
// operate it. Keep general settings listeners and OS effects disabled there.
useEffect(() => {
if (enableSettingsSync) return;
const applySharedWindowSetting = (key: string, value: unknown) => {
if (key === STORAGE_KEY_WINDOW_OPACITY) applyIncomingWindowOpacity(value);
if (key === STORAGE_KEY_HOTKEY_SCHEME && (value === 'disabled' || value === 'mac' || value === 'pc')) {
setHotkeyScheme(value);
}
if (key === STORAGE_KEY_CUSTOM_KEY_BINDINGS) {
const incoming = parseCustomKeyBindingsStorageRecord(value);
if (incoming) applyIncomingCustomKeyBindings(incoming);
}
if (key === STORAGE_KEY_HOTKEY_RECORDING && typeof value === 'boolean') {
setIsHotkeyRecordingState(value);
}
};
const unsubscribe = netcattyBridge.get()?.onSettingsChanged?.(({ key, value }) => {
applySharedWindowSetting(key, value);
});
const onStorage = (event: StorageEvent) => {
if (event.key !== null && event.newValue !== null) {
applySharedWindowSetting(event.key, event.newValue);
}
};
window.addEventListener('storage', onStorage);
return () => {
unsubscribe?.();
window.removeEventListener('storage', onStorage);
};
}, [enableSettingsSync, applyIncomingWindowOpacity, applyIncomingCustomKeyBindings]);
useEffect(() => {
if (!enableSettingsSync) return;
const bridge = netcattyBridge.get();
@@ -2183,6 +2218,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setGlobalHotkeyEnabled,
windowOpacity,
setWindowOpacity,
toggleWindowOpacity,
appIconVariant,
setAppIconVariant,
rehydrateAllFromStorage,
@@ -483,3 +483,73 @@ for (const phase of ["snapshot", "commit"] as const) {
assert.equal(commits, phase === "snapshot" ? 0 : 1);
});
}
for (const mixedSelection of [false, true]) {
test(`group deletion prunes host and inherited chains, mixed selection: ${mixedSelection}`, async () => {
const actEnvironment = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
};
const previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
const storedHosts = [
{ id: "jump", group: "A", label: "jump", hostname: "j.example.com", port: 22, username: "root", protocol: "ssh" as const, tags: [], os: "linux" as const },
{ id: "survivor", group: "B", label: "survivor", hostname: "s.example.com", port: 22, username: "root", protocol: "ssh" as const, tags: [], os: "linux" as const, hostChain: { hostIds: ["jump"] } },
{ id: "extra", group: "B", label: "extra", hostname: "e.example.com", username: "root", tags: [], os: "linux" as const },
{ id: "kept", group: "B", label: "kept", hostname: "k.example.com", username: "root", tags: [], os: "linux" as const },
];
const configs: GroupConfig[] = [{ path: "B", hostChain: { hostIds: ["jump", "extra", "kept"] } }];
let deleteGroups: ReturnType<typeof useVaultGroupDeletion> | undefined;
let renderer: ReactTestRenderer | null = null;
let committedHosts: Array<{ id: string; hostChain?: { hostIds: string[] } }> = [];
let committedConfigs: GroupConfig[] = [];
const Probe = () => {
deleteGroups = useVaultGroupDeletion({
customGroups: ["A", "B"],
hosts: storedHosts,
groupConfigs: configs,
managedSources: [],
onReadPersistedHosts: async () => storedHosts,
onReadPersistedManagedSources: () => [],
onCommitVaultGroupMutation: async (mutate) => {
const result = mutate({
groups: ["A", "B"],
configs,
hosts: storedHosts,
managedSources: [],
snippets: [],
});
if (result.ok) {
committedHosts = result.state.hosts;
committedConfigs = result.state.configs;
}
return result;
},
});
return null;
};
try {
await act(async () => {
renderer = create(React.createElement(Probe));
});
await act(async () => {
await deleteGroups?.(["A"], true, new Set(mixedSelection ? ["extra"] : []));
});
} finally {
await act(async () => {
renderer?.unmount();
});
actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
assert.deepEqual(committedHosts.map(({ id, hostChain }) => ({ id, hostChain })), [
{ id: "survivor", hostChain: { hostIds: [] } },
...(!mixedSelection ? [{ id: "extra", hostChain: undefined }] : []),
{ id: "kept", hostChain: undefined },
]);
assert.deepEqual(committedConfigs[0].hostChain,
{ hostIds: mixedSelection ? ["kept"] : ["extra", "kept"] });
});
}
+21 -4
View File
@@ -3,6 +3,7 @@ import { useCallback, useRef } from "react";
import type { GroupConfig, Host, ManagedSource } from "../../domain/models";
import { removeSnippetTargetGroupPaths } from "../../domain/hostGroupPathMutations";
import { buildVaultGroupDeletion } from "../../domain/vaultGroupDeletion";
import { pruneVaultJumpHostReferences } from "../../domain/vaultJumpGraph";
import type {
VaultGroupMutationResult,
VaultGroupMutationState,
@@ -155,14 +156,30 @@ export function useVaultGroupDeletion({
)) {
throw RETRY_VAULT_GROUP_DELETION;
}
const nextTransactionHosts = currentDeletion.hosts.filter(
(host) => !additionallyDeletedHostIds.has(host.id),
);
// Hosts removed by this transaction must stop being referenced
// from other hosts' jump chains (and group config chains), or
// those targets keep failing with "A configured jump host is
// missing".
const retainedHostIds = new Set(
nextTransactionHosts.map((host) => host.id),
);
const removedHostIds = current.hosts
.filter((host) => !retainedHostIds.has(host.id))
.map((host) => host.id);
const prunedReferences = pruneVaultJumpHostReferences({
hosts: nextTransactionHosts,
groupConfigs: currentDeletion.groupConfigs,
removedHostIds,
});
return {
ok: true,
state: {
groups: currentDeletion.customGroups,
hosts: currentDeletion.hosts.filter(
(host) => !additionallyDeletedHostIds.has(host.id),
),
configs: currentDeletion.groupConfigs,
hosts: prunedReferences.hosts,
configs: prunedReferences.groupConfigs,
managedSources: current.managedSources.filter(
(source) => !currentDeletion.sourcesToRemove.some(
(removed) => removed.id === source.id,
@@ -0,0 +1,103 @@
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 { Host } from '../../domain/models';
import type { VaultGroupMutationState } from '../../domain/vaultGroupMutation';
import { useVaultHostDeletion } from './useVaultHostDeletion';
import { commitVaultGroupMutationPersistence } from './vaultGroupMutationPersistence';
import {
STORAGE_KEY_GROUP_CONFIGS,
STORAGE_KEY_HOSTS,
} from '../../infrastructure/config/storageKeys';
const host = (id: string, hostIds?: string[]): Host => ({
id, label: id, hostname: `${id}.test`, username: 'root', tags: [], os: 'linux',
...(hostIds ? { hostChain: { hostIds } } : {}),
});
async function withDeletion(
commit: Parameters<typeof useVaultHostDeletion>[0],
run: (remove: ReturnType<typeof useVaultHostDeletion>) => Promise<void>,
) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
let remove!: ReturnType<typeof useVaultHostDeletion>;
let renderer: ReactTestRenderer | undefined;
function Probe() {
remove = useVaultHostDeletion(commit);
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await run(remove);
} finally {
await act(async () => { renderer?.unmount(); });
environment.IS_REACT_ACT_ENVIRONMENT = previous;
}
}
for (const removed of [['jump'], ['jump', 'extra']]) {
test(`host deletion cleans latest host and group references together: ${removed.join(',')}`, async () => {
const latest: VaultGroupMutationState = {
hosts: [host('jump'), host('extra'), host('kept'), host('target', ['jump', 'kept'])],
configs: [{ path: 'prod', username: 'latest-user', hostChain: { hostIds: ['jump'] } }],
groups: ['prod'], managedSources: [], snippets: [],
};
let committed: VaultGroupMutationState | undefined;
await withDeletion(async (mutate) => {
const result = mutate(latest);
if (result.ok) committed = result.state;
return result;
}, async (remove) => { await act(async () => { await remove(removed); }); });
assert.ok(committed);
assert.deepEqual(committed.hosts.map((item) => item.id),
removed.length === 1 ? ['extra', 'kept', 'target'] : ['kept', 'target']);
assert.deepEqual(committed.hosts.at(-1)?.hostChain, { hostIds: ['kept'] });
assert.deepEqual(committed.configs[0], {
path: 'prod', username: 'latest-user', hostChain: { hostIds: [] },
});
assert.equal(committed.snippets, latest.snippets);
assert.deepEqual(latest.hosts.at(-1)?.hostChain, { hostIds: ['jump', 'kept'] });
});
}
test('a failed group-config write rolls host deletion back and reports failure', async () => {
const original = {
[STORAGE_KEY_HOSTS]: [host('jump'), host('target', ['jump'])],
[STORAGE_KEY_GROUP_CONFIGS]: [{ path: 'prod', hostChain: { hostIds: ['jump'] } }],
};
const values = new Map(Object.entries(original).map(([key, value]) => [key, JSON.stringify(value)]));
const storage = {
read: <T,>(key: string): T | null => JSON.parse(values.get(key) ?? 'null'),
readString: (key: string) => values.get(key) ?? null,
write: <T,>(key: string, value: T) => {
if (key === STORAGE_KEY_GROUP_CONFIGS) return false;
values.set(key, JSON.stringify(value));
return true;
},
writeString: (key: string, value: string) => { values.set(key, value); return true; },
remove: (key: string) => { values.delete(key); },
};
const identity = async <T,>(value: T) => value;
await withDeletion((mutate) => commitVaultGroupMutationPersistence({
storage, mutate, prepareState: (value) => value,
decryptHosts: identity, decryptConfigs: identity,
encryptHosts: identity, encryptConfigs: identity, isCurrent: () => true,
}), async (remove) => {
await assert.rejects(remove(['jump']), /rejected importer transaction/);
});
for (const [key, value] of Object.entries(original)) {
assert.deepEqual(storage.read(key), value);
}
});
test('host deletion reports a rejected or superseded transaction', async () => {
for (const failure of [{ ok: false, error: 'unavailable' }, { ok: false, superseded: true }] as const) {
await withDeletion(async () => failure, async (remove) => {
await assert.rejects(remove(['jump']), /unavailable|superseded/);
});
}
});
+29
View File
@@ -0,0 +1,29 @@
import { useCallback } from 'react';
import type { VaultGroupMutationResult, VaultGroupMutationState } from '../../domain/vaultGroupMutation';
import { pruneVaultJumpHostReferences } from '../../domain/vaultJumpGraph';
export function useVaultHostDeletion(
commit: (
mutate: (current: VaultGroupMutationState) => VaultGroupMutationResult,
) => Promise<VaultGroupMutationResult | { ok: false; superseded: true }>,
) {
return useCallback(async (hostIds: Iterable<string>) => {
const removedHostIds = new Set(hostIds);
if (removedHostIds.size === 0) return;
const result = await commit((current) => {
const pruned = pruneVaultJumpHostReferences({
hosts: current.hosts.filter((host) => !removedHostIds.has(host.id)),
groupConfigs: current.configs,
removedHostIds,
});
return {
ok: true,
state: { ...current, hosts: pruned.hosts, configs: pruned.groupConfigs },
};
});
if (!result.ok) {
throw new Error('error' in result ? result.error : 'Host deletion was superseded. Try again.');
}
}, [commit]);
}
+28
View File
@@ -1,3 +1,5 @@
import { readMonitorPanels, writeMonitorPanels } from './monitorPanelsStorage';
import type { MonitorPanel } from '../../domain/monitorPanels';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import {
hostsEqualForIdentityReuse,
@@ -82,6 +84,10 @@ import {
import { commitVaultNotesWrite } from "./vaultNotesPersistence";
import { rebasePendingVaultNotes } from "../../domain/vaultNotesReconciliation";
import { publishShellHistorySnapshot } from "./shellHistoryStore";
import {
clearHistory as clearAutocompleteHistory,
markCommandHistoryCleared,
} from "./commandHistoryStore";
import { setVaultInitialized } from "./vaultInitStore";
import { notify } from "../notification";
import {
@@ -120,6 +126,7 @@ import {
import { commitVaultGroupMutationPersistence } from "./vaultGroupMutationPersistence";
type ExportableVaultData = {
monitorPanels?: MonitorPanel[];
hosts: Host[];
keys: SSHKey[];
identities?: Identity[];
@@ -1184,6 +1191,7 @@ export const useVaultState = () => {
}, []);
const clearVaultData = useCallback(() => {
void withVaultImportLock('vault', async () => writeMonitorPanels([]));
updateHosts([]);
updateKeys([]);
updateIdentities([]);
@@ -1250,6 +1258,23 @@ export const useVaultState = () => {
publishShellHistorySnapshot([]);
}, []);
/**
* Clear every locally recorded command history: the global shell history, the
* terminal autocomplete history, and the in-memory compose-bar recall.
*
* The autocomplete store persists the clear synchronously and fans it out to
* other renderers through its own `storage` listener. The compose-bar store
* subscribes to that same clear event, so detached terminal popups drop their
* recall too without a separate broadcast.
*/
const clearAllCommandHistory = useCallback(() => {
clearShellHistory();
clearAutocompleteHistory();
// Tombstone so a later first-time histfile import cannot restore the
// commands the user just deleted.
markCommandHistoryCleared();
}, [clearShellHistory]);
const removeShellHistoryEntry = useCallback((entryId: string) => {
setShellHistory((prev) => {
const updated = removeGlobalHistoryEntry(prev, entryId);
@@ -1951,6 +1976,7 @@ export const useVaultState = () => {
const exportData = useCallback(
(): ExportableVaultData => ({
monitorPanels: readMonitorPanels(),
hosts,
keys,
identities,
@@ -1969,6 +1995,7 @@ export const useVaultState = () => {
const importData = useCallback(
(payload: Partial<ExportableVaultData>): Promise<void> => {
const encryptedWrites: Promise<void>[] = [];
if (payload.monitorPanels !== undefined) encryptedWrites.push(withVaultImportLock('vault', async () => writeMonitorPanels(payload.monitorPanels)));
if (payload.hosts) {
// Cloud payloads no longer carry `lastConnectedAt` (#2629), but any
// remote reconciliation replaces the whole local host array. Re-attach
@@ -2201,6 +2228,7 @@ export const useVaultState = () => {
updateGroupConfigs,
addShellHistoryEntry,
clearShellHistory,
clearAllCommandHistory,
removeShellHistoryEntry,
addConnectionLog,
updateConnectionLog,
@@ -86,6 +86,13 @@ test('saved default resolves per session with fresh ids and protocol-aware pruni
const again = state.resolveDefaultLayoutForSession({ protocol: 'ssh' });
assert.ok(again);
assert.notEqual(again.layout.root.id, sshResolved.layout.root.id);
await act(async () => {
state?.saveWorkspaceLayoutAsDefault(createSidePanelLayout('browser', 'browser-pane'));
});
assert.equal(state.resolveDefaultLayoutForSession({ protocol: 'telnet' }), null);
for (const protocol of ['ssh', 'mosh', 'local']) {
assert.equal(state.resolveDefaultLayoutForSession({ protocol })?.focusedTool, 'browser');
}
} finally {
if (previousLocalStorage) {
Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
@@ -35,7 +35,7 @@ export type ResolvedWorkspaceLayoutPreset = {
export function useWorkspaceLayoutPresetState() {
/**
* Resolve the saved default preset into a fresh layout for a newly
* connected session. Panes the session cannot serve (SFTP on non-file
* connected session. Panes the session cannot serve (SFTP/Browser on non-file
* protocols) are pruned, and ids are rekeyed so several workspaces can
* run the same preset in parallel. Returns null when there is no preset
* or nothing survives availability filtering.
@@ -48,7 +48,7 @@ export function useWorkspaceLayoutPresetState() {
const proto = session.protocol ?? 'ssh';
const usable = withoutUnavailableSidePanelTools(
preset.layout,
(tool) => tool !== 'sftp' || canServeSftp(proto),
(tool) => (tool !== 'sftp' && tool !== 'browser') || canServeSftp(proto),
);
if (!usable) return null;
@@ -86,6 +86,7 @@ test('vault actions register and unregister', () => {
updateHostLastConnected: noop,
addShellHistoryEntry: noop,
removeShellHistoryEntry: noop,
clearAllCommandHistory: noop,
});
getVaultSnapshotActions()?.updateHosts([]);
assert.deepEqual(calls, ['hosts']);
+1
View File
@@ -63,6 +63,7 @@ export type VaultSnapshotActions = Pick<
| 'updateHostLastConnected'
| 'addShellHistoryEntry'
| 'removeShellHistoryEntry'
| 'clearAllCommandHistory'
>;
const EMPTY_HOSTS: readonly Host[] = Object.freeze([]);
@@ -6,6 +6,8 @@ import {
serializeWindowOpacityRecord,
shouldApplyWindowOpacityRecord,
shouldBroadcastWindowOpacityChange,
updateWindowOpacityRecord,
toggleWindowOpacityRecord,
type WindowOpacityMutationSource,
type WindowOpacityRecord,
} from './windowOpacitySync.ts';
@@ -197,3 +199,23 @@ test('serializeWindowOpacityRecord round-trips through parse', () => {
const raw = serializeWindowOpacityRecord({ opacity: 0.55, version: 9 });
assert.deepEqual(parseWindowOpacityRecord(JSON.parse(raw)), { opacity: 0.55, version: 9 });
});
test('toggling off and restarting preserves a legacy selected opacity', () => {
const selected = parseWindowOpacityRecord('0.6');
const opaque = toggleWindowOpacityRecord(selected);
assert.equal(opaque.opacity, 1);
const restarted = parseWindowOpacityRecord(serializeWindowOpacityRecord(opaque));
assert.equal(toggleWindowOpacityRecord(restarted).opacity, 0.6);
assert.equal(toggleWindowOpacityRecord(restarted).version, selected.version + 2);
});
test('slider changes replace the preferred opacity and toggles use the latest record', () => {
const opaque = toggleWindowOpacityRecord({ opacity: 0.6, version: 2 });
const slider = updateWindowOpacityRecord(opaque, 0.7);
const next = toggleWindowOpacityRecord(toggleWindowOpacityRecord(slider));
assert.equal(next.opacity, 0.7);
assert.equal(next.preferredOpacity, 0.7);
assert.equal(next.version, 6);
assert.equal(updateWindowOpacityRecord(next, 0.7), next);
assert.equal(toggleWindowOpacityRecord({ opacity: 1, version: 0 }).opacity, 0.85);
});
+27 -1
View File
@@ -10,6 +10,7 @@ export type WindowOpacityMutationSource = 'local' | 'incoming';
export type WindowOpacityRecord = {
opacity: number;
version: number;
preferredOpacity?: number;
};
/**
@@ -34,12 +35,16 @@ export function parseWindowOpacityRecord(raw: unknown): WindowOpacityRecord {
}
if (raw && typeof raw === 'object') {
const record = raw as { opacity?: unknown; version?: unknown };
const record = raw as { opacity?: unknown; version?: unknown; preferredOpacity?: unknown };
const opacity = clampWindowOpacity(record.opacity);
const version = Number(record.version);
const preferred = Number(record.preferredOpacity);
return {
opacity,
version: Number.isFinite(version) && version > 0 ? Math.floor(version) : 0,
...(Number.isFinite(preferred) && preferred < 1
? { preferredOpacity: clampWindowOpacity(preferred) }
: {}),
};
}
@@ -50,9 +55,30 @@ export function serializeWindowOpacityRecord(record: WindowOpacityRecord): strin
return JSON.stringify({
opacity: clampWindowOpacity(record.opacity),
version: Math.max(0, Math.floor(record.version) || 0),
...(record.preferredOpacity !== undefined ? { preferredOpacity: record.preferredOpacity } : {}),
});
}
/** Slider changes and temporary toggles share the existing versioned setting. */
export function updateWindowOpacityRecord(
current: WindowOpacityRecord,
nextValue: number,
): WindowOpacityRecord {
const opacity = clampWindowOpacity(nextValue);
if (opacity === current.opacity) return current;
const preferredOpacity = opacity < 1 ? opacity
: current.opacity < 1 ? current.opacity : current.preferredOpacity;
return {
opacity,
version: current.version + 1,
...(preferredOpacity !== undefined ? { preferredOpacity } : {}),
};
}
export function toggleWindowOpacityRecord(current: WindowOpacityRecord): WindowOpacityRecord {
return updateWindowOpacityRecord(current, current.opacity < 1 ? 1 : (current.preferredOpacity ?? 0.85));
}
/**
* Incoming peer updates must not clobber a newer local/drag revision.
* Equal versions are treated as already-applied (no state thrash).
+340
View File
@@ -0,0 +1,340 @@
import { installBrowserLockFixture } from "./testSupport/browserLockFixture";
import test from 'node:test';
import assert from 'node:assert/strict';
import type { AISession } from '../infrastructure/ai/types';
import type { SyncPayload } from '../domain/sync';
import { withSyncReliabilityMeta } from '../domain/syncReliability';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime';
import { useAIChatStreaming, type UseAIChatStreamingReturn } from './state/useAIChatStreaming';
installBrowserLockFixture();
const storage = new Map<string, string>();
const events = new EventTarget();
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => storage.set(key, value),
removeItem: (key: string) => storage.delete(key),
} });
Object.defineProperty(globalThis, 'window', { configurable: true, value: events });
const keys = await import('../infrastructure/config/storageKeys');
const snapshots = await import('./state/aiStateSnapshots');
const { getAISessionsSnapshot } = await import('./state/aiSessionsStore');
const {
buildCloudSyncPayload, buildLocalVaultPayload, collectAiSessionsForSync,
applySyncPayload, applyLocalVaultPayload, hasMeaningfulSyncData,
setAiSessionsSyncPreference,
hasCloudSyncEntityData, hasMeaningfulCloudSyncData, shouldPromptCloudVaultRecovery,
} = await import('./syncPayload');
const vault = { hosts: [], keys: [], identities: [], snippets: [], customGroups: [], knownHosts: [] };
const remotePayload = (aiSessions: AISession[]): SyncPayload => ({ ...vault, aiSessions, syncedAt: 1 });
const session = (): AISession => ({
id: 'chat', title: 'Chat', agentId: 'catty', scope: { type: 'global' }, createdAt: 1, updatedAt: 2,
messages: [{ id: 'message', role: 'user', content: 'Inspect', timestamp: 1, attachments: [{
filename: 'terminal.log', mediaType: 'text/plain', terminalSelection: true,
base64Data: 'cHJpdmF0ZQ==', previewText: 'private', filePath: '/private/device/file', lineCount: 1,
}] }],
});
function save(sessions: AISession[], enabled = true) {
snapshots.setLatestAISessionsSnapshot(sessions);
storage.set(keys.STORAGE_KEY_AI_SESSIONS, JSON.stringify(sessions));
storage.set(keys.STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled }));
}
test.beforeEach(() => { storage.clear(); save([], false); });
test('actual manual upload and auto collector honor consent and explicit empty', async () => {
save([session()], false);
const options = { collectPluginSidecars: () => undefined };
assert.equal((await buildCloudSyncPayload(vault, [], options)).aiSessions, undefined);
assert.equal(collectAiSessionsForSync(), undefined);
save([], true);
assert.deepEqual((await buildCloudSyncPayload(vault, [], options)).aiSessions, []);
assert.deepEqual(collectAiSessionsForSync(), []);
save([session()], true);
const cloud = await buildCloudSyncPayload(vault, [], options);
assert.equal(cloud.aiSessions?.length, 1);
assert.deepEqual(cloud.aiSessions, collectAiSessionsForSync());
assert.equal(JSON.stringify(cloud).includes('cHJpdmF0ZQ=='), false);
assert.equal(JSON.stringify(cloud).includes('/private/device/file'), false);
assert.equal(JSON.stringify(cloud.aiSessions?.[0].messages[0].attachments).includes('private'), false);
});
test('sync persistence survives restart beyond the local-only history limits', () => {
const many = Array.from({ length: 51 }, (_, index) => ({ ...session(), id: `chat-${index}`, updatedAt: index,
messages: Array.from({ length: 201 }, (_, turn) => ({ id: `m-${turn}`, role: 'user' as const, content: 'History', timestamp: turn })) }));
save(many);
assert.equal(snapshots.writeSessionsForStorage(many), true);
assert.equal(collectAiSessionsForSync()?.length, 51);
snapshots.setLatestAISessionsSnapshot(null as unknown as AISession[]);
const afterRestart = collectAiSessionsForSync()!;
assert.equal(afterRestart.length, 51);
assert.equal(afterRestart[0].messages.length, 201);
save(many, false);
assert.equal(snapshots.writeSessionsForStorage(many), true);
const localOnly = JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!);
assert.equal(localOnly.length, 50);
assert.equal(localOnly[0].messages.length, 200);
});
test('failed history persistence refuses upload without pruning the cloud representation', async () => {
save([session()]);
const original = globalThis.localStorage.setItem;
globalThis.localStorage.setItem = (key, value) => {
if (key === keys.STORAGE_KEY_AI_SESSIONS) throw new DOMException('Full', 'QuotaExceededError');
original(key, value);
};
snapshots.setLatestAISessionsSnapshot([{ ...session(), title: 'Unsaved change' }]);
try {
await assert.rejects(buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined }), /persist|save/i);
assert.equal(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!)[0].title, 'Chat');
const backup = buildLocalVaultPayload(vault);
assert.equal(backup.aiSessions?.[0].title, 'Unsaved change');
assert.equal(backup.aiSessions?.[0].messages[0].attachments?.[0].base64Data, 'cHJpdmF0ZQ==');
} finally { globalThis.localStorage.setItem = original; }
});
test('failed opt-in preference commit leaves local chats and native threads untouched', async () => {
const local = { ...session(), externalSessionId: 'native-thread' };
save([local], false);
const original = globalThis.localStorage.setItem;
const cleanups: string[] = [];
Object.assign(window, { netcatty: { aiSdkAgentCleanup: async (id: string) => { cleanups.push(id); return { ok: true }; } } });
globalThis.localStorage.setItem = (key, value) => {
if (key === keys.STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS) throw new DOMException('Full', 'QuotaExceededError');
original(key, value);
};
const incoming = { ...session(), updatedAt: 3, messages: [...session().messages,
{ id: 'remote', role: 'assistant' as const, content: 'Remote turn', timestamp: 3 }] };
try {
await assert.rejects(setAiSessionsSyncPreference(true, async () => [remotePayload([incoming])]), /preference|enable/i);
assert.deepEqual(snapshots.latestAISessionsSnapshot, [local]);
assert.deepEqual(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!), [local]);
assert.deepEqual(cleanups, []);
assert.equal(JSON.parse(storage.get(keys.STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)!).enabled, false);
} finally { globalThis.localStorage.setItem = original; delete (window as unknown as { netcatty?: unknown }).netcatty; }
});
test('local backup retains chat and attachment bytes with cloud consent off', async () => {
const local = session();
save([local], false);
const backup = buildLocalVaultPayload(vault);
assert.deepEqual(backup.aiSessions, [local]);
assert.equal(hasMeaningfulSyncData({ ...vault, aiSessions: [local], syncedAt: 1 }), true);
save([], false);
await applyLocalVaultPayload(backup, { importVaultData: () => undefined }, {
prepareConvergentRestore: async () => async () => {},
});
assert.equal(getAISessionsSnapshot().sessions[0].messages[0].attachments?.[0].base64Data, 'cHJpdmF0ZQ==');
});
test('chat-only data is syncable but does not suppress empty-vault recovery', () => {
const local = { ...vault, aiSessions: [session()], syncedAt: 1 };
assert.equal(hasMeaningfulCloudSyncData(local), true);
assert.equal(hasCloudSyncEntityData(local), false);
const host = { id: 'remote', label: 'Remote', hostname: 'remote.example', username: 'test', port: 22, protocol: 'ssh' as const, tags: [], os: 'linux' as const };
for (const hosts of [[host], [host, { ...host, id: 'second' }]]) {
assert.equal(shouldPromptCloudVaultRecovery(local, { ...vault, hosts, syncedAt: 2 }), true);
}
assert.equal(shouldPromptCloudVaultRecovery({ ...vault, syncedAt: 1 }, local), false);
});
test('download publishes immediately and keeps local attachment bytes on a newer message', async () => {
save([session()]);
const incoming = session();
incoming.updatedAt = 3;
incoming.messages[0].content = 'Updated';
incoming.messages[0].attachments = [{ base64Data: '', mediaType: 'text/plain', filename: 'terminal.log', terminalSelection: true, contentUnavailable: true }];
const payload: SyncPayload = { ...vault, aiSessions: [incoming], syncedAt: 2 };
await applySyncPayload(payload, { importVaultData: () => undefined });
const current = getAISessionsSnapshot().sessions[0];
assert.equal(current.messages[0].content, 'Updated');
assert.equal(current.messages[0].attachments?.[0].base64Data, 'cHJpdmF0ZQ==');
assert.equal(snapshots.latestAISessionsSnapshot?.[0], current);
assert.equal(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!)[0].messages[0].content, 'Updated');
});
test('restoring an old backup without chat leaves current chats alone', async () => {
const local = session();
save([local], false);
await applyLocalVaultPayload({ ...vault, syncedAt: 1 }, { importVaultData: () => undefined }, {
prepareConvergentRestore: async () => async () => {},
});
assert.deepEqual(snapshots.latestAISessionsSnapshot, [local]);
assert.deepEqual(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!), [local]);
});
test('authoritative cloud session removal stays removed in the next upload', async () => {
save([session()]);
await applySyncPayload({ ...vault, aiSessions: [], syncedAt: 3 }, { importVaultData: () => undefined });
assert.deepEqual(getAISessionsSnapshot().sessions, []);
assert.deepEqual(collectAiSessionsForSync(), []);
assert.deepEqual((await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined })).aiSessions, []);
});
test('replacement stops active turns and waits for finalizers before persisting history', async (context) => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let hook: UseAIChatStreamingReturn;
function Harness() {
hook = useAIChatStreaming({ maxIterations: 1, addMessageToSession: () => {}, updateLastMessage: () => {}, updateMessageById: () => {} });
return null;
}
let renderer: ReactTestRenderer;
await act(async () => { renderer = create(React.createElement(Harness)); });
const original = globalThis.localStorage.setItem;
try {
for (const remove of [false, true]) {
const order: string[] = [];
const controller = new AbortController();
const local = { ...session(), messages: [...session().messages,
{ id: 'reply', role: 'assistant' as const, content: 'Partial', timestamp: 2, executionStatus: 'running' as const }] };
save([local]);
hook!.abortControllersRef.current.set('chat', controller);
await act(async () => { hook!.setStreamingForScope('chat', true); });
Object.assign(window, { netcatty: {
aiCattyCancelExec: async () => { order.push('cancel'); },
aiSdkAgentCancel: async () => ({ ok: true }),
aiSdkAgentCleanup: async () => { order.push('cleanup'); return { ok: true }; },
} });
const wait = context.mock.method(getAgentRuntime(), 'waitForActiveTurn', async () => {
assert.equal(controller.signal.aborted, true);
await new Promise(resolve => setTimeout(resolve, 0));
snapshots.setLatestAISessionsSnapshot([{ ...local, messages: [local.messages[0],
{ ...local.messages[1], content: 'Settled', executionStatus: 'cancelled' }] }]);
order.push('settled');
});
globalThis.localStorage.setItem = (key, value) => { if (key === keys.STORAGE_KEY_AI_SESSIONS) order.push('persist'); original(key, value); };
const incoming = { ...session(), updatedAt: 3, messages: [...session().messages,
{ id: 'remote', role: 'user' as const, content: 'Remote', timestamp: 3 }] };
await applySyncPayload(remotePayload(remove ? [] : [incoming]), { importVaultData: () => undefined });
assert.ok(order.indexOf('cancel') < order.indexOf('settled'));
assert.ok(order.indexOf('settled') < order.indexOf('persist'));
assert.ok(order.indexOf('persist') < order.indexOf('cleanup'));
assert.equal(hook!.abortControllersRef.current.has('chat'), false);
if (remove) assert.deepEqual(getAISessionsSnapshot().sessions, []);
else assert.ok(getAISessionsSnapshot().sessions[0].messages.some(message => message.content === 'Settled'));
wait.mock.restore();
globalThis.localStorage.setItem = original;
await act(async () => { hook!.setStreamingForScope('chat', false); });
}
} finally {
context.mock.restoreAll(); globalThis.localStorage.setItem = original;
delete (window as unknown as { netcatty?: unknown }).netcatty;
await act(async () => { renderer!.unmount(); });
}
});
test('local restore replaces later sessions and later turns with the backup snapshot', async () => {
const backedUp = session();
const later = { ...session(), updatedAt: 3, messages: [...session().messages,
{ id: 'later', role: 'assistant' as const, content: 'After backup', timestamp: 3 }] };
save([later, { ...session(), id: 'created-after-backup' }]);
await applyLocalVaultPayload({ ...vault, aiSessions: [backedUp], syncedAt: 1 }, { importVaultData: () => undefined }, {
prepareConvergentRestore: async () => async () => {},
});
assert.deepEqual(getAISessionsSnapshot().sessions, [backedUp]);
await applyLocalVaultPayload({ ...vault, aiSessions: [], syncedAt: 1 }, { importVaultData: () => undefined }, {
prepareConvergentRestore: async () => async () => {},
});
assert.deepEqual(getAISessionsSnapshot().sessions, []);
});
test('cloud downloads respect local chat opt-in while still applying vault data', async () => {
save([], false);
let vaultImports = 0;
const downloaded = { ...vault, aiSessions: [session()], syncedAt: 2 };
await applySyncPayload(downloaded, { importVaultData: () => { vaultImports++; } });
assert.equal(vaultImports, 1);
assert.deepEqual(snapshots.latestAISessionsSnapshot, []);
assert.deepEqual(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!), []);
save([], true);
await applySyncPayload(downloaded, { importVaultData: () => { vaultImports++; } });
assert.equal(vaultImports, 2);
assert.equal(snapshots.latestAISessionsSnapshot?.[0].id, 'chat');
});
test('enabling sync imports existing cloud chats before an empty local list can be uploaded', async () => {
save([], false);
let loads = 0;
await setAiSessionsSyncPreference(true, async () => {
loads++;
assert.equal(collectAiSessionsForSync(), undefined);
return [remotePayload([session()])];
});
assert.equal(loads, 1);
assert.equal(collectAiSessionsForSync()?.[0].id, 'chat');
assert.equal(getAISessionsSnapshot().sessions[0].id, 'chat');
await setAiSessionsSyncPreference(false, async () => { throw new Error('Disable must not load'); });
assert.equal(collectAiSessionsForSync(), undefined);
});
test('an unsuccessful initial cloud read leaves chat sync disabled and local history unchanged', async () => {
save([], false);
await assert.rejects(setAiSessionsSyncPreference(true, async () => { throw new Error('offline'); }), /offline/);
assert.equal(collectAiSessionsForSync(), undefined);
assert.deepEqual(snapshots.latestAISessionsSnapshot, []);
});
test('enabling from multiple mirrored providers retains the newer turns from either copy', async () => {
save([], false);
const newer = session();
newer.updatedAt = 3;
newer.messages.push({ id: 'new-turn', role: 'assistant', content: 'Newer provider turn', timestamp: 3 });
await setAiSessionsSyncPreference(true, async () => [remotePayload([newer]), remotePayload([session()])]);
assert.deepEqual(collectAiSessionsForSync()?.[0].messages.map((message) => message.id), ['message', 'new-turn']);
});
test('initial enable retains local-only chats but respects remote deletions and preservation', async () => {
const localOnly = { ...session(), id: 'local-only' };
save([localOnly], false);
await setAiSessionsSyncPreference(true, async () => [remotePayload([session()])]);
assert.deepEqual(collectAiSessionsForSync()?.map(item => item.id).sort(), ['chat', 'local-only']);
const removed = withSyncReliabilityMeta(remotePayload([]), remotePayload([session()]), { now: 3 });
for (const preserve of [false, true]) {
save([session(), localOnly], false);
await setAiSessionsSyncPreference(true, async () => [removed, remotePayload([session()])], preserve);
assert.deepEqual(collectAiSessionsForSync()?.map(item => item.id).sort(), preserve ? ['chat', 'local-only'] : ['local-only']);
}
});
test('backup rollback resets the native thread that still contains later turns', async () => {
const cleanups: string[] = [];
Object.assign(window, { netcatty: { aiSdkAgentCleanup: async (id: string) => { cleanups.push(id); return { ok: true }; } } });
const backedUp = { ...session(), agentId: 'codex', externalSessionId: 'native-thread' };
save([{ ...backedUp, updatedAt: 4, messages: [...backedUp.messages,
{ id: 'later', role: 'assistant', content: 'After backup', timestamp: 4 }] }]);
await applyLocalVaultPayload(remotePayload([backedUp]), { importVaultData: () => undefined }, {
prepareConvergentRestore: async () => async () => {},
});
const restored = getAISessionsSnapshot().sessions[0];
assert.equal(restored.externalSessionId, undefined);
assert.deepEqual(restored.messages, backedUp.messages);
assert.deepEqual(cleanups, ['chat']);
delete (window as unknown as { netcatty?: unknown }).netcatty;
});
test('cloud restore never resumes a source device SDK thread, and preserves matching local threads', async () => {
const local = { ...session(), externalSessionId: 'local-native-thread' };
save([local]);
const incoming = { ...session(), updatedAt: 3, externalSessionId: 'remote-native-thread' };
const fresh = { ...incoming, id: 'new-chat' };
await applySyncPayload({ ...vault, aiSessions: [incoming, fresh], syncedAt: 2 }, { importVaultData: () => undefined });
const current = getAISessionsSnapshot().sessions;
assert.equal(current.find((s) => s.id === 'chat')?.externalSessionId, 'local-native-thread');
assert.equal(current.find((s) => s.id === 'new-chat')?.externalSessionId, undefined);
});
test('changed remote transcript resets the local native SDK thread before continuing', async () => {
const cleanups: string[] = [];
Object.assign(window, { netcatty: { aiSdkAgentCleanup: async (id: string) => { cleanups.push(id); return { ok: true }; } } });
save([{ ...session(), agentId: 'codex', externalSessionId: 'local-native-thread' }]);
const incoming = { ...session(), agentId: 'codex', updatedAt: 3, externalSessionId: 'remote-native-thread' };
incoming.messages.push({ id: 'remote-turn', role: 'user', content: 'Added on another device', timestamp: 3 });
await applySyncPayload({ ...vault, aiSessions: [incoming], syncedAt: 2 }, { importVaultData: () => undefined });
assert.deepEqual(cleanups, ['chat']);
assert.equal(getAISessionsSnapshot().sessions[0].externalSessionId, undefined);
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
delete (window as unknown as { netcatty?: unknown }).netcatty;
});
+23
View File
@@ -1,3 +1,4 @@
import { installBrowserLockFixture } from "./testSupport/browserLockFixture";
import test from "node:test";
import assert from "node:assert/strict";
@@ -38,6 +39,8 @@ function installLocalStorage(): LocalStorageMock {
return localStorage;
}
installBrowserLockFixture();
const localStorage = installLocalStorage();
const {
applyLocalVaultPayload,
@@ -1420,6 +1423,26 @@ test("hasCloudSyncEntityData ignores settings-only payloads for empty-vault reco
);
});
test("surviving browser bookmarks do not suppress empty-vault recovery", () => {
const local: SyncPayload = {
...vault([]), syncedAt: 1,
browserBookmarks: [{
id: "app", title: "App", url: "https://app.example.com/", scope: "all-hosts",
hostId: null, icon: "A", color: "#247969", order: 0, createdAt: 1, updatedAt: 1,
}],
};
assert.equal(hasMeaningfulCloudSyncData(local), true, "bookmarks must remain syncable");
assert.equal(hasCloudSyncEntityData(local), false);
const host = {
id: "remote", label: "Remote", hostname: "remote.example.com", username: "test",
port: 22, protocol: "ssh" as const, tags: [], os: "linux" as const,
};
for (const hosts of [[host], [host, { ...host, id: "second" }]]) {
assert.equal(shouldPromptCloudVaultRecovery(local, { ...vault([]), hosts, syncedAt: 2 }), true);
}
assert.equal(shouldPromptCloudVaultRecovery({ ...vault([]), syncedAt: 1 }, local), false);
});
test("shouldPromptCloudVaultRecovery ignores settings-only remote payloads", () => {
const settingsOnlyPayload: SyncPayload = {
hosts: [],
+165 -15
View File
@@ -1,3 +1,5 @@
import { readMonitorPanels, applyMonitorPanels } from './state/monitorPanelsStorage';
import { normalizeMonitorPanels } from '../domain/monitorPanels';
import { decryptProviderHeaders, encryptProviderHeaders } from '../infrastructure/ai/providerHeaderCredentials';
/**
* Sync Payload Builders - Single source of truth for constructing and applying
@@ -46,11 +48,20 @@ import { localStorageAdapter } from '../infrastructure/persistence/localStorageA
import { decryptField, encryptField } from '../infrastructure/persistence/secureFieldAdapter';
import { sanitizeQuickMessages } from '../infrastructure/ai/quickMessages';
import { emitAIStateChanged } from './state/aiStateEvents';
import {
latestAISessionsSnapshot,
setLatestAISessionsSnapshot,
writeSessionsForStorage,
cleanupSdkAgentSessions,
cleanupDeletedAIChatSessions,
} from './state/aiStateSnapshots';
import { getAISessionsSnapshot, publishAISessionsSnapshot } from './state/aiSessionsStore';
import {
persistCommandBlocklistSetting,
readCommandBlocklistSetting,
} from './state/commandBlocklistSettings';
import { rehydrateGlobalSftpBookmarks } from './state/sftp/globalSftpBookmarks';
import { applyHostBrowserBookmarks, collectHostBrowserBookmarks, getCachedHostBrowserBookmarks } from './hostBrowserBookmarks';
import {
clampTerminalFontSizeValue,
nextTerminalFontSizeSyncVersion,
@@ -64,6 +75,7 @@ import {
import { isValidHslToken } from './state/settingsStateDefaults';
import {
STORAGE_KEY_TERM_AUTO_CLOSE_EXIT_MIGRATED,
STORAGE_KEY_VAULT_RESTORE_IN_PROGRESS_UNTIL,
STORAGE_KEY_THEME,
STORAGE_KEY_UI_THEME_LIGHT,
STORAGE_KEY_UI_THEME_DARK,
@@ -125,7 +137,10 @@ import {
STORAGE_KEY_VAULT_NOTES_FONT_FAMILY,
STORAGE_KEY_VAULT_NOTES_FONT_SIZE,
STORAGE_KEY_VAULT_NOTES_CODE_FONT_SIZE,
STORAGE_KEY_AI_SESSIONS,
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
} from '../infrastructure/config/storageKeys';
import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge';
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
@@ -171,6 +186,7 @@ function hasMeaningfulPluginSidecars(payload: SyncPayload): boolean {
*/
export function hasMeaningfulSyncData(payload: SyncPayload): boolean {
if (hasSyncPayloadEntityData(payload, SYNC_PAYLOAD_ENTITY_KEYS)) return true;
if (Array.isArray(payload.aiSessions) && payload.aiSessions.length > 0) return true;
if (
payload.settings && Object.values(payload.settings).some((value) => value !== undefined)
@@ -200,11 +216,11 @@ export function hasMeaningfulCloudSyncData(payload: SyncPayload): boolean {
/**
* Returns true only when the payload contains synced vault entities.
* Settings are intentionally ignored so default settings written on first
* launch do not make a new device look non-empty during cloud restore checks.
* Settings, chat history, and browser bookmarks are ignored: none proves that the vault's
* hosts and keys survived local data loss.
*/
export function hasCloudSyncEntityData(payload: SyncPayload): boolean {
return hasSyncPayloadEntityData(payload, CLOUD_SYNC_PAYLOAD_ENTITY_KEYS);
return hasSyncPayloadEntityData(payload, CLOUD_SYNC_PAYLOAD_ENTITY_KEYS.filter((key) => key !== 'aiSessions' && key !== 'browserBookmarks'));
}
export function shouldPromptCloudVaultRecovery(
@@ -1029,16 +1045,42 @@ function pruneOrphanPerAgentBindings(): void {
// ---------------------------------------------------------------------------
/**
* Build a complete `SyncPayload` from local data.
*
* Port-forwarding rules are optional because they are managed by a separate
* state hook (`usePortForwardingState`). Callers should strip transient
* runtime fields (status, error, lastUsedAt) before passing them in.
* AI chat sessions only leave the device when the user opted in.
* Attachments are stripped — see {@link stripAiSessionPayloadForSync}.
*/
export function collectAiSessionsForSync(): SyncPayload['aiSessions'] {
const enabled = localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS);
if (enabled?.enabled !== true) return undefined;
const sessions = collectLocalAiSessions();
if (!writeSessionsForStorage(sessions)) {
throw new Error('Unable to persist chat history for cloud sync');
}
return stripAiSessionPayloadForSync(sessions);
}
function collectLocalAiSessions(): NonNullable<SyncPayload['aiSessions']> {
return latestAISessionsSnapshot
?? localStorageAdapter.read<SyncPayload['aiSessions']>(STORAGE_KEY_AI_SESSIONS)
?? [];
}
/** Build the portable payload; device-local data is added by the backup builder. */
export function buildSyncPayload(
vault: SyncableVaultData,
portForwardingRules?: PortForwardingRule[],
): SyncPayload {
const aiSessions = collectAiSessionsForSync();
return {
...buildVaultSyncPayload(vault, portForwardingRules),
...(aiSessions !== undefined ? { aiSessions } : {}),
};
}
function buildVaultSyncPayload(
vault: SyncableVaultData,
portForwardingRules?: PortForwardingRule[],
): SyncPayload {
const browserBookmarks = getCachedHostBrowserBookmarks();
return {
hosts: sanitizeHostsForSync(vault.hosts),
keys: vault.keys,
@@ -1050,7 +1092,9 @@ export function buildSyncPayload(
notes: vault.notes,
noteGroups: vault.noteGroups,
groupConfigs: vault.groupConfigs,
monitorPanels: readMonitorPanels(),
portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules),
...(browserBookmarks !== undefined ? { browserBookmarks } : {}),
settings: collectSyncableSettings(),
syncedAt: Date.now(),
};
@@ -1124,6 +1168,8 @@ export async function buildCloudSyncPayload(
collectPluginSidecars?: PluginSyncSidecarCollector;
},
): Promise<SyncPayload> {
const aiSessions = collectAiSessionsForSync();
const browserBookmarks = await collectHostBrowserBookmarks();
const base: SyncPayload = {
hosts: sanitizeHostsForSync(vault.hosts),
keys: vault.keys,
@@ -1135,7 +1181,10 @@ export async function buildCloudSyncPayload(
notes: vault.notes,
noteGroups: vault.noteGroups,
groupConfigs: vault.groupConfigs,
monitorPanels: readMonitorPanels(),
portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules),
...(aiSessions !== undefined ? { aiSessions } : {}),
...(browserBookmarks !== undefined ? { browserBookmarks } : {}),
settings: await collectCloudSyncableSettings(),
syncedAt: Date.now(),
};
@@ -1150,11 +1199,13 @@ export function buildLocalVaultPayload(
portForwardingRules?: PortForwardingRule[],
): SyncPayload {
const base: SyncPayload = {
...buildSyncPayload(vault, portForwardingRules),
...buildVaultSyncPayload(vault, portForwardingRules),
// Keep device-local recent-connection timestamps in protective backups.
hosts: vault.hosts,
settings: collectLocalBackupSettings(),
knownHosts: vault.knownHosts,
// Cloud consent and cloud attachment stripping do not apply to local backups.
aiSessions: collectLocalAiSessions(),
};
// Protective backups must capture plugin sidecars so restore can recover
// plugin settings/baselines. Prefer the last successful host collect cache
@@ -1184,6 +1235,8 @@ export async function buildLocalVaultPayloadAsync(
portForwardingRules?: PortForwardingRule[],
): Promise<SyncPayload> {
const base = buildLocalVaultPayload(vault, portForwardingRules);
const browserBookmarks = await collectHostBrowserBookmarks();
if (browserBookmarks !== undefined) base.browserBookmarks = browserBookmarks;
const {
collectPluginSyncSidecarsFromHost,
isPluginSidecarHostUnavailableError,
@@ -1207,12 +1260,96 @@ export async function buildLocalVaultPayloadAsync(
return base;
}
/**
* Apply a downloaded `SyncPayload` to local state via the provided importers.
*
* This ensures both vault data and port-forwarding rules are imported
* consistently across windows.
*/
/** Merge downloaded chat data through the existing state and persistence boundary. */
async function applyAiSessionData(sessions: NonNullable<SyncPayload['aiSessions']>, includeLocalOnlyData: boolean): Promise<void> {
const incoming = includeLocalOnlyData
? sessions
: sessions.map(stripAiSessionDeviceState);
const incomingIds = new Set(incoming.map((session) => session.id));
const incomingById = new Map(incoming.map((session) => [session.id, session]));
const portableMessages = (value: typeof incoming[number]) => stripAiSessionPayloadForSync([value])[0].messages;
const affectedIds = collectLocalAiSessions().filter((local) => {
const next = incomingById.get(local.id);
if (!next) return true;
const candidate = includeLocalOnlyData ? next : mergeAiSessionLists([local], [next])[0];
return JSON.stringify(portableMessages(local)) !== JSON.stringify(portableMessages(candidate));
}).map((session) => session.id);
if (affectedIds.length > 0) {
const { stopAIChatSessionBeforeReplacement } = await import('./state/useAIChatStreaming');
await Promise.all(affectedIds.map(stopAIChatSessionBeforeReplacement));
}
// Stop finalizers can finish the last local message. Read it again before
// merging so the stopped turn cannot write into a replaced/deleted session.
const localSessions = collectLocalAiSessions();
const localById = new Map(localSessions.map((session) => [session.id, session]));
const removedIds = localSessions.filter((session) => !incomingIds.has(session.id)).map((session) => session.id);
const resetSdkSessions: string[] = [];
// The sync merge has already decided which session IDs survive. Backups
// restore their exact transcript; cloud survivors still retain local turns.
const candidates = includeLocalOnlyData ? incoming
: mergeAiSessionLists(localSessions.filter((session) => incomingIds.has(session.id)), incoming);
const mergedSessions = candidates.map((session) => {
// Native SDK threads belong to this device. Reuse the local thread
// only while it already contains the entire merged transcript.
const local = localById.get(session.id);
const transcriptChanged = local
&& JSON.stringify(portableMessages(local)) !== JSON.stringify(portableMessages(session));
if (transcriptChanged) resetSdkSessions.push(session.id);
const { externalSessionId: _remoteThread, ...portable } = session;
return local?.externalSessionId && !transcriptChanged
? { ...portable, externalSessionId: local.externalSessionId }
: portable;
});
if (!writeSessionsForStorage(mergedSessions)) {
throw new Error('Unable to save downloaded AI chat history');
}
cleanupDeletedAIChatSessions(removedIds);
await cleanupSdkAgentSessions(resetSdkSessions);
setLatestAISessionsSnapshot(mergedSessions);
publishAISessionsSnapshot({ ...getAISessionsSnapshot(), sessions: mergedSessions });
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
}
/** Read existing cloud chats before an enabled empty local list can overwrite them. */
export async function setAiSessionsSyncPreference(
enabled: boolean,
loadRemotePayloads: () => Promise<SyncPayload[]>,
preserveDeletions = false,
): Promise<void> {
const wasEnabled = localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
if (enabled && !wasEnabled) {
const remotes = await loadRemotePayloads();
// Reuse the ordinary no-base deletion rules, including cloud tombstones,
// while retaining local-only chats when this is a first-time opt-in.
const local: SyncPayload = { hosts: [], keys: [], identities: [], snippets: [], customGroups: [],
aiSessions: collectLocalAiSessions(), syncedAt: 0 };
const merged = remotes.reduce((current, remote) =>
mergeSyncPayloads(null, current, remote, { preserveDeletions }).payload, local);
const previous = localStorageAdapter.readString(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS);
const { withRestoreBarrier } = await import('./localVaultBackups');
await withRestoreBarrier(async () => {
if ((localStorageAdapter.readNumber(STORAGE_KEY_VAULT_RESTORE_IN_PROGRESS_UNTIL) ?? 0) <= Date.now()) {
throw new Error('Unable to pause sync while enabling chat history');
}
if (!localStorageAdapter.write(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, { enabled })) {
throw new Error('Unable to save the chat sync preference');
}
try {
await applyAiSessionData(merged.aiSessions ?? [], false);
} catch (error) {
if (previous === null) localStorageAdapter.remove(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS);
else localStorageAdapter.writeString(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, previous);
throw error;
}
});
return;
}
if (!localStorageAdapter.write(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, { enabled })) {
throw new Error('Unable to save the chat sync preference');
}
}
/** Apply downloaded vault data and supported settings through their state boundaries. */
async function preparePayloadApply(
payload: SyncPayload,
importers: SyncPayloadImporters,
@@ -1226,6 +1363,7 @@ async function preparePayloadApply(
// so a previously poisoned cloud/backup snapshot can still restore host
// shells and let the user re-enter secrets (#2702).
const sanitizedPayload = stripSyncPayloadEncryptedCredentials(payload);
const monitorPanelsAtPrepare = readMonitorPanels();
// Prepare credentials before any vault or settings mutation. Encryption can
// fail when local credential storage is unavailable; reuse the result below.
const providers = sanitizedPayload.settings?.ai?.providers;
@@ -1267,6 +1405,7 @@ async function preparePayloadApply(
}
return () => Promise.resolve(importers.importVaultData(JSON.stringify(vaultImport))).then(async () => {
if (sanitizedPayload.monitorPanels !== undefined) await applyMonitorPanels(normalizeMonitorPanels(sanitizedPayload.monitorPanels), monitorPanelsAtPrepare, options.includeLocalOnlyData);
// Only import port-forwarding rules when the payload explicitly carries
// them. Absent field = "payload was created before this feature existed",
// so local rules are preserved. Explicitly present [] = "remote has no
@@ -1274,6 +1413,17 @@ async function preparePayloadApply(
if (sanitizedPayload.portForwardingRules !== undefined && importers.importPortForwardingRules) {
importers.importPortForwardingRules(sanitizedPayload.portForwardingRules);
}
if (sanitizedPayload.browserBookmarks !== undefined) {
await applyHostBrowserBookmarks(sanitizedPayload.browserBookmarks);
}
// AI chat sessions merge append-only: a cloud snapshot may be missing
// turns that only exist on this device, so union instead of replace.
const applyAiSessions = options.includeLocalOnlyData
|| localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
if (applyAiSessions && Array.isArray(sanitizedPayload.aiSessions)) {
await applyAiSessionData(sanitizedPayload.aiSessions, options.includeLocalOnlyData);
}
// Apply synced settings
if (sanitizedPayload.settings) {
@@ -0,0 +1,26 @@
/** Serialized Web Locks fixture for tests with a simulated browser window. */
export function installBrowserLockFixture(): void {
const tails = new Map<string, Promise<void>>();
const locks = {
async request<T>(name: string, task: () => Promise<T>): Promise<T> {
const previous = tails.get(name) ?? Promise.resolve();
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const tail = previous.then(() => gate);
tails.set(name, tail);
await previous;
try {
return await task();
} finally {
release();
if (tails.get(name) === tail) tails.delete(name);
}
},
};
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: { locks },
});
}
+8
View File
@@ -73,6 +73,10 @@ interface AIChatPanelContentProps {
modelCatalogWarning?: string;
/** Live SDK model catalog is loading (no built-in presets to show yet). */
modelCatalogLoading?: boolean;
/** Provenance of the active model list, rendered as the picker status chip. */
modelCatalogSource?: 'live' | 'last-known-good' | 'presets';
/** ISO timestamp of the successful fetch backing `modelCatalogSource`. */
modelCatalogFetchedAt?: string;
/** Retry a failed SDK model catalog load from the warning banner. */
handleModelCatalogRetry?: () => void;
agentModelPresets: AgentModelPreset[];
@@ -153,6 +157,8 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
modelDisplayName,
modelCatalogWarning,
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
agentModelPresets,
allowCustomModelEntry = true,
selectedAgentModel,
@@ -403,6 +409,8 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
agentName={currentAgentId === 'catty' ? 'Catty Agent' : externalAgents.find(a => a.id === currentAgentId)?.name}
modelPresets={agentModelPresets}
modelCatalogLoading={modelCatalogLoading}
modelCatalogSource={modelCatalogSource}
modelCatalogFetchedAt={modelCatalogFetchedAt}
allowCustomModelEntry={allowCustomModelEntry}
selectedModelId={selectedAgentModel}
onModelSelect={handleAgentModelSelect}
@@ -165,6 +165,18 @@ test('hidden empty AI side panel can release its subtree', () => {
assert.equal(shouldKeepAIChatSidePanelMounted(props), false);
});
test('Catty without an SDK catalog request does not claim models are loading', () => {
const html = renderToStaticMarkup(
React.createElement(I18nProvider, {
locale: 'en',
children: React.createElement(TooltipProvider, {
children: React.createElement(AIChatSidePanel, baseProps({ isVisible: true })),
}),
}),
);
assert.doesNotMatch(html, /Loading models|ai\.chat\.loadingModels/);
});
test('hidden AI side panel is retained when it has draft text', () => {
const props = baseProps({
draftsByScope: {
+151 -68
View File
@@ -80,15 +80,21 @@ import {
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
sdkRuntimeModelCache,
reconcileRuntimeModelWarning,
retainStoredModelPresetForCatalog,
toSdkRuntimeModelCatalog,
generateId,
agentModelPresetsShallowEqual,
mergeFallbackThinkingLevels,
normalizeStoredAgentModelSelection,
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
shouldAdoptSdkCurrentModel,
appendRetainedStoredModelPreset,
shouldLoadSdkRuntimeModels,
shouldUseStoredAgentModel,
type SdkRuntimeModelCatalog,
type SdkRuntimeModelCatalogSource,
} from './AIChatSidePanelHelpers';
import { AIChatPanelContent } from './AIChatPanelContent';
import { TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS } from './terminalLayer/terminalSidePanelChrome';
@@ -327,12 +333,20 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
// is tracked separately to block sends until the branch settles: a turn
// submitted meanwhile would run against the (soon hidden) source session.
const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false);
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, { cacheKey: string; models: AgentModelPreset[] }>>({});
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, { cacheKey: string; models: AgentModelPreset[]; catalogUnavailable: boolean }>>({});
const [runtimeModelWarnings, setRuntimeModelWarnings] = useState<Record<string, { cacheKey: string; message: string }>>({});
// Tracks SDK runtime model catalogs currently loading (per agent scope):
// while an OpenCode catalog is pending we must not flash the built-in
// OPENCODE_MODEL_PRESETS for providers the user never configured (#3584).
// Tracks SDK runtime model catalogs currently loading (per agent scope);
// the composer shows the loading row alongside the build-time presets and
// the live catalog replaces them when it arrives.
const [runtimeModelLoading, setRuntimeModelLoading] = useState<Record<string, { cacheKey: string }>>({});
// Provenance of the last applied SDK runtime catalog, per agent scope. The
// picker renders a uniform status chip from it; when no runtime catalog is
// active the composer falls back to build-time presets ('presets').
const [runtimeModelCatalogMeta, setRuntimeModelCatalogMeta] = useState<Record<string, {
cacheKey: string;
source: SdkRuntimeModelCatalogSource;
fetchedAt?: string;
}>>({});
const [steerWarnings, setSteerWarnings] = useState<Record<string, SteerWarning>>({});
const [steeringSessionId, setSteeringSessionId] = useState<string | null>(null);
const [userSkillOptions, setUserSkillOptions] = useState<UserSkillOption[]>([]);
@@ -852,7 +866,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
undoInFlightRef.current = true;
setIsUndoingLastTurn(true);
try {
const result = await undoLastTurnInSession(sessionId);
const result = await undoLastTurnInSession(sessionId, {
type: scopeType,
targetId: scopeTargetId,
});
if (!result) return;
ensureScopeDraft(currentAgentId);
@@ -899,6 +916,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
undoLastTurnInSession,
updateScopeDraft,
currentAgentId,
scopeType,
scopeTargetId,
]);
const providersRef = useRef(providers);
@@ -994,29 +1013,37 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const agent = externalAgentsRef.current.find((item) => item.id === target.agentId);
if (buildExternalAgentRuntimeModelTarget(agent)?.cacheKey !== target.cacheKey) return;
const agentId = target.agentId;
// Record the catalog provenance for the picker's status chip. An absent
// source (older main without the marker) displays as a live catalog.
setRuntimeModelCatalogMeta((prev) => ({
...prev,
[agentId]: {
cacheKey: target.cacheKey,
source: catalog.source ?? 'live',
...(catalog.fetchedAt ? { fetchedAt: catalog.fetchedAt } : {}),
},
}));
const catalogPresets = mergeFallbackThinkingLevels(
normalizeSdkRuntimeModelPresets(catalog.models, catalog.currentModelId),
getAgentModelPresets(agent?.command, getExternalAgentSdkBackend(agent)),
);
const runtimePresets = appendComposerCustomModelPresets(
const runtimePresets = retainStoredModelPresetForCatalog(
catalogPresets,
collectCustomModelIds(agentId, catalogPresets),
appendComposerCustomModelPresets(
catalogPresets,
collectCustomModelIds(agentId, catalogPresets),
),
agentModelMapRef.current[agentId],
agent,
Boolean(catalog.warning),
);
const storedModelId = agentModelMapRef.current[agentId];
if (runtimePresets.length === 0) {
setRuntimeAgentModelPresets((prev) => {
if (!(agentId in prev)) return prev;
const { [agentId]: _removed, ...rest } = prev;
return rest;
});
} else {
setRuntimeAgentModelPresets((prev) => (
prev[agentId]?.cacheKey === target.cacheKey
&& agentModelPresetsShallowEqual(prev[agentId].models, runtimePresets)
? prev
: { ...prev, [agentId]: { cacheKey: target.cacheKey, models: runtimePresets } }
));
}
setRuntimeAgentModelPresets((prev) => (
prev[agentId]?.cacheKey === target.cacheKey
&& prev[agentId].catalogUnavailable === Boolean(catalog.warning)
&& agentModelPresetsShallowEqual(prev[agentId].models, catalogPresets)
? prev
: { ...prev, [agentId]: { cacheKey: target.cacheKey, models: catalogPresets, catalogUnavailable: Boolean(catalog.warning) } }
));
// Another path (e.g. send preflight) applied the catalog before the
// deferred idle callback scheduled in the visibility effect: clear its
// stale pending flag so the composer stops claiming models are loading.
@@ -1027,20 +1054,21 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
});
const normalizedStoredModelId = normalizeStoredAgentModelSelection(
storedModelId,
agentModelMapRef.current[agentId],
runtimePresets,
);
if (normalizedStoredModelId && normalizedStoredModelId !== storedModelId) {
if (normalizedStoredModelId && normalizedStoredModelId !== agentModelMapRef.current[agentId]) {
setAgentModel(agentId, normalizedStoredModelId);
return;
}
const defaultModelId = resolveSdkRuntimeCatalogDefaultModelId(catalog, agent);
if (
options.adoptCurrentModel
&& catalog.currentModelId
&& shouldAdoptSdkCurrentModel(catalog.currentModelId, storedModelId, runtimePresets)
&& defaultModelId
&& shouldAdoptSdkCurrentModel(defaultModelId, agentModelMapRef.current[agentId], runtimePresets, agent)
) {
setAgentModel(agentId, catalog.currentModelId);
setAgentModel(agentId, defaultModelId);
}
}, [setAgentModel, setRuntimeModelLoading, buildExternalAgentRuntimeModelTarget, collectCustomModelIds]);
@@ -1081,13 +1109,25 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}
return next;
});
return {
currentModelId: result.currentModelId ?? null,
models: result.models,
};
return toSdkRuntimeModelCatalog(result);
},
{ force: options.force },
).catch((err) => {
).then((catalog) => {
// A refresh that joined another panel's in-flight load never ran the
// loader above, so sync this panel's banner from the shared result.
setRuntimeModelWarnings((current) => {
const agent = externalAgentsRef.current.find((item) => item.id === target.agentId);
if (buildExternalAgentRuntimeModelTarget(agent)?.cacheKey !== target.cacheKey) return current;
return reconcileRuntimeModelWarning(
current,
target.agentId,
target.cacheKey,
Boolean(catalog.warning),
t('ai.chat.modelCatalogWarning'),
);
});
return catalog;
}).catch((err) => {
setRuntimeModelWarnings((current) => {
const agent = externalAgentsRef.current.find((item) => item.id === target.agentId);
if (buildExternalAgentRuntimeModelTarget(agent)?.cacheKey !== target.cacheKey) return current;
@@ -1114,6 +1154,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const cached = sdkRuntimeModelCache.read(target.cacheKey);
if (cached) {
applySdkRuntimeModelCatalog(target, cached);
// The cache stores warned (last-known-good) responses too: sync the
// banner so another panel or a remount within the TTL does not present
// degraded models as live.
setRuntimeModelWarnings((current) => reconcileRuntimeModelWarning(
current,
target.agentId,
target.cacheKey,
Boolean(cached.warning),
t('ai.chat.modelCatalogWarning'),
));
}
// Respect renderer TTL / in-flight coalescing for all SDK agents including
@@ -1130,10 +1180,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
};
let cancelled = false;
let idleFired = false;
// Mark the catalog pending as soon as the refresh is scheduled: otherwise
// `runtimeModelLoading` stays false for the whole idle delay (and longer
// while the composer stays focused), so the built-in OPENCODE_MODEL_PRESETS
// remain selectable the entire time (#3584). Only do this on a cache miss:
// Mark the catalog pending as soon as the refresh is scheduled so the
// composer can show its loading affordance for the whole idle delay (and
// longer while the composer stays focused) instead of silently keeping
// only the build-time presets (#3584). Only do this on a cache miss:
// when a cached catalog was already applied above, the runtime presets are
// available, so a pending flag would keep the composer banner/picker in the
// "loading" state indefinitely while the idle callback is deferred.
@@ -1169,8 +1219,34 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
t,
]);
// Uniform status chip inputs: when a runtime catalog is active for the
// current agent its recorded provenance wins; otherwise the composer is
// showing build-time presets (the renderer-side preset fallback derives
// 'presets' here). While a load is pending the picker replaces the chip
// with the spinner row.
const modelCatalogSource = useMemo((): SdkRuntimeModelCatalogSource | undefined => {
// A config-locked Codex picker shows only that configured model, not the
// discovered catalog whose provenance is tracked below.
if (isCodexManagedAgent && codexConfigModel) return undefined;
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
const meta = runtimeModelCatalogMeta[currentAgentId];
const runtimeEntry = runtimeAgentModelPresets[currentAgentId];
if (meta && target && meta.cacheKey === target.cacheKey
&& runtimeEntry?.cacheKey === target.cacheKey && runtimeEntry.models.length > 0) {
return meta.source;
}
return 'presets';
}, [currentAgentConfig, currentAgentId, runtimeModelCatalogMeta, runtimeAgentModelPresets, buildExternalAgentRuntimeModelTarget, isCodexManagedAgent, codexConfigModel]);
const modelCatalogFetchedAt = useMemo((): string | undefined => {
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
const meta = runtimeModelCatalogMeta[currentAgentId];
if (meta && target && meta.cacheKey === target.cacheKey) return meta.fetchedAt;
return undefined;
}, [currentAgentConfig, currentAgentId, runtimeModelCatalogMeta, buildExternalAgentRuntimeModelTarget]);
const isCodexAppServer = isCodexManagedAgent && currentAgentConfig?.codexRuntime === 'app-server';
const canSteerCurrentTurn = Boolean(activeSessionId && isStreaming && isCodexAppServer);
const hasCodexCustomConfig = Boolean(codexConfigModel) && isCodexManagedAgent;
@@ -1190,26 +1266,15 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
if (hasCodexCustomConfig && codexConfigModel) {
return [{ id: codexConfigModel, name: codexConfigModel }];
}
if (runtimePresets) {
return appendComposerCustomModelPresets(
runtimePresets,
collectCustomModelIds(currentAgentId, runtimePresets),
);
}
// While an OpenCode catalog load is pending, do not flash the built-in
// OPENCODE_MODEL_PRESETS: they enumerate well-known gateway providers the
// user may never have configured, so for a few seconds every switch looks
// like a broken default model (#3584). Show only the user's own custom
// model ids until the live catalog resolves (or a retryable warning
// appears in the composer banner).
if (
target
&& getExternalAgentSdkBackend(currentAgentConfig) === 'opencode'
&& runtimeModelLoading[currentAgentId]?.cacheKey === target.cacheKey
) {
return appendComposerCustomModelPresets(
[],
collectCustomModelIds(currentAgentId, []),
if (runtimePresets?.length) {
return appendRetainedStoredModelPreset(
appendComposerCustomModelPresets(
runtimePresets,
collectCustomModelIds(currentAgentId, runtimePresets),
),
agentModelMap[currentAgentId],
currentAgentConfig,
Boolean(runtimeEntry?.catalogUnavailable),
);
}
const presets = getAgentModelPresets(
@@ -1221,15 +1286,22 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const filteredPresets = filterAgentModelPresetsForCliVersion(presets, cliVersion);
// Manual model ids typed in the composer (#3534) stay selectable even when
// the CLI catalog does not list them yet.
return appendComposerCustomModelPresets(
filteredPresets,
collectCustomModelIds(currentAgentId, filteredPresets),
return appendRetainedStoredModelPreset(
appendComposerCustomModelPresets(
filteredPresets,
collectCustomModelIds(currentAgentId, filteredPresets),
),
agentModelMap[currentAgentId],
currentAgentConfig,
// Until the initial catalog settles, show the choice a failed
// preflight would actually send instead of flashing Auto.
!runtimeEntry || !target || runtimeEntry.cacheKey !== target.cacheKey || runtimeEntry.catalogUnavailable,
);
}, [
currentAgentConfig,
currentAgentId,
runtimeAgentModelPresets,
runtimeModelLoading,
agentModelMap,
buildExternalAgentRuntimeModelTarget,
hasCodexCustomConfig,
codexConfigModel,
@@ -1454,17 +1526,24 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
getExternalAgentSdkBackend(currentAgentConfig),
),
);
const runtimePresets = appendComposerCustomModelPresets(
const runtimePresets = retainStoredModelPresetForCatalog(
catalogPresets,
collectCustomModelIds(sendAgentId, catalogPresets),
appendComposerCustomModelPresets(
catalogPresets,
collectCustomModelIds(sendAgentId, catalogPresets),
),
agentModelMapRef.current[sendAgentId],
currentAgentConfig,
Boolean(catalog.warning),
);
const storedModelId = agentModelMapRef.current[sendAgentId];
const defaultModelId = resolveSdkRuntimeCatalogDefaultModelId(catalog, currentAgentConfig);
if (
catalog.currentModelId
&& shouldAdoptSdkCurrentModel(catalog.currentModelId, storedModelId, runtimePresets)
defaultModelId
&& shouldAdoptSdkCurrentModel(defaultModelId, storedModelId, runtimePresets, currentAgentConfig)
) {
sendSelectedAgentModel = catalog.currentModelId;
} else if (shouldUseStoredAgentModel(storedModelId, runtimePresets)) {
sendSelectedAgentModel = defaultModelId;
} else if (shouldUseStoredAgentModel(storedModelId, runtimePresets, currentAgentConfig)) {
sendSelectedAgentModel = normalizeStoredAgentModelSelection(
storedModelId,
runtimePresets,
@@ -1994,14 +2073,18 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
canSendCurrentAgent={canSendCurrentAgent}
providerDisplayName={providerDisplayName}
modelDisplayName={modelDisplayName}
modelCatalogWarning={runtimeModelWarnings[currentAgentId]
modelCatalogWarning={!hasCodexCustomConfig
&& runtimeModelWarnings[currentAgentId]
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
? runtimeModelWarnings[currentAgentId].message
: undefined}
modelCatalogLoading={
getExternalAgentSdkBackend(currentAgentConfig) === 'opencode'
!hasCodexCustomConfig
&& Boolean(runtimeModelLoading[currentAgentId])
&& runtimeModelLoading[currentAgentId]?.cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
}
modelCatalogSource={modelCatalogSource}
modelCatalogFetchedAt={modelCatalogFetchedAt}
handleModelCatalogRetry={handleRetrySdkModelCatalog}
agentModelPresets={agentModelPresets}
// A managed Codex config's `model` field overrides every selection on
+1
View File
@@ -40,6 +40,7 @@ export interface AIChatSidePanelProps {
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
undoLastTurnInSession?: (
sessionId: string,
viewingScope?: Pick<AISessionScope, 'type' | 'targetId'>,
) => 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;
+369
View File
@@ -1,20 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
appendRetainedStoredModelPreset,
retainStoredModelPresetForCatalog,
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
canonicalizeEffortEncodedModelId,
createSdkRuntimeModelCache,
agentModelPresetsShallowEqual,
mergeFallbackThinkingLevels,
MODEL_CACHE_ENV_HINTS,
modelPresetsContainId,
normalizeStoredAgentModelSelection,
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
reconcileRuntimeModelWarning,
toSdkRuntimeModelCatalog,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
shouldUseStoredAgentModel,
} from './AIChatSidePanelHelpers';
import { createRequire } from 'node:module';
import type { AgentModelPreset, ExternalAgentConfig } from '../infrastructure/ai/types';
test('buildCursorListModelsAgentEnv injects cli-login auth mode for list-models', () => {
@@ -298,6 +306,157 @@ test('shouldUseStoredAgentModel trusts SDK defaults when no runtime list is retu
);
});
test('stored claude alias selections keep resolving against a full-id catalog', () => {
const claudeAgent: ExternalAgentConfig = {
id: 'managed_claude',
name: 'Claude Code',
command: 'claude',
enabled: true,
sdkBackend: 'claude',
};
const fullIdPresets: AgentModelPreset[] = [
{ id: 'claude-sonnet-5-5', name: 'Sonnet 5.5' },
{ id: 'claude-haiku-5-5', name: 'Haiku 5.5' },
];
// Legacy persisted alias ids (pre-2026-10 preset refresh) still resolve for
// the claude backend, with or without an effort suffix.
assert.equal(shouldUseStoredAgentModel('sonnet', fullIdPresets, claudeAgent), true);
assert.equal(shouldUseStoredAgentModel('sonnet/high', fullIdPresets, claudeAgent), true);
// ...and are never silently replaced by the catalog's current model.
assert.equal(shouldAdoptSdkCurrentModel('claude-sonnet-5-5', 'sonnet', fullIdPresets, claudeAgent), false);
assert.equal(shouldAdoptSdkCurrentModel('claude-sonnet-5-5', 'sonnet/high', fullIdPresets, claudeAgent), false);
// Without agent context the previous behavior is unchanged.
assert.equal(shouldUseStoredAgentModel('sonnet', fullIdPresets), false);
assert.equal(shouldAdoptSdkCurrentModel('claude-sonnet-5-5', 'sonnet', fullIdPresets), true);
// Non-claude backends and non-alias stored ids are untouched.
const opencodeAgent: ExternalAgentConfig = {
id: 'managed_opencode',
name: 'OpenCode',
command: 'opencode',
enabled: true,
sdkBackend: 'opencode',
};
assert.equal(shouldUseStoredAgentModel('sonnet', fullIdPresets, opencodeAgent), false);
assert.equal(shouldAdoptSdkCurrentModel('claude-sonnet-5-5', 'gpt-5.5', fullIdPresets, claudeAgent), true);
});
test('a saved Copilot model survives the auto-only degraded fallback', () => {
const copilotAgent: ExternalAgentConfig = {
id: 'managed_copilot',
name: 'GitHub Copilot',
command: 'copilot',
enabled: true,
sdkBackend: 'copilot',
};
const autoOnlyFallback: AgentModelPreset[] = [{ id: 'auto', name: 'Auto' }];
// Live discovery failed (no last-known store yet): the saved explicit model
// must keep resolving instead of silently switching to `auto`.
assert.equal(shouldUseStoredAgentModel('claude-sonnet-4.5', autoOnlyFallback, copilotAgent, true), true);
assert.equal(shouldUseStoredAgentModel('claude-sonnet-4.5/high', autoOnlyFallback, copilotAgent, true), true);
// Other backends with the same shape are unaffected.
const opencodeAgent: ExternalAgentConfig = {
id: 'managed_opencode',
name: 'OpenCode',
command: 'opencode',
enabled: true,
sdkBackend: 'opencode',
};
assert.equal(shouldUseStoredAgentModel('claude-sonnet-4.5', autoOnlyFallback, opencodeAgent), false);
// Composer custom ids are mixed into the same picker list; the degraded
// fallback must still be detected with extra rows present.
const mixedFallback: AgentModelPreset[] = [
{ id: 'auto', name: 'Auto', description: 'Automatic model selection' },
{ id: 'gpt-custom', name: 'gpt-custom' },
];
assert.equal(shouldUseStoredAgentModel('claude-sonnet-4.5', mixedFallback, copilotAgent, true), true);
assert.equal(modelPresetsContainId(
appendRetainedStoredModelPreset(mixedFallback, 'claude-sonnet-4.5', copilotAgent, true),
'claude-sonnet-4.5',
), true);
// A real Copilot catalog (multiple entries with named rows) does not
// trigger the fallback, mixed or not.
assert.equal(
shouldUseStoredAgentModel('claude-sonnet-4.5', [
{ id: 'auto', name: 'Auto' },
{ id: 'gpt-5', name: 'GPT-5' },
], copilotAgent),
false,
);
assert.equal(
shouldUseStoredAgentModel('claude-sonnet-4.5', [
{ id: 'auto', name: 'Auto' },
{ id: 'gpt-5', name: 'GPT-5' },
{ id: 'gpt-custom', name: 'gpt-custom' },
], copilotAgent),
false,
);
});
test('appendRetainedStoredModelPreset makes preserved saved models visible', () => {
const claudeAgent: ExternalAgentConfig = {
id: 'managed_claude',
name: 'Claude Code',
command: 'claude',
enabled: true,
sdkBackend: 'claude',
};
const fullIdPresets: AgentModelPreset[] = [{ id: 'claude-sonnet-5-5', name: 'Sonnet 5.5' }];
// A stored claude alias absent from a full-id catalog gains a preset row
// (reusing the build-time preset so thinking levels come along).
const withAlias = appendRetainedStoredModelPreset(fullIdPresets, 'sonnet/high', claudeAgent);
assert.equal(withAlias.length, 2);
assert.equal(withAlias[1].id, 'sonnet');
assert.equal(modelPresetsContainId(withAlias, 'sonnet/high'), true);
// The copilot auto-only degraded fallback keeps a saved explicit model
// selectable as its own row.
const copilotAgent: ExternalAgentConfig = {
id: 'managed_copilot',
name: 'GitHub Copilot',
command: 'copilot',
enabled: true,
sdkBackend: 'copilot',
};
const withCopilot = appendRetainedStoredModelPreset(
[{ id: 'auto', name: 'Auto' }],
'claude-sonnet-4.5',
copilotAgent,
true,
);
assert.deepEqual(withCopilot[1], { id: 'claude-sonnet-4.5', name: 'claude-sonnet-4.5' });
// An effort-suffixed saved id keeps its full spelling so the appended row
// matches the selection the send preflight passes.
const withCopilotSuffix = appendRetainedStoredModelPreset(
[{ id: 'auto', name: 'Auto' }],
'claude-sonnet-4.5/high',
copilotAgent,
true,
);
assert.deepEqual(withCopilotSuffix[1], { id: 'claude-sonnet-4.5/high', name: 'claude-sonnet-4.5/high' });
assert.equal(modelPresetsContainId(withCopilotSuffix, 'claude-sonnet-4.5/high'), true);
// A base-only custom row (no thinking levels) does not cover the stored
// suffixed id, so the exact retained id is appended beside it.
const baseOnly: AgentModelPreset[] = [
{ id: 'auto', name: 'Auto' },
{ id: 'claude-sonnet-4.5', name: 'claude-sonnet-4.5' },
];
const besideBase = appendRetainedStoredModelPreset(baseOnly, 'claude-sonnet-4.5/high', copilotAgent, true);
assert.equal(besideBase.length, 3);
assert.equal(modelPresetsContainId(besideBase, 'claude-sonnet-4.5/high'), true);
// Listed or non-retained selections are untouched.
assert.equal(appendRetainedStoredModelPreset(fullIdPresets, 'claude-sonnet-5-5', claudeAgent), fullIdPresets);
assert.equal(appendRetainedStoredModelPreset(fullIdPresets, 'gpt-5.5', claudeAgent), fullIdPresets);
assert.equal(appendRetainedStoredModelPreset(fullIdPresets, undefined, claudeAgent), fullIdPresets);
});
test('SDK runtime model cache coalesces concurrent refreshes', async () => {
const cache = createSdkRuntimeModelCache();
let calls = 0;
@@ -440,3 +599,213 @@ test('SDK runtime model cache stays bounded under agent configuration churn', as
assert.equal(cache.read('agent:0'), null);
assert.equal(cache.read('agent:19')?.currentModelId, 'model-19');
});
test('SDK runtime model cache preserves degraded warnings until a successful retry', async () => {
const cache = createSdkRuntimeModelCache();
const degraded = {
currentModelId: 'auto',
models: [{ id: 'auto', name: 'Auto' }],
warning: 'Live discovery failed; serving last-known-good models',
};
assert.equal((await cache.refresh('copilot', async () => degraded)).warning, degraded.warning);
assert.equal(cache.read('copilot')?.warning, degraded.warning);
assert.equal((await cache.refresh('copilot', async () => {
assert.fail('A second panel should use the cached catalog within the TTL');
})).warning, degraded.warning);
await cache.refresh('copilot', async () => ({
currentModelId: 'auto',
models: [{ id: 'auto', name: 'Auto' }],
}), { force: true });
assert.equal(cache.read('copilot')?.warning, undefined);
});
// #3584 alignment: OpenCode must render build-time presets while its live
// catalog load is pending, exactly like every other backend. The old host
// code suppressed presets for opencode while `runtimeModelLoading` was set,
// leaving the picker empty until the pull resolved. Guard against it coming
// back: the preset fallback in the panel must not gate on opencode loading.
test('host preset fallback does not suppress presets for a loading opencode catalog', () => {
const source = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.doesNotMatch(source, /getExternalAgentSdkBackend\(currentAgentConfig\) === 'opencode'[\s\S]*?runtimeModelLoading/);
// Build-time presets remain the fallback whenever no runtime catalog is
// active for the agent (loading included).
assert.match(source, /const presets = getAgentModelPresets\(/);
});
test('reconcileRuntimeModelWarning adds the banner for a warned catalog and keeps unrelated agents', () => {
const current = { other: { cacheKey: 'k-other', message: 'x' } };
const next = reconcileRuntimeModelWarning(current, 'copilot', 'k1', true, 'warn');
assert.deepEqual(next, {
other: { cacheKey: 'k-other', message: 'x' },
copilot: { cacheKey: 'k1', message: 'warn' },
});
});
test('reconcileRuntimeModelWarning returns the same object when nothing changes', () => {
const current = { copilot: { cacheKey: 'k1', message: 'warn' } };
assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k1', true, 'warn'), current);
assert.equal(reconcileRuntimeModelWarning({}, 'copilot', 'k1', false, 'warn').copilot, undefined);
});
test('reconcileRuntimeModelWarning clears only the banner that belongs to this cache key', () => {
const current = { copilot: { cacheKey: 'k1', message: 'warn' } };
assert.deepEqual(reconcileRuntimeModelWarning(current, 'copilot', 'k1', false, 'warn'), {});
// A banner that belongs to another cache key (another profile) is not ours to clear.
assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current);
});
test('renderer model cache env hints cover every key the main-process catalog cache fingerprints', () => {
// Both caches must split on the same profile-affecting environment: a key that
// only the main process knows lets the renderer serve one profile's catalog to another.
const require = createRequire(import.meta.url);
const { SDK_MODEL_CACHE_ENV_KEYS } = require('../electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs') as {
SDK_MODEL_CACHE_ENV_KEYS: string[];
};
const hints = new Set<string>(MODEL_CACHE_ENV_HINTS);
const missing = SDK_MODEL_CACHE_ENV_KEYS.filter((key) => !hints.has(key));
assert.deepEqual(missing, []);
});
test('toSdkRuntimeModelCatalog keeps the provenance main reported for a last-known-good serve', () => {
const catalog = toSdkRuntimeModelCatalog({
ok: true,
currentModelId: 'm-1',
models: [{ id: 'm-1', name: 'M1' }],
warning: 'live fetch failed',
source: 'last-known-good',
fetchedAt: '2026-10-10T08:00:00.000Z',
});
assert.deepEqual(catalog, {
currentModelId: 'm-1',
models: [{ id: 'm-1', name: 'M1' }],
warning: 'live fetch failed',
source: 'last-known-good',
fetchedAt: '2026-10-10T08:00:00.000Z',
});
});
test('toSdkRuntimeModelCatalog tolerates an older main without provenance or with unknown values', () => {
assert.deepEqual(
toSdkRuntimeModelCatalog({ ok: true, models: [{ id: 'a', name: 'A' }] }),
{ currentModelId: null, models: [{ id: 'a', name: 'A' }], warning: null },
);
const odd = toSdkRuntimeModelCatalog({
ok: true,
models: [],
source: 'something-else' as never,
fetchedAt: 42 as never,
});
assert.equal(odd.source, undefined);
assert.equal(odd.fetchedAt, undefined);
});
test('retainStoredModelPresetForCatalog leaves the built-in fallback list alone when no catalog arrived', () => {
const claudeAgent = { id: 'claude', command: 'claude', sdkBackend: 'claude' } as unknown as ExternalAgentConfig;
// The first Claude catalog request failed: nothing to extend. Appending only
// the saved alias would make a one-row list authoritative and hide the
// built-in presets, so the empty list must stay empty.
assert.deepEqual(retainStoredModelPresetForCatalog([], [], 'sonnet', claudeAgent), []);
});
test('retainStoredModelPresetForCatalog drops composer custom rows too when no catalog arrived', () => {
const claudeAgent = { id: 'claude', command: 'claude', sdkBackend: 'claude' } as unknown as ExternalAgentConfig;
// The callers wrap the empty catalog with the user's custom composer models, so
// the list is non-empty even though no catalog arrived. Stored as the runtime
// list it would still hide the built-in presets; the panel appends custom
// models on top of the fallback list itself.
const withCustom = [{ id: 'my-custom-model', name: 'my-custom-model' }];
assert.deepEqual(retainStoredModelPresetForCatalog([], withCustom, 'sonnet', claudeAgent), []);
});
test('retainStoredModelPresetForCatalog still retains a saved selection on top of a real catalog', () => {
const claudeAgent = { id: 'claude', command: 'claude', sdkBackend: 'claude' } as unknown as ExternalAgentConfig;
const catalog = [{ id: 'claude-opus-5-5', name: 'Opus 5.5' }];
const retained = retainStoredModelPresetForCatalog(catalog, catalog, 'sonnet', claudeAgent);
assert.deepEqual(retained, appendRetainedStoredModelPreset(catalog, 'sonnet', claudeAgent));
});
test('catalog source adaptation preserves explicit Copilot failure retention', () => {
const agent = { id: 'copilot', command: 'copilot', sdkBackend: 'copilot' } as ExternalAgentConfig;
const catalog = toSdkRuntimeModelCatalog({
ok: true,
models: [{ id: 'auto', name: 'Auto' }],
warning: 'live discovery unavailable',
source: 'last-known-good',
fetchedAt: '2026-10-15T09:00:00.000Z',
});
const presets = retainStoredModelPresetForCatalog(
catalog.models, catalog.models, 'saved-model', agent, Boolean(catalog.warning),
);
assert.deepEqual(presets.map(model => model.id), ['auto', 'saved-model']);
assert.deepEqual(retainStoredModelPresetForCatalog(
catalog.models, catalog.models, 'saved-model', agent, false,
).map(model => model.id), ['auto']);
});
test('SDK runtime model cache keeps the retry warning when a degraded refresh retains the cached catalog', async () => {
let now = 1_000;
const cache = createSdkRuntimeModelCache({ now: () => now });
const key = 'copilot:/opt/bin/copilot';
await cache.refresh(key, async () => ({
currentModelId: 'gpt-5',
models: [{ id: 'gpt-5', name: 'GPT-5' }],
source: 'live',
fetchedAt: '2026-10-15T09:00:00.000Z',
}));
now = 2_000;
const retried = await cache.refresh(
key,
async () => ({ currentModelId: null, models: [], warning: 'catalog unavailable' }),
{ force: true },
);
assert.deepEqual(retried.models, [{ id: 'gpt-5', name: 'GPT-5' }]);
assert.equal(retried.warning, 'catalog unavailable');
assert.equal(retried.source, 'last-known-good');
assert.equal(retried.fetchedAt, '2026-10-15T09:00:00.000Z');
// Later reads retain the warning without extending the good catalog's age.
assert.equal(cache.read(key)?.warning, 'catalog unavailable');
assert.equal(cache.read(key)?.updatedAt, 1_000);
const nextRead = await cache.refresh(key, async () => { throw new Error('fresh cache should be reused'); });
assert.equal(nextRead.warning, 'catalog unavailable');
assert.equal(nextRead.source, 'last-known-good');
});
test('degraded Copilot selection survives custom rows while live auto-only remains authoritative', () => {
const agent: ExternalAgentConfig = { id: 'copilot', name: 'Copilot', command: 'copilot', enabled: true, sdkBackend: 'copilot' };
const customRows = [{ id: 'manual-model', name: 'manual-model' }];
const retained = appendRetainedStoredModelPreset(customRows, 'saved-model', agent, true);
assert.equal(modelPresetsContainId(retained, 'saved-model'), true);
assert.equal(shouldUseStoredAgentModel('saved-model', retained, agent, true), true);
assert.equal(shouldAdoptSdkCurrentModel('auto', 'saved-model', retained, agent), false);
const live = [{ id: 'auto', name: 'auto' }];
assert.equal(appendRetainedStoredModelPreset(live, 'saved-model', agent, false), live);
assert.equal(shouldUseStoredAgentModel('saved-model', live, agent, false), false);
assert.equal(shouldAdoptSdkCurrentModel('auto', 'saved-model', live, agent), true);
});
test('renderer catalogs separate supported credential and profile overrides', () => {
const agent = { id: 'agent', command: '/same/cli', sdkBackend: 'copilot' };
for (const name of ['COPILOT_GITHUB_TOKEN', 'GH_TOKEN', 'GITHUB_TOKEN', 'GH_CONFIG_DIR', 'CODEBUDDY_API_KEY', 'CODEBUDDY_AUTH_TOKEN', 'CODEBUDDY_INTERNET_ENVIRONMENT', 'XAI_API_KEY', 'GROK_CONFIG_DIR']) {
const key = buildSdkRuntimeModelCacheKey({ ...agent, env: { [name]: 'fixture-profile-a' } });
assert.notEqual(key, buildSdkRuntimeModelCacheKey({ ...agent, env: { [name]: 'fixture-profile-b' } }), name);
assert.doesNotMatch(key, /fixture-profile-a/);
}
});
test('Copilot successful catalog without current id replaces an unlisted saved choice before failure', () => {
const agent: ExternalAgentConfig = { id: 'copilot', name: 'Copilot', command: 'copilot', enabled: true, sdkBackend: 'copilot' };
// Copilot returns an array, so IPC has no currentModelId even on success.
const live = { models: [{ id: 'auto', name: 'auto' }], currentModelId: null };
const next = resolveSdkRuntimeCatalogDefaultModelId(live, agent);
assert.equal(next, 'auto');
assert.equal(shouldAdoptSdkCurrentModel(next, 'saved-model', live.models, agent), true);
const laterFailure = appendRetainedStoredModelPreset(live.models, next, agent, true);
assert.deepEqual(laterFailure, live.models);
assert.equal(resolveSdkRuntimeCatalogDefaultModelId({ ...live, warning: 'unavailable' }, agent), null);
});
+222 -4
View File
@@ -1,4 +1,5 @@
import {
getAgentModelPresets,
resolveAgentModelSelection,
type AgentModelPreset,
type ExternalAgentConfig,
@@ -18,9 +19,22 @@ export {
modelPresetsContainId,
};
export type SdkRuntimeModelCatalogSource = 'live' | 'last-known-good' | 'presets';
export type SdkRuntimeModelCatalog = {
currentModelId: string | null;
models: AgentModelPreset[];
// Degraded loads (e.g. last-known-good serve) carry their warning so a
// cached hit in another panel or after a remount still shows the retry
// banner instead of presenting stale models as live.
warning?: string | null;
// Provenance of the models list: 'live' when the SDK fetch succeeded,
// 'last-known-good' when main served the persisted previous success.
// Absent (older main) behaves like a live fetch for display purposes.
source?: Exclude<SdkRuntimeModelCatalogSource, 'presets'>;
// ISO timestamp of the successful fetch backing this catalog (live fetch
// time, or the persisted last-known-good fetchedAt).
fetchedAt?: string;
};
export type SdkRuntimeModelCacheEntry = SdkRuntimeModelCatalog & {
@@ -41,7 +55,7 @@ const SDK_RUNTIME_MODEL_CACHE_TTL_MS = 5 * 60 * 1000;
const SDK_RUNTIME_MODEL_CACHE_MAX_ENTRIES = 64;
// Keep in sync with main-process SDK_MODEL_CACHE_ENV_KEYS: profile-affecting
// env must bust the renderer cache so we re-query after OpenCode config switches.
const MODEL_CACHE_ENV_HINTS = [
export const MODEL_CACHE_ENV_HINTS = [
'HOME',
'USERPROFILE',
'XDG_CONFIG_HOME',
@@ -49,6 +63,7 @@ const MODEL_CACHE_ENV_HINTS = [
'CLAUDE_CONFIG_DIR',
'ANTHROPIC_API_KEY',
'ANTHROPIC_AUTH_TOKEN',
'ANTHROPIC_BASE_URL',
'CLAUDE_CODE_OAUTH_TOKEN',
'OPENCODE_BIN',
'OPENCODE_CONFIG',
@@ -64,15 +79,41 @@ const MODEL_CACHE_ENV_HINTS = [
'XDG_CACHE_HOME',
'CLAUDE_CODE_EXECUTABLE',
'CODEBUDDY_CODE_PATH',
'CODEBUDDY_API_KEY',
'CODEBUDDY_AUTH_TOKEN',
'CODEBUDDY_INTERNET_ENVIRONMENT',
'XAI_API_KEY',
'GROK_CONFIG_DIR',
'COPILOT_GITHUB_TOKEN',
'GH_TOKEN',
'GITHUB_TOKEN',
'GH_CONFIG_DIR',
'CURSOR_API_KEY',
'NETCATTY_CURSOR_AUTH_MODE',
'NETCATTY_CURSOR_CLI_BIN',
] as const;
const SDK_RUNTIME_MODEL_CATALOG_SOURCES = new Set(['live', 'last-known-good']);
function normalizeCatalogSource(
source: unknown,
): SdkRuntimeModelCatalog['source'] {
return typeof source === 'string' && SDK_RUNTIME_MODEL_CATALOG_SOURCES.has(source)
? source as SdkRuntimeModelCatalog['source']
: undefined;
}
function normalizeCatalogFetchedAt(fetchedAt: unknown): string | undefined {
return typeof fetchedAt === 'string' && fetchedAt ? fetchedAt : undefined;
}
function cloneCatalog(catalog: SdkRuntimeModelCatalog): SdkRuntimeModelCatalog {
return {
currentModelId: catalog.currentModelId ?? null,
models: [...catalog.models],
...(catalog.warning ? { warning: catalog.warning } : {}),
...(catalog.source ? { source: catalog.source } : {}),
...(catalog.fetchedAt ? { fetchedAt: catalog.fetchedAt } : {}),
};
}
@@ -82,6 +123,36 @@ function normalizeSdkRuntimeModelCatalog(catalog: SdkRuntimeModelCatalog): SdkRu
models: Array.isArray(catalog.models)
? catalog.models.filter((model): model is AgentModelPreset => Boolean(model?.id))
: [],
...(catalog.warning ? { warning: catalog.warning } : {}),
...(normalizeCatalogSource(catalog.source) ? { source: normalizeCatalogSource(catalog.source) } : {}),
...(normalizeCatalogFetchedAt(catalog.fetchedAt) ? { fetchedAt: normalizeCatalogFetchedAt(catalog.fetchedAt) } : {}),
};
}
/** The list-models IPC result as the renderer receives it. */
export type SdkListModelsResult = {
ok: boolean;
models?: AgentModelPreset[];
currentModelId?: string | null;
warning?: string;
error?: string;
// Provenance reported by main (absent on an older main).
source?: Exclude<SdkRuntimeModelCatalogSource, 'presets'>;
fetchedAt?: string;
};
/**
* Adapt a successful list-models result to a catalog while keeping the
* provenance main reported. Dropping source/fetchedAt would make the picker
* label a persisted last-known-good list as a live catalog.
*/
export function toSdkRuntimeModelCatalog(result: SdkListModelsResult): SdkRuntimeModelCatalog {
return {
currentModelId: result.currentModelId ?? null,
models: result.models ?? [],
warning: result.warning ?? null,
...(normalizeCatalogSource(result.source) ? { source: normalizeCatalogSource(result.source) } : {}),
...(normalizeCatalogFetchedAt(result.fetchedAt) ? { fetchedAt: normalizeCatalogFetchedAt(result.fetchedAt) } : {}),
};
}
@@ -187,7 +258,16 @@ export function createSdkRuntimeModelCache(options: SdkRuntimeModelCacheOptions
.then((catalog) => {
const normalized = normalizeSdkRuntimeModelCatalog(catalog);
if (normalized.models.length === 0 && !normalized.currentModelId) {
return cached ? cloneCatalog(cached) : cloneCatalog(normalized);
// A degraded retry keeps the older catalog usable but must still
// report its own warning, or the banner and Retry would vanish.
if (!cached) return cloneCatalog(normalized);
const retained = cloneCatalog(cached);
if (normalized.warning) {
retained.warning = normalized.warning;
retained.source = 'last-known-good';
touchEntry(key, { ...retained, updatedAt: cached.updatedAt });
}
return retained;
}
touchEntry(key, { ...cloneCatalog(normalized), updatedAt: now() });
pruneEntries();
@@ -207,6 +287,32 @@ export function createSdkRuntimeModelCache(options: SdkRuntimeModelCacheOptions
export const sdkRuntimeModelCache = createSdkRuntimeModelCache();
export type RuntimeModelWarnings = Record<string, { cacheKey: string; message: string }>;
/**
* Make the per-agent catalog warning banner match a catalog result. Used both
* for cache reads and after a refresh settles: a refresh that coalesced onto
* another panel's in-flight load never runs its own loader callback, so
* the caller must reconcile the banner from the shared result itself.
* Returns the same object when nothing changes (no extra render). A banner
* that belongs to a different cache key is never cleared.
*/
export function reconcileRuntimeModelWarning(
current: RuntimeModelWarnings,
agentId: string,
cacheKey: string,
hasWarning: boolean,
message: string,
): RuntimeModelWarnings {
const existing = current[agentId];
if (hasWarning) {
return existing?.cacheKey === cacheKey ? current : { ...current, [agentId]: { cacheKey, message } };
}
if (existing?.cacheKey !== cacheKey) return current;
const { [agentId]: _removed, ...rest } = current;
return rest;
}
export function mergeFallbackThinkingLevels(
runtime: AgentModelPreset[],
fallbacks: AgentModelPreset[],
@@ -278,12 +384,71 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
|| sdkBackend === 'mimo';
}
// Alias ids the claude CLI itself still resolves: its alias table maps
// opus/sonnet/haiku -> claude-*-5-5 and fable -> claude-fable-5-1. Preset
// lists before the 2026-10 catalog refresh persisted `sonnet`/`haiku` as
// preset ids, so a stored alias must keep resolving instead of being
// silently replaced by the live catalog's full id.
const CLAUDE_CLI_MODEL_ALIASES = new Set(['opus', 'sonnet', 'haiku', 'fable']);
function isStillValidClaudeAlias(
storedModelId: string | null | undefined,
agent?: ExternalAgentConfig,
): boolean {
if (!storedModelId) return false;
if (getExternalAgentSdkBackend(agent) !== 'claude') return false;
const baseId = canonicalizeEffortEncodedModelId(storedModelId).split('/')[0];
return CLAUDE_CLI_MODEL_ALIASES.has(baseId);
}
// Retain unlisted Copilot choices while discovery is pending or failed.
// A successful auto-only catalog is authoritative, regardless of row names.
function shouldRetainUnlistedCopilotModel(
agent: ExternalAgentConfig | undefined,
retainUnlistedModel: boolean,
): boolean {
return retainUnlistedModel && getExternalAgentSdkBackend(agent) === 'copilot';
}
/**
* True when a stored selection still resolves even though it is absent from
* the given presets: either the presets list it under an effort-suffixed
* spelling, or it is a claude CLI alias the backend accepts verbatim.
*/
export function storedModelStillResolvesForAgent(
storedModelId: string | null | undefined,
presets: AgentModelPreset[],
agent?: ExternalAgentConfig,
): boolean {
if (!storedModelId) return false;
return modelPresetsContainId(presets, storedModelId)
|| isStillValidClaudeAlias(storedModelId, agent);
}
export function resolveSdkRuntimeCatalogDefaultModelId(
catalog: SdkRuntimeModelCatalog,
agent?: ExternalAgentConfig,
): string | null {
if (catalog.currentModelId) return catalog.currentModelId;
// Copilot lists models without a current id. Commit the same visible
// default on live success, so a later failed refresh cannot revive an
// unlisted saved choice that the live catalog has already replaced.
if (!catalog.warning && getExternalAgentSdkBackend(agent) === 'copilot' && catalog.models[0]) {
return resolveAgentModelSelection(catalog.models[0]);
}
return null;
}
export function shouldAdoptSdkCurrentModel(
currentModelId: string | null | undefined,
storedModelId: string | null | undefined,
runtimePresets: AgentModelPreset[],
agent?: ExternalAgentConfig,
): boolean {
if (!currentModelId) return false;
// A stored claude alias the CLI still resolves is a user choice: never
// overwrite it with the catalog's current model.
if (isStillValidClaudeAlias(storedModelId, agent)) return false;
return !storedModelId
|| runtimePresets.length === 0
|| !modelPresetsContainId(runtimePresets, storedModelId);
@@ -302,10 +467,63 @@ export function shouldUseStoredAgentModel(
storedModelId: string | null | undefined,
presets: AgentModelPreset[],
agent?: ExternalAgentConfig,
retainUnlistedModel = false,
): boolean {
if (!storedModelId) return false;
return modelPresetsContainId(presets, storedModelId)
|| (presets.length === 0 && shouldLoadSdkRuntimeModels(agent));
return storedModelStillResolvesForAgent(storedModelId, presets, agent)
|| (presets.length === 0 && shouldLoadSdkRuntimeModels(agent))
|| shouldRetainUnlistedCopilotModel(agent, retainUnlistedModel);
}
/**
* A stored selection preserved through the claude-alias or copilot
* degraded fallback has no preset row of its own; append one (reusing the
* build-time preset when it defines the id) so the picker can render and
* check the selection while the send preflight passes the same value.
*/
export function appendRetainedStoredModelPreset(
presets: AgentModelPreset[],
storedModelId: string | null | undefined,
agent?: ExternalAgentConfig,
retainUnlistedModel = false,
): AgentModelPreset[] {
if (!storedModelId || modelPresetsContainId(presets, storedModelId)) return presets;
if (!isStillValidClaudeAlias(storedModelId, agent)
&& !shouldRetainUnlistedCopilotModel(agent, retainUnlistedModel)) {
return presets;
}
const canonical = canonicalizeEffortEncodedModelId(storedModelId);
const baseId = canonical.split('/')[0];
if (presets.some((preset) => preset.id === baseId)) {
// The base row did not cover the stored id (checked above), so a suffixed
// selection needs its own exact row; a bare id is already present.
return canonical === baseId ? presets : [...presets, { id: canonical, name: canonical }];
}
const fallback = getAgentModelPresets(agent?.command, getExternalAgentSdkBackend(agent))
.find((preset) => preset.id === baseId);
// Keep the exact stored id (including any effort suffix) so the appended
// row still matches the selection the send preflight passes.
return [...presets, fallback ?? { id: canonical, name: canonical }];
}
/**
* Retain the saved selection on top of the presets built for a catalog, but
* only when a catalog actually arrived. When none did (the request failed
* before any last-known-good entry existed) the result is empty so the agent
* keeps its whole built-in fallback list: a lone retained row, or only the
* user's custom composer models, would be stored as the authoritative runtime
* list and hide every built-in preset. The panel appends custom models on top
* of the fallback list itself.
*/
export function retainStoredModelPresetForCatalog(
catalogPresets: AgentModelPreset[],
presets: AgentModelPreset[],
storedModelId: string | null | undefined,
agent?: ExternalAgentConfig,
retainUnlistedModel = false,
): AgentModelPreset[] {
if (catalogPresets.length === 0) return [];
return appendRetainedStoredModelPreset(presets, storedModelId, agent, retainUnlistedModel);
}
export function generateId(): string {
@@ -0,0 +1,94 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { I18nProvider } from '../application/i18n/I18nProvider';
import { createDomRenderer, dispatchDomEvent, flushEffects, installDomEnvironment, runWithAct } from './test-support/renderReactDom';
test('provider disconnect waits for completion, reports failure and permits retry', async () => {
const dom = installDomEnvironment();
const globals = {
localStorage: dom.window.localStorage,
MutationObserver: dom.window.MutationObserver,
NodeFilter: dom.window.NodeFilter,
HTMLInputElement: dom.window.HTMLInputElement,
};
const previous = new Map(Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
for (const [key, value] of Object.entries(globals)) Object.defineProperty(globalThis, key, { configurable: true, value });
const { ProviderCard } = await import('./cloud-sync/CloudSyncControls');
const { toast } = await import('./ui/toast');
const renderer = await createDomRenderer(dom.document);
const notices: string[] = [];
const info = toast.info;
const error = toast.error;
toast.info = (message) => { notices.push(`info:${message}`); };
toast.error = (message) => { notices.push(`error:${message}`); };
let finish: (() => void) | undefined;
let fail = true;
let calls = 0;
try {
await renderer.render(
<I18nProvider locale="en">
<ProviderCard provider="webdav" name="WebDAV" icon={null} isConnected isSyncing={false}
onConnect={() => {}} onSync={() => {}}
onDisconnect={() => {
calls += 1;
if (fail) throw new Error('fixture failure');
return new Promise<void>((resolve) => { finish = resolve; });
}} />
</I18nProvider>,
);
const click = async (node: Element) => {
await dispatchDomEvent(node, new dom.window.MouseEvent('click', { bubbles: true }));
await flushEffects();
};
const button = dom.document.querySelector('button[aria-label="Disconnect"]');
assert.ok(button);
assert.equal(button.textContent, 'Disconnect');
await click(button);
let dialog = dom.document.querySelector('[role="dialog"]');
assert.ok(dialog);
assert.match(dialog.textContent ?? '', /backup history and sync encryption password stay here/);
const confirm = () => {
const node = [...dom.document.querySelectorAll('[role="dialog"] button')].find((el) => el.textContent === 'Disconnect');
assert.ok(node);
return node as HTMLButtonElement;
};
await click(confirm());
assert.equal(calls, 1);
assert.equal(notices.length, 1);
assert.match(notices[0], /^error:Could not finish disconnecting from WebDAV/);
assert.ok(dom.document.querySelector('[role="dialog"]'));
assert.equal(confirm().disabled, false);
fail = false;
await click(confirm());
assert.equal(calls, 2);
assert.equal(confirm().disabled, true);
assert.equal(notices.length, 1);
await runWithAct(async () => { finish?.(); });
await flushEffects();
assert.equal(dom.document.querySelector('[role="dialog"]'), null);
assert.equal(notices.length, 2);
assert.match(notices[1], /^info:Encrypted sync copies may still exist in your WebDAV storage/);
assert.doesNotMatch(notices[1], /\{name\}/);
// Cancelling a new confirmation never calls the disconnect callback.
await click(button);
dialog = dom.document.querySelector('[role="dialog"]');
assert.ok(dialog);
const cancel = [...dialog.querySelectorAll('button')].find((el) => el.textContent === 'Cancel');
assert.ok(cancel);
await click(cancel);
assert.equal(calls, 2);
} finally {
toast.info = info;
toast.error = error;
await renderer.unmount();
// Radix restores focus on a timer after unmount. Keep the DOM globals
// installed until that cleanup has dispatched its final event.
await new Promise((resolve) => setTimeout(resolve, 0));
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
dom.cleanup();
}
});
+35 -1
View File
@@ -27,8 +27,9 @@ import {
toGlobalHistoryDisplayEntries,
} from '../domain/globalHistory';
import type { Host, RemoteHistoryEntry, ShellHistoryEntry } from '../domain/models';
import { removeCommandHistoryEntry } from './terminal/autocomplete/commandHistoryStore';
import { removeCommandHistoryEntry } from '../application/state/commandHistoryStore';
import { cn } from '../lib/utils';
import { ConfirmDialog } from './ui/confirm-dialog';
import type { RemoteHistoryHostState } from '../application/state/useRemoteHistoryState';
import {
VariableSizeVirtualList,
@@ -46,6 +47,7 @@ export interface HistorySidePanelProps {
globalEntries: ShellHistoryEntry[];
onFetch: (sessionId: string, hostId: string) => void;
onDeleteGlobalEntry?: (entryId: string) => void;
onClearGlobalHistory?: () => void;
/** Paste into the terminal without executing (no trailing Enter). */
onPasteToTerminal: (command: string) => void;
/** Write to the terminal and execute (append Enter). */
@@ -115,6 +117,7 @@ const HistorySidePanelInner: React.FC<HistorySidePanelProps> = ({
globalEntries,
onFetch,
onDeleteGlobalEntry,
onClearGlobalHistory,
onPasteToTerminal,
onRunInTerminal,
isVisible = true,
@@ -123,6 +126,7 @@ const HistorySidePanelInner: React.FC<HistorySidePanelProps> = ({
const [scope, setScope] = useState<HistoryPanelScope>('host');
const [search, setSearch] = useState('');
const [selectedEntryId, setSelectedEntryId] = useState<string | null>(null);
const [clearAllOpen, setClearAllOpen] = useState(false);
const listRef = useRef<VariableSizeVirtualListHandle>(null);
const protocol = focusedHost?.protocol;
@@ -208,6 +212,14 @@ const HistorySidePanelInner: React.FC<HistorySidePanelProps> = ({
setSelectedEntryId(null);
}, [globalEntries, onDeleteGlobalEntry, scope, sourceEntries]);
const handleClearAll = useCallback(() => {
// The application-state action clears both the global shell history and the
// autocomplete history, and fans the clear out to every renderer.
onClearGlobalHistory?.();
setClearAllOpen(false);
setSelectedEntryId(null);
}, [onClearGlobalHistory]);
const handleRowClick = useCallback((entryId: string) => {
setSelectedEntryId((current) => {
const next = current === entryId ? null : entryId;
@@ -294,6 +306,18 @@ const HistorySidePanelInner: React.FC<HistorySidePanelProps> = ({
<RefreshCw size={14} className={cn(state.loading && 'animate-spin')} />
</button>
)}
{scope === 'global' && (
<button
type="button"
onClick={() => setClearAllOpen(true)}
disabled={!onClearGlobalHistory}
title={t('history.action.clearAll')}
aria-label={t('history.action.clearAll')}
className="shrink-0 h-6 w-6 flex items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-40 disabled:hover:text-muted-foreground disabled:hover:bg-transparent"
>
<Trash2 size={14} />
</button>
)}
</div>
<div className="shrink-0 flex items-center gap-2 px-3 py-1.5 text-[11px] text-muted-foreground border-b border-border/30 min-h-[28px]">
@@ -411,6 +435,16 @@ const HistorySidePanelInner: React.FC<HistorySidePanelProps> = ({
/>
)}
</div>
<ConfirmDialog
open={clearAllOpen}
onOpenChange={setClearAllOpen}
title={t('history.clearAll.dialog.title')}
message={t('history.clearAll.dialog.desc')}
confirmLabel={t('history.clearAll.dialog.confirm')}
destructive
onConfirm={handleClearAll}
/>
</div>
);
};
+16
View File
@@ -0,0 +1,16 @@
import React from 'react';
import { useHostBrowserPanel } from '../application/state/useHostBrowserPanel';
import { useI18n } from '../application/i18n/I18nProvider';
export function HostBrowserSidePanel(props: Parameters<typeof useHostBrowserPanel>[0]) {
const { elementRef, error, retry } = useHostBrowserPanel(props);
const { t } = useI18n();
return (
<div ref={elementRef} className="relative h-full min-h-0 w-full overflow-hidden" data-section="host-browser-panel" data-browser-host-id={props.host.id}>
{error && <div className="p-4 text-sm text-muted-foreground">
<p>{error}</p>
<button type="button" className="mt-3 text-primary" onClick={retry}>{t('common.retry')}</button>
</div>}
</div>
);
}
+12
View File
@@ -282,6 +282,7 @@ interface HostTreeViewProps {
onExpandAll?: (paths: string[]) => void;
onCollapseAll?: () => void;
onConnect: (host: Host) => void;
onOpenBrowser?: (host: Host) => void;
onEditHost: (host: Host) => void;
onDuplicateHost: (host: Host) => void;
onDeleteHost: (host: Host) => void;
@@ -322,6 +323,7 @@ interface TreeNodeProps {
expandedPaths: Set<string>;
onToggle: (path: string) => void;
onConnect: (host: Host) => void;
onOpenBrowser?: (host: Host) => void;
onEditHost: (host: Host) => void;
onDuplicateHost: (host: Host) => void;
onDeleteHost: (host: Host) => void;
@@ -368,6 +370,7 @@ const TreeNode: React.FC<TreeNodeProps> = ({
expandedPaths,
onToggle,
onConnect,
onOpenBrowser,
onEditHost,
onDuplicateHost,
onDeleteHost,
@@ -584,6 +587,7 @@ const TreeNode: React.FC<TreeNodeProps> = ({
expandedPaths={expandedPaths}
onToggle={onToggle}
onConnect={onConnect}
onOpenBrowser={onOpenBrowser}
onEditHost={onEditHost}
onDuplicateHost={onDuplicateHost}
onDeleteHost={onDeleteHost}
@@ -627,6 +631,7 @@ const TreeNode: React.FC<TreeNodeProps> = ({
host={host}
depth={depth + 1}
onConnect={onConnect}
onOpenBrowser={onOpenBrowser}
onEditHost={onEditHost}
onDuplicateHost={onDuplicateHost}
onDeleteHost={onDeleteHost}
@@ -660,6 +665,7 @@ interface HostTreeItemProps {
host: Host;
depth: number;
onConnect: (host: Host) => void;
onOpenBrowser?: (host: Host) => void;
onEditHost: (host: Host) => void;
onDuplicateHost: (host: Host) => void;
onDeleteHost: (host: Host) => void;
@@ -706,6 +712,7 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
host,
depth,
onConnect,
onOpenBrowser,
onEditHost,
onDuplicateHost,
onDeleteHost,
@@ -871,6 +878,7 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
<HostTreeHostContextMenuContent
host={host}
onConnect={onConnect}
onOpenBrowser={onOpenBrowser}
onEditHost={onEditHost}
onDuplicateHost={onDuplicateHost}
onCopyHostname={onCopyHostname}
@@ -890,6 +898,7 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
onExpandAll: externalOnExpandAll,
onCollapseAll: externalOnCollapseAll,
onConnect,
onOpenBrowser,
onEditHost,
onDuplicateHost,
onDeleteHost,
@@ -1199,6 +1208,7 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
expandedPaths={expandedPaths}
onToggle={togglePath}
onConnect={onConnect}
onOpenBrowser={onOpenBrowser}
onEditHost={onEditHost}
onDuplicateHost={onDuplicateHost}
onDeleteHost={onDeleteHost}
@@ -1240,6 +1250,7 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
host={item.host}
depth={item.depth}
onConnect={onConnect}
onOpenBrowser={onOpenBrowser}
onEditHost={onEditHost}
onDuplicateHost={onDuplicateHost}
onDeleteHost={onDeleteHost}
@@ -1289,6 +1300,7 @@ function hostTreeViewAreEqual(prev: HostTreeViewProps, next: HostTreeViewProps):
&& prev.onExpandAll === next.onExpandAll
&& prev.onCollapseAll === next.onCollapseAll
&& prev.onConnect === next.onConnect
&& prev.onOpenBrowser === next.onOpenBrowser
&& prev.onEditHost === next.onEditHost
&& prev.onDuplicateHost === next.onDuplicateHost
&& prev.onDeleteHost === next.onDeleteHost
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff. Show more