Compare commits

...
Author SHA1 Message Date
netcatty-bot 6a6f364aaf fix: address Codex review on PR #3585 2026-10-02 22:26:01 +00:00
netcatty-bot 3eab934412 fix: address Codex review on PR #3585 2026-10-02 21:49:40 +00:00
netcatty-bot 9cb556ce95 fix(#3584): automated AI fix 2026-10-02 16:02:16 +00:00
b2ed83ae51 fix(tray): add independent persisted show-tray-icon setting (#3572)
* fix(#3553): automated AI fix

* fix(tray): keep icon visible independently of close behavior

* docs(settings): clarify background close behavior

* fix(settings): preserve tray visibility for existing users

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: binaricat <16399091+binaricat@users.noreply.github.com>
2026-09-30 15:11:23 +08:00
陈大猫 f91b2cd04e feat(ai): scope external MCP approvals to connection or host (#3569)
* feat(ai): scope external MCP approvals to connection or host

* test(ai): keep MCP fixture in Netcatty temp directory

* fix(ai): refine external MCP approval UI and grant safety

* fix(ai): wrap long approval targets and support Node 22

* fix(ai): keep automatic scripts in observer mode

* fix(sftp): release preflight markers after transfer

* fix(sftp): retain preflight cap through conflict resolution

* Keep SFTP preflight cap across panel remount

* Update worker terminal metadata expectations

* Persist SFTP preflight skip state across restart

* Limit persistent host approvals to saved hosts

* Scope host-open approvals to the selected saved host

* Exclude serial hosts from persistent approval scopes
2026-09-30 09:57:47 +08:00
1d10d1679e fix(terminal): opt-in broadcast without password protection during interactive prompts (#3491)
* fix(#3488): automated AI fix

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* fix: address Codex review on PR #3491

* test: verify broadcast password prompts on Windows desktop

* test: run desktop SSH check only in Windows job

* fix: preserve sensitive peer input across compose wake

* fix: retain compose history when sensitive peer receives nothing

* fix: protect compose history during sensitive fallback writes

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-30 00:38:50 +08:00
陈大猫 8d2058267a fix(terminal): commit live IME transcription once (#3568)
* fix(terminal): commit live IME transcription once

xterm sends a rewritten dictation hypothesis as the interim, the full
final string, and the tail. Keep the pending textarea diff from firing
again when composition starts, and send only the part that is not
already on the PTY.

* fix(terminal): retype rewritten IME tails as separate backspaces

A shared suffix has to be deleted and typed again because the cursor
stays at the end of the line. One-character hypotheses are real
prefixes, and each backspace is its own input event so Ctrl-H hosts
still erase.

* fix(terminal): rewrite a revised IME hypothesis in place

A composition that replaces the snapshot, instead of extending it,
sends the cancelled textarea edit. Deletions are counted in graphemes
so a surrogate pair is one backspace.

* fix(terminal): send a new IME word that shares a finished prefix

A composition that starts at or after the snapshot is a new word.
Sharing the first character with text already on the PTY is not
enough to treat it as the same hypothesis.

* fix(terminal): remember a rewritten IME hypothesis in full

A 229 rewrite stored only the inserted tail, so a later
compositionend with no composition marker sent the revised
line again. Remember the whole revised textarea instead.

* fix(terminal): preserve IME rewrite state across delayed commits
2026-09-29 23:07:10 +08:00
陈大猫 8020eaa427 fix(scripts): let explicit user scripts run in observer mode (#3566)
Observer mode stays on AI-started scripts that write to the terminal. Compose bar, connect, and panel runs are explicit user actions and no longer read that setting.
2026-09-29 20:50:11 +08:00
3298a70f32 fix(sftp): re-stat remote source before dual-pane transfer plan (#3560)
* fix(#3559): automated AI fix

* fix: address Codex review on PR #3560

* fix: address Codex review on PR #3560

* fix: address Codex review on PR #3560

* fix: address Codex review on PR #3560

* fix: keep listing size out of the dual-pane transfer plan

A stat-less source can show the pane listing in the overwrite dialog, but that size must not be written back as totalBytes or a short listing truncates the file again. Files past the preflight cap stay on an unknown plan and are not statted a second time.

* fix: stop preflight after a timeout and honor cancel

A half-open browse session no longer walks the whole selection at 10 seconds per file. Cancel during the overwrite size stat is checked before an apply-to-all replace deletes the existing target.

* fix: do not stat remote files again after a failed preflight

A stat that returns no usable size, times out, or never runs is not repeated for the whole selection. The transfer plan stays unknown so the bridge measures the live size.

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-29 20:44:57 +08:00
icelee123 e7202f392a feat(cli): preserve launcher-provided terminal tab names (#3473)
Carry PuTTY -newtab and SecureCRT /N names through the launch queue so the new terminal tab uses the requested name.
2026-09-29 20:40:37 +08:00
陈大猫 9423a1d1cd fix(ssh): drop the manual single-channel SSH toggle (#3561)
* fix(ssh): 去掉单通道 SSH 的手动开关

单通道只在握手后匹配 BHostSSH、TERM-SSHD、CLOUDBILITY 时生效。
主机和分组不再保存这个选项,读到旧字段时直接丢掉。

* test(sftp): 对齐单通道登录后的重连扫描

专用 SFTP 登录改为 reuseTerminalTransport 之后,旧的 sourceSessionId 三元表达式扫描不再匹配,lint-and-test 因此失败。扫描改为锁定当前门槛:已连接,或已经钉住严格来源,才复用终端传输。
2026-09-29 20:05:51 +08:00
Netcatty-Botandnetcatty-bot 50ca182e1e fix(#3562): automated AI fix (#3564)
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-29 19:47:06 +08:00
陈大猫 04a63c653a fix(ui): apply the chosen app icon to the Windows tray (#3563)
* fix(ui): apply the chosen app icon to the Windows tray

Settings already swap the taskbar icon. On Windows, the notification
area now follows that choice. Original keeps the multi-size tray ico;
other variants are scaled to the small-icon size Windows asks for.

* fix(ui): crop the app-icon margin before sizing the Windows tray

The variant PNGs keep a transparent inset, so scaling them straight into
the notification slot made every non-original style smaller than the
full-bleed tray ico. Crop to the opaque artwork first.

* test(sftp): update the side-panel reuse source lock

The single-channel change replaced the connected-only sourceSessionId
ternary with reuseTerminalTransport. The source lock still expected the
old expression, so lint-and-test fails on main.
2026-09-29 19:25:29 +08:00
Netcatty-Bot e2f499b0f9 fix(ssh): reject unresolved lsof cwd annotations (#3494)
When /proc/<pid>/cwd is unreadable, accept an lsof name ending in (verb: message) only if that path is an existing directory. This drops the AL2023 record "/proc/<pid>/cwd (readlink: Permission denied)" instead of using it as the SFTP follow or upload target. Real directories with parenthesized names stay usable.

Fixes #3493.
2026-09-29 18:17:53 +08:00
又是一条懒汉 5805d15746 feat(ssh): add single-channel SSH option for bastion hosts (#3458)
Add a host and group toggle for bastions that allow one session channel per TCP connection. After the handshake, BHostSSH, TERM-SSHD, and CLOUDBILITY take that path automatically. File transfer uses a separate SFTP login, and the interactive terminal is not given another exec, SFTP, copy/split, or port-forward channel.

The manual toggle remains for bastions that still advertise OpenSSH.
2026-09-29 18:01:04 +08:00
陈大猫 bd8476fb34 fix(terminal): enable font ligatures from the terminal setting (#3557)
fontLigatures already defaulted to on, but the terminal never loaded
the ligatures addon, so Fira Code and Maple Mono kept drawing != as two
cells. Activate the addon after open and before WebGL, and rebuild the
WebGL atlas when the setting changes so glyphs are not rasterized
without the calt feature.

The addon bundles lru-cache's node:diagnostics_channel import. Alias
that builtin to a no-op channel in the Vite renderer build and in the
Electron live-test bundles.

Closes #3543
2026-09-29 17:34:00 +08:00
Netcatty-Botandnetcatty-bot c74daf0102 fix(#3550): automated AI fix (#3552)
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-29 16:06:18 +08:00
f1425c8d5a feat(ai): add MiMo Code (mimo) agent support (#3500)
* feat(ai): add MiMo Code (mimo) agent support scaffolding

Registry/wiring only: discovery entry, managed-agent metadata, model presets, icon, i18n and Settings UI for Xiaomi's MiMo Code CLI (an OpenCode fork). The SDK driver is intentionally not wired yet - it depends on the pending @mimo-ai/sdk parity probe, so DRIVER_REGISTRY keeps a TODO and run-turn/list-models reject the mimo backend until then.

* feat(ai): add MiMo Code (mimo) agent support

Adds Xiaomi's MiMo Code CLI as a managed agent backend, mirroring the existing
OpenCode integration (discovery, managed-agent metadata, model presets, icon,
i18n, Settings UI) and adding the SDK driver that was left as a TODO in the
scaffolding commit.

Driver notes:
- New electron/bridges/aiBridge/sdk/mimoDriver.cjs reuses the pure translation
  helpers exported by opencodeDriver.cjs (config/prompt building, event
  translation, model mapping) because MiMo Code is an OpenCode fork and speaks
  the same wire protocol.
- It does NOT use @mimo-ai/sdk's createOpencode(). On 0.1.15 that helper spawns
  a binary named "opencode", waits for an "opencode server listening" banner,
  and passes config via OPENCODE_CONFIG_CONTENT; the mimo CLI prints
  "mimocode server listening on <url>", reads MIMOCODE_CONFIG_CONTENT, and ships
  as "mimo"/"mimo.exe". So createOpencode() can only ever time out. The driver
  runs "mimo serve" itself, parses the readiness URL, and attaches the SDK's
  createOpencodeClient({ baseUrl }).
- Binary resolution honours binPath, MIMOCODE_BIN and MIMOCODE_BIN_PATH, then
  falls back to PATH via resolveCliFromPath (the npm shim is mimo.cmd on
  Windows, which Node cannot spawn directly).
- @mimo-ai/sdk ^0.1.15 added as a dependency.

Verified on Windows against mimo 0.1.15 + @mimo-ai/sdk 0.1.15:
- "mimo serve --port" boots and reports its URL; driver parses it.
- SDK symbols used all exist: createOpencodeClient, client.config.providers(),
  client.global.event() (SSE stream), client.session.create/abort/promptAsync.
- Live provider catalog reads 2 providers (xiaomi, mimo); MIMO_MODEL_PRESETS
  updated to the real lower-case provider-prefixed ids and its TODO removed.
- Server process is killed on close (taskkill tree kill), no orphan processes.

Not yet verified at runtime:
- A full end-to-end turn (no prompt was sent, so no tokens were spent): text /
  reasoning / tool-part streaming and abort handling are untested against a
  live model.
- MIMOCODE_CONFIG_CONTENT accepting the OpenCode config schema (permission,
  mcp, model, share, autoupdate) end-to-end; only that the env var exists in
  the binary has been confirmed.
- Whether the loopback server needs MIMOCODE_SERVER_PASSWORD when the API
  client attaches.
- The placeholder public/ai/agents/mimo.svg still needs an official asset.
- Multi-turn resume (resumeSessionId) and MCP injection against the live CLI.

* feat(ai): inject MIMOCODE_BIN for discovered MiMo Code agents

Mirror the OpenCode OPENCODE_BIN handling so a discovered or re-detected
mimo binary path reaches the driver, and cover it with the same assertion
shape as the opencode managed-agent env test.

* fix(ai): use MiMo branding in the mimo driver

* test(ai): cover the mimo driver

Add a unit test file for the MiMo Code driver, matching the existing
opencode driver test in shape, runner (node:test via node --test) and
`.test.cjs` extension. It is the last driver in the registry without
one.

Coverage:
- spawn/launch: `mimo serve --hostname/--port` argv, binary resolution
  (explicit binPath / MIMOCODE_BIN / MIMOCODE_BIN_PATH), pass-through
  env and MIMOCODE_CONFIG_CONTENT; `child_process.spawn` is stubbed, so
  no real `mimo` process is ever started.
- readiness: parsing of `mimocode server listening on <url>` from
  stdout (including split chunks) and stderr, the OpenCode spelling,
  and the MIMO_SERVE_TIMEOUT_MS timeout path (asserts the rejection and
  that the child is killed).
- abort/cleanup: stopMimoProcess kill/idempotency/swallow, the Windows
  taskkill tree kill, server.close() teardown, and abort mid-turn with
  a throwing close().
- branding: OpenCode -> MiMo Code for the busy/idle/status, failed and
  tool-failure fallback strings, with tool output and non-brand
  technical errors left verbatim.
- happy path: session create -> streamed event translation -> done,
  plus listMimoModels catalog mapping and the empty/aborted paths.

* fix(ai): filter MiMo events by session and stop the server behind the npm shim

Address review on #3500:

- The global SSE stream carries every session on the server, and
  runMimoTurn translated all of them, so another session's text could leak
  into the reply and its session.idle could end the turn early. Skip events
  whose session id is not ours, reusing the OpenCode driver's
  getOpenCodeSessionIdFromEvent (now exported). Covered by a test with
  interleaved sessions.
- On macOS/Linux the official @mimo-ai/cli `mimo` is a Node shim that runs
  the native binary through spawnSync, so killing the shim left the server
  listening. `mimo serve` is now spawned detached on POSIX and
  stopMimoProcess signals its whole process group (SIGTERM, then SIGKILL
  after a grace period). Windows keeps taskkill /T.

Verified against the real @mimo-ai/cli@0.1.15 npm shim: on Linux (WSL
Ubuntu 22.04) the listener is the native .mimocode child; before this change
it was still listening 3s after close(), now the port is released within 1s
and no mimo process remains. On Windows the .cmd shim path also releases the
port within 1s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: harden MiMo CLI integration before merge

* fix: wait for MiMo events and handle setup cancellation

* fix: finish MiMo stream handling and scope skill access

* fix: preflight MiMo skill paths before one server startup

* fix: scope MiMo skill reads to trusted roots

* fix: allow MiMo skills from ancestor project roots

* fix: honor MiMo observer and confirm command permissions

* fix: clear MiMo approval when its service exits

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-29 14:51:22 +08:00
fc55e9ac17 feat(vault): let Skills + CLI operate notes with the same approval as MCP (#3512)
* feat(vault): let Skills + CLI operate notes with the same approval as MCP

Expose vault note list, read, write, and markdown import on the tool CLI so agents can save generated documents only after the user approves.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): keep explicit empty note fields in the CLI

A supplied empty string was treated as an omitted flag, so note clears and empty markdown imports never reached the note service.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): allow an explicit empty note body on CLI create

notes create --content "" was rejected as a missing flag, so it did not match vault_notes_create.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): stop echoing imported note bodies and recognize leading CLI flags

A batch import resent every document over IPC, and a leading --json hid the notes command from artifact inference.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): make note CLI import safe and fail writes cleanly

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-29 12:22:35 +08:00
刘白菜 025ce741c2 fix(terminal): refresh local session PATH from the Windows registry (#3470)
A local terminal inherited the PATH snapshot the Electron main process
captured at launch. A GUI-launched or auto-started Netcatty keeps that
snapshot for its entire lifetime, so a CLI installed or upgraded afterwards
is missing inside Netcatty while resolving fine in an external
cmd/PowerShell. The upgrade case is the worst: installers that rewrite a
versioned user-PATH entry leave the captured entry pointing at a directory
the upgrade deleted, so the command disappears entirely.

Reuse the registry re-read the AI harness already performs for its shell
env. resolveWindowsLivePath() merges the HKCU/HKLM PATH (with %VAR%
expanded) and the well-known npm/pnpm/Yarn bin dirs ahead of the captured
PATH, and buildLocalSessionEnv() applies it to local sessions on Windows
only, degrading to today's behaviour off Windows or when the registry
cannot be read.

An explicit PATH in the session payload is never widened, and PATH/Path
duplicates are collapsed so the effective value stays deterministic.
2026-09-29 12:22:23 +08:00
323ff0b16a fix(ai): put static Catty guidelines before dynamic prompt sections for cache hits (#3547)
* fix(#3545): automated AI fix

* fix: preserve prompt guardrails after dynamic context

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-29 02:07:03 +08:00
OOKAMISAMAandbincxz 6ece7e8222 feat(terminal): Add configurable terminal bar cursor width (#3495)
* feat(terminal): Add configurable terminal bar cursor width

Adds a configurable bar-cursor width for the terminal so thin vertical cursors are easier to find, particularly when vi/vim switches to insert mode.

* Add terminal bar cursor width setting

This adds the terminal bar cursor width control to the settings UI with an aria-label for accessibility and a matching test. It also adds localized labels/descriptions and search catalog entries so the setting is discoverable in both English and Chinese.

* Fix terminal cursor width override bug

Prevent width-only cursor updates from clearing DEC/vi cursor overrides by tracking the last applied shape/blink snapshot. The runtime now resets the snapshot on teardown, skips full cursor reapplication for width-only changes, and preserves remote bar/underline cursor styles. Added regression tests covering boot-time and later width updates.

* Fix terminal cursor preference lifecycle

Preserve DEC/vi cursor overrides during the first width-only terminal update after runtime creation. The runtime now records the user cursor preference snapshot when a term is published and applies width-only updates without clearing active cursor style or blink overrides. This prevents regressions when terminal settings change before the panel has fully booted.

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-29 00:24:27 +08:00
GOUKI9999andClaude Opus 5.5 e3894eb850 terminal: allow Shift+Enter text fallback inside ConPTY Win32 input mode (#3464)
* terminal: allow Shift+Enter text inside ConPTY Win32 input mode

Win32 input mode (PR #3247) delivers Shift+Enter to ConPTY as a lossless
INPUT_RECORD, which CLIs reading console records natively (Codex, Grok) can
use. Node/Bun CLIs read input through libuv, which drops modifier state when
translating INPUT_RECORD to VT bytes, so Claude Code and CodeBuddy still see a
bare CR and submit instead of inserting a newline (anthropics/claude-code#92771,
reproducing on 2.1.278).

While the mode is active, Netcatty also skips its Shift+Enter text fallback and
Kitty encoding, so shiftEnterNewlineText had no effect on local Windows
sessions at all.

Add shiftEnterForceText (default false): when enabled, Shift+Enter sends the
configured text even inside Win32 input mode, and consumes the keydown so no
native record is emitted as well. Add `\e` (ESC) to the escape decoder so the
text can carry the legacy Alt+Enter encoding, which is the only sequence that
survives the ConPTY input path.

Defaults keep the #2974 behaviour untouched for Codex/Grok.

* docs: record libuv input findings and the Win32 input mode opt-out

* fix(terminal): don't swallow Shift+Enter when there is no text to send

The Shift+Enter send-text interception resolved its text after already
calling preventDefault/stopPropagation, and returned false outside the
`if (shiftEnterText)` guard. When resolveShiftEnterText() yields an empty
string (e.g. a persisted empty setting) the keydown was therefore consumed
with nothing written, and the handler never fell through to the Win32
bookkeeping or Kitty paths below, so no Enter reached the session either.
The result was indistinguishable from a dead feature.

Resolve the text first and only enter the interception block when it is
non-empty; empty text now falls through exactly as it did before the
`shiftEnterForceText` setting existed, so a normal Enter is still produced.
The opt-out semantics for the non-empty case are unchanged.

Also tighten the source-shape test so it verifies the real intent: the
interception (preventDefault through return false) must live inside the
empty-text guard, which fails against the previous code.

* fix(terminal): scope Shift+Enter force-text to Win32 mode, honor it per broadcast target

Address review on #3464:

- The force-text opt-out could override a negotiated Kitty encoding that
  preserves Shift+Enter in non-Win32 sessions. The keydown decision now
  lives in shouldClaimShiftEnterForText: under Win32 input mode it follows
  shiftEnterForceText, otherwise only the existing collapse fallback
  applies. Covered by a regression test for a non-Win32 session whose Kitty
  encoding already preserves the chord.
- Broadcast Win32 targets returned the native record without consulting
  their own shiftEnterForceText. They now send their configured text for
  Shift+Enter when opted in, whether the source forwarded a key chord or a
  native Win32 record, and drop the paired release so ConPTY never sees a
  key-up without its key-down. Targets without the opt-out keep the native
  press/release pair. Tests cover source and target settings that differ.

ShiftEnterEvent now accepts KittyKeyboardEvent's optional type/modifier
fields so broadcast events can be checked with the same helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:36:10 +08:00
GOUKI9999andClaude Opus 5.5 38c7376515 fix(terminal): resolve the fake ssh deterministically in the Mosh ConPTY test (#3505)
The flaky Windows run timed out in where.exe inside startMoshSession,
before any wait started. findExecutable then fell back to the in-box
OpenSSH, which never prints the fixture's MOSH CONNECT line, so no ready
event could arrive no matter how long the test waited.

Pass the existing findExecutable option so the test always uses its
compiled fake ssh.exe without shelling out, and keep the 15s wait: locally
the whole handoff finishes in about 7s.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:35:19 +08:00
陈大猫 1b8228b23d fix(ui): choose side panel position from one menu (#3544)
* fix: expose all side panel dock positions

* fix: use compact dock position menu
2026-09-28 23:03:01 +08:00
Magisk317andbincxz b2c518a6f1 fix(sync): avoid repeated versioned setting writes (#3520)
* fix: prevent cloud sync version inflation when idle

Three bugs combine to cause an infinite upload loop where the sync
version increments every ~2.5 minutes even with no user interaction:

1. Smart merge unconditionally uploads (useAutoSync.ts):
   `if (mergeResult.payload)` is always true since payload is an object.
   Now checks `cloudSyncPayloadsEqual(portableMerge, remotePayload)`
   before uploading — if merged result matches remote, skip the upload
   and mark data as synced.

2. Download-remote re-uploads to same single provider (useAutoSync.ts):
   When only one cloud provider is connected, downloading the remote
   payload and immediately re-uploading it to the same provider bumps
   the version unnecessarily. Now checks `readyProviders.length > 1`
   before round-tripping.

3. applySyncableSettings bumps versions unconditionally (syncPayload.ts):
   customAccent, terminalFontSize, and customKeyBindings handlers always
   bump their storage version counters even when incoming values are
   identical to existing values. This fires LOCAL_STORAGE_ADAPTER_CHANGED_EVENT
   and triggers a debounced syncNow(). Now guarded with change detection:
   - customAccent: compare parsed color values
   - terminalFontSize: compare fontSize numbers
   - customKeyBindings: compare JSON-serialized bindings

Observed impact: lastSyncVersion reached 7796+ with LevelDB compaction
every ~155 seconds matching getRuntimeRemoteCheckIntervalMs(5).

* fix(sync): avoid repeated versioned setting writes

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-28 09:35:05 +08:00
GOUKI9999andClaude Opus 5.5 ea36f46d1d fix(ai-cli): stop unit tests from deleting the installed discovery file (#3501) (#3507)
Requiring mcpServerBridge from node --test inherited the production
netcatty-tool-cli/discovery.json path, so cleanup() removed the running
app's bridge pointer. Resolve the discovery path on demand and isolate the
affected tests via NETCATTY_TOOL_CLI_DISCOVERY_FILE.

Rebased onto #3502, which now owns the self-heal (live-host reuse, status
and content validation); this change only adds on-demand path resolution to
those helpers and drops the separate 30s missing-file sweep.

The subprocess regression test redirects HOME/USERPROFILE as well as
APPDATA/XDG_CONFIG_HOME, since macOS derives the default path from
os.homedir(), and refuses to plant its canary anywhere outside the
throwaway root, so it can never write the real app path on any OS.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 09:14:25 +08:00
github-actions[bot]andgithub-actions[bot] 6d0d39e678 chore: update star history charts [skip ci] (#3541)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-09-28 00:11:14 +00:00
陈大猫 08089323a9 Merge pull request #3540 from binaricat/codex/revert-3478-window-controls
revert(ui): withdraw #3478 window control alignment
2026-09-27 22:47:44 +08:00
bincxz 91db655a1a revert(ui): withdraw #3478 window control alignment 2026-09-27 22:32:08 +08:00
陈大猫 d51cd2714d Merge pull request #3539 from binaricat/codex/revert-3371-sftp-command-refresh
Revert SFTP auto-refresh after terminal commands (#3371)
2026-09-27 22:21:21 +08:00
bincxz 3fd954d2bf fix(sftp): keep selection scroll on reconnect listing updates 2026-09-27 22:11:35 +08:00
bincxz ff28c9b412 revert(sftp): remove terminal command auto-refresh (#3371) 2026-09-27 22:03:47 +08:00
陈大猫 7006fa214e Merge pull request #3538 from binaricat/codex/revert-3504-sftp-sidebar
revert(vault): remove SFTP sidebar option pending #3504 decision
2026-09-27 21:27:09 +08:00
bincxz 459f3a5278 revert(vault): remove SFTP sidebar option from #3504
Revert the changes merged in #3506 while preserving the later bottom-tab removal.
2026-09-27 21:14:53 +08:00
陈大猫 6c8edddfa8 Merge pull request #3537 from binaricat/codex/revert-3366-bottom-tabs
revert(ui): remove bottom tab bar option from #3366
2026-09-27 21:07:51 +08:00
bincxz 5af2c86f8f revert(ui): remove bottom tab bar option from #3366 2026-09-27 20:51:27 +08:00
陈大猫 7b1151f976 Merge pull request #3536 from binaricat/codex/3509-preserve-ssh-config-read-failure
fix(vault): preserve managed SSH config when source read fails
2026-09-27 18:14:04 +08:00
bincxz d21016b91a fix(vault): stop managed SSH config writes after read failure 2026-09-27 18:03:09 +08:00
陈大猫 b62a0b3a8f Merge pull request #3522 from binaricat/ai/issue-3519-35968132212
fix(sync): skip identical cloud uploads that inflated versions while idle
2026-09-27 17:53:05 +08:00
bincxz 3560a04fa6 Keep peer sync metadata writes from canceling no-op sync 2026-09-27 17:41:36 +08:00
bincxz a373f57905 Notify idle state after unchanged provider sync 2026-09-27 17:33:14 +08:00
bincxz e376190a70 Fix unchanged per-provider sync and startup identity snapshot 2026-09-27 17:29:53 +08:00
bincxz 037a2f651b fix(sync): ignore peer no-op metadata in identity guard 2026-09-27 16:48:38 +08:00
bincxz 1a4a022a8e fix(sync): distinguish token refresh from provider switch 2026-09-27 16:36:42 +08:00
bincxz fd177e8453 fix(sync): detect provider changes before storage events arrive 2026-09-27 16:29:42 +08:00
bincxz dee468dcfa fix(sync): guard no-op persistence across provider changes 2026-09-27 16:25:40 +08:00
bincxz c666fdb156 fix(sync): keep newer provider credentials during no-op 2026-09-27 16:15:53 +08:00
bincxz b4111cf970 test(sync): verify two devices settle after shared edits 2026-09-27 16:03:39 +08:00
69497ccc6a fix(terminal): offer saved password identities in SSH re-auth dialog (#3477)
* fix(#3475): automated AI fix

* fix: address Codex review on PR #3477

* fix: keep SSH identity picker state accurate

* style: keep SSH identity picker source ASCII-only

* fix: require usernames for saved SSH identity retries

* Keep selected SSH identity for terminal SFTP

* Share reauthenticated identity with all terminal SFTP entry points

* Pass SFTP identity source setter into layer effects

* Use effective identity for preset SFTP panel

* fix: keep focused SFTP identity in sync for toggle

* fix(terminal): use selected vault identity without exposing password

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-27 15:43:25 +08:00
Netcatty-Botandnetcatty-bot 078353dc87 fix(ai): allow custom model ids in composer picker and persist manual picks (#3535)
* fix(#3534): automated AI fix

* fix: address Codex review on PR #3535

* fix: address Codex review on PR #3535

* fix: address Codex review on PR #3535

* fix: address Codex review on PR #3535

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-27 14:57:10 +08:00
fb7adc3bfc fix(sftp): fall back to copy on EISDIR from hardlink publication (#3484)
* fix(#3483): automated AI fix

* test(sftp): cover EISDIR through local download publication

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-27 14:42:45 +08:00
bincxz 8d6ef72006 fix(sync): stop upload when no-op state persistence fails 2026-09-27 14:30:07 +08:00
陈大猫 85683757e5 Merge pull request #3532 from binaricat/codex/claude-model-label-smoke
fix(ai): distinguish Claude aliases sharing model names
2026-09-25 21:24:03 +08:00
bincxz 7224ad37c8 fix(ai): distinguish Claude aliases sharing model names 2026-09-25 21:06:31 +08:00
bincxz 598f5cf796 test(sync): cover vault lock during no-op base save 2026-09-25 17:51:51 +08:00
bincxz ed92944af0 fix(sync): stop no-op commit after vault security changes 2026-09-25 17:50:33 +08:00
bincxz e2b3daac9a test(sync): cover download-remote source no-op with stale peer 2026-09-25 17:44:26 +08:00
85bddba538 feat(ai): add bottom dock position for AI assistant side panel (#3482)
* fix(#3481): automated AI fix

* fix: address Codex review on PR #3482

* fix: address Codex review on PR #3482

* fix: address Codex review on PR #3482

* fix: address Codex review on PR #3482

* fix: address Codex review on PR #3482

* fix: remeasure bottom dock when compose bar toggles

* fix: preserve terminal height when bottom dock cannot fit

* fix: preserve dock preference through temporary shrinkage

* fix: update bottom dock when compose bar toggles

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 17:35:49 +08:00
Netcatty-Botandnetcatty-bot 66e87a95f1 fix(ai-cli): self-heal tool-CLI discovery file while TCP bridge is alive (#3502)
* fix(#3501): automated AI fix

* fix: address Codex review on PR #3502

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-25 17:33:57 +08:00
7cce9c9dbb fix(terminal): center titlebar window control buttons in the title bar (#3478)
* fix(#3476): automated AI fix

* fix: align window controls with full title bar

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 17:28:51 +08:00
954b60acf2 feat(vault): keep SFTP in the sidebar with a persistent vault rail (#3506)
* fix(#3504): automated AI fix

* fix: address Codex review on PR #3506

* fix: address Codex review on PR #3506

* fix: address Codex review on PR #3506

* fix: address Codex review on PR #3506

* fix: keep sidebar SFTP visible above inactive terminal

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 17:15:43 +08:00
73284582f5 fix(ai): keep Claude/Codex/Grok model pickers on live CLI catalogs instead of build-time presets (#3499)
* fix(#3496): automated AI fix

* fix: address Codex review on PR #3499

* fix: address Codex review on PR #3499

* fix: keep live model catalogs scoped and surface discovery failures

* fix: isolate Claude catalog profiles and support xhigh effort

* fix: handle missing external model catalog state

* fix: isolate Claude model catalogs by credentials

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 17:15:03 +08:00
33853398d4 fix(keychain): detect ECDSA key type in imported OpenSSH and PKCS#8 keys (#3490)
* fix(#3489): automated AI fix

* fix(keychain): read OpenSSH algorithm field precisely

* fix: preserve imported key size after vault reload

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 16:51:13 +08:00
陈大猫 9497cd65fc fix(sftp): focus the safe conflict action on open (#3531) 2026-09-25 15:37:48 +08:00
95a0186d90 fix(vault): fall back to GB18030 for non-UTF-8 CSV imports (#3517)
* fix(#3515): automated AI fix

* fix(vault): limit legacy CSV encoding fallback to intended imports

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-25 15:27:24 +08:00
626e0ce5bd fix(quick-connect): accept multi-@ jump chains like JumpServer (#3525)
* fix(#3523): automated AI fix

* fix(#3523): parse JumpServer login on final SSH host

* fix(#3523): preserve login with SSH HostName override

* fix(#3523): guard JumpServer credential presets

* fix(#3523): retain SSH user with HostName alias

* fix(#3523): distinguish JumpServer login from SSH user option

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-24 17:49:46 +08:00
71d378c9b8 fix(sftp): verify current source before side-panel download (#3524)
* fix(#3521): automated AI fix

* fix: address Codex review on PR #3524

* fix: address Codex review on PR #3524

* fix(sftp): require fresh source metadata before downloads

* fix(sftp): refresh SCP symlink targets before download

* test(sftp): include download regression in default suite

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-24 17:48:22 +08:00
bincxz 105b7f16bc fix(sync): carry deletion records into later uploads 2026-09-24 17:14:24 +08:00
bincxz ec11989d52 fix(sync): reconcile remote deletion records in no-op base 2026-09-24 17:10:43 +08:00
bincxz fd3e82386a fix(sync): retain deletion records across no-op providers 2026-09-24 17:04:17 +08:00
bincxz 2b120c0d41 fix(sync): preserve discovered provider identity during no-op 2026-09-24 16:57:22 +08:00
bincxz 318577cd72 fix(sync): avoid version ping-pong for identical providers 2026-09-24 16:52:16 +08:00
netcatty-bot 6398360854 fix: address Codex review on PR #3522 2026-09-24 08:32:45 +00:00
netcatty-bot e3b2e82f88 fix: address Codex review on PR #3522 2026-09-24 07:58:54 +00:00
netcatty-bot 9e07e9e7b9 fix(#3519): automated AI fix 2026-09-24 07:35:54 +00:00
陈大猫 0261931f95 fix(terminal): keep broadcast going on vim ex command-line (#3467)
* fix(terminal): keep broadcast going on vim ex command-line

Broadcast pauses on fail-closed colon prompts so passwords are not
copied to peers. Vim command mode's last line is a bare `:`, which
matched that heuristic. Exempt lines that start with `:` so `:w` and
friends stay in sync; `Password:` is unchanged.

* fix(terminal): only treat a bare colon as vim command-mode

Codex: exempting every `:`-prefixed line would broadcast into custom
prompts such as `sudo -p ':'`. The hang is the first `:` key; later
`:w` no longer matches the trailing-colon heuristic.

* fix(terminal): exempt vim colon only on the alternate screen

A bare `:` on the primary screen can be `sudo -p ':'`. Vim command mode
uses DEC 1049, so require alternateScreen before treating `:` as ex.

* test(terminal): allow alternateScreen in prompt-security options
2026-09-21 16:09:50 +08:00
陈大猫 62e9c9ed12 fix(mcp): drop mustache braces from tool descriptions (#3465)
* fix(mcp): drop mustache braces from tool descriptions

Hosts that interpolate {{name}} in tools/list text treat the literal
{{variables}} snippet wording as a missing template variable and abort
the turn. Use plain language instead and regenerate the committed specs.

* fix(mcp): describe snippet placeholders without mustache tokens

Keep agents informed that snippets use two curly braces on each side,
without emitting a literal {{name}} token that template hosts interpolate.
2026-09-21 15:56:24 +08:00
1b4e826e15 feat(terminal): save and auto-apply a default side panel layout on connect (#3456)
* fix(#3455): automated AI fix

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix(terminal): let explicit SFTP auto-open beat the saved layout

A JumpServer SFTP deep link or host.autoOpenSftpPanel must still open
file transfer when the saved default layout omitted SFTP.

* fix(terminal): skip saved layout only when SFTP auto-open is available

Telnet/plugin hosts can carry autoOpenSidePanel=sftp even though the
protocol cannot serve SFTP. Those sessions should still get the saved
default with the SFTP pane pruned.

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-21 15:45:59 +08:00
陈大猫 f469513579 fix(ai): parse live-shell probe sentinels after bash PS2 (#3466)
Interactive bash prints PS2 on the probe's backslash continuations, so
strict startsWith checks miss `_Q`/`_P:` and silent PTY execs hang until
the command timeout. Strip common prompt prefixes in the parser; keep
the existing short-line probe for OpenWrt.
2026-09-21 15:34:47 +08:00
Netcatty-Botandnetcatty-bot 707972d976 fix(sftp): read local *.asar upload sources outside Electron's asar fs wrapper (#3451)
* fix(#3450): automated AI fix

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-21 14:57:08 +08:00
Netcatty-Botandnetcatty-bot 8573027e61 fix(ssh): hang up aux exec channels after completion to stop relay session leak (#3460)
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-21 14:56:56 +08:00
Netcatty-Botandnetcatty-bot ff65339e04 fix(terminal): keep IME preedit commits alive when Shift ends composition (#3444)
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-21 14:56:48 +08:00
Netcatty-Botandnetcatty-bot a70c43e302 fix(vault): keep host groups unchanged when dragging host cards (#3442)
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-21 14:56:28 +08:00
github-actions[bot]andgithub-actions[bot] 7b3b8214a9 chore: update star history charts [skip ci] (#3462)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-09-21 00:10:41 +00:00
cb06857480 feat(terminal): confirm before pasting multiple lines (#3398) (#3400)
* fix(#3398): automated AI fix

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix(terminal): protect popup and sanitized multiline pastes

* fix(terminal): preserve input state across paste confirmation

* fix(terminal): retain serial character-mode paste echo

* test(terminal): cover paced input write options

* fix(terminal): retain telnet echo for paced pastes

* test(terminal): scope serial buffer assertion to serial sessions

* fix(terminal): align runtime write options with bridge contract

* fix(terminal): preserve bookkeeping for all paced pastes

* fix(terminal): record confirmed paste lines in order

* fix: record paced paste commands after transport writes

* fix: omit paste receipts for filtered input

* fix: cancel superseded paste batches across input paths

* fix: classify each acknowledged paste line before recording

* fix: stop paced paste when editing buffered serial input

* fix: preserve recording pause boundaries and serial edit cancellation

* fix: treat paced terminal pastes as user input

* fix: preserve paste drafts until write and snippet broadcast origin

* fix: retain filtered paste drafts and invalidate urgent input ownership

* fix: broadcast paced user paste only on guarded line receipts

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 15:19:34 +08:00
GOUKI9999 0982c213e7 fix: recover paused terminal output after AI interruption (#3431) 2026-09-18 14:11:13 +08:00
0d21e37a19 fix(terminal): map macOS Command+. to interrupt running command like Ctrl+C (#3409)
* fix(#3408): automated AI fix

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: preserve physical releases for Command-period interrupts

* fix: allow Command-period with selected terminal text

* style: keep Command-period additions ASCII-only

* test: validate Command-period fixture without renderer errors

* fix: support logical period across macOS keyboard layouts

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:11:05 +08:00
9082aa08a4 fix(serial): auto-login on serial consoles with saved host credentials (#3418)
* fix(#3417): automated AI fix

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: guard serial quick login and reconnect startup commands

* fix: preserve serial startup while tabs sleep

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:58 +08:00
dffcefc308 fix(ai): prime echo suppression before agent input to stop OpenWrt ash variable leak (#3385)
* fix(#3384): automated AI fix

* fix(ai): order display suppression with terminal output

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:52 +08:00
6bee56220c fix(terminal): stop stale zmodem echo suppression from eating typed command (#3424)
* fix(#3423): automated AI fix

* test: clean up drag-drop suppression expiry watchdog

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:46 +08:00
Netcatty-Botandnetcatty-bot 0fa0c6a0a4 fix(sftp): treat stat-less SCP remotes as unknown size instead of failing upload (#3402)
* fix(#3399): automated AI fix

* fix: address Codex review on PR #3402

* fix: address Codex review on PR #3402

* fix: address Codex review on PR #3402

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-09-18 14:10:40 +08:00
12a3ae07ef feat: Enable SFTP sidebar and button for local shell sessions (#3379)
* Add local shell side panel auto-open settings with i18n support

- Add settings to control side panel behavior for local shell sessions
- Support auto-opening side panel when local shell is launched
- Allow users to choose which pane (Files, SFTP, Scripts, etc.) opens by default
- Add complete i18n translations for en, zh-CN, zh-TW, es, ru locales

* fix: wire local shell side panel settings

* fix: restore undefined check for local shell protocol detection

Local shell sessions may have protocol=undefined, not just 'local'.
Restore the original condition to auto-open sidebar for both cases.

* fix: enable SFTP sidebar for local shell sessions

Local shell now supports SFTP (for local file browsing).
Update sftpAvailable to include local shell so the auto-open
sidebar setting works correctly for PowerShell/bash sessions.

* chore: bump version to 1.1.83-fork.1

Distinguish fork from upstream (1.1.83) and previous 0.0.0 dev version.

* feat: show SFTP button in local shell toolbar

Local shell sessions now display the 'Open SFTP' button in the toolbar,
allowing users to browse local files via SFTP sidebar, consistent with
the auto-open behavior added earlier.

* feat: 本地Shell侧边栏支持追随终端目录功能

- 追随终端目录现在支持本地 POSIX shell(bash/zsh/fish)
- 排除 PowerShell 和 cmd(因为它们的 cd 命令和路径格式不同)
- 串口连接仍然不支持(它们根本没有 SFTP)
- 定位路径到终端功能已支持本地 Shell(无需修改)

* feat: support PowerShell and CMD in session restore

- Accept Windows absolute paths (C:\...) in isRestoreCwdPathEligible
- Add shell-specific cd commands:
  * PowerShell: Set-Location -LiteralPath with '' quote escaping
  * CMD: cd /d with "" quote escaping
  * bash/POSIX: cd -- with '\'' quote escaping
- Remove PowerShell/CMD restrictions in cwd injection eligibility
- Fix line terminator in SFTP locate path (use \r\n for Windows PTY)

* fix: bound local shell panel preferences and synchronize settings

---------

Co-authored-by: HHXXYY123 <HHXXYY123@outlook.com>
Co-authored-by: binaricat <binaricat@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:33 +08:00
nervi0s ec2f0d0bce fix: support native file dragging from local filesystem panes (#3377)
* fix: support native file dragging from local filesystem panes

* fix: preserve symlink-aware paths during native file drag
2026-09-18 14:10:26 +08:00
Ryanisgoodandbincxz 3738565b1b feat(mcp): improve external agent discovery and setup (#3407)
* fix(ai): expose renamed terminal session labels

* feat(mcp): guide agents toward Netcatty tools

* feat(mcp): load Netcatty toolsets on demand

* feat(codex): install Netcatty skill with external MCP

* feat(mcp): install skills for Claude Code and Grok

* feat(mcp): add universal client setup prompt

* fix(mcp): keep Cursor in client setup tabs

* chore(ai): refresh generated tool specs

* fix(mcp): honor Claude skill config root and run MCP tests in CI

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:20 +08:00
d98a22f49b fix(deep-link): accept SecureCRT-style CLI launches from bastion callers (#3391)
* fix(#3390): automated AI fix

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: preserve SecureCRT launch targets and operand boundaries

* fix: redact SecureCRT credentials before legacy switch scrubbing

* fix: reject ambiguous SecureCRT launch destinations

* fix: reject unknown slash switches consistently

* fix: reject mixed client switches in SecureCRT launches

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:13 +08:00
08009d4ce0 feat(terminal): show GPU utilization next to CPU in server stats strip (#3411)
* fix(#3410): automated AI fix

* fix(terminal): bound GPU stats queries and complete Chinese labels

* fix(terminal): declare optional GPU fields on stats bridge

* test(terminal): keep GPU fixtures in managed temporary storage

* fix(terminal): preserve unknown GPU memory totals

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:10:06 +08:00
OOKAMISAMAandbincxz f841ab4778 fix(terminal): start WSL local shells from Linux home (#3412)
* Default WSL launches to Linux $HOME

When launching WSL on Windows, ensure the distro starts in the Linux home if no explicit working directory was provided. Adds isWslExecutable and getWslLaunchArgs which append `--cd ~` for wsl.exe calls that lack an explicit cwd or --cd option. startLocalSession now uses getWslLaunchArgs when building shell args. Exports getWslLaunchArgs and adds a unit test verifying the behavior. This prevents WSL from failing early when the parent Windows cwd isn't mounted or accessible to the chosen distro.

* Insert --cd before WSL command/--exec

Ensure WSL launch uses Linux home by inserting --cd "~" before the first bare command or --exec/-e boundary so the option is consumed by WSL rather than passed to the invoked shell/command. Early-return when not a WSL executable, when an explicit cwd is supplied, or when --cd is already present. Also account for WSL options that take a separate value (--distribution/-d, --user/-u). Adds a unit test verifying --cd is placed before --exec.

* fix(terminal): preserve WSL command argument boundaries

* fix(terminal): retain legacy WSL distribution selectors

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:09:59 +08:00
2fa13257e7 fix(session-logs): add millisecond precision to per-line timestamps (#3416)
* fix(#3414): automated AI fix

* fix(session-logs): preserve output arrival timestamps through flushes

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:09:53 +08:00
8ef37454ae fix(terminal): stabilize autocomplete popup geometry against hover jitter (#3427)
* fix(#3426): automated AI fix

* fix: address Codex review on PR #3427

* fix: keep autocomplete detail reserve within narrow panes

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:09:47 +08:00
7e4b3c293a fix(vault): warn about ssh_config data loss before deleting managed group (#3429)
* fix(#3428): automated AI fix

* fix: address Codex review on PR #3429

* fix: address Codex review on PR #3429

* fix: address Codex review on PR #3429

* fix: require confirmation for changed managed deletion files

* fix: bind managed deletion confirmation to group scope

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:09:40 +08:00
陈大猫 bf9fa571ee fix(sftp): preserve complete folder recovery after ownership changes (#3436)
* fix(sftp): preserve folder recovery completion and ownership

* fix(sftp): discard displaced updates before batch flush

* fix(sftp): bind recovery admission to reset and owner state

* fix(sftp): preserve replacement owners on rejected invocations

* fix(sftp): expire initial identity exemptions on activation

* fix(sftp): preserve recovery ownership through deferred writes
2026-09-18 14:09:34 +08:00
陈大猫 477bc0c4ec fix(ssh): reject lsof error text as terminal upload paths (#3432)
* fix(ssh): reject lsof diagnostics as terminal directories

* fix(ssh): retain vnode directory cwd fallback
2026-09-18 14:09:27 +08:00
陈大猫 741299f71d fix(terminal): pass through unavailable broadcast shortcuts (#3435) 2026-09-18 14:09:21 +08:00
陈大猫 349755aaf7 fix(shortcuts): leave Ctrl+L available for terminal clearing (#3433) 2026-09-18 14:09:15 +08:00
陈大猫 199afd56f6 fix(ai): handle sparse streamed tool call indexes (#3434)
* fix(ai): normalize sparse streamed tool call indexes

* test(ai): isolate mocked bridge window typing
2026-09-18 14:09:08 +08:00
246fc39536 fix(vault): round-trip proxy config in CSV import/export (#3438)
* fix(#3437): automated AI fix

* fix: preserve effective CSV proxy settings and reject invalid endpoints

* fix: warn when CSV proxy credentials cannot be exported

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-18 14:08:17 +08:00
526 changed files with 32389 additions and 1907 deletions

No files matched your search

+23
View File
@@ -70,3 +70,26 @@ jobs:
- name: Build
run: npm run build
windows-broadcast-ssh:
name: windows-broadcast-ssh
runs-on: windows-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- name: Install deps
run: npm ci
- name: Build
run: npm run build
- name: Exercise two SSH password prompts in the desktop app
run: node scripts/terminal-broadcast-ssh.live.cjs
+2
View File
@@ -11,6 +11,7 @@ import { TooltipProvider } from './components/ui/tooltip';
import { ScriptAutomationRoot } from './components/scripts/ScriptAutomationRoot';
import { ExternalMcpApprovalsHost } from './components/ai/ExternalMcpApprovalsHost';
import { PluginAuthenticationHost } from './components/plugins/PluginAuthenticationHost';
import { MultilinePasteConfirmHost } from './components/terminal/MultilinePasteConfirmDialog';
import { useExternalMcpGrantPersister } from './components/ai/useExternalMcpGrantPersister';
import { setupMcpApprovalBridge } from './infrastructure/ai/shared/approvalGate';
import { setupCodexAppServerInteractionBridge } from './infrastructure/ai/shared/codexAppServerInteractions';
@@ -81,6 +82,7 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
<ScriptAutomationRoot />
<ExternalMcpApprovalsHost />
<PluginAuthenticationHost />
<MultilinePasteConfirmHost />
<VaultPublisher>
<SessionPublisher persistSessionRestore={!isPeerSessionWindow}>
<App />
@@ -698,3 +698,51 @@ test('connection log host snapshot includes custom host icon fields', () => {
},
);
});
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' },
{ name: 'hidden active session', active: 'hidden', sessions: [{ id: 'one' }, { id: 'two' }, { id: 'hidden', hiddenFromTabs: true }], available: true, expected: null },
{ name: 'non-terminal tab', active: 'vault', sessions: [{ id: 'one' }, { id: 'two' }], available: true, expected: null },
{ name: 'workspace', active: 'workspace', sessions: [{ id: 'one', workspaceId: 'workspace' }, { id: 'two', workspaceId: 'workspace' }], available: false, expected: 'workspace' },
]) {
for (const scheme of ['pc', 'mac'] as const) {
test(`broadcast shortcut ${scheme}: ${scenario.name} only consumes an executed toggle`, () => {
const target = new FakeHTMLElement();
let prevented = 0;
let stopped = 0;
let globalEnabled = false;
let workspaceEnabled = false;
const toggles: string[] = [];
const event = {
key: 'b', code: 'KeyB', ctrlKey: scheme === 'pc', metaKey: scheme === 'mac',
altKey: false, shiftKey: false, target, composedPath: () => [target],
preventDefault: () => { prevented += 1; },
stopPropagation: () => { stopped += 1; },
} as unknown as KeyboardEvent;
const actionCtx = {
activeTabStore: { getActiveTabId: () => scenario.active },
editorTabs: [], orderedTabs: [], settings: {}, toEditorTabId: (id: string) => id,
sessions: scenario.sessions,
workspaces: scenario.active === 'workspace' ? [{ id: 'workspace' }] : [],
canUseGlobalBroadcast: scenario.available,
toggleGlobalBroadcast: () => { globalEnabled = !globalEnabled; toggles.push('global'); },
toggleBroadcast: (id: string) => { assert.equal(id, 'workspace'); workspaceEnabled = !workspaceEnabled; toggles.push('workspace'); },
};
const invoke = () => handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false, closeTabKeyStr: '', hotkeyScheme: scheme,
keyBindings: DEFAULT_KEY_BINDINGS, matchesKeyBinding,
executeHotkeyAction: (action: string, e: KeyboardEvent) => executeHotkeyActionImpl(() => actionCtx, action, e),
}), event);
invoke();
assert.equal(globalEnabled, scenario.expected === 'global');
assert.equal(workspaceEnabled, scenario.expected === 'workspace');
invoke();
assert.equal(globalEnabled, false);
assert.equal(workspaceEnabled, false);
assert.deepEqual(toggles, scenario.expected ? [scenario.expected, scenario.expected] : []);
assert.equal(prevented, scenario.expected ? 2 : 0);
assert.equal(stopped, scenario.expected ? 2 : 0);
});
}
}
+20 -4
View File
@@ -3,7 +3,7 @@ import type React from 'react';
import type { Host, HostProtocol, TerminalSession } from '../../types';
import type { PassphraseRequest } from '../../components/PassphraseModal';
import type { TerminalPopupPayload } from '../../domain/systemManager/types';
import { getEffectiveHostDistro, classifyDistroId, shouldProbeSessionCwd } from '../../domain/host';
import { getEffectiveHostDistro, classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from '../../domain/host';
import { getAvailablePaneMagnificationController } from '../../domain/paneMagnification';
import { sanitizeHostIconFields } from '../../domain/hostIcon';
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
@@ -313,6 +313,16 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
continue;
}
// An unavailable broadcast action must leave the chord to the terminal
// (notably tmux's Ctrl+B prefix). Dispatch once before consuming it.
if (binding.action === 'broadcast') {
if (executeHotkeyAction(binding.action, e) === true) {
e.preventDefault();
e.stopPropagation();
}
return;
}
e.preventDefault();
e.stopPropagation();
if (HOTKEY_DEBUG) {
@@ -525,7 +535,11 @@ async function captureCtxInheritedCwd(getCtx: AppContextGetter, sessionId: strin
if (!liveCwd && isConnectedSsh && !isNetworkDevice) {
try {
const info = await bridge?.getSessionRemoteInfo?.(sessionId);
allowSshProbe = shouldProbeSessionCwd({ isNetworkDevice: false, remoteSshVersion: info?.remoteSshVersion });
allowSshProbe = shouldProbeSessionCwd({
isNetworkDevice: false,
remoteSshVersion: info?.remoteSshVersion,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(host),
});
} catch {
allowSshProbe = false;
}
@@ -963,12 +977,14 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
const activeWs = workspaces.find(w => w.id === currentId);
if (activeWs) {
toggleBroadcast(activeWs.id);
return true;
} else if (sessions.some((session: TerminalSession) => (
session.id === currentId && !session.workspaceId
session.id === currentId && !session.workspaceId && !session.hiddenFromTabs
)) && canUseGlobalBroadcast) {
toggleGlobalBroadcast();
return true;
}
break;
return false;
}
case 'openSettings':
handleOpenSettingsRef.current();
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8");
test("deep-link tab names are applied to terminal sessions", () => {
assert.match(source, /type DeepLinkPayload = \{[\s\S]*tabName\?: string/);
assert.match(source, /const handleConnectToHostWithTabName = useCallback/);
assert.match(source, /renameSessionInline\(sessionId, tabName\)/);
assert.match(source, /handleConnectToHostWithTabName\(ephemeralHost, tabName\)/);
assert.match(
source,
/handleConnectToHostWithTabName\(buildSshDeepLinkConnectionHost\(originalHost\), tabName\)/,
);
assert.match(
source,
/handleConnectToHostWithTabName\(buildTelnetDeepLinkConnectionHost\(matchedEffectiveHost\), tabName\)/,
);
assert.match(source, /label: tabName/);
});
+37 -13
View File
@@ -98,6 +98,11 @@ type OpenSessionInNewWindowPayload = {
localShellType?: TerminalSession['shellType'];
};
type DeepLinkPayload = {
url?: string;
tabName?: string;
};
const IS_DEV = import.meta.env.DEV;
const HOTKEY_DEBUG =
IS_DEV && localStorageAdapter.readString(STORAGE_KEY_DEBUG_HOTKEYS) === '1';
@@ -252,12 +257,15 @@ export function AppSideEffects() {
runSnippet,
getOrderedWorkTabs,
toggleBroadcast,
toggleGlobalBroadcast,
canUseGlobalBroadcast,
logViews,
closeLogView,
copySession,
copyWorkspace,
createSessionFromCloneSource,
getSessionRestoreCwd,
renameSessionInline,
} = sessionState;
// Presentation-field thrash stays off Host bags (Hosts use retainStable);
@@ -906,6 +914,8 @@ export function AppSideEffects() {
// array thrash does not rebuild appTerminalDomain (see domain isolation).
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
const canUseGlobalBroadcastRef = useRef(canUseGlobalBroadcast);
canUseGlobalBroadcastRef.current = canUseGlobalBroadcast;
// Logs live in connectionLogsStore — keep a ref fresh without re-rendering App.
const connectionLogsRef = useRef(getConnectionLogsSnapshot().connectionLogs);
useEffect(() => {
@@ -1076,6 +1086,8 @@ export function AppSideEffects() {
terminalPaneMagnificationRef,
toEditorTabId,
toggleBroadcast,
toggleGlobalBroadcast,
canUseGlobalBroadcast: canUseGlobalBroadcastRef.current,
toggleScriptsSidePanelRef,
toggleSidePanelRef,
toggleWorkspaceViewMode,
@@ -1090,6 +1102,7 @@ export function AppSideEffects() {
splitSessionWithCurrentShell,
moveFocusInWorkspace,
toggleBroadcast,
toggleGlobalBroadcast,
toggleWorkspaceViewMode,
confirmIfBusyLocalTerminal,
]);
@@ -1391,6 +1404,14 @@ export function AppSideEffects() {
}), host, hidden);
}, [addConnectionLog, connectToHost, resolveEffectiveHost, identities, keys]);
const handleConnectToHostWithTabName = useCallback((host: Host, tabName?: string) => {
const sessionId = handleConnectToHost(host);
if (sessionId && tabName) {
renameSessionInline(sessionId, tabName);
}
return sessionId;
}, [handleConnectToHost, renameSessionInline]);
const openHostForVaultAgent = useCallback((host: Host, isExternalMcpCall: boolean) => {
// Silent sessions only apply to actual external MCP clients (chatSessionId
// equals the reserved external-MCP scope). The in-app Catty AI chat's
@@ -1458,15 +1479,16 @@ export function AppSideEffects() {
// deep links until unlock so saved-credential connects cannot start behind
// the lock screen.
const pendingDeepLinksWhileLockedRef = useRef<Array<
| { kind: 'ssh'; payload: { url?: string } }
| { kind: 'telnet'; payload: { url?: string } }
| { kind: 'ssh'; payload: DeepLinkPayload }
| { kind: 'telnet'; payload: DeepLinkPayload }
| { kind: 'jms'; payload: { url?: string } }
| { kind: 'open-terminal-path'; payload: { path?: string } }
>>([]);
const _processSshDeepLink = useEffectEvent((payload: { url?: string }) => {
const _processSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
startupLaunchIntentReceivedRef.current = true;
const rawUrl = payload?.url || '';
const tabName = payload?.tabName?.trim();
const target = parseSshDeepLink(rawUrl);
if (!target) {
toast.warning(t('deepLink.ssh.invalid'));
@@ -1495,25 +1517,26 @@ export function AppSideEffects() {
? buildSshDeepLinkEphemeralHostFromSaved(matchedEffectiveHost, target, draftOptions)
: buildSshDeepLinkEphemeralHost(target, draftOptions);
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHost(ephemeralHost);
handleConnectToHostWithTabName(ephemeralHost, tabName);
return;
}
if (matchedEffectiveHost) {
const originalHost = hosts.find((host) => host.id === matchedEffectiveHost.id) ?? matchedEffectiveHost;
handleConnectToHost(buildSshDeepLinkConnectionHost(originalHost));
handleConnectToHostWithTabName(buildSshDeepLinkConnectionHost(originalHost), tabName);
return;
}
setDeepLinkHostDraft(buildSshDeepLinkHostDraft(target, {
const hostDraft = buildSshDeepLinkHostDraft(target, {
id: crypto.randomUUID(),
now: Date.now(),
}));
});
setDeepLinkHostDraft(tabName ? { ...hostDraft, label: tabName } : hostDraft);
setNavigateToSection('hosts');
setActiveTabId('vault');
});
const _handleSshDeepLink = useEffectEvent((payload: { url?: string }) => {
const _handleSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
pendingDeepLinksWhileLockedRef.current.push({ kind: 'ssh', payload: payload || {} });
return;
@@ -1530,9 +1553,10 @@ export function AppSideEffects() {
});
}, [isPeerSessionWindow]);
const _processTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
const _processTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
startupLaunchIntentReceivedRef.current = true;
const rawUrl = payload?.url || '';
const tabName = payload?.tabName?.trim();
const target = parseTelnetDeepLink(rawUrl);
if (!target) {
toast.warning(t('deepLink.telnet.invalid'));
@@ -1553,10 +1577,10 @@ export function AppSideEffects() {
now: Date.now(),
});
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHost(ephemeralHost);
handleConnectToHostWithTabName(ephemeralHost, tabName);
return;
}
handleConnectToHost(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost));
handleConnectToHostWithTabName(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost), tabName);
return;
}
@@ -1565,10 +1589,10 @@ export function AppSideEffects() {
now: Date.now(),
});
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHost(ephemeralHost);
handleConnectToHostWithTabName(ephemeralHost, tabName);
});
const _handleTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
const _handleTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
pendingDeepLinksWhileLockedRef.current.push({ kind: 'telnet', payload: payload || {} });
return;
+4
View File
@@ -300,6 +300,8 @@ function AppViewInner({ domains }: AppViewProps) {
restoreTerminalCwd,
terminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
} = useSettingsChromeStore();
const { setTheme, setWindowOpacity } = useSettingsChromeActions();
@@ -752,6 +754,8 @@ function AppViewInner({ domains }: AppViewProps) {
sftpAutoOpenSidebar={sftpAutoOpenSidebar}
terminalSidePanelAutoOpen={terminalSidePanelAutoOpen}
terminalSidePanelAutoOpenTab={terminalSidePanelAutoOpenTab}
localShellSidePanelAutoOpen={localShellSidePanelAutoOpen}
localShellSidePanelAutoOpenTab={localShellSidePanelAutoOpenTab}
sftpFollowTerminalCwd={sftpFollowTerminalCwd}
setSftpFollowTerminalCwd={setSftpFollowTerminalCwd}
editorWordWrap={editorWordWrap}
+22 -6
View File
@@ -1,10 +1,12 @@
import type { TransferOwnerObservation } from "../state/sftp/waitForTransferOwner";
import type { TransferStatus, TransferTask } from "../../domain/models";
export const DEDICATED_RESUME_LARGE_HISTORY_THRESHOLD = 4_096;
export const DEDICATED_RESUME_CHILD_UPDATE_BATCH_SIZE = 512;
export interface DedicatedResumeChildUpdateBatcher {
push(task: TransferTask): void;
push(task: TransferTask, observation?: TransferOwnerObservation): void;
discard(taskId: string): void;
flush(): void;
}
@@ -24,25 +26,39 @@ export function createDedicatedResumeChildUpdateBatcher(deps: {
hasTask: (taskId: string) => boolean;
upsertTasks: (tasks: readonly TransferTask[]) => void;
}): DedicatedResumeChildUpdateBatcher {
const pending = new Map<string, TransferTask>();
const pending = new Map<string, { task: TransferTask; observation?: TransferOwnerObservation }>();
const flush = () => {
if (pending.size === 0) return;
const batch = [...pending.values()];
pending.clear();
deps.upsertTasks(batch);
try {
const updates = batch.filter(({ observation }) => !observation?.hasIdentityConflict()).map(({ task }) => task);
if (updates.length) deps.upsertTasks(updates);
} finally {
for (const { observation } of batch) observation?.dispose();
}
};
return {
push(task) {
push(task, observation) {
if (observation?.hasIdentityConflict()) {
pending.get(task.id)?.observation?.dispose();
pending.delete(task.id);
observation.dispose();
return;
}
const shouldBatch = !!task.parentTaskId
&& deps.getTaskCount() >= DEDICATED_RESUME_LARGE_HISTORY_THRESHOLD
&& deps.hasTask(task.id);
if (!shouldBatch) {
deps.upsertTasks([task]);
try { deps.upsertTasks([task]); } finally { observation?.dispose(); }
return;
}
pending.set(task.id, task);
const previous = pending.get(task.id);
if (previous?.observation && previous.observation !== observation) previous.observation.dispose();
pending.set(task.id, { task, observation });
if (pending.size >= DEDICATED_RESUME_CHILD_UPDATE_BATCH_SIZE) flush();
},
discard: (taskId) => { pending.get(taskId)?.observation?.dispose(); pending.delete(taskId); },
flush,
};
}
@@ -28,35 +28,3 @@ test("top tabs chrome theme keeps accent foreground in sync", () => {
assert.match(supportSource, /removeStylePropertyIfSet\(tabsRoot, '--primary-foreground'\)/);
assert.match(supportSource, /removeStylePropertyIfSet\(tabsRoot, '--accent-foreground'\)/);
});
test("bottom title bar receives and clears the same active theme as the tabs", async () => {
const { applyTopTabsChromeThemeVars, clearTopTabsChromeThemeVars } = await import('./topTabsChromeTheme.ts');
const { TERMINAL_THEMES } = await import('../../infrastructure/config/terminalThemes.ts');
const makeRoot = () => {
const values = new Map<string, string>();
return { style: {
getPropertyValue: (key: string) => values.get(key) ?? '',
setProperty: (key: string, value: string) => values.set(key, value),
removeProperty: (key: string) => values.delete(key),
}};
};
const tabs = makeRoot();
const titlebar = makeRoot();
const original = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', { configurable: true, value: {
querySelector: (selector: string) => selector === '[data-top-tabs-root]' ? tabs : titlebar,
}});
try {
applyTopTabsChromeThemeVars(TERMINAL_THEMES[0]);
for (const property of ['--secondary', '--foreground', '--top-tabs-bg']) {
assert.notEqual(tabs.style.getPropertyValue(property), '');
assert.equal(titlebar.style.getPropertyValue(property), tabs.style.getPropertyValue(property));
}
clearTopTabsChromeThemeVars();
assert.equal(tabs.style.getPropertyValue('--secondary'), '');
assert.equal(titlebar.style.getPropertyValue('--secondary'), '');
} finally {
if (original) Object.defineProperty(globalThis, 'document', original);
else Reflect.deleteProperty(globalThis, 'document');
}
});
+20 -30
View File
@@ -70,31 +70,23 @@ const TOP_TABS_THEME_PROPERTIES = [
'--muted-foreground',
] as const;
export function getTopTabsChromeRoots(): HTMLElement[] {
if (typeof document === 'undefined') return [];
return [
document.querySelector<HTMLElement>('[data-top-tabs-root]'),
document.querySelector<HTMLElement>('[data-tab-window-titlebar]'),
].filter((root): root is HTMLElement => root !== null);
}
let topTabsChromeThemeVarsApplied = false;
export function clearTopTabsChromeThemeVars(): void {
if (typeof document === 'undefined') return;
if (!topTabsChromeThemeVarsApplied) return;
for (const root of getTopTabsChromeRoots()) {
for (const property of TOP_TABS_THEME_PROPERTIES) {
removeStylePropertyIfSet(root, property);
}
const tabsRoot = document.querySelector<HTMLElement>('[data-top-tabs-root]');
if (!tabsRoot) return;
for (const property of TOP_TABS_THEME_PROPERTIES) {
removeStylePropertyIfSet(tabsRoot, property);
}
topTabsChromeThemeVarsApplied = false;
}
export function applyTopTabsChromeThemeVars(theme: TerminalTheme): void {
if (typeof document === 'undefined') return;
const roots = getTopTabsChromeRoots();
if (roots.length === 0) return;
const tabsRoot = document.querySelector<HTMLElement>('[data-top-tabs-root]');
if (!tabsRoot) return;
const bg = hexToHslToken(theme.colors.background);
const fg = hexToHslToken(theme.colors.foreground);
@@ -105,21 +97,19 @@ export function applyTopTabsChromeThemeVars(theme: TerminalTheme): void {
const border = adjustLightnessToken(bg, isDark ? 12 : -10);
const mutedFg = adjustSaturationToken(adjustLightnessToken(fg, isDark ? -20 : 20), 0.5);
for (const tabsRoot of roots) {
setStylePropertyIfChanged(tabsRoot, '--background', bg);
setStylePropertyIfChanged(tabsRoot, '--foreground', fg);
setStylePropertyIfChanged(tabsRoot, '--accent', accent);
setStylePropertyIfChanged(tabsRoot, '--accent-foreground', accentForeground);
setStylePropertyIfChanged(tabsRoot, '--primary', accent);
setStylePropertyIfChanged(tabsRoot, '--primary-foreground', accentForeground);
setStylePropertyIfChanged(tabsRoot, '--secondary', secondary);
setStylePropertyIfChanged(tabsRoot, '--border', border);
setStylePropertyIfChanged(tabsRoot, '--muted-foreground', mutedFg);
setStylePropertyIfChanged(tabsRoot, '--top-tabs-bg', 'hsl(var(--secondary))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-fg', 'hsl(var(--foreground))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-muted', 'hsl(var(--muted-foreground))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-active-bg', 'hsl(var(--background))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-accent', 'hsl(var(--accent))');
}
setStylePropertyIfChanged(tabsRoot, '--background', bg);
setStylePropertyIfChanged(tabsRoot, '--foreground', fg);
setStylePropertyIfChanged(tabsRoot, '--accent', accent);
setStylePropertyIfChanged(tabsRoot, '--accent-foreground', accentForeground);
setStylePropertyIfChanged(tabsRoot, '--primary', accent);
setStylePropertyIfChanged(tabsRoot, '--primary-foreground', accentForeground);
setStylePropertyIfChanged(tabsRoot, '--secondary', secondary);
setStylePropertyIfChanged(tabsRoot, '--border', border);
setStylePropertyIfChanged(tabsRoot, '--muted-foreground', mutedFg);
setStylePropertyIfChanged(tabsRoot, '--top-tabs-bg', 'hsl(var(--secondary))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-fg', 'hsl(var(--foreground))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-muted', 'hsl(var(--muted-foreground))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-active-bg', 'hsl(var(--background))');
setStylePropertyIfChanged(tabsRoot, '--top-tabs-accent', 'hsl(var(--accent))');
topTabsChromeThemeVarsApplied = true;
}
+5 -2
View File
@@ -181,11 +181,14 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
},
{
children,
onChildUpdate: (child) => {
onChildUpdate: (child, observation) => {
if (acceptsResumeCallbacks) {
childUpdateBatcher.push({ ...child, ownerId: "dedicated-resume" });
childUpdateBatcher.push({ ...child, ownerId: "dedicated-resume" }, observation);
return true;
}
},
onChildSuperseded: (taskId) => childUpdateBatcher.discard(taskId),
flushChildUpdates: () => childUpdateBatcher.flush(),
onDirectoryCheckpointUpdate: (checkpoint) => {
if (acceptsResumeCallbacks) {
sftpTransferCenterStore.patchTask(task.id, {
+37 -5
View File
@@ -4,6 +4,8 @@ export const enAiMessages: Messages = {
// AI Settings
'ai.agentSettings': 'Agent Settings',
'ai.chat.preparing': 'Preparing…',
'ai.chat.modelCatalogWarning': 'Could not refresh the live model list. Showing the last available or built-in models.',
'ai.chat.modelCatalogRetry': 'Retry',
'ai.chat.compactingContext': 'Compacting earlier context…',
'ai.chat.compactingStep': 'Trimming context for next step…',
'ai.chat.compactionRetry': 'Request was too large. Compacting context and retrying…',
@@ -287,6 +289,18 @@ export const enAiMessages: Messages = {
'ai.opencode.check': 'Check',
'ai.opencode.resetPath': 'Reset',
// AI MiMo Code (Xiaomi MiMo Code CLI — OpenCode fork)
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': "Xiaomi's MiMo Code CLI, an OpenCode fork. Install it and configure providers in its own config, then select it as an external coding agent.",
'ai.mimo.detecting': 'Detecting...',
'ai.mimo.detected': 'Detected',
'ai.mimo.notFound': 'Not found',
'ai.mimo.path': 'Path:',
'ai.mimo.notFoundHint': 'Could not find mimo in PATH. Install it or specify the executable path below.',
'ai.mimo.customPathPlaceholder': 'e.g. /usr/local/bin/mimo',
'ai.mimo.check': 'Check',
'ai.mimo.resetPath': 'Reset',
// AI Grok Build (in-app managed agent — distinct from External MCP client install)
'ai.grok.title': 'Grok Build',
'ai.grok.description': "xAI's Grok Build coding agent CLI. Install the Grok CLI, sign in with `grok login` or set XAI_API_KEY, then select it as an external agent.",
@@ -323,6 +337,13 @@ export const enAiMessages: Messages = {
// External MCP (productized catalog MCP for Codex / Claude Code / Cursor)
'ai.externalMcp.title': 'External MCP',
'ai.externalMcp.allowCommandOnHost': 'Always',
'ai.externalMcp.allowCommandOnHostHint': 'Always allow this action on this server.',
'ai.externalMcp.allowAll': 'Allow all actions',
'ai.externalMcp.allowSession': 'This connection',
'ai.externalMcp.allowSessionHint': 'Allow all actions from this client until it disconnects.',
'ai.externalMcp.allowHost': 'This server',
'ai.externalMcp.allowHostHint': 'Always allow actions on this server.',
'ai.externalMcp.description': 'Expose Netcatty as an MCP server for external clients such as Codex, Claude Code, Cursor, and Grok. Uses the same catalog tools as in-app agents (terminal, SFTP, Vault, port forwarding). Keep Netcatty running while clients are connected.',
'ai.externalMcp.sessionsExposed': 'Sessions in scope: {count}',
'ai.externalMcp.mode': 'Availability mode',
@@ -364,21 +385,24 @@ export const enAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Other',
'ai.externalMcp.cliCommand': 'CLI command',
'ai.externalMcp.configSnippet': 'Config snippet',
'ai.externalMcp.universalSetupPrompt': 'Universal setup prompt',
'ai.externalMcp.addToCodex': 'Add to Codex',
'ai.externalMcp.addToClaude': 'Add to Claude Code',
'ai.externalMcp.addToGrok': 'Add to Grok',
'ai.externalMcp.codexAdded': 'Codex MCP entry added. Restart Codex or open a new Codex session.',
'ai.externalMcp.claudeAdded': 'Claude Code MCP entry added. Restart Claude Code or open a new Claude Code session.',
'ai.externalMcp.grokAdded': 'Grok MCP entry added. Restart Grok or open a new Grok session.',
'ai.externalMcp.codexAdded': 'Codex MCP entry and Netcatty skill added. Restart Codex or open a new Codex session.',
'ai.externalMcp.claudeAdded': 'Claude Code MCP entry and Netcatty skill added. Restart Claude Code or open a new Claude Code session.',
'ai.externalMcp.grokAdded': 'Grok MCP entry and Netcatty skill added. Restart Grok or open a new Grok session.',
'ai.externalMcp.installCodex': 'Install Codex separately, then click Refresh.',
'ai.externalMcp.installClaude': 'Install Claude Code separately, then click Refresh.',
'ai.externalMcp.installGrok': 'Install the Grok CLI separately, then click Refresh.',
'ai.externalMcp.conflict.description': 'A netcatty-external entry already exists and points elsewhere. Remove or edit it manually.',
'ai.externalMcp.enableForLauncher': 'Enable External MCP to get a usable launcher path.',
'ai.externalMcp.cursor.title': 'Cursor / other clients',
'ai.externalMcp.cursor.description': 'Merge this into your MCP config (for example ~/.cursor/mcp.json). Do not replace the whole file if you already have other servers.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Merge this into your Cursor MCP configuration without replacing existing servers.',
'ai.externalMcp.other.description': 'Copy the setup prompt into another terminal agent, or merge the MCP snippet into its client configuration.',
'ai.externalMcp.status.unavailable': 'Unavailable',
'ai.externalMcp.status.disabled': 'Disabled',
'ai.externalMcp.status.running': 'Running',
@@ -597,8 +621,16 @@ export const enAiMessages: Messages = {
'terminal.layer.aiChat': 'AI Chat',
'terminal.layer.movePanelLeft': 'Move panel to left',
'terminal.layer.movePanelRight': 'Move panel to right',
'terminal.layer.movePanelBottom': 'Move panel to bottom',
'terminal.layer.choosePanelPosition': 'Change position',
'terminal.layer.dockLeft': 'Left',
'terminal.layer.dockRight': 'Right',
'terminal.layer.dockBottom': 'Bottom',
'terminal.layer.closePanel': 'Close panel',
'terminal.layer.closePane': 'Close split',
'terminal.layer.saveLayoutAsDefault': 'Save layout as default',
'terminal.layer.layoutSavedAsDefault': 'Layout saved as default',
'terminal.layer.layoutSaveFailed': 'Could not save layout',
'terminal.layer.resizeSplit': 'Resize split',
'terminal.layer.splitHorizontal': 'Split top and bottom',
'terminal.layer.splitVertical': 'Split left and right',
+31 -7
View File
@@ -312,8 +312,11 @@ export const enCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': 'Press a key combination to set a global shortcut for showing/hiding the window.',
'settings.globalHotkey.notSet': 'Not set',
'settings.globalHotkey.reset': 'Reset to default',
'settings.globalHotkey.closeToTray': 'Close to System Tray',
'settings.globalHotkey.closeToTrayDesc': 'When enabled, closing the window will minimize to the system tray instead of quitting.',
'settings.globalHotkey.closeToTray': 'Keep Running When Window Closes',
'settings.globalHotkey.closeToTrayDesc': 'When enabled, closing the window hides it while the app keeps running. Tray icon visibility is set separately.',
'settings.globalHotkey.showTrayIcon': 'Show System Tray Icon',
'settings.globalHotkey.showTrayIconDesc': 'When disabled, the tray icon is hidden but the app keeps running in the background.',
'settings.globalHotkey.showTrayIconHiddenHint': 'Tray icon hidden. Launch the app again or use the global toggle hotkey to bring the window back, then re-enable this setting to restore the icon.',
'settings.globalHotkey.enabled': 'Enable Global Hotkey',
'settings.globalHotkey.enabledDesc': 'Register system-wide keyboard shortcuts. When disabled, all global hotkeys are unregistered.',
'settings.globalHotkey.hint': 'Global hotkey works system-wide to quickly show or hide the window (Quake-style terminal).',
@@ -359,9 +362,6 @@ export const enCoreMessages: Messages = {
'settings.vault.selectBeforeConnectDesc': 'Click once to select a host (accent highlight in grid view), click again to connect. Groups work the same way. Default remains single-click connect.',
'settings.vault.showOnlyUngroupedHostsInRoot': 'Only show ungrouped hosts at root',
'settings.vault.showOnlyUngroupedHostsInRootDesc': 'When enabled, the root host list only shows hosts without a group. Open a group from the sidebar to see grouped hosts.',
'settings.appearance.tabBarPosition': 'Tab bar position',
'settings.appearance.tabBarPosition.top': 'Top',
'settings.appearance.tabBarPosition.bottom': 'Bottom',
'settings.vault.showSftpTab': 'Show SFTP tab',
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
@@ -541,7 +541,7 @@ Highlight the focused split pane:
'settings.appearance.windowOpacity': 'Window Opacity',
'settings.appearance.windowOpacity.desc': 'Adjust the transparency of the entire application window. Lower values also fade terminal text. Some Linux desktop environments may not support this.',
'settings.appearance.appIcon': 'App Icon',
'settings.appearance.appIcon.desc': 'Choose a dock/taskbar icon style to make Netcatty easier to spot when switching apps. Applies at runtime; the installed app bundle icon is unchanged.',
'settings.appearance.appIcon.desc': 'Choose a dock/taskbar icon style to make Netcatty easier to spot when switching apps. On Windows, the notification area icon uses the same style. Applies at runtime; the installed app bundle icon is unchanged.',
'settings.appearance.appIcon.original': 'Original',
'settings.appearance.appIcon.bright': 'Bright',
'settings.appearance.appIcon.dark': 'Dark',
@@ -617,6 +617,8 @@ Highlight the focused split pane:
'settings.terminal.font.weightBold.desc': 'Weight for bold text (100-900)',
'settings.terminal.font.smoothing': 'Font smoothing',
'settings.terminal.font.smoothing.desc': 'Use native macOS font anti-aliasing',
'settings.terminal.font.ligatures': 'Font ligatures',
'settings.terminal.font.ligatures.desc': 'Render ligatures such as != when the terminal font includes them',
'settings.terminal.font.linePadding': 'Line padding',
'settings.terminal.font.linePadding.desc': 'Additional space between lines (0-10)',
'settings.terminal.font.emulationType': 'Terminal emulation type',
@@ -624,6 +626,8 @@ Highlight the focused split pane:
'settings.terminal.cursor.style.block': 'Block',
'settings.terminal.cursor.style.bar': 'Bar',
'settings.terminal.cursor.style.underline': 'Underline',
'settings.terminal.cursor.barWidth': 'Bar cursor width',
'settings.terminal.cursor.barWidth.desc': 'Width of bar cursors used by applications such as vi (1-4 px)',
'settings.terminal.cursor.blink': 'Cursor blink',
'settings.terminal.cursor.highlightLine': 'Highlight current line',
'settings.terminal.cursor.highlightLine.desc':
@@ -649,6 +653,12 @@ Highlight the focused split pane:
'settings.terminal.sidePanel.pane.system': 'System',
'settings.terminal.sidePanel.pane.notes': 'Notes',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': 'Local Shell Side Panel',
'settings.terminal.localShellSidePanel.autoOpen': 'Open side panel with local shell',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Automatically open a side panel when opening a local shell.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Default side panel',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Choose which panel opens first.',
'settings.terminal.localShellSidePanel.pane.files': 'Files',
'settings.terminal.accessibility.minimumContrastRatio.desc':
'Adjust colors to meet contrast requirements (1 = disabled, 21 = max)',
'settings.terminal.behavior.rightClick': 'Right-click behavior',
@@ -691,12 +701,21 @@ Highlight the focused split pane:
'settings.terminal.behavior.autoUploadClipboardImage': 'Auto-upload clipboard images on paste',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'When the clipboard holds an image, pasting in a remote session uploads it via SFTP to .netcatty-paste-images/ under the remote working directory and inserts the remote path instead of pasting text.',
'settings.terminal.behavior.confirmMultilinePaste': 'Ask before pasting multiple lines',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Show a confirmation dialog before pasting multiple lines, with the line/character count, an editable preview, and Send / Send line by line / Cancel actions. Protects switch and firewall CLIs (Cisco IOS, Huawei VRP, H3C Comware) that do not support bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Confirmation threshold (lines)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Ask for confirmation when a paste contains at least this many lines.',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter text',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Send configured text instead of normal Enter when pressing Shift+Enter in the terminal.',
'settings.terminal.behavior.shiftEnterNewlineText': 'Text to send',
'settings.terminal.behavior.shiftEnterNewlineText.desc':
'Use \\n for newline, \\t for tab, and \\\\ for backslash.',
'Use \\n for newline, \\t for tab, \\e for Escape, and \\\\ for backslash.',
'settings.terminal.behavior.shiftEnterForceText': 'Send text in Win32 input mode',
'settings.terminal.behavior.shiftEnterForceText.desc':
'Also send the text above when a local Windows ConPTY session negotiates Win32 input mode. Needed for Node/Bun CLIs (Claude Code, CodeBuddy) that cannot read modifier keys from console input records.',
'settings.terminal.behavior.clearWipesScrollback': '`clear` wipes scrollback',
'settings.terminal.behavior.clearWipesScrollback.desc':
'Make `clear` also wipe the scrollback buffer (POSIX default). Disable to keep history visible after `clear`.',
@@ -1048,6 +1067,10 @@ Highlight the focused split pane:
'vault.groups.deleteDialogTitle': 'Delete Group',
'vault.groups.deleteDialog.desc': 'This will permanently delete the group and move all hosts to the root level.',
'vault.groups.deleteDialog.managedDesc': 'This is a managed SSH config group. Deleting it will also delete all hosts and unlink from the source file.',
'vault.groups.deleteDialog.mixedDesc': 'This group contains hosts imported from a linked SSH config file. Every host under its managed subgroup will be deleted, even hosts not managed by that file. All other hosts will move to the root level unless you also delete them below.',
'vault.groups.deleteDialog.managedWarning': 'Deleting this group will also clear its entries from the linked SSH config file. Entries that came from that file may be lost for other apps that use it. Back up the file before continuing.',
'vault.groups.deleteDialog.sourcesChanged': 'The managed files affected by this deletion have changed. Review the files and confirm again.',
'vault.groups.deleteDialog.managedFile': 'Linked file: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Also delete all hosts in this group',
'vault.groups.deleteDialog.bulkTitle': 'Delete Selected Groups',
'vault.groups.deleteDialog.bulkDesc': 'This will permanently delete the selected groups and move their hosts to the root level.',
@@ -1106,6 +1129,7 @@ Highlight the focused split pane:
'vault.hosts.export.toast.success': 'Exported {count} hosts to CSV',
'vault.hosts.export.toast.successWithSkipped': 'Exported {count} hosts to CSV ({skipped} unsupported hosts skipped)',
'vault.hosts.export.toast.passphrasesSkipped': '{count} saved key passphrases could not be read and were left blank',
'vault.hosts.export.toast.proxyCredentialsSkipped': '{count} saved proxy passwords could not be read and were left blank',
'vault.hosts.export.toast.noHosts': 'No hosts to export',
'vault.hosts.allHosts': 'All hosts',
'vault.hosts.pinned': 'Pinned',
+3
View File
@@ -27,6 +27,9 @@ export const enScriptsMessages = {
'scripts.actions.runParallel': 'Run on all tabs (parallel)',
'scripts.actions.runSequential': 'Run on all tabs (sequential)',
'scripts.actions.runOnAllTabs': 'Run on all tabs',
'scripts.actions.copyCommand': 'Copy command',
'scripts.actions.copyCommand.copied': 'Command copied',
'scripts.actions.copyCommand.failed': 'Could not copy command',
'scripts.actions.skippedConnectingSessions': '{count} tab(s) still connecting and were skipped',
'scripts.actions.skippedSensitiveSessions': '{count} tab(s) skipped (password/sensitive input)',
'scripts.actions.noRunnableHosts': 'No connectable hosts match this script\'s targets',
@@ -31,6 +31,7 @@ export const enSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': 'Failed to load listening ports',
'systemManager.errors.loadServices': 'Failed to load systemd services',
'systemManager.errors.sshChannelUnavailable': 'The server refused to open a new execution channel. Try again later, or reconnect this host.',
'systemManager.unsupportedRemote': 'This host does not allow extra SSH exec channels, so System Manager is unavailable. Opening this panel will no longer disconnect the terminal.',
'systemManager.overview.empty': 'No system overview data yet.',
'systemManager.overview.loading': 'Loading system overview…',
+15
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const enTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Save current screen',
'terminal.saveScreen.failed': 'Failed to save terminal screen.',
// Multi-line paste confirmation dialog (#3398)
'terminal.pasteConfirm.title': 'Paste multiple lines?',
'terminal.pasteConfirm.summary': '{lines} lines ({chars} characters) will be sent to the session.',
'terminal.pasteConfirm.preview': 'Preview (editable)',
'terminal.pasteConfirm.send': 'Send',
'terminal.pasteConfirm.sendLineByLine': 'Send line by line',
'terminal.pasteConfirm.cancel': 'Cancel',
'terminal.sudoHint.pressEnter': 'Press Enter to paste saved password',
'terminal.passwordPicker.title': 'Saved passwords',
'terminal.passwordPicker.empty': 'No saved passwords',
@@ -54,6 +61,7 @@ export const enTerminalMessages: Messages = {
'terminal.composeBar.send': 'Send',
'terminal.composeBar.close': 'Close compose bar',
'terminal.composeBar.broadcasting': 'Broadcasting to all sessions',
'terminal.composeBar.broadcastAllowPassword': 'Broadcast without password protection',
'terminal.composeBar.resize': 'Resize compose bar height',
'terminal.composeBar.manageSnippets': 'Manage quick snippets',
'terminal.composeBar.searchSnippets': 'Search snippets...',
@@ -93,6 +101,7 @@ export const enTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Reconnect this session',
'terminal.serverStats.cpu': 'CPU Usage',
'terminal.serverStats.cpuCores': 'CPU Core Usage',
'terminal.serverStats.gpu': 'GPU Usage',
'terminal.serverStats.memory': 'Memory Usage',
'terminal.serverStats.memoryDetails': 'Memory Details',
'terminal.serverStats.memUsed': 'Used',
@@ -126,6 +135,7 @@ export const enTerminalMessages: Messages = {
'terminal.search.noResults': 'No results',
'terminal.search.prevMatch': 'Previous match (Shift+Enter)',
'terminal.search.nextMatch': 'Next match (Enter)',
'terminal.menu.cut': 'Cut',
'terminal.menu.copy': 'Copy',
'terminal.menu.paste': 'Paste',
'terminal.menu.uploadClipboardImage': 'Upload clipboard image',
@@ -180,6 +190,7 @@ export const enTerminalMessages: Messages = {
'terminal.auth.retryMessage': 'Authentication failed. Please check your credentials and try again.',
'terminal.auth.retryLog': 'Authentication failed. Please try again.',
'terminal.auth.noKeysHint': 'No keys available. Add keys in Keychain.',
'terminal.auth.selectIdentity': 'Use saved identity',
'terminal.auth.continueSave': 'Continue & Save',
'terminal.auth.credentialsUnavailable': 'Saved credentials cannot be decrypted on this device. Please re-enter and save them again.',
'terminal.auth.jumpCredentialsUnavailable': 'A jump host has saved credentials that cannot be decrypted on this device. Open host settings and re-enter them.',
@@ -827,6 +838,10 @@ export const enTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'e.g. Arduino Uno',
'serial.connectAndSave': 'Connect & Save',
'serial.edit.title': 'Serial Port Settings',
'serial.field.username': 'Username',
'serial.field.password': 'Password',
'serial.field.autoLoginDesc': 'When set, Login/Password prompts on the serial console are answered automatically with these saved credentials.',
'serial.field.clearPassword': 'Clear saved password',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Authentication Required',
-1
View File
@@ -417,7 +417,6 @@ export const enVaultMessages: Messages = {
'sftp.goUp': 'Go up',
'sftp.goToTerminalCwd': 'Go to terminal directory',
'sftp.locatePathInTerminal': 'Open path in terminal',
'sftp.refreshAfterCommand': 'Refresh after terminal commands',
'sftp.followTerminalCwd': 'Follow terminal directory',
'sftp.followTerminalCwd.enable': 'Enable follow terminal directory',
'sftp.followTerminalCwd.disable': 'Disable follow terminal directory',
+34 -5
View File
@@ -4,6 +4,8 @@ export const esAiMessages: Messages = {
// AI Settings
'ai.agentSettings': 'Configuración del agente',
'ai.chat.preparing': 'Preparando…',
'ai.chat.modelCatalogWarning': 'No se pudo actualizar la lista de modelos. Se muestran los últimos modelos disponibles o los integrados.',
'ai.chat.modelCatalogRetry': 'Reintentar',
'ai.chat.compactingContext': 'Compactando el contexto anterior…',
'ai.chat.compactingStep': 'Recortando el contexto para el siguiente paso…',
'ai.chat.compactionRetry': 'La petición era demasiado grande. Compactando el contexto y reintentando…',
@@ -278,6 +280,18 @@ export const esAiMessages: Messages = {
'ai.opencode.check': 'Verificar',
'ai.opencode.resetPath': 'Restablecer',
// AI MiMo Code (CLI de Xiaomi MiMo Code — fork de OpenCode)
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'CLI de MiMo Code de Xiaomi, un fork de OpenCode. Instálalo y configura los proveedores en su propia configuración, luego selecciónalo como agente de codificación externo.',
'ai.mimo.detecting': 'Detectando...',
'ai.mimo.detected': 'Detectado',
'ai.mimo.notFound': 'No encontrado',
'ai.mimo.path': 'Ruta:',
'ai.mimo.notFoundHint': 'No se pudo encontrar mimo en el PATH. Instálalo o especifica la ruta del ejecutable a continuación.',
'ai.mimo.customPathPlaceholder': 'p. ej. /usr/local/bin/mimo',
'ai.mimo.check': 'Verificar',
'ai.mimo.resetPath': 'Restablecer',
// AI Grok Build (in-app managed agent — distinct from External MCP client install)
'ai.grok.title': 'Grok Build',
'ai.grok.description': "La CLI de agente de codificación Grok Build de xAI. Instala la CLI de Grok, inicia sesión con `grok login` o define XAI_API_KEY, y luego selecciónala como agente externo.",
@@ -314,6 +328,13 @@ export const esAiMessages: Messages = {
// External MCP (productized catalog MCP for Codex / Claude Code / Cursor)
'ai.externalMcp.title': 'MCP externo',
'ai.externalMcp.allowCommandOnHost': 'Siempre',
'ai.externalMcp.allowCommandOnHostHint': 'Permitir siempre esta acción en este servidor.',
'ai.externalMcp.allowAll': 'Permitir todas las acciones',
'ai.externalMcp.allowSession': 'Esta conexión',
'ai.externalMcp.allowSessionHint': 'Permitir todas las acciones de este cliente hasta que se desconecte.',
'ai.externalMcp.allowHost': 'Este servidor',
'ai.externalMcp.allowHostHint': 'Permitir siempre acciones en este servidor.',
'ai.externalMcp.description': 'Expón Netcatty como un servidor MCP para clientes externos como Codex, Claude Code, Cursor y Grok. Usa las mismas herramientas del catálogo que los agentes de la aplicación (terminal, SFTP, Vault, reenvío de puertos). Mantén Netcatty en ejecución mientras los clientes estén conectados.',
'ai.externalMcp.sessionsExposed': 'Sesiones en alcance: {count}',
'ai.externalMcp.mode': 'Modo de disponibilidad',
@@ -355,21 +376,24 @@ export const esAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Otros',
'ai.externalMcp.cliCommand': 'Comando CLI',
'ai.externalMcp.configSnippet': 'Fragmento de configuración',
'ai.externalMcp.universalSetupPrompt': 'Prompt de instalación universal',
'ai.externalMcp.addToCodex': 'Agregar a Codex',
'ai.externalMcp.addToClaude': 'Agregar a Claude Code',
'ai.externalMcp.addToGrok': 'Agregar a Grok',
'ai.externalMcp.codexAdded': 'Entrada de MCP de Codex agregada. Reinicia Codex o abre una nueva sesión de Codex.',
'ai.externalMcp.claudeAdded': 'Entrada de MCP de Claude Code agregada. Reinicia Claude Code o abre una nueva sesión de Claude Code.',
'ai.externalMcp.grokAdded': 'Entrada de MCP de Grok agregada. Reinicia Grok o abre una nueva sesión de Grok.',
'ai.externalMcp.codexAdded': 'Entrada MCP de Codex y skill de Netcatty agregados. Reinicia Codex o abre una nueva sesión de Codex.',
'ai.externalMcp.claudeAdded': 'Entrada MCP de Claude Code y skill de Netcatty agregados. Reinicia Claude Code o abre una nueva sesión de Claude Code.',
'ai.externalMcp.grokAdded': 'Entrada MCP de Grok y skill de Netcatty agregados. Reinicia Grok o abre una nueva sesión de Grok.',
'ai.externalMcp.installCodex': 'Instala Codex por separado y luego haz clic en Actualizar.',
'ai.externalMcp.installClaude': 'Instala Claude Code por separado y luego haz clic en Actualizar.',
'ai.externalMcp.installGrok': 'Instala la CLI de Grok por separado y luego haz clic en Actualizar.',
'ai.externalMcp.conflict.description': 'Ya existe una entrada netcatty-external que apunta a otro lugar. Quítala o edítala manualmente.',
'ai.externalMcp.enableForLauncher': 'Habilita el MCP externo para obtener una ruta de launcher utilizable.',
'ai.externalMcp.cursor.title': 'Cursor / otros clientes',
'ai.externalMcp.cursor.description': 'Combina esto en tu configuración de MCP (por ejemplo, ~/.cursor/mcp.json). No reemplaces todo el archivo si ya tienes otros servidores.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Combina esto con la configuración MCP de Cursor sin reemplazar los servidores existentes.',
'ai.externalMcp.other.description': 'Copia el prompt de instalación en otro agente de terminal o combina el fragmento MCP con la configuración de su cliente.',
'ai.externalMcp.status.unavailable': 'No disponible',
'ai.externalMcp.status.disabled': 'Desactivado',
'ai.externalMcp.status.running': 'En ejecución',
@@ -588,6 +612,11 @@ export const esAiMessages: Messages = {
'terminal.layer.aiChat': 'Chat de IA',
'terminal.layer.movePanelLeft': 'Mover panel a la izquierda',
'terminal.layer.movePanelRight': 'Mover panel a la derecha',
'terminal.layer.movePanelBottom': 'Mover panel a la parte inferior',
'terminal.layer.choosePanelPosition': 'Cambiar posición',
'terminal.layer.dockLeft': 'Izquierda',
'terminal.layer.dockRight': 'Derecha',
'terminal.layer.dockBottom': 'Abajo',
'terminal.layer.closePanel': 'Cerrar panel',
'terminal.layer.closePane': 'Cerrar división',
'terminal.layer.resizeSplit': 'Redimensionar división',
+31 -7
View File
@@ -227,8 +227,11 @@ export const esCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': 'Presiona una combinación de teclas para definir un atajo global que muestre u oculte la ventana.',
'settings.globalHotkey.notSet': 'No configurada',
'settings.globalHotkey.reset': 'Restablecer al valor predeterminado',
'settings.globalHotkey.closeToTray': 'Cerrar a la bandeja del sistema',
'settings.globalHotkey.closeToTrayDesc': 'Cuando está activado, cerrar la ventana la minimiza a la bandeja del sistema en lugar de salir.',
'settings.globalHotkey.closeToTray': 'Seguir en segundo plano al cerrar la ventana',
'settings.globalHotkey.closeToTrayDesc': 'Al cerrar la ventana, se oculta y la aplicación sigue activa. La visibilidad del icono de la bandeja se configura aparte.',
'settings.globalHotkey.showTrayIcon': 'Mostrar icono de la bandeja del sistema',
'settings.globalHotkey.showTrayIconDesc': 'Cuando está desactivado, el icono de la bandeja se oculta, pero la aplicación sigue ejecutándose en segundo plano.',
'settings.globalHotkey.showTrayIconHiddenHint': 'Icono de la bandeja oculto. Vuelve a iniciar la aplicación o usa el atajo global para recuperar la ventana y vuelve a activar este ajuste para restaurar el icono.',
'settings.globalHotkey.enabled': 'Activar tecla de acceso global',
'settings.globalHotkey.enabledDesc': 'Registra atajos de teclado a nivel de todo el sistema. Cuando está desactivado, todas las teclas de acceso global se desregistran.',
'settings.globalHotkey.hint': 'La tecla de acceso global funciona en todo el sistema para mostrar u ocultar la ventana rápidamente (terminal estilo Quake).',
@@ -274,9 +277,6 @@ export const esCoreMessages: Messages = {
'settings.vault.selectBeforeConnectDesc': 'Haz clic una vez para seleccionar un host (resaltado con el color de acento en la vista de cuadrícula), haz clic de nuevo para conectarte. Los grupos funcionan igual. El valor predeterminado sigue siendo conectarse con un solo clic.',
'settings.vault.showOnlyUngroupedHostsInRoot': 'Mostrar solo hosts sin grupo en la raíz',
'settings.vault.showOnlyUngroupedHostsInRootDesc': 'Cuando está activado, la lista de hosts de la raíz solo muestra hosts sin grupo. Abre un grupo desde la barra lateral para ver los hosts agrupados.',
'settings.appearance.tabBarPosition': 'Posición de la barra de pestañas',
'settings.appearance.tabBarPosition.top': 'Arriba',
'settings.appearance.tabBarPosition.bottom': 'Abajo',
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
@@ -456,7 +456,7 @@ Resalta el panel dividido enfocado:
'settings.appearance.windowOpacity': 'Opacidad de la ventana',
'settings.appearance.windowOpacity.desc': 'Ajusta la transparencia de toda la ventana de la aplicación. Los valores más bajos también atenúan el texto de la terminal. Algunos entornos de escritorio de Linux pueden no admitir esto.',
'settings.appearance.appIcon': 'Ícono de la aplicación',
'settings.appearance.appIcon.desc': 'Elige un estilo de ícono para el dock o la barra de tareas que haga más fácil distinguir Netcatty al cambiar de aplicación. Se aplica en tiempo de ejecución; el ícono del paquete instalado no cambia.',
'settings.appearance.appIcon.desc': 'Elige un estilo de ícono para el dock o la barra de tareas que haga más fácil distinguir Netcatty al cambiar de aplicación. En Windows, el icono del área de notificación usa el mismo estilo. Se aplica en tiempo de ejecución; el ícono del paquete instalado no cambia.',
'settings.appearance.appIcon.original': 'Original',
'settings.appearance.appIcon.bright': 'Brillante',
'settings.appearance.appIcon.dark': 'Oscuro',
@@ -532,6 +532,8 @@ Resalta el panel dividido enfocado:
'settings.terminal.font.weightBold.desc': 'Peso del texto en negrita (100-900)',
'settings.terminal.font.smoothing': 'Suavizado de fuente',
'settings.terminal.font.smoothing.desc': 'Usar el anti-aliasing nativo de fuentes de macOS',
'settings.terminal.font.ligatures': 'Ligaduras de fuente',
'settings.terminal.font.ligatures.desc': 'Mostrar ligaduras como != cuando la fuente del terminal las incluye',
'settings.terminal.font.linePadding': 'Espaciado de líneas',
'settings.terminal.font.linePadding.desc': 'Espacio adicional entre líneas (0-10)',
'settings.terminal.font.emulationType': 'Tipo de emulación de terminal',
@@ -539,6 +541,8 @@ Resalta el panel dividido enfocado:
'settings.terminal.cursor.style.block': 'Bloque',
'settings.terminal.cursor.style.bar': 'Barra',
'settings.terminal.cursor.style.underline': 'Subrayado',
'settings.terminal.cursor.barWidth': 'Ancho del cursor de barra',
'settings.terminal.cursor.barWidth.desc': 'Ancho de los cursores de barra utilizados por aplicaciones como vi (1-4 px)',
'settings.terminal.cursor.blink': 'Parpadeo del cursor',
'settings.terminal.cursor.highlightLine': 'Resaltar línea actual',
'settings.terminal.cursor.highlightLine.desc':
@@ -564,6 +568,12 @@ Resalta el panel dividido enfocado:
'settings.terminal.sidePanel.pane.system': 'Sistema',
'settings.terminal.sidePanel.pane.notes': 'Notas',
'settings.terminal.sidePanel.pane.ai': 'IA',
'settings.terminal.section.localShellSidePanel': 'Panel lateral de Shell local',
'settings.terminal.localShellSidePanel.autoOpen': 'Expandir panel lateral al abrir Shell local',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Abre automáticamente un panel lateral después de abrir el Shell local.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Panel lateral predeterminado',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Elige qué panel se abre primero.',
'settings.terminal.localShellSidePanel.pane.files': 'Archivos',
'settings.terminal.accessibility.minimumContrastRatio.desc':
'Ajusta los colores para cumplir con los requisitos de contraste (1 = desactivado, 21 = máximo)',
'settings.terminal.behavior.rightClick': 'Comportamiento del clic derecho',
@@ -606,12 +616,21 @@ Resalta el panel dividido enfocado:
'settings.terminal.behavior.autoUploadClipboardImage': 'Subir automáticamente imágenes del portapapeles al pegar',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'Cuando el portapapeles contiene una imagen, pegarla en una sesión remota la sube por SFTP a .netcatty-paste-images/ dentro del directorio de trabajo remoto e inserta la ruta remota en lugar de pegar texto.',
'settings.terminal.behavior.confirmMultilinePaste': 'Preguntar antes de pegar varias líneas',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Muestra un diálogo de confirmación antes de pegar varias líneas, con el número de líneas y caracteres, una vista previa editable y las acciones Enviar / Enviar línea por línea / Cancelar. Protege las CLI de dispositivos de red (Cisco IOS, Huawei VRP, H3C Comware) que no admiten bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Umbral de confirmación (líneas)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Pedir confirmación cuando el texto pegado contenga al menos esta cantidad de líneas.',
'settings.terminal.behavior.shiftEnterNewline': 'Texto de Shift+Enter',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Envía el texto configurado en lugar del Enter normal al presionar Shift+Enter en la terminal.',
'settings.terminal.behavior.shiftEnterNewlineText': 'Texto a enviar',
'settings.terminal.behavior.shiftEnterNewlineText.desc':
'Usa \\n para nueva línea, \\t para tabulación y \\\\ para barra invertida.',
'Usa \\n para nueva línea, \\t para tabulación, \\e para Escape y \\\\ para barra invertida.',
'settings.terminal.behavior.shiftEnterForceText': 'Enviar texto también en modo de entrada Win32',
'settings.terminal.behavior.shiftEnterForceText.desc':
'Envía también el texto anterior cuando una sesión ConPTY local de Windows negocia el modo de entrada Win32. Necesario para CLI escritas en Node/Bun (Claude Code, CodeBuddy) que no pueden leer modificadores desde los registros de entrada de la consola.',
'settings.terminal.behavior.clearWipesScrollback': '`clear` borra el historial de desplazamiento',
'settings.terminal.behavior.clearWipesScrollback.desc':
'Haz que `clear` también borre el buffer del historial de desplazamiento (predeterminado de POSIX). Desactívalo para mantener visible el historial después de `clear`.',
@@ -1006,6 +1025,10 @@ Resalta el panel dividido enfocado:
'vault.groups.deleteDialogTitle': 'Eliminar grupo',
'vault.groups.deleteDialog.desc': 'Esto eliminará permanentemente el grupo y moverá todos los hosts al nivel raíz.',
'vault.groups.deleteDialog.managedDesc': 'Este es un grupo administrado de configuración SSH. Eliminarlo también eliminará todos los hosts y lo desvinculará del archivo de origen.',
'vault.groups.deleteDialog.mixedDesc': 'Este grupo contiene hosts importados de un archivo de configuración SSH vinculado. Todos los hosts bajo su subgrupo administrado se eliminarán, incluso los hosts no administrados por ese archivo. Los demás hosts se moverán al nivel raíz a menos que también los elimine abajo.',
'vault.groups.deleteDialog.managedWarning': 'Al eliminar este grupo también se borrarán sus entradas del archivo de configuración SSH vinculado. Las entradas provenientes de ese archivo pueden perderse y también afectará a otras aplicaciones que lo usen. Haz una copia de seguridad del archivo antes de continuar.',
'vault.groups.deleteDialog.sourcesChanged': 'Los archivos administrados afectados por esta eliminación han cambiado. Revisa los archivos y vuelve a confirmar.',
'vault.groups.deleteDialog.managedFile': 'Archivo vinculado: {file}',
'vault.groups.deleteDialog.deleteHosts': 'También eliminar todos los hosts de este grupo',
'vault.groups.deleteDialog.bulkTitle': 'Eliminar grupos seleccionados',
'vault.groups.deleteDialog.bulkDesc': 'Esto eliminará permanentemente los grupos seleccionados y moverá sus hosts al nivel raíz.',
@@ -1064,6 +1087,7 @@ Resalta el panel dividido enfocado:
'vault.hosts.export.toast.success': 'Se exportaron {count} hosts a CSV',
'vault.hosts.export.toast.successWithSkipped': 'Se exportaron {count} hosts a CSV (se omitieron {skipped} hosts no compatibles)',
'vault.hosts.export.toast.passphrasesSkipped': 'No se pudieron leer {count} frases de contraseña de claves guardadas y se dejaron en blanco',
'vault.hosts.export.toast.proxyCredentialsSkipped': 'No se pudieron leer {count} contraseñas de proxy guardadas y se dejaron en blanco',
'vault.hosts.export.toast.noHosts': 'No hay hosts para exportar',
'vault.hosts.allHosts': 'Todos los hosts',
'vault.hosts.pinned': 'Fijados',
+3
View File
@@ -27,6 +27,9 @@ export const esScriptsMessages = {
'scripts.actions.runParallel': 'Ejecutar en todas las pestañas (en paralelo)',
'scripts.actions.runSequential': 'Ejecutar en todas las pestañas (en secuencia)',
'scripts.actions.runOnAllTabs': 'Ejecutar en todas las pestañas',
'scripts.actions.copyCommand': 'Copiar comando',
'scripts.actions.copyCommand.copied': 'Comando copiado',
'scripts.actions.copyCommand.failed': 'No se pudo copiar el comando',
'scripts.actions.skippedConnectingSessions': '{count} pestaña(s) aún conectándose y fueron omitidas',
'scripts.actions.skippedSensitiveSessions': '{count} pestaña(s) omitidas (entrada de contraseña/datos sensibles)',
'scripts.actions.noRunnableHosts': 'Ningún host conectable coincide con los destinos de este script',
@@ -31,6 +31,7 @@ export const esSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': 'No se pudieron cargar los puertos en escucha',
'systemManager.errors.loadServices': 'No se pudieron cargar los servicios de systemd',
'systemManager.errors.sshChannelUnavailable': 'El servidor se negó a abrir un nuevo canal de ejecución. Inténtalo de nuevo más tarde o vuelve a conectar este host.',
'systemManager.unsupportedRemote': 'Este host no permite canales SSH de ejecución adicionales, por lo que el administrador del sistema no está disponible. Abrir este panel ya no desconectará la terminal.',
'systemManager.overview.empty': 'Aún no hay datos de resumen del sistema.',
'systemManager.overview.loading': 'Cargando resumen del sistema…',
+15
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const esTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Guardar pantalla actual',
'terminal.saveScreen.failed': 'No se pudo guardar la pantalla del terminal.',
// Diálogo de confirmación de pegado multilínea (#3398)
'terminal.pasteConfirm.title': '¿Pegar varias líneas?',
'terminal.pasteConfirm.summary': 'Se enviarán {lines} líneas ({chars} caracteres) a la sesión.',
'terminal.pasteConfirm.preview': 'Vista previa (editable)',
'terminal.pasteConfirm.send': 'Enviar',
'terminal.pasteConfirm.sendLineByLine': 'Enviar línea por línea',
'terminal.pasteConfirm.cancel': 'Cancelar',
'terminal.sudoHint.pressEnter': 'Presiona Enter para pegar la contraseña guardada',
'terminal.passwordPicker.title': 'Contraseñas guardadas',
'terminal.passwordPicker.empty': 'No hay contraseñas guardadas',
@@ -54,6 +61,7 @@ export const esTerminalMessages: Messages = {
'terminal.composeBar.send': 'Enviar',
'terminal.composeBar.close': 'Cerrar barra de redacción',
'terminal.composeBar.broadcasting': 'Difundiendo a todas las sesiones',
'terminal.composeBar.broadcastAllowPassword': 'Difundir sin protección de contraseña',
'terminal.composeBar.resize': 'Cambiar la altura de la barra de redacción',
'terminal.composeBar.manageSnippets': 'Administrar snippets rápidos',
'terminal.composeBar.searchSnippets': 'Buscar snippets...',
@@ -93,6 +101,7 @@ export const esTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Reconectar esta sesión',
'terminal.serverStats.cpu': 'Uso de CPU',
'terminal.serverStats.cpuCores': 'Uso de núcleos de CPU',
'terminal.serverStats.gpu': 'Uso de GPU',
'terminal.serverStats.memory': 'Uso de memoria',
'terminal.serverStats.memoryDetails': 'Detalles de memoria',
'terminal.serverStats.memUsed': 'Usada',
@@ -126,6 +135,7 @@ export const esTerminalMessages: Messages = {
'terminal.search.noResults': 'Sin resultados',
'terminal.search.prevMatch': 'Coincidencia anterior (Shift+Enter)',
'terminal.search.nextMatch': 'Coincidencia siguiente (Enter)',
'terminal.menu.cut': 'Cortar',
'terminal.menu.copy': 'Copiar',
'terminal.menu.paste': 'Pegar',
'terminal.menu.uploadClipboardImage': 'Subir imagen del portapapeles',
@@ -180,6 +190,7 @@ export const esTerminalMessages: Messages = {
'terminal.auth.retryMessage': 'Falló la autenticación. Verifica tus credenciales e inténtalo de nuevo.',
'terminal.auth.retryLog': 'Falló la autenticación. Inténtalo de nuevo.',
'terminal.auth.noKeysHint': 'No hay claves disponibles. Agrega claves en Keychain.',
'terminal.auth.selectIdentity': 'Usar identidad guardada',
'terminal.auth.continueSave': 'Continuar y guardar',
'terminal.auth.credentialsUnavailable': 'Las credenciales guardadas no se pueden descifrar en este dispositivo. Vuelve a ingresarlas y guárdalas de nuevo.',
'terminal.auth.jumpCredentialsUnavailable': 'Un host de salto tiene credenciales guardadas que no se pueden descifrar en este dispositivo. Abre la configuración del host y vuelve a ingresarlas.',
@@ -827,6 +838,10 @@ export const esTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'p. ej., Arduino Uno',
'serial.connectAndSave': 'Conectar y guardar',
'serial.edit.title': 'Configuración del puerto serial',
'serial.field.username': 'Usuario',
'serial.field.password': 'Contraseña',
'serial.field.autoLoginDesc': 'Si se establecen, los mensajes Login/Password de la consola serial se responden automáticamente con estas credenciales guardadas.',
'serial.field.clearPassword': 'Borrar la contraseña guardada',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Se requiere autenticación',
+22 -5
View File
@@ -5,6 +5,8 @@ export const ruAiMessages: Messages = {
// AI Settings
'ai.agentSettings': 'Настройки агента',
'ai.chat.preparing': 'Подготовка…',
'ai.chat.modelCatalogWarning': 'Не удалось обновить список моделей. Показаны последние доступные или встроенные модели.',
'ai.chat.modelCatalogRetry': 'Повторить',
'ai.chat.contextCompacted': 'Контекст сжат',
'ai.title': 'AI',
'ai.description': 'Настройка AI-провайдеров, агентов и параметров безопасности',
@@ -282,6 +284,13 @@ export const ruAiMessages: Messages = {
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
'ai.externalMcp.title': 'Внешний MCP',
'ai.externalMcp.allowCommandOnHost': 'Всегда',
'ai.externalMcp.allowCommandOnHostHint': 'Всегда разрешать это действие на этом сервере.',
'ai.externalMcp.allowAll': 'Разрешить все действия',
'ai.externalMcp.allowSession': 'Это подключение',
'ai.externalMcp.allowSessionHint': 'Разрешать все действия клиента до отключения.',
'ai.externalMcp.allowHost': 'Этот сервер',
'ai.externalMcp.allowHostHint': 'Всегда разрешать действия на этом сервере.',
'ai.externalMcp.description': 'Откройте Netcatty как MCP-сервер для Codex, Claude Code, Cursor и Grok. Набор инструментов тот же, что у встроенных агентов. Держите Netcatty запущенным, пока клиенты подключены.',
'ai.externalMcp.sessionsExposed': 'Сессий в области: {count}',
'ai.externalMcp.mode': 'Режим доступности',
@@ -323,21 +332,24 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Другие',
'ai.externalMcp.cliCommand': 'CLI-команда',
'ai.externalMcp.configSnippet': 'Фрагмент конфига',
'ai.externalMcp.universalSetupPrompt': 'Универсальный запрос установки',
'ai.externalMcp.addToCodex': 'Добавить в Codex',
'ai.externalMcp.addToClaude': 'Добавить в Claude Code',
'ai.externalMcp.addToGrok': 'Добавить в Grok',
'ai.externalMcp.codexAdded': 'Запись MCP для Codex добавлена. Перезапустите Codex или откройте новую сессию.',
'ai.externalMcp.claudeAdded': 'Запись MCP для Claude Code добавлена. Перезапустите Claude Code или откройте новую сессию.',
'ai.externalMcp.grokAdded': 'Запись MCP для Grok добавлена. Перезапустите Grok или откройте новую сессию.',
'ai.externalMcp.codexAdded': 'Запись MCP для Codex и навык Netcatty добавлены. Перезапустите Codex или откройте новую сессию.',
'ai.externalMcp.claudeAdded': 'Запись MCP для Claude Code и навык Netcatty добавлены. Перезапустите Claude Code или откройте новую сессию.',
'ai.externalMcp.grokAdded': 'Запись MCP для Grok и навык Netcatty добавлены. Перезапустите Grok или откройте новую сессию.',
'ai.externalMcp.installCodex': 'Сначала установите Codex, затем нажмите Обновить.',
'ai.externalMcp.installClaude': 'Сначала установите Claude Code, затем нажмите Обновить.',
'ai.externalMcp.installGrok': 'Сначала установите Grok CLI, затем нажмите Обновить.',
'ai.externalMcp.conflict.description': 'Запись netcatty-external уже существует и указывает в другое место. Удалите или измените её вручную.',
'ai.externalMcp.enableForLauncher': 'Включите External MCP, чтобы получить путь launcher.',
'ai.externalMcp.cursor.title': 'Cursor / другие клиенты',
'ai.externalMcp.cursor.description': 'Объедините с MCP-конфигом (например ~/.cursor/mcp.json). Не заменяйте весь файл, если там уже есть другие серверы.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Добавьте этот фрагмент в конфигурацию MCP Cursor, сохранив существующие серверы.',
'ai.externalMcp.other.description': 'Скопируйте запрос установки в другой терминальный агент или добавьте фрагмент MCP в конфигурацию его клиента.',
'ai.externalMcp.status.unavailable': 'Недоступно',
'ai.externalMcp.status.disabled': 'Выключено',
'ai.externalMcp.status.running': 'Работает',
@@ -556,6 +568,11 @@ export const ruAiMessages: Messages = {
'terminal.layer.aiChat': 'AI-чат',
'terminal.layer.movePanelLeft': 'Переместить панель влево',
'terminal.layer.movePanelRight': 'Переместить панель вправо',
'terminal.layer.movePanelBottom': 'Переместить панель вниз',
'terminal.layer.choosePanelPosition': 'Изменить положение',
'terminal.layer.dockLeft': 'Слева',
'terminal.layer.dockRight': 'Справа',
'terminal.layer.dockBottom': 'Снизу',
'terminal.layer.closePanel': 'Закрыть панель',
'terminal.layer.closePane': 'Закрыть область',
'terminal.layer.resizeSplit': 'Изменить размер области',
+30 -7
View File
@@ -296,8 +296,11 @@ export const ruCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': 'Нажмите сочетание клавиш, чтобы задать глобальную горячую клавишу для показа или скрытия окна.',
'settings.globalHotkey.notSet': 'Не задано',
'settings.globalHotkey.reset': 'Сбросить по умолчанию',
'settings.globalHotkey.closeToTray': 'Сворачивать в системный трей',
'settings.globalHotkey.closeToTrayDesc': 'Если включено, при закрытии окно будет сворачиваться в системный трей вместо выхода из приложения.',
'settings.globalHotkey.closeToTray': 'Оставлять приложение в фоне при закрытии окна',
'settings.globalHotkey.closeToTrayDesc': 'При закрытии окно скрывается, а приложение продолжает работать. Отображение значка в трее настраивается отдельно.',
'settings.globalHotkey.showTrayIcon': 'Показывать значок в системном трее',
'settings.globalHotkey.showTrayIconDesc': 'Если отключено, значок в трее скрыт, но приложение продолжает работать в фоне.',
'settings.globalHotkey.showTrayIconHiddenHint': 'Значок в трее скрыт. Запустите приложение снова или используйте глобальную горячую клавишу, чтобы вернуть окно, затем снова включите этот параметр, чтобы восстановить значок.',
'settings.globalHotkey.enabled': 'Включить глобальную горячую клавишу',
'settings.globalHotkey.enabledDesc': 'Регистрировать системные сочетания клавиш. Когда отключено, все глобальные горячие клавиши снимаются с регистрации.',
'settings.globalHotkey.hint': 'Глобальная горячая клавиша работает на уровне всей системы и позволяет быстро показывать или скрывать окно (терминал в стиле Quake).',
@@ -343,9 +346,6 @@ export const ruCoreMessages: Messages = {
'settings.vault.selectBeforeConnectDesc': 'Один клик выбирает хост (акцентная рамка в сетке), повторный клик подключает. Группы работают так же. По умолчанию — подключение одним кликом.',
'settings.vault.showOnlyUngroupedHostsInRoot': 'Показывать в корне только хосты без группы',
'settings.vault.showOnlyUngroupedHostsInRootDesc': 'Если включено, в корневом списке хостов будут показаны только хосты без группы. Откройте группу на боковой панели, чтобы увидеть сгруппированные хосты.',
'settings.appearance.tabBarPosition': 'Расположение панели вкладок',
'settings.appearance.tabBarPosition.top': 'Сверху',
'settings.appearance.tabBarPosition.bottom': 'Снизу',
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
@@ -510,7 +510,7 @@ export const ruCoreMessages: Messages = {
'settings.appearance.windowOpacity': 'Прозрачность окна',
'settings.appearance.windowOpacity.desc': 'Настройте прозрачность всего окна приложения. При низких значениях текст терминала тоже бледнеет. В некоторых средах Linux это может не поддерживаться.',
'settings.appearance.appIcon': 'Значок приложения',
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. Применяется во время работы; значок установленного пакета не меняется.',
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. В Windows значок области уведомлений использует тот же стиль. Применяется во время работы; значок установленного пакета не меняется.',
'settings.appearance.appIcon.original': 'Оригинал',
'settings.appearance.appIcon.bright': 'Яркий',
'settings.appearance.appIcon.dark': 'Тёмный',
@@ -585,6 +585,8 @@ export const ruCoreMessages: Messages = {
'settings.terminal.font.weightBold.desc': 'Толщина жирного текста (100-900)',
'settings.terminal.font.smoothing': 'Сглаживание шрифта',
'settings.terminal.font.smoothing.desc': 'Использовать родное сглаживание шрифтов macOS',
'settings.terminal.font.ligatures': 'Лигатуры шрифта',
'settings.terminal.font.ligatures.desc': 'Показывать лигатуры вроде !=, если шрифт терминала их содержит',
'settings.terminal.font.linePadding': 'Межстрочный отступ',
'settings.terminal.font.linePadding.desc': 'Дополнительное пространство между строками (0-10)',
'settings.terminal.font.emulationType': 'Тип эмуляции терминала',
@@ -592,6 +594,8 @@ export const ruCoreMessages: Messages = {
'settings.terminal.cursor.style.block': 'Блок',
'settings.terminal.cursor.style.bar': 'Полоса',
'settings.terminal.cursor.style.underline': 'Подчёркивание',
'settings.terminal.cursor.barWidth': 'Толщина курсора-полосы',
'settings.terminal.cursor.barWidth.desc': 'Ширина курсоров-полос, используемых приложениями вроде vi (1-4 пикс.)',
'settings.terminal.cursor.blink': 'Мигание курсора',
'settings.terminal.cursor.highlightLine': 'Подсветка текущей строки',
'settings.terminal.cursor.highlightLine.desc':
@@ -648,12 +652,21 @@ export const ruCoreMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': 'Авто-загрузка изображений буфера обмена при вставке',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'Когда в буфере обмена есть изображение, вставка в удалённой сессии загружает его по SFTP в каталог .netcatty-paste-images/ в текущем удалённом каталоге и вводит удалённый путь вместо вставки текста.',
'settings.terminal.behavior.confirmMultilinePaste': 'Спрашивать перед вставкой нескольких строк',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Перед вставкой нескольких строк показывать диалог подтверждения с количеством строк и символов, редактируемым предпросмотром и действиями «Отправить» / «Отправить построчно» / «Отмена». Защищает CLI сетевых устройств (Cisco IOS, Huawei VRP, H3C Comware), не поддерживающих bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Порог подтверждения (строк)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Запрашивать подтверждение, если вставка содержит не меньше этого числа строк.',
'settings.terminal.behavior.shiftEnterNewline': 'Текст для Shift+Enter',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Отправлять настроенный текст вместо обычного Enter при нажатии Shift+Enter в терминале.',
'settings.terminal.behavior.shiftEnterNewlineText': 'Отправляемый текст',
'settings.terminal.behavior.shiftEnterNewlineText.desc':
'Используйте \\n для перевода строки, \\t для табуляции и \\\\ для обратной косой черты.',
'Используйте \\n для перевода строки, \\t для табуляции, \\e для Escape и \\\\ для обратной косой черты.',
'settings.terminal.behavior.shiftEnterForceText': 'Отправлять текст и в режиме ввода Win32',
'settings.terminal.behavior.shiftEnterForceText.desc':
'Отправлять указанный выше текст даже когда локальная сессия Windows ConPTY согласует режим ввода Win32. Нужно для CLI на Node/Bun (Claude Code, CodeBuddy), которые не читают модификаторы из записей ввода консоли.',
'settings.terminal.behavior.clearWipesScrollback': '`clear` очищает буфер прокрутки',
'settings.terminal.behavior.clearWipesScrollback.desc':
'Команда `clear` также будет очищать буфер прокрутки (поведение POSIX по умолчанию). Отключите, чтобы история оставалась видимой после `clear`.',
@@ -750,6 +763,12 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShell.startDir.placeholder': 'Домашний каталог',
'settings.terminal.localShell.startDir.notFound': 'Каталог не найден',
'settings.terminal.localShell.startDir.isFile': 'Путь указывает на файл, а не на каталог',
'settings.terminal.section.localShellSidePanel': 'Боковая панель локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen': 'Развернуть боковую панель при открытии локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Боковая панель по умолчанию',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.localShellSidePanel.pane.files': 'Файлы',
'settings.terminal.section.connection': 'Подключение',
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
'settings.terminal.connection.keepaliveInterval.desc': 'Как часто (в секундах) отправлять keepalive-пакеты на уровне SSH. Установите 0, чтобы отключить глобально. Учтите, что отдельные хосты могут переопределять это значение в своих настройках.',
@@ -1030,6 +1049,10 @@ export const ruCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': 'Удалить группу',
'vault.groups.deleteDialog.desc': 'Группа будет безвозвратно удалена, а все хосты будут перемещены в корень.',
'vault.groups.deleteDialog.managedDesc': 'Это управляемая группа SSH-конфига. При её удалении также будут удалены все хосты и снята связь с исходным файлом.',
'vault.groups.deleteDialog.mixedDesc': 'Эта группа содержит хосты, импортированные из связанного SSH-конфига. Все хосты под управляемой подгруппой будут удалены, включая хосты, не управляемые этим файлом. Остальные хосты будут перемещены в корень, если вы также не удалите их ниже.',
'vault.groups.deleteDialog.managedWarning': 'При удалении этой группы её записи также будут удалены из связанного файла конфигурации SSH. Записи, импортированные из этого файла, могут быть утеряны, это затронет и другие приложения, использующие файл. Сделайте резервную копию файла перед продолжением.',
'vault.groups.deleteDialog.sourcesChanged': 'Управляемые файлы, затрагиваемые этим удалением, изменились. Проверьте файлы и подтвердите удаление снова.',
'vault.groups.deleteDialog.managedFile': 'Связанный файл: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Также удалить все хосты в этой группе',
'vault.groups.deleteDialog.bulkTitle': 'Удалить выбранные группы',
'vault.groups.deleteDialog.bulkDesc': 'Выбранные группы будут безвозвратно удалены, а их хосты перемещены в корень.',
+3
View File
@@ -27,6 +27,9 @@ export const ruScriptsMessages = {
'scripts.actions.runParallel': 'Запустить на всех вкладках (параллельно)',
'scripts.actions.runSequential': 'Запустить на всех вкладках (последовательно)',
'scripts.actions.runOnAllTabs': 'Запустить на всех вкладках',
'scripts.actions.copyCommand': 'Копировать команду',
'scripts.actions.copyCommand.copied': 'Команда скопирована',
'scripts.actions.copyCommand.failed': 'Не удалось скопировать команду',
'scripts.actions.skippedConnectingSessions': 'Пропущено вкладок, которые ещё подключаются: {count}',
'scripts.actions.skippedSensitiveSessions': 'Пропущено вкладок с паролем/чувствительным вводом: {count}',
'scripts.actions.noRunnableHosts': 'Нет доступных для подключения хостов, соответствующих целям этого скрипта',
@@ -31,6 +31,7 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
'systemManager.errors.sshChannelUnavailable': 'Сервер отказался открыть новый канал выполнения. Повторите попытку позже или переподключите этот хост.',
'systemManager.unsupportedRemote': 'Этот хост не разрешает дополнительные SSH exec-каналы, поэтому системная панель недоступна. Открытие панели больше не разрывает терминал.',
'systemManager.overview.empty': 'Данных обзора пока нет.',
'systemManager.overview.loading': 'Загрузка обзора системы…',
+15
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const ruTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Сохранить текущий экран',
'terminal.saveScreen.failed': 'Не удалось сохранить экран терминала.',
// Диалог подтверждения многострочной вставки (#3398)
'terminal.pasteConfirm.title': 'Вставить несколько строк?',
'terminal.pasteConfirm.summary': 'В сессию будет отправлено строк: {lines} (символов: {chars}).',
'terminal.pasteConfirm.preview': 'Предпросмотр (можно изменить)',
'terminal.pasteConfirm.send': 'Отправить',
'terminal.pasteConfirm.sendLineByLine': 'Отправить построчно',
'terminal.pasteConfirm.cancel': 'Отмена',
'terminal.sudoHint.pressEnter': 'Нажмите Enter, чтобы вставить сохранённый пароль',
'terminal.passwordPicker.title': 'Сохранённые пароли',
'terminal.passwordPicker.empty': 'Нет сохранённых паролей',
@@ -75,6 +82,7 @@ export const ruTerminalMessages: Messages = {
'terminal.composeBar.send': 'Отправить',
'terminal.composeBar.close': 'Закрыть строку ввода',
'terminal.composeBar.broadcasting': 'Трансляция во все сессии',
'terminal.composeBar.broadcastAllowPassword': 'Транслировать без защиты пароля',
'terminal.composeBar.resize': 'Изменить высоту строки ввода',
'terminal.composeBar.manageSnippets': 'Управление быстрыми сниппетами',
'terminal.composeBar.searchSnippets': 'Поиск сниппетов...',
@@ -114,6 +122,7 @@ export const ruTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Переподключить эту сессию',
'terminal.serverStats.cpu': 'Использование CPU',
'terminal.serverStats.cpuCores': 'Использование ядер CPU',
'terminal.serverStats.gpu': 'Использование GPU',
'terminal.serverStats.memory': 'Использование памяти',
'terminal.serverStats.memoryDetails': 'Сведения о памяти',
'terminal.serverStats.memUsed': 'Использовано',
@@ -147,6 +156,7 @@ export const ruTerminalMessages: Messages = {
'terminal.search.noResults': 'Ничего не найдено',
'terminal.search.prevMatch': 'Предыдущее совпадение (Shift+Enter)',
'terminal.search.nextMatch': 'Следующее совпадение (Enter)',
'terminal.menu.cut': 'Вырезать',
'terminal.menu.copy': 'Копировать',
'terminal.menu.paste': 'Вставить',
'terminal.menu.uploadClipboardImage': 'Загрузить изображение из буфера',
@@ -201,6 +211,7 @@ export const ruTerminalMessages: Messages = {
'terminal.auth.retryMessage': 'Ошибка аутентификации. Проверьте учётные данные и повторите попытку.',
'terminal.auth.retryLog': 'Ошибка аутентификации. Повторите попытку.',
'terminal.auth.noKeysHint': 'Нет доступных ключей. Добавьте ключи в связке ключей.',
'terminal.auth.selectIdentity': 'Использовать сохранённый профиль',
'terminal.auth.continueSave': 'Продолжить и сохранить',
'terminal.auth.credentialsUnavailable': 'Сохранённые учётные данные не могут быть расшифрованы на этом устройстве. Пожалуйста, введите и сохраните их заново.',
'terminal.auth.jumpCredentialsUnavailable': 'У jump-хоста сохранены учётные данные, которые нельзя расшифровать на этом устройстве. Откройте настройки хоста и введите их заново.',
@@ -834,6 +845,10 @@ export const ruTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'например, Arduino Uno',
'serial.connectAndSave': 'Подключить и сохранить',
'serial.edit.title': 'Настройки последовательного порта',
'serial.field.username': 'Имя пользователя',
'serial.field.password': 'Пароль',
'serial.field.autoLoginDesc': 'Если задано, запросы Login/Password в последовательной консоли автоматически заполняются этими сохранёнными учётными данными.',
'serial.field.clearPassword': 'Очистить сохранённый пароль',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Требуется аутентификация',
+1
View File
@@ -108,6 +108,7 @@ export const ruVaultMessages: Messages = {
'vault.hosts.export.toast.success': 'Экспортировано {count} хостов в CSV',
'vault.hosts.export.toast.successWithSkipped': 'Экспортировано {count} хостов в CSV ({skipped} неподдерживаемых хостов пропущено)',
'vault.hosts.export.toast.passphrasesSkipped': 'Не удалось прочитать {count} сохранённых парольных фраз ключей; они оставлены пустыми',
'vault.hosts.export.toast.proxyCredentialsSkipped': 'Не удалось прочитать {count} сохранённых паролей прокси; они оставлены пустыми',
'vault.hosts.export.toast.noHosts': 'Нет хостов для экспорта',
'vault.hosts.allHosts': 'Все хосты',
'vault.hosts.pinned': 'Закреплённые',
@@ -7,9 +7,11 @@ import { HOST_ICON_COLORS, HOST_ICON_IDS } from "../../../domain/hostIcon.ts";
import zhCN from "./zh-CN.ts";
import ru from "./ru.ts";
import es from "./es.ts";
import zhTW from "./zh-TW.ts";
const LOCALIZED_SETTINGS_LOCALES = [
{ name: "zh-CN", messages: zhCN },
{ name: "zh-TW", messages: zhTW },
{ name: "ru", messages: ru },
{ name: "es", messages: es },
];
@@ -83,6 +85,21 @@ test("localized settings include OSC desktop notification labels", () => {
}
});
test("localized settings include bar cursor width labels", () => {
const keys = [
"settings.terminal.cursor.barWidth",
"settings.terminal.cursor.barWidth.desc",
];
for (const locale of [
{ name: "en", messages: en },
...LOCALIZED_SETTINGS_LOCALES,
]) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing bar cursor width labels`);
}
});
test("localized settings include terminal font weight option labels", () => {
const keys = [
"settings.terminal.font.weight.thin",
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import en from './en.ts';
import ru from './ru.ts';
import es from './es.ts';
import zhCN from './zh-CN.ts';
import zhTW from './zh-TW.ts';
const KEYS = [
'vault.groups.deleteDialog.managedDesc',
'vault.groups.deleteDialog.mixedDesc',
'vault.groups.deleteDialog.managedWarning',
'vault.groups.deleteDialog.managedFile',
] as const;
test('managed group delete warning copy exists in every locale', () => {
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const missing = KEYS.filter((key) => !messages[key]);
assert.deepEqual(missing, [], `${locale} is missing managed group delete copy`);
}
});
test('managed group delete warning mentions data loss in every locale', () => {
const MARKERS = ['备份', '備份', 'copia de seguridad', 'резервную копию', 'Back up'];
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const text = messages['vault.groups.deleteDialog.managedWarning'];
assert.match(
text ?? '',
/SSH/,
`${locale} warning should reference the SSH config file`,
);
assert.ok(
MARKERS.some((marker) => text?.includes(marker)),
`${locale} warning should tell the user to back up the file`,
);
}
});
test('linked file line interpolates the file path', () => {
for (const messages of [en, ru, es, zhCN, zhTW]) {
assert.match(
messages['vault.groups.deleteDialog.managedFile'] ?? '',
/\{file\}/,
'managedFile copy should include the {file} placeholder',
);
}
});
+37 -5
View File
@@ -4,6 +4,8 @@ export const zhCNAiMessages: Messages = {
// AI Settings
'ai.agentSettings': 'Agent 设置',
'ai.chat.preparing': '准备中…',
'ai.chat.modelCatalogWarning': '暂时无法更新实时模型列表,当前显示上次可用或内置的模型。',
'ai.chat.modelCatalogRetry': '重试',
'ai.chat.compactingContext': '正在压缩较早的上下文…',
'ai.chat.compactingStep': '正在为下一步整理上下文…',
'ai.chat.compactionRetry': '请求过大,正在压缩上下文并重试…',
@@ -287,6 +289,18 @@ export const zhCNAiMessages: Messages = {
'ai.opencode.check': '检查',
'ai.opencode.resetPath': '重置',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安装后在它自己的配置里配置 provider 和密钥,检测到后即可作为外部编程 Agent 使用。',
'ai.mimo.detecting': '检测中...',
'ai.mimo.detected': '已检测到',
'ai.mimo.notFound': '未找到',
'ai.mimo.path': '路径:',
'ai.mimo.notFoundHint': '在 PATH 中未找到 mimo。请安装或在下方指定可执行文件路径。',
'ai.mimo.customPathPlaceholder': '例如 /usr/local/bin/mimo',
'ai.mimo.check': '检查',
'ai.mimo.resetPath': '重置',
// AI Grok Build(应用内托管 Agent,与 External MCP「添加到 Grok」不同)
'ai.grok.title': 'Grok Build',
'ai.grok.description': 'xAI 的 Grok Build 编程 Agent CLI。安装 Grok CLI,使用 `grok login` 登录或设置 XAI_API_KEY 后,即可作为外部 Agent 选择。',
@@ -323,6 +337,13 @@ export const zhCNAiMessages: Messages = {
// External MCP
'ai.externalMcp.title': '对外 MCP',
'ai.externalMcp.allowCommandOnHost': '始终',
'ai.externalMcp.allowCommandOnHostHint': '始终允许在此服务器执行同类操作。',
'ai.externalMcp.allowAll': '允许所有操作',
'ai.externalMcp.allowSession': '此次连接',
'ai.externalMcp.allowSessionHint': '在客户端断开前,允许此次连接的所有操作。',
'ai.externalMcp.allowHost': '此服务器',
'ai.externalMcp.allowHostHint': '始终允许操作此服务器。',
'ai.externalMcp.description': '把 Netcatty 作为 MCP 服务器暴露给 Codex、Claude Code、Cursor、Grok 等外部客户端。工具面与应用内 Agent 相同(终端、SFTP、Vault、端口转发)。客户端连接期间请保持 Netcatty 运行。',
'ai.externalMcp.sessionsExposed': '作用域内会话:{count}',
'ai.externalMcp.mode': '可用模式',
@@ -364,21 +385,24 @@ export const zhCNAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': '其他',
'ai.externalMcp.cliCommand': 'CLI 命令',
'ai.externalMcp.configSnippet': '配置片段',
'ai.externalMcp.universalSetupPrompt': '通用安装提示词',
'ai.externalMcp.addToCodex': '添加到 Codex',
'ai.externalMcp.addToClaude': '添加到 Claude Code',
'ai.externalMcp.addToGrok': '添加到 Grok',
'ai.externalMcp.codexAdded': '已添加 Codex MCP 条目。请重启 Codex 或打开新会话。',
'ai.externalMcp.claudeAdded': '已添加 Claude Code MCP 条目。请重启 Claude Code 或打开新会话。',
'ai.externalMcp.grokAdded': '已添加 Grok MCP 条目。请重启 Grok 或打开新会话。',
'ai.externalMcp.codexAdded': '已添加 Codex MCP 条目和 Netcatty Skill。请重启 Codex 或打开新会话。',
'ai.externalMcp.claudeAdded': '已添加 Claude Code MCP 条目和 Netcatty Skill。请重启 Claude Code 或打开新会话。',
'ai.externalMcp.grokAdded': '已添加 Grok MCP 条目和 Netcatty Skill。请重启 Grok 或打开新会话。',
'ai.externalMcp.installCodex': '请先单独安装 Codex,然后点击刷新。',
'ai.externalMcp.installClaude': '请先单独安装 Claude Code,然后点击刷新。',
'ai.externalMcp.installGrok': '请先单独安装 Grok CLI,然后点击刷新。',
'ai.externalMcp.conflict.description': '已存在指向其他位置的 netcatty-external 条目,请手动删除或修改。',
'ai.externalMcp.enableForLauncher': '请先启用对外 MCP,以获取可用的 launcher 路径。',
'ai.externalMcp.cursor.title': 'Cursor / 其他客户端',
'ai.externalMcp.cursor.description': '合并到 MCP 配置文件(例如 ~/.cursor/mcp.json)。若已有其他服务器,请勿整文件覆盖。',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': '将片段合并到 Cursor MCP 配置中,并保留已有服务器。',
'ai.externalMcp.other.description': '将安装提示词复制到其他终端 Agent,或把 MCP 片段合并到对应客户端配置。',
'ai.externalMcp.status.unavailable': '不可用',
'ai.externalMcp.status.disabled': '已关闭',
'ai.externalMcp.status.running': '运行中',
@@ -597,8 +621,16 @@ export const zhCNAiMessages: Messages = {
'terminal.layer.aiChat': 'AI 助手',
'terminal.layer.movePanelLeft': '面板移至左侧',
'terminal.layer.movePanelRight': '面板移至右侧',
'terminal.layer.movePanelBottom': '面板移至底部',
'terminal.layer.choosePanelPosition': '改变位置',
'terminal.layer.dockLeft': '左侧',
'terminal.layer.dockRight': '右侧',
'terminal.layer.dockBottom': '底部',
'terminal.layer.closePanel': '关闭面板',
'terminal.layer.closePane': '关闭分屏',
'terminal.layer.saveLayoutAsDefault': '将布局保存为默认',
'terminal.layer.layoutSavedAsDefault': '布局已保存为默认',
'terminal.layer.layoutSaveFailed': '布局保存失败',
'terminal.layer.resizeSplit': '调整分屏大小',
'terminal.layer.splitHorizontal': '上下分屏',
'terminal.layer.splitVertical': '左右分屏',
+17 -7
View File
@@ -120,6 +120,12 @@ export const zhCNCoreMessages: Messages = {
'settings.terminal.sidePanel.pane.system': '系统',
'settings.terminal.sidePanel.pane.notes': '笔记',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': '本地 Shell 侧边栏',
'settings.terminal.localShellSidePanel.autoOpen': '打开本地 Shell 时展开侧边栏',
'settings.terminal.localShellSidePanel.autoOpen.desc': '打开本地 Shell 后自动打开一个侧边栏。',
'settings.terminal.localShellSidePanel.autoOpenPane': '默认侧边栏',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': '选择优先打开哪个面板。',
'settings.terminal.localShellSidePanel.pane.files': '文件',
// Settings > System
'settings.system.title': '系统',
@@ -310,8 +316,11 @@ export const zhCNCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': '按下组合键以设置显示/隐藏窗口的全局快捷键。',
'settings.globalHotkey.notSet': '未设置',
'settings.globalHotkey.reset': '恢复默认',
'settings.globalHotkey.closeToTray': '关闭时最小化到托盘',
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口将最小化到系统托盘而不是退出程序。',
'settings.globalHotkey.closeToTray': '关闭窗口后在后台运行',
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口会隐藏窗口,应用继续在后台运行。托盘图标可单独开关。',
'settings.globalHotkey.showTrayIcon': '显示系统托盘图标',
'settings.globalHotkey.showTrayIconDesc': '关闭后,托盘图标将被隐藏,但应用仍会在后台正常运行。',
'settings.globalHotkey.showTrayIconHiddenHint': '托盘图标已隐藏。再次启动应用或使用全局显示/隐藏快捷键即可找回窗口,然后重新打开此设置即可恢复图标。',
'settings.globalHotkey.enabled': '启用全局快捷键',
'settings.globalHotkey.enabledDesc': '注册系统级键盘快捷键。禁用后将取消所有全局快捷键注册。',
'settings.globalHotkey.hint': '全局快捷键在系统范围内工作,可快速显示或隐藏窗口(下拉式终端风格)。',
@@ -357,9 +366,6 @@ export const zhCNCoreMessages: Messages = {
'settings.vault.selectBeforeConnectDesc': '单击选中主机(网格模式显示强调色边框),再次单击连接;分组同理。默认仍为单击直接连接。',
'settings.vault.showOnlyUngroupedHostsInRoot': '根目录只显示未分组主机',
'settings.vault.showOnlyUngroupedHostsInRootDesc': '开启后,主机库根目录的主机列表只显示没有分组的主机,已分组主机请从左侧分组进入查看。',
'settings.appearance.tabBarPosition': '标签栏位置',
'settings.appearance.tabBarPosition.top': '顶部',
'settings.appearance.tabBarPosition.bottom': '底部',
'settings.vault.showSftpTab': '显示 SFTP 标签页',
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
@@ -539,7 +545,7 @@ export const zhCNCoreMessages: Messages = {
'settings.appearance.windowOpacity': '窗口透明度',
'settings.appearance.windowOpacity.desc': '调节整个应用窗口的透明度,方便叠在其他内容上方。较低时终端文字也会变淡;部分 Linux 桌面环境可能不支持。',
'settings.appearance.appIcon': '应用图标',
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。运行时生效,安装包内的图标不会改变。',
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。Windows 通知区域图标会使用同一套风格。运行时生效,安装包内的图标不会改变。',
'settings.appearance.appIcon.original': '原始',
'settings.appearance.appIcon.bright': '明亮',
'settings.appearance.appIcon.dark': '深色',
@@ -678,6 +684,10 @@ export const zhCNCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '删除分组',
'vault.groups.deleteDialog.desc': '这将永久删除该分组并将所有主机移动到根级别。',
'vault.groups.deleteDialog.managedDesc': '这是一个托管的 SSH config 分组。删除后将同时删除所有主机并断开与源文件的连接。',
'vault.groups.deleteDialog.mixedDesc': '该分组包含从关联 SSH config 文件导入的主机。其托管子分组下的所有主机都将被删除,包括不受该文件管理的主机;其余主机将移动到根级别,除非您在下方选择同时删除。',
'vault.groups.deleteDialog.managedWarning': '删除该分组会同时清空关联 SSH config 文件中的对应条目,从该文件导入的配置可能会丢失,其他使用该文件的应用也会受到影响。请先备份文件再继续。',
'vault.groups.deleteDialog.sourcesChanged': '此次删除涉及的托管文件已发生变化。请检查文件并重新确认。',
'vault.groups.deleteDialog.managedFile': '关联文件:{file}',
'vault.groups.deleteDialog.deleteHosts': '同时删除该分组下的所有主机',
'vault.groups.deleteDialog.bulkTitle': '删除所选分组',
'vault.groups.deleteDialog.bulkDesc': '这将永久删除所选分组,并把其中的主机移动到根级别。',
@@ -736,6 +746,7 @@ export const zhCNCoreMessages: Messages = {
'vault.hosts.export.toast.success': '已导出 {count} 个主机到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已导出 {count} 个主机到 CSV(跳过 {skipped} 个不支持的主机)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 个已保存的密钥口令无法读取,导出时已留空',
'vault.hosts.export.toast.proxyCredentialsSkipped': '有 {count} 个已保存的代理密码无法读取,导出时已留空',
'vault.hosts.export.toast.noHosts': '没有主机可导出',
'vault.hosts.allHosts': '全部主机',
'vault.hosts.pinned': '已置顶',
@@ -1050,7 +1061,6 @@ export const zhCNCoreMessages: Messages = {
'sftp.goUp': '上一级',
'sftp.goToTerminalCwd': '定位到终端当前目录',
'sftp.locatePathInTerminal': '定位路径到终端',
'sftp.refreshAfterCommand': '终端命令完成后刷新',
'sftp.followTerminalCwd': '追随终端目录',
'sftp.followTerminalCwd.enable': '开启追随终端目录',
'sftp.followTerminalCwd.disable': '关闭追随终端目录',
@@ -27,6 +27,9 @@ export const zhCNScriptsMessages = {
'scripts.actions.runParallel': '在所有标签页并行运行',
'scripts.actions.runSequential': '在所有标签页顺序运行',
'scripts.actions.runOnAllTabs': '在所有标签页运行',
'scripts.actions.copyCommand': '复制命令',
'scripts.actions.copyCommand.copied': '命令已复制',
'scripts.actions.copyCommand.failed': '复制命令失败',
'scripts.actions.skippedConnectingSessions': '有 {count} 个标签仍在连接中,已跳过',
'scripts.actions.skippedSensitiveSessions': '有 {count} 个标签处于密码/敏感输入,已跳过',
'scripts.actions.noRunnableHosts': '没有与脚本目标匹配的可连接主机',
@@ -31,6 +31,7 @@ export const zhCnSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': '加载监听端口失败',
'systemManager.errors.loadServices': '加载 systemd 服务失败',
'systemManager.errors.sshChannelUnavailable': '服务器拒绝打开新的执行通道。请稍后重试,或重新连接当前主机。',
'systemManager.unsupportedRemote': '该主机不允许额外的 SSH 执行通道,系统面板不可用。打开此面板不会再断开当前终端。',
'systemManager.overview.empty': '暂无系统概览数据。',
'systemManager.overview.loading': '正在加载系统概览…',
+25 -1
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const zhCNTerminalMessages: Messages = {
'terminal.menu.saveScreen': '保存当前屏幕',
'terminal.saveScreen.failed': '保存终端屏幕失败。',
// 多行粘贴确认对话框(#3398)
'terminal.pasteConfirm.title': '要粘贴多行文本吗?',
'terminal.pasteConfirm.summary': '将向会话发送 {lines} 行({chars} 个字符)。',
'terminal.pasteConfirm.preview': '预览(可编辑)',
'terminal.pasteConfirm.send': '发送',
'terminal.pasteConfirm.sendLineByLine': '逐行发送',
'terminal.pasteConfirm.cancel': '取消',
'terminal.sudoHint.pressEnter': '按 Enter 粘贴已保存的密码',
'terminal.passwordPicker.title': '已保存的密码',
'terminal.passwordPicker.empty': '没有已保存的密码',
@@ -271,6 +278,8 @@ export const zhCNTerminalMessages: Messages = {
'settings.terminal.font.weightBold.desc': '粗体文本字重 (100-900)',
'settings.terminal.font.smoothing': '字体平滑',
'settings.terminal.font.smoothing.desc': '使用 macOS 原生字体抗锯齿',
'settings.terminal.font.ligatures': '字体连字',
'settings.terminal.font.ligatures.desc': '支持连字的字体把 != 这类字符显示成一个符号',
'settings.terminal.font.linePadding': '行间距',
'settings.terminal.font.linePadding.desc': '行之间的额外间距 (0-10)',
'settings.terminal.font.emulationType': '终端仿真类型',
@@ -278,6 +287,8 @@ export const zhCNTerminalMessages: Messages = {
'settings.terminal.cursor.style.block': '块',
'settings.terminal.cursor.style.bar': '竖线',
'settings.terminal.cursor.style.underline': '下划线',
'settings.terminal.cursor.barWidth': '竖线光标粗细',
'settings.terminal.cursor.barWidth.desc': 'vi 等应用使用竖线光标时的宽度(1-4 像素)',
'settings.terminal.cursor.blink': '光标闪烁',
'settings.terminal.cursor.highlightLine': '高亮当前行',
'settings.terminal.cursor.highlightLine.desc': '为光标所在行加上淡色背景,方便定位当前输入位置',
@@ -326,12 +337,21 @@ export const zhCNTerminalMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': '粘贴时自动上传剪贴板图片',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'当剪贴板包含图片时,在远程会话中粘贴会通过 SFTP 将图片上传到远端当前目录的 .netcatty-paste-images/ 文件夹,并在终端输入远端路径,而不是粘贴文本。',
'settings.terminal.behavior.confirmMultilinePaste': '粘贴多行前先询问',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'粘贴多行文本时先弹出确认对话框,显示行数和字符数、可编辑的预览,并提供发送 / 逐行发送 / 取消操作。可保护不支持括号粘贴的网络设备 CLI(Cisco IOS、华为 VRP、H3C Comware)。',
'settings.terminal.behavior.confirmMultilinePasteMinLines': '确认阈值(行数)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'粘贴内容达到该行数时才弹出确认对话框。',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter 发送文本',
'settings.terminal.behavior.shiftEnterNewline.desc':
'在终端中按 Shift+Enter 时发送配置的文本,而不是普通回车。',
'settings.terminal.behavior.shiftEnterNewlineText': '发送内容',
'settings.terminal.behavior.shiftEnterNewlineText.desc':
'使用 \\n 表示换行,\\t 表示 Tab,\\\\ 表示反斜杠。',
'使用 \\n 表示换行,\\t 表示 Tab,\\e 表示 ESC,\\\\ 表示反斜杠。',
'settings.terminal.behavior.shiftEnterForceText': '在 Win32 输入模式下也发送文本',
'settings.terminal.behavior.shiftEnterForceText.desc':
'本机 Windows ConPTY 会话协商 Win32 输入模式时,仍然发送上面的文本。Node/Bun 写的 CLI(Claude Code、CodeBuddy)读不到控制台输入记录里的修饰键,需要这个开关才能区分 Shift+Enter。',
'settings.terminal.behavior.clearWipesScrollback': '`clear` 同时清空回滚历史',
'settings.terminal.behavior.clearWipesScrollback.desc':
'`clear` 命令同时清空回滚历史(POSIX 默认行为)。关闭则保留历史。',
@@ -918,6 +938,10 @@ export const zhCNTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': '例如 Arduino Uno',
'serial.connectAndSave': '连接并保存',
'serial.edit.title': '串口设置',
'serial.field.username': '用户名',
'serial.field.password': '密码',
'serial.field.autoLoginDesc': '设置后,串口终端出现 Login/Password 登录提示时,会自动填充此处保存的用户名和密码。',
'serial.field.clearPassword': '清除已保存的密码',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': '需要验证',
+4
View File
@@ -466,6 +466,7 @@ export const zhCNVaultMessages: Messages = {
'terminal.composeBar.send': '发送',
'terminal.composeBar.close': '关闭撰写栏',
'terminal.composeBar.broadcasting': '正在广播到所有会话',
'terminal.composeBar.broadcastAllowPassword': '广播时不对密码进行保护',
'terminal.composeBar.resize': '拖拽调整撰写栏高度',
'terminal.composeBar.manageSnippets': '管理快捷代码片段',
'terminal.composeBar.searchSnippets': '搜索代码片段...',
@@ -503,6 +504,7 @@ export const zhCNVaultMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': '重新连接当前会话',
'terminal.serverStats.cpu': 'CPU 使用率',
'terminal.serverStats.cpuCores': 'CPU 核心使用率',
'terminal.serverStats.gpu': 'GPU 使用率',
'terminal.serverStats.memory': '内存使用',
'terminal.serverStats.memoryDetails': '内存详情',
'terminal.serverStats.memUsed': '已用',
@@ -536,6 +538,7 @@ export const zhCNVaultMessages: Messages = {
'terminal.search.noResults': '无结果',
'terminal.search.prevMatch': '上一个匹配 (Shift+Enter)',
'terminal.search.nextMatch': '下一个匹配 (Enter)',
'terminal.menu.cut': '剪切',
'terminal.menu.copy': '复制',
'terminal.menu.paste': '粘贴',
'terminal.menu.addSelectionToAI': '添加到对话',
@@ -578,6 +581,7 @@ export const zhCNVaultMessages: Messages = {
'terminal.auth.retryMessage': '身份验证失败。请检查凭据后重试。',
'terminal.auth.retryLog': '身份验证失败,请重试。',
'terminal.auth.noKeysHint': '暂无密钥,请先在钥匙串中添加。',
'terminal.auth.selectIdentity': '使用已保存的身份',
'terminal.auth.continueSave': '继续并保存',
'terminal.auth.credentialsUnavailable': '当前设备无法解密已保存凭据,请重新输入并再次保存。',
'terminal.auth.jumpCredentialsUnavailable': '某个跳板机的已保存凭据无法在当前设备解密,请到主机设置中重新填写。',
+37 -5
View File
@@ -4,6 +4,8 @@ export const zhTWAiMessages: Messages = {
// AI Settings
'ai.agentSettings': 'Agent 設定',
'ai.chat.preparing': '準備中…',
'ai.chat.modelCatalogWarning': '暫時無法更新即時模型清單,目前顯示上次可用或內建的模型。',
'ai.chat.modelCatalogRetry': '重試',
'ai.chat.compactingContext': '正在壓縮較早的上下文…',
'ai.chat.compactingStep': '正在為下一步整理上下文…',
'ai.chat.compactionRetry': '請求過大,正在壓縮上下文並重試…',
@@ -278,6 +280,18 @@ export const zhTWAiMessages: Messages = {
'ai.opencode.check': '檢查',
'ai.opencode.resetPath': '重設',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安裝後在它自己的設定裡設定 provider 和金鑰,偵測到後即可作為外部程式設計 Agent 使用。',
'ai.mimo.detecting': '偵測中...',
'ai.mimo.detected': '已偵測到',
'ai.mimo.notFound': '未找到',
'ai.mimo.path': '路徑:',
'ai.mimo.notFoundHint': '在 PATH 中未找到 mimo。請安裝或在下方指定執行檔路徑。',
'ai.mimo.customPathPlaceholder': '例如 /usr/local/bin/mimo',
'ai.mimo.check': '檢查',
'ai.mimo.resetPath': '重設',
// AI Grok Build(應用內託管 Agent,與 External MCP「新增到 Grok」不同)
'ai.grok.title': 'Grok Build',
'ai.grok.description': 'xAI 的 Grok Build 程式設計 Agent CLI。安裝 Grok CLI,使用 `grok login` 登入或設定 XAI_API_KEY 後,即可作為外部 Agent 選擇。',
@@ -313,6 +327,13 @@ export const zhTWAiMessages: Messages = {
'ai.toolAccess.skills.unavailable': '暫時無法取得 Skill 檔案路徑',
'ai.externalMcp.title': '對外 MCP',
'ai.externalMcp.allowCommandOnHost': '始終',
'ai.externalMcp.allowCommandOnHostHint': '始終允許在此伺服器執行同類操作。',
'ai.externalMcp.allowAll': '允許所有操作',
'ai.externalMcp.allowSession': '此次連線',
'ai.externalMcp.allowSessionHint': '在用戶端中斷前,允許此次連線的所有操作。',
'ai.externalMcp.allowHost': '此伺服器',
'ai.externalMcp.allowHostHint': '始終允許操作此伺服器。',
'ai.externalMcp.description': '將 Netcatty 作為 MCP 伺服器暴露給 Codex、Claude Code、Cursor、Grok 等外部用戶端。工具面與應用內 Agent 相同。用戶端連線期間請保持 Netcatty 執行。',
'ai.externalMcp.sessionsExposed': '作用域內工作階段:{count}',
'ai.externalMcp.mode': '可用模式',
@@ -354,21 +375,24 @@ export const zhTWAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': '其他',
'ai.externalMcp.cliCommand': 'CLI 命令',
'ai.externalMcp.configSnippet': '設定片段',
'ai.externalMcp.universalSetupPrompt': '通用安裝提示詞',
'ai.externalMcp.addToCodex': '新增到 Codex',
'ai.externalMcp.addToClaude': '新增到 Claude Code',
'ai.externalMcp.addToGrok': '新增到 Grok',
'ai.externalMcp.codexAdded': '已新增 Codex MCP 項目。請重新啟動 Codex 或開啟新工作階段。',
'ai.externalMcp.claudeAdded': '已新增 Claude Code MCP 項目。請重新啟動 Claude Code 或開啟新工作階段。',
'ai.externalMcp.grokAdded': '已新增 Grok MCP 項目。請重新啟動 Grok 或開啟新工作階段。',
'ai.externalMcp.codexAdded': '已新增 Codex MCP 項目和 Netcatty Skill。請重新啟動 Codex 或開啟新工作階段。',
'ai.externalMcp.claudeAdded': '已新增 Claude Code MCP 項目和 Netcatty Skill。請重新啟動 Claude Code 或開啟新工作階段。',
'ai.externalMcp.grokAdded': '已新增 Grok MCP 項目和 Netcatty Skill。請重新啟動 Grok 或開啟新工作階段。',
'ai.externalMcp.installCodex': '請先另外安裝 Codex,然後按重新整理。',
'ai.externalMcp.installClaude': '請先另外安裝 Claude Code,然後按重新整理。',
'ai.externalMcp.installGrok': '請先另外安裝 Grok CLI,然後按重新整理。',
'ai.externalMcp.conflict.description': '已存在指向其他位置的 netcatty-external 項目,請手動刪除或修改。',
'ai.externalMcp.enableForLauncher': '請先啟用對外 MCP,以取得可用的 launcher 路徑。',
'ai.externalMcp.cursor.title': 'Cursor / 其他用戶端',
'ai.externalMcp.cursor.description': '合併到 MCP 設定檔(例如 ~/.cursor/mcp.json)。若已有其他伺服器,請勿整檔覆蓋。',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': '將片段合併到 Cursor MCP 設定中,並保留已有伺服器。',
'ai.externalMcp.other.description': '將安裝提示詞複製到其他終端 Agent,或把 MCP 片段合併到對應用戶端設定。',
'ai.externalMcp.status.unavailable': '無法使用',
'ai.externalMcp.status.disabled': '已關閉',
'ai.externalMcp.status.running': '執行中',
@@ -587,8 +611,16 @@ export const zhTWAiMessages: Messages = {
'terminal.layer.aiChat': 'AI 助手',
'terminal.layer.movePanelLeft': '面板移至左側',
'terminal.layer.movePanelRight': '面板移至右側',
'terminal.layer.movePanelBottom': '面板移至底部',
'terminal.layer.choosePanelPosition': '變更位置',
'terminal.layer.dockLeft': '左側',
'terminal.layer.dockRight': '右側',
'terminal.layer.dockBottom': '底部',
'terminal.layer.closePanel': '關閉面板',
'terminal.layer.closePane': '關閉分割',
'terminal.layer.saveLayoutAsDefault': '將佈局儲存為預設',
'terminal.layer.layoutSavedAsDefault': '佈局已儲存為預設',
'terminal.layer.layoutSaveFailed': '佈局儲存失敗',
'terminal.layer.resizeSplit': '調整分割大小',
'terminal.layer.splitHorizontal': '上下分割',
'terminal.layer.splitVertical': '左右分割',
+17 -7
View File
@@ -122,6 +122,12 @@ export const zhTWCoreMessages: Messages = {
'settings.terminal.sidePanel.pane.system': '系統',
'settings.terminal.sidePanel.pane.notes': '筆記',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': '本機 Shell 側邊欄',
'settings.terminal.localShellSidePanel.autoOpen': '開啟本機 Shell 時展開側邊欄',
'settings.terminal.localShellSidePanel.autoOpen.desc': '開啟本機 Shell 後自動開啟一個側邊欄。',
'settings.terminal.localShellSidePanel.autoOpenPane': '預設側邊欄',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': '選擇優先開啟哪個面板。',
'settings.terminal.localShellSidePanel.pane.files': '檔案',
// Settings > System
'settings.system.title': '系統',
@@ -312,8 +318,11 @@ export const zhTWCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': '按下組合鍵以設定顯示/隱藏視窗的全域快速鍵。',
'settings.globalHotkey.notSet': '未設定',
'settings.globalHotkey.reset': '恢復預設',
'settings.globalHotkey.closeToTray': '關閉時最小化到系統匣',
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗將最小化到系統匣而不是結束程式。',
'settings.globalHotkey.closeToTray': '關閉視窗後在背景執行',
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗會隱藏視窗,應用程式繼續在背景執行。系統匣圖示可另外開關。',
'settings.globalHotkey.showTrayIcon': '顯示系統匣圖示',
'settings.globalHotkey.showTrayIconDesc': '關閉後,系統匣圖示將被隱藏,但應用程式仍會在背景正常執行。',
'settings.globalHotkey.showTrayIconHiddenHint': '系統匣圖示已隱藏。再次啟動應用程式或使用全域顯示/隱藏快捷鍵即可找回視窗,然後重新開啟此設定即可恢復圖示。',
'settings.globalHotkey.enabled': '啟用全域快速鍵',
'settings.globalHotkey.enabledDesc': '註冊系統級鍵盤快速鍵。停用後將取消所有全域快速鍵註冊。',
'settings.globalHotkey.hint': '全域快速鍵在系統範圍內工作,可快速顯示或隱藏視窗(下拉式終端風格)。',
@@ -359,9 +368,6 @@ export const zhTWCoreMessages: Messages = {
'settings.vault.selectBeforeConnectDesc': '點一下選取主機(網格模式會顯示強調色邊框),再點一下才連線;群組同理。預設仍是點一下直接連線。',
'settings.vault.showOnlyUngroupedHostsInRoot': '根目錄只顯示未歸類主機',
'settings.vault.showOnlyUngroupedHostsInRootDesc': '開啟後,主機庫根目錄的主機列表只顯示沒有群組的主機,已歸類的主機請從左側群組進入檢視。',
'settings.appearance.tabBarPosition': '分頁列位置',
'settings.appearance.tabBarPosition.top': '頂部',
'settings.appearance.tabBarPosition.bottom': '底部',
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
@@ -541,7 +547,7 @@ export const zhTWCoreMessages: Messages = {
'settings.appearance.windowOpacity': '視窗透明度',
'settings.appearance.windowOpacity.desc': '調節整個應用程式視窗的透明度,方便疊在其他內容上方。較低時終端文字也會變淡;部分 Linux 桌面環境可能不支援。',
'settings.appearance.appIcon': '應用程式圖示',
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。執行時生效,安裝檔內的圖示不會改變。',
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。Windows 通知區域圖示會使用同一套風格。執行時生效,安裝檔內的圖示不會改變。',
'settings.appearance.appIcon.original': '原始',
'settings.appearance.appIcon.bright': '明亮',
'settings.appearance.appIcon.dark': '深色',
@@ -680,6 +686,10 @@ export const zhTWCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '刪除群組',
'vault.groups.deleteDialog.desc': '這將永久刪除該群組並將所有主機移動到根層級。',
'vault.groups.deleteDialog.managedDesc': '這是一個託管的 SSH config 群組。刪除後將同時刪除所有主機並斷開與原始檔的連線。',
'vault.groups.deleteDialog.mixedDesc': '該群組包含從關聯 SSH config 檔案匯入的主機。其受管理子群組下的所有主機都將被刪除,包括不受該檔案管理的主機;其餘主機將移動到根層級,除非您在下方選擇同時刪除。',
'vault.groups.deleteDialog.managedWarning': '刪除該群組會同時清空關聯 SSH config 檔案中的對應條目,從該檔案匯入的設定可能會遺失,其他使用該檔案的應用也會受到影響。請先備份檔案再繼續。',
'vault.groups.deleteDialog.sourcesChanged': '此次刪除涉及的受管理檔案已發生變化。請檢查檔案並重新確認。',
'vault.groups.deleteDialog.managedFile': '關聯檔案:{file}',
'vault.groups.deleteDialog.deleteHosts': '同時刪除該群組下的所有主機',
'vault.groups.deleteDialog.bulkTitle': '刪除所選群組',
'vault.groups.deleteDialog.bulkDesc': '這將永久刪除所選群組,並把其中的主機移動到根層級。',
@@ -738,6 +748,7 @@ export const zhTWCoreMessages: Messages = {
'vault.hosts.export.toast.success': '已匯出 {count} 個主機到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已匯出 {count} 個主機到 CSV(跳過 {skipped} 個不支援的主機)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 個已儲存的金鑰密碼無法讀取,匯出時已留空',
'vault.hosts.export.toast.proxyCredentialsSkipped': '有 {count} 個已儲存的代理密碼無法讀取,匯出時已留空',
'vault.hosts.export.toast.noHosts': '沒有主機可匯出',
'vault.hosts.allHosts': '全部主機',
'vault.hosts.pinned': '已置頂',
@@ -1052,7 +1063,6 @@ export const zhTWCoreMessages: Messages = {
'sftp.goUp': '上一級',
'sftp.goToTerminalCwd': '定位到終端目前目錄',
'sftp.locatePathInTerminal': '定位路徑到終端',
'sftp.refreshAfterCommand': '終端命令完成後重新整理',
'sftp.followTerminalCwd': '追隨終端目錄',
'sftp.followTerminalCwd.enable': '開啟追隨終端目錄',
'sftp.followTerminalCwd.disable': '關閉追隨終端目錄',
@@ -27,6 +27,9 @@ export const zhTWScriptsMessages = {
'scripts.actions.runParallel': '在所有分頁並行執行',
'scripts.actions.runSequential': '在所有分頁依序執行',
'scripts.actions.runOnAllTabs': '在所有分頁執行',
'scripts.actions.copyCommand': '複製指令',
'scripts.actions.copyCommand.copied': '指令已複製',
'scripts.actions.copyCommand.failed': '複製指令失敗',
'scripts.actions.skippedConnectingSessions': '有 {count} 個分頁仍在連線中,已跳過',
'scripts.actions.skippedSensitiveSessions': '有 {count} 個分頁處於密碼/敏感輸入,已跳過',
'scripts.actions.noRunnableHosts': '沒有與指令碼目標相符的可連線主機',
@@ -31,6 +31,7 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': '載入監聽連接埠失敗',
'systemManager.errors.loadServices': '載入 systemd 服務失敗',
'systemManager.errors.sshChannelUnavailable': '伺服器拒絕開啟新的執行通道。請稍後重試,或重新連線目前主機。',
'systemManager.unsupportedRemote': '此主機不允許額外的 SSH 執行通道,系統面板無法使用。開啟此面板不會再中斷目前終端。',
'systemManager.overview.empty': '暫無系統概覽資料。',
'systemManager.overview.loading': '正在載入系統概覽…',
+25 -1
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const zhTWTerminalMessages: Messages = {
'terminal.menu.saveScreen': '儲存目前畫面',
'terminal.saveScreen.failed': '儲存終端畫面失敗。',
// 多行貼上確認對話框(#3398)
'terminal.pasteConfirm.title': '要貼上多行文字嗎?',
'terminal.pasteConfirm.summary': '將向工作階段傳送 {lines} 行({chars} 個字元)。',
'terminal.pasteConfirm.preview': '預覽(可編輯)',
'terminal.pasteConfirm.send': '傳送',
'terminal.pasteConfirm.sendLineByLine': '逐行傳送',
'terminal.pasteConfirm.cancel': '取消',
'terminal.sudoHint.pressEnter': '按 Enter 貼上已儲存的密碼',
'terminal.passwordPicker.title': '已儲存的密碼',
'terminal.passwordPicker.empty': '沒有已儲存的密碼',
@@ -271,6 +278,8 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.font.weightBold.desc': '粗體文字字重 (100-900)',
'settings.terminal.font.smoothing': '字型平滑',
'settings.terminal.font.smoothing.desc': '使用 macOS 原生字型抗鋸齒',
'settings.terminal.font.ligatures': '字型連字',
'settings.terminal.font.ligatures.desc': '支援連字的字型把 != 這類字元顯示成一個符號',
'settings.terminal.font.linePadding': '行間距',
'settings.terminal.font.linePadding.desc': '行之間的額外間距 (0-10)',
'settings.terminal.font.emulationType': '終端模擬型別',
@@ -278,6 +287,8 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.cursor.style.block': '塊',
'settings.terminal.cursor.style.bar': '豎線',
'settings.terminal.cursor.style.underline': '下劃線',
'settings.terminal.cursor.barWidth': '豎線游標粗細',
'settings.terminal.cursor.barWidth.desc': 'vi 等應用程式使用豎線游標時的寬度(1-4 像素)',
'settings.terminal.cursor.blink': '游標閃爍',
'settings.terminal.cursor.highlightLine': '高亮目前行',
'settings.terminal.cursor.highlightLine.desc': '為游標所在行加上淡色背景,方便定位目前輸入位置',
@@ -326,12 +337,21 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': '貼上時自動上傳剪貼簿圖片',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'當剪貼簿包含圖片時,在遠端工作階段中貼上會透過 SFTP 將圖片上傳到遠端目前目錄的 .netcatty-paste-images/ 資料夾,並在終端輸入遠端路徑,而不是貼上文字。',
'settings.terminal.behavior.confirmMultilinePaste': '貼上多行前先詢問',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'貼上多行文字時先彈出確認對話框,顯示行數和字元數、可編輯的預覽,並提供傳送 / 逐行傳送 / 取消操作。可保護不支援括號貼上的網路設備 CLI(Cisco IOS、華為 VRP、H3C Comware)。',
'settings.terminal.behavior.confirmMultilinePasteMinLines': '確認門檻(行數)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'貼上內容達到該行數時才彈出確認對話框。',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter 傳送文字',
'settings.terminal.behavior.shiftEnterNewline.desc':
'在終端中按 Shift+Enter 時傳送設定的文字,而不是一般 Enter。',
'settings.terminal.behavior.shiftEnterNewlineText': '傳送內容',
'settings.terminal.behavior.shiftEnterNewlineText.desc':
'使用 \\n 表示換行,\\t 表示 Tab,\\\\ 表示反斜線。',
'使用 \\n 表示換行,\\t 表示 Tab,\\e 表示 ESC,\\\\ 表示反斜線。',
'settings.terminal.behavior.shiftEnterForceText': '在 Win32 輸入模式下也傳送文字',
'settings.terminal.behavior.shiftEnterForceText.desc':
'本機 Windows ConPTY 工作階段協商 Win32 輸入模式時,仍然傳送上面的文字。Node/Bun 寫的 CLI(Claude Code、CodeBuddy)讀不到主控台輸入記錄中的修飾鍵,需要這個開關才能區分 Shift+Enter。',
'settings.terminal.behavior.clearWipesScrollback': '`clear` 同時清空捲動緩衝',
'settings.terminal.behavior.clearWipesScrollback.desc':
'`clear` 指令同時清空捲動緩衝(POSIX 預設行為)。關閉則保留歷史。',
@@ -918,6 +938,10 @@ export const zhTWTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': '例如 Arduino Uno',
'serial.connectAndSave': '連線並儲存',
'serial.edit.title': '序列埠設定',
'serial.field.username': '使用者名稱',
'serial.field.password': '密碼',
'serial.field.autoLoginDesc': '設定後,序列埠終端出現 Login/Password 登入提示時,會自動填入此處儲存的使用者名稱和密碼。',
'serial.field.clearPassword': '清除已儲存的密碼',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': '需要驗證',
+4
View File
@@ -466,6 +466,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.composeBar.send': '傳送',
'terminal.composeBar.close': '關閉撰寫欄',
'terminal.composeBar.broadcasting': '正在廣播到所有工作階段',
'terminal.composeBar.broadcastAllowPassword': '廣播時不對密碼進行保護',
'terminal.composeBar.resize': '拖曳調整撰寫欄高度',
'terminal.composeBar.manageSnippets': '管理快捷程式碼片段',
'terminal.composeBar.searchSnippets': '搜尋程式碼片段...',
@@ -503,6 +504,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': '重新連線目前工作階段',
'terminal.serverStats.cpu': 'CPU 使用率',
'terminal.serverStats.cpuCores': 'CPU 核心使用率',
'terminal.serverStats.gpu': 'GPU 使用率',
'terminal.serverStats.memory': '記憶體使用',
'terminal.serverStats.memoryDetails': '記憶體詳情',
'terminal.serverStats.memUsed': '已用',
@@ -536,6 +538,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.search.noResults': '無結果',
'terminal.search.prevMatch': '上一個相符 (Shift+Enter)',
'terminal.search.nextMatch': '下一個相符 (Enter)',
'terminal.menu.cut': '剪下',
'terminal.menu.copy': '複製',
'terminal.menu.paste': '貼上',
'terminal.menu.addSelectionToAI': '新增到對話',
@@ -578,6 +581,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.auth.retryMessage': '驗證失敗。請檢查憑證後再試一次。',
'terminal.auth.retryLog': '驗證失敗,請再試一次。',
'terminal.auth.noKeysHint': '暫無金鑰,請先在鑰匙串中新增。',
'terminal.auth.selectIdentity': '使用已儲存的身分',
'terminal.auth.continueSave': '繼續並儲存',
'terminal.auth.credentialsUnavailable': '目前裝置無法解密已儲存憑證,請重新輸入並再次儲存。',
'terminal.auth.jumpCredentialsUnavailable': '某個跳板機的已儲存憑證無法在目前裝置解密,請到主機設定中重新填寫。',
@@ -0,0 +1,62 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
getPendingMultilinePasteConfirm,
requestMultilinePasteConfirm,
respondMultilinePasteConfirm,
subscribeMultilinePasteConfirm,
} from "./multilinePasteConfirmStore";
test("request stores the pending paste and respond resolves it", async () => {
const pending = requestMultilinePasteConfirm({
text: "line1\nline2",
lineCount: 2,
charCount: 12,
});
assert.equal(getPendingMultilinePasteConfirm()?.lineCount, 2);
respondMultilinePasteConfirm("line-by-line", "line1\nline2\nline3");
const response = await pending;
assert.deepEqual(response, { action: "line-by-line", text: "line1\nline2\nline3" });
assert.equal(getPendingMultilinePasteConfirm(), null);
});
test("respond without text falls back to the original request text", async () => {
const pending = requestMultilinePasteConfirm({
text: "line1\nline2",
lineCount: 2,
charCount: 12,
});
respondMultilinePasteConfirm("send");
const response = await pending;
assert.deepEqual(response, { action: "send", text: "line1\nline2" });
});
test("a newer paste request supersedes the pending one as cancelled", async () => {
const first = requestMultilinePasteConfirm({ text: "a\nb", lineCount: 2, charCount: 3 });
const second = requestMultilinePasteConfirm({ text: "c\nd", lineCount: 2, charCount: 3 });
assert.equal(getPendingMultilinePasteConfirm()?.text, "c\nd");
respondMultilinePasteConfirm("send", "c\nd");
assert.deepEqual(await first, { action: "cancel", text: "a\nb" });
assert.deepEqual(await second, { action: "send", text: "c\nd" });
});
test("respond without a pending request is a no-op and listeners are notified", async () => {
respondMultilinePasteConfirm("send");
assert.equal(getPendingMultilinePasteConfirm(), null);
const events: Array<string | null> = [];
const unsubscribe = subscribeMultilinePasteConfirm(() => {
events.push(getPendingMultilinePasteConfirm()?.id ?? "cleared");
});
const pending = requestMultilinePasteConfirm({ text: "x", lineCount: 1, charCount: 1 });
const pendingId = getPendingMultilinePasteConfirm()?.id ?? null;
respondMultilinePasteConfirm("cancel", "x");
await pending;
unsubscribe();
assert.ok(pendingId);
assert.deepEqual(events, [pendingId, "cleared"]);
});
@@ -0,0 +1,81 @@
/**
* App-level store for the "paste multiple lines" confirmation dialog (#3398).
*
* Terminal paste handlers call `requestMultilinePasteConfirm` from anywhere in
* the renderer and await the user's decision; `MultilinePasteConfirmHost`
* (mounted once in App) renders the dialog and resolves the pending request.
*/
export type MultilinePasteConfirmAction = "send" | "line-by-line" | "cancel";
export interface MultilinePasteConfirmRequest {
id: string;
/** Clipboard text the dialog previews (editable by the user). */
text: string;
lineCount: number;
charCount: number;
/** Restore the originating terminal's focus after the modal releases it. */
onClose?: () => void;
}
export interface MultilinePasteConfirmResponse {
action: MultilinePasteConfirmAction;
/** Text to send: the preview content, possibly edited by the user. */
text: string;
}
interface PendingRequest {
request: MultilinePasteConfirmRequest;
resolve: (response: MultilinePasteConfirmResponse) => void;
}
let pending: PendingRequest | null = null;
let nextRequestId = 0;
const listeners = new Set<() => void>();
const emit = (): void => {
for (const listener of listeners) listener();
};
export function requestMultilinePasteConfirm(
request: Omit<MultilinePasteConfirmRequest, "id">,
): Promise<MultilinePasteConfirmResponse> {
// Only one confirmation dialog can be pending; a newer paste supersedes the
// older one (the stale promise resolves as "cancel" so its paste is dropped).
if (pending) {
const stale = pending;
pending = null;
stale.resolve({ action: "cancel", text: stale.request.text });
}
nextRequestId += 1;
const requestWithId: MultilinePasteConfirmRequest = {
...request,
id: `multiline-paste-${nextRequestId}`,
};
return new Promise((resolve) => {
pending = { request: requestWithId, resolve };
emit();
});
}
export function respondMultilinePasteConfirm(
action: MultilinePasteConfirmAction,
text?: string,
): void {
const current = pending;
if (!current) return;
pending = null;
current.resolve({ action, text: text ?? current.request.text });
emit();
}
/** Snapshot for `useSyncExternalStore`; stable reference while pending. */
export const getPendingMultilinePasteConfirm =
(): MultilinePasteConfirmRequest | null => pending?.request ?? null;
export function subscribeMultilinePasteConfirm(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
runAutomationScript,
runConnectScriptsSequential,
selectScriptOverlayRun,
setScriptRuns,
@@ -8,6 +9,7 @@ import {
} from './scriptAutomationCoordinator.ts';
import type { ScriptRun } from '@/types/global/netcatty-bridge-script.d.ts';
import type { Snippet } from '@/domain/models';
import { STORAGE_KEY_AI_PERMISSION_MODE } from '@/infrastructure/config/storageKeys.ts';
import { netcattyBridge } from '@/infrastructure/services/netcattyBridge.ts';
test('waitForScriptRun resolves when run is already completed on subscribe', async () => {
@@ -246,3 +248,127 @@ test('runConnectScriptsSequential does not treat a script error named Aborted as
Reflect.deleteProperty(globalThis, 'localStorage');
}
});
function installPermissionMode(mode: string) {
const storage = new Map<string, string>([[STORAGE_KEY_AI_PERMISSION_MODE, mode]]);
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => { storage.set(key, String(value)); },
removeItem: (key: string) => { storage.delete(key); },
clear: () => { storage.clear(); },
},
});
}
const writeScript: Snippet = {
id: 'write-script',
label: 'Write',
command: "await nct.screen.sendLine('echo hi');",
kind: 'script',
};
test('runAutomationScript executes a user write script while AI permission mode is observer', async () => {
const originalGet = netcattyBridge.get;
installPermissionMode('observer');
let seenMode: string | undefined;
netcattyBridge.get = () => ({
scriptRun: async (params) => {
seenMode = params.permissionMode;
return { runId: 'user-run', runIds: ['user-run'] };
},
}) as ReturnType<typeof netcattyBridge.get>;
try {
const result = await runAutomationScript({
snippet: writeScript,
sessionId: 'sess-user',
initiatedBy: 'user',
});
assert.equal(result.runId, 'user-run');
assert.equal(seenMode, 'auto');
} finally {
netcattyBridge.get = originalGet;
Reflect.deleteProperty(globalThis, 'localStorage');
}
});
test('runAutomationScript blocks automatic write scripts in observer mode', async () => {
const originalGet = netcattyBridge.get;
installPermissionMode('observer');
let called = false;
netcattyBridge.get = () => ({
scriptRun: async () => {
called = true;
return { runId: 'automatic-run', runIds: ['automatic-run'] };
},
}) as ReturnType<typeof netcattyBridge.get>;
try {
await assert.rejects(
() => runAutomationScript({ snippet: writeScript, sessionId: 'sess-automatic' }),
/Observer mode blocks scripts that write to the terminal/,
);
assert.equal(called, false);
} finally {
netcattyBridge.get = originalGet;
Reflect.deleteProperty(globalThis, 'localStorage');
}
});
test('runAutomationScript blocks an AI write script in observer mode', async () => {
const originalGet = netcattyBridge.get;
installPermissionMode('observer');
let called = false;
netcattyBridge.get = () => ({
scriptRun: async () => {
called = true;
return { runId: 'ai-run', runIds: ['ai-run'] };
},
}) as ReturnType<typeof netcattyBridge.get>;
try {
await assert.rejects(
() => runAutomationScript({
snippet: writeScript,
sessionId: 'sess-ai',
initiatedBy: 'ai',
}),
/Observer mode blocks scripts that write to the terminal/,
);
assert.equal(called, false);
} finally {
netcattyBridge.get = originalGet;
Reflect.deleteProperty(globalThis, 'localStorage');
}
});
test('runAutomationScript keeps observer on an AI read-only script so later writes stay blocked', async () => {
const originalGet = netcattyBridge.get;
installPermissionMode('observer');
let seenMode: string | undefined;
netcattyBridge.get = () => ({
scriptRun: async (params) => {
seenMode = params.permissionMode;
return { runId: 'ai-read', runIds: ['ai-read'] };
},
}) as ReturnType<typeof netcattyBridge.get>;
try {
await runAutomationScript({
snippet: {
id: 'read-script',
label: 'Read',
command: "await nct.screen.waitForPrompt(1000);",
kind: 'script',
},
sessionId: 'sess-ai-read',
initiatedBy: 'ai',
});
assert.equal(seenMode, 'observer');
} finally {
netcattyBridge.get = originalGet;
Reflect.deleteProperty(globalThis, 'localStorage');
}
});
@@ -95,8 +95,10 @@ export async function runAutomationScript(params: {
hostname?: string;
username?: string;
};
/** Only a direct user action bypasses Observer; AI and automatic runs honor it. */
initiatedBy?: 'user' | 'ai';
}): Promise<{ runId: string; runIds: string[] }> {
const permissionMode = readPermissionMode();
const permissionMode = params.initiatedBy === 'user' ? 'auto' : readPermissionMode();
if (permissionMode === 'observer' && scriptContainsWriteOperations(params.snippet.command)) {
throw new Error('Observer mode blocks scripts that write to the terminal.');
}
+7 -4
View File
@@ -23,7 +23,6 @@ export type SettingsChromeSnapshot = {
darkUiThemeId: string;
uiLanguage: UILanguage;
windowOpacity: number;
tabBarPosition: 'top' | 'bottom';
showSftpTab: boolean;
showHostTreeSidebar: boolean;
showRecentHosts: boolean;
@@ -37,6 +36,8 @@ export type SettingsChromeSnapshot = {
restoreTerminalCwd: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
localShellSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
};
/**
@@ -56,7 +57,6 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
darkUiThemeId: 'default',
uiLanguage: 'en',
windowOpacity: 1,
tabBarPosition: 'top',
showSftpTab: true,
showHostTreeSidebar: true,
showRecentHosts: true,
@@ -70,6 +70,8 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
restoreTerminalCwd: true,
terminalSidePanelAutoOpen: false,
terminalSidePanelAutoOpenTab: 'ai',
localShellSidePanelAutoOpen: false,
localShellSidePanelAutoOpenTab: 'scripts',
} satisfies SettingsChromeSnapshot);
export function settingsChromeSnapshotsEqual(
@@ -82,7 +84,6 @@ export function settingsChromeSnapshotsEqual(
&& a.darkUiThemeId === b.darkUiThemeId
&& a.uiLanguage === b.uiLanguage
&& a.windowOpacity === b.windowOpacity
&& a.tabBarPosition === b.tabBarPosition
&& a.showSftpTab === b.showSftpTab
&& a.showHostTreeSidebar === b.showHostTreeSidebar
&& a.showRecentHosts === b.showRecentHosts
@@ -95,7 +96,9 @@ export function settingsChromeSnapshotsEqual(
&& a.showTabNumberBadges === b.showTabNumberBadges
&& a.restoreTerminalCwd === b.restoreTerminalCwd
&& a.terminalSidePanelAutoOpen === b.terminalSidePanelAutoOpen
&& a.terminalSidePanelAutoOpenTab === b.terminalSidePanelAutoOpenTab;
&& a.terminalSidePanelAutoOpenTab === b.terminalSidePanelAutoOpenTab
&& a.localShellSidePanelAutoOpen === b.localShellSidePanelAutoOpen
&& a.localShellSidePanelAutoOpenTab === b.localShellSidePanelAutoOpenTab;
}
class SettingsChromeStore {
@@ -0,0 +1,79 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { useState } from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { useSettingsIpcSync } from './settingsIpcSync.ts';
import { useSettingsStorageSync } from './settingsStorageSync.ts';
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen.ts';
import {
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN as enabledKey,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB as tabKey,
} from '../../infrastructure/config/storageKeys.ts';
for (const pathway of ['ipc', 'storage'] as const) {
test(`${pathway} receives local shell settings, rejects invalid tabs and cleans up`, async (t) => {
let receive: ((payload: { key: string; value: unknown }) => void) | undefined;
let unsubscribed = false;
const fakeWindow = Object.assign(new EventTarget(), {
netcatty: {
onSettingsChanged(callback: typeof receive) {
receive = callback;
return () => { unsubscribed = true; };
},
},
});
for (const [key, value] of Object.entries({ window: fakeWindow, IS_REACT_ACT_ENVIRONMENT: true })) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { value, configurable: true });
t.after(() => {
if (previous) Object.defineProperty(globalThis, key, previous);
else Reflect.deleteProperty(globalThis, key);
});
}
let current = { enabled: false, tab: 'scripts' };
let renderer: ReactTestRenderer | undefined;
function Harness() {
const [enabled, setEnabled] = useState(false);
const [tab, setTab] = useState<TerminalSidePanelAutoOpenTab>('scripts');
current = { enabled, tab };
const params = {
localShellSidePanelAutoOpen: enabled,
localShellSidePanelAutoOpenTab: tab,
setLocalShellSidePanelAutoOpenState: setEnabled,
setLocalShellSidePanelAutoOpenTabState: setTab,
};
// Only local-shell events are dispatched; unrelated settings are not used.
useSettingsIpcSync({ ...params, enabled: pathway === 'ipc' } as unknown as Parameters<typeof useSettingsIpcSync>[0]);
useSettingsStorageSync({ ...params, enabled: pathway === 'storage' } as Parameters<typeof useSettingsStorageSync>[0]);
return null;
}
async function send(key: string, value: unknown) {
await act(async () => {
if (pathway === 'ipc') receive!({ key, value });
else fakeWindow.dispatchEvent(Object.assign(new Event('storage'), { key, newValue: value === null ? null : String(value) }));
});
}
try {
await act(async () => { renderer = create(React.createElement(Harness)); });
await send(enabledKey, true);
await send(tabKey, 'notes');
assert.deepEqual(current, { enabled: true, tab: 'notes' });
await send(tabKey, 'invalid');
await send(tabKey, null);
await send(enabledKey, null);
assert.deepEqual(current, { enabled: true, tab: 'notes' });
if (pathway === 'ipc') {
await send(enabledKey, 'false');
assert.equal(current.enabled, true);
}
await send(enabledKey, false);
await send(tabKey, 'history');
assert.deepEqual(current, { enabled: false, tab: 'history' });
await act(async () => { renderer!.unmount(); });
renderer = undefined;
if (pathway === 'ipc') assert.equal(unsubscribed, true);
} finally {
await act(async () => { renderer?.unmount(); });
}
});
}
+14 -8
View File
@@ -1,4 +1,3 @@
import { normalizeTabBarPosition, type TabBarPosition } from '../../domain/tabBarPosition';
import { useEffect, type Dispatch, type SetStateAction } from 'react';
import type { CustomKeyBindings, HotkeyScheme, SessionLogFormat, TerminalSettings, UILanguage } from '../../domain/models';
import { parseCustomKeyBindingsStorageRecord } from '../../domain/customKeyBindings';
@@ -45,9 +44,10 @@ import {
STORAGE_KEY_UI_THEME_LIGHT,
STORAGE_KEY_WORKSPACE_FOCUS_STYLE,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_TAB_BAR_POSITION,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_APP_ICON_VARIANT,
STORAGE_KEY_HTTP_NETWORK_PROXY,
@@ -102,10 +102,11 @@ interface UseSettingsIpcSyncParams {
setSftpFollowTerminalCwd: Dispatch<SetStateAction<boolean>>;
setSftpDefaultViewMode: Dispatch<SetStateAction<'list' | 'tree'>>;
setWorkspaceFocusStyleState: Dispatch<SetStateAction<'dim' | 'border'>>;
setTabBarPositionState: Dispatch<SetStateAction<TabBarPosition>>;
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setLocalShellSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setDisableTerminalFontZoomState: Dispatch<SetStateAction<boolean>>;
setRestorePreviousSessionState: Dispatch<SetStateAction<boolean>>;
setRestoreTerminalCwdState: Dispatch<SetStateAction<boolean>>;
@@ -149,10 +150,11 @@ export function useSettingsIpcSync({
setSftpFollowTerminalCwd,
setSftpDefaultViewMode,
setWorkspaceFocusStyleState,
setTabBarPositionState,
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
@@ -304,9 +306,6 @@ export function useSettingsIpcSync({
if (key === STORAGE_KEY_WORKSPACE_FOCUS_STYLE && (value === 'dim' || value === 'border')) {
setWorkspaceFocusStyleState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_TAB_BAR_POSITION) {
setTabBarPositionState(normalizeTabBarPosition(value));
}
if (key === STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR && typeof value === 'boolean') {
setShowHostTreeSidebarState((prev) => (prev === value ? prev : value));
}
@@ -316,6 +315,12 @@ export function useSettingsIpcSync({
if (key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB && isTerminalSidePanelAutoOpenTab(value)) {
setTerminalSidePanelAutoOpenTabState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN && typeof value === 'boolean') {
setLocalShellSidePanelAutoOpenState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB && isTerminalSidePanelAutoOpenTab(value)) {
setLocalShellSidePanelAutoOpenTabState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM && typeof value === 'boolean') {
setDisableTerminalFontZoomState((prev) => (prev === value ? prev : value));
}
@@ -367,10 +372,11 @@ export function useSettingsIpcSync({
setSftpAutoOpenSidebar,
setSftpFollowTerminalCwd,
setSftpDefaultViewMode,
setTabBarPositionState,
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
+24 -12
View File
@@ -1,4 +1,3 @@
import { normalizeTabBarPosition, type TabBarPosition } from '../../domain/tabBarPosition';
import { useEffect, useRef, type Dispatch, type SetStateAction } from 'react';
import type { CustomKeyBindings, HotkeyScheme, SessionLogFormat, TerminalSettings, UILanguage } from '../../domain/models';
import { parseCustomKeyBindingsStorageRecord } from '../../domain/customKeyBindings';
@@ -35,10 +34,11 @@ import {
STORAGE_KEY_SHOW_RECENT_HOSTS,
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_TAB_BAR_POSITION,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
@@ -92,11 +92,12 @@ interface UseSettingsStorageSyncParams {
showRecentHosts: boolean;
hostClickBehavior: HostClickBehavior;
showOnlyUngroupedHostsInRoot: boolean;
tabBarPosition: TabBarPosition;
showSftpTab: boolean;
showHostTreeSidebar: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
localShellSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
shellOnlyTabNumberShortcuts: boolean;
showTabNumberBadges: boolean;
disableTerminalFontZoom: boolean;
@@ -142,11 +143,12 @@ interface UseSettingsStorageSyncParams {
setShowRecentHostsState: Dispatch<SetStateAction<boolean>>;
setHostClickBehaviorState: Dispatch<SetStateAction<HostClickBehavior>>;
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
setTabBarPositionState: Dispatch<SetStateAction<TabBarPosition>>;
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setLocalShellSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setShellOnlyTabNumberShortcutsState: Dispatch<SetStateAction<boolean>>;
setShowTabNumberBadgesState: Dispatch<SetStateAction<boolean>>;
setDisableTerminalFontZoomState: Dispatch<SetStateAction<boolean>>;
@@ -180,7 +182,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode, applyIncomingCustomAccent,
@@ -189,7 +191,7 @@ export function useSettingsStorageSync({
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState,
setGlobalHotkeyEnabled, setWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
@@ -204,7 +206,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
});
@@ -214,7 +216,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
};
@@ -435,9 +437,6 @@ export function useSettingsStorageSync({
setShowOnlyUngroupedHostsInRootState(newValue);
}
}
if (e.key === STORAGE_KEY_TAB_BAR_POSITION) {
setTabBarPositionState(normalizeTabBarPosition(e.newValue));
}
if (e.key === STORAGE_KEY_SHOW_SFTP_TAB && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.showSftpTab) {
@@ -461,6 +460,17 @@ export function useSettingsStorageSync({
setTerminalSidePanelAutoOpenTabState(e.newValue);
}
}
if (e.key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.localShellSidePanelAutoOpen) {
setLocalShellSidePanelAutoOpenState(newValue);
}
}
if (e.key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB && e.newValue !== null) {
if (isTerminalSidePanelAutoOpenTab(e.newValue) && e.newValue !== s.localShellSidePanelAutoOpenTab) {
setLocalShellSidePanelAutoOpenTabState(e.newValue);
}
}
if (e.key === STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.shellOnlyTabNumberShortcuts) {
@@ -581,8 +591,10 @@ export function useSettingsStorageSync({
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setShowRecentHostsState,
setTabBarPositionState, setShowSftpTabState,
setShowSftpTabState,
setShellOnlyTabNumberShortcutsState,
setShowTabNumberBadgesState,
setDisableTerminalFontZoomState,
@@ -41,8 +41,12 @@ const host = (id: string, label: string, hostname = label): Host => ({
for (const retainedStatus of [undefined, "interrupted", "failed", "paused"] as const) {
for (const newerPause of retainedStatus === "paused" ? [false, true] : [false]) {
for (const ownerChange of retainedStatus === "interrupted" || retainedStatus === undefined ? ["same", "active", "completed"] : ["same"]) {
for (const completedBeforeReplacement of ownerChange === "active" ? [false, true] : [false]) {
for (const flushBeforeReply of ownerChange === "same" || retainedStatus === undefined ? [false] : [false, true]) {
for (const replyRejects of ownerChange !== "same" && !completedBeforeReplacement && !flushBeforeReply ? [false, true] : [false]) {
const batchExistingIdentity = retainedStatus !== undefined;
test(`superseded folder child settles when its completion was compacted into the parent: retained=${retainedStatus ?? "none"}, newerPause=${newerPause}`, async (t) => {
test(`superseded folder child settles when its completion was compacted into the parent: retained=${retainedStatus ?? "none"}, newerPause=${newerPause}, owner=${ownerChange}, flush=${flushBeforeReply}, priorComplete=${completedBeforeReplacement}, reject=${replyRejects}`, async (t) => {
const { sftpTransferCenterStore } = await import("../sftpTransferCenterStore");
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
@@ -75,14 +79,19 @@ test(`superseded folder child settles when its completion was compacted into the
...parent, id: "retained-child", parentTaskId: parent.id, isDirectory: false,
sourcePath: "/local/folder/a.bin", targetPath: "/remote/folder/a.bin",
totalBytes: 10, sourceLastModified: 1, status: retainedStatus ?? "interrupted",
directoryEntryIndex: 0, directoryEntryIdentity: "a".repeat(64),
directoryEntryIndex: 0,
directoryEntryIdentity: newerPause ? createDirectoryEntryIdentity({
sourcePath: "/local/folder/a.bin", targetPath: "/remote/folder/a.bin", size: 10, lastModified: 1,
}) : "a".repeat(64),
};
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
// Exercise the real large-history batching branch with one relevant retained row.
const childBatcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096,
hasTask: (id) => id === persisted.id,
upsertTasks: (updates) => sftpTransferCenterStore.upsertTasks(updates),
hasTask: (id) => id === persisted.id || id.startsWith("flush-peer-"),
// Peer rows only drive the real 512-entry flush; keep the relevant store
// fixture small so unrelated history maintenance cannot mask ownership.
upsertTasks: (updates) => sftpTransferCenterStore.upsertTasks(updates.filter((task) => !task.id.startsWith("flush-peer-"))),
});
sftpTransferCenterStore.publishOwner("compacted-owner", [parent, ...(batchExistingIdentity ? [persisted] : [])]);
(netcattyBridge as { get: () => unknown }).get = () => ({
@@ -106,20 +115,50 @@ test(`superseded folder child settles when its completion was compacted into the
directoryEntryIndex: options.directoryEntryIndex,
directoryEntryIdentity: options.directoryEntryIdentity,
});
// A newer same-id owner completes before this older invocation rejoins.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: 0,
});
return { superseded: true };
if (ownerChange !== "same") {
const current = sftpTransferCenterStore.getTask(childId)!;
if (completedBeforeReplacement) {
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: 0,
});
}
sftpTransferCenterStore.upsertTasks([{
...current, status: "transferring", directoryEntryIdentity: "e".repeat(64), lifecycleEpoch: 1,
}]);
}
if (ownerChange !== "active") {
// A newer same-id owner completes before this older invocation rejoins.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: ownerChange === "same" ? 0 : 1,
});
}
if (flushBeforeReply) {
for (let index = 0; index < 512; index += 1) {
childBatcher.push({ ...persisted, id: `flush-peer-${index}`, status: "transferring" });
}
if (ownerChange === "active") {
assert.equal(sftpTransferCenterStore.getTask(childId)?.directoryEntryIdentity, "e".repeat(64),
"automatic flush before the displaced reply must preserve the new owner");
} else assert.equal(sftpTransferCenterStore.getTask(childId), undefined,
"automatic flush must not recreate the compacted new owner");
}
if (replyRejects) throw new Error("old invocation transport failed");
return completedBeforeReplacement ? {} : { superseded: true };
},
});
running = resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box", "1.2.3.4")], keys: [], identities: [],
}, undefined, {
children: batchExistingIdentity ? [persisted] : [], shouldAbort: () => abort,
onChildUpdate: (child) => batchExistingIdentity
? childBatcher.push(child)
: sftpTransferCenterStore.publishOwner("compacted-owner", [parent, child]),
onChildSuperseded: (id) => childBatcher.discard(id),
flushChildUpdates: () => childBatcher.flush(),
onChildUpdate: (child, observation) => {
if (batchExistingIdentity) {
childBatcher.push(child, observation);
return true;
}
sftpTransferCenterStore.publishOwner("compacted-owner", [parent, child]);
},
});
const result = await Promise.race([
running,
@@ -133,6 +172,15 @@ test(`superseded folder child settles when its completion was compacted into the
}
assert.notEqual(result, "still-waiting", "completed compacted child must not leave its folder waiting forever");
assert.ok(childId);
if (ownerChange !== "same") {
childBatcher.flush();
assert.equal((result as { success: boolean }).success, false, "the displaced walk must not report success");
if (ownerChange === "active") {
assert.equal(sftpTransferCenterStore.getTask(childId)?.status, "transferring");
assert.equal(sftpTransferCenterStore.getTask(childId)?.directoryEntryIdentity, "e".repeat(64));
} else assert.equal(sftpTransferCenterStore.getTask(childId), undefined, "old waiter must not recreate a failed row");
return;
}
assert.equal(sftpTransferCenterStore.getTask(childId), undefined, "completed row was compacted");
assert.equal(sftpTransferCenterStore.getTask(parent.id)?.directoryResumeCheckpoint?.completedEntries, 1);
assert.notEqual(result, "still-waiting", "completed compacted child must not leave its folder waiting forever");
@@ -140,6 +188,10 @@ test(`superseded folder child settles when its completion was compacted into the
});
}
}
}
}
}
}
test("resolveDirectoryResumeTargetRoot prefers staged replace path", () => {
assert.equal(
@@ -696,6 +748,67 @@ test("single-file restart resume continues from checkpoint without page callback
}
});
test("stat-less SCP download resume keeps saved progress instead of restarting", async (t) => {
resetDedicatedSessionOpenGateForTests();
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: { getItem: () => "2", setItem: () => {}, removeItem: () => {} },
});
t.after(() => {
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
});
const originalGet = netcattyBridge.get;
let startOptions: Record<string, unknown> | undefined;
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated-sftp",
closeSftp: async () => {},
// Stat-less SCP host: size cannot be measured, so the bridge reports the
// placeholder 0 with sizeKnown false.
statSftp: async () => ({ type: "file", size: 0, lastModified: 5, sizeKnown: false }),
startStreamTransfer: async (options: Record<string, unknown>) => {
startOptions = options;
return { transferId: "scp-download-resume" };
},
});
try {
const result = await resumeTransferWithDedicatedSession({
id: "scp-download-resume",
fileName: "file.bin",
sourcePath: "/remote/file.bin",
targetPath: "/local/file.bin",
sourceConnectionId: "old-sftp",
sourceHostId: "h1",
sourceHostLabel: "box",
targetConnectionId: "local",
direction: "download",
status: "interrupted",
totalBytes: 100,
transferredBytes: 20,
checkpointBytes: 20,
sourceLastModified: 5,
speed: 0,
startTime: 1,
isDirectory: false,
reconnectRequired: true,
}, {
hosts: [host("h1", "box", "1.2.3.4")],
keys: [],
identities: [],
});
assert.equal(result.success, true, result.error);
// Unknown size must not misread the saved checkpoint as a shrunk source;
// the download resumes from byte 20 instead of silently restarting.
assert.equal(startOptions?.checkpointBytes, 20);
assert.equal(startOptions?.totalBytes, 100);
} finally {
(netcattyBridge as { get: typeof originalGet }).get = originalGet;
resetDedicatedSessionOpenGateForTests();
}
});
test("folder restart resume reports file-count progress without child page callbacks", async (t) => {
resetDedicatedSessionOpenGateForTests();
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
@@ -2131,3 +2244,202 @@ for (const scenario of ["deleted-id", "ambiguous-legacy-label"] as const) {
assert.equal(uploads, 0);
});
}
for (const completeDuringSetup of [false, true]) {
test(`large-history replace recovery retransfers retained completed children into its empty stage: late=${completeDuringSetup}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const originalGet = netcattyBridge.get;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true, value: { getItem: () => "2", setItem: () => {}, removeItem: () => {} },
});
const { createRequire } = await import("node:module");
const tempDirBridge = createRequire(import.meta.url)("../../../electron/bridges/tempDirBridge.cjs");
const root = await fs.promises.mkdtemp(`${tempDirBridge.getTempFilePath("folder-rebuild-test")}-`);
const finalPath = path.join(root, "final");
const stage = `${finalPath}.netcatty-retained-replace.part`;
await fs.promises.mkdir(stage);
await fs.promises.writeFile(path.join(stage, "b.txt"), "old contents");
const parent: TransferTask = {
id: "retained-replace", fileName: "folder", sourcePath: "/remote/folder", targetPath: finalPath,
stagedTargetPath: stage, replaceExistingTarget: true, sourceConnectionId: "old-sftp", targetConnectionId: "local",
sourceHostId: "h1", direction: "download", status: "transferring", totalBytes: 2,
transferredBytes: 1, speed: 0, startTime: 1, isDirectory: true, progressMode: "files", reconnectRequired: true,
};
const retained: TransferTask = {
...parent, id: "retained-replace-b", parentTaskId: parent.id, isDirectory: false,
sourcePath: "/remote/folder/b.txt", targetPath: `${stage}/b.txt`, fileName: "b.txt",
status: completeDuringSetup ? "interrupted" : "completed", totalBytes: 10, transferredBytes: 10, checkpointBytes: 10,
sourceLastModified: 2, directoryEntryIndex: 1,
directoryEntryIdentity: createDirectoryEntryIdentity({
sourcePath: "/remote/folder/b.txt", targetPath: `${stage}/b.txt`, size: 10, lastModified: 2,
}),
};
store.upsertTasks([parent, retained]);
assert.ok(store.getTask(retained.id), "missing earlier manifest index retains the completed row");
const batcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096,
hasTask: (id) => !!store.getTask(id),
upsertTasks: (updates) => store.upsertTasks(updates),
});
let releaseFirst!: () => void;
const secondDispatched = new Promise<void>((resolve) => { releaseFirst = resolve; });
t.after(async () => {
await fs.promises.rm(root, { recursive: true, force: true });
netcattyBridge.get = originalGet;
store.patchTask(parent.id, { status: "completed" });
store.dismiss(parent.id);
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
resetDedicatedSessionOpenGateForTests();
});
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated-sftp", closeSftp: async () => {},
listSftp: async (_id: string, remotePath: string) => {
if (completeDuringSetup) store.patchTask(retained.id, { status: "completed", ownerId: "dedicated-resume" });
return remotePath === parent.sourcePath
? ["a.txt", "b.txt"].map((name) => ({ name, type: "file", size: 10, lastModified: 2 })) : [];
},
mkdirLocal: async (target: string) => { await fs.promises.mkdir(target, { recursive: true }); },
statLocal: async (target: string) => {
try {
const stat = await fs.promises.stat(target);
return { type: stat.isDirectory() ? "directory" : "file", size: stat.size, lastModified: stat.mtimeMs };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
},
statSftp: async (_id: string, source: string) => {
if (source.endsWith("a.txt")) await secondDispatched;
return { type: "file", size: 10, lastModified: 2 };
},
deleteLocalFile: async (target: string) => { await fs.promises.rm(target, { recursive: true }); },
renameLocalFile: async (source: string, target: string) => { await fs.promises.rename(source, target); },
startStreamTransfer: async (options: { targetPath: string; checkpointBytes: number }) => {
assert.equal(options.checkpointBytes, 0, "an empty replacement stage cannot reuse byte checkpoints");
await fs.promises.writeFile(options.targetPath, `new ${path.basename(options.targetPath)}`);
return {};
},
});
const result = await resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box")], keys: [], identities: [],
}, undefined, {
children: [retained],
flushChildUpdates: () => batcher.flush(),
onChildUpdate: (task, observation) => {
batcher.push(task, observation);
if (task.id === retained.id && task.status === "completed") releaseFirst();
return true;
},
onDirectoryCheckpointUpdate: (value) => store.patchTask(parent.id, { directoryResumeCheckpoint: value }),
});
batcher.flush();
assert.equal(result.success, true, result.error);
assert.deepEqual((await fs.promises.readdir(finalPath)).sort(), ["a.txt", "b.txt"],
"published replacement must include the previously completed file");
assert.equal(await fs.promises.readFile(path.join(finalPath, "b.txt"), "utf8"), "new b.txt");
});
}
for (const boundary of ["before-admission", "source-missing", "source-modified", "after-completion", "after-commit"] as const) {
test(`dedicated recovery preserves replacement ownership ${boundary}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const originalGet = netcattyBridge.get;
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: {
getItem: () => "2", setItem: () => {}, removeItem: () => {},
} });
const parent: TransferTask = {
id: `ownership-${boundary}`, fileName: "folder", sourcePath: "/local/folder", targetPath: "/remote/folder",
sourceConnectionId: "local", targetConnectionId: "old", targetHostId: "h1", direction: "upload",
status: "transferring", totalBytes: 2, transferredBytes: 0, speed: 0, startTime: 1,
isDirectory: true, progressMode: "files", reconnectRequired: true,
};
const child: TransferTask = {
...parent, id: `${parent.id}-a`, parentTaskId: parent.id, isDirectory: false,
sourcePath: "/local/folder/a", targetPath: "/remote/folder/a", fileName: "a", totalBytes: 1,
status: "interrupted", directoryEntryIndex: 0, directoryEntryIdentity: "a".repeat(64), sourceLastModified: 1,
};
store.upsertTasks([parent, boundary === "before-admission"
? { ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }
: child]);
const batch = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096, hasTask: (id) => id === child.id || id.startsWith("peer-"),
upsertTasks: (rows) => store.upsertTasks(rows.filter((row) => !row.id.startsWith("peer-"))),
});
if (boundary === "before-admission") {
for (let n = 0; n < 511; n++) batch.push({ ...child, id: `peer-${n}` });
}
let releaseB!: () => void;
const bGate = new Promise<void>((resolve) => { releaseB = resolve; });
let timedOut = false;
const watchdog = setTimeout(() => { timedOut = true; releaseB(); }, 1000);
t.after(() => {
clearTimeout(watchdog);
releaseB();
batch.flush();
store.patchTask(parent.id, { status: "completed" });
store.dismiss(parent.id);
netcattyBridge.get = originalGet;
if (originalStorage) Object.defineProperty(globalThis, "localStorage", originalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
resetDedicatedSessionOpenGateForTests();
});
let starts = 0;
let displaced = 0;
let replaced = false;
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated", closeSftp: async () => {
if (boundary === "after-commit") {
assert.equal(store.getTask(child.id), undefined, "completion must be committed before async cleanup");
store.upsertTasks([{ ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
}
},
listLocalTree: async () => (boundary === "after-completion" ? ["a", "b"] : ["a"]).map((name) => ({
localPath: `/local/folder/${name}`, relativePath: name, type: "file", size: 1, lastModified: 1,
})),
mkdirSftp: async () => {}, statLocal: async () => {
if (boundary === "source-missing" || boundary === "source-modified") {
store.upsertTasks([{ ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
if (boundary === "source-missing") return null;
return { type: "file", size: 1, lastModified: 2 };
}
return { type: "file", size: 1, lastModified: 1 };
},
startStreamTransfer: async (options: { sourcePath: string }) => {
starts++;
if (options.sourcePath.endsWith("/b")) await bGate;
return {};
},
});
const result = await resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box")], keys: [], identities: [],
}, undefined, {
children: [child],
onChildSuperseded: (id) => { displaced++; batch.discard(id); },
flushChildUpdates: () => batch.flush(),
onChildUpdate: (task, observation) => {
batch.push(task, observation);
if (boundary === "after-completion" && task.id === child.id && task.status === "completed" && !replaced) {
replaced = true;
queueMicrotask(() => {
try {
store.upsertTasks([{ ...task, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
} finally { releaseB(); }
});
}
return true;
},
});
batch.flush();
assert.equal(timedOut, false);
assert.equal(result.success, boundary === "after-commit", "only a committed success may precede a legitimate replacement");
assert.equal(store.getTask(child.id)?.directoryEntryIdentity, "b".repeat(64));
assert.equal(store.getTask(child.id)?.status, "transferring");
if (boundary !== "after-completion" && boundary !== "after-commit") assert.equal(starts, 0, "source validation and a full batch must not bypass ownership");
else assert.equal(displaced, boundary === "after-commit" ? 0 : 1);
});
}
@@ -1,4 +1,4 @@
import { runTransferAndWaitForOwner } from "./waitForTransferOwner";
import { runTransferAndWaitForOwner, TransferOwnerChangedError, type TransferOwnerObservation } from "./waitForTransferOwner";
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings, TransferTask } from "../../../domain/models";
import { validateTransferResumeSource } from "../../../domain/sftpTransferCenter";
import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY } from "../../../infrastructure/config/storageKeys";
@@ -62,7 +62,10 @@ export type DedicatedResumeResult = {
export type DedicatedResumeOptions = {
children?: readonly TransferTask[];
onChildUpdate?: (child: TransferTask) => void;
/** Return true only when the consumer takes responsibility for disposing the observation. */
onChildUpdate?: (child: TransferTask, observation?: TransferOwnerObservation) => unknown;
onChildSuperseded?: (taskId: string) => void;
flushChildUpdates?: () => void;
onDirectoryCheckpointUpdate?: (checkpoint: TransferTask["directoryResumeCheckpoint"]) => void;
shouldAbort?: () => boolean;
};
@@ -671,6 +674,7 @@ async function resumeSingleFileWithDedicatedSession(
const validationError = validateTransferResumeSource(task, {
size: sourceStat.size,
lastModified: sourceStat.lastModified,
sizeKnown: sourceStat.sizeKnown,
}, { allowSourceGrowth });
const classified = classifyResumeSourceValidationError(validationError);
if (classified.kind === "modified") {
@@ -1090,6 +1094,12 @@ async function resumeDirectoryWithDedicatedSession(
// the source since the interrupted attempt, so rebuild it from empty.
await resetDirectoryReplaceStage(parent, endpoints, targetSftpId);
}
// Session setup and traversal may finish more children. Capture only
// after resetting the stage/checkpoint: all these completions refer to
// the discarded destination, while later completions remain valid.
const completedAtRestart = new Map(sftpTransferCenterStore.getSnapshot().tasks
.filter((child) => child.parentTaskId === parent.id && child.status === "completed")
.map((child) => [child.id, child]));
const destRoot = resolveDirectoryResumeTargetRoot(parent);
if (endpoints.isDownload) await ensureLocalDir(destRoot);
if (targetSftpId) await ensureRemoteDir(targetSftpId, destRoot);
@@ -1188,8 +1198,25 @@ async function resumeDirectoryWithDedicatedSession(
}
if (targetSftpId) await ensureRemoteDir(targetSftpId, getParentPath(file.targetPath));
let countedCompleted = false;
const onOwnerChanged = () => {
if (countedCompleted) {
countedCompleted = false;
completedCount -= 1;
failedCount += 1;
}
options?.onChildSuperseded?.(childId);
};
let childObservation: TransferOwnerObservation | undefined = sftpTransferCenterStore.observeTaskSettlement(
childBase, resetPersistedCheckpoint ? completedAtRestart.get(childId) : undefined, onOwnerChanged,
);
const publishChild = (child: TransferTask) => {
if (childObservation?.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before child update");
if (options?.onChildUpdate?.(child, childObservation) === true) childObservation = undefined;
};
try {
if (options?.shouldAbort?.()) throw new Error("Transfer cancelled");
if (childObservation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before source validation");
const sourceType = endpoints.isUpload ? "local" as const : "sftp" as const;
const targetType = endpoints.isDownload ? "local" as const : "sftp" as const;
@@ -1206,6 +1233,7 @@ async function resumeDirectoryWithDedicatedSession(
const validationError = validateTransferResumeSource(childBase, {
size: sourceStat.size,
lastModified: sourceStat.lastModified,
sizeKnown: sourceStat.sizeKnown,
}, { allowSourceGrowth });
const classified = classifyResumeSourceValidationError(validationError);
if (classified.kind === "restart") {
@@ -1217,8 +1245,7 @@ async function resumeDirectoryWithDedicatedSession(
sourceLastModified: sourceStat.lastModified,
};
} else if (classified.kind === "modified") {
attentionCount += 1;
options?.onChildUpdate?.({
publishChild({
...childBase,
status: "attention",
error: classified.message || validationError || "Source was modified",
@@ -1227,6 +1254,7 @@ async function resumeDirectoryWithDedicatedSession(
phase: undefined,
retryable: true,
});
attentionCount += 1;
return;
} else if (classified.kind === "fatal") {
throw new Error(classified.message || validationError || "Resume validation failed");
@@ -1236,56 +1264,71 @@ async function resumeDirectoryWithDedicatedSession(
// zero-byte plans (`||` would incorrectly promote to grown size).
const plannedBytes = Number(childBase.totalBytes);
const hasPlannedBytes = Number.isFinite(plannedBytes) && plannedBytes >= 0;
// Stat-less SCP sources report size as a placeholder 0; keep the
// planned size rather than re-planning to a fake zero.
const sourceSizeKnown = sourceStat.sizeKnown !== false && Number.isFinite(sourceStat.size);
childBase = {
...childBase,
totalBytes: allowSourceGrowth
? (hasPlannedBytes ? plannedBytes : sourceStat.size)
: (sourceStat.size || childBase.totalBytes),
sourceLastModified: allowSourceGrowth
&& hasPlannedBytes
&& sourceStat.size > plannedBytes
? (childBase.sourceLastModified ?? sourceStat.lastModified)
: (sourceStat.lastModified ?? childBase.sourceLastModified),
totalBytes: !sourceSizeKnown
? childBase.totalBytes
: allowSourceGrowth
? (hasPlannedBytes ? plannedBytes : sourceStat.size)
: (sourceStat.size || childBase.totalBytes),
sourceLastModified: !sourceSizeKnown
? (sourceStat.lastModified ?? childBase.sourceLastModified)
: allowSourceGrowth
&& hasPlannedBytes
&& sourceStat.size > plannedBytes
? (childBase.sourceLastModified ?? sourceStat.lastModified)
: (sourceStat.lastModified ?? childBase.sourceLastModified),
};
}
// Re-check abort after async stat before inserting a transferring child.
if (options?.shouldAbort?.()) throw new Error("Transfer cancelled");
options?.onChildUpdate?.(childBase);
const streamResult = await runTransferAndWaitForOwner(childBase, () => {
// Publish only after admission, while identity changes are observed.
options?.onChildUpdate?.(childBase);
return bridge.startStreamTransfer!({
transferId: childId,
// Lifecycle events must carry the current identity even while
// large-history renderer child updates remain batched.
parentTaskId: childBase.parentTaskId,
directoryEntryIndex: childBase.directoryEntryIndex,
directoryEntryIdentity: childBase.directoryEntryIdentity,
sourcePath: file.sourcePath,
targetPath: file.targetPath,
sourceType,
targetType,
sourceSftpId,
targetSftpId,
sourceHostId: endpoints.sourceHost?.id,
targetHostId: endpoints.targetHost?.id,
totalBytes: Number.isFinite(childBase.totalBytes)
? childBase.totalBytes
: (file.size || undefined),
resumable: parent.resumable !== false,
checkpointBytes: childBase.checkpointBytes ?? 0,
resumeStage: childBase.resumeStage,
downloadCheckpointBytes: childBase.downloadCheckpointBytes,
uploadCheckpointBytes: childBase.uploadCheckpointBytes,
sourceFingerprint: childBase.sourceFingerprint,
skipAdmission: true,
});
}, () => options?.shouldAbort?.() === true, pausedAtResume.get(childId),
resetPersistedCheckpoint ? completedAtRestart.get(childId) : undefined,
// Drop queued UI updates at the ownership change itself: waiting
// for this invocation's reply may allow an intervening batch flush.
onOwnerChanged,
(observation) => { childObservation = observation; return true; }, childObservation);
const streamResult = await runTransferAndWaitForOwner(childBase, () => bridge.startStreamTransfer!({
transferId: childId,
// Lifecycle events must carry the current identity even while
// large-history renderer child updates remain batched.
parentTaskId: childBase.parentTaskId,
directoryEntryIndex: childBase.directoryEntryIndex,
directoryEntryIdentity: childBase.directoryEntryIdentity,
sourcePath: file.sourcePath,
targetPath: file.targetPath,
sourceType,
targetType,
sourceSftpId,
targetSftpId,
sourceHostId: endpoints.sourceHost?.id,
targetHostId: endpoints.targetHost?.id,
totalBytes: Number.isFinite(childBase.totalBytes)
? childBase.totalBytes
: (file.size || undefined),
resumable: parent.resumable !== false,
checkpointBytes: childBase.checkpointBytes ?? 0,
resumeStage: childBase.resumeStage,
downloadCheckpointBytes: childBase.downloadCheckpointBytes,
uploadCheckpointBytes: childBase.uploadCheckpointBytes,
sourceFingerprint: childBase.sourceFingerprint,
skipAdmission: true,
}), () => options?.shouldAbort?.() === true, pausedAtResume.get(childId));
if (childObservation?.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before child update");
if (streamResult?.error || streamResult?.cancelled) {
throw new Error(streamResult.error || "Transfer cancelled");
}
completedCount += 1;
options?.onChildUpdate?.({
publishChild({
...childBase,
status: "completed",
transferredBytes: Number.isFinite(childBase.totalBytes)
@@ -1297,13 +1340,21 @@ async function resumeDirectoryWithDedicatedSession(
reconnectRequired: false,
phase: undefined,
});
countedCompleted = true;
completedCount += 1;
bumpParentProgress(0);
} catch (error) {
if (options?.shouldAbort?.() || /cancelled|canceled/i.test(error instanceof Error ? error.message : String(error))) {
throw error instanceof Error ? error : new Error(String(error));
}
failedCount += 1;
options?.onChildUpdate?.({
// Another invocation owns this ID now. Report this walk's failure
// without replacing the winner or recreating its compacted row.
if (error instanceof TransferOwnerChangedError || childObservation?.hasIdentityConflict()) {
options?.onChildSuperseded?.(childId);
return;
}
publishChild({
...childBase,
status: "failed",
error: error instanceof Error ? error.message : String(error),
@@ -1312,6 +1363,8 @@ async function resumeDirectoryWithDedicatedSession(
reconnectRequired: false,
phase: undefined,
});
} finally {
childObservation?.dispose();
}
},
);
@@ -1322,6 +1375,10 @@ async function resumeDirectoryWithDedicatedSession(
if (result?.error) throw new Error(result.error);
// Commit deferred child outcomes before deciding success or promoting a stage.
// Async connection cleanup must not outlive provisional completion evidence.
options?.flushChildUpdates?.();
if (attentionCount > 0 && failedCount === 0 && completedCount + attentionCount >= totalFiles) {
return {
success: false,
@@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveDownloadSourceSnapshot } from "./downloadSourceSnapshot.ts";
const stat = (overrides: Partial<SftpStatResult> = {}): SftpStatResult => ({
name: "f",
size: 50_000,
type: "file",
lastModified: 0,
sizeKnown: true,
...overrides,
});
for (const listedSize of [25_000, 100_000]) {
test(`recreated file uses the current 50k size rather than listed ${listedSize}`, async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async (_id, path, encoding) => {
assert.equal(path, "/tmp/f");
assert.equal(encoding, "auto");
return stat();
},
"sftp-1", "/tmp/f", "auto",
);
assert.deepEqual(snapshot, { size: 50_000, isDirectory: false });
assert.notEqual(snapshot.size, listedSize);
});
}
test("a stale file entry replaced by a directory uses directory routing", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 0, type: "directory" }),
"sftp-1", "/tmp/x", "auto",
);
assert.deepEqual(snapshot, { size: 0, isDirectory: true });
});
test("a stale directory entry replaced by a file uses file routing", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 12, type: "file" }),
"sftp-1", "/tmp/x", "auto",
);
assert.deepEqual(snapshot, { size: 12, isDirectory: false });
});
test("missing, failed and unsupported stats reject instead of using a stale listing", async () => {
const rejected = [
undefined,
async () => null as unknown as SftpStatResult,
async () => { throw new Error("File not found"); },
async () => stat({ type: "symlink" }),
async () => stat({ size: Number.NaN }),
async () => stat({ size: -1 }),
];
for (const candidate of rejected) {
await assert.rejects(
resolveDownloadSourceSnapshot(candidate, "sftp-1", "/tmp/f", "auto"),
/Cannot verify the current remote source before download/,
);
}
});
test("stat-less SCP file leaves sizing to the transfer instead of using listed bytes", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 0, sizeKnown: false }),
"scp-1", "/tmp/f", "auto",
);
assert.deepEqual(snapshot, { size: undefined, isDirectory: false });
});
test("SCP links retain their resolved file or directory routing without using link size", async () => {
for (const target of ["file", "directory"] as const) {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ type: "symlink", size: 8 }),
"scp-1", "/tmp/link", "auto",
async (_id, parent, encoding) => {
assert.equal(parent, "/tmp");
assert.equal(encoding, "auto");
return [{ name: "link", type: "symlink", linkTarget: target, size: "8 bytes", lastModified: "" }];
},
);
assert.deepEqual(snapshot, { size: undefined, isDirectory: target === "directory" });
}
});
test("SCP link whose current target cannot be confirmed stops safely", async () => {
for (const entries of [
[],
[{ name: "link", type: "symlink" as const, linkTarget: null, size: "8 bytes", lastModified: "" }],
[{ name: "link", type: "file" as const, size: "8 bytes", lastModified: "" }],
]) {
await assert.rejects(
resolveDownloadSourceSnapshot(
async () => stat({ type: "symlink" }),
"scp-1", "/tmp/link", "auto", async () => entries,
),
/Cannot verify the current remote source before download/,
);
}
});
test("directory routing does not require a file byte count", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: Number.NaN, sizeKnown: false, type: "directory" }),
"sftp-1", "/tmp/d", "auto",
);
assert.deepEqual(snapshot, { size: 0, isDirectory: true });
});
@@ -0,0 +1,67 @@
import type { SftpFilenameEncoding } from "../../../domain/models/sftp";
import type { RemoteFile } from "../../../domain/models/workspace";
import { getFileName, getParentPath } from "./utils";
export type DownloadSourceSnapshot = {
/** Unknown for stat-less SCP files and links; the transfer reads its wire size. */
size: number | undefined;
isDirectory: boolean;
};
type StatSftp = (
sftpId: string,
path: string,
encoding?: SftpFilenameEncoding,
) => Promise<SftpStatResult>;
type ListSftp = (
sftpId: string,
path: string,
encoding?: SftpFilenameEncoding,
) => Promise<RemoteFile[]>;
const sourceUnavailable = () => new Error("Cannot verify the current remote source before download");
/** A stale listing must never supply the size or type of a new download. */
export const resolveDownloadSourceSnapshot = async (
statSftp: StatSftp | undefined,
sftpId: string,
sourcePath: string,
encoding: SftpFilenameEncoding | undefined,
listSftp?: ListSftp,
): Promise<DownloadSourceSnapshot> => {
if (!statSftp) throw sourceUnavailable();
let stat: SftpStatResult | null;
try {
stat = await statSftp(sftpId, sourcePath, encoding);
} catch (cause) {
throw new Error("Cannot verify the current remote source before download", { cause });
}
if (!stat) {
throw sourceUnavailable();
}
if (stat.type === "directory") return { size: 0, isDirectory: true };
if (stat.type === "symlink") {
// SFTP STAT follows links; legacy SCP describes the link node. Re-list its
// parent to resolve the current target kind rather than trusting the pane.
if (!listSftp) throw sourceUnavailable();
let entries: RemoteFile[];
try {
entries = await listSftp(sftpId, getParentPath(sourcePath), encoding);
} catch (cause) {
throw new Error("Cannot verify the current remote source before download", { cause });
}
const current = entries.find((entry) => entry.name === getFileName(sourcePath));
if (current?.type !== "symlink"
|| (current.linkTarget !== "file" && current.linkTarget !== "directory")) {
throw sourceUnavailable();
}
// The link's own size is never a valid file plan; SCP's wire header is.
return { size: undefined, isDirectory: current.linkTarget === "directory" };
}
if (stat.type !== "file") throw sourceUnavailable();
if (stat.sizeKnown === false) return { size: undefined, isDirectory: false };
if (!Number.isSafeInteger(stat.size) || stat.size < 0) throw sourceUnavailable();
return { size: stat.size, isDirectory: false };
};
+13 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isMissingStatError } from "./errors";
import { isMissingStatError, unwrapSftpIpcError } from "./errors";
test("isMissingStatError accepts only true path absence codes", () => {
for (const code of [2, "ENOENT", "NO_SUCH_FILE", "SSH_FX_NO_SUCH_FILE"] as const) {
@@ -64,3 +64,15 @@ test("isMissingStatError rejects unsupported LSTAT and other failures", () => {
false,
);
});
test("unwrapSftpIpcError strips the Electron IPC wrapper", () => {
assert.equal(
unwrapSftpIpcError(
new Error("Error invoking remote method 'netcatty:sftp:delete': Error: Permission denied"),
),
"Permission denied",
);
assert.equal(unwrapSftpIpcError(new Error("Permission denied")), "Permission denied");
assert.equal(unwrapSftpIpcError("channel closed"), "channel closed");
});
+9
View File
@@ -18,4 +18,13 @@ export const isSessionError = (err: unknown): boolean => {
);
};
const SFTP_IPC_ERROR_PREFIX = /^Error invoking remote method 'netcatty:[^']+':\s*/i;
/** Drop Electron IPC wrapper so dialogs can show the server error. */
export function unwrapSftpIpcError(err: unknown): string {
const raw = err instanceof Error ? err.message : String(err ?? "");
const unwrapped = raw.replace(SFTP_IPC_ERROR_PREFIX, "").replace(/^Error:\s*/, "").trim();
return unwrapped || raw;
}
export { isMissingStatError } from "../../../domain/sftpStatError";
@@ -0,0 +1,174 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge';
import { JSDOM } from 'jsdom';
import {
startSftpFileDrag, takeLocalFileDragSources, getLocalFileDragSources,
clearLocalFileDrag, clearLocalFileDragForPane, localDragPathKey, localFileDragMoveEffect,
} from './localFileDrag';
function setup(t: test.TestContext) {
const dom = new JSDOM('<!doctype html><html><body></body></html>');
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
Object.defineProperty(globalThis, 'window', { value: dom.window, configurable: true });
const calls: { requestId: string; paths: string[] }[] = [];
const cancels: string[] = [];
const errors: string[] = [];
const remote: unknown[] = [];
const bridge = {
startLocalFileDrag: async (payload) => { calls.push(payload); return { started: true }; },
cancelLocalFileDrag: (id) => cancels.push(id),
getPathForFile: (file) => (file as unknown as { path: string }).path,
} as unknown as NetcattyBridge;
Object.defineProperty(window, "netcatty", { value: bridge, configurable: true });
t.after(() => {
clearLocalFileDrag();
dom.window.close();
if (previous) Object.defineProperty(globalThis, 'window', previous);
else Reflect.deleteProperty(globalThis, 'window');
});
const transfer = (paths: string[] = []) => ({
types: ['Files'], files: paths.map((path) => ({ path })),
effectAllowed: '', setData: (...args: string[]) => remote.push(args),
}) as unknown as DataTransfer;
const sources = [
{ name: 'certificate.txt', sourcePath: '/local', sourceConnectionId: 'local', isDirectory: false },
{ name: 'folder', sourcePath: '/another path', sourceConnectionId: 'local', isDirectory: true },
];
let prevented = 0;
const start = (isLocal: boolean | undefined = true, selection = sources) => startSftpFileDrag({
event: { dataTransfer: transfer(), preventDefault: () => { prevented++; } },
paneId: 'pane', connection: { id: 'local', isLocal }, sources: selection, side: 'left',
onRemoteDrag: (...args) => remote.push(args), onError: (error) => errors.push(error),
});
return { calls, cancels, errors, remote, transfer, sources, start, prevented: () => prevented, dom };
}
test('local multi-selection retains individual tree paths and never exports plain text', async (t) => {
const h = setup(t);
h.start();
assert.equal(h.prevented(), 1);
assert.equal(h.remote.length, 0);
assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt', '/another path/folder']);
const payload = h.transfer([...h.calls[0].paths].reverse());
assert.equal(getLocalFileDragSources(payload)?.length, 2);
assert.deepEqual(takeLocalFileDragSources(payload), h.sources.map((source) => ({ ...source, side: 'left' })));
assert.equal(takeLocalFileDragSources(payload), null, 'a native gesture is consumed exactly once');
assert.equal(getLocalFileDragSources(payload), null);
});
test('native paths retain symlink-parent segments and match the returning internal drop', (t) => {
const h = setup(t);
const sources = [{ ...h.sources[0], sourcePath: '/local/link/.././folder' }];
h.start(true, sources);
assert.deepEqual(h.calls[0].paths, ['/local/link/.././folder/certificate.txt']);
const payload = h.transfer(h.calls[0].paths);
assert.deepEqual(takeLocalFileDragSources(payload), sources.map(source => ({ ...source, side: 'left' })));
assert.equal(takeLocalFileDragSources(payload), null);
});
test('remote origin preserves HTML payload and callbacks, including absent isLocal', (t) => {
const h = setup(t);
h.start(false);
assert.equal(h.prevented(), 0);
assert.equal(h.calls.length, 0);
assert.deepEqual(h.remote, [['text/plain', 'certificate.txt\nfolder'], [h.sources, 'left']]);
startSftpFileDrag({ event: { dataTransfer: h.transfer(), preventDefault: () => assert.fail('remote drag canceled') },
paneId: 'remote', connection: { id: 'remote' }, sources: h.sources, side: 'right',
onRemoteDrag: () => {}, onError: assert.fail });
assert.equal(h.calls.length, 0);
});
test('unrelated external files cannot reuse a previous local gesture', (t) => {
const h = setup(t);
h.start();
assert.equal(takeLocalFileDragSources(h.transfer(['/different/certificate.txt'])), null);
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
assert.equal(takeLocalFileDragSources(h.transfer(['/local/certificate.txt'])), null, 'partial selection is not an internal transfer');
});
test('local failure cancels without text fallback and stale async errors cannot clear a newer gesture', async (t) => {
const h = setup(t);
let reject!: (error: Error) => void;
netcattyBridge.require().startLocalFileDrag = () => new Promise((_resolve, rejectPromise) => { reject = rejectPromise; });
h.start();
const oldReject = reject;
h.start();
oldReject(new Error('obsolete'));
await new Promise((resolve) => setImmediate(resolve));
assert.equal(h.errors.length, 0);
assert.ok(getLocalFileDragSources(h.transfer()));
reject(new Error('file disappeared'));
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(h.errors, ['file disappeared']);
assert.equal(getLocalFileDragSources(h.transfer()), null);
assert.equal(h.remote.length, 0);
});
test('native state is cleared on physical cancellation, external completion, connection disposal and new gestures', async (t) => {
const h = setup(t);
for (const event of [new h.dom.window.KeyboardEvent('keydown', { key: 'Escape' }),
new h.dom.window.MouseEvent('mousemove', { buttons: 0 }), new h.dom.window.MouseEvent('mousedown'),
new h.dom.window.Event('blur'), new h.dom.window.Event('pagehide')]) {
h.start();
await Promise.resolve();
window.dispatchEvent(event);
assert.equal(getLocalFileDragSources(h.transfer()), null, event.type);
}
h.start();
clearLocalFileDragForPane('another-pane');
assert.ok(getLocalFileDragSources(h.transfer()));
clearLocalFileDragForPane('pane');
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
h.start(false);
assert.equal(getLocalFileDragSources(h.transfer()), null);
});
test('invalid local selections and missing bridge are rejected; parent entry is excluded', (t) => {
const h = setup(t);
h.start(true, [{ ...h.sources[0], name: '..' }]);
assert.equal(h.calls.length, 0);
h.start(true, [{ ...h.sources[0], sourceConnectionId: 'remote' }]);
assert.equal(h.calls.length, 0);
h.start(true, [h.sources[0], { ...h.sources[0], name: '..' }]);
assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt']);
netcattyBridge.require().startLocalFileDrag = undefined;
h.start();
assert.equal(h.errors.length, 3);
assert.equal(h.remote.length, 0);
});
test('path matching preserves POSIX whitespace, Unicode and backslashes, and accepts Windows separators', () => {
assert.equal(localDragPathKey('C:\\Users\\david\\certificate.pem'), 'C:/Users/david/certificate.pem');
assert.equal(localDragPathKey('\\\\server\\share\\folder'), '//server/share/folder');
assert.equal(localDragPathKey('/local/é \\name '), '/local/é \\name ');
assert.notEqual(localDragPathKey('/local/A'), localDragPathKey('/local/a'));
});
test('local move accepts the copy-only native transport on Windows/Linux without changing the operation', () => {
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyLink' }), 'copy');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copy' }), 'copy');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'all' }), 'move');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyMove' }), 'move');
});
test('native drop cleanup survives the browser microtask checkpoint before React receives the drop', async (t) => {
const h = setup(t);
h.start();
window.dispatchEvent(new h.dom.window.Event('drop'));
// Unlike dispatchEvent in jsdom, native browser events can drain microtasks
// after the window capture callback, before the React root bubble callback.
await Promise.resolve();
assert.ok(getLocalFileDragSources(h.transfer()), 'capture must not erase native identity before React handles drop');
assert.deepEqual(takeLocalFileDragSources(h.transfer(h.calls[0].paths)), h.sources.map(source => ({ ...source, side: 'left' })));
await new Promise(resolve => setTimeout(resolve, 5));
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
window.dispatchEvent(new h.dom.window.Event('drop'));
await new Promise(resolve => setTimeout(resolve, 5));
assert.equal(getLocalFileDragSources(h.transfer()), null, 'unhandled drops also release the gesture');
});
+177
View File
@@ -0,0 +1,177 @@
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { joinPath } from "./utils";
export interface LocalDragSource {
name: string;
isDirectory: boolean;
sourcePath?: string;
sourceConnectionId?: string;
targetPath?: string;
side: "left" | "right";
}
interface DragSession {
requestId: string;
paneId: string;
connectionId: string;
paths: string[];
sources: LocalDragSource[];
started?: boolean;
}
// Windows separators can differ between the SFTP UI and Electron webUtils.
// POSIX backslashes, whitespace, and case must remain significant.
export function localDragPathKey(value: string): string {
if (/^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value)) {
return value.replace(/\\/g, "/").replace(/\/$/, "");
}
return value.length > 1 ? value.replace(/\/$/, "") : value;
}
class LocalFileDragState {
session: DragSession | null = null;
clear(requestId?: string) {
if (!requestId || this.session?.requestId === requestId) this.session = null;
}
take(paths: string[]): LocalDragSource[] | null {
const session = this.session;
this.clear();
if (!session || paths.length === 0 || paths.some((path) => !path)) return null;
const expected = new Set(session.paths.map(localDragPathKey));
const actual = new Set(paths.map(localDragPathKey));
if (expected.size !== actual.size || [...expected].some((path) => !actual.has(path))) return null;
return session.sources;
}
}
const state = new LocalFileDragState();
let detach: (() => void) | undefined;
export function clearLocalFileDrag(requestId?: string) {
if (requestId && state.session?.requestId !== requestId) return;
const previous = state.session;
state.clear();
detach?.();
detach = undefined;
if (previous) netcattyBridge.get()?.cancelLocalFileDrag?.(previous.requestId);
}
export function clearLocalFileDragForPane(paneId: string) {
if (state.session?.paneId === paneId) clearLocalFileDrag();
}
function observeGestureEnd() {
let dropCleanupTimer: ReturnType<typeof setTimeout> | undefined;
// Electron has no cross-platform native-drag completion callback. A canceled
// HTML drag's dragend is not a native completion signal. Clear on drop and
// on the next physical input/focus transition, including Escape and returning
// after a drop outside the window. Never retain state into a new gesture.
const clear = () => clearLocalFileDrag();
const key = (event: KeyboardEvent) => { if (event.key === "Escape") clear(); };
const move = (event: MouseEvent) => { if (state.session?.started && event.buttons === 0) clear(); };
const drop = () => {
const requestId = state.session?.requestId;
// Native event dispatch can run microtasks BETWEEN capture and React's
// bubble listener. Use a macrotask so the row/pane can consume the gesture.
dropCleanupTimer = setTimeout(() => { if (requestId) clearLocalFileDrag(requestId); }, 0);
};
// preventDefault() on dragstart produces a synthetic mouseup in Chromium.
// It must not cancel the native handoff. Observe later input instead.
window.addEventListener("mousedown", clear, true);
window.addEventListener("mousemove", move, true);
window.addEventListener("keydown", key, true);
window.addEventListener("blur", clear);
window.addEventListener("pagehide", clear);
window.addEventListener("drop", drop, true);
detach = () => {
if (dropCleanupTimer !== undefined) clearTimeout(dropCleanupTimer);
window.removeEventListener("mousedown", clear, true);
window.removeEventListener("mousemove", move, true);
window.removeEventListener("keydown", key, true);
window.removeEventListener("blur", clear);
window.removeEventListener("pagehide", clear);
window.removeEventListener("drop", drop, true);
};
}
type DragEventLike = Pick<DragEvent, "dataTransfer" | "preventDefault">;
export function startSftpFileDrag({ event, paneId, connection, sources, side, onRemoteDrag, onError }: {
event: DragEventLike;
paneId: string;
connection?: { id: string; isLocal?: boolean } | null;
sources: Omit<LocalDragSource, "side">[];
side: "left" | "right";
onRemoteDrag: (sources: Omit<LocalDragSource, "side">[], side: "left" | "right") => void;
onError: (message: string) => void;
}) {
clearLocalFileDrag();
if (connection?.isLocal !== true) {
event.dataTransfer!.effectAllowed = "copyMove";
event.dataTransfer!.setData("text/plain", sources.map((file) => file.name).join("\n"));
onRemoteDrag(sources, side);
return;
}
event.preventDefault();
const bridge = netcattyBridge.get();
if (!bridge?.startLocalFileDrag) {
onError("Native file drag is unavailable. Restart Netcatty after updating.");
return;
}
const files = sources.filter((source) => source.name !== "..");
if (!files.length || files.some((file) => !file.sourcePath || file.sourceConnectionId !== connection.id)) {
onError("The local file selection is no longer available.");
return;
}
const requestId = crypto.randomUUID();
const paths = [...new Set(files.map((file) => joinPath(file.sourcePath!, file.name)))];
state.session = { requestId, paneId, connectionId: connection.id, paths, sources: files.map((file) => ({ ...file, side })) };
observeGestureEnd();
// Send during dragstart, without awaiting in the renderer. Do not interpret
// the reply as a completed transfer or use it to clear an active gesture.
try {
void bridge.startLocalFileDrag({ requestId, paths }).then((result) => {
if (result.started && state.session?.requestId === requestId) state.session.started = true;
if (!result.started && state.session?.requestId === requestId) {
clearLocalFileDrag(requestId);
if (result.error) onError(result.error);
}
}).catch((error: unknown) => {
if (state.session?.requestId !== requestId) return;
clearLocalFileDrag(requestId);
onError(error instanceof Error ? error.message : "Unable to drag local files");
});
} catch (error) {
clearLocalFileDrag(requestId);
onError(error instanceof Error ? error.message : "Unable to drag local files");
}
}
export function getLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null {
return dataTransfer.types.includes("Files") ? state.session?.sources ?? null : null;
}
export function localFileDragMoveEffect(dataTransfer: Pick<DataTransfer, "effectAllowed">): "copy" | "move" {
// Electron's Windows/Linux native source advertises COPY | LINK, not MOVE.
// Negotiate an allowed transport effect; our existing same-pane callback is
// responsible for the actual local move (the OS must not delete originals).
return ["all", "copyMove", "linkMove", "move"].includes(dataTransfer.effectAllowed) ? "move" : "copy";
}
export function takeLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null {
if (!state.session) return null;
const bridge = netcattyBridge.get();
const session = state.session;
try {
return state.take(Array.from(dataTransfer.files).map((file) => bridge?.getPathForFile?.(file) ?? ""));
} catch {
state.clear();
return null;
} finally {
detach?.();
detach = undefined;
bridge?.cancelLocalFileDrag?.(session.requestId);
}
}
@@ -334,7 +334,8 @@ test("live directory download rejects a Windows backslash traversal entry", asyn
}
});
test("live folder settles a superseded child whose completed row was compacted", async () => {
for (const ownerChange of ["same", "changed-active", "changed-completed"] as const) {
test(`live folder settles superseded ownership without clobbering its replacement: ${ownerChange}`, async () => {
const { sftpTransferCenterStore } = await import("../sftpTransferCenterStore");
const previousWindow = (globalThis as { window?: unknown }).window;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
@@ -355,10 +356,18 @@ test("live folder settles a superseded child whose completed row was compacted",
startStreamTransfer: async (options: { transferId: string }) => {
childId = options.transferId;
sftpTransferCenterStore.publishOwner("live-compacted-owner", tasks);
// The winning invocation has already completed; history compaction drops its row.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 1, totalBytes: 1, lifecycleEpoch: 0,
});
if (ownerChange !== "same") {
const current = sftpTransferCenterStore.getTask(childId)!;
sftpTransferCenterStore.admitTaskRun({ ...current, directoryEntryIdentity: "b".repeat(64) });
}
if (ownerChange !== "changed-active") {
// The winning invocation completed; history compaction drops its row.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 1, totalBytes: 1, lifecycleEpoch: 0,
});
}
tasks = [...sftpTransferCenterStore.getSnapshot().tasks];
transfersRef.current = tasks;
return { superseded: true };
},
} };
@@ -387,10 +396,15 @@ test("live folder settles a superseded child whose completed row was compacted",
new Promise<"still-waiting">((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
]);
assert.ok(childId);
assert.equal(sftpTransferCenterStore.getTask(childId), undefined);
assert.equal(sftpTransferCenterStore.getTask(root.id)?.directoryResumeCheckpoint?.completedEntries, 1);
if (ownerChange === "changed-active") {
assert.equal(tasks.find((task) => task.id === childId)?.status, "transferring");
assert.equal(tasks.find((task) => task.id === childId)?.directoryEntryIdentity, "b".repeat(64));
} else {
assert.equal(tasks.find((task) => task.id === childId), undefined, "old waiter must not reinsert a compacted child");
assert.equal(sftpTransferCenterStore.getTask(root.id)?.directoryResumeCheckpoint?.completedEntries, 1);
}
assert.notEqual(result, "still-waiting", "compacted completion must settle the live folder");
assert.equal(result, 0);
assert.equal(result, ownerChange === "same" ? 0 : 1);
} finally {
cancelledTasksRef.current.add(root.id);
await running?.catch(() => {});
@@ -404,3 +418,4 @@ test("live folder settles a superseded child whose completed row was compacted",
}
});
}
@@ -1,5 +1,5 @@
import { reconcileSupersededControls } from "./globalSftpTransferControl";
import { runTransferAndWaitForOwner } from "./waitForTransferOwner";
import { runTransferAndWaitForOwner, TransferOwnerChangedError } from "./waitForTransferOwner";
import { useCallback, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
import type { Host, SftpFileEntry, SftpFilenameEncoding, TransferStatus, TransferTask } from "../../../domain/models";
import {
@@ -118,6 +118,10 @@ async function tryStatTransferPath(
if (!sftpId) return null;
const stat = await netcattyBridge.get()?.statSftp?.(sftpId, filePath, encoding);
if (!stat || stat.type === "directory") return null;
// Stat-less SCP endpoints report size as a placeholder 0 (sizeKnown false).
// Treat that as missing metadata so skip-unchanged is disabled rather than
// comparing a fake zero against the other endpoint (Codex P1).
if (stat.sizeKnown === false) return null;
return { size: Number(stat.size) || 0, lastModified: Number(stat.lastModified) || 0, type: stat.type };
} catch {
return null;
@@ -978,6 +982,10 @@ export function useSftpDirectoryTransferOps({
errors.push(err instanceof Error ? err : new Error(message));
return;
}
if (err instanceof TransferOwnerChangedError) {
errors.push(err);
return;
}
// Mark child as failed
setTransfers((prev) =>
prev.map((t) =>
@@ -169,3 +169,284 @@ test("fresh directory recovery authorizes only an unchanged retained pause under
store.patchTask("root", { status: "paused", lifecycleEpoch: 6 });
assert.equal(store.admitTaskRun(task, currentPause), "paused", "parent pause still wins");
});
for (const compactNewOwner of [false, true]) {
test(`superseded waiter rejects a changed identity even after new owner compaction: ${compactNewOwner}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: `changed-owner-${compactNewOwner}`, parentTaskId: `changed-root-${compactNewOwner}` };
store.upsertTasks([{ ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true }, task]);
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => {
const changed = { ...task, directoryEntryIdentity: "b".repeat(64) };
assert.equal(store.admitTaskRun(changed), "ready");
if (compactNewOwner) {
store.patchTask(changed.id, { status: "completed" });
assert.equal(store.getTask(changed.id), undefined);
}
return { superseded: true };
}, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
await settled;
store.patchTask(task.parentTaskId, { status: "completed" });
store.dismiss(task.parentTaskId);
});
assert.match(String(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
])), /identity changed/i);
});
}
test("destination rebuild restarts only the captured completion and preserves newer controls", async (t) => {
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const store = createSftpTransferCenterStore();
const task = { ...child(), parentTaskId: undefined, status: "completed" as const, checkpointBytes: 10 };
store.upsertTasks([task]);
const captured = store.getTask(task.id)!;
const restart = { ...task, status: "transferring" as const, checkpointBytes: 0, transferredBytes: 0 };
latchTransferPause(task.id);
t.after(resetTransferPauseLatchesForTests);
assert.equal(store.admitTaskRun(restart, undefined, captured), "paused");
resetTransferPauseLatchesForTests();
assert.equal(store.admitTaskRun(restart, undefined, captured), "ready");
assert.equal(store.getTask(task.id)?.checkpointBytes, 0);
store.patchTask(task.id, { status: "completed" });
assert.equal(store.admitTaskRun(restart, undefined, captured), "completed", "new completion must not be restarted");
store.patchTask(task.id, { status: "cancelled" });
assert.equal(store.admitTaskRun(restart, undefined, captured), "cancelled");
});
test("destination rebuild waiting on pause reuses a newer compacted completion", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "restart-wait-child", parentTaskId: "restart-wait-root", directoryEntryIndex: 1 };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, { ...task, status: "completed" }]);
const captured = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort, undefined, captured);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
// An unrelated lifecycle emit must not pin the old completion in the observation.
store.patchTask(root.id, { reconnectRequired: true });
assert.equal(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 230)),
]), "still-waiting", "old completion cannot finish recovery while a new transfer is still needed");
assert.equal(starts, 0);
resetTransferPauseLatchesForTests();
store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 1 });
store.upsertTasks([{ ...task, id: "restart-wait-first", directoryEntryIndex: 0, status: "completed" }]);
store.patchTask(task.id, { status: "completed", lifecycleEpoch: 2 });
assert.equal(store.getTask(task.id), undefined);
assert.equal(await settled, "completed");
assert.equal(starts, 0, "new completion after stage rebuild must be reused even when its row was compacted");
});
test("paused admission cannot reclaim an identity replaced while it waited", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "paused-displaced", parentTaskId: undefined };
store.upsertTasks([{ ...task, status: "paused" }]);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
await settled;
store.patchTask(task.id, { status: "completed" });
store.dismiss(task.id);
});
store.upsertTasks([{ ...task, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
assert.match(await settled, /identity changed/i);
assert.equal(starts, 0);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
for (const identityChangesDuringWait of [false, true]) {
test(`paused recovery distinguishes initial stale identity from later ownership: changed=${identityChangesDuringWait}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: `paused-origin-${identityChangesDuringWait}`, parentTaskId: `paused-origin-root-${identityChangesDuringWait}` };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, {
...task, status: identityChangesDuringWait ? "failed" : "paused",
directoryEntryIdentity: identityChangesDuringWait ? task.directoryEntryIdentity : "b".repeat(64),
}]);
const initialPause = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
let conflicts = 0;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort,
identityChangesDuringWait ? undefined : initialPause, undefined, () => { conflicts += 1; });
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
// This captures the prior failed result, or republishes the unchanged
// initial old identity. Neither is evidence of a replacement by itself.
store.patchTask(root.id, { reconnectRequired: true });
resetTransferPauseLatchesForTests();
if (identityChangesDuringWait) {
store.patchTask(task.id, { status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 });
}
const outcome = await settled;
if (identityChangesDuringWait) {
assert.match(outcome, /identity changed/i);
assert.equal(starts, 0);
assert.equal(conflicts, 1);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
} else {
assert.equal(outcome, "completed");
assert.equal(starts, 1);
assert.equal(conflicts, 0);
}
});
}
test("paused retry observes newer same-identity completion after an old failure", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "failed-then-completed", parentTaskId: "failed-then-completed-root" };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, { ...task, status: "failed" }]);
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
store.patchTask(root.id, { reconnectRequired: true });
resetTransferPauseLatchesForTests();
store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 1 });
store.patchTask(task.id, { status: "completed", lifecycleEpoch: 2 });
assert.equal(store.getTask(task.id), undefined);
assert.equal(await settled, "completed");
assert.equal(starts, 0, "a newer completed attempt must replace the captured old failure");
});
test("an unchanged owner retains its original transport rejection", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "unchanged-rejected-owner", parentTaskId: undefined };
store.upsertTasks([task]);
t.after(() => { store.patchTask(task.id, { status: "completed" }); store.dismiss(task.id); });
const error = new Error("original transport failure");
await assert.rejects(runTransferAndWaitForOwner(task, async () => { throw error; }, () => false),
(actual) => actual === error);
});
for (const activation of ["patch", "progress", "owner"] as const) {
test(`initial stale identity exemption ends when another owner activates that row: ${activation}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "activated-initial-identity", parentTaskId: undefined };
store.upsertTasks([{ ...task, status: "paused", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
const initial = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort, initial);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(task.id, { status: "completed" });
store.dismiss(task.id);
});
resetTransferPauseLatchesForTests();
if (activation === "progress") {
store.ingestBackgroundEvent({ type: "progress", transferId: task.id,
transferred: 1, lifecycleEpoch: 2, lifecycleState: "transferring" });
} else if (activation === "owner") store.patchTask(task.id, { ownerId: "replacement-owner" });
else store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 2 });
assert.match(String(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
])), /identity changed/i);
assert.equal(starts, 0);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
}
test("already active different identity is rejected before first admission", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "already-active-identity", parentTaskId: undefined };
store.upsertTasks([{ ...task, directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
t.after(() => { store.patchTask(task.id, { status: "completed" }); store.dismiss(task.id); });
let starts = 0;
let conflicts = 0;
await assert.rejects(runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => false,
undefined, undefined, () => { conflicts += 1; }), /identity changed/i);
assert.equal(starts, 0);
assert.equal(conflicts, 1);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
for (const replacementStatus of ["transferring", "completed"] as const) {
for (const oldStatus of ["completed", "failed"] as const) {
test(`deferred ${oldStatus} cannot overwrite a ${replacementStatus} replacement after waiter exit`, async () => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const task = child();
const root = { ...task, id: task.parentTaskId!, parentTaskId: undefined, isDirectory: true };
const batcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096, hasTask: () => true,
upsertTasks: (updates) => store.upsertTasks(updates),
});
store.upsertTasks([root, task]);
let observation: ReturnType<typeof store.observeTaskSettlement> | undefined;
try {
await runTransferAndWaitForOwner(task, async () => {
store.patchTask(task.id, { status: oldStatus });
return {};
}, () => false, undefined, undefined, () => batcher.discard(task.id), (value) => {
observation = value;
return true;
});
assert.ok(observation);
batcher.push({ ...task, status: oldStatus }, observation);
store.upsertTasks([{ ...task, directoryEntryIdentity: "b".repeat(64), status: replacementStatus }]);
const replacement = store.getTask(task.id);
batcher.flush();
assert.equal(store.getTask(task.id), replacement);
if (replacementStatus === "transferring") assert.equal(replacement?.directoryEntryIdentity, "b".repeat(64));
else assert.equal(replacement, undefined, "the replacement remains compacted");
assert.equal(observation.read(), undefined, "the retained observation is disposed");
} finally {
batcher.flush();
observation?.dispose();
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
}
});
}
}
@@ -1,60 +0,0 @@
import assert from 'node:assert/strict';
import test, { after } from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { publishTerminalCommandCompletion } from '../terminalCommandCompletion';
import { useSftpCommandRefresh } from './useSftpCommandRefresh';
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
after(() => { environment.IS_REACT_ACT_ENVIRONMENT = previous; });
test('completion refresh is coalesced, visible, idle and bound to its original pane', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let count = 0;
let options = {
sessionId: 'terminal-1', enabled: true, visible: true, busy: false,
matchesTerminal: true, paneId: 'pane-1', connectionId: 'connection-1',
path: '/browsed', connected: true, refresh: async () => { count += 1; },
};
function Probe() { useSftpCommandRefresh(options); return null; }
let renderer: ReactTestRenderer;
await act(async () => { renderer = create(React.createElement(Probe)); });
const update = async (patch: Partial<typeof options>) => {
options = { ...options, ...patch };
await act(async () => { renderer.update(React.createElement(Probe)); });
};
const finish = async () => { await act(async () => { t.mock.timers.tick(250); }); };
publishTerminalCommandCompletion('another-terminal');
await finish();
assert.equal(count, 0);
publishTerminalCommandCompletion('terminal-1');
publishTerminalCommandCompletion('terminal-1');
await finish();
assert.equal(count, 1);
for (const patch of [{ enabled: false }, { visible: false }, { connected: false }, { matchesTerminal: false }]) {
await update(patch);
publishTerminalCommandCompletion('terminal-1');
await finish();
assert.equal(count, 1);
await update({ enabled: true, visible: true, busy: false, connected: true, matchesTerminal: true });
}
await update({ busy: true });
publishTerminalCommandCompletion('terminal-1');
await finish();
assert.equal(count, 1);
await update({ busy: false });
await finish();
assert.equal(count, 2);
for (const patch of [{ path: '/new' }, { paneId: 'pane-2' }, { connectionId: 'connection-2' }, { sessionId: 'terminal-2' }]) {
publishTerminalCommandCompletion(options.sessionId);
await update(patch);
await finish();
assert.equal(count, 2);
}
publishTerminalCommandCompletion(options.sessionId);
await act(async () => { renderer.unmount(); });
await finish();
assert.equal(count, 2);
});
@@ -1,56 +0,0 @@
import { useEffect, useRef } from 'react';
import { subscribeTerminalCommandCompletion } from '../terminalCommandCompletion';
interface Options {
sessionId: string | null;
enabled: boolean;
visible: boolean;
busy: boolean;
matchesTerminal: boolean;
paneId: string;
connectionId: string | null;
path: string | null;
connected: boolean;
refresh: () => Promise<void>;
}
/** Coalesce completion bursts; never poll or carry refreshes across pane changes. */
export function useSftpCommandRefresh(options: Options): void {
const latest = useRef(options);
latest.current = options;
const drain = useRef(() => {});
useEffect(() => {
if (!options.enabled || !options.visible || !options.sessionId) return;
let timer: ReturnType<typeof setTimeout> | undefined;
let pending = false;
let refreshing = false;
let disposed = false;
const eligible = () => {
const live = latest.current;
return !disposed && live.enabled && live.visible && live.connected && live.matchesTerminal
&& live.sessionId === options.sessionId && live.paneId === options.paneId
&& live.connectionId === options.connectionId && live.path === options.path;
};
const schedule = () => {
if (!pending || refreshing || latest.current.busy || !eligible()) return;
clearTimeout(timer);
timer = setTimeout(() => {
if (!eligible() || latest.current.busy) return;
pending = false;
refreshing = true;
void latest.current.refresh().catch(() => {}).finally(() => {
refreshing = false;
schedule();
});
}, 250);
};
drain.current = schedule;
const unsubscribe = subscribeTerminalCommandCompletion((sessionId) => {
if (sessionId !== options.sessionId || !eligible()) return;
pending = true;
schedule();
});
return () => { disposed = true; clearTimeout(timer); unsubscribe(); drain.current = () => {}; };
}, [options.enabled, options.visible, options.sessionId, options.paneId, options.connectionId, options.path]);
useEffect(() => { drain.current(); }, [options.busy]);
}
@@ -62,6 +62,8 @@ export interface SftpConnectOptions {
sourceSessionId?: string;
/** Fail instead of opening a new route when the requested terminal transport cannot be reused. */
requireSourceSessionReuse?: boolean;
/** When false, never attach SFTP to a live terminal SSH transport. */
reuseTransport?: boolean;
/** Prevent a forced terminal-drop route rebind from sharing an older open. */
connectRequestKey?: string;
/** Identifies the exact tab and connection created for a route-bound request. */
@@ -1074,6 +1076,7 @@ export const useSftpConnections = ({
openOptions: {
sessionId: sftpSessionId,
...credentials,
...(options?.reuseTransport === false ? { reuseTransport: false } : {}),
},
});
@@ -85,6 +85,60 @@ test("first-open follow uses a fresh terminal cwd instead of the cached home pat
await act(async () => renderer?.unmount());
});
test("first-open follow stays put when the terminal cwd is still an unresolved ~", async () => {
const navigatedPaths: string[] = [];
const connection = {
id: "conn-1",
hostId: "host-1",
currentPath: "/root",
homeDir: "/root",
status: "connected",
isLocal: false,
};
const sftpRef = {
current: {
leftPane: { connection, loading: false },
navigateTo: async (_side: "left", path: string) => {
navigatedPaths.push(path);
connection.currentPath = path;
return "reached" as const;
},
},
};
let renderer: ReactTestRenderer | null = null;
function Probe() {
useSftpFollowTerminalCwd({
activeSessionId: "session-1",
activeTerminalCwd: "~",
canFollowTerminalCwd: true,
connectionId: connection.id,
connectionIsLocal: connection.isLocal,
connectionLoading: false,
connectionPath: connection.currentPath,
connectionStatus: connection.status,
effectiveFollowTerminalCwd: true,
followTerminalCwdHost: host,
hasActiveWork: false,
isVisible: true,
ownerPanelOpen: true,
onGetTerminalCwd: async () => "~",
onPendingFollowOverride: () => {},
sftpRef,
});
return null;
}
await act(async () => {
renderer = create(React.createElement(Probe));
await new Promise((resolve) => setImmediate(resolve));
});
assert.deepEqual(navigatedPaths, []);
assert.equal(connection.currentPath, "/root");
await act(async () => renderer?.unmount());
});
test("first-open follow does not use a stale cached cwd while the fresh probe is pending", async () => {
let resolveCwd: ((cwd: string) => void) | null = null;
const navigatedPaths: string[] = [];
@@ -16,6 +16,9 @@ import {
shouldReleaseInitialFollowSyncAttempt,
shouldResetInitialFollowTerminalCwdSync,
type SftpFollowTerminalCwdBlock,
resolveTerminalCwdForSftp,
isSftpFollowTargetPath,
fallbackFollowPathForUntrackedSession,
} from "../../../domain/sftpFollowTerminalCwd";
import type { Host } from "../../../types";
import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActions";
@@ -23,6 +26,7 @@ import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActio
type FollowConnection = {
id: string;
currentPath?: string | null;
homeDir?: string | null;
status: string;
isLocal?: boolean;
};
@@ -48,6 +52,7 @@ type GetTerminalCwd = (options?: {
type InitialFollowConnection = {
id: string;
currentPath?: string | null;
homeDir?: string | null;
status: string;
isLocal?: boolean;
};
@@ -85,13 +90,21 @@ const runInitialFollowTerminalCwdSync = async ({
return false;
}
const targetPath = resolveTerminalCwdForSftp(cwd, live.homeDir, live.currentPath);
if (!isSftpFollowTargetPath(targetPath)) {
// Prompt-only shortcuts such as `~` are not a real SFTP path yet. Stay on
// the connection's landing directory instead of listing `/~`.
setHandled({ connectionId: expectedConnectionId, terminalCwd: cwd });
return true;
}
setHandled({
connectionId: expectedConnectionId,
terminalCwd: staleTerminalCwd && staleTerminalCwd !== cwd ? staleTerminalCwd : cwd,
terminalCwd: staleTerminalCwd && staleTerminalCwd !== targetPath ? staleTerminalCwd : targetPath,
});
if (live.currentPath === cwd) return true;
if (live.currentPath === targetPath) return true;
const navigateResult = await navigate(cwd, isEligible);
const navigateResult = await navigate(targetPath, isEligible);
if (!isEligible()) return false;
const current = getConnection();
if (!current || current.id !== expectedConnectionId || current.status !== "connected") {
@@ -174,6 +187,7 @@ export function useSftpFollowTerminalCwd({
const ownerPanelOpenRef = useRef(ownerPanelOpen);
const hasActiveWorkRef = useRef(hasActiveWork);
const initialFollowReadyConnectionRef = useRef<string | null>(null);
const lastFollowOriginIdRef = useRef<string | null>(null);
effectiveFollowTerminalCwdRef.current = effectiveFollowTerminalCwd;
canFollowTerminalCwdRef.current = canFollowTerminalCwd;
@@ -257,10 +271,16 @@ export function useSftpFollowTerminalCwd({
});
if (!cwd) return;
if (!shouldApply()) return;
const navigateResult = await sftpRef.current.navigateTo("left", cwd, { shouldApply });
const connection = sftpRef.current.leftPane.connection;
const targetPath = resolveTerminalCwdForSftp(
cwd,
connection?.homeDir,
connection?.currentPath,
);
if (!isSftpFollowTargetPath(targetPath)) return;
const navigateResult = await sftpRef.current.navigateTo("left", targetPath, { shouldApply });
if (navigateResult !== "reached" || !shouldApply()) return;
blockedFollowRef.current = null;
const connection = sftpRef.current.leftPane.connection;
if (connection?.id) {
handledFollowRef.current = { connectionId: connection.id, terminalCwd: cwd };
}
@@ -275,9 +295,23 @@ export function useSftpFollowTerminalCwd({
const syncGeneration = followSyncGenerationRef.current;
const expectedSessionId = focusedSessionIdRef.current ?? activeSessionIdRef.current ?? null;
const expectedConnectionIdAtStart = connectionIdRef.current ?? liveConnectionId;
const previousOriginId = lastFollowOriginIdRef.current;
const originChanged = Boolean(
previousOriginId
&& expectedSessionId
&& previousOriginId !== expectedSessionId,
);
if (expectedSessionId) lastFollowOriginIdRef.current = expectedSessionId;
const usesLiveTerminalCwd = Boolean(activeTerminalCwd && activeTerminalCwdTrusted);
let terminalCwd = usesLiveTerminalCwd ? activeTerminalCwd : null;
if (!terminalCwd) {
if (!terminalCwd && originChanged) {
// Do not reuse an in-flight probe from the pane we just left.
terminalCwd = fallbackFollowPathForUntrackedSession({
originChanged,
homeDir: sftpRef.current.leftPane.connection?.homeDir,
currentPath: sftpRef.current.leftPane.connection?.currentPath,
});
} else if (!terminalCwd) {
terminalCwd = await onGetTerminalCwd({
preferFreshBackend: true,
allowRendererFallback: false,
@@ -335,26 +369,36 @@ export function useSftpFollowTerminalCwd({
liveTerminalCwd: activeTerminalCwdRef.current,
requireLiveTerminalCwd: usesLiveTerminalCwd,
});
const navigateResult = await sftpRef.current.navigateTo("left", terminalCwd, {
if (!connection) return;
const targetPath = resolveTerminalCwdForSftp(
terminalCwd,
connection.homeDir,
connection.currentPath,
);
if (!isSftpFollowTargetPath(targetPath)) return;
const navigateResult = await sftpRef.current.navigateTo("left", targetPath, {
shouldApply: shouldApplyCurrentFollowSync,
quiet: true,
});
if (!shouldApplyCurrentFollowSync()) return;
const currentConnection = sftpRef.current.leftPane.connection;
if (!currentConnection || currentConnection.id !== connection?.id) return;
if (navigateResult === "failed") {
blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
} else if (navigateResult === "superseded") {
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
} else if (navigateResult === "reached") {
blockedFollowRef.current = null;
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
}
}, [
activeSessionId,
activeTerminalCwd,
activeTerminalCwdTrusted,
canFollowTerminalCwd,
effectiveFollowTerminalCwd,
focusedSessionId,
hasActiveWork,
isVisible,
onGetTerminalCwd,
@@ -380,6 +424,7 @@ export function useSftpFollowTerminalCwd({
if (!effectiveFollowTerminalCwd || !canFollowTerminalCwd || !isVisible || hasActiveWork) return;
void syncFollowToTerminalCwd();
}, [
activeSessionId,
activeTerminalCwd,
activeTerminalCwdTrusted,
canFollowTerminalCwd,
@@ -387,6 +432,7 @@ export function useSftpFollowTerminalCwd({
connectionIsLocal,
connectionStatus,
effectiveFollowTerminalCwd,
focusedSessionId,
hasActiveWork,
isVisible,
syncFollowToTerminalCwd,
@@ -533,7 +579,7 @@ export function useSftpFollowTerminalCwd({
getConnection: () => sftpRef.current.leftPane.connection,
navigate: (cwd, shouldApply) => {
navigationStarted = true;
return sftpRef.current.navigateTo("left", cwd, { shouldApply });
return sftpRef.current.navigateTo("left", cwd, { shouldApply, quiet: true });
},
setHandled: (value) => { handledFollowRef.current = value; },
setBlocked: (value) => { blockedFollowRef.current = value; },
@@ -5,6 +5,7 @@ import {
buildSftpHostCredentials,
} from "./useSftpHostCredentials.ts";
import type { Host, Identity, KnownHost, SSHKey } from "../../../domain/models.ts";
import { resolvePasswordAuthSftpHost } from "../../../domain/authIdentityPicker.ts";
const host = (overrides: Partial<Host> = {}): Host => ({
id: "host-1",
@@ -16,6 +17,22 @@ const host = (overrides: Partial<Host> = {}): Host => ({
...overrides,
});
test("SFTP credentials follow the temporary deploy identity on a root profile", () => {
const identities = [
{ id: "root-id", label: "root", username: "root", authMethod: "password", password: "bad-root", created: 0 },
{ id: "deploy-id", label: "deploy", username: "deploy", authMethod: "password", password: "good-deploy", created: 0 },
] as Identity[];
const savedHost = host({ identityId: "root-id" });
const sftpHost = resolvePasswordAuthSftpHost(savedHost, identities, {
authMethod: "password", username: "deploy", password: "good-deploy", savedToHost: false,
});
const credentials = buildSftpHostCredentials({ host: sftpHost, hosts: [savedHost], keys: [], identities });
assert.equal(credentials.username, "deploy");
assert.equal(credentials.password, "good-deploy");
assert.equal(credentials.hostId, savedHost.id);
assert.equal(savedHost.identityId, "root-id");
});
test("buildSftpHostCredentials forwards system agent settings for target and jump hosts", () => {
const jump = host({
id: "jump-1",
@@ -1,51 +0,0 @@
import assert from 'node:assert/strict';
import test, { after } from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { useSftpPaneActions } from './useSftpPaneActions';
import { createEmptyPane, type SftpPane } from './types';
import type { SftpFileEntry } from '../../../types';
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
after(() => { environment.IS_REACT_ACT_ENVIRONMENT = previous; });
test('command refresh keeps current directory/filter/selection and drops deleted selections', async () => {
const file = (name: string): SftpFileEntry => ({ name, type: 'file', size: 1, sizeFormatted: '1 B', lastModified: 0, lastModifiedFormatted: '1970-01-01' });
let result = [file('kept'), file('new')];
const selection = new Set(['kept']);
const pane: SftpPane = { ...createEmptyPane('pane'), connection: { id: 'conn', hostId: 'host', hostLabel: 'Host', status: 'connected', currentPath: '/browsed', homeDir: '/', isLocal: true }, files: [file('kept')], selectedFiles: selection, filter: 'ke' };
const left = { current: { tabs: [pane], activeTabId: pane.id } };
const calls: string[] = [];
let actions: ReturnType<typeof useSftpPaneActions>;
const update: Parameters<typeof useSftpPaneActions>[0]['updateTab'] = (_side, id, updater) => {
left.current.tabs = left.current.tabs.map((p) => p.id === id ? updater(p) : p);
};
function Probe() {
actions = useSftpPaneActions({
hosts: [], getActivePane: () => left.current.tabs[0], updateTab: update,
updateActiveTab: (side, updater) => update(side, pane.id, updater),
leftTabsRef: left, rightTabsRef: { current: { tabs: [], activeTabId: null } },
navSeqRef: { current: { left: 0, right: 0 } }, dirCacheRef: { current: new Map() },
sftpSessionsRef: { current: new Map() }, lastConnectedHostRef: { current: { left: null, right: null } },
connectionCacheKeyMapRef: { current: new Map() }, makeCacheKey: (id, path) => id + path,
clearCacheForConnection() {}, listLocalFiles: async (path) => { calls.push(path); return result; },
listRemoteFiles: async () => [], handleSessionError() {}, releaseConnection: async () => {},
isSessionError: () => false, clearSelectionsExcept() {}, dirCacheTtlMs: 1000,
});
return null;
}
let renderer: ReactTestRenderer;
await act(async () => { renderer = create(React.createElement(Probe)); });
await actions!.refresh('left', { tabId: pane.id, preserveSelection: true });
assert.deepEqual(calls, ['/browsed']);
assert.equal(left.current.tabs[0].selectedFiles, selection);
assert.equal(left.current.tabs[0].filter, 'ke');
assert.deepEqual(left.current.tabs[0].files.map((f) => f.name), ['kept', 'new']);
result = [file('new')];
await actions!.refresh('left', { preserveSelection: true });
assert.equal(left.current.tabs[0].selectedFiles.size, 0);
assert.equal(left.current.tabs[0].connection?.currentPath, '/browsed');
await act(async () => { renderer.unmount(); });
});
+37 -17
View File
@@ -2,6 +2,7 @@ import React, { useCallback, useRef } from "react";
import type { Host, SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { logger } from "../../../lib/logger";
import { unwrapSftpIpcError } from "./errors";
import { SftpPane } from "./types";
import {
getFileName,
@@ -27,13 +28,6 @@ import {
/** Shared empty set for navigation resets — never mutate this. */
const EMPTY_SET = new Set<string>();
/** Retain selection identity when no selected entry disappeared. */
export function retainSftpSelection(selected: Set<string>, files: SftpFileEntry[]): Set<string> {
const names = new Set(files.map((file) => file.name));
const retained = new Set([...selected].filter((name) => names.has(name)));
return retained.size === selected.size ? selected : retained;
}
interface UseSftpPaneActionsParams {
hosts: Host[];
getActivePane: (side: "left" | "right") => SftpPane | null;
@@ -60,14 +54,15 @@ interface UseSftpPaneActionsParams {
export type SftpNavigateResult = "reached" | "failed" | "aborted" | "superseded";
export type SftpNavigateOptions = {
force?: boolean;
preserveSelection?: boolean;
tabId?: string;
shouldApply?: () => boolean;
/** Restore the previous listing without showing a pane error. */
quiet?: boolean;
};
interface UseSftpPaneActionsResult {
navigateTo: (side: "left" | "right", path: string, options?: SftpNavigateOptions) => Promise<SftpNavigateResult>;
refresh: (side: "left" | "right", options?: { tabId?: string; preserveSelection?: boolean }) => Promise<void>;
refresh: (side: "left" | "right", options?: { tabId?: string }) => Promise<void>;
navigateUp: (side: "left" | "right") => Promise<void>;
openEntry: (side: "left" | "right", entry: SftpFileEntry) => Promise<void>;
toggleSelection: (side: "left" | "right", fileName: string, multiSelect: boolean) => void;
@@ -187,7 +182,6 @@ export const useSftpPaneActions = ({
pane.connection.homeDir,
);
const preserveSelection = options?.preserveSelection && normalizedPath === pane.connection.currentPath;
const connectionId = pane.connection.id;
const requestId = ++navSeqRef.current[side];
const cacheKey = makeCacheKey(connectionId, normalizedPath, pane.filenameEncoding);
@@ -290,7 +284,7 @@ export const useSftpPaneActions = ({
connection: prev.connection
? { ...prev.connection, currentPath: normalizedPath }
: null,
selectedFiles: preserveSelection ? prev.selectedFiles : EMPTY_SET,
selectedFiles: EMPTY_SET,
filter: clearFilterForPathChange ? "" : prev.filter,
loading: true,
error: null,
@@ -378,7 +372,7 @@ export const useSftpPaneActions = ({
connectionId,
path: normalizedPath,
files,
selectedFiles: preserveSelection ? retainSftpSelection(getTargetPane()?.selectedFiles ?? EMPTY_SET, files) : EMPTY_SET,
selectedFiles: EMPTY_SET,
filter: nextConfirmedFilter,
});
@@ -389,7 +383,7 @@ export const useSftpPaneActions = ({
: null,
files,
loading: false,
selectedFiles: preserveSelection ? retainSftpSelection(prev.selectedFiles, files) : EMPTY_SET,
selectedFiles: EMPTY_SET,
filter: clearFilterForPathChange ? "" : prev.filter,
}));
if (!pane.connection.isLocal) {
@@ -425,8 +419,9 @@ export const useSftpPaneActions = ({
files: previousFiles,
selectedFiles: previousSelection,
filter: getSftpFilterAfterPathChangeError(clearFilterForPathChange, previousFilter, prev.filter),
error:
err instanceof Error ? err.message : "Failed to list directory",
error: options?.quiet
? previousError
: unwrapSftpIpcError(err) || "Failed to list directory",
loading: false,
};
});
@@ -454,7 +449,7 @@ export const useSftpPaneActions = ({
);
const refresh = useCallback(
async (side: "left" | "right", options?: { tabId?: string; preserveSelection?: boolean }) => {
async (side: "left" | "right", options?: { tabId?: string }) => {
const sideTabs = side === "left" ? leftTabsRef.current : rightTabsRef.current;
const pane = options?.tabId
? sideTabs.tabs.find((t) => t.id === options.tabId) ?? null
@@ -485,7 +480,7 @@ export const useSftpPaneActions = ({
}
return;
}
await navigateTo(side, pane.connection.currentPath, { force: true, tabId: options?.tabId, preserveSelection: options?.preserveSelection });
await navigateTo(side, pane.connection.currentPath, { force: true, tabId: options?.tabId });
} else if (!pane?.connection && pane?.error) {
// For background tabs, don't trigger reconnection (it operates on
// the active tab). Just leave the error state for the user to see
@@ -1039,6 +1034,30 @@ export const useSftpPaneActions = ({
[getActivePane, refresh, handleSessionError, sftpSessionsRef, isSessionError],
);
const removeListedNames = useCallback((
side: "left" | "right",
parentPath: string,
names: string[],
) => {
if (names.length === 0) return;
const removeSet = new Set(names);
updateActiveTab(side, (prev) => {
if (!prev.connection || prev.connection.currentPath !== parentPath) return prev;
const nextSelection = new Set(prev.selectedFiles);
for (const name of names) nextSelection.delete(name);
return {
...prev,
files: prev.files.filter((file) => !removeSet.has(file.name)),
selectedFiles: nextSelection,
error: null,
};
});
const pane = getActivePane(side);
if (pane?.connection && !pane.connection.isLocal) {
clearCacheForConnection(pane.connection.id);
}
}, [clearCacheForConnection, getActivePane, updateActiveTab]);
return {
navigateTo,
refresh,
@@ -1056,6 +1075,7 @@ export const useSftpPaneActions = ({
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -0,0 +1,563 @@
/** @test issue #3559 — dual-pane transfers must re-stat remote sources before planning */
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 { PREFLIGHT_STAT_CONCURRENCY, PREFLIGHT_STAT_MAX_FILES, useSftpTransfers } from "./useSftpTransfers";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
import type { SftpPane } from "./types";
type StartOptions = {
transferId: string;
sourcePath: string;
sourceType: string;
targetType: string;
totalBytes?: number;
sourceSftpId?: string;
};
/** Remote pane whose listing was captured before the file grew to 3626 bytes. */
function makePane(side: "left" | "right"): SftpPane {
const isLocal = side === "right";
return {
id: side,
connection: {
id: isLocal ? "local-conn" : "remote-conn",
hostId: isLocal ? undefined : "host-1",
hostLabel: isLocal ? "Local" : "SSH host",
isLocal,
status: "connected",
currentPath: isLocal ? "/Users/reporter/Downloads" : "/opt",
},
files: isLocal
? []
: [
{
name: "aops_dns_view_demo.sh",
type: "file" as const,
size: 3622,
sizeFormatted: "3.5 KB",
lastModified: 1758000000000,
lastModifiedFormatted: "",
},
],
loading: false,
reconnecting: false,
error: null,
connectionLogs: [],
selectedFiles: new Set<string>(),
filter: "",
filenameEncoding: "auto",
showHiddenFiles: true,
transferMutationToken: 0,
};
}
function installGlobals(netty: Record<string, unknown>) {
const previousWindow = (globalThis as { window?: unknown }).window;
const previousActFlag = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const previousStorage = (globalThis as { localStorage?: unknown }).localStorage;
const previousRaf = (globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame;
const previousCancelRaf = (globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame;
// Progress patches are rAF-coalesced; provide a microtask-ish shim.
const raf = (cb: (time: number) => void) => setTimeout(() => cb(Date.now()), 0);
(globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame = raf;
(globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame = (id: unknown) => clearTimeout(id as number);
(globalThis as { window?: unknown }).window = {
netcatty: netty,
requestAnimationFrame: raf,
cancelAnimationFrame: (id: unknown) => clearTimeout(id as number),
};
(globalThis as { localStorage?: unknown }).localStorage = {
getItem: () => null,
setItem: () => undefined,
removeItem: () => undefined,
};
return () => {
(globalThis as { window?: unknown }).window = previousWindow;
(globalThis as { localStorage?: unknown }).localStorage = previousStorage;
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousActFlag;
(globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame = previousRaf;
(globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame = previousCancelRaf;
};
}
for (const liveStatAvailable of [true, false]) {
test(
liveStatAvailable
? "dual-pane download plan uses the live source size, not the stale listing (#3559)"
: "dual-pane download plan falls back to live size measurement when stat is unavailable (#3559)",
async () => {
const statCalls: Array<{ sftpId: string; path: string }> = [];
const startedOptions: StartOptions[] = [];
let resolveTransfer!: (options: StartOptions) => void;
const transferStarted = new Promise<StartOptions>((resolve) => { resolveTransfer = resolve; });
const restore = installGlobals({
statSftp: async (sftpId: string, target: string) => {
if (!liveStatAvailable) return undefined;
statCalls.push({ sftpId, path: target });
return {
name: "aops_dns_view_demo.sh",
type: "file" as const,
size: 3626,
sizeKnown: true,
lastModified: 1758000001000,
};
},
statLocal: async () => null,
startStreamTransfer: async (options: StartOptions) => {
startedOptions.push(options);
resolveTransfer(options);
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed",
transferId: options.transferId,
transferred: options.totalBytes ?? 0,
totalBytes: options.totalBytes ?? 0,
lifecycleEpoch: 0,
});
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
const running = ops!.startTransfer(
[{ name: "aops_dns_view_demo.sh", isDirectory: false }],
"left",
"right",
);
const options = await transferStarted;
startedOptions.length = 0;
startedOptions.push(options);
await running;
});
// Every fresh remote plan must come from a live re-stat of the source.
if (liveStatAvailable) {
assert.equal(statCalls.length, 1);
assert.equal(statCalls[0].sftpId, "sftp-remote");
assert.equal(statCalls[0].path, "/opt/aops_dns_view_demo.sh");
}
const planBytes = startedOptions[0]?.totalBytes;
if (liveStatAvailable) {
assert.equal(planBytes, 3626, "plan must use the live remote size, not the stale listing 3622");
} else {
// No live stat possible: plan 0 must be omitted so the transfer
// bridge measures the live size instead of truncating.
assert.equal(planBytes, undefined);
}
} finally {
renderer?.unmount();
restore();
}
},
);
}
test("stat-less remote source keeps the listing size in the overwrite dialog and leaves the plan unknown", async () => {
const started: StartOptions[] = [];
const restore = installGlobals({
statSftp: async () => ({
name: "aops_dns_view_demo.sh",
type: "file" as const,
size: 0,
sizeKnown: false,
lastModified: 0,
}),
statLocal: async () => ({
name: "aops_dns_view_demo.sh",
type: "file" as const,
size: 100,
lastModified: 1,
}),
startStreamTransfer: async (options: StartOptions) => {
started.push(options);
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner-statless",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
await ops!.startTransfer(
[{ name: "aops_dns_view_demo.sh", isDirectory: false }],
"left",
"right",
);
});
assert.equal(started.length, 0, "an unresolved conflict must not start the transfer");
assert.equal(ops!.conflicts.length, 1);
assert.equal(ops!.conflicts[0].newSize, 3622);
assert.equal(ops!.conflicts[0].newModified, 1758000000000);
const task = ops!.transfers.find((row) => row.fileName === "aops_dns_view_demo.sh");
assert.equal(task?.totalBytes, 0, "listing size must not become the transfer plan");
assert.equal(task?.status, "attention");
} finally {
renderer?.unmount();
restore();
}
});
test("remote transfer preflight stats stay within the concurrency cap and file bound", async () => {
const limit = PREFLIGHT_STAT_CONCURRENCY;
const fileCount = limit + 4;
let inflight = 0;
let maxInflight = 0;
let releaseAll = () => {};
const gate = new Promise<void>((resolve) => { releaseAll = resolve; });
let reachedCap = () => {};
const hitCap = new Promise<void>((resolve) => { reachedCap = resolve; });
const names = Array.from({ length: fileCount }, (_, index) => `file-${index}.bin`);
const restore = installGlobals({
statSftp: async () => {
inflight += 1;
maxInflight = Math.max(maxInflight, inflight);
if (inflight >= limit) reachedCap();
try {
await gate;
} finally {
inflight -= 1;
}
return {
name: "file",
type: "file" as const,
size: 10,
sizeKnown: true,
lastModified: 1,
};
},
statLocal: async () => null,
startStreamTransfer: async (options: StartOptions) => {
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed",
transferId: options.transferId,
transferred: options.totalBytes ?? 0,
totalBytes: options.totalBytes ?? 0,
lifecycleEpoch: 0,
});
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner-concurrency",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
let running: Promise<unknown> = Promise.resolve();
await act(async () => {
running = ops!.startTransfer(
names.map((name) => ({ name, isDirectory: false })),
"left",
"right",
);
const capTimeout = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error("preflight did not reach the concurrency cap")), 2000);
});
await Promise.race([hitCap, capTimeout]);
});
assert.equal(maxInflight, limit);
assert.ok(inflight <= limit);
releaseAll();
await act(async () => { await running; });
assert.equal(maxInflight, limit);
} finally {
releaseAll();
renderer?.unmount();
restore();
}
});
test("a preflight timeout stops the rest of the batch", async () => {
const extra = 4;
const names = Array.from(
{ length: PREFLIGHT_STAT_CONCURRENCY + extra },
(_, index) => `hung-${index}.bin`,
);
let statCalls = 0;
const restore = installGlobals({
statSftp: () => {
statCalls += 1;
return new Promise(() => {});
},
statLocal: async () => null,
startStreamTransfer: async (options: StartOptions) => {
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed",
transferId: options.transferId,
transferred: options.totalBytes ?? 0,
totalBytes: options.totalBytes ?? 0,
lifecycleEpoch: 0,
});
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner-timeout",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
await ops!.startTransfer(
names.map((name) => ({ name, isDirectory: false })),
"left",
"right",
);
});
// One preflight wave, then stop. Timed-out files are not statted again.
assert.equal(statCalls, PREFLIGHT_STAT_CONCURRENCY);
} finally {
renderer?.unmount();
restore();
}
});
test("stat-less preflight results are not statted again before transfer", async () => {
const names = Array.from(
{ length: PREFLIGHT_STAT_CONCURRENCY + 2 },
(_, index) => `legacy-${index}.bin`,
);
let statCalls = 0;
let inflight = 0;
let maxInflight = 0;
const started: StartOptions[] = [];
const restore = installGlobals({
statSftp: async () => {
statCalls += 1;
inflight += 1;
maxInflight = Math.max(maxInflight, inflight);
await Promise.resolve();
inflight -= 1;
return {
name: "legacy",
type: "file" as const,
size: 0,
sizeKnown: false,
lastModified: 0,
};
},
statLocal: async () => null,
startStreamTransfer: async (options: StartOptions) => {
started.push(options);
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed",
transferId: options.transferId,
transferred: options.totalBytes ?? 0,
totalBytes: options.totalBytes ?? 0,
lifecycleEpoch: 0,
});
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner-statless-batch",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
await ops!.startTransfer(
names.map((name) => ({ name, isDirectory: false })),
"left",
"right",
);
});
assert.equal(statCalls, names.length);
assert.ok(maxInflight <= PREFLIGHT_STAT_CONCURRENCY);
assert.equal(started.length, names.length);
assert.equal(started.filter((options) => options.totalBytes === undefined).length, names.length);
} finally {
renderer?.unmount();
restore();
}
});
test("files past the preflight bound stay un-statted after conflict resolution", async () => {
const extra = 2;
const names = Array.from({ length: PREFLIGHT_STAT_MAX_FILES + extra }, (_, index) => `bulk-${index}.bin`);
let statCalls = 0;
const started: StartOptions[] = [];
const restore = installGlobals({
statSftp: async () => {
statCalls += 1;
return {
name: "bulk",
type: "file" as const,
size: 20,
sizeKnown: true,
lastModified: 5,
};
},
statLocal: async (target: string) => names.slice(-extra).some((name) => target.endsWith(`/${name}`))
? { name: target.split("/").pop() || "", type: "file" as const, size: 1, lastModified: 1 }
: null,
startStreamTransfer: async (options: StartOptions) => {
started.push(options);
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed",
transferId: options.transferId,
transferred: options.totalBytes ?? 0,
totalBytes: options.totalBytes ?? 0,
lifecycleEpoch: 0,
});
return {};
},
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId: "plan-owner-bound",
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
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 () => [],
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
await ops!.startTransfer(
names.map((name) => ({ name, isDirectory: false })),
"left",
"right",
);
});
assert.equal(statCalls, PREFLIGHT_STAT_MAX_FILES);
assert.equal(started.length, names.length - extra);
assert.equal(ops!.conflicts.length, extra);
await act(async () => { renderer?.unmount(); });
await act(async () => { renderer = create(React.createElement(Probe)); });
assert.equal(ops!.conflicts.length, extra, "conflicts must survive panel remount");
await act(async () => {
await ops!.resolveConflict(ops!.conflicts[0].transferId, "replace", true);
await new Promise((resolve) => setTimeout(resolve, 300));
});
assert.equal(started.length, names.length);
assert.equal(statCalls, PREFLIGHT_STAT_MAX_FILES, "conflict resolution must keep the preflight cap");
const omitted = started.filter((options) => options.totalBytes === undefined);
assert.equal(omitted.length, extra);
} finally {
renderer?.unmount();
restore();
}
});
+205 -21
View File
@@ -63,6 +63,21 @@ import {
retryExternalDragDropFileUpload,
} from "./externalDragDropRetry";
// The bridge's statSftp awaits an unbounded SFTP callback, so a half-open
// session can leave a stat pending forever. Every stat issued outside the
// bridge is bounded with this timeout; on timeout the caller falls back to
// stale metadata / a 0 plan instead of one hung stat blocking a batch.
const STAT_SFTP_TIMEOUT_MS = 10_000;
// Preflight re-stats share the browse SFTP session and the renderer IPC
// queue. Launching one stat per file for a huge multi-file selection would
// flood both before any transfer task reaches the UI, so cap the number of
// in-flight preflight stats and skip the re-stat entirely once the selection
// grows past a bound (files beyond the cap stay on the safe 0 plan, which
// makes the bridge measure the live size anyway).
export const PREFLIGHT_STAT_CONCURRENCY = 8;
export const PREFLIGHT_STAT_MAX_FILES = 128;
/** Keep the MutableRefObject mirror in sync with the process-global latch set. */
function syncPausedTasksRef(ref: { current: Set<string> }, taskId: string, latched: boolean) {
if (latched) ref.current.add(taskId);
@@ -207,7 +222,6 @@ export const useSftpTransfers = ({
const transfersRef = useRef(transfers);
const conflictsRef = useRef(conflicts);
conflictsRef.current = conflicts;
// When the retained panel is re-opened, catch up React state from the ref that
// kept receiving progress while the surface was hidden.
useEffect(() => {
@@ -613,9 +627,30 @@ export const useSftpTransfers = ({
const sameHost = sameHostEndpoints && !!sourceSftpId && !!targetSftpId;
const discoverTransferSize = async () => {
// Returns the discovered stat so callers that need the size (e.g. the
// overwrite conflict dialog) can await this instead of reading stale
// metadata from the local task copy.
const discoverTransferSize = async (): Promise<{
size: number;
lastModified?: number;
/** False for pane-listing display data. That size must not become the plan. */
plan: boolean;
} | null> => {
// When the endpoint cannot stat the source (legacy SCP returns the
// sizeKnown: false placeholder) or the stat fails, the transfer plan
// stays unknown (0 bytes, so the bridge measures the live size). The
// overwrite dialog still needs display metadata, so fall back to the
// retained cached listing entry instead of reporting 0 bytes — but only
// for the dialog; the plan itself must never take the listing's
// possibly stale size back.
const cachedListingStatForDialog = (): { size: number; lastModified?: number; plan: false } | null => {
if (getParentPath(task.sourcePath) !== sourcePane.connection?.currentPath) return null;
const entry = sourcePane.files.find((candidate) => candidate.name === task.fileName);
if (!entry || !(entry.size > 0)) return null;
return { size: entry.size, lastModified: entry.lastModified, plan: false };
};
try {
if (task.totalBytes > 0 || !!task.sourceLastModified) return;
if (task.totalBytes > 0 || !!task.sourceLastModified) return null;
if (sourcePane.connection?.isLocal) {
const stat = await netcattyBridge.get()?.statLocal?.(task.sourcePath);
@@ -628,17 +663,41 @@ export const useSftpTransfers = ({
totalBytes: stat.size,
});
}
return { size: stat.size, lastModified: stat.lastModified, plan: true };
}
return;
return null;
}
if (sourceSftpId) {
const stat = await netcattyBridge.get()?.statSftp?.(
sourceSftpId,
task.sourcePath,
sourceEncoding,
);
if (stat) {
if (task.preflightStatSkipped) {
return cachedListingStatForDialog();
}
// This stat runs deferred (started before the conflict check) and
// can be awaited by the conflict path, so it must not hang on a
// half-open session. Bound it like the preflight stat and settle
// early once the task is cancelled, since a marked task cannot
// settle an in-flight SFTP callback itself.
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
let cancelTimer: ReturnType<typeof setInterval> | undefined;
const stat = await Promise.race([
Promise.resolve(netcattyBridge.get()?.statSftp?.(
sourceSftpId,
task.sourcePath,
sourceEncoding,
)),
new Promise<undefined>((resolve) => {
timeoutTimer = setTimeout(() => resolve(undefined), STAT_SFTP_TIMEOUT_MS);
}),
new Promise<undefined>((resolve) => {
cancelTimer = setInterval(() => {
if (cancelledTasksRef.current.has(task.id)) resolve(undefined);
}, 250);
}),
]).finally(() => {
if (timeoutTimer) clearTimeout(timeoutTimer);
if (cancelTimer) clearInterval(cancelTimer);
});
if (stat && stat.sizeKnown !== false) {
if (!task.sourceLastModified && stat.lastModified) {
task.sourceLastModified = stat.lastModified;
}
@@ -647,12 +706,18 @@ export const useSftpTransfers = ({
totalBytes: stat.size,
});
}
return { size: stat.size, lastModified: stat.lastModified, plan: true };
}
// Unknown size (e.g. legacy SCP stat): keep the transfer plan
// unknown so a 0-byte placeholder never replaces trusted metadata,
// but give the conflict dialog the retained cached listing entry.
return cachedListingStatForDialog();
}
} catch (err) {
if (!isTransferCancelledError(err)) {
logger.debug?.("[SFTP] Deferred transfer size discovery failed", err);
}
return cachedListingStatForDialog();
}
};
@@ -746,16 +811,35 @@ export const useSftpTransfers = ({
return null;
})();
// For single files: fire-and-forget size discovery
if (!task.isDirectory) {
void discoverTransferSize();
}
// For single files: start size discovery without blocking the conflict
// check, but keep the promise so an actual conflict can await fresh
// size metadata before the dialog is shown.
const sizeDiscoveryPromise = task.isDirectory ? null : discoverTransferSize();
// Only await conflict check (fast single stat call)
const conflict = await conflictCheckPromise;
// Cancel/Stop may have won while conflict stats were in flight.
if (cancelledTasksRef.current.has(task.id)) return "cancelled";
// null means the plan size is still unknown. A verified 0-byte stat is 0,
// not null, so an empty file does not pick up a stale listing size.
let verifiedPlanBytes: number | null = task.totalBytes > 0 ? task.totalBytes : null;
if (conflict && sizeDiscoveryPromise) {
// The task's totalBytes may still be 0 here because discovery ran
// deferred and updateTask never mutates the local task copy. Await
// discovery (bounded per-task; the task is already visible/cancellable)
// so the overwrite dialog shows the real source size, not 0 (#3559).
const discovered = await sizeDiscoveryPromise;
// Cancel during this stat must win before an apply-to-all Replace
// deletes an existing symlink.
if (cancelledTasksRef.current.has(task.id)) return "cancelled";
if (discovered && discovered.size >= 0) {
conflict.newSize = discovered.size;
if (discovered.lastModified) conflict.newModified = discovered.lastModified;
if (discovered.plan) verifiedPlanBytes = discovered.size;
}
}
if (conflict) {
const defaultAction = conflictDefaultsRef.current
.get(task.batchId ?? "global")
@@ -819,7 +903,9 @@ export const useSftpTransfers = ({
setConflicts((prev) => [...prev, conflict]);
updateTask({
status: "attention",
totalBytes: conflict.newSize || task.totalBytes || 0,
// Dialog newSize may be the listing fallback (plan: false). Only a
// verified stat may become the plan; 0 stays omitted at startStreamTransfer.
totalBytes: verifiedPlanBytes ?? 0,
conflict,
});
return "attention";
@@ -1094,6 +1180,84 @@ export const useSftpTransfers = ({
? new Map(sourcePane.files.map(f => [f.name, f]))
: null;
// Pane listings can be stale when the file changed in a terminal or
// another session after the pane was listed (#3559). A stale undersized
// size becomes the transfer plan and silently truncates the download, so
// remote single files are always re-statted before the plan is built.
// When no live stat is possible the plan stays 0, which makes the bridge
// measure the live size instead of trusting the stale listing.
const freshRemoteMetadata = new Map<string, { size: number; lastModified: number }>();
const sourceSftpIdForPlan = sourcePane.connection.isLocal
? null
: (sftpSessionsRef.current.get(sourceConnectionId) ?? null);
const remoteSingleFiles = sourcePane.connection.isLocal
? []
: sourceFiles.filter((file) => !file.isDirectory);
const preflightFiles = remoteSingleFiles.slice(0, PREFLIGHT_STAT_MAX_FILES);
// Remote files without a verified live stat are not statted again in
// discoverTransferSize. That covers the tail past the cap, a missing
// browse session, a timeout that stops the pool, and a stat that
// returns no usable size. The plan stays unknown so the bridge measures
// the live size; the overwrite dialog still uses the pane listing.
const preflightSkippedNames = new Set<string>();
if (remoteSingleFiles.length > 0 && sourceSftpIdForPlan) {
const sourceEncoding = sourcePane.filenameEncoding || "auto";
// The bridge's statSftp awaits an unbounded SFTP callback, so a
// half-open session can leave a stat pending forever. Bound each
// preflight stat: on timeout the file keeps its 0 plan and the bridge
// measures the live size during the transfer instead of one hung stat
// blocking the entire selected batch.
const PREFLIGHT_STAT_TIMEOUT_MS = STAT_SFTP_TIMEOUT_MS;
// These stats share the browse session. Keep a few in flight, and
// after the first timeout stop claiming more files so a half-open
// session cannot run the whole selection out to 10s each.
let preflightStopped = false;
const statOneRemoteFile = async (file: { name: string; isDirectory: boolean }) => {
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
try {
const stat = await Promise.race([
Promise.resolve(netcattyBridge.get()?.statSftp?.(
sourceSftpIdForPlan,
joinPath(sourcePath, file.name),
sourceEncoding,
)),
new Promise<undefined>((resolve) => {
timeoutTimer = setTimeout(() => {
timedOut = true;
resolve(undefined);
}, PREFLIGHT_STAT_TIMEOUT_MS);
}),
]);
if (timedOut) {
preflightStopped = true;
return;
}
if (stat && stat.type !== "symlink" && stat.sizeKnown !== false && stat.size >= 0) {
freshRemoteMetadata.set(file.name, { size: stat.size, lastModified: stat.lastModified });
}
} catch (err) {
// Fall through to a 0 plan so the bridge measures the live size.
logger.debug?.("[SFTP] Transfer plan re-stat failed; falling back to live size", err);
} finally {
if (timeoutTimer) clearTimeout(timeoutTimer);
}
};
const workers = Math.min(PREFLIGHT_STAT_CONCURRENCY, preflightFiles.length);
let preflightCursor = 0;
await Promise.allSettled(
Array.from({ length: workers }, async () => {
while (!preflightStopped && preflightCursor < preflightFiles.length) {
const file = preflightFiles[preflightCursor++];
await statOneRemoteFile(file);
}
}),
);
}
for (const file of remoteSingleFiles) {
if (!freshRemoteMetadata.has(file.name)) preflightSkippedNames.add(file.name);
}
for (const file of sourceFiles) {
const direction: TransferDirection =
sourcePane.connection!.isLocal && !targetPane.connection!.isLocal
@@ -1102,12 +1266,30 @@ export const useSftpTransfers = ({
? "download"
: "remote-to-remote";
// Use cached metadata from the source pane's file list to avoid
// redundant stat calls over the network, but only when the transfer
// source matches the pane's currently listed directory.
// Prefer the fresh re-stat for remote files: a cached listing size can
// be stale and undersized, which would silently truncate downloads
// (#3559). Remote files without a live stat use plan 0 so the bridge
// measures the live size; local sources keep the pane metadata.
const fileEntry = fileEntryMap?.get(file.name);
const fileSize = file.isDirectory ? 0 : (fileEntry?.size ?? 0);
const sourceLastModified = fileEntry?.lastModified ?? 0;
const freshMetadata = freshRemoteMetadata.get(file.name);
const fileSize = file.isDirectory
? 0
: freshMetadata
? freshMetadata.size
: sourcePane.connection!.isLocal
? (fileEntry?.size ?? 0)
: 0;
// Only keep an mtime that is paired with trusted metadata (live re-stat,
// local source size, or directory totals). A remote file whose re-stat
// failed must stay fully unknown (size 0 AND mtime 0 in the plan):
// discoverTransferSize and the conflict check both treat a nonzero
// sourceLastModified as proof the size is already known, so a stale
// mtime would suppress the deferred source re-stat. The overwrite
// dialog still gets the pane listing's cached entry via
// discoverTransferSize's cachedListingStatForDialog fallback.
const sourceLastModified = !file.isDirectory && !sourcePane.connection!.isLocal && !freshMetadata
? 0
: (freshMetadata?.lastModified ?? fileEntry?.lastModified ?? 0);
const nextSourcePath = joinPath(sourcePath, file.name);
const nextTargetPath = joinPath(targetPath, file.name);
@@ -1167,8 +1349,9 @@ export const useSftpTransfers = ({
}
continue;
}
const taskId = crypto.randomUUID();
newTasks.push({
id: crypto.randomUUID(),
id: taskId,
batchId,
fileName: file.name,
originalFileName: file.name,
@@ -1189,6 +1372,7 @@ export const useSftpTransfers = ({
isDirectory: file.isDirectory,
progressMode: file.isDirectory ? "files" : "bytes",
sourceLastModified,
preflightStatSkipped: preflightSkippedNames.has(file.name),
origin: "manual",
resumable: !usesLegacyScp,
pauseUnavailableReason: usesLegacyScp ? "This server uses legacy SCP; cancel and retry from the beginning instead" : undefined,
+24 -5
View File
@@ -1,6 +1,11 @@
import type { TransferTask } from "../../../domain/models";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
/** The displaced invocation may fail its walk, but no longer owns the child row. */
export class TransferOwnerChangedError extends Error {}
export type TransferOwnerObservation = ReturnType<typeof sftpTransferCenterStore.observeTaskSettlement>;
type StreamResult = { error?: string; cancelled?: boolean; superseded?: boolean } | undefined;
/** A live waiter owns bounded settlement evidence; persisted history stays compact. */
@@ -9,33 +14,47 @@ export async function runTransferAndWaitForOwner(
start: () => Promise<StreamResult>,
shouldAbort: () => boolean,
pausedAtResume?: TransferTask,
completedAtRestart?: TransferTask,
onOwnerChanged?: () => void,
retainObservation?: (observation: TransferOwnerObservation) => boolean,
existingObservation?: TransferOwnerObservation,
): Promise<StreamResult> {
// Register before admission/start: an owner may finish while dispatch waits for resume.
let observation = sftpTransferCenterStore.observeTaskSettlement(task);
let observation = existingObservation ?? sftpTransferCenterStore.observeTaskSettlement(task, completedAtRestart, onOwnerChanged);
try {
for (;;) {
if (shouldAbort()) throw new Error("Transfer cancelled");
const admission = sftpTransferCenterStore.admitTaskRun(task, pausedAtResume);
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before dispatch");
const admission = sftpTransferCenterStore.admitTaskRun(task, pausedAtResume, completedAtRestart);
if (admission === "cancelled") throw new Error("Transfer cancelled");
if (admission === "completed" || observation.read()?.status === "completed") return {};
if (admission === "conflict") throw new Error("Transfer identity changed before dispatch");
if (admission === "conflict") throw new TransferOwnerChangedError("Transfer identity changed before dispatch");
if (admission === "ready") break;
await new Promise((resolve) => setTimeout(resolve, 200));
}
// Admission begins a new attempt; discard any previous failed settlement.
observation.dispose();
observation = sftpTransferCenterStore.observeTaskSettlement(task);
observation = sftpTransferCenterStore.observeTaskSettlement(task, undefined, onOwnerChanged);
const result = await start();
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
if (!result?.superseded) return result;
for (;;) {
if (shouldAbort()) throw new Error("Transfer cancelled");
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
const latest = observation.read();
if (latest?.status === "completed") return { ...result, superseded: false };
if (latest?.status === "failed") throw new Error(latest.error || "Transfer failed");
if (latest?.status === "cancelled") throw new Error("Transfer cancelled");
await new Promise((resolve) => setTimeout(resolve, 200));
}
} catch (error) {
// A displaced invocation can reject instead of returning superseded. Its
// transport error must not regain permission to write the winning row.
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
throw error;
} finally {
observation.dispose();
// A deferred child update may outlive the invocation. Its caller must either
// retain this evidence through the write or release it after handling exit.
if (!retainObservation?.(observation)) observation.dispose();
}
}
+71 -16
View File
@@ -42,6 +42,14 @@ import { restoreSftpTransferHistoryCooperatively } from "./sftp/transferHistoryR
import { cancelExternalUploadRuntime } from "./sftp/externalUploadRuntime";
type Listener = () => void;
type TaskSettlementObserver = {
expected: TransferTask;
initialInactiveRow?: TransferTask;
settled?: TransferTask;
conflicted?: boolean;
ignoredCompletion?: TransferTask;
onIdentityConflict?: () => void;
};
// Ordinary bounded history restores synchronously so existing callers receive
// it immediately. Legacy directory snapshots can contain tens of thousands of
@@ -98,9 +106,9 @@ export interface SftpTransferCenterStore {
/** Single task row — same object identity until that row is patched. */
getTask(taskId: string): TransferTask | undefined;
/** Observe exact task settlement before completed child rows are compacted. */
observeTaskSettlement(task: TransferTask): { read(): TransferTask | undefined; dispose(): void };
observeTaskSettlement(task: TransferTask, ignoredCompletion?: TransferTask, onIdentityConflict?: () => void): { read(): TransferTask | undefined; hasIdentityConflict(): boolean; dispose(): void };
/** Publish an explicit dispatch identity without flushing large child-history batches. */
admitTaskRun(task: TransferTask, pausedAtResume?: TransferTask): "ready" | "paused" | "completed" | "cancelled" | "conflict";
admitTaskRun(task: TransferTask, pausedAtResume?: TransferTask, completedAtRestart?: TransferTask): "ready" | "paused" | "completed" | "cancelled" | "conflict";
getOwnerTasks(ownerId: string): TransferTask[];
publishOwner(ownerId: string, tasks: readonly TransferTask[]): void;
registerOwner(ownerId: string, controls: SftpTransferOwnerControls): () => void;
@@ -405,7 +413,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
let snapshotDirty = false;
const listeners = new Set<Listener>();
const progressListeners = new Set<Listener>();
const settlementObservers = new Map<string, Set<{ expected: TransferTask; settled?: TransferTask }>>();
const settlementObservers = new Map<string, Set<TaskSettlementObserver>>();
const matchesObservedTask = (expected: TransferTask, candidate: TransferTask) => (
expected.id === candidate.id
&& expected.sourcePath === candidate.sourcePath
@@ -414,6 +422,29 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
&& expected.directoryEntryIndex === candidate.directoryEntryIndex
&& expected.directoryEntryIdentity === candidate.directoryEntryIdentity
);
const captureObservedTask = (task: TransferTask) => {
for (const observer of settlementObservers.get(task.id) ?? []) {
if (observer.conflicted || task === observer.ignoredCompletion) continue;
const matchesExpected = matchesObservedTask(observer.expected, task);
// A retry may plan a new source identity while its initial stale row is
// still paused. Only the unchanged initial attempt is exempt: activating
// it or replacing its owner/epoch must not let the stale plan reclaim it.
if (!matchesExpected && observer.initialInactiveRow
&& matchesObservedTask(observer.initialInactiveRow, task)
&& observer.initialInactiveRow.status === task.status
&& observer.initialInactiveRow.lifecycleEpoch === task.lifecycleEpoch
&& observer.initialInactiveRow.ownerId === task.ownerId) continue;
observer.initialInactiveRow = undefined;
if (!matchesExpected) {
observer.conflicted = true;
observer.onIdentityConflict?.();
} else if (observer.settled?.status !== "completed") {
// Failed/cancelled evidence belongs to the latest observed attempt. A
// resumed owner can supersede it; exact successful completion stays final.
observer.settled = TERMINAL_OWNER_STATUSES.has(task.status) ? task : undefined;
}
}
};
const refreshBadgeSnapshot = () => {
const next = buildBadgeSnapshot(tasks);
if (
@@ -633,12 +664,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// settles; everything else can release its whole tree here.
settleFinishedTransferControlState(tasks, tasks);
if (settlementObservers.size > 0) {
for (const task of tasks) {
if (!TERMINAL_OWNER_STATUSES.has(task.status)) continue;
for (const observer of settlementObservers.get(task.id) ?? []) {
if (!observer.settled && matchesObservedTask(observer.expected, task)) observer.settled = task;
}
}
for (const task of tasks) captureObservedTask(task);
}
const beforePrune = tasks;
tasks = pruneSftpTransferHistory(tasks);
@@ -1338,7 +1364,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
},
getSnapshot: () => ensureSnapshot(),
getBadgeSnapshot: () => badgeSnapshot,
admitTaskRun(incoming, pausedAtResume) {
admitTaskRun(incoming, pausedAtResume, completedAtRestart) {
const rootId = incoming.parentTaskId ?? incoming.id;
if (isTransferOrRootCancelled(rootId, incoming.id)) return "cancelled";
const parent = incoming.parentTaskId ? tasks.find((task) => task.id === rootId) : undefined;
@@ -1348,7 +1374,10 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if (existing && (existing.sourcePath !== incoming.sourcePath || existing.targetPath !== incoming.targetPath
|| existing.parentTaskId !== incoming.parentTaskId)) return "conflict";
if (existing?.status === "cancelled") return "cancelled";
if (existing?.status === "completed") {
// Only the exact completion captured at the destination reset is
// stale. A newer completion or user control must keep its authority.
const restartsCompletion = existing?.status === "completed" && existing === completedAtRestart;
if (existing?.status === "completed" && !restartsCompletion) {
return matchesObservedTask(incoming, existing) ? "completed" : "conflict";
}
const resumesUnchangedPause = existing === pausedAtResume
@@ -1369,6 +1398,14 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
...existing,
directoryEntryIndex: incoming.directoryEntryIndex,
directoryEntryIdentity: incoming.directoryEntryIdentity,
...(restartsCompletion ? {
checkpointBytes: incoming.checkpointBytes,
transferredBytes: incoming.transferredBytes,
resumeStage: incoming.resumeStage,
downloadCheckpointBytes: incoming.downloadCheckpointBytes,
uploadCheckpointBytes: incoming.uploadCheckpointBytes,
sourceFingerprint: incoming.sourceFingerprint,
} : {}),
...(existing.status === "transferring" ? {} : {
status: "transferring" as const,
lifecycleEpoch: undefined,
@@ -1378,25 +1415,36 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
}),
};
tasks = next;
captureObservedTask(next[index]);
emitProgress(false);
return "ready";
},
observeTaskSettlement(expected) {
const observer: { expected: TransferTask; settled?: TransferTask } = { expected: { ...expected } };
observeTaskSettlement(expected, ignoredCompletion, onIdentityConflict) {
const initial = tasks.find((task) => task.id === expected.id);
const observer: TaskSettlementObserver = {
expected: { ...expected }, ignoredCompletion, onIdentityConflict,
initialInactiveRow: initial && ["paused", "failed", "interrupted", "attention"].includes(initial.status)
&& !matchesObservedTask(expected, initial) ? { ...initial } : undefined,
};
const observers = settlementObservers.get(expected.id) ?? new Set();
observers.add(observer);
settlementObservers.set(expected.id, observers);
// A different active owner may predate registration. Detect it now,
// before admission can publish the stale caller's identity over it.
if (initial) captureObservedTask(initial);
let disposed = false;
return {
read() {
if (disposed) return undefined;
if (observer.settled) return observer.settled;
const current = tasks.find((task) => task.id === expected.id);
return current && matchesObservedTask(observer.expected, current) ? current : undefined;
return current && current !== ignoredCompletion && matchesObservedTask(observer.expected, current) ? current : undefined;
},
hasIdentityConflict: () => !disposed && observer.conflicted === true,
dispose() {
disposed = true;
observer.settled = undefined;
observer.conflicted = undefined;
observers.delete(observer);
if (observers.size === 0) settlementObservers.delete(expected.id);
},
@@ -1662,6 +1710,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
const next = tasks.slice();
next[index] = nextTask;
tasks = next;
captureObservedTask(nextTask);
if (changed) {
const lifecycleChanged = (
(updates.status !== undefined && updates.status !== task.status)
@@ -2023,7 +2072,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
backgroundEventsDuringRestore.set(event.transferId, pending);
return;
}
let existing = tasks.find((task) => task.id === event.transferId);
let existingIndex = tasks.findIndex((task) => task.id === event.transferId);
let existing = tasks[existingIndex];
const eventParent = event.parentTaskId
? tasks.find((task) => task.id === event.parentTaskId)
: undefined;
@@ -2039,7 +2089,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
directoryEntryIdentity: event.directoryEntryIdentity ?? task.directoryEntryIdentity,
background: false,
} : task);
existing = tasks.find((task) => task.id === event.transferId);
existing = tasks[existingIndex];
captureObservedTask(existing);
}
// A delayed child progress event can arrive after the renderer compacted
// that completed child into its parent checkpoint. Never resurrect it as
@@ -2119,6 +2170,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if ((event.type === "queued" || event.type === "started" || event.type === "progress") && !existing) {
const sourcePath = event.sourcePath ?? "";
const targetPath = event.targetPath ?? "";
existingIndex = tasks.length;
tasks.push({
id: event.transferId,
ownerId: eventParent?.ownerId
@@ -2352,6 +2404,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
phase: undefined,
} : task);
}
// Ownership changes must be observed synchronously even when a progress
// event takes the lightweight UI path. Reuse the located row, not a scan.
if (existingIndex >= 0) captureObservedTask(tasks[existingIndex]);
// Progress-only ticks skip prune + coalesce listener paints; lifecycle
// events still take the full emit path so UI never lags on pause/cancel.
if (event.type === "progress" && !persistImmediately) {
@@ -2,6 +2,7 @@ import { useEffect, useRef, type MutableRefObject } from 'react';
import {
STORAGE_KEY_AUTO_UPDATE_ENABLED,
STORAGE_KEY_CLOSE_TO_TRAY,
STORAGE_KEY_SHOW_TRAY_ICON,
STORAGE_KEY_AUTO_LAUNCH_ENABLED,
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
STORAGE_KEY_TOGGLE_WINDOW_HOTKEY,
@@ -42,6 +43,7 @@ interface UseSystemSettingsEffectsParams {
toggleWindowHotkey: string;
globalHotkeyEnabled: boolean;
closeToTray: boolean;
showTrayIcon: boolean;
autoLaunchEnabled: boolean;
windowOpacityRecord: WindowOpacityRecord;
windowOpacityMutationSourceRef: MutableRefObject<WindowOpacityMutationSource>;
@@ -62,6 +64,7 @@ export function useSystemSettingsEffects({
toggleWindowHotkey,
globalHotkeyEnabled,
closeToTray,
showTrayIcon,
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
@@ -173,6 +176,24 @@ export function useSystemSettingsEffects({
notifySettingsChanged(STORAGE_KEY_CLOSE_TO_TRAY, closeToTray);
}, [enabled, closeToTray, notifySettingsChanged, persistMountedRef]);
// Persist and sync the show-tray-icon setting. Runs after the close-to-tray
// effect above (declaration order) so a hidden icon destroys the tray that
// close-to-tray's mount-time push may have just created.
useEffect(() => {
if (!enabled) return;
// Update main process tray visibility (needed on mount)
const bridge = netcattyBridge.get();
if (bridge?.setShowTrayIcon) {
bridge.setShowTrayIcon(showTrayIcon).catch((err) => {
console.warn('[SystemTray] Failed to set show-tray-icon:', err);
});
}
localStorageAdapter.writeString(STORAGE_KEY_SHOW_TRAY_ICON, showTrayIcon ? 'true' : 'false');
// Skip IPC on initial mount
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_SHOW_TRAY_ICON, showTrayIcon);
}, [enabled, showTrayIcon, notifySettingsChanged, persistMountedRef]);
// Hydrate auto-launch from the main process on mount — the OS login item
// is the real source of truth (the user may have toggled it outside the
// app), localStorage is only an optimistic cache for first paint.
@@ -1,12 +0,0 @@
type Listener = (sessionId: string) => void;
const listeners = new Set<Listener>();
/** Renderer-local fan-out of the terminal's existing completion detection. */
export function publishTerminalCommandCompletion(sessionId: string): void {
for (const listener of listeners) listener(sessionId);
}
export function subscribeTerminalCommandCompletion(listener: Listener): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
+1 -1
View File
@@ -1,6 +1,6 @@
type Listener = () => void;
export type TerminalCwdSource = "osc7" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
export type TerminalCwdSource = "osc7" | "inferred" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
/**
* Live terminal CWD map + version token.
@@ -2,10 +2,15 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
clampTerminalSidePanelHeight,
clampTerminalSidePanelWidth,
getTerminalSidePanelAvailableWidth,
getTerminalSidePanelMaxShownTools,
getTerminalSidePanelMaxWidth,
getTerminalSidePanelAvailableHeight,
getTerminalSidePanelMaxHeight,
TERMINAL_SIDE_PANEL_MAX_HEIGHT,
TERMINAL_SIDE_PANEL_MIN_HEIGHT,
TERMINAL_SIDE_PANEL_MAX_WIDTH,
TERMINAL_SIDE_PANEL_MIN_WIDTH,
} from './terminalSidePanelWidth.ts';
@@ -34,3 +39,17 @@ test('terminal side panel keeps usable terminal space in smaller windows', () =>
assert.equal(clampTerminalSidePanelWidth(280, 1000, 401), 401);
assert.equal(clampTerminalSidePanelWidth(280, 600, 401), TERMINAL_SIDE_PANEL_MIN_WIDTH);
});
test('terminal side panel bottom dock clamps height against surface height', () => {
assert.equal(getTerminalSidePanelAvailableHeight(1000, 200), 800);
assert.equal(getTerminalSidePanelMaxHeight(1000), 760);
assert.equal(clampTerminalSidePanelHeight(900, 1000), 760);
assert.equal(clampTerminalSidePanelHeight(100, 1000), TERMINAL_SIDE_PANEL_MIN_HEIGHT);
assert.equal(clampTerminalSidePanelHeight(300, 1000, 500), 500);
assert.equal(clampTerminalSidePanelHeight(5000, 4000), TERMINAL_SIDE_PANEL_MAX_HEIGHT);
// A tall compose bar in the smallest window leaves less than the nominal
// panel minimum; the terminal's 240px reserve must still win.
assert.equal(getTerminalSidePanelMaxHeight(244), 4);
assert.equal(clampTerminalSidePanelHeight(560, 244), 4);
assert.equal(clampTerminalSidePanelHeight(560, 220), 0);
});
@@ -41,3 +41,37 @@ export function getTerminalSidePanelMaxShownTools(panelWidth: number): number {
),
);
}
export const TERMINAL_SIDE_PANEL_MIN_HEIGHT = 200;
export const TERMINAL_SIDE_PANEL_MAX_HEIGHT = 1200;
export const TERMINAL_SIDE_PANEL_MIN_TERMINAL_HEIGHT = 240;
// Shared tab toolbar rendered above the pane tree (`h-9`).
export const TERMINAL_SIDE_PANEL_TOOLBAR_HEIGHT = 36;
export function getTerminalSidePanelAvailableHeight(
terminalLayerHeight: number,
occupiedSiblingHeight: number,
): number {
return Math.max(0, terminalLayerHeight - occupiedSiblingHeight);
}
export function getTerminalSidePanelMaxHeight(availableSurfaceHeight: number): number {
const availableHeight = availableSurfaceHeight - TERMINAL_SIDE_PANEL_MIN_TERMINAL_HEIGHT;
return Math.max(
0,
Math.min(TERMINAL_SIDE_PANEL_MAX_HEIGHT, availableHeight),
);
}
export function clampTerminalSidePanelHeight(
height: number,
availableSurfaceHeight: number,
contentMinimumHeight = TERMINAL_SIDE_PANEL_MIN_HEIGHT,
): number {
const maximumHeight = getTerminalSidePanelMaxHeight(availableSurfaceHeight);
const minimumHeight = Math.min(
maximumHeight,
Math.max(TERMINAL_SIDE_PANEL_MIN_HEIGHT, contentMinimumHeight),
);
return Math.max(minimumHeight, Math.min(maximumHeight, height));
}
+8 -3
View File
@@ -174,10 +174,13 @@ export function useAgentDiscovery(
? { ...(ea.env ?? {}), CLAUDE_CODE_EXECUTABLE: matchPath }
: match.command === 'opencode'
? { ...(ea.env ?? {}), OPENCODE_BIN: matchPath }
: ea.env;
: match.command === 'mimo'
? { ...(ea.env ?? {}), MIMOCODE_BIN: matchPath }
: ea.env;
const envChanged =
(match.command === 'claude' && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath)
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath);
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath)
|| (match.command === 'mimo' && ea.env?.MIMOCODE_BIN !== matchPath);
const versionChanged = Boolean(match.version) && ea.cliVersion !== match.version;
if (currentArgs !== newArgs || backendChanged || envChanged || versionChanged) {
changed = true;
@@ -220,7 +223,9 @@ export function useAgentDiscovery(
? { env: { CLAUDE_CODE_EXECUTABLE: agent.binPath || agent.path || '' } }
: agent.command === 'opencode'
? { env: { OPENCODE_BIN: agent.binPath || agent.path || '' } }
: {}),
: agent.command === 'mimo'
? { env: { MIMOCODE_BIN: agent.binPath || agent.path || '' } }
: {}),
};
},
[],
+7 -1
View File
@@ -10,5 +10,11 @@ export const useClipboardBackend = () => {
return typeof text === "string" ? text : "";
}, []);
return { readClipboardText };
const writeClipboardText = useCallback(async (text: string): Promise<boolean> => {
const bridge = netcattyBridge.get();
if (!bridge?.writeClipboardText) return false;
return await bridge.writeClipboardText(text) === true;
}, []);
return { readClipboardText, writeClipboardText };
};
@@ -29,6 +29,9 @@ for (const codexRuntime of ['sdk', 'app-server'] as const) {
const config = { ...agent, codexRuntime };
await act(async () => { root = TestRenderer.create(React.createElement(Harness, { config })); });
assert.equal(result.model, null);
// The unresolved probe must be distinguishable from "no locked model"
// so consumers can hide manual entry until it resolves (#3535).
assert.equal(result.isPending, true);
let sent = false;
const sending = result.loadModel().then(model => { sent = true; return model; });
await Promise.resolve();
@@ -38,9 +41,11 @@ for (const codexRuntime of ['sdk', 'app-server'] as const) {
await act(async () => { resolve({ customConfig: { model: 'glm-5' } }); await sending; });
assert.equal(await sending, 'glm-5');
assert.equal(result.model, 'glm-5');
assert.equal(result.isPending, false);
// A different agent must not inherit the previous home/model or promise.
await act(async () => { root.update(React.createElement(Harness, { config: { ...config, env: { CODEX_HOME: '/fixture/other' } } })); });
assert.equal(result.model, null);
assert.equal(result.isPending, true);
assert.equal(calls.length, 2);
await act(async () => { resolve({ customConfig: null }); await result.loadModel(); });
assert.equal(result.model, null);
+7 -1
View File
@@ -29,5 +29,11 @@ export function useCodexConfigModel(agent: ExternalAgentConfig | undefined, isVi
});
return () => { cancelled = true; };
}, [isVisible, loadModel]);
return { model: result?.loadModel === loadModel ? result.model : null, loadModel };
return {
model: result?.loadModel === loadModel ? result.model : null,
loadModel,
// `model` is null both while the probe is pending and when no locked model
// exists; this flag lets consumers distinguish the unresolved state.
isPending: result?.loadModel !== loadModel,
};
}
@@ -201,3 +201,96 @@ test("managed sync writes the latest persisted hosts, not the pre-edit snapshot"
});
}
});
test("managed source deletion preserves the file when its contents cannot be read", async () => {
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost",
});
const globalAny = globalThis as Record<string, unknown>;
const saved = {
window: globalAny.window,
document: globalAny.document,
localStorage: globalAny.localStorage,
navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"),
actEnv: (globalAny as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT,
};
Object.defineProperty(globalThis, "window", { configurable: true, value: dom.window });
Object.defineProperty(globalThis, "document", { configurable: true, value: dom.window.document });
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: dom.window.localStorage });
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: { locks: createFakeLockManager() },
});
Object.defineProperty(globalAny, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
const container = dom.window.document.createElement("div");
dom.window.document.body.appendChild(container);
const original = "# Keep this comment\nHost outside\n HostName outside.example.com\n"
+ "# BEGIN NETCATTY MANAGED - DO NOT EDIT THIS BLOCK\n"
+ "Host managed\n HostName managed.example.com\n"
+ "# END NETCATTY MANAGED\n";
let fileContent = original;
let writes = 0;
let failRead = true;
(dom.window as unknown as Record<string, unknown>).netcatty = {
readLocalFile: async () => {
if (failRead) throw new Error("EIO: simulated read failure");
return new TextEncoder().encode(fileContent).buffer;
},
writeLocalFile: async (_filePath: string, buffer: ArrayBuffer) => {
writes += 1;
fileContent = new TextDecoder().decode(buffer);
},
};
let clearAndRemoveSource!: ReturnType<typeof useManagedSourceSync>["clearAndRemoveSource"];
function Harness() {
({ clearAndRemoveSource } = useManagedSourceSync({
hosts: [],
managedSources: [],
onUpdateManagedSources: () => {},
onReadPersistedHosts: async () => [],
}));
return null;
}
const root = createRoot(container);
try {
await act(async () => root.render(React.createElement(Harness)));
await assert.rejects(clearAndRemoveSource(managedSource), /Could not clear managed SSH config source/);
assert.equal(writes, 0);
assert.equal(fileContent, original);
failRead = false;
await clearAndRemoveSource(managedSource);
assert.equal(writes, 1);
assert.match(fileContent, /Host outside/);
assert.doesNotMatch(fileContent, /Host managed/);
} finally {
await act(async () => root.unmount());
container.remove();
dom.window.close();
for (const key of ["window", "document", "localStorage"] as const) {
if (key in globalAny) {
Object.defineProperty(globalThis, key, {
configurable: true,
enumerable: true,
writable: true,
value: saved[key],
});
} else {
delete globalAny[key];
}
}
if (saved.navigator) {
Object.defineProperty(globalThis, "navigator", saved.navigator);
} else {
delete (globalThis as { navigator?: unknown }).navigator;
}
Object.defineProperty(globalAny, "IS_REACT_ACT_ENVIRONMENT", {
configurable: true,
value: saved.actEnv,
});
}
});
+6 -12
View File
@@ -55,26 +55,20 @@ export const useManagedSourceSync = ({
);
const readExistingFileContent = useCallback(
async (filePath: string): Promise<string | null> => {
async (filePath: string): Promise<string> => {
const bridge = netcattyBridge.get();
if (!bridge?.readLocalFile) {
return null;
}
try {
const buffer = await bridge.readLocalFile(filePath);
const decoder = new TextDecoder();
return decoder.decode(buffer);
} catch {
// File might not exist yet
return null;
throw new Error("readLocalFile not available");
}
const buffer = await bridge.readLocalFile(filePath);
return new TextDecoder().decode(buffer);
},
[],
);
const mergeWithExistingContent = useCallback(
(
existingContent: string | null,
existingContent: string,
managedHosts: Host[],
allHosts: Host[],
): string => {
@@ -82,7 +76,7 @@ export const useManagedSourceSync = ({
const managedContent = serializeHostsToSshConfig(managedHosts, allHosts);
if (!existingContent) {
// No existing file, just wrap the managed content
// The existing file is empty; wrap the managed content.
return `${MANAGED_BLOCK_BEGIN}\n${managedContent}${MANAGED_BLOCK_END}\n`;
}
+155
View File
@@ -352,3 +352,158 @@ test("manual stop still returns its recording and permits a clean restart", asyn
assert.equal(recorder!.isRecording, true);
await act(async () => renderer!.unmount());
});
test("confirmed line-by-line recording awaits each send and prompt step in order", async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
let appendGate: Promise<void> | undefined;
let stopCalls = 0;
const steps: Array<{ type: string; value?: unknown; sensitive?: boolean }> = [];
const eventTarget = new EventTarget();
Object.assign(eventTarget, {
netcatty: {
scriptRecordingStart: async () => ({ ok: true }),
scriptRecordingStop: async () => { stopCalls++; return { steps: [...steps], code: "" }; },
scriptRecordingAppendStep: async (_id: string, step: typeof steps[number]) => {
await appendGate;
await new Promise(resolve => setImmediate(resolve));
steps.push(step);
return { stopped: false };
},
},
setInterval, clearInterval,
});
Object.defineProperty(globalThis, "window", { configurable: true, value: eventTarget });
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
let recorder!: Recorder;
let renderer!: ReactTestRenderer;
function Probe() { recorder = useScriptRecorder("session-1"); return null; }
await act(async () => { renderer = create(React.createElement(Probe)); });
try {
await act(async () => { await recorder.startRecording(); });
await act(async () => {
recorder.recordInput("echo ");
const recordLine = recorder.captureSubmittedLineRecorder()!;
recorder.recordInput("new input");
await Promise.all([recordLine("echo first"), recordLine("cd /tmp")]);
});
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "echo first"], ["waitForPrompt", undefined],
["send", "cd /tmp"], ["waitForPrompt", undefined],
]);
steps.length = 0;
await act(async () => {
await recorder.recordEnter();
assert.equal(steps[0].value, "new input");
steps.length = 0;
const recordLine = recorder.captureSubmittedLineRecorder()!;
await Promise.all([recordLine("secret", { sensitive: true }), recordLine("second secret", { sensitive: true })]);
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.sensitive), [true, true]);
const staleRecorder = recorder.captureSubmittedLineRecorder()!;
await act(async () => { await recorder.stopRecording(); await recorder.startRecording(); });
steps.length = 0;
await act(async () => { await staleRecorder("never sent in this recording"); });
assert.deepEqual(steps, []);
const pauseGate = deferred<void>();
appendGate = pauseGate.promise;
const beforePause = recorder.captureSubmittedLineRecorder()!;
const pausedFirst = beforePause("sent before pause 1");
const pausedSecond = beforePause("sent before pause 2");
await flushReact();
act(() => recorder.pauseRecording());
await beforePause("ignored while paused");
pauseGate.resolve();
await act(async () => { await Promise.all([pausedFirst, pausedSecond]); });
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "sent before pause 1"], ["waitForPrompt", undefined],
["send", "sent before pause 2"], ["waitForPrompt", undefined],
]);
act(() => recorder.resumeRecording());
steps.length = 0;
const gate = deferred<void>();
appendGate = gate.promise;
const recordLine = recorder.captureSubmittedLineRecorder()!;
const first = recordLine("sent first");
const second = recordLine("sent second");
await flushReact();
let stopped!: ReturnType<Recorder["stopRecording"]>;
act(() => { stopped = recorder.stopRecording(); });
assert.equal(stopCalls, 1);
await recordLine("arrived after stop");
gate.resolve();
await act(async () => { await Promise.all([first, second, stopped]); });
assert.equal(stopCalls, 2);
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "sent first"], ["waitForPrompt", undefined],
["send", "sent second"], ["waitForPrompt", undefined],
]);
} finally {
await act(async () => renderer.unmount());
}
});
test("paced recording uses its captured prefix and never imports text typed while paused", async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const steps: Array<{ type: string; value?: unknown }> = [];
const target = new EventTarget();
Object.assign(target, {
netcatty: {
scriptRecordingStart: async () => ({ ok: true }),
scriptRecordingAppendStep: async (_id: string, step: typeof steps[number]) => {
steps.push(step);
return { stopped: false };
},
}, setInterval, clearInterval,
});
Object.defineProperty(globalThis, "window", { configurable: true, value: target });
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
let recorder!: Recorder;
let renderer!: ReactTestRenderer;
function Probe() { recorder = useScriptRecorder("s"); return null; }
await act(async () => { renderer = create(React.createElement(Probe)); });
try {
await act(async () => {
await recorder.startRecording();
recorder.recordInput("echo ");
recorder.pauseRecording();
recorder.recordInput("PAUSED_");
recorder.resumeRecording();
const lineRecorder = recorder.captureSubmittedLineRecorder()!;
recorder.recordInput("next input");
await lineRecorder("first", { includePendingInput: true });
await lineRecorder("second");
await recorder.recordEnter();
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["echo first", "second", "next input"]);
steps.length = 0;
await act(async () => {
recorder.recordInput("preserved ");
recorder.captureSubmittedLineRecorder(); // No write receipt: rejected batch.
recorder.recordInput("draft");
await recorder.recordEnter();
assert.equal(steps.find(step => step.type === "send")?.value, "preserved draft");
steps.length = 0;
recorder.recordInput("old ");
const lateReceipt = recorder.captureSubmittedLineRecorder()!;
recorder.recordClearLine();
recorder.recordInput("old new draft");
await lateReceipt("sent", { includePendingInput: true });
await recorder.recordEnter();
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["old sent", "old new draft"]);
steps.length = 0;
recorder.recordInput("prefix for a dropped first line");
const lineRecorder = recorder.captureSubmittedLineRecorder()!;
await lineRecorder("second was sent", { consumePendingInput: false });
await recorder.recordEnter();
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["second was sent", "prefix for a dropped first line"]);
} finally {
await act(async () => renderer.unmount());
}
});
+67 -20
View File
@@ -27,12 +27,16 @@ export function useScriptRecorder(sessionId: string | undefined) {
const [elapsedMs, setElapsedMs] = useState(0);
const startedAtRef = useRef<number | null>(null);
const inputBufferRef = useRef('');
const inputRevisionRef = useRef(0);
const lastStepAtRef = useRef<number>(Date.now());
const isRecordingRef = useRef(false);
const isPausedRef = useRef(false);
const isStoppingRef = useRef(false);
const stopPromiseRef = useRef<Promise<ScriptRecordingResult> | null>(null);
const sessionIdRef = useRef(sessionId);
const recordingGenerationRef = useRef(0);
const pendingRecordStepsRef = useRef(Promise.resolve());
const isDrainingRecordingRef = useRef(false);
sessionIdRef.current = sessionId;
@@ -60,8 +64,10 @@ export function useScriptRecorder(sessionId: string | undefined) {
const bridge = netcattyBridge.get();
if (!sid || !bridge?.scriptRecordingStart) return;
await bridge.scriptRecordingStart(sid);
recordingGenerationRef.current += 1;
startedAtRef.current = Date.now();
lastStepAtRef.current = Date.now();
inputRevisionRef.current += 1;
inputBufferRef.current = '';
setElapsedMs(0);
setIsPaused(false);
@@ -76,27 +82,26 @@ export function useScriptRecorder(sessionId: string | undefined) {
const sid = sessionIdRef.current;
const bridge = netcattyBridge.get();
isStoppingRef.current = true;
isDrainingRecordingRef.current = true;
isRecordingRef.current = false;
isPausedRef.current = false;
setIsRecording(false);
setIsPaused(false);
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
if (!sid || !bridge?.scriptRecordingStop) {
isStoppingRef.current = false;
isDrainingRecordingRef.current = false;
return emptyScriptRecordingResult();
}
let stopRequest: Promise<ScriptRecordingResult>;
try {
stopRequest = Promise.resolve(bridge.scriptRecordingStop(sid));
} catch (error) {
stopRequest = Promise.reject(error);
}
const stopRequest = pendingRecordStepsRef.current.catch(() => {}).then(() => bridge.scriptRecordingStop!(sid));
let stopPromise: Promise<ScriptRecordingResult>;
stopPromise = stopRequest.finally(() => {
if (stopPromiseRef.current === stopPromise) {
stopPromiseRef.current = null;
isStoppingRef.current = false;
isDrainingRecordingRef.current = false;
}
});
stopPromiseRef.current = stopPromise;
@@ -104,8 +109,10 @@ export function useScriptRecorder(sessionId: string | undefined) {
}, []);
const finishAutomaticStop = useCallback((detail: ScriptRecordingLimitDetail) => {
isDrainingRecordingRef.current = false;
isRecordingRef.current = false;
isPausedRef.current = false;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
setIsRecording(false);
@@ -126,10 +133,13 @@ export function useScriptRecorder(sessionId: string | undefined) {
setIsPaused(false);
}, []);
const appendStep = useCallback(async (step: ScriptRecordingStep) => {
const appendStep = useCallback(async (step: ScriptRecordingStep, accepted = false) => {
const sid = sessionIdRef.current;
if (!sid || !isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
if (!sid || (!(accepted && isDrainingRecordingRef.current)
&& (!isRecordingRef.current || (!accepted && isPausedRef.current) || isStoppingRef.current))) return;
const generation = recordingGenerationRef.current;
const result = await netcattyBridge.get()?.scriptRecordingAppendStep?.(sid, step);
if (generation !== recordingGenerationRef.current || sid !== sessionIdRef.current) return;
if (result?.stopped) {
finishAutomaticStop({
sessionId: sid,
@@ -154,6 +164,7 @@ export function useScriptRecorder(sessionId: string | undefined) {
isStoppingRef.current = true;
isRecordingRef.current = false;
isPausedRef.current = false;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
setIsRecording(false);
@@ -188,33 +199,68 @@ export function useScriptRecorder(sessionId: string | undefined) {
const recordBackspace = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
inputRevisionRef.current += 1;
inputBufferRef.current = inputBufferRef.current.slice(0, -1);
}, []);
const recordClearLine = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
}, []);
const recordEnter = useCallback(async (options?: { sensitive?: boolean }) => {
const recordEnter = useCallback(async (options?: { sensitive?: boolean; submittedLine?: string }) => {
const sid = sessionIdRef.current;
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current || !sid) return;
const line = inputBufferRef.current;
inputBufferRef.current = '';
const line = options?.submittedLine ?? inputBufferRef.current;
if (options?.submittedLine === undefined) {
inputRevisionRef.current += 1;
inputBufferRef.current = '';
}
const now = Date.now();
const gap = now - lastStepAtRef.current;
if (gap > 1000) {
await appendStep({ type: 'sleep', value: gap });
}
await appendStep({
type: 'send',
value: line,
sensitive: options?.sensitive,
});
await appendStep({ type: 'waitForPrompt', timeoutMs: DEFAULT_RECORDING_PROMPT_TIMEOUT_MS });
lastStepAtRef.current = now;
const generation = recordingGenerationRef.current;
const pending = pendingRecordStepsRef.current.catch(() => {}).then(async () => {
const isCurrent = () => generation === recordingGenerationRef.current && sid === sessionIdRef.current
&& (isRecordingRef.current || isDrainingRecordingRef.current);
if (!isCurrent()) return;
if (gap > 1000) await appendStep({ type: 'sleep', value: gap }, true);
if (!isCurrent()) return;
await appendStep({ type: 'send', value: line, sensitive: options?.sensitive }, true);
if (!isCurrent()) return;
await appendStep({ type: 'waitForPrompt', timeoutMs: DEFAULT_RECORDING_PROMPT_TIMEOUT_MS }, true);
});
pendingRecordStepsRef.current = pending;
await pending;
}, [appendStep]);
// Delayed paste receipts must not consume newly typed input or leak into a
// recording started after the paste. Each receipt records one actual write.
const captureSubmittedLineRecorder = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return undefined;
const generation = recordingGenerationRef.current;
const sid = sessionIdRef.current;
const pendingInput = inputBufferRef.current;
const revision = inputRevisionRef.current;
let consumed = false;
const isCurrent = () => generation === recordingGenerationRef.current
&& sid === sessionIdRef.current && isRecordingRef.current
&& !isPausedRef.current && !isStoppingRef.current;
return (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }): Promise<void> => {
// Capturing a batch is not a write. Retain its prefix if no receipt
// arrives; only its prefixed first line can consume the still-owned draft.
if (options?.consumePendingInput !== false && !consumed && generation === recordingGenerationRef.current && sid === sessionIdRef.current
&& revision === inputRevisionRef.current && inputBufferRef.current.startsWith(pendingInput)) {
inputBufferRef.current = inputBufferRef.current.slice(pendingInput.length);
inputRevisionRef.current += 1;
}
if (options?.consumePendingInput !== false) consumed = true;
if (!isCurrent()) return Promise.resolve();
return recordEnter({ sensitive: options?.sensitive, submittedLine: options?.includePendingInput ? `${pendingInput}${line}` : line });
};
}, [recordEnter]);
return {
isRecording,
isPaused,
@@ -227,5 +273,6 @@ export function useScriptRecorder(sessionId: string | undefined) {
recordBackspace,
recordClearLine,
recordEnter,
captureSubmittedLineRecorder,
};
}
+12
View File
@@ -33,6 +33,10 @@ export interface ServerStats {
cpu: number | null; // CPU usage percentage (0-100)
cpuCores: number | null; // Number of CPU cores
cpuPerCore: number[]; // Per-core CPU usage array
gpu: number | null; // NVIDIA GPU utilization percentage (0-100), null when no GPU data
gpuName: string | null; // First GPU name (tooltip)
gpuMemUsed: number | null; // Summed VRAM used in MB
gpuMemTotal: number | null; // Summed VRAM total in MB
memTotal: number | null; // Total memory in MB
memUsed: number | null; // Used memory in MB (excluding buffers/cache)
memFree: number | null; // Free memory in MB
@@ -107,6 +111,10 @@ function createEmptyServerStats(): ServerStats {
cpu: null,
cpuCores: null,
cpuPerCore: [],
gpu: null,
gpuName: null,
gpuMemUsed: null,
gpuMemTotal: null,
memTotal: null,
memUsed: null,
memFree: null,
@@ -200,6 +208,10 @@ function normalizeServerStats(stats: Partial<ServerStats>): ServerStats {
cpu: stats.cpu ?? null,
cpuCores: stats.cpuCores ?? null,
cpuPerCore: stats.cpuPerCore || [],
gpu: stats.gpu ?? null,
gpuName: stats.gpuName ?? null,
gpuMemUsed: stats.gpuMemUsed ?? null,
gpuMemTotal: stats.gpuMemTotal ?? null,
memTotal: stats.memTotal ?? null,
memUsed: stats.memUsed ?? null,
memFree: stats.memFree ?? null,
+16
View File
@@ -66,6 +66,8 @@ import {
getSessionConnectionLabel,
} from '../../domain/sessionTabTitle';
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import { useVaultSnapshotField } from './vaultSnapshotStore';
export function addWorkspaceIfMissing(
workspaces: Workspace[],
@@ -267,6 +269,20 @@ export const useSessionState = ({
}
}, [initialRestoreState.activeTabId]);
// Keep open sessions' connection label in sync with the vault. Sessions
// snapshot `hostLabel` at connect time, so renaming a host would otherwise
// leave its already-open tabs (and merged-workspace titles derived from
// those labels) showing the old name until the session is closed. The
// generated-title sync effect below re-runs on this session change and
// refreshes synthesized workspace titles too.
const vaultHosts = useVaultSnapshotField('hosts');
useEffect(() => {
if (vaultHosts.length === 0) return;
// The helper returns the same array reference when nothing changed, so
// React bails out of the state update.
setSessions(prev => syncSessionHostLabels(prev, vaultHosts));
}, [vaultHosts]);
// Keep generated merged-workspace titles (e.g. "01/02" after dragging tab
// "02" onto "01") synchronized with the workspace's current membership and
// each pane's connection label. `autoTitle: false` makes
@@ -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 { EMPTY_VAULT_SNAPSHOT, publishVaultSnapshot } from "./vaultSnapshotStore";
import { useSessionState } from "./useSessionState.ts";
type SessionState = ReturnType<typeof useSessionState>;
const testHost = (overrides: Partial<Host> = {}): Host => ({
id: "host-1",
label: "web-01",
hostname: "10.0.0.1",
port: 22,
username: "root",
os: "linux",
tags: [],
...overrides,
} as Host);
test("rewriting the host label updates already-open session tabs on that host", async (t) => {
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
t.after(() => publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT));
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const eventTarget = new EventTarget() as EventTarget & Record<string, unknown>;
Object.assign(eventTarget, { setTimeout, clearTimeout });
Object.defineProperty(globalThis, "window", {
configurable: true,
value: eventTarget,
});
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
const actEnvironment = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
};
const previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
t.after(() => {
actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
});
let state: SessionState | null = null;
let renderer: ReactTestRenderer | null = null;
const current = (): SessionState => {
assert.ok(state);
return state;
};
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return null;
}
await act(async () => {
renderer = create(React.createElement(Probe));
});
let sessionId = "";
await act(async () => {
sessionId = current().connectToHost(testHost());
});
const sessionOf = () => current().sessions.find((s) => s.id === sessionId);
assert.ok(sessionOf());
assert.equal(sessionOf()?.hostLabel, "web-01");
// The host is renamed in the vault while the session stays open.
await act(async () => {
publishVaultSnapshot({
...EMPTY_VAULT_SNAPSHOT,
hosts: [testHost({ label: "web-01-renamed" })],
});
});
assert.equal(sessionOf()?.hostLabel, "web-01-renamed");
// Renaming the pane afterwards hands the title to the user rename.
await act(async () => {
current().submitSessionRename(sessionId, "my pane");
});
const renamed = sessionOf();
assert.ok(renamed);
assert.equal(renamed!.customName, "my pane");
// A later vault rename must not clobber the user-authored pane name.
await act(async () => {
publishVaultSnapshot({
...EMPTY_VAULT_SNAPSHOT,
hosts: [testHost({ label: "web-01-again" })],
});
});
const after = sessionOf();
assert.ok(after);
assert.equal(after!.customName, "my pane");
await act(async () => {
renderer?.unmount();
});
});
+57 -22
View File
@@ -1,4 +1,3 @@
import { normalizeTabBarPosition, type TabBarPosition } from '../../domain/tabBarPosition';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type SetStateAction } from 'react';
import { runThemeTransition, type ThemeTransitionMode } from './themeTransition';
@@ -68,6 +67,7 @@ import {
STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED,
STORAGE_KEY_TOGGLE_WINDOW_HOTKEY,
STORAGE_KEY_CLOSE_TO_TRAY,
STORAGE_KEY_SHOW_TRAY_ICON,
STORAGE_KEY_AUTO_LAUNCH_ENABLED,
STORAGE_KEY_HTTP_NETWORK_PROXY,
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
@@ -79,10 +79,11 @@ import {
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
STORAGE_KEY_SHOW_SFTP_TAB,
STORAGE_KEY_TAB_BAR_POSITION,
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
@@ -415,9 +416,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT);
return stored ?? DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT;
});
const [tabBarPosition, setTabBarPositionState] = useState<TabBarPosition>(() =>
normalizeTabBarPosition(readStoredString(STORAGE_KEY_TAB_BAR_POSITION)),
);
const [showSftpTab, setShowSftpTabState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_SFTP_TAB);
return stored ?? DEFAULT_SHOW_SFTP_TAB;
@@ -434,6 +432,14 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const stored = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
return isTerminalSidePanelAutoOpenTab(stored) ? stored : DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB;
});
const [localShellSidePanelAutoOpen, setLocalShellSidePanelAutoOpenState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN);
return stored ?? false;
});
const [localShellSidePanelAutoOpenTab, setLocalShellSidePanelAutoOpenTabState] = useState<TerminalSidePanelAutoOpenTab>(() => {
const stored = readStoredString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB);
return isTerminalSidePanelAutoOpenTab(stored) ? stored : 'scripts';
});
const [shellOnlyTabNumberShortcuts, setShellOnlyTabNumberShortcutsState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
return stored ?? DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS;
@@ -545,6 +551,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
if (stored === null) return true;
return stored === 'true';
});
// Preserve the old tray visibility for existing users until they set this
// independently. Fresh installs still default to showing the icon.
const [showTrayIcon, setShowTrayIcon] = useState<boolean>(() => {
const stored = readStoredString(STORAGE_KEY_SHOW_TRAY_ICON);
if (stored === null) return closeToTray;
return stored === 'true';
});
// Optimistic cache for first paint; useSystemSettingsEffects hydrates this
// from app.getLoginItemSettings() (the real source of truth) on mount.
const [autoLaunchEnabled, setAutoLaunchEnabled] = useState<boolean>(() => {
@@ -1017,7 +1030,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
);
const storedShowOnlyUngroupedHostsInRoot = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT);
setShowOnlyUngroupedHostsInRootState(storedShowOnlyUngroupedHostsInRoot ?? DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT);
setTabBarPositionState(normalizeTabBarPosition(readStoredString(STORAGE_KEY_TAB_BAR_POSITION)));
const storedShowSftpTab = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_SFTP_TAB);
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
@@ -1030,6 +1042,14 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
? storedTerminalSidePanelAutoOpenTab
: DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
);
const storedLocalShellSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN);
setLocalShellSidePanelAutoOpenState(storedLocalShellSidePanelAutoOpen ?? false);
const storedLocalShellSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB);
setLocalShellSidePanelAutoOpenTabState(
isTerminalSidePanelAutoOpenTab(storedLocalShellSidePanelAutoOpenTab)
? storedLocalShellSidePanelAutoOpenTab
: 'scripts',
);
const storedShellOnlyTabNumberShortcuts = localStorageAdapter.readBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
setShellOnlyTabNumberShortcutsState(storedShellOnlyTabNumberShortcuts ?? DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
const storedShowTabNumberBadges = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_TAB_NUMBER_BADGES);
@@ -1204,10 +1224,11 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setSftpFollowTerminalCwd,
setSftpDefaultViewMode,
setWorkspaceFocusStyleState,
setTabBarPositionState,
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
@@ -1261,7 +1282,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode,
@@ -1271,7 +1292,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
@@ -1401,14 +1422,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
notifySettingsChanged(STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT, enabled);
}, [notifySettingsChanged]);
const setTabBarPosition = useCallback((value: TabBarPosition) => {
const next = normalizeTabBarPosition(value);
setTabBarPositionState(next);
localStorageAdapter.writeString(STORAGE_KEY_TAB_BAR_POSITION, next);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_TAB_BAR_POSITION, next);
}, [notifySettingsChanged]);
const setShowSftpTab = useCallback((enabled: boolean) => {
setShowSftpTabState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_SHOW_SFTP_TAB, enabled);
@@ -1438,6 +1451,21 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
notifySettingsChanged(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB, next);
}, [notifySettingsChanged]);
const setLocalShellSidePanelAutoOpen = useCallback((enabled: boolean) => {
setLocalShellSidePanelAutoOpenState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, enabled);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, enabled);
}, [notifySettingsChanged]);
const setLocalShellSidePanelAutoOpenTab = useCallback((tab: TerminalSidePanelAutoOpenTab) => {
const next = isTerminalSidePanelAutoOpenTab(tab) ? tab : 'scripts';
setLocalShellSidePanelAutoOpenTabState(next);
localStorageAdapter.writeString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, next);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, next);
}, [notifySettingsChanged]);
const setShellOnlyTabNumberShortcuts = useCallback((enabled: boolean) => {
setShellOnlyTabNumberShortcutsState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS, enabled);
@@ -1771,6 +1799,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
toggleWindowHotkey,
globalHotkeyEnabled,
closeToTray,
showTrayIcon,
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
@@ -1880,7 +1909,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
darkUiThemeId,
uiLanguage,
windowOpacity,
tabBarPosition,
showSftpTab,
showHostTreeSidebar,
showRecentHosts,
@@ -1894,6 +1922,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
restoreTerminalCwd,
terminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
});
}, [
darkUiThemeId,
@@ -1907,7 +1937,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
showHostTreeSidebar,
showOnlyUngroupedHostsInRoot,
showRecentHosts,
tabBarPosition,
showSftpTab,
showTabNumberBadges,
terminalSettings.dynamicTabTitleMode,
@@ -1916,6 +1945,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
theme,
uiLanguage,
windowOpacity,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
]);
useLayoutEffect(() => {
@@ -2080,9 +2111,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setHostClickBehavior,
showOnlyUngroupedHostsInRoot,
setShowOnlyUngroupedHostsInRoot,
tabBarPosition,
showSftpTab,
setTabBarPosition,
setShowSftpTab,
showHostTreeSidebar,
setShowHostTreeSidebar,
@@ -2090,6 +2119,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
setTerminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
setLocalShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
setLocalShellSidePanelAutoOpenTab,
shellOnlyTabNumberShortcuts,
setShellOnlyTabNumberShortcuts,
showTabNumberBadges,
@@ -2132,6 +2165,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setToggleWindowHotkey,
closeToTray,
setCloseToTray,
showTrayIcon,
setShowTrayIcon,
autoLaunchEnabled,
setAutoLaunchEnabled,
autoLaunchSupported,
@@ -2158,7 +2193,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, terminalFontFamilyId, terminalFontSize, terminalSettings,
customKeyBindings, editorWordWrap,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom,
customThemes, workspaceFocusStyle, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
]),
};
+4
View File
@@ -469,6 +469,7 @@ export const useSftpState = (
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -781,6 +782,7 @@ export const useSftpState = (
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -857,6 +859,8 @@ export const useSftpState = (
deleteFiles: (...args: Parameters<typeof deleteFiles>) => methodsRef.current.deleteFiles(...args),
deleteFilesAtPath: (...args: Parameters<typeof deleteFilesAtPath>) =>
methodsRef.current.deleteFilesAtPath(...args),
removeListedNames: (...args: Parameters<typeof removeListedNames>) =>
methodsRef.current.removeListedNames(...args),
renameFile: (...args: Parameters<typeof renameFile>) => methodsRef.current.renameFile(...args),
renameFileAtPath: (...args: Parameters<typeof renameFileAtPath>) => methodsRef.current.renameFileAtPath(...args),
moveEntriesToPath: (...args: Parameters<typeof moveEntriesToPath>) => methodsRef.current.moveEntriesToPath(...args),
+3
View File
@@ -15,6 +15,9 @@ function delay(ms: number): Promise<void> {
function normalizePollingErrorMessage(error: unknown, t: I18nContextValue['t']): string {
const message = error instanceof Error ? error.message : String(error || 'Unknown error');
const lower = message.toLowerCase();
if (lower.includes('extra exec channels')) {
return t('systemManager.unsupportedRemote');
}
if (lower.includes('channel open failure') || lower.includes('unable to exec')) {
return t('systemManager.errors.sshChannelUnavailable');
}
+12 -4
View File
@@ -202,13 +202,19 @@ export const useTerminalBackend = () => {
bridge?.writeToSession?.(sessionId, data, options);
}, []);
const interruptSession = useCallback((sessionId: string, trace?: NetcattyTerminalInterruptTrace) => {
const notifyUserInput = useCallback((sessionId: string) => {
const bridge = netcattyBridge.get();
bridge?.notifySessionUserInput?.(sessionId);
}, []);
const interruptSession = useCallback((...args: Parameters<NonNullable<NetcattyBridge["interruptSession"]>>) => {
const [sessionId, , options] = args;
const bridge = netcattyBridge.get();
if (bridge?.interruptSession) {
bridge.interruptSession(sessionId, trace);
bridge.interruptSession(...args);
return;
}
bridge?.writeToSession?.(sessionId, "\x03");
if (!options?.cancelPendingWritesOnly) bridge?.writeToSession?.(sessionId, "\x03");
}, []);
const resizeSession = useCallback((sessionId: string, cols: number, rows: number) => {
@@ -515,7 +521,7 @@ export const useTerminalBackend = () => {
const getSessionPwd = useCallback(async (
sessionId: string,
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean },
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean; timeoutMs?: number },
) => {
const bridge = netcattyBridge.get();
if (!bridge?.getSessionPwd) return { success: false, error: 'getSessionPwd unavailable' };
@@ -593,6 +599,7 @@ export const useTerminalBackend = () => {
getSessionDistroInfo,
getServerStats,
writeToSession,
notifyUserInput,
interruptSession,
resizeSession,
clearSessionPtyBuffer,
@@ -675,6 +682,7 @@ export const useTerminalBackend = () => {
getSessionDistroInfo,
getServerStats,
writeToSession,
notifyUserInput,
interruptSession,
resizeSession,
clearSessionPtyBuffer,
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import {
applyAgentNotesUpdate,
haveSameVaultAgentSnapshot,
resolveVaultAgentEffectiveHost,
resolveVaultAgentNotes,
@@ -27,6 +28,33 @@ describe('haveSameVaultAgentSnapshot', () => {
});
});
describe('applyAgentNotesUpdate', () => {
it('rolls back an unsaved agent note before a later successful write', () => {
const oldNotes = [{ id: 'old', title: 'Old', content: 'old', createdAt: 1, updatedAt: 1 }];
const noteA = { id: 'a', title: 'A', content: 'a', createdAt: 2, updatedAt: 2 };
const noteB = { id: 'b', title: 'B', content: 'b', createdAt: 3, updatedAt: 3 };
let inMemory = oldNotes;
let persisted = oldNotes;
let failNext = true;
const updateNotes = (notes: typeof oldNotes) => {
inMemory = notes;
if (failNext) {
failNext = false;
return false;
}
persisted = notes;
return true;
};
assert.equal(applyAgentNotesUpdate([...oldNotes, noteA], oldNotes, updateNotes), false);
assert.deepEqual(inMemory, oldNotes);
assert.deepEqual(persisted, oldNotes);
assert.equal(applyAgentNotesUpdate([...inMemory, noteB], inMemory, updateNotes), true);
assert.deepEqual(persisted.map((note) => note.id), ['old', 'b']);
});
});
describe('resolveVaultAgentEffectiveHost', () => {
it('uses the latest snapshotted group defaults', () => {
const host: Host = {
+19 -2
View File
@@ -89,6 +89,20 @@ export function resolveVaultAgentNotes(
: (getNotesSnapshot().notes as VaultNote[]);
}
export function applyAgentNotesUpdate(
notes: VaultNote[],
previousNotes: VaultNote[],
updateNotes: (notes: VaultNote[]) => boolean | void,
): boolean | void {
const saved = updateNotes(notes);
if (saved === false) {
// Editor autosave keeps failed writes in memory so a draft is not lost.
// Agent writes must roll that draft back before another approved write.
updateNotes(previousNotes);
}
return saved;
}
export const haveSameVaultAgentSnapshot = (
left: VaultAgentSnapshot,
right: VaultAgentSnapshot,
@@ -145,6 +159,7 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
?? ((notes: VaultNote[]) => {
console.warn('[useVaultAgentBridge] updateNotes unavailable');
void notes;
return false;
});
return handleVaultAgentOp(op, params, {
getHosts: () => vaultSnapshotRef.current.hosts,
@@ -239,8 +254,10 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
vaultSnapshotRef.current.notes = notes;
applyUpdateNotes(notes);
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
@@ -4,7 +4,7 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { GroupConfig, ManagedSource } from "../../domain/models.ts";
import { useVaultGroupDeletion } from "./useVaultGroupDeletion.ts";
import { useVaultGroupDeletion, VaultGroupDeletionConfirmationChangedError } from "./useVaultGroupDeletion.ts";
test("group deletion removes saved settings in the same Vault transaction", async () => {
const actEnvironment = globalThis as typeof globalThis & {
@@ -132,7 +132,7 @@ test("group deletion restores managed files when the persisted Vault cannot be r
assert.equal(commitCount, 0);
});
test("group deletion retries file clearing when another managed source enters the group", async () => {
test("group deletion rejects retry when another managed source enters the group", async () => {
const actEnvironment = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
};
@@ -198,7 +198,7 @@ test("group deletion retries file clearing when another managed source enters th
renderer = create(React.createElement(Probe));
});
await act(async () => {
await deleteGroups?.(["Production"]);
await assert.rejects(deleteGroups!(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
} finally {
await act(async () => {
@@ -209,10 +209,9 @@ test("group deletion retries file clearing when another managed source enters th
assert.deepEqual(clearedSourceIds, [
["managed-first"],
["managed-concurrent", "managed-first"],
]);
assert.equal(restoreCount, 1);
assert.equal(commitCount, 1);
assert.equal(commitCount, 0);
});
test("group deletion restores managed files and does not report success when commit fails", async () => {
@@ -278,3 +277,209 @@ test("group deletion restores managed files and does not report success when com
assert.equal(restoreCount, 1);
assert.equal(reportedCount, 0);
});
const confirmedSource: ManagedSource = {
id: "managed-production",
type: "ssh_config",
filePath: "/tmp/managed-production.conf",
groupName: "Production",
lastSyncedAt: 1,
};
async function withDeletionProbe(
options: Partial<Parameters<typeof useVaultGroupDeletion>[0]>,
run: (getDelete: () => ReturnType<typeof useVaultGroupDeletion>, rerender: (sources: ManagedSource[]) => Promise<void>) => 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 renderer: ReactTestRenderer | undefined;
let deleteGroups!: ReturnType<typeof useVaultGroupDeletion>;
const defaults: Parameters<typeof useVaultGroupDeletion>[0] = {
customGroups: ["Production"], hosts: [], groupConfigs: [],
managedSources: [confirmedSource],
onReadPersistedHosts: async () => [],
onReadPersistedManagedSources: () => [confirmedSource],
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [],
managedSources: [confirmedSource], snippets: [],
}),
...options,
};
const Probe = ({ sources }: { sources: ManagedSource[] }) => {
deleteGroups = useVaultGroupDeletion({ ...defaults, managedSources: sources });
return null;
};
try {
await act(async () => {
renderer = create(<Probe sources={defaults.managedSources} />);
});
await run(() => deleteGroups, async (sources) => {
await act(async () => { renderer!.update(<Probe sources={sources} />); });
});
} finally {
await act(async () => { renderer?.unmount(); });
environment.IS_REACT_ACT_ENVIRONMENT = previous;
}
}
for (const [name, rendered, persisted] of [
["changed file path", [confirmedSource], [{ ...confirmedSource, filePath: "/tmp/other.conf" }]],
["changed source id", [confirmedSource], [{ ...confirmedSource, id: "replacement" }]],
["added source", [confirmedSource], [confirmedSource, { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" }]],
["first source", [], [confirmedSource]],
["source moved up within selection", [{ ...confirmedSource, groupName: "Production/Sub" }], [confirmedSource]],
["source moved into selection", [{ ...confirmedSource, groupName: "Staging" }], [confirmedSource]],
] as const) {
test(`group deletion rejects initially persisted ${name} before clearing files`, async () => {
let clearCount = 0;
let commitCount = 0;
let reportedCount = 0;
await withDeletionProbe({
managedSources: [...rendered],
onReadPersistedManagedSources: () => [...persisted],
onClearAndRemoveManagedSources: async () => {
clearCount += 1;
return async () => {};
},
onCommitVaultGroupMutation: async () => {
commitCount += 1;
throw new Error("unexpected commit");
},
onDeletedPaths: () => { reportedCount += 1; },
}, async (getDelete) => {
// A failed attempt refreshes latestRef without refreshing the warning.
for (let attempt = 0; attempt < 2; attempt += 1) {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
}
});
assert.equal(clearCount, 0);
assert.equal(commitCount, 0);
assert.equal(reportedCount, 0);
});
}
test("group deletion keeps old callbacks bound to their rendered confirmation", async () => {
const changed = { ...confirmedSource, filePath: "/tmp/changed.conf" };
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => [changed],
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => {};
},
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [], managedSources: [changed], snippets: [],
}),
}, async (getDelete, rerender) => {
const staleDelete = getDelete();
await rerender([changed]);
assert.notEqual(getDelete(), staleDelete);
await assert.rejects(staleDelete(["Production"]), VaultGroupDeletionConfirmationChangedError);
assert.deepEqual(cleared, []);
await getDelete()(["Production"]);
});
assert.deepEqual(cleared, [changed.filePath]);
});
for (const retry of ["snapshot", "commit", "superseded"] as const) {
test(`group deletion retains safe ${retry} retries for the same confirmed file`, async () => {
const updated = { ...confirmedSource, lastSyncedAt: 2 };
let reads = 0;
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => {
reads += 1;
return [retry === "snapshot" && reads > 1 ? updated : confirmedSource];
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
if (retry === "superseded" && commits === 1) return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [],
managedSources: [retry === "snapshot" || (retry === "commit" && commits === 1) ? updated : confirmedSource],
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => { await getDelete()(["Production"]); });
assert.deepEqual(cleared, [confirmedSource.filePath, confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, retry === "snapshot" ? 1 : 2);
assert.equal(reported, 1);
});
}
for (const retry of ["commit", "superseded"] as const) {
test(`group deletion rejects new files after a ${retry} retry`, async () => {
const added = { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" };
let persisted = [confirmedSource];
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => persisted,
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource, added];
if (retry === "superseded") return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [], managedSources: persisted,
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, [confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, 1);
assert.equal(reported, 0);
});
}
for (const phase of ["snapshot", "commit"] as const) {
test(`group deletion rejects a managed subgroup moved to its parent during ${phase}`, async () => {
const subgroup = { ...confirmedSource, groupName: "Production/Sub" };
let persisted = [subgroup];
let reads = 0;
let restores = 0;
let commits = 0;
const cleared: string[] = [];
await withDeletionProbe({
managedSources: [subgroup],
onReadPersistedManagedSources: () => {
if (phase === "snapshot" && ++reads > 1) persisted = [confirmedSource];
return persisted;
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.groupName));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource];
return mutate({
groups: ["Production", "Production/Sub"], configs: [], hosts: [],
managedSources: persisted, snippets: [],
});
},
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, ["Production/Sub"]);
assert.equal(restores, 1);
assert.equal(commits, phase === "snapshot" ? 0 : 1);
});
}
@@ -14,6 +14,17 @@ import {
const RETRY_VAULT_GROUP_DELETION = Symbol("retry-vault-group-deletion");
export class VaultGroupDeletionConfirmationChangedError extends Error {
constructor() {
super("The managed files affected by this deletion have changed. Review the files and confirm again.");
this.name = "VaultGroupDeletionConfirmationChangedError";
}
}
const managedSourceDeletionIdentity = (source: ManagedSource): string => (
JSON.stringify([source.id, source.type, source.filePath, source.groupName])
);
const managedSourceSnapshotsMatch = (
left: ManagedSource[],
right: ManagedSource[],
@@ -59,6 +70,14 @@ export function useVaultGroupDeletion({
additionallyDeletedHostIds: ReadonlySet<string> = new Set(),
) => {
const selectedPaths = [...paths];
// Bind confirmation to the sources rendered with this callback, not the
// latest persisted snapshot (which reads and retries update independently).
const confirmedFiles = new Set(buildVaultGroupDeletion({
...latestRef.current,
selectedPaths,
deleteHosts,
managedSources,
}).sourcesToRemove.map(managedSourceDeletionIdentity));
let deletedRoots: string[] = [];
while (true) {
let restoreManagedFiles: (() => Promise<void>) | undefined;
@@ -82,6 +101,12 @@ export function useVaultGroupDeletion({
return { status: "empty" as const };
}
if (deletion.sourcesToRemove.some((source) => (
!confirmedFiles.has(managedSourceDeletionIdentity(source))
))) {
throw new VaultGroupDeletionConfirmationChangedError();
}
if (deletion.sourcesToRemove.length > 0) {
if (onClearAndRemoveManagedSources) {
restoreManagedFiles = await onClearAndRemoveManagedSources(deletion.sourcesToRemove);
@@ -194,6 +219,7 @@ export function useVaultGroupDeletion({
}
onDeletedPaths?.(deletedRoots);
}, [
managedSources,
onClearAndRemoveManagedSource,
onClearAndRemoveManagedSources,
onCommitVaultGroupMutation,
+1
View File
@@ -186,6 +186,7 @@ const migrateKey = (key: Partial<SSHKey>): SSHKey => {
id,
label,
type: key.type || "ED25519",
keySize: key.keySize,
privateKey: key.privateKey || "",
publicKey: key.publicKey,
certificate: key.certificate,
@@ -0,0 +1,145 @@
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 {
collectSidePanelPanes,
createSidePanelLayout,
splitSidePanelPane,
type SidePanelLayout,
} from '../../domain/sidePanelLayout.ts';
import { STORAGE_KEY_WORKSPACE_LAYOUT_PRESET } from '../../infrastructure/config/storageKeys.ts';
import { useWorkspaceLayoutPresetState } from './useWorkspaceLayoutPresetState.ts';
function buildSplitLayout(): SidePanelLayout {
let layout = createSidePanelLayout('scripts', 'pane-scripts');
layout = splitSidePanelPane(layout, 'pane-scripts', 'sftp', 'horizontal', {
paneId: 'pane-sftp',
splitId: 'split-root',
}, 400);
return layout;
}
test('saved default resolves per session with fresh ids and protocol-aware pruning', async () => {
const values = new Map<string, string>();
const fakeStorage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => { values.set(key, value); },
removeItem: (key: string) => { values.delete(key); },
};
const globals = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
localStorage?: typeof fakeStorage;
};
const previousActEnvironment = globals.IS_REACT_ACT_ENVIRONMENT;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
globals.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(globalThis, 'localStorage', {
value: fakeStorage,
configurable: true,
});
let state: ReturnType<typeof useWorkspaceLayoutPresetState> | null = null;
const Probe = () => {
state = useWorkspaceLayoutPresetState();
return null;
};
try {
await act(async () => {
create(React.createElement(Probe));
});
assert.ok(state);
// Nothing saved yet: no preset to apply.
assert.equal(state.resolveDefaultLayoutForSession({ protocol: 'ssh' }), null);
let saved = false;
await act(async () => {
saved = state?.saveWorkspaceLayoutAsDefault(buildSplitLayout()) ?? false;
});
assert.equal(saved, true);
assert.ok(values.has(STORAGE_KEY_WORKSPACE_LAYOUT_PRESET));
// SSH sessions keep their SFTP pane; ids are rekeyed per application.
const sshResolved = state.resolveDefaultLayoutForSession({ protocol: 'ssh' });
assert.ok(sshResolved);
assert.equal(sshResolved.protocol, 'ssh');
assert.deepEqual(
collectSidePanelPanes(sshResolved.layout.root).map((pane) => pane.tool),
['scripts', 'sftp'],
);
assert.notEqual(sshResolved.layout.root.id, buildSplitLayout().root.id);
assert.equal(sshResolved.focusedTool, 'sftp');
// Protocols that cannot serve SFTP lose that pane.
const telnetResolved = state.resolveDefaultLayoutForSession({ protocol: 'telnet' });
assert.ok(telnetResolved);
assert.deepEqual(
collectSidePanelPanes(telnetResolved.layout.root).map((pane) => pane.tool),
['scripts'],
);
assert.equal(telnetResolved.focusedTool, 'scripts');
// A second resolve rekeys again so parallel workspaces share no node ids.
const again = state.resolveDefaultLayoutForSession({ protocol: 'ssh' });
assert.ok(again);
assert.notEqual(again.layout.root.id, sshResolved.layout.root.id);
} finally {
if (previousLocalStorage) {
Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
} else {
delete (globalThis as { localStorage?: unknown }).localStorage;
}
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
});
test('saving falls back to false when persistence rejects the write', async () => {
const fakeStorage = {
getItem: () => null,
setItem: () => {
const quotaError = new DOMException('full', 'QuotaExceededError');
throw quotaError;
},
removeItem: () => undefined,
};
const globals = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
localStorage?: typeof fakeStorage;
};
const previousActEnvironment = globals.IS_REACT_ACT_ENVIRONMENT;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
globals.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(globalThis, 'localStorage', {
value: fakeStorage,
configurable: true,
});
let state: ReturnType<typeof useWorkspaceLayoutPresetState> | null = null;
const Probe = () => {
state = useWorkspaceLayoutPresetState();
return null;
};
try {
await act(async () => {
create(React.createElement(Probe));
});
assert.ok(state);
let saved = true;
await act(async () => {
saved = state?.saveWorkspaceLayoutAsDefault(buildSplitLayout()) ?? true;
});
assert.equal(saved, false);
} finally {
if (previousLocalStorage) {
Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
} else {
delete (globalThis as { localStorage?: unknown }).localStorage;
}
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
});
@@ -0,0 +1,69 @@
import { useCallback } from 'react';
import {
getFocusedSidePanelPane,
type SidePanelLayout,
type SidePanelTool,
} from '../../domain/sidePanelLayout';
import {
createWorkspaceLayoutPreset,
rekeySidePanelLayout,
withoutUnavailableSidePanelTools,
} from '../../domain/workspaceLayoutPreset';
import {
readWorkspaceLayoutPreset,
writeWorkspaceLayoutPreset,
} from './workspaceLayoutPresetStore';
/** Protocols whose sessions can actually serve an SFTP pane. */
function canServeSftp(protocol: string): boolean {
return protocol === 'local' || protocol === 'ssh' || protocol === 'mosh';
}
export type ResolvedWorkspaceLayoutPreset = {
layout: SidePanelLayout;
focusedTool: SidePanelTool;
/** Connection protocol used for availability filtering (`session.protocol ?? 'ssh'`). */
protocol: string;
};
/**
* Application boundary for the saved default workspace side panel layout.
* Owns the preset persistence lifecycle (read, validate, write) so UI
* components consume handlers instead of touching the store directly.
*/
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
* 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.
*/
const resolveDefaultLayoutForSession = useCallback(
(session: { protocol?: string | null }): ResolvedWorkspaceLayoutPreset | null => {
const preset = readWorkspaceLayoutPreset();
if (!preset) return null;
const proto = session.protocol ?? 'ssh';
const usable = withoutUnavailableSidePanelTools(
preset.layout,
(tool) => tool !== 'sftp' || canServeSftp(proto),
);
if (!usable) return null;
const layout = rekeySidePanelLayout(usable, () => crypto.randomUUID());
return { layout, focusedTool: getFocusedSidePanelPane(layout).tool, protocol: proto };
},
[],
);
/** Validate and persist a live layout as the default. False when invalid or the write failed. */
const saveWorkspaceLayoutAsDefault = useCallback((layout: SidePanelLayout): boolean => {
const preset = createWorkspaceLayoutPreset(layout);
if (!preset) return false;
return writeWorkspaceLayoutPreset(preset);
}, []);
return { resolveDefaultLayoutForSession, saveWorkspaceLayoutAsDefault };
}
Loaded 100 of 526 files, more files were not shown because too many files have changed in this diff. Show more