Compare commits

..
Author SHA1 Message Date
陈大猫 5e1bdd85d8 fix(sftp): preserve settled folder pause failure on stale owner publish 2026-11-18 15:18:54 +08:00
陈大猫 450d1df2e7 fix(sftp): keep partial pause feedback consistent across transfer views 2026-11-18 15:07:28 +08:00
陈大猫 3ed22954db fix(sftp): preserve partial folder pause results 2026-11-18 14:44:35 +08:00
陈大猫 8b3832feef fix(notes): keep MDX link dialog inside the editor container (#4258)
MDXEditor portals the link preview toolbar to document.body by default.
Notes stays retained-mounted and is only CSS-hidden, so the toolbar was
left floating over other vault pages and terminal sessions.

Fixes #4257
2026-11-17 14:53:32 +08:00
github-actions[bot]andgithub-actions[bot] 83d0d5f949 chore: update star history charts [skip ci] (#4247)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-11-16 00:09:01 +00:00
GOUKI9999and陈大猫 0a4ff8875f feat(ai): make unrecognized shell prompts an actionable unknown state instead of a terminal block (#4198)
* feat(ai): make unrecognized shell prompts an actionable unknown state instead of a terminal block

Composes #3935 (advisory semantics), #4110 (OSC 133 marker authority + pending-input guards) and #4195 (asymmetric harm / state-model proposal). An unrecognized prompt on a live shell now yields a non-terminal SHELL_READINESS_UNKNOWN result with a read-only/confirm viable path; PROVEN-busy states keep the exact hard SHELL_NOT_READY block. Never blind-types into unknown; never claims ready without evidence.

* fix(ai): propagate unknown readiness code through the active Catty SDK path

---------

Co-authored-by: 陈大猫 <16399091+binaricat@users.noreply.github.com>
2026-11-15 01:27:43 +08:00
rnaranyand陈大猫 8433302959 fix(i18n): complete zh-TW strings and unify Taiwan terminology (#4185)
* fix(i18n): complete zh-TW strings and unify Taiwan terminology

- Translate the 19 settings.plugins.sources.* keys that were still in
  Simplified Chinese, and add the 9 missing ai.providers.headers.* keys.
- Add the two zh-CN keys the dialog already looked up (createWorkspace.title,
  field.selectHosts) so those labels no longer fall back to English.
- Keep {{name}} / {{name:default}} literal in snippets.field.variablesHelp;
  the previous text translated the metavariable names.
- Unify zh-TW terms in the shipped UI: 外掛, 市集, 行程, 指令碼, 金鑰,
  佔位符, 檔案系統, 網路, 資料, 使用者, 預設.
- Tighten localeParityLocales: zh-CN and zh-TW are at full parity, so move
  them out of LOCALES_PENDING_PARITY and check interpolation placeholders for
  every translated locale, not just es.

* fix(i18n): finish zh-TW plugin wording and :default placeholders

Review follow-up on the terminology pass:

- Replace the remaining mainland terms on the plugin settings screen:
  導入→匯入, 卸載→解除安裝, 存儲→儲存, 遠程→遠端, 加載→載入. 網路設備 is
  correct Taiwan usage and stays.
- Widen the interpolation token regex so {{name:default}} is compared too;
  the previous \w+ form silently ignored the colon and could not catch a
  translated metavariable. Add a direct assertion for that form.

* test(ci): pin Vite contract probe to numeric loopback

---------

Co-authored-by: 陈大猫 <16399091+binaricat@users.noreply.github.com>
2026-11-14 23:37:53 +08:00
陈大猫 51cb14955c fix(logs): finalize session logs on quit and pre-connect close (#4236)
* fix(logs): finalize session logs when the app quits without closing tabs

Fixes #4235

* fix(logs): finalize logs when unconnected sessions close

Capture never-connected terminal logs at explicit session removal, including empty buffers, without finalizing logs during runtime remounts. Cover tab close, failed-dialog close, batch close, and workspace close with persistence regressions.

Fixes #4235

* fix(logs): tolerate unavailable finalization IPC

Preserve window close and layout saves when session-log finalization IPC cannot be set up, and clear its timeout on setup failures.

Follow-up for #4235 / PR #4236.
2026-11-14 21:36:08 +08:00
陈大猫 1d5cef09ec fix(settings): index later-added settings in search catalog (Fixes #4230) (#4232)
* fix(settings): index later-added settings in search catalog

Fixes #4230

Follow-up after #4231. Settings search still missed later-added
rows such as Appearance "Code font" (代码字体) and System session
log "Add timestamps" (时间戳), which already rendered in their
tabs. Index those destinations and other visible setting rows
that had the same catalog/anchor omission.

* fix(settings): fall back to visible parent when search target is gated
2026-11-14 21:30:27 +08:00
陈大猫 cf7f998689 fix(ci): prevent plugin-contract lint-and-test hang (#4240) 2026-11-14 20:17:13 +08:00
陈大猫andCodex db3a9e88e2 fix(terminal): cap WebGL contexts for visible split panes (Fixes #4128) (#4239)
The #4122 budget of 12 only released hidden panes, so 17+ visible
splits still crossed Chromium’s 16-context limit and the 50ms
rebuild avalanched into white panes until the DOM breaker tripped.

Refuse new visible contexts when visible holders fill the cap while
preserving recently hidden holders during the tab-flip grace period.
Cover acquisition limits, missed visibility syncs, and recovery at cap.

Co-authored-by: Codex <codex@openai.com>
2026-11-14 18:21:32 +08:00
陈大猫andCodex 65435c06f5 fix(x11): hide fd-bearing X11 extensions on byte-only forwards (Fixes #4200) (#4238)
Clear QueryExtension present for DRI3 and MIT-SHM on built-in X11 forwards so clients avoid SCM_RIGHTS replies that the SSH byte stream cannot transport. Preserve framing, byte order, sequence isolation and cookie rewriting.

Strip AppImage ARGV0 from local shell PTY environments so zsh preserves ssh argv[0] and Xorg recognizes system SSH forwarding. Add protocol and environment regression tests. Fixes #4200.

Co-authored-by: Codex <codex@openai.com>
2026-11-14 16:28:28 +08:00
陈大猫 3096f86889 fix(sftp): use remote cp for fresh same-host copies (Fixes #4207) (#4226)
* fix(sftp): use remote cp for fresh same-host copies (Fixes #4207)

Ordinary SFTP tasks were marked resumable, which skipped the existing file and directory cp optimizations. Select the non-resumable route only when creating fresh matching-host copies with eligible encodings, keeping transfer-center rows and recursive children consistent. Existing checkpointed transfers retain their saved resumable path; failed cp attempts retain the download/upload fallback.

* fix(sftp): skip same-host directory cp when auto encoding resolves to non-UTF-8

* fix(sftp): preserve dest mode when same-host cp replaces a file

* fix(sftp): skip same-host cp for symlinks and directory merges

* test(sftp): mock missing dest in same-host cp cache fixture

* fix(sftp): expose lstat on session-backed copy clients
2026-11-13 17:24:27 +08:00
陈大猫 94f8bd9bc7 fix(ai): recognize Enter-PSSession remoting prompts as idle (#4229)
Fixes #4228

PowerShell remoting (Enter-PSSession / WinRM) prefixes the default
prompt with [ComputerName]: , which POWERSHELL_PROMPT_PATTERN missed,
so the readiness gate returned SHELL_NOT_READY and never sent the
command. Accept one or more [token]: prefixes before the existing
PS ...> shape, including [DBG]:.
2026-11-13 16:47:59 +08:00
陈大猫 5cd42cb518 fix(settings): include folder compression in settings search (#4231)
Fixes #4230

Settings search uses a static catalog. The SFTP "Enable folder
compression" row was already in the tab but missing from the catalog
and had no anchor, so queries such as 压缩 showed no matches. Index
that destination, plus the skip-unchanged and SSH keep-alive rows in
the same tab that had the same omission.
2026-11-13 16:30:21 +08:00
陈大猫andCodex 9ccb62ea07 fix(ssh): fingerprint OpenSSH host certs by the underlying key (Fixes #4222)
Fixes #4222

describeHostKey previously hashed the entire certificate blob, so load-balanced or re-issued certs for the same host key looked like a fingerprint change. Pin the underlying public key instead.

Share extraction across verifier, renderer migration, and system known_hosts. Migrate legacy full-cert fingerprints only when the stored certificate body is available, preserving certificate metadata and raw rekey checks.

Co-authored-by: Codex <codex@openai.com>
2026-11-13 09:33:14 +08:00
陈大猫 ad05867026 fix(linux): use Secret Service keyring on non-GNOME/KDE desktops (#4190)
Chromium only enables gnome-libsecret or kwallet when it recognizes a
GNOME/KDE desktop name, so niri/sway/Hyprland fall through to BASIC_TEXT
even when org.freedesktop.secrets is available. Set --password-store
before app ready when Secret Service is present, without overriding an
explicit switch or KDE's kwallet default.
2026-11-09 09:29:59 +08:00
github-actions[bot]andgithub-actions[bot] e72d6fc7c6 chore: update star history charts [skip ci] (#4193)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-11-09 00:07:23 +00:00
陈大猫 907f60616b fix(nix): work around bwrap ssh config owner check for home-manager (#4192)
* fix(nix): work around bwrap ssh config owner check for home-manager

Unprivileged wrapType2/bwrap maps only the caller uid, so a home-manager
~/.ssh/config symlink into the nix store appears as overflowuid 65534.
OpenSSH then rejects the default user config and the Mosh handshake
never sees MOSH CONNECT. Inject an ssh wrapper via extraPkgs that
snapshots a badly owned config and execs nixpkgs OpenSSH with -F.

* fix(nix): always refresh ssh config snapshot for home-manager

Nix store files have normalized old mtimes, so a -nt check never
notices a newer home-manager generation after the first snapshot.

* fix(nix): publish ssh config snapshot atomically

cp truncates the destination before copying, so a concurrent ssh -F
reader can see an empty or partial config and ignore HostName,
identity, or proxy settings. Copy to a unique staging file and
rename it over the snapshot.
2026-11-09 01:46:36 +08:00
陈大猫 d536b22dee fix(host-details): show inherited group proxy and jump hosts (#4188)
* fix(host-details): show inherited group proxy and jump hosts

Host editor summaries for HTTP/SOCKS5/command proxy and ProxyJump
chains now display the same values applyGroupDefaults uses at
connect time, without writing inherited settings onto the host
until the user edits them.

Fixes #4187

* fix(host-details): keep custom proxy and empty jump-host overrides

Selecting Custom while a group saved proxy is inherited now keeps a host-owned draft instead of snapping back to that profile. Removing the last hop of a multi-hop inherited chain keeps an empty override so applyGroupDefaults cannot restore the group hops.

* fix(host-details): keep empty override when clearing inherited chain

Clear Chain on an inherited-only jump-host list now stores { hostIds: [] }
instead of deleting the field so group hops cannot snap back.
2026-11-08 21:30:36 +08:00
陈大猫 74d5e126d4 fix(system-manager): show all CPU cores in the overview list (#4184)
* fix(system-manager): show all CPU cores in the overview list

The overview CPU card hardcoded cpuPerCore.slice(0, 12), so a 16-thread
host showed "16 核" at the top but only C1–C12 below. Render every
reported core and allow the list to scroll when it overflows.

Fixes #4183

* ci: retrigger lint-and-test after plugin-contract runner shutdown
2026-11-08 12:59:27 +08:00
jinshenganyuciandbincxz 4a55492c17 feat(sftp): create archives from the context menu (#3936)
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-07 20:44:49 +08:00
rnarany 51d9f715da feat(autocomplete): localize common commands and polish terminal hints (#4172)
* feat(autocomplete): add zh-CN descriptions for zip, unzip, make, nano

Cover 32 missing Fig descriptions, generate zh-TW, add batch coverage tests, and record source and semantic checks.

* fix(autocomplete): correct zip, unzip, and make semantics

Limit zip -9 to the compression level, warn that unzip -0 is a suspect upstream option, and describe make -N as the Apple/NeXT compatibility extension.

* fix(autocomplete): simplify unzip -0 warning and correct NeXT note

Keep the -O gbk version caveat in the research record and describe Next/NeXT as a capitalization difference.

* feat(autocomplete): complete remaining common command descriptions

Add 177 zh-CN descriptions for python, python3, node, vim, sort, awk, and sed; generate zh-TW, cover the batch with real Fig specs, and record one deferred shared node key.

* fix(autocomplete): correct sed n and sort parallel semantics

Add the automatic-print condition to sed n, remove the universal CPU default from sort --parallel, and remove duplicated adopted-entry sections from the source record.

* fix: repair macOS terminal setup and align autocomplete details

- Read OSC 7 setup payloads through base64 stdin so BSD/macOS works
- Keep the FIDO askpass socket path within the Unix sun_path limit
- Align autocomplete descriptions in a shared fixed column
- Fix an invalid optional-parameter declaration and lint warnings
- Harden macOS-sensitive OSC 7, SFTP, temp-dir and privacy tests

* feat(autocomplete): add zh-CN descriptions for file and text utilities

Cover ln, stat, wc, cut, uniq, tee and xargs with 70 localized
descriptions. Add coverage and localization tests, preload the new common
specs, and record the upstream wc/xargs wording corrections.

* fix(autocomplete): keep popup scrollbars draggable

Panel mousedown handlers no longer preventDefault across the whole box, so the right-side detail scrollbar and the suggestion list scrollbar can be dragged while padding clicks still preserve terminal focus.

* fix(autocomplete): keep detail panel open while selecting text

Delay row hover clearing so the pointer can move into the right-side detail panel, and allow native text selection there without stealing terminal focus on ordinary padding clicks.
2026-11-07 20:00:43 +08:00
陈大猫 23d3fe454b Merge pull request #4158 from GOUKI9999/feat/workspace-pane-rearrange
Rearrange workspace panes and retain empty/single-member workspaces.

Includes #4155 with its workspace lifecycle, chat continuity, empty-state, action-wiring and rendering-performance fixes. Final Codex review is clean; all CI checks and real Electron smoke passed.
2026-11-07 19:57:39 +08:00
bincxz 3622d482a4 perf(workspace): keep pane drop callbacks stable across tab switches 2026-11-07 19:34:58 +08:00
bincxz c1c5787cab fix(workspace): preserve resumed history when the last member closes 2026-11-07 19:17:55 +08:00
bincxz 419a6734fc Merge remote-tracking branch 'origin/main' into codex/preview-pr4158 2026-11-07 19:14:13 +08:00
bincxz b2be70aae7 fix(workspace): align empty state icon with workspace tabs 2026-11-07 19:02:56 +08:00
bincxz 9491b800b6 fix(workspace): retain displayed chat through final member close 2026-11-07 18:52:11 +08:00
bincxz 3c36e7e1a2 fix(workspace): prevent hidden pane moves while magnified 2026-11-07 18:32:49 +08:00
陈大猫andCodex 642bf03ea7 fix(mcp): recognize unbracketed space-separated Bash prompts as idle (#4176)
Accept space-separated Bash $ prompts while preserving delimiter and pending-input guards. Add recognition and extraction regression coverage.

Fixes #4175

Co-authored-by: Codex <codex@openai.com>
2026-11-07 18:26:57 +08:00
bincxz 22856a368a fix(workspace): guard stale drops and preserve chat scope priority 2026-11-07 18:18:38 +08:00
bincxz 4ed3d09c7a fix(workspace): complete pane dragging and empty workspace recovery 2026-11-07 16:08:00 +08:00
945722fbe8 fix(ai): place host_open tabs in the invoking chat's bound workspace (#4156)
* fix(ai): place host_open tabs in the invoking chat's bound workspace

* fix(ai): sync generated host open workspace guidance

* fix(ai): preserve invoking turn scope for resumed chats

---------

Co-authored-by: GOUKI9999 <GOUKI9999@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-07 15:41:46 +08:00
陈大猫 77f90999c7 fix(ui): accent border for terminal pane magnification (#4171)
* fix(ui): accent border for terminal pane magnification

* chore: retrigger CI after Actions runner shutdown flake

lint-and-test was cancelled mid-run by runner shutdown (not a product failure) on 42326458479 and 42328660175.
2026-11-07 10:44:59 +08:00
Mateus A.M Ferreiraandbincxz a62cc1bd3f feat(sftp): add a one-click Duplicate action for files and folders (#4133)
* feat(sftp): add a one-click Duplicate action for files and folders

Duplicate copies the selected entries next to their originals in the same
folder, covering files, folders, and multi-selection. It reuses the existing
transfer queue and the transfer pipeline's "(copy)" naming helper, so progress,
cancel, and error reporting behave like Copy to other pane.

The target name is resolved before the transfer starts. Resolving through the
batch conflict defaults instead would re-enter processTransfer for a task that
is still marked in flight and stall the copy.

Adds the action to both the list and tree context menus, plus translations for
en, es, ru, zh-CN, and zh-TW.

Closes #4132

* fix(sftp): keep Duplicate safe around navigation rows and reserved names

Hide and ignore the tree's synthetic ".." row: duplicating it resolved the
source to an ancestor directory and could walk the copy into its own output.
The transfer hook also drops "." / ".." inputs for duplicate batches, and the
same-pane handler filters them defensively.

Pick duplicate names around destinations already reserved by a queued or paused
transfer. Those rows have no file on disk yet, so stat-only naming returned the
same "(copy)" path and the follow-up active-path check turned the second
one-click duplicate into a conflict dialog. The naming helper now accepts an
occupied-path predicate fed from the active transfer set.

* fix(sftp): block stale entry menus on parent navigation

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-07 10:07:08 +08:00
GOUKI9999andGOUKI9999 c8f8adcc87 fix(ai): keep the chat panel close button visible at narrow widths (#4161)
Co-authored-by: GOUKI9999 <GOUKI9999@users.noreply.github.com>
2026-11-07 10:06:16 +08:00
陈大猫 7bb91d0fe2 fix(terminal): do not restore pane zoom on Escape (#4170) 2026-11-07 09:50:54 +08:00
陈大猫 a5a4117d8e fix(sftp): navigate into tree folders on double-click (#4166)
* fix(sftp): navigate into tree folders on double-click

* ci: retrigger cancelled lint-and-test for #4166
2026-11-07 08:17:07 +08:00
陈大猫 2ecf471a29 fix: prevent accidental Quick Connect dismissal (#4165) 2026-11-07 07:10:27 +08:00
陈大猫 968e84ff59 feat(plugins): install published plugin packages from GitHub (#4164)
* feat(plugins): install published plugin packages from GitHub

* fix(plugins): prebundle GitHub parser and reset consumed preview trust

* fix(plugins): localize GitHub install errors and trust review
2026-11-07 07:10:08 +08:00
陈大猫 7949242765 fix: bracket multiline compose submissions when supported (#4163)
Use shell-advertised bracketed paste for compose command blocks even when clipboard bracketing is disabled. Keep the final Enter outside the paste and preserve snippet preferences and compose target routing.

Fixes #4062
2026-11-06 22:08:09 +08:00
GOUKI9999 19ab38217b feat(workspace): rearrange member panes within a workspace by drag
Issue #4037 (phase 3 of #4098). An existing member pane can now be
dragged back onto its own workspace to rearrange it, landing with the
same snap-in split semantics an orphan drop gets.

- domain: add pure movePaneInWorkspace(root, sessionId, hint) composing
  the existing prune + insert conventions (no-op for unknown/single-pane
  self-drops; prune-first keeps target-inside-subtree drops correct).
- state: moveWorkspacePane / moveWorkspacePaneInWorkspaces touch only
  workspaces[].root — session ids, tab order, focus fields and every AI
  binding (anchorChatId etc.) are untouched by construction.
- drop flow: handleWorkspaceDrop routes same-workspace member drops to
  the move op; cross-workspace drops stay rejected (#4098 policy) and
  orphan drops are unchanged.
- preview: member panes drag via pointer events, so the split-hint
  preview and drop are mirrored on the pointer stream while a member of
  the active workspace is dragged; dropping a pane onto itself previews
  and drops as a no-op.

Identity guarantee: a move never changes session ids, workspace id,
anchorChatId, focusedSessionId (focus is keyed by session id, so it
visually follows the moved pane), focusSessionOrder or tab order; the
moved tree roundtrips through netcatty_session_restore_v1 unchanged.
2026-11-06 17:07:16 +08:00
GOUKI9999 98d75c13fe feat(ai): anchor workspace AI chats by id, not position
Phase 2 of #4098: every remaining positional fallback in the workspace
AI scope is replaced with id-based resolution.

- Workspace gains anchorChatId: pinned by the AI side panel whenever a
  chat becomes active in the workspace scope, persisted through the
  session restore snapshot, and validated lazily by consumers.
- resolveDisplayedPanelView: the auto-resume fallback now resolves the
  anchored chat first, then the most recently updated chat (updatedAt),
  else draft; sessions[0] is gone.
- retargetWorkspaceActiveChatAfterMemberLoss: when the focused member
  did not survive, the retarget lands on the most-recently-active
  survivor by chat recency, not the first positional member.
- plugin keybinding context: focused member, then the terminal member
  owning the anchored chat, then the most-recently-active member; a
  single-member workspace uses its only member.
- New domain/aiSessionRecency helper shared by all survivor rankings.
- /rebind and session_recover semantics (#4019) are unchanged.
2026-11-06 15:34:15 +08:00
GOUKI9999 ba135c0e98 feat(ai): keep workspaces alive below two members
Phase 2 of #4098: the workspace becomes a first-class object that
survives membership changes.

- Close/detach no longer dissolves a workspace at <=1 member. The
  workspace entity (and its id) survives with its remaining members,
  even at zero, where it keeps an empty split root placeholder that
  renders as an empty workspace tab.
- Focus handoff after member loss resolves to the most-recently-active
  surviving member (AI chat updatedAt via the AI session store), never
  positionally to remainingSessionIds[0]; with no recency signal focus
  is cleared and the pane renderer uses its display default.
- session restore: drop the empty-workspace skip. Workspaces closed to
  zero members persist an empty root and come back after restart with
  the same id, so their AI chats re-link. Roots that prune to null
  because their member sessions cannot be restored are still dropped.
- applyCloseSessionToSessions no longer orphans the survivor; the
  dissolved-workspace tab-order replacement machinery is removed.
2026-11-06 15:33:35 +08:00
265 changed files with 13300 additions and 771 deletions

No files matched your search

+1
View File
@@ -141,6 +141,7 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
### 📁 SFTP + 内蔵エディタ
- **ファイル作業** — ドラッグ&ドロップでアップロード/ダウンロード
- **その場で編集** — 内蔵エディタで小さな修正を素早く
- **リモート圧縮** — ファイルやフォルダーを1つ以上選び、右クリックの **Compress...** から、表示された保存先に名前を指定して `.tar.gz` または `.zip` アーカイブを作成できます。サーバーには選択した形式に対応する `tar`/`gzip` または `zip` が必要です。
### 🎨 パーソナライズ
- **カスタムテーマ** — UI の見た目を好みに調整
+1
View File
@@ -144,6 +144,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
### 📁 SFTP + Built-in Editor
- **File workflows** — drag & drop uploads/downloads
- **Edit in place** — built-in editor for quick changes
- **Create remote archives** — select files or folders, right-click **Compress...**, and create a named `.tar.gz` or `.zip` archive in the displayed destination directory; the server needs `tar`/`gzip` or `zip` for the chosen format.
### 🎨 Personalization
- **Custom themes** — tune the app appearance to your taste
+1
View File
@@ -141,6 +141,7 @@
### 📁 SFTP + 内置编辑器
- **文件工作流** —— 拖拽上传/下载更直观
- **就地编辑** —— 内置编辑器快速修改文件
- **远程压缩** —— 单选或多选文件、文件夹,右键选择“压缩…”,在对话框显示的保存目录生成指定名称的 `.tar.gz` 或 `.zip` 压缩包;服务器需安装对应的 `tar`/`gzip` 或 `zip`。
### 🎨 个性化
- **自定义主题** —— 按喜好调整应用外观
+1
View File
@@ -141,6 +141,7 @@
### 📁 SFTP + 內建編輯器
- **檔案工作流** —— 拖放上傳/下載
- **就地編輯** —— 內建編輯器,快速修改檔案
- **遠端壓縮** —— 單選或多選檔案、資料夾,按右鍵選擇「壓縮…」,在對話方塊顯示的儲存目錄建立指定名稱的 `.tar.gz` 或 `.zip` 壓縮檔;伺服器需安裝對應的 `tar`/`gzip` 或 `zip`。
### 🎨 個人化
- **自訂主題** —— 依你的喜好調整外觀
+19 -20
View File
@@ -377,7 +377,7 @@ test('move-focus shortcut cannot send input behind a magnified pane', () => {
assert.equal(moveCalls, 0);
});
test('Escape restores magnification after transient dialogs are closed', () => {
test('Escape leaves magnification unchanged and reaches the terminal', () => {
let restores = 0;
let prevented = false;
let stopped = false;
@@ -405,30 +405,29 @@ test('Escape restores magnification after transient dialogs are closed', () => {
},
}), event);
assert.equal(restores, 1);
assert.equal(prevented, true);
assert.equal(stopped, true);
assert.equal(restores, 0);
assert.equal(prevented, false);
assert.equal(stopped, false);
});
test('consumed Escape does not restore magnification', () => {
let restores = 0;
test('Escape closes the quick switcher', () => {
let open = true;
handleEscapeKeyDownImpl(() => ({
isQuickSwitcherOpen: false,
setIsQuickSwitcherOpen: () => {},
terminalPaneMagnificationRef: {
current: {
getState: () => 'focused',
focus: () => false,
restore: () => {
restores += 1;
return true;
},
toggle: () => false,
},
},
isQuickSwitcherOpen: open,
setIsQuickSwitcherOpen: (value: boolean) => { open = value; },
}), { key: 'Escape', defaultPrevented: false } as KeyboardEvent);
assert.equal(open, false);
});
test('consumed Escape leaves the quick switcher open', () => {
let open = true;
handleEscapeKeyDownImpl(() => ({
isQuickSwitcherOpen: open,
setIsQuickSwitcherOpen: (value: boolean) => { open = value; },
}), { key: 'Escape', defaultPrevented: true } as KeyboardEvent);
assert.equal(restores, 0);
assert.equal(open, true);
});
test('close tab hotkey routes native plugin view tabs through their owner', () => {
+17 -9
View File
@@ -365,8 +365,6 @@ export function handleEscapeKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEve
const {
isQuickSwitcherOpen,
setIsQuickSwitcherOpen,
sftpPaneMagnificationRef,
terminalPaneMagnificationRef,
} = getCtx();
{
if (e.key !== 'Escape' || e.defaultPrevented) return;
@@ -374,13 +372,6 @@ export function handleEscapeKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEve
setIsQuickSwitcherOpen(false);
return;
}
if (getAvailablePaneMagnificationController([
sftpPaneMagnificationRef?.current,
terminalPaneMagnificationRef?.current,
])?.restore()) {
e.preventDefault();
e.stopPropagation();
}
}
}
@@ -1229,6 +1220,23 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
}
}
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
const { addConnectionLog, systemInfoRef } = getCtx();
const { username, hostname } = systemInfoRef.current;
addConnectionLog({
sessionId: session.id,
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
protocol: session.protocol || 'ssh',
startTime: Date.now(),
localUsername: username,
localHostname: hostname,
saved: false,
});
}
export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, sessionId: string, data: string) {
const { IS_DEV, connectionLogs, selectConnectionLogForTerminalDataCapture, sessions, updateConnectionLog } = getCtx();
{
+15 -5
View File
@@ -4,6 +4,8 @@ import { PluginContributionHost } from '../../components/plugins/PluginContribut
import type { TerminalSession, Workspace } from '../../types';
import { useActiveTabId } from '../state/activeTabStore';
import { resolveActivePluginKeybindingContext } from '../state/pluginContributionContexts';
import { getAISessionsSnapshot } from '../state/aiSessionsStore';
import { getPersistedAiSessionsSnapshot } from '../state/aiStateSnapshots';
/**
* Leaf host for plugin keybindings so AppView does not subscribe to activeTabId.
@@ -23,11 +25,19 @@ export function AppPluginKeybindingHost({
workspaces: Workspace[];
}) {
const activeTabId = useActiveTabId();
const keybindingContext = useMemo(() => resolveActivePluginKeybindingContext({
activeTabId,
sessions,
workspaces,
}), [activeTabId, sessions, workspaces]);
const keybindingContext = useMemo(() => {
// AI chat recency drives the workspace anchor fallback (#4098 phase 2).
// Read without subscribing: keybinding context is best-effort and refreshes
// on every tab/session/workspaces change that matters here.
const live = getAISessionsSnapshot().sessions;
const aiSessions = live.length > 0 ? live : getPersistedAiSessionsSnapshot();
return resolveActivePluginKeybindingContext({
activeTabId,
sessions,
workspaces,
aiSessions,
});
}, [activeTabId, sessions, workspaces]);
return (
<PluginContributionHost
@@ -4,12 +4,13 @@ import test from 'node:test';
const source = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8');
test('terminal Escape restoration runs before xterm can stop propagation', () => {
const effectStart = source.indexOf("const onCaptureKeyDown = (e: KeyboardEvent) => {");
const effectSource = source.slice(effectStart, effectStart + 900);
test('quick-switcher Escape handling stays in the bubble phase', () => {
const effectStart = source.indexOf('const onKeyDown = (e: KeyboardEvent) => {\n _handleEscapeKeyDown(e);');
const effectEnd = source.indexOf('}, [appLockLocked]);', effectStart);
const effectSource = source.slice(effectStart, effectEnd);
assert.notEqual(effectStart, -1);
assert.match(effectSource, /target\.closest\('\.xterm'\)/);
assert.match(effectSource, /window\.addEventListener\('keydown', onCaptureKeyDown, true\)/);
assert.match(effectSource, /window\.removeEventListener\('keydown', onCaptureKeyDown, true\)/);
assert.match(effectSource, /window\.addEventListener\('keydown', onKeyDown\)/);
assert.match(effectSource, /window\.removeEventListener\('keydown', onKeyDown\)/);
assert.doesNotMatch(source, /onCaptureKeyDown/);
});
+31 -14
View File
@@ -58,7 +58,9 @@ import {
} from '../../domain/terminalAppearance';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import { collectSessionIds } from '../../domain/workspace';
import { resolveAgentHostWorkspace } from '../../domain/agentHostWorkspace';
import { resolveAgentHostOpenWorkspace } from '../../domain/agentHostWorkspace';
import { getAISessionsSnapshot } from '../state/aiSessionsStore';
import { peekAgentRuntimeCleanup } from '../../infrastructure/ai/harness/agentRuntimeHandle';
import { useHostOpenSessionReuse } from '../state/useHostOpenSessionReuse';
import type { PaneMagnificationController } from '../../domain/paneMagnification';
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
@@ -102,7 +104,7 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
import { createOpenTerminalQueue } from './openTerminalQueue';
import { useAppStartupEffects } from './useAppStartupEffects';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
type OpenSessionInNewWindowPayload = {
title?: string;
@@ -613,7 +615,7 @@ export function AppSideEffects() {
const _handleTrayPanelConnect = useEffectEvent((hostId: string) => { return handleTrayPanelConnectImpl(() => ({ addConnectionLog, connectToHost, hostId, hosts, identities, keys, resolveEffectiveHost, resolveHostAuth, systemInfoRef, t, toast }), hostId); });
const _handleTrayPanelConnectRequest = useEffectEvent((hostId: string) => { return handleTrayPanelConnectRequestImpl(() => ({ connectNow: _handleTrayPanelConnect, hostId, isVaultInitialized, queueConnect: (queuedHostId: string) => setPendingTrayPanelConnectHostIds((prev) => [...prev, queuedHostId]) }), hostId); });
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, closeTabKeyStr, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
const _handleEscapeKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleEscapeKeyDownImpl(() => ({ e, isQuickSwitcherOpen, setIsQuickSwitcherOpen, sftpPaneMagnificationRef, terminalPaneMagnificationRef }), e); });
const _handleEscapeKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleEscapeKeyDownImpl(() => ({ e, isQuickSwitcherOpen, setIsQuickSwitcherOpen }), e); });
// Vault hosts for tray / auto-start; terminalHosts (vault + ephemeral) only for
// dedicated transfer resume so quick-connect rows do not break tray connect.
@@ -1233,19 +1235,11 @@ export function AppSideEffects() {
useEffect(() => {
if (appLockLocked) return;
const onCaptureKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
const target = e.target;
if (!(target instanceof HTMLElement) || !target.closest('.xterm')) return;
_handleEscapeKeyDown(e);
};
const onKeyDown = (e: KeyboardEvent) => {
_handleEscapeKeyDown(e);
};
window.addEventListener('keydown', onCaptureKeyDown, true);
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onCaptureKeyDown, true);
window.removeEventListener('keydown', onKeyDown);
};
}, [appLockLocked]);
@@ -1505,8 +1499,21 @@ export function AppSideEffects() {
return sessionId;
}, [handleConnectToHost, renameSessionInline]);
const openHostForVaultAgent = useCallback((host: Host, isExternalMcpCall: boolean, options?: { workspaceId?: string }) => {
const target = resolveAgentHostWorkspace(options?.workspaceId, activeTabStore.getActiveTabId(), workspaces.map(workspace => workspace.id));
const openHostForVaultAgent = useCallback((host: Host, isExternalMcpCall: boolean, options?: { workspaceId?: string; chatSessionId?: string }) => {
// A resumed history chat can run in a panel other than its saved binding.
// Prefer that turn's captured scope, never the window's current focus.
// Outside a running turn, retain the saved chat binding as the fallback.
const chat = options?.chatSessionId
? getAISessionsSnapshot().sessions.find((session) => session.id === options.chatSessionId)
: undefined;
const turnScope = options?.chatSessionId
? peekAgentRuntimeCleanup()?.getActiveScope?.(options.chatSessionId)
: undefined;
const target = resolveAgentHostOpenWorkspace(options?.workspaceId, turnScope ? { scope: turnScope } : chat, {
activeTabId: activeTabStore.getActiveTabId(),
workspaceIds: workspaces.map(workspace => workspace.id),
terminalSessions: sessionsRef.current,
});
if (target.error) return { ok: false as const, error: target.error };
// Silent sessions only apply to actual external MCP clients (chatSessionId
// equals the reserved external-MCP scope). The in-app Catty AI chat's
@@ -1888,8 +1895,18 @@ export function AppSideEffects() {
setActiveTabId('vault');
}, [setActiveTabId]);
const restoredSessionLogsStartedRef = useRef(new Set<string>());
// A restored tab retains its session ID, but its previous ConnectionLog is closed.
// Start the new incarnation's log before updateSessionStatus clears restoreState.
// Wrap updateSessionStatus to track lastConnectedAt on successful connection
const handleSessionStatusChange = useCallback((sessionId: string, status: TerminalSession['status']) => {
const session = sessionByIdRef.current.get(sessionId);
if (session?.restoreState === 'restored-disconnected'
&& (status === 'connecting' || status === 'connected')
&& !restoredSessionLogsStartedRef.current.has(sessionId)) {
restoredSessionLogsStartedRef.current.add(sessionId);
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog, systemInfoRef }), session);
}
updateSessionStatus(sessionId, status);
if (status === 'connected') {
const session = sessionByIdRef.current.get(sessionId);
@@ -1897,7 +1914,7 @@ export function AppSideEffects() {
updateHostLastConnected(session.hostId);
}
}
}, [updateSessionStatus, updateHostLastConnected]);
}, [addConnectionLog, updateSessionStatus, updateHostLastConnected]);
const handleUpdateHostFromTerminal = useCallback((host: TerminalHostUpdate) => {
// Functional update + identity-preserving updateHosts: only the patched
+4 -2
View File
@@ -264,7 +264,7 @@ function AppViewInner({ domains }: AppViewProps) {
useMainWindowInputFocusRecovery({ onPageHidden: dismissTransientOverlays });
const {
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace,
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
@@ -279,7 +279,7 @@ function AppViewInner({ domains }: AppViewProps) {
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap,
setNavigateToSection, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride,
setWorkspaceFocusedSession, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior,
setWorkspaceFocusedSession, setWorkspaceAnchorChat, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior,
sftpShowHiddenFiles, sftpUseCompressedUpload, snippetPackages, snippets, splitSessionWithCurrentShell, startSessionRename,
startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, terminalFontFamilyId, terminalFontSize, terminalSettings, terminalThemeId, themeById,
toggleBroadcast, toggleScriptsSidePanelRef, toggleSidePanelRef, terminalPaneMagnificationRef, sftpPaneMagnificationRef, toggleWorkspaceViewMode, unmanageSource,
@@ -774,12 +774,14 @@ function AppViewInner({ domains }: AppViewProps) {
onTerminalDataCapture={handleTerminalDataCapture}
onCreateWorkspaceFromSessions={createWorkspaceFromSessions}
onAddSessionToWorkspace={addSessionToWorkspace}
onMoveWorkspacePane={moveWorkspacePane}
onRequestAddToWorkspace={handleRequestAddToWorkspace}
onAppendHostToWorkspace={handleAppendHostToWorkspace}
onUpdateSplitSizes={updateSplitSizes}
onSetDraggingSessionId={setDraggingSessionId}
onToggleWorkspaceViewMode={toggleWorkspaceViewMode}
onSetWorkspaceFocusedSession={setWorkspaceFocusedSession}
onSetWorkspaceAnchorChat={setWorkspaceAnchorChat}
onReorderWorkspaceSessions={reorderWorkspaceSessions}
onReorderTabs={reorderWorkTabs}
onCopySession={copySessionWithCurrentShell}
@@ -0,0 +1,93 @@
import assert from 'node:assert/strict';
import { registerHooks } from 'node:module';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import {
EMPTY_SESSION_SNAPSHOT,
getSessionSnapshotActions,
publishSessionSnapshot,
} from '../state/sessionSnapshotStore';
import { getAppShellPropsSnapshot } from './appShellPropsStore';
import { registerAppHandlers } from './appHandlersBridge';
// Keep both production publishers and the store between them real. Only the
// state owner and unrelated theme side effects are replaced with fixtures.
const sessionFixtureUrl = `data:text/javascript,${encodeURIComponent(`
let session;
export function setSession(value) { session = value; }
export function useSessionState() { return session; }
`)}`;
const themeFixtureUrl = `data:text/javascript,${encodeURIComponent(`
const noop = () => {};
const theme = {};
const runtime = {
globalAppearance: theme, accentedGlobalAppearance: theme,
clearIntent: noop, settleManualIntent: noop, pickTheme: noop,
resolveFocusedAppearance: noop, currentTerminalTheme: theme,
};
export function useThemeRuntime() { return runtime; }
export function useTerminalAppearanceInjection() {}
`)}`;
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === '../../state/useSessionState' && context.parentURL?.endsWith('/SessionPublisher.tsx')) {
return { url: sessionFixtureUrl, shortCircuit: true };
}
if (specifier === '../../state/useThemeRuntime' && context.parentURL?.endsWith('/TerminalHost.tsx')) {
return { url: themeFixtureUrl, shortCircuit: true };
}
return nextResolve(specifier, context);
},
});
const { setSession } = await import(sessionFixtureUrl);
const { SessionPublisher } = await import('./publishers/SessionPublisher');
const { TerminalHost } = await import('./hosts/TerminalHost');
test('workspace actions reach the terminal shell through SessionPublisher and TerminalHost', async (t) => {
const previousActEnvironment = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
let renderer: ReactTestRenderer | undefined;
t.after(async () => {
await act(async () => renderer?.unmount());
registerAppHandlers(null);
publishSessionSnapshot(EMPTY_SESSION_SNAPSHOT);
if (previousActEnvironment) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousActEnvironment);
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
});
const calls: unknown[][] = [];
const moveWorkspacePane = (...args: unknown[]) => calls.push(['move', ...args]);
const setWorkspaceAnchorChat = (...args: unknown[]) => calls.push(['anchor', ...args]);
setSession({ ...EMPTY_SESSION_SNAPSHOT, moveWorkspacePane, setWorkspaceAnchorChat });
registerAppHandlers({});
const renderTree = () => React.createElement(
SessionPublisher,
{ persistSessionRestore: false },
React.createElement(TerminalHost),
);
await act(async () => { renderer = create(renderTree()); });
assert.equal(getSessionSnapshotActions()?.moveWorkspacePane, moveWorkspacePane);
assert.equal(getSessionSnapshotActions()?.setWorkspaceAnchorChat, setWorkspaceAnchorChat);
const terminal = getAppShellPropsSnapshot().domains?.terminal;
assert.equal(terminal?.moveWorkspacePane, moveWorkspacePane);
assert.equal(terminal?.setWorkspaceAnchorChat, setWorkspaceAnchorChat);
const hint = { direction: 'horizontal', position: 'top', targetSessionId: 'pane-b' };
(terminal?.moveWorkspacePane as typeof moveWorkspacePane)('workspace', 'pane-a', hint);
(terminal?.setWorkspaceAnchorChat as typeof setWorkspaceAnchorChat)('workspace', 'chat');
assert.deepEqual(calls, [
['move', 'workspace', 'pane-a', hint],
['anchor', 'workspace', 'chat'],
]);
// A changed state-owner callback must not be trapped in a stale memoized
// action bag even when all session/workspace snapshots stay identical.
const replacementMove = (...args: unknown[]) => calls.push(['replacement-move', ...args]);
const replacementAnchor = (...args: unknown[]) => calls.push(['replacement-anchor', ...args]);
setSession({ ...EMPTY_SESSION_SNAPSHOT, moveWorkspacePane: replacementMove, setWorkspaceAnchorChat: replacementAnchor });
await act(async () => renderer!.update(renderTree()));
assert.equal(getAppShellPropsSnapshot().domains?.terminal.moveWorkspacePane, replacementMove);
assert.equal(getAppShellPropsSnapshot().domains?.terminal.setWorkspaceAnchorChat, replacementAnchor);
});
+2
View File
@@ -170,6 +170,7 @@ export function TerminalHost() {
if (!handlers) return null;
return {
addSessionToWorkspace: sessionActions?.addSessionToWorkspace,
moveWorkspacePane: sessionActions?.moveWorkspacePane,
appendHostToWorkspace: sessionActions?.appendHostToWorkspace,
appendLocalTerminalToWorkspace: sessionActions?.appendLocalTerminalToWorkspace,
clearSessionFontSizeOverride: sessionActions?.clearSessionFontSizeOverride,
@@ -227,6 +228,7 @@ export function TerminalHost() {
setTerminalFontFamilyId: terminalSettingsActions?.setTerminalFontFamilyId,
setTerminalFontSize: terminalSettingsActions?.setTerminalFontSize,
setWorkspaceFocusedSession: sessionActions?.setWorkspaceFocusedSession,
setWorkspaceAnchorChat: sessionActions?.setWorkspaceAnchorChat,
sftpAutoOpenSidebar: terminalSettings.sftpAutoOpenSidebar,
sftpFollowTerminalCwd: terminalSettings.sftpFollowTerminalCwd,
setSftpFollowTerminalCwd: terminalSettingsActions?.setSftpFollowTerminalCwd,
@@ -48,6 +48,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
resetWorkspaceRename,
removeSessionFromWorkspace,
setWorkspaceFocusedSession,
setWorkspaceAnchorChat,
toggleWorkspaceViewMode,
createLocalTerminal,
createSerialSession,
@@ -58,6 +59,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
createWorkspaceWithHosts,
createWorkspaceFromSessions,
addSessionToWorkspace,
moveWorkspacePane,
appendHostToWorkspace,
appendHostToWorkspaceConfirmed,
appendLocalTerminalToWorkspace,
@@ -133,6 +135,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
resetWorkspaceRename,
removeSessionFromWorkspace,
setWorkspaceFocusedSession,
setWorkspaceAnchorChat,
toggleWorkspaceViewMode,
createLocalTerminal,
createSerialSession,
@@ -143,6 +146,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
createWorkspaceWithHosts,
createWorkspaceFromSessions,
addSessionToWorkspace,
moveWorkspacePane,
appendHostToWorkspace,
appendHostToWorkspaceConfirmed,
appendLocalTerminalToWorkspace,
@@ -172,6 +176,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
updateSessionCodingCliProvider,
}), [
addSessionToWorkspace,
moveWorkspacePane,
appendHostToWorkspace,
appendHostToWorkspaceConfirmed,
appendLocalTerminalToWorkspace,
@@ -208,6 +213,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
setActiveTabId,
setDraggingSessionId,
setWorkspaceFocusedSession,
setWorkspaceAnchorChat,
splitSession,
startSessionRename,
startWorkspaceRename,
@@ -0,0 +1,206 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import React, { useEffect, useRef } from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { useSessionState } from '../state/useSessionState';
import { captureClosingTerminalSessions, useTerminalSessionCloseCapture } from '../state/terminalSessionCloseCapture';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { TerminalConnectionProgress } from '../../components/terminal/TerminalConnectionProgress';
import { I18nProvider } from '../i18n/I18nProvider';
import { handleTerminalDataCaptureImpl } from './AppHandlers';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('explicit close persists never-connected logs; runtime remounts leave them open', async (t) => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
try {
for (const scenario of [
{ name: 'tab X before connected, empty buffer', status: 'connecting', data: '' },
{ name: 'failed-dialog close, empty buffer', status: 'disconnected', data: '' },
{ name: 'failed-dialog close preserves buffered diagnostics', status: 'disconnected', data: 'SSH diagnostic\r\n' },
{ name: 'batch close before connected', status: 'connecting', data: '', closeMode: 'batch' },
{ name: 'workspace close before connected', status: 'connecting', data: '', closeMode: 'workspace' },
] as const) {
await t.test(scenario.name, async () => {
let vault!: ReturnType<typeof useVaultState>;
let state!: ReturnType<typeof useSessionState>;
let root: ReactTestRenderer | undefined;
let sessionId!: string;
let logId!: string;
const captures: Promise<void>[] = [];
const capturedData: string[] = [];
function TerminalProbe() {
const hasConnectedRef = useRef(false);
const terminalDataCapturedRef = useRef(false);
const buffer = useRef(createConnectionLogBuffer(10000));
useEffect(() => {
buffer.current.append(scenario.data);
return () => { buffer.current.reset(); };
}, []);
useTerminalSessionCloseCapture({
sessionId, enabled: true, hasConnectedRef, terminalDataCapturedRef,
finalizeTerminalLogData: () => buffer.current.toString(),
onTerminalDataCapture: (id, data, options) => {
assert.equal(options.finalized, true);
assert.ok(state.sessions.some((session) => session.id === id), 'capture starts before removal');
terminalDataCapturedRef.current = true;
capturedData.push(data);
const pending = handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: state.sessions,
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), id, data);
captures.push(pending);
return pending;
},
});
return scenario.status === 'disconnected' ? React.createElement(
I18nProvider, { locale: 'en' }, React.createElement(TerminalConnectionProgress, {
status: 'disconnected', error: 'Connection refused', timeLeft: 0,
isCancelling: false, showLogs: false, progressLogs: [],
onCancelConnect: () => {}, onCloseSession: () => state.closeSession(sessionId),
}),
) : null;
}
function Probe({ showTerminal = true }) {
vault = useVaultState();
state = useSessionState({ persistSessionRestore: false });
return showTerminal && state.sessions.some((session) => session.id === sessionId)
? React.createElement(TerminalProbe) : null;
}
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
try {
await mount();
await act(async () => { sessionId = state.createLocalTerminal(); });
await act(async () => {
state.updateSessionStatus(sessionId, scenario.status);
const session = state.sessions.find((candidate) => candidate.id === sessionId)!;
logId = vault.addConnectionLog({
sessionId, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username,
protocol: session.protocol, startTime: Date.now(),
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
await vault.updateConnectionLog(logId, {});
});
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
let otherId!: string;
await act(async () => { otherId = state.createLocalTerminal(); });
await act(async () => { state.createWorkspaceFromSessions(sessionId, otherId, 'right'); });
}
// Recycle the renderer while retaining the session, as with a pane
// remount. Neither disposal nor the replacement runtime may end its log.
await act(async () => { root!.update(React.createElement(Probe, { showTerminal: false })); });
await act(async () => { root!.update(React.createElement(Probe)); });
assert.equal(captures.length, 0);
assert.equal(vault.connectionLogs.find((log) => log.id === logId)?.endTime, undefined);
// Both UI actions converge here. This exercises the actual state
// removal, owning-terminal hook, capture handler and vault persistence.
await act(async () => {
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
state.closeWorkspace(state.workspaces[0].id);
} else if ('closeMode' in scenario && scenario.closeMode === 'batch') {
state.closeSessions([sessionId]);
} else if (scenario.status === 'disconnected') {
// Click the actual Close button rendered inside the failed dialog.
root!.root.findByType('button').props.onClick();
} else {
state.closeSession(sessionId);
}
await Promise.all(captures);
});
assert.equal(state.sessions.some((session) => session.id === sessionId), false);
assert.deepEqual(capturedData, [scenario.data]);
await act(async () => { state.closeSession(sessionId); });
assert.equal(captures.length, 1, 'removed runtimes must unregister their capture');
await act(async () => { root!.unmount(); });
root = undefined;
await mount();
const persisted = vault.connectionLogs.find((log) => log.id === logId)!;
assert.ok(persisted.endTime, 'a durable endTime must exist even without terminal output');
assert.equal(persisted.terminalData || '', scenario.data);
} finally {
await act(async () => { root?.unmount(); });
}
});
}
} finally {
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('close capture skips non-owning, already connected and already captured runtimes', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
try {
for (const scenario of [
{ name: 'attached popup / inactive restored placeholder', enabled: false, connected: false, captured: false },
{ name: 'connected terminal uses existing drain path', enabled: true, connected: true, captured: false },
{ name: 'quit already captured the log', enabled: true, connected: false, captured: true },
]) {
await t.test(scenario.name, async () => {
let calls = 0;
let root!: ReactTestRenderer;
function Probe() {
useTerminalSessionCloseCapture({
sessionId: 'guarded', enabled: scenario.enabled,
hasConnectedRef: useRef(scenario.connected),
terminalDataCapturedRef: useRef(scenario.captured),
finalizeTerminalLogData: () => { calls++; return ''; },
onTerminalDataCapture: () => { calls++; },
});
return null;
}
await act(async () => { root = create(React.createElement(Probe)); });
try {
await act(async () => { captureClosingTerminalSessions(['guarded']); });
assert.equal(calls, 0);
} finally {
await act(async () => { root.unmount(); });
}
});
}
} finally {
if (previous) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previous);
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('both UI close paths reach session removal and Terminal registers the owning capture', () => {
const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
const app = read('./AppView.tsx');
assert.match(app, /onCloseSession=\{closeSession\}/);
assert.match(read('../../components/top-tabs/TopTabItems.tsx'), /onClick=\{\(e\) => onCloseSession\(session\.id, e\)\}/);
const terminal = read('../../components/Terminal.tsx');
assert.match(terminal, /useTerminalSessionCloseCapture\(\{\s*sessionId,\s*enabled: !attachExistingSession && restoreState !== "restored-disconnected",\s*hasConnectedRef,\s*terminalDataCapturedRef,\s*finalizeTerminalLogData,\s*onTerminalDataCapture: handleTerminalDataCaptureOnce,/);
const handler = terminal.slice(terminal.indexOf('const handleCloseDisconnectedSession ='), terminal.indexOf('const handleHostKeyClose ='));
assert.match(handler, /onCloseSession\?\.\(sessionId\)/);
assert.match(read('../../components/TerminalLayer.tsx'), /onCloseSession\(sessionId\)/);
assert.match(read('../../components/terminal/TerminalView.tsx'), /onCloseSession: handleCloseDisconnectedSession/);
assert.match(read('../../components/terminal/TerminalConnectionProgress.tsx'), /onClick=\{onCloseSession\}/);
});
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { EventEmitter } from 'node:events';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { withVaultImportLock } from '../state/vaultManagedImportLock';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type { TerminalSession } from '../../domain/models';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl } from './AppHandlers';
import { createPreloadApi } from '../../electron/preload/api.cjs';
import { finalizeSessionLogs } from '../../electron/bridges/sessionLogShutdown.cjs';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('quit persists replay before acknowledgment; restored reconnect keeps the old log and starts a new one', async () => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
let vault!: ReturnType<typeof useVaultState>;
let root: ReactTestRenderer | undefined;
const Probe = () => { vault = useVaultState(); return null; };
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
const session: TerminalSession = {
id: 'restorable-tab', hostId: 'host', hostLabel: 'Host', hostname: 'host.test',
username: 'user', protocol: 'ssh', status: 'connected',
};
const systemInfoRef = { current: { username: 'local-user', hostname: 'local-host' } };
const capture = (data: string) => handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: [session],
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), session.id, data);
try {
await mount();
let oldId!: string;
await act(async () => {
oldId = vault.addConnectionLog({
sessionId: session.id, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username, protocol: 'ssh', startTime: 1,
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
// Wait for the initial catalog write before blocking the capture write.
await vault.updateConnectionLog(oldId, {});
});
const buffer = createConnectionLogBuffer(10000);
buffer.append('output before quitting\r\n');
const ipcMain = new EventEmitter();
const ipcRenderer = new EventEmitter() as EventEmitter & { send: (channel: string, payload: unknown) => void };
const webContents = { send: (channel: string, payload: unknown) => ipcRenderer.emit(channel, {}, payload) };
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
const api = createPreloadApi({ ipcRenderer });
const off = api.onFinalizeSessionLogs(() => capture(buffer.toString()));
let release!: () => void;
const blockedWrite = withVaultImportLock('connection-logs', () => new Promise<void>((resolve) => { release = resolve; }));
await tick();
let acknowledged = false;
await act(async () => {
const quit = finalizeSessionLogs(webContents, { ipcMain }).then((success: boolean) => {
acknowledged = true;
assert.equal(success, true);
});
await tick();
assert.equal(acknowledged, false, 'main must wait for the persistence queue');
release();
await blockedWrite;
await quit;
});
off();
// Remounting reads durable storage. Node has no IndexedDB, so this also
// exercises the existing localStorage replay fallback.
await act(async () => { root?.unmount(); });
await mount();
const oldLog = vault.connectionLogs.find((log) => log.id === oldId)!;
assert.ok(oldLog.endTime);
assert.equal(oldLog.terminalData, 'output before quitting\r\n');
await act(async () => {
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog: vault.addConnectionLog, systemInfoRef }), {
...session, status: 'disconnected', restoreState: 'restored-disconnected',
});
});
const newLog = vault.connectionLogs.find((log) => log.id !== oldId)!;
assert.equal(newLog.sessionId, session.id);
assert.equal(newLog.endTime, undefined);
assert.equal(newLog.terminalData, undefined);
await act(async () => { await capture('output after reconnect\r\n'); });
await act(async () => { root?.unmount(); });
await mount();
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.terminalData, oldLog.terminalData);
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.endTime, oldLog.endTime);
assert.equal(vault.connectionLogs.find((log) => log.id === newLog.id)?.terminalData, 'output after reconnect\r\n');
assert.ok(vault.connectionLogs.find((log) => log.id === newLog.id)?.endTime);
} finally {
await act(async () => { root?.unmount(); });
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('terminal quit listener drains output and awaits capture without tearing down tabs', () => {
const source = readFileSync(new URL('../../components/Terminal.tsx', import.meta.url), 'utf8');
const start = source.indexOf('onFinalizeSessionLogs?.(async () => {');
assert.ok(start > 0);
const listener = source.slice(start, source.indexOf('const attachHomeWebContentsIdRef', start));
assert.match(listener, /await flushPendingTerminalWritesBeforeHibernate\(term\)/);
assert.match(listener, /await handleTerminalDataCaptureOnce\(sessionId, finalizeTerminalLogData\(\), \{ finalized: true \}\)/);
assert.doesNotMatch(listener, /closeSession|teardown/);
const effects = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8');
const handler = effects.slice(effects.indexOf('const handleSessionStatusChange ='), effects.indexOf('const handleUpdateHostFromTerminal ='));
assert.ok(handler.indexOf('startRestoredSessionConnectionLogImpl(') < handler.indexOf('updateSessionStatus(sessionId, status)'));
assert.match(handler, /restoredSessionLogsStartedRef\.current\.has\(sessionId\)/);
});
+2
View File
@@ -720,6 +720,8 @@ export const enAiMessages: Messages = {
// Unified tooltips for terminal workspace and top tabs (issue #954)
'terminal.layer.addTerminal': 'Add Terminal',
'terminal.layer.emptyWorkspace': 'No terminals in this workspace',
'terminal.layer.emptyWorkspaceHint': 'Add a local terminal or connect to a host to get started.',
'terminal.layer.switchToSplitView': 'Switch to Split View',
'terminal.layer.sftp': 'SFTP',
'terminal.layer.scripts': 'Scripts',
+38
View File
@@ -1,6 +1,44 @@
import type { Messages } from '../types';
export const enCoreMessages: Messages = {
"settings.plugins.github.install": "Install from GitHub",
"settings.plugins.github.description": "Download a published .ncpkg release, then review its source and permissions.",
"settings.plugins.github.repository": "GitHub repository",
"settings.plugins.github.formats": "Accepts https://github.com/owner/repo, github.com/owner/repo or owner/repo.",
"settings.plugins.github.busy": "Downloading, validating or installing the package...",
"settings.plugins.github.review": "Repository ownership and package integrity do not verify publisher trust. No build scripts run. The plugin installs disabled; review permission modes before enabling.",
"settings.plugins.github.accept": "I trust this repository and have reviewed the declared permissions.",
"settings.plugins.github.confirm": "Install disabled",
"settings.plugins.github.download": "Download and review",
"settings.plugins.github.error.invalidRepository": "Enter https://github.com/owner/repo, github.com/owner/repo or owner/repo (repository only; no credentials, query, fragment or extra paths).",
"settings.plugins.github.error.unavailable": "GitHub plugin installation is unavailable in this session.",
"settings.plugins.github.error.reviewFirst": "Download and review a GitHub plugin first.",
"settings.plugins.github.error.network": "Cannot reach GitHub. Check your network connection and try again.",
"settings.plugins.github.error.timeout": "The GitHub download timed out. Please try again.",
"settings.plugins.github.error.rateLimit": "GitHub API rate limit reached. Try again later.",
"settings.plugins.github.error.notFound": "GitHub repository or asset not found. Only accessible public repositories are supported; import private packages locally.",
"settings.plugins.github.error.accessDenied": "GitHub access denied. Private repositories and sign-in are not supported.",
"settings.plugins.github.error.http": "GitHub download failed (HTTP {status}). Please try again later.",
"settings.plugins.github.error.moved": "This GitHub repository has moved. Enter its current repository URL.",
"settings.plugins.github.error.redirect": "The GitHub download redirect could not be verified. Download a trusted .ncpkg package and import it locally.",
"settings.plugins.github.error.noRelease": "This repository has no published stable release. Ask the author to publish one with a .ncpkg asset, or import a built package locally.",
"settings.plugins.github.error.noAsset": "This release has no .ncpkg asset. Ask the author to build and attach one; Netcatty cannot build source repositories.",
"settings.plugins.github.error.multipleAssets": "This release contains multiple .ncpkg assets. Download the intended package and import it locally.",
"settings.plugins.github.error.metadata": "The GitHub release metadata is invalid. Ask the author to check the release, tag and .ncpkg asset.",
"settings.plugins.github.error.identity": "The package does not match the selected GitHub repository and release. Installation was stopped.",
"settings.plugins.github.error.commit": "The release tag has no accessible commit. Ask the author to repair the release tag.",
"settings.plugins.github.error.size": "The GitHub package size is invalid or exceeds the download limit.",
"settings.plugins.github.error.integrity": "The downloaded package failed its size or SHA-256 check. Download and review it again.",
"settings.plugins.github.error.package": "GitHub did not return a valid .ncpkg ZIP package or release metadata. Ask the author to check the release asset.",
"settings.plugins.github.error.busy": "A GitHub plugin operation is already active. Close the preview and try again.",
"settings.plugins.github.error.expired": "The GitHub package preview expired. Download and review it again.",
"settings.plugins.github.error.advanced": "This package requires advanced developer mode. Normal plugin management accepts browser-only packages.",
"settings.plugins.github.error.incompatible": "This plugin is incompatible with this version of Netcatty. Check the technical details with the author.",
"settings.plugins.github.error.source": "This plugin is already bound to another source. Uninstall it and explicitly clear its old source data before changing sources.",
"settings.plugins.github.error.failed": "The plugin could not be validated or installed. Check the technical details before trying again.",
"settings.plugins.github.error.details": "Technical details",
"settings.plugins.landing.checkUpdates": "Check for updates",
"settings.plugins.landing.checkingUpdates": "Checking…",
"settings.plugins.landing.updateSummary": "Checked: {checked} · Published updates: {updates} · Not checked: {skipped}.",
+19
View File
@@ -316,7 +316,26 @@ export const enVaultMessages: Messages = {
'sftp.extract.extracting': 'Extracting {fileName}...',
'sftp.extract.success': 'Extracted {fileName}',
'sftp.extract.error': 'Failed to extract {fileName}: {error}',
'sftp.archive.action': 'Compress...',
'sftp.archive.title': 'Compress files',
'sftp.archive.description': 'Create an archive on the server from {count} selected items.',
'sftp.archive.name': 'Archive name',
'sftp.archive.format': 'Format',
'sftp.archive.destination': 'Save in',
'sftp.archive.create': 'Compress',
'sftp.archive.creating': 'Compressing...',
'sftp.archive.overwriteTitle': 'Replace existing archive?',
'sftp.archive.overwriteDescription': 'An archive named "{name}" already exists. Confirm to replace it with the new archive.',
'sftp.archive.overwrite': 'Replace and compress',
'sftp.archive.failed': 'Failed to create archive',
'sftp.archive.invalidSelection': 'Cannot compress this selection',
'sftp.archive.invalidName': 'Enter a valid file name without a directory path.',
'sftp.archive.invalidExtension': 'The file extension must match the selected format.',
'sftp.archive.connectionChanged': 'The connection has changed. Select the files again.',
'sftp.archive.unavailable': 'Archive creation is unavailable for this connection.',
'sftp.archive.success': 'Created {fileName}',
'sftp.context.copyToOtherPane': 'Copy to other pane',
'sftp.context.duplicate': 'Duplicate',
'sftp.copyToOtherPane.unavailable': 'Open the two-pane SFTP view and connect the destination pane before copying files.',
'sftp.copyCurrentPath': 'Copy current path',
'sftp.copyCurrentPath.success': 'Current path copied',
+2
View File
@@ -720,6 +720,8 @@ export const esAiMessages: Messages = {
// Unified tooltips for terminal workspace and top tabs (issue #954)
'terminal.layer.addTerminal': 'Agregar terminal',
'terminal.layer.emptyWorkspace': 'No hay terminales en este espacio de trabajo',
'terminal.layer.emptyWorkspaceHint': 'Agrega un terminal local o conecta un host para comenzar.',
'terminal.layer.switchToSplitView': 'Cambiar a vista dividida',
'terminal.layer.sftp': 'SFTP',
'terminal.layer.scripts': 'Scripts',
+38
View File
@@ -1,6 +1,44 @@
import type { Messages } from '../types';
export const esCoreMessages: Messages = {
"settings.plugins.github.install": "Instalar desde GitHub",
"settings.plugins.github.description": "Descarga una versión .ncpkg publicada y revisa su origen y permisos.",
"settings.plugins.github.repository": "Repositorio de GitHub",
"settings.plugins.github.formats": "Acepta https://github.com/owner/repo, github.com/owner/repo u owner/repo.",
"settings.plugins.github.busy": "Descargando, validando o instalando el paquete...",
"settings.plugins.github.review": "El origen y la integridad no verifican la confianza en el autor. No se ejecutan scripts de compilación. Se instala desactivado; revisa los permisos antes de activarlo.",
"settings.plugins.github.accept": "Confío en este repositorio y he revisado los permisos declarados.",
"settings.plugins.github.confirm": "Instalar desactivado",
"settings.plugins.github.download": "Descargar y revisar",
"settings.plugins.github.error.invalidRepository": "Introduce https://github.com/owner/repo, github.com/owner/repo u owner/repo. Usa solo el repositorio, sin credenciales, parámetros, fragmentos ni rutas adicionales.",
"settings.plugins.github.error.unavailable": "La instalación de plugins desde GitHub no está disponible en esta sesión.",
"settings.plugins.github.error.reviewFirst": "Primero descarga y revisa un plugin de GitHub.",
"settings.plugins.github.error.network": "No se puede conectar con GitHub. Comprueba tu conexión e inténtalo de nuevo.",
"settings.plugins.github.error.timeout": "La descarga de GitHub agotó el tiempo de espera. Inténtalo de nuevo.",
"settings.plugins.github.error.rateLimit": "Se alcanzó el límite de solicitudes de la API de GitHub. Inténtalo más tarde.",
"settings.plugins.github.error.notFound": "No se encontró el repositorio o archivo de GitHub. Solo se admiten repositorios públicos accesibles; importa los paquetes privados desde un archivo local.",
"settings.plugins.github.error.accessDenied": "GitHub denegó el acceso. No se admiten repositorios privados ni inicio de sesión.",
"settings.plugins.github.error.http": "La descarga de GitHub falló (HTTP {status}). Inténtalo más tarde.",
"settings.plugins.github.error.moved": "Este repositorio de GitHub se ha movido. Introduce su dirección actual.",
"settings.plugins.github.error.redirect": "No se pudo verificar la redirección de GitHub. Descarga un paquete .ncpkg de confianza e impórtalo desde un archivo local.",
"settings.plugins.github.error.noRelease": "Este repositorio no tiene una versión estable publicada. Pide al autor que publique una con un archivo .ncpkg o importa un paquete compilado local.",
"settings.plugins.github.error.noAsset": "Esta versión no incluye un archivo .ncpkg. Pide al autor que lo compile y adjunte; Netcatty no puede compilar repositorios de código fuente.",
"settings.plugins.github.error.multipleAssets": "Esta versión contiene varios archivos .ncpkg. Descarga el paquete deseado e impórtalo desde un archivo local.",
"settings.plugins.github.error.metadata": "Los metadatos de la versión de GitHub no son válidos. Pide al autor que revise la versión, la etiqueta y el archivo .ncpkg.",
"settings.plugins.github.error.identity": "El paquete no coincide con el repositorio y la versión de GitHub seleccionados. Se detuvo la instalación.",
"settings.plugins.github.error.commit": "La etiqueta de la versión no tiene un commit accesible. Pide al autor que corrija la etiqueta.",
"settings.plugins.github.error.size": "El tamaño del paquete de GitHub no es válido o supera el límite de descarga.",
"settings.plugins.github.error.integrity": "El paquete descargado no superó la comprobación de tamaño o SHA-256. Descárgalo y revísalo de nuevo.",
"settings.plugins.github.error.package": "GitHub no devolvió un paquete ZIP .ncpkg o metadatos de versión válidos. Pide al autor que revise el archivo publicado.",
"settings.plugins.github.error.busy": "Ya hay una operación de plugin de GitHub en curso. Cierra la vista previa e inténtalo de nuevo.",
"settings.plugins.github.error.expired": "La vista previa del paquete de GitHub caducó. Descárgalo y revísalo de nuevo.",
"settings.plugins.github.error.advanced": "Este paquete requiere el modo de desarrollo avanzado. La gestión normal solo admite paquetes para navegador.",
"settings.plugins.github.error.incompatible": "Este plugin no es compatible con esta versión de Netcatty. Consulta los detalles técnicos con el autor.",
"settings.plugins.github.error.source": "Este plugin ya está vinculado a otro origen. Desinstálalo y borra explícitamente los datos del origen anterior antes de cambiarlo.",
"settings.plugins.github.error.failed": "No se pudo validar o instalar el plugin. Revisa los detalles técnicos antes de intentarlo de nuevo.",
"settings.plugins.github.error.details": "Detalles técnicos",
"settings.plugins.landing.checkUpdates": "Buscar actualizaciones",
"settings.plugins.landing.checkingUpdates": "Buscando…",
"settings.plugins.landing.updateSummary": "Comprobados: {checked} · Actualizaciones publicadas: {updates} · Sin comprobar: {skipped}.",
+19
View File
@@ -316,7 +316,26 @@ export const esVaultMessages: Messages = {
'sftp.extract.extracting': 'Extrayendo {fileName}...',
'sftp.extract.success': 'Se extrajo {fileName}',
'sftp.extract.error': 'No se pudo extraer {fileName}: {error}',
'sftp.archive.action': 'Comprimir...',
'sftp.archive.title': 'Comprimir archivos',
'sftp.archive.description': 'Crea un archivo comprimido en el servidor con los {count} elementos seleccionados.',
'sftp.archive.name': 'Nombre del archivo comprimido',
'sftp.archive.format': 'Formato',
'sftp.archive.destination': 'Guardar en',
'sftp.archive.create': 'Comprimir',
'sftp.archive.creating': 'Comprimiendo...',
'sftp.archive.overwriteTitle': '¿Reemplazar el archivo comprimido existente?',
'sftp.archive.overwriteDescription': 'Ya existe un archivo comprimido llamado "{name}". Confirma para reemplazarlo por el nuevo.',
'sftp.archive.overwrite': 'Reemplazar y comprimir',
'sftp.archive.failed': 'No se pudo crear el archivo comprimido',
'sftp.archive.invalidSelection': 'No se puede comprimir esta selección',
'sftp.archive.invalidName': 'Ingresa un nombre de archivo válido sin una ruta de directorio.',
'sftp.archive.invalidExtension': 'La extensión del archivo debe coincidir con el formato seleccionado.',
'sftp.archive.connectionChanged': 'La conexión cambió. Vuelve a seleccionar los archivos.',
'sftp.archive.unavailable': 'No se pueden crear archivos comprimidos en esta conexión.',
'sftp.archive.success': 'Se creó {fileName}',
'sftp.context.copyToOtherPane': 'Copiar al otro panel',
'sftp.context.duplicate': 'Duplicar',
'sftp.copyToOtherPane.unavailable': 'Abre la vista SFTP de dos paneles y conecta el panel de destino antes de copiar archivos.',
'sftp.copyCurrentPath': 'Copiar ruta actual',
'sftp.copyCurrentPath.success': 'Ruta actual copiada',
@@ -12,16 +12,23 @@ import zhTW from "./zh-TW.ts";
// so the remaining debt stays visible instead of silently rendering in English
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
// Move a locale out of this list once it covers every `en` key.
const LOCALES_PENDING_PARITY = ["ru", "zh-CN", "zh-TW"] as const;
const LOCALES_PENDING_PARITY = ["ru"] as const;
const hasKey = (messages: Record<string, string>, key: string) =>
Object.hasOwn(messages, key);
const interpolationTokens = (value: string) =>
[...value.matchAll(/\{\{\s*\w+\s*\}\}|\{\s*\w+\s*\}/g)]
[...value.matchAll(/\{\{\s*[^}]+\s*\}\}|\{\s*\w+\s*\}/g)]
.map((match) => match[0].replace(/[{}]/g, "").trim())
.sort();
test("interpolationTokens reads the :default placeholder form", () => {
assert.deepEqual(interpolationTokens("{{name}} or {{name:default}}"), [
"name",
"name:default",
]);
});
test("es defines every message key that en defines", () => {
const missing = Object.keys(en).filter((key) => !hasKey(es, key));
@@ -42,22 +49,31 @@ test("es defines no message keys that en does not define", () => {
);
});
test("es keeps the same interpolation placeholders as en", () => {
const mismatched: string[] = [];
test("every translated locale keeps the same interpolation placeholders as en", () => {
const locales = [
{ name: "es", messages: es },
{ name: "ru", messages: ru },
{ name: "zh-CN", messages: zhCN },
{ name: "zh-TW", messages: zhTW },
];
for (const key of Object.keys(es)) {
if (!hasKey(en, key)) continue;
for (const locale of locales) {
const mismatched: string[] = [];
const expected = interpolationTokens(en[key] ?? "").join(",");
const actual = interpolationTokens(es[key] ?? "").join(",");
if (expected !== actual) mismatched.push(key);
for (const key of Object.keys(locale.messages)) {
if (!hasKey(en, key)) continue;
const expected = interpolationTokens(en[key] ?? "").join(",");
const actual = interpolationTokens(locale.messages[key] ?? "").join(",");
if (expected !== actual) mismatched.push(key);
}
assert.deepEqual(
mismatched,
[],
`${locale.name} changes interpolation placeholders for ${mismatched.length} keys`,
);
}
assert.deepEqual(
mismatched,
[],
`es changes interpolation placeholders for ${mismatched.length} keys`,
);
});
test("every default shortcut has a label in en and es", () => {
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { SUPPORTED_UI_LOCALES } from '../../../infrastructure/config/i18n';
import { getLoadedLocaleMessages, loadLocaleMessages } from '../messages';
import en from './en';
import { describePluginGitHubInstallError } from '../../../domain/pluginGitHubInstallError';
test('GitHub install copy and error interpolation are complete in every supported UI locale', async () => {
const keys = Object.keys(en).filter(key => key.startsWith('settings.plugins.github.'));
assert.ok(keys.length > 30);
for (const { id } of SUPPORTED_UI_LOCALES) {
await loadLocaleMessages(id);
const messages = getLoadedLocaleMessages(id)!;
for (const key of keys) {
assert.ok(messages[key]?.trim(), `${id}: ${key}`);
assert.deepEqual(messages[key].match(/\{\w+\}/g) ?? [], en[key].match(/\{\w+\}/g) ?? [], `${id}: ${key}`);
}
}
});
test('GitHub error presentation handles Electron wrappers, HTTP status and diagnostic fallback', () => {
const expired = describePluginGitHubInstallError("Error invoking remote method 'plugins:github:install': Error: GitHub package preview expired. Download and review it again");
assert.equal(expired.key, 'settings.plugins.github.error.expired');
assert.equal(expired.details, null);
assert.deepEqual(describePluginGitHubInstallError('GitHub download failed (HTTP 503)').values, { status: '503' });
const validator = 'manifest version must be a semantic version';
assert.equal(describePluginGitHubInstallError(validator).details, validator);
assert.equal(describePluginGitHubInstallError(validator).key, 'settings.plugins.github.error.failed');
assert.equal(describePluginGitHubInstallError('Plugin is incompatible: engine version').key, 'settings.plugins.github.error.incompatible');
});
+2
View File
@@ -659,6 +659,8 @@ export const ruAiMessages: Messages = {
// Unified tooltips for terminal workspace and top tabs (issue #954)
'terminal.layer.addTerminal': 'Добавить терминал',
'terminal.layer.emptyWorkspace': 'В этом рабочем пространстве пока нет терминалов',
'terminal.layer.emptyWorkspaceHint': 'Добавьте локальный терминал или подключитесь к хосту, чтобы начать.',
'terminal.layer.switchToSplitView': 'Переключить в режим разделения',
'terminal.layer.sftp': 'SFTP',
'terminal.layer.scripts': 'Скрипты',
+38
View File
@@ -1,6 +1,44 @@
import type { Messages } from '../types';
export const ruCoreMessages: Messages = {
"settings.plugins.github.install": "Установить из GitHub",
"settings.plugins.github.description": "Загрузите опубликованный выпуск .ncpkg и проверьте источник и разрешения.",
"settings.plugins.github.repository": "Репозиторий GitHub",
"settings.plugins.github.formats": "Поддерживаются https://github.com/owner/repo, github.com/owner/repo и owner/repo.",
"settings.plugins.github.busy": "Загрузка, проверка или установка пакета...",
"settings.plugins.github.review": "Источник и целостность пакета не подтверждают доверие к издателю. Скрипты сборки не запускаются. Плагин устанавливается выключенным; проверьте разрешения перед включением.",
"settings.plugins.github.accept": "Я доверяю этому репозиторию и проверил заявленные разрешения.",
"settings.plugins.github.confirm": "Установить выключенным",
"settings.plugins.github.download": "Загрузить и проверить",
"settings.plugins.github.error.invalidRepository": "Введите https://github.com/owner/repo, github.com/owner/repo или owner/repo. Укажите только репозиторий, без учётных данных, параметров, фрагментов и дополнительных путей.",
"settings.plugins.github.error.unavailable": "Установка плагинов из GitHub недоступна в этом сеансе.",
"settings.plugins.github.error.reviewFirst": "Сначала загрузите и проверьте плагин из GitHub.",
"settings.plugins.github.error.network": "Не удалось подключиться к GitHub. Проверьте соединение и повторите попытку.",
"settings.plugins.github.error.timeout": "Время ожидания загрузки из GitHub истекло. Повторите попытку.",
"settings.plugins.github.error.rateLimit": "Достигнут лимит запросов API GitHub. Повторите попытку позже.",
"settings.plugins.github.error.notFound": "Репозиторий или файл GitHub не найден. Поддерживаются только доступные публичные репозитории; импортируйте приватные пакеты из локального файла.",
"settings.plugins.github.error.accessDenied": "GitHub отказал в доступе. Приватные репозитории и вход в аккаунт не поддерживаются.",
"settings.plugins.github.error.http": "Ошибка загрузки из GitHub (HTTP {status}). Повторите попытку позже.",
"settings.plugins.github.error.moved": "Репозиторий GitHub перемещён. Введите его текущий адрес.",
"settings.plugins.github.error.redirect": "Не удалось проверить перенаправление загрузки GitHub. Загрузите доверенный пакет .ncpkg и импортируйте его из локального файла.",
"settings.plugins.github.error.noRelease": "В репозитории нет опубликованного стабильного выпуска. Попросите автора опубликовать выпуск с файлом .ncpkg или импортируйте готовый пакет из локального файла.",
"settings.plugins.github.error.noAsset": "В выпуске нет файла .ncpkg. Попросите автора собрать и прикрепить его; Netcatty не собирает репозитории исходного кода.",
"settings.plugins.github.error.multipleAssets": "В выпуске несколько файлов .ncpkg. Загрузите нужный пакет и импортируйте его из локального файла.",
"settings.plugins.github.error.metadata": "Некорректные метаданные выпуска GitHub. Попросите автора проверить выпуск, тег и файл .ncpkg.",
"settings.plugins.github.error.identity": "Пакет не соответствует выбранному репозиторию и выпуску GitHub. Установка остановлена.",
"settings.plugins.github.error.commit": "У тега выпуска нет доступного коммита. Попросите автора исправить тег.",
"settings.plugins.github.error.size": "Размер пакета GitHub некорректен или превышает лимит загрузки.",
"settings.plugins.github.error.integrity": "Загруженный пакет не прошёл проверку размера или SHA-256. Загрузите и проверьте его снова.",
"settings.plugins.github.error.package": "GitHub не вернул корректный ZIP-пакет .ncpkg или метаданные выпуска. Попросите автора проверить файл выпуска.",
"settings.plugins.github.error.busy": "Операция с плагином GitHub уже выполняется. Закройте предпросмотр и повторите попытку.",
"settings.plugins.github.error.expired": "Предпросмотр пакета GitHub устарел. Загрузите и проверьте его снова.",
"settings.plugins.github.error.advanced": "Для этого пакета нужен расширенный режим разработчика. Обычный менеджер принимает только браузерные пакеты.",
"settings.plugins.github.error.incompatible": "Плагин несовместим с этой версией Netcatty. Уточните технические подробности у автора.",
"settings.plugins.github.error.source": "Плагин уже привязан к другому источнику. Перед сменой источника удалите плагин и явно очистите данные прежнего источника.",
"settings.plugins.github.error.failed": "Не удалось проверить или установить плагин. Изучите технические подробности перед повторной попыткой.",
"settings.plugins.github.error.details": "Технические подробности",
// Common
'common.save': 'Сохранить',
'common.cancel': 'Отмена',
+19
View File
@@ -360,7 +360,26 @@ export const ruVaultMessages: Messages = {
'sftp.extract.extracting': 'Распаковка {fileName}...',
'sftp.extract.success': 'Распакован {fileName}',
'sftp.extract.error': 'Не удалось распаковать {fileName}: {error}',
'sftp.archive.action': 'Сжать...',
'sftp.archive.title': 'Сжать файлы',
'sftp.archive.description': 'Создать архив на сервере из выбранных объектов: {count}.',
'sftp.archive.name': 'Имя архива',
'sftp.archive.format': 'Формат',
'sftp.archive.destination': 'Сохранить в',
'sftp.archive.create': 'Сжать',
'sftp.archive.creating': 'Сжатие...',
'sftp.archive.overwriteTitle': 'Заменить существующий архив?',
'sftp.archive.overwriteDescription': 'Архив с именем «{name}» уже существует. Подтвердите его замену новым архивом.',
'sftp.archive.overwrite': 'Заменить и сжать',
'sftp.archive.failed': 'Не удалось создать архив',
'sftp.archive.invalidSelection': 'Невозможно сжать выбранные объекты',
'sftp.archive.invalidName': 'Введите допустимое имя файла без пути к каталогу.',
'sftp.archive.invalidExtension': 'Расширение файла должно соответствовать выбранному формату.',
'sftp.archive.connectionChanged': 'Подключение изменилось. Выберите файлы заново.',
'sftp.archive.unavailable': 'Создание архивов недоступно для этого подключения.',
'sftp.archive.success': 'Создан архив {fileName}',
'sftp.context.copyToOtherPane': 'Копировать в другую панель',
'sftp.context.duplicate': 'Дублировать',
'sftp.copyToOtherPane.unavailable': 'Откройте двухпанельный режим SFTP и подключите панель назначения перед копированием файлов.',
'sftp.copyCurrentPath': 'Копировать текущий путь',
'sftp.copyCurrentPath.success': 'Текущий путь скопирован',
+2
View File
@@ -720,6 +720,8 @@ export const zhCNAiMessages: Messages = {
// 统一终端工作区和顶部标签的 tooltip 文案 (issue #954)
'terminal.layer.addTerminal': '添加终端',
'terminal.layer.emptyWorkspace': '工作区中还没有终端',
'terminal.layer.emptyWorkspaceHint': '添加本地终端或连接主机,开始使用这个工作区。',
'terminal.layer.switchToSplitView': '切换到分屏视图',
'terminal.layer.sftp': '文件传输',
'terminal.layer.scripts': '脚本',
+59
View File
@@ -1,6 +1,44 @@
import type { Messages } from '../types';
export const zhCNCoreMessages: Messages = {
"settings.plugins.github.install": "从 GitHub 安装",
"settings.plugins.github.description": "下载已发布的 .ncpkg 插件包,安装前请审查来源和所需权限。",
"settings.plugins.github.repository": "GitHub 仓库",
"settings.plugins.github.formats": "支持 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。",
"settings.plugins.github.busy": "正在下载、验证或安装插件包…",
"settings.plugins.github.review": "确认仓库来源并通过完整性校验,并不代表发布者值得信任。安装过程不会运行构建脚本,插件安装后默认禁用。启用前,请确认来源可信并检查各项权限的授权方式。",
"settings.plugins.github.accept": "已审查并信任此仓库,且已查看声明的权限。",
"settings.plugins.github.confirm": "安装并保持禁用",
"settings.plugins.github.download": "下载并审查",
"settings.plugins.github.error.invalidRepository": "请输入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。请只填写仓库地址,不要包含账号密码、查询参数、片段或额外路径。",
"settings.plugins.github.error.unavailable": "当前会话无法从 GitHub 安装插件。",
"settings.plugins.github.error.reviewFirst": "请先下载并审查 GitHub 插件。",
"settings.plugins.github.error.network": "无法连接 GitHub,请检查网络连接后重试。",
"settings.plugins.github.error.timeout": "从 GitHub 下载超时,请重试。",
"settings.plugins.github.error.rateLimit": "GitHub API 请求次数已达上限,请稍后重试。",
"settings.plugins.github.error.notFound": "未找到 GitHub 仓库或发布附件。仅支持可访问的公开仓库;私有插件包请从本地导入。",
"settings.plugins.github.error.accessDenied": "GitHub 拒绝访问。此功能不支持私有仓库或登录验证。",
"settings.plugins.github.error.http": "从 GitHub 下载失败(HTTP {status}),请稍后重试。",
"settings.plugins.github.error.moved": "此 GitHub 仓库已迁移,请输入当前仓库地址。",
"settings.plugins.github.error.redirect": "无法验证 GitHub 下载重定向。请下载可信的 .ncpkg 插件包,再从本地导入。",
"settings.plugins.github.error.noRelease": "此仓库尚未发布稳定版本。请作者发布包含 .ncpkg 附件的稳定版本,或从本地导入已构建的插件包。",
"settings.plugins.github.error.noAsset": "此版本没有 .ncpkg 附件。请作者构建并上传插件包;Netcatty 无法直接构建源码仓库。",
"settings.plugins.github.error.multipleAssets": "此版本包含多个 .ncpkg 附件。请下载需要的插件包,再从本地导入。",
"settings.plugins.github.error.metadata": "GitHub 发布信息无效。请作者检查版本发布、标签和 .ncpkg 附件。",
"settings.plugins.github.error.identity": "插件包与所选 GitHub 仓库或发布版本不匹配,已停止安装。",
"settings.plugins.github.error.commit": "无法访问发布标签对应的提交,请作者修复发布标签。",
"settings.plugins.github.error.size": "GitHub 插件包大小无效或超出下载限制。",
"settings.plugins.github.error.integrity": "下载的插件包未通过大小或 SHA-256 校验,请重新下载并审查。",
"settings.plugins.github.error.package": "GitHub 返回的内容不是有效的 .ncpkg ZIP 插件包或发布信息,请作者检查发布附件。",
"settings.plugins.github.error.busy": "已有 GitHub 插件操作正在进行,请关闭预览后重试。",
"settings.plugins.github.error.expired": "GitHub 插件包预览已失效,请重新下载并审查。",
"settings.plugins.github.error.advanced": "此插件包需要高级开发者模式。普通插件管理仅接受浏览器运行时插件包。",
"settings.plugins.github.error.incompatible": "此插件与当前 Netcatty 版本不兼容,请联系作者确认技术详情。",
"settings.plugins.github.error.source": "此插件已绑定其他来源。更换来源前,请先卸载插件并明确清除原来源的私有数据。",
"settings.plugins.github.error.failed": "无法验证或安装插件,请查看技术详情后再重试。",
"settings.plugins.github.error.details": "技术详情",
"settings.plugins.landing.checkUpdates": "检查更新",
"settings.plugins.landing.checkingUpdates": "正在检查…",
"settings.plugins.landing.updateSummary": "已检查:{checked} · 已发布更新:{updates} · 未检查:{skipped}。",
@@ -83,9 +121,11 @@ export const zhCNCoreMessages: Messages = {
'confirm.closeBusyTerminal.messageWithMore': '进程 "{command}" 及其他 {count} 个正在运行的进程将被终止。',
'confirm.closeBusyTerminal.cancel': '取消',
'confirm.closeBusyTerminal.close': '关闭',
'dialog.createWorkspace.title': '创建工作区',
'dialog.renameWorkspace.title': '重命名工作区',
'dialog.renameSession.title': '重命名会话',
'field.name': '名称',
'field.selectHosts': '选择主机',
'placeholder.workspaceName': '工作区名称',
'placeholder.sessionName': '会话名称',
'placeholder.searchHosts': '搜索主机或标签...',
@@ -1015,7 +1055,26 @@ Vaults 标签保持扁平,不使用这块背景。
'sftp.extract.extracting': '正在解压 {fileName}...',
'sftp.extract.success': '已解压 {fileName}',
'sftp.extract.error': '解压 {fileName} 失败:{error}',
'sftp.archive.action': '压缩…',
'sftp.archive.title': '压缩文件',
'sftp.archive.description': '将 {count} 个选中项目打包到服务器上的压缩包。',
'sftp.archive.name': '压缩包名称',
'sftp.archive.format': '格式',
'sftp.archive.destination': '保存目录',
'sftp.archive.create': '压缩',
'sftp.archive.creating': '正在压缩…',
'sftp.archive.overwriteTitle': '覆盖现有压缩包?',
'sftp.archive.overwriteDescription': '“{name}”已存在。确认后将用新的压缩包替换它。',
'sftp.archive.overwrite': '覆盖并压缩',
'sftp.archive.failed': '压缩失败',
'sftp.archive.invalidSelection': '无法压缩此选区',
'sftp.archive.invalidName': '请输入有效的文件名,不要包含目录路径。',
'sftp.archive.invalidExtension': '文件扩展名必须与所选格式一致。',
'sftp.archive.connectionChanged': '连接已切换,请重新选择文件。',
'sftp.archive.unavailable': '当前连接不支持创建压缩包。',
'sftp.archive.success': '已创建 {fileName}',
'sftp.context.copyToOtherPane': '复制到另一侧',
'sftp.context.duplicate': '创建副本',
'sftp.copyToOtherPane.unavailable': '请打开双栏 SFTP 文件管理,并连接目标侧后再复制文件。',
'sftp.copyCurrentPath': '复制当前路径',
'sftp.copyCurrentPath.success': '已复制当前路径',
+1 -1
View File
@@ -969,7 +969,7 @@ export const zhCNTerminalMessages: Messages = {
'snippets.variables.placeholderDefault': '默认:{value}',
'snippets.variables.required': '请填写此变量',
'snippets.variables.run': '运行',
'snippets.field.variablesHelp': '在脚本中使用 {{名称}} 或 {{名称:默认值}} 定义变量。',
'snippets.field.variablesHelp': '在脚本中使用 {{name}} 或 {{name:default}} 作为占位符。',
'snippets.field.variablesDetected': '变量',
'snippets.field.variableDefault': '默认 {value}',
+14 -3
View File
@@ -39,6 +39,15 @@ export const zhTWAiMessages: Messages = {
'ai.providers.noApiKey': '未設定 API Key',
'ai.providers.configure': '設定',
'ai.providers.remove': '移除',
'ai.providers.headers': '自訂 HTTP 請求標頭',
'ai.providers.headers.help': '為此服務新增選用請求標頭。內容會隱藏顯示,並在儲存時加密。',
'ai.providers.headers.name': '請求標頭名稱',
'ai.providers.headers.value': '請求標頭內容',
'ai.providers.headers.add': '新增請求標頭',
'ai.providers.headers.remove': '刪除請求標頭',
'ai.providers.headers.invalid': '請填寫有效且不重複的請求標頭。Content-Length 和 Transfer-Encoding 由應用程式自動設定。',
'ai.providers.headers.loadError': '無法解鎖已儲存的請求標頭。請取消編輯,解鎖系統鑰匙圈後重試。',
'ai.providers.headers.saveError': '無法安全儲存。請確認系統鑰匙圈可用後重試。',
'ai.providers.name': '顯示名稱',
'ai.providers.name.placeholder': '例如 我的供應商',
'ai.providers.style': '協定風格',
@@ -385,8 +394,8 @@ export const zhTWAiMessages: Messages = {
"ai.privacy.cidrs.description": "每行一個 IPv4 或 IPv6 CIDR。留空則僅使用內建規則。",
"ai.privacy.patterns": "自訂正規表示式",
"ai.privacy.patterns.description": "每行一個相容 RE2 的模式,不含 / 分隔符號或旗標。不支援或不安全的模式會遭拒絕。",
"ai.privacy.connectionScope": "預留位置在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用預留位置。",
"ai.privacy.connectionScope": "佔位符在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用佔位符。",
"ai.privacy.apply": "套用",
"ai.privacy.applying": "正在套用...",
"ai.privacy.applied": "AI 隱私設定已套用。請建立新的受管對話並重新連接外部 MCP 用戶端。",
@@ -657,7 +666,7 @@ export const zhTWAiMessages: Messages = {
'ai.chatHistory.messageCap.unit': '則訊息',
// AI Error
'ai.codex.bridgeError': 'Codex 主程序處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發程序,然後重試。',
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
// AI Web Search
'ai.webSearch.title': '網路搜尋',
@@ -710,6 +719,8 @@ export const zhTWAiMessages: Messages = {
// 統一終端工作區和頂部標籤的 tooltip 文案 (issue #954)
'terminal.layer.addTerminal': '新增終端',
'terminal.layer.emptyWorkspace': '工作區中還沒有終端',
'terminal.layer.emptyWorkspaceHint': '新增本機終端或連線至主機,開始使用這個工作區。',
'terminal.layer.switchToSplitView': '切換到分割檢視',
'terminal.layer.sftp': '檔案傳輸',
'terminal.layer.scripts': '指令碼',
+104 -47
View File
@@ -1,6 +1,44 @@
import type { Messages } from '../types';
export const zhTWCoreMessages: Messages = {
"settings.plugins.github.install": "從 GitHub 安裝",
"settings.plugins.github.description": "下載已發布的 .ncpkg 外掛套件,安裝前請審查來源與所需權限。",
"settings.plugins.github.repository": "GitHub 儲存庫",
"settings.plugins.github.formats": "支援 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。",
"settings.plugins.github.busy": "正在下載、驗證或安裝套件…",
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置指令碼,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
"settings.plugins.github.accept": "已審查並信任此儲存庫,且已查看宣告的權限。",
"settings.plugins.github.confirm": "安裝並保持停用",
"settings.plugins.github.download": "下載並審查",
"settings.plugins.github.error.invalidRepository": "請輸入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。請只填寫儲存庫位址,不要包含帳號密碼、查詢參數、片段或額外路徑。",
"settings.plugins.github.error.unavailable": "目前的工作階段無法從 GitHub 安裝外掛。",
"settings.plugins.github.error.reviewFirst": "請先下載並審查 GitHub 外掛。",
"settings.plugins.github.error.network": "無法連線至 GitHub,請檢查網路連線後重試。",
"settings.plugins.github.error.timeout": "從 GitHub 下載逾時,請重試。",
"settings.plugins.github.error.rateLimit": "GitHub API 請求次數已達上限,請稍後重試。",
"settings.plugins.github.error.notFound": "找不到 GitHub 儲存庫或發布附件。僅支援可存取的公開儲存庫;私有外掛套件請從本機匯入。",
"settings.plugins.github.error.accessDenied": "GitHub 拒絕存取。此功能不支援私有儲存庫或登入驗證。",
"settings.plugins.github.error.http": "從 GitHub 下載失敗(HTTP {status}),請稍後重試。",
"settings.plugins.github.error.moved": "此 GitHub 儲存庫已遷移,請輸入目前的儲存庫位址。",
"settings.plugins.github.error.redirect": "無法驗證 GitHub 下載重新導向。請下載可信的 .ncpkg 外掛套件,再從本機匯入。",
"settings.plugins.github.error.noRelease": "此儲存庫尚未發布穩定版本。請作者發布包含 .ncpkg 附件的穩定版本,或從本機匯入已建置的外掛套件。",
"settings.plugins.github.error.noAsset": "此版本沒有 .ncpkg 附件。請作者建置並上傳外掛套件;Netcatty 無法直接建置原始碼儲存庫。",
"settings.plugins.github.error.multipleAssets": "此版本包含多個 .ncpkg 附件。請下載需要的外掛套件,再從本機匯入。",
"settings.plugins.github.error.metadata": "GitHub 發布資訊無效。請作者檢查版本發布、標籤及 .ncpkg 附件。",
"settings.plugins.github.error.identity": "外掛套件與所選 GitHub 儲存庫或發布版本不符,已停止安裝。",
"settings.plugins.github.error.commit": "無法存取發布標籤對應的提交,請作者修復發布標籤。",
"settings.plugins.github.error.size": "GitHub 外掛套件大小無效或超出下載限制。",
"settings.plugins.github.error.integrity": "下載的外掛套件未通過大小或 SHA-256 驗證,請重新下載並審查。",
"settings.plugins.github.error.package": "GitHub 傳回的內容不是有效的 .ncpkg ZIP 外掛套件或發布資訊,請作者檢查發布附件。",
"settings.plugins.github.error.busy": "已有 GitHub 外掛操作正在進行,請關閉預覽後重試。",
"settings.plugins.github.error.expired": "GitHub 外掛套件預覽已失效,請重新下載並審查。",
"settings.plugins.github.error.advanced": "此外掛套件需要進階開發者模式。一般外掛管理僅接受瀏覽器執行環境的套件。",
"settings.plugins.github.error.incompatible": "此外掛與目前的 Netcatty 版本不相容,請聯絡作者確認技術詳細資料。",
"settings.plugins.github.error.source": "此外掛已綁定其他來源。更換來源前,請先解除安裝並明確清除原來源的私有資料。",
"settings.plugins.github.error.failed": "無法驗證或安裝外掛,請查看技術詳細資料後再重試。",
"settings.plugins.github.error.details": "技術詳細資料",
"settings.plugins.landing.checkUpdates": "檢查更新",
"settings.plugins.landing.checkingUpdates": "正在檢查…",
"settings.plugins.landing.updateSummary": "已檢查:{checked} · 已發佈更新:{updates} · 未檢查:{skipped}。",
@@ -79,8 +117,8 @@ export const zhTWCoreMessages: Messages = {
'confirm.deleteIdentity': '刪除身分 "{name}"?',
'confirm.removeProvider': '移除供應商 "{name}"?',
'confirm.closeBusyTerminal.title': '確認關閉',
'confirm.closeBusyTerminal.message': '程序 "{command}" 仍在執行,關閉後會被終止。',
'confirm.closeBusyTerminal.messageWithMore': '程序 "{command}" 及其他 {count} 個正在執行的程序將被終止。',
'confirm.closeBusyTerminal.message': '行程 "{command}" 仍在執行,關閉後會被終止。',
'confirm.closeBusyTerminal.messageWithMore': '行程 "{command}" 及其他 {count} 個正在執行的行程將被終止。',
'confirm.closeBusyTerminal.cancel': '取消',
'confirm.closeBusyTerminal.close': '關閉',
'dialog.createWorkspace.title': '建立工作區',
@@ -258,7 +296,7 @@ export const zhTWCoreMessages: Messages = {
// Settings > System > Crash Logs
'settings.system.crashLogs.title': '崩潰日誌',
'settings.system.crashLogs.description': '檢視主程序錯誤日誌,協助診斷異常行為。',
'settings.system.crashLogs.description': '檢視主行程錯誤日誌,協助診斷異常行為。',
'settings.system.crashLogs.noLogs': '未找到崩潰日誌。',
'settings.system.crashLogs.entries': '{count} 條記錄',
'settings.system.crashLogs.clear': '清除所有日誌',
@@ -1017,7 +1055,26 @@ Vaults 分頁維持扁平,不使用這塊背景。
'sftp.extract.extracting': '正在解壓 {fileName}...',
'sftp.extract.success': '已解壓 {fileName}',
'sftp.extract.error': '解壓 {fileName} 失敗:{error}',
'sftp.archive.action': '壓縮…',
'sftp.archive.title': '壓縮檔案',
'sftp.archive.description': '將 {count} 個選取項目打包成伺服器上的壓縮檔。',
'sftp.archive.name': '壓縮檔名稱',
'sftp.archive.format': '格式',
'sftp.archive.destination': '儲存目錄',
'sftp.archive.create': '壓縮',
'sftp.archive.creating': '正在壓縮…',
'sftp.archive.overwriteTitle': '覆寫現有壓縮檔?',
'sftp.archive.overwriteDescription': '「{name}」已存在。確認後將以新的壓縮檔取代它。',
'sftp.archive.overwrite': '覆寫並壓縮',
'sftp.archive.failed': '壓縮失敗',
'sftp.archive.invalidSelection': '無法壓縮此選取範圍',
'sftp.archive.invalidName': '請輸入有效的檔案名稱,不要包含目錄路徑。',
'sftp.archive.invalidExtension': '副檔名必須與所選格式一致。',
'sftp.archive.connectionChanged': '連線已切換,請重新選取檔案。',
'sftp.archive.unavailable': '目前連線不支援建立壓縮檔。',
'sftp.archive.success': '已建立 {fileName}',
'sftp.context.copyToOtherPane': '複製到另一側',
'sftp.context.duplicate': '建立副本',
'sftp.copyToOtherPane.unavailable': '請開啟雙欄 SFTP 檔案管理,並連線目標側後再複製檔案。',
'sftp.copyCurrentPath': '複製目前路徑',
'sftp.copyCurrentPath.success': '已複製目前路徑',
@@ -1188,16 +1245,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
'settings.tab.plugins': '外掛程式',
"settings.plugins.author.official": "官方維護",
"settings.plugins.author.officialMeaning": "由 Netcatty 專案維護。這不是安全認證。",
"settings.plugins.manager.installed": "已安裝插件",
"settings.plugins.manager.import": "導入 .ncpkg",
"settings.plugins.manager.preview": "導入的插件保持停用,請檢查後再啟用。",
"settings.plugins.manager.empty": "導入本地插件包以開始使用。",
"settings.plugins.manager.installed": "已安裝外掛",
"settings.plugins.manager.import": "匯入 .ncpkg",
"settings.plugins.manager.preview": "匯入的外掛保持停用,請檢查後再啟用。",
"settings.plugins.manager.empty": "匯入本地外掛包以開始使用。",
"settings.plugins.manager.enabled": "已啟用",
"settings.plugins.manager.disabled": "已停用",
"settings.plugins.manager.enable": "啟用",
"settings.plugins.manager.disable": "停用",
"settings.plugins.manager.remove": "卸載",
"settings.plugins.manager.removeNote": "卸載會移除插件代碼和本地 KV 數據,保留用戶設置、秘密存儲和同步 sidecar。",
"settings.plugins.manager.remove": "解除安裝",
"settings.plugins.manager.removeNote": "解除安裝會移除外掛代碼和本地 KV 資料,保留使用者設定、秘密儲存和同步 sidecar。",
"settings.plugins.permissions.statusUnknown": "狀態不明",
"plugins.sidebar.extensions": "擴充功能頁面",
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
@@ -1258,44 +1315,44 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.themes.invalid": "部分主題配色未通過驗證或無法使用。",
"settings.plugins.themes.failed": "無法套用主題。",
"settings.plugins.manager.dataTheme": "主題套件:已驗證配色,不啟動程式執行環境。",
"settings.plugins.manager.browser": "瀏覽器運行時:特權訪問通過宿主權限代理。",
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 文件系統和網絡能力,代理權限無法限制這些訪問。僅供開發預覽。",
"settings.plugins.manager.data": "本地 KV 僅保留在此設備。只有明確標記為同步的非秘密設置進入加密雲 sidecar。插件包和權限授權不參與同步。",
"settings.plugins.manager.browser": "瀏覽器運行時:特權存取通過宿主權限代理。",
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 檔案系統和網路能力,代理權限無法限制這些存取。僅供開發預覽。",
"settings.plugins.manager.data": "本地 KV 僅保留在此裝置。只有明確標記為同步的非秘密設置進入加密雲 sidecar。外掛包和權限授權不參與同步。",
"settings.plugins.manager.unbounded": "未宣告更細的資源範圍,仍受應用程式驗證和所選權限模式約束。",
"settings.plugins.openView": "開啟",
"settings.plugins.openManager": "開啟插件管理",
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
"settings.plugins.sources.clearPrivate": "同时清除本来源的私有数据、授权和秘密,以便显式换源重装。此操作不可撤销。",
"settings.plugins.openManager": "開啟外掛管理",
"settings.plugins.sources.conflict": "此 ID 已從其他來源安裝。請先解除安裝並明確清理舊來源資料,再換源重新安裝。原來源:",
"settings.plugins.sources.clearPrivate": "同時清除本來源的私有資料、授權和秘密,以便明確換源重新安裝。此操作無法復原。",
"settings.plugins.sources.short.official": "官方",
"settings.plugins.sources.short.thirdparty": "第三方",
"settings.plugins.sources.short.local": "本機",
"settings.plugins.sources.official": "官方市场",
"settings.plugins.sources.thirdparty": "第三方市场",
"settings.plugins.sources.manage": "管理来源",
"settings.plugins.sources.select": "选择来源",
"settings.plugins.sources.empty": "选择或添加第三方来源。",
"settings.plugins.sources.add": "添加来源",
"settings.plugins.sources.remove": "移除来源",
"settings.plugins.sources.name": "来源名称",
"settings.plugins.sources.address": "HTTPS 来源地址",
"settings.plugins.sources.risk": "第三方来源不代表 Netcatty 维护或认可。安装前请核对真实域名、插件权限与作者。",
"settings.plugins.sources.accept": "我信任此域名提供插件目录和软件包。此操作不会授予插件权限。",
"settings.plugins.sources.removeNote": "保留已安装插件及数据,停止此来源更新,不会自动切换到其他来源。",
"settings.plugins.sources.disablePlugins": "同时停用来自该来源的插件",
"settings.plugins.sources.installConfirm": "确认第三方安装",
"settings.plugins.sources.source": "来源",
"settings.plugins.sources.local": "本地导入",
"settings.plugins.sources.all": "全部来源",
"settings.plugins.title": "插件",
"settings.plugins.configuration": "插件設定",
"settings.plugins.description": "管理已安裝插件,瀏覽精選目錄。",
"settings.plugins.sources.official": "官方市集",
"settings.plugins.sources.thirdparty": "第三方市集",
"settings.plugins.sources.manage": "管理來源",
"settings.plugins.sources.select": "選擇來源",
"settings.plugins.sources.empty": "選擇或新增第三方來源。",
"settings.plugins.sources.add": "新增來源",
"settings.plugins.sources.remove": "移除來源",
"settings.plugins.sources.name": "來源名稱",
"settings.plugins.sources.address": "HTTPS 來源位址",
"settings.plugins.sources.risk": "第三方來源不代表 Netcatty 維護或認可。安裝前請核對真實網域、外掛權限與作者。",
"settings.plugins.sources.accept": "我信任此網域提供外掛目錄和套件。此操作不會授予外掛權限。",
"settings.plugins.sources.removeNote": "保留已安裝外掛及資料,停止此來源更新,不會自動切換到其他來源。",
"settings.plugins.sources.disablePlugins": "同時停用來自該來源的外掛",
"settings.plugins.sources.installConfirm": "確認第三方安裝",
"settings.plugins.sources.source": "來源",
"settings.plugins.sources.local": "本機匯入",
"settings.plugins.sources.all": "全部來源",
"settings.plugins.title": "外掛",
"settings.plugins.configuration": "外掛設定",
"settings.plugins.description": "管理已安裝外掛,瀏覽精選目錄。",
'settings.plugins.loading': '正在載入外掛程式設定…',
"settings.plugins.market.results": "{count} 個插件",
"settings.plugins.market.results": "{count} 個外掛",
"settings.plugins.manager.lastError": "上次記錄的錯誤",
"settings.plugins.sources.offline": "來源暫不可用。如已快取此來源通過驗證的目錄,僅可繼續瀏覽;重新整理成功前無法安裝。",
"settings.plugins.sources.note": "此目錄由所選第三方提供,不屬於 Netcatty 精選目錄。安裝前請核對來源網域和權限,更新需手動確認。",
"settings.plugins.sources.sourceOnly": "此提供方僅提供原始碼項目,沒有可下載外掛套件;請查看作者的建置和匯入說明。",
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市場安裝。",
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市集安裝。",
"settings.plugins.manager.details": "查看詳情",
"settings.plugins.manager.noDescription": "作者尚未提供功能簡介。",
"settings.plugins.status": "{count} 項提醒",
@@ -1305,22 +1362,22 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.market.readmeInfo": "README 來源說明",
"settings.plugins.market.installed": "已安裝",
"settings.plugins.market.sourceBadge": "原始碼範例",
"settings.plugins.market.title": "插件市場",
"settings.plugins.market.note": "精選開源插件。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有插件",
"settings.plugins.market.title": "外掛市集",
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有外掛",
"settings.plugins.market.install": "安裝此版本(保持停用)",
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並導入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠程圖片不加載。內容由插件作者提供。",
"settings.plugins.manager.noVault": "系統密鑰存儲不可用。秘密和憑據操作被阻止;瀏覽市場和不使用秘密的插件仍可使用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
"settings.plugins.manager.noVault": "系統金鑰儲存不可用。秘密和憑據操作被阻止;瀏覽市集和不使用秘密的外掛仍可使用。",
"settings.plugins.manager.sensitive": "敏感存取:此能力可能涉及私密資料,可在權限設定中調整其模式。",
"settings.plugins.manager.dual": "默認使用瀏覽器運行時,但包中還包含擁有完整設備權限的 Node 入口;僅限開發者模式。",
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器插件模式;請逐項檢查聲明權限。",
"settings.plugins.manager.dual": "預設使用瀏覽器運行時,但包中還包含擁有完整裝置權限的 Node 入口;僅限開發者模式。",
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器外掛模式;請逐項檢查聲明權限。",
"settings.plugins.market.retry": "重試",
"settings.plugins.market.empty": "目錄暫無插件,仍可導入本地瀏覽器插件。",
"settings.plugins.market.empty": "目錄暫無外掛,仍可匯入本地瀏覽器外掛。",
"settings.plugins.market.emptyReadme": "README 內容為空。",
"settings.plugins.market.search": "搜索名稱、作者或描述",
"settings.plugins.market.noResults": "沒有匹配插件,請嘗試其他關鍵詞。",
"settings.plugins.market.noResults": "沒有匹配外掛,請嘗試其他關鍵詞。",
"settings.plugins.market.manifest": "兼容性與權限",
'settings.plugins.empty': '目前沒有已啟用外掛程式提供設定。',
'settings.plugins.scopeContext': '請在對應的 {scope} 情境中開啟此設定。',
+18 -18
View File
@@ -4,10 +4,10 @@ export const zhTwSystemManagerMessages: Messages = {
'terminal.layer.system': '系統',
'systemManager.noSession': '沒有使用中的終端工作階段。',
'systemManager.notConnected': '請先連線到主機以管理程序與服務。',
'systemManager.notConnected': '請先連線到主機以管理行程與服務。',
'systemManager.empty': '暫無資料。',
'systemManager.tabs.overview': '概覽',
'systemManager.tabs.processes': '程序',
'systemManager.tabs.processes': '行程',
'systemManager.tabs.ports': '連接埠',
'systemManager.tabs.services': '服務',
'systemManager.tabs.tmux': 'tmux',
@@ -17,7 +17,7 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.popup.loading': '正在開啟終端…',
'systemManager.popup.startupFailed': '啟動指令未順利完成。請確認目標仍可使用後再試一次。',
'systemManager.errors.loadProcesses': '載入程序列表失敗',
'systemManager.errors.loadProcesses': '載入行程列表失敗',
'systemManager.errors.loadTmux': '載入 tmux 工作階段失敗',
'systemManager.errors.loadTmuxWindows': '載入 tmux 視窗失敗',
'systemManager.errors.loadTmuxPanes': '載入 tmux 窗格失敗',
@@ -58,13 +58,13 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.overview.cpuCores': 'CPU 核心',
'systemManager.overview.disks': '磁碟',
'systemManager.overview.interfaces': '網路介面',
'systemManager.overview.topProcesses': '記憶體佔用最高程序',
'systemManager.overview.topProcesses': '記憶體佔用最高行程',
'systemManager.overview.noData': '暫無資料',
'systemManager.overview.noDisks': '暫無磁碟資料',
'systemManager.overview.noInterfaces': '暫無網路卡資料',
'systemManager.overview.noTopProcesses': '暫無程序資料',
'systemManager.overview.noTopProcesses': '暫無行程資料',
'systemManager.processes.search': '搜尋程序…',
'systemManager.processes.search': '搜尋行程…',
'systemManager.processes.command': '指令',
'systemManager.processes.user': '使用者',
'systemManager.processes.term': '終止',
@@ -75,18 +75,18 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.processes.renice': '調整優先順序',
'systemManager.processes.renicePrompt': 'Nice 值 (-20 到 19)',
'systemManager.processes.reniceInvalid': 'Nice 值必須在 -20 到 19 之間',
'systemManager.processes.confirmKill': '向程序 {{pid}} 傳送 SIGKILL?',
'systemManager.processes.confirmSignal': '向程序 {{pid}} 傳送 SIG{{signal}}?',
'systemManager.processes.confirmKill': '向行程 {{pid}} 傳送 SIGKILL?',
'systemManager.processes.confirmSignal': '向行程 {{pid}} 傳送 SIG{{signal}}?',
'systemManager.processes.filter.all': '全部',
'systemManager.processes.filter.running': '執行中',
'systemManager.processes.ppid': '父程序 PID',
'systemManager.processes.ppid': '父行程 PID',
'systemManager.processes.rss': '實體記憶體',
'systemManager.processes.vsz': '虛擬記憶體',
'systemManager.processes.elapsed': '執行時長',
'systemManager.processes.stat': '狀態',
'systemManager.processes.meta': '{{count}} 個程序',
'systemManager.processes.loading': '正在載入程序…',
'systemManager.processes.loadingMore': '正在載入更多程序…',
'systemManager.processes.meta': '{{count}} 個行程',
'systemManager.processes.loading': '正在載入行程…',
'systemManager.processes.loadingMore': '正在載入更多行程…',
'systemManager.processes.state.running': '執行中',
'systemManager.processes.state.sleeping': '睡眠',
'systemManager.processes.state.stopped': '已暫停',
@@ -236,9 +236,9 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.ports.search': '搜尋連接埠…',
'systemManager.ports.meta': '{{count}} 個監聽',
'systemManager.ports.filter.all': '全部',
'systemManager.ports.unknownProcess': '未知程序',
'systemManager.ports.terminate': '結束程序',
'systemManager.ports.confirmTerminate': '向佔用該連接埠的程序 {{pid}} 傳送 SIGTERM?',
'systemManager.ports.unknownProcess': '未知行程',
'systemManager.ports.terminate': '結束行程',
'systemManager.ports.confirmTerminate': '向佔用該連接埠的行程 {{pid}} 傳送 SIGTERM?',
'systemManager.services.unavailable': '此主機未偵測到 systemctl。',
'systemManager.services.loading': '正在載入 systemd 服務…',
@@ -261,10 +261,10 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.gpu.unavailable': '此主機未偵測到 NVIDIA GPU 或昇騰 NPU 工具。',
'systemManager.gpu.loading': '正在載入加速卡狀態…',
'systemManager.gpu.empty': '已偵測到加速卡工具,但未回傳裝置資訊。',
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個程序',
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個行程',
'systemManager.gpu.devices': '裝置',
'systemManager.gpu.processes': '計算程序',
'systemManager.gpu.noProcesses': '目前沒有計算程序。',
'systemManager.gpu.processes': '計算行程',
'systemManager.gpu.noProcesses': '目前沒有計算行程。',
'systemManager.gpu.vendor.nvidia': 'NVIDIA',
'systemManager.gpu.vendor.ascend': '昇騰',
'systemManager.gpu.util': '使用率',
+3 -3
View File
@@ -510,8 +510,8 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.serverStats.refreshInterval.desc': '伺服器狀態重新整理的頻率。',
'settings.terminal.serverStats.seconds': '秒',
'settings.terminal.section.systemManager': '系統管理',
'settings.terminal.systemManager.processRefreshInterval': '程序列表重新整理間隔',
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中程序列表的重新整理頻率。',
'settings.terminal.systemManager.processRefreshInterval': '行程列表重新整理間隔',
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中行程列表的重新整理頻率。',
'settings.terminal.systemManager.tmuxRefreshInterval': 'tmux 工作階段重新整理間隔',
'settings.terminal.systemManager.tmuxRefreshInterval.desc': 'tmux 工作階段列表的重新整理頻率。',
'settings.terminal.systemManager.dockerListRefreshInterval': '容器列表重新整理間隔',
@@ -969,7 +969,7 @@ export const zhTWTerminalMessages: Messages = {
'snippets.variables.placeholderDefault': '預設:{value}',
'snippets.variables.required': '請填寫此變數',
'snippets.variables.run': '執行',
'snippets.field.variablesHelp': '在指令碼中使用 {{名稱}} 或 {{名稱:預設值}} 定義變數。',
'snippets.field.variablesHelp': '在指令碼中使用 {{name}} 或 {{name:default}} 作為佔位符。',
'snippets.field.variablesDetected': '變數',
'snippets.field.variableDefault': '預設 {value}',
+1 -1
View File
@@ -580,7 +580,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.serverStats.swapUsed': '已用交換',
'terminal.serverStats.swapFree': '空閒交換',
'terminal.serverStats.swapTotal': '總計',
'terminal.serverStats.topProcesses': '記憶體佔用前十程序',
'terminal.serverStats.topProcesses': '記憶體佔用前十行程',
'terminal.serverStats.disk': '磁碟使用',
'terminal.serverStats.diskDetails': '已掛載磁碟',
'terminal.serverStats.network': '網路速度',
+1 -1
View File
@@ -165,7 +165,7 @@ function isSuccessfulApplyResult(result: unknown): boolean {
* the DB before collection. Ordinary last-known collect snapshots are never
* re-applied, so local settings edits made after the last collect are kept.
*/
export async function collectPluginSyncSidecarsFromHost(options?: {
export async function collectPluginSyncSidecarsFromHost(options: {
/**
* When true, never fall back to last-known cache. Returns null if the host is
* gated off / non-authoritative so callers can omit `pluginSidecars` instead
@@ -75,6 +75,95 @@ test('resolves the focused workspace session for global keybindings', () => {
});
});
test('uses the anchor chat owner when focus is missing (#4098 phase 2)', () => {
const splitWorkspace: Workspace = {
id: 'workspace-1',
title: 'Workspace',
anchorChatId: 'chat-2',
root: {
id: 'split-1',
type: 'split',
direction: 'vertical',
children: [
{ id: 'pane-1', type: 'pane', sessionId: 'session-1' },
{ id: 'pane-2', type: 'pane', sessionId: 'session-3' },
],
sizes: [1, 1],
},
};
const chatOwnerSessions: TerminalSession[] = [
...sessions,
{
id: 'session-3',
hostId: 'host-3',
hostLabel: 'Host 3',
username: 'root',
hostname: 'example.org',
status: 'connected',
protocol: 'ssh',
workspaceId: 'workspace-1',
},
];
assert.equal(
resolveActivePluginKeybindingContext({
activeTabId: 'workspace-1',
sessions: chatOwnerSessions,
workspaces: [splitWorkspace],
aiSessions: [
{ id: 'chat-2', scope: { type: 'terminal', targetId: 'session-3' }, updatedAt: 2 },
{ id: 'chat-1', scope: { type: 'terminal', targetId: 'session-1' }, updatedAt: 1 },
],
})['terminal.sessionId'],
// anchorChatId's chat is terminal-scoped to session-3, which wins even
// though session-1's chat is older and session-1 is the first member.
'session-3',
);
});
test('falls back to the most-recently-active member when there is no anchor (#4098 phase 2)', () => {
const splitWorkspace: Workspace = {
id: 'workspace-1',
title: 'Workspace',
root: {
id: 'split-1',
type: 'split',
direction: 'vertical',
children: [
{ id: 'pane-1', type: 'pane', sessionId: 'session-1' },
{ id: 'pane-2', type: 'pane', sessionId: 'session-3' },
],
sizes: [1, 1],
},
};
const chatOwnerSessions: TerminalSession[] = [
...sessions,
{
id: 'session-3',
hostId: 'host-3',
hostLabel: 'Host 3',
username: 'root',
hostname: 'example.org',
status: 'connected',
protocol: 'ssh',
workspaceId: 'workspace-1',
},
];
assert.equal(
resolveActivePluginKeybindingContext({
activeTabId: 'workspace-1',
sessions: chatOwnerSessions,
workspaces: [splitWorkspace],
aiSessions: [
{ id: 'chat-1', scope: { type: 'terminal', targetId: 'session-1' }, updatedAt: 1 },
{ id: 'chat-2', scope: { type: 'terminal', targetId: 'session-3' }, updatedAt: 9 },
],
})['terminal.sessionId'],
'session-3',
);
});
test('resolves standalone sessions and fails closed for non-terminal tabs', () => {
assert.equal(
resolveActivePluginKeybindingContext({ activeTabId: 'session-2', sessions, workspaces })['terminal.sessionId'],
@@ -89,3 +178,18 @@ test('resolves standalone sessions and fails closed for non-terminal tabs', () =
'netcatty.activeTabId': 'vault',
});
});
test('empty workspace does not target the detached owner of its anchored chat', () => {
const context = resolveActivePluginKeybindingContext({
activeTabId: 'workspace-1',
sessions: sessions.map((session) => ({ ...session, workspaceId: undefined })),
workspaces: [{ ...workspaces[0], focusedSessionId: undefined, anchorChatId: 'chat-1', root: {
id: 'empty', type: 'split', direction: 'vertical', children: [], sizes: [],
} }],
aiSessions: [{ id: 'chat-1', scope: { type: 'terminal', targetId: 'session-1' }, updatedAt: 1 }],
});
assert.equal(context['terminal.sessionId'], undefined);
assert.equal(context['host.id'], undefined);
assert.equal(context['workspace.id'], 'workspace-1');
});
@@ -1,4 +1,6 @@
import { collectSessionIds } from '../../domain/workspace';
import { resolveMostRecentlyActiveMemberTerminalId } from '../../domain/aiSessionRecency';
import type { AIChatRecencyEntry } from '../../domain/aiSessionRecency';
import type { TerminalSession, Workspace } from '../../types';
export type PluginContributionContextValue = string | boolean | number | null;
@@ -44,14 +46,17 @@ export function resolveActivePluginKeybindingContext({
activeTabId,
sessions,
workspaces,
aiSessions,
}: {
activeTabId: string;
sessions: readonly TerminalSession[];
workspaces: readonly Workspace[];
/** AI chat snapshot: resolves the workspace anchor and recency fallback (#4098 phase 2). */
aiSessions?: readonly AIChatRecencyEntry[];
}): PluginContributionContext {
const workspace = workspaces.find((candidate) => candidate.id === activeTabId);
const activeSessionId = workspace
? (workspace.focusedSessionId ?? collectSessionIds(workspace.root)[0])
? resolveWorkspaceActiveTerminalId(workspace, aiSessions)
: sessions.some((candidate) => candidate.id === activeTabId)
? activeTabId
: undefined;
@@ -72,3 +77,32 @@ export function resolveActivePluginKeybindingContext({
'netcatty.activeTabId': activeTabId,
};
}
/**
* Issue #4098 phase 2: the keybinding context's workspace session resolves by
* id, never positionally — focused member first, then the terminal member that
* owns the anchored chat, then the most-recently-active member by chat recency.
*/
function resolveWorkspaceActiveTerminalId(
workspace: Workspace,
aiSessions: readonly AIChatRecencyEntry[] | undefined,
): string | undefined {
if (workspace.focusedSessionId && collectSessionIds(workspace.root).includes(workspace.focusedSessionId)) {
return workspace.focusedSessionId;
}
const memberTerminalIds = collectSessionIds(workspace.root);
if (memberTerminalIds.length === 1) {
// A single-member workspace has exactly one candidate — not a positional
// pick among many.
return memberTerminalIds[0];
}
const anchorChat = workspace.anchorChatId
? aiSessions?.find((session) => session.id === workspace.anchorChatId && session.scope?.type === 'terminal')
: undefined;
const anchorOwner = anchorChat?.scope.targetId;
return (anchorOwner && memberTerminalIds.includes(anchorOwner) ? anchorOwner : undefined)
?? resolveMostRecentlyActiveMemberTerminalId({ memberTerminalIds, aiSessions })
?? undefined;
}
@@ -45,6 +45,7 @@ export type SessionSnapshotActions = Pick<
| 'resetWorkspaceRename'
| 'removeSessionFromWorkspace'
| 'setWorkspaceFocusedSession'
| 'setWorkspaceAnchorChat'
| 'toggleWorkspaceViewMode'
// Terminal / chrome mutators previously read only via App session runtime.
| 'createLocalTerminal'
@@ -56,6 +57,7 @@ export type SessionSnapshotActions = Pick<
| 'createWorkspaceWithHosts'
| 'createWorkspaceFromSessions'
| 'addSessionToWorkspace'
| 'moveWorkspacePane'
| 'appendHostToWorkspace'
| 'appendHostToWorkspaceConfirmed'
| 'appendLocalTerminalToWorkspace'
+96 -121
View File
@@ -1,12 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { TerminalSession, Workspace } from "../../domain/models";
import type { AIChatRecencyEntry } from "../../domain/aiSessionRecency";
import {
applyCloseSessionToSessions,
closeSessionsState,
closeSessionWorkspaceLayoutState,
detachSessionFromWorkspaceState,
replaceDissolvedWorkspaceTabOrder,
resolveActiveTabAfterCloseSession,
} from "./sessionWorkspaceDetach";
@@ -14,11 +14,19 @@ const session = (id: string, workspaceId = "ws-1"): TerminalSession => ({
id,
hostId: id,
hostLabel: id,
username: "user",
hostname: id,
status: "connected",
workspaceId,
});
const workspace = (sessionIds: string[]): Workspace => ({
const chat = (id: string, targetId: string, updatedAt: number): AIChatRecencyEntry => ({
id,
scope: { type: "terminal", targetId },
updatedAt,
});
const workspace = (sessionIds: string[], overrides: Partial<Workspace> = {}): Workspace => ({
id: "ws-1",
title: "Workspace",
focusedSessionId: sessionIds[0],
@@ -36,9 +44,17 @@ const workspace = (sessionIds: string[]): Workspace => ({
})),
sizes: sessionIds.map(() => 1),
},
...overrides,
});
test("detach dissolves the original workspace when one session remains", () => {
const rootPaneSessionIds = (workspace: Workspace): string[] => (
workspace.root.type === "pane"
? [workspace.root.sessionId]
: workspace.root.children.map((child) => child.type === "pane" ? child.sessionId : "")
.filter((id): id is string => Boolean(id))
);
test("detaching to one member keeps the workspace alive (#4098 phase 2)", () => {
const result = detachSessionFromWorkspaceState({
sessions: [session("s1"), session("s2")],
workspaces: [workspace(["s1", "s2"])],
@@ -49,149 +65,126 @@ test("detach dissolves the original workspace when one session remains", () => {
assert.equal(result.activeTabId, "s1");
assert.deepEqual(result.sessions.map((s) => [s.id, s.workspaceId]), [
["s1", undefined],
["s2", undefined],
// The survivor keeps its workspace binding — no orphan promotion.
["s2", "ws-1"],
]);
assert.equal(result.workspaces.length, 0);
assert.equal(result.dissolvedWorkspaceId, "ws-1");
assert.deepEqual(result.replacementTabIds, ["s1", "s2"]);
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].id, "ws-1");
assert.deepEqual(rootPaneSessionIds(result.workspaces[0]), ["s2"]);
});
test("detach preserves the other sessions in a multi-pane workspace", () => {
test("detaching the last member keeps the workspace with an empty root (#4098 phase 2)", () => {
const result = detachSessionFromWorkspaceState({
sessions: [session("s1"), session("s2"), session("s3")],
workspaces: [workspace(["s1", "s2", "s3"])],
sessionId: "s2",
sessions: [session("s1")],
workspaces: [workspace(["s1"])],
sessionId: "s1",
});
assert.equal(result.changed, true);
assert.deepEqual(result.sessions.map((s) => [s.id, s.workspaceId]), [
["s1", "ws-1"],
["s2", undefined],
["s3", "ws-1"],
]);
assert.deepEqual(result.workspaces[0].focusSessionOrder, ["s1", "s3"]);
assert.equal(result.workspaces[0].focusedSessionId, "s1");
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].id, "ws-1");
assert.equal(result.workspaces[0].root.type, "split");
assert.deepEqual(
result.workspaces[0].root.type === "split"
? result.workspaces[0].root.children.map((child) => child.type === "pane" ? child.sessionId : null)
: [],
["s1", "s3"],
result.workspaces[0].root.type === "split" ? result.workspaces[0].root.children : null,
[],
);
assert.equal(result.workspaces[0].focusedSessionId, undefined);
});
test("dissolved workspace replacement preserves its tab position", () => {
assert.deepEqual(
replaceDissolvedWorkspaceTabOrder(["log-1", "ws-1", "session-3"], "ws-1", ["s1", "s2"]),
["log-1", "s1", "s2", "session-3"],
);
test("closing one member keeps the workspace and its surviving member bound (#4098 phase 2)", () => {
const result = closeSessionsState({
sessions: [session("s1"), session("s2")],
workspaces: [workspace(["s1", "s2"])],
sessionIds: ["s1"],
currentActiveTabId: "ws-1",
tabOrder: ["ws-1"],
});
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].id, "ws-1");
assert.deepEqual(result.sessions.map((s) => [s.id, s.workspaceId]), [["s2", "ws-1"]]);
// The workspace tab is still live, so the active tab does not move.
assert.equal(result.activeTabId, undefined);
});
test("dissolved workspace replacement removes duplicate replacement ids", () => {
assert.deepEqual(
replaceDissolvedWorkspaceTabOrder(["s1", "ws-1", "session-3"], "ws-1", ["s1", "s2"]),
["s1", "s2", "session-3"],
);
});
test("dissolved workspace replacement is idempotent", () => {
const once = replaceDissolvedWorkspaceTabOrder(["log-1", "ws-1", "session-3"], "ws-1", ["s1", "s2"]);
assert.deepEqual(
replaceDissolvedWorkspaceTabOrder(once, "ws-1", ["s1", "s2"]),
once,
);
});
test("single remaining session preserves dissolved workspace tab position", () => {
assert.deepEqual(
replaceDissolvedWorkspaceTabOrder(["log-1", "ws-1", "session-3"], "ws-1", ["s2"]),
["log-1", "s2", "session-3"],
);
});
test("closing a workspace session dissolves the workspace when one terminal remains", () => {
const result = closeSessionWorkspaceLayoutState([workspace(["s1", "s2"])], "ws-1", "s1");
assert.equal(result.dissolvedWorkspaceId, "ws-1");
assert.equal(result.lastRemainingSessionId, "s2");
assert.deepEqual(result.workspaces, []);
assert.deepEqual(
replaceDissolvedWorkspaceTabOrder(
["log-1", result.dissolvedWorkspaceId!, "session-3"],
result.dissolvedWorkspaceId,
result.lastRemainingSessionId ? [result.lastRemainingSessionId] : undefined,
),
["log-1", "s2", "session-3"],
);
});
test("closing the focused session hands focus to a remaining session (#3046)", () => {
test("member loss hands focus to the most-recently-active survivor, not sessions[0]", () => {
const result = closeSessionWorkspaceLayoutState(
[workspace(["s1", "s2", "s3", "s4"])],
[workspace(["s1", "s2", "s3"])],
"ws-1",
"s1",
[chat("chat-s2", "s2", 4), chat("chat-s3", "s3", 9)],
);
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].focusedSessionId, "s2");
assert.deepEqual(result.workspaces[0].focusSessionOrder, ["s2", "s3", "s4"]);
// remainingSessionIds[0] is s2, but s3's chat is the most recent.
assert.equal(result.workspaces[0].focusedSessionId, "s3");
});
test("closing a non-focused session keeps the focused session", () => {
test("reordering focus order does not change the survivor retarget", () => {
const result = closeSessionWorkspaceLayoutState(
[workspace(["s1", "s2", "s3", "s4"])],
[workspace(["s1", "s2", "s3"], { focusSessionOrder: ["s3", "s2", "s1"] })],
"ws-1",
"s1",
[chat("chat-s2", "s2", 4), chat("chat-s3", "s3", 9)],
);
assert.equal(result.workspaces[0].focusedSessionId, "s3");
});
test("closing a non-focused member keeps the focused member", () => {
const result = closeSessionWorkspaceLayoutState(
[workspace(["s1", "s2", "s3"])],
"ws-1",
"s3",
);
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].focusedSessionId, "s1");
assert.deepEqual(result.workspaces[0].focusSessionOrder, ["s1", "s2", "s4"]);
assert.deepEqual(result.workspaces[0].focusSessionOrder, ["s1", "s2"]);
});
test("closing one split pane keeps the other terminal as an orphan tab", () => {
const layoutResult = closeSessionWorkspaceLayoutState(
test("with no AI recency signal focus stays on a surviving terminal", () => {
const result = closeSessionWorkspaceLayoutState(
[workspace(["s1", "s2"])],
"ws-1",
"s1",
);
const nextSessions = applyCloseSessionToSessions(
[session("s1"), session("s2")],
"s1",
layoutResult,
);
assert.deepEqual(nextSessions.map((s) => [s.id, s.workspaceId]), [
["s2", undefined],
]);
assert.equal(
resolveActiveTabAfterCloseSession({
currentActiveTabId: "ws-1",
closedSessionId: "s1",
workspaceId: "ws-1",
layoutResult,
remainingSessions: nextSessions,
preferredTabId: "s-outside",
}),
"s2",
);
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].focusedSessionId, "s2");
});
test("closing the last workspace session does not invent a surviving terminal", () => {
test("closing ALL members keeps the workspace alive with an empty root (#4098 phase 2)", () => {
const result = closeSessionsState({
sessions: [session("s1"), session("s2")],
workspaces: [workspace(["s1", "s2"])],
sessionIds: ["s1", "s2"],
currentActiveTabId: "ws-1",
tabOrder: ["ws-1"],
});
assert.deepEqual(result.sessions, []);
assert.equal(result.workspaces.length, 1);
assert.equal(result.workspaces[0].id, "ws-1");
assert.equal(result.workspaces[0].root.type, "split");
assert.deepEqual(
result.workspaces[0].root.type === "split" ? result.workspaces[0].root.children : null,
[],
);
// The workspace tab survives, so the active tab is left alone.
assert.equal(result.activeTabId, undefined);
});
test("closing a solo workspace member still replaces the closed tab's activity via fallbacks", () => {
const layoutResult = closeSessionWorkspaceLayoutState(
[workspace(["s1"])],
"ws-1",
"s1",
);
const nextSessions = applyCloseSessionToSessions(
[session("s1")],
"s1",
layoutResult,
);
const nextSessions = applyCloseSessionToSessions([session("s1")], "s1");
assert.deepEqual(nextSessions, []);
assert.equal(layoutResult.removedWorkspaceId, "ws-1");
assert.equal(layoutResult.lastRemainingSessionId, undefined);
// The workspace tab survives, so an active workspace tab needs no fallback.
assert.equal(
resolveActiveTabAfterCloseSession({
currentActiveTabId: "ws-1",
@@ -200,25 +193,7 @@ test("closing the last workspace session does not invent a surviving terminal",
layoutResult,
remainingSessions: nextSessions,
}),
"vault",
);
});
test("closing the last visible solo tab does not fall back to a hidden MCP session", () => {
const visibleSession: TerminalSession = { ...session("s1", undefined) };
const hiddenSession: TerminalSession = { ...session("s2", undefined), hiddenFromTabs: true };
const layoutResult = closeSessionWorkspaceLayoutState([], undefined, "s1");
const remainingSessions = [hiddenSession];
assert.equal(
resolveActiveTabAfterCloseSession({
currentActiveTabId: visibleSession.id,
closedSessionId: "s1",
workspaceId: undefined,
layoutResult,
remainingSessions,
}),
"vault",
null,
);
});
+74 -126
View File
@@ -1,20 +1,17 @@
import type { TerminalSession, Workspace } from "../../domain/models";
import { collectSessionIds, pruneWorkspaceNode } from "../../domain/workspace";
import type { AIChatRecencyEntry } from "../../domain/aiSessionRecency";
import { resolveMostRecentlyActiveMemberTerminalId } from "../../domain/aiSessionRecency";
import { collectSessionIds, createEmptyWorkspaceRoot, pruneWorkspaceNode } from "../../domain/workspace";
export type DetachSessionFromWorkspaceStateResult = {
changed: boolean;
sessions: TerminalSession[];
workspaces: Workspace[];
activeTabId?: string;
dissolvedWorkspaceId?: string;
replacementTabIds?: string[];
};
export type CloseSessionWorkspaceLayoutResult = {
workspaces: Workspace[];
removedWorkspaceId?: string;
dissolvedWorkspaceId?: string;
lastRemainingSessionId?: string;
};
export type CloseSessionsStateResult = {
@@ -28,82 +25,65 @@ type DetachSessionFromWorkspaceStateOptions = {
sessions: TerminalSession[];
workspaces: Workspace[];
sessionId: string;
/**
* AI chat store snapshot used to rank surviving members by chat recency.
* Without a recency signal, terminal display still needs a live member.
*/
aiSessions?: readonly AIChatRecencyEntry[];
};
export function replaceDissolvedWorkspaceTabOrder(
tabOrder: readonly string[],
workspaceId: string | undefined,
replacementTabIds: readonly string[] | undefined,
): string[] {
if (!workspaceId || !replacementTabIds?.length) return [...tabOrder];
const uniqueReplacementIds = replacementTabIds.filter((tabId, index, list) => (
tabId && list.indexOf(tabId) === index
));
if (uniqueReplacementIds.length === 0) return [...tabOrder];
if (!tabOrder.includes(workspaceId)) {
const hasAllReplacementIds = uniqueReplacementIds.every((tabId) => tabOrder.includes(tabId));
return hasAllReplacementIds ? [...tabOrder] : [
...tabOrder,
...uniqueReplacementIds.filter((tabId) => !tabOrder.includes(tabId)),
];
/**
* Resolve the member that should receive focus (or an anchor retarget) after a
* member loss. Prefers the AI-chat recency winner; falls back to the still-
* valid preferred (focused) member because that is explicit user intent, and
* falls back to a surviving pane so focus mode never hides all terminals.
*/
const resolveSurvivingFocusMemberId = (
remainingSessionIds: readonly string[],
previousFocusedSessionId: string | undefined,
aiSessions: readonly AIChatRecencyEntry[] | undefined,
): string | undefined => {
if (previousFocusedSessionId && remainingSessionIds.includes(previousFocusedSessionId)) {
return previousFocusedSessionId;
}
const replacementIdSet = new Set(uniqueReplacementIds);
let inserted = false;
const nextOrder: string[] = [];
for (const tabId of tabOrder) {
if (tabId === workspaceId) {
if (!inserted) {
nextOrder.push(...uniqueReplacementIds);
inserted = true;
}
continue;
}
if (!replacementIdSet.has(tabId)) {
nextOrder.push(tabId);
}
}
return nextOrder;
}
return resolveMostRecentlyActiveMemberTerminalId({
memberTerminalIds: remainingSessionIds,
aiSessions,
}) ?? remainingSessionIds[0];
};
export function closeSessionWorkspaceLayoutState(
workspaces: readonly Workspace[],
workspaceId: string | undefined,
sessionId: string,
aiSessions?: readonly AIChatRecencyEntry[],
): CloseSessionWorkspaceLayoutResult {
if (!workspaceId) return { workspaces: [...workspaces] };
let removedWorkspaceId: string | undefined;
let dissolvedWorkspaceId: string | undefined;
let lastRemainingSessionId: string | undefined;
const nextWorkspaces = workspaces
.map((workspace) => {
if (workspace.id !== workspaceId) return workspace;
const prunedRoot = pruneWorkspaceNode(workspace.root, sessionId);
if (!prunedRoot) {
removedWorkspaceId = workspace.id;
return null;
// Issue #4098 phase 2: the last member closed, but the workspace is a
// first-class entity — it survives with an empty root so its id (and
// the AI chats anchored to it) survive restart and member churn.
return {
...workspace,
root: createEmptyWorkspaceRoot(),
focusedSessionId: undefined,
focusSessionOrder: [],
};
}
const remainingSessionIds = collectSessionIds(prunedRoot);
if (remainingSessionIds.length === 1) {
dissolvedWorkspaceId = workspace.id;
lastRemainingSessionId = remainingSessionIds[0];
return null;
}
// Closing the focused session must hand focus to a remaining one, or a
// focus-mode workspace is left with a dangling focusedSessionId: no pane
// qualifies as visible and the continuously rendered hidden panes all
// paint on top of each other (#3046).
const nextFocusedSessionId =
workspace.focusedSessionId && !remainingSessionIds.includes(workspace.focusedSessionId)
? remainingSessionIds[0]
: workspace.focusedSessionId;
// Closing the focused session hands focus to the most-recently-active
// surviving member when AI chat recency is available.
const nextFocusedSessionId = resolveSurvivingFocusMemberId(
remainingSessionIds,
workspace.focusedSessionId,
aiSessions,
);
const nextFocusSessionOrder = workspace.focusSessionOrder?.filter(
(candidateId) => remainingSessionIds.includes(candidateId),
);
@@ -114,36 +94,23 @@ export function closeSessionWorkspaceLayoutState(
focusedSessionId: nextFocusedSessionId,
focusSessionOrder: nextFocusSessionOrder,
};
})
.filter((workspace): workspace is Workspace => Boolean(workspace));
});
return {
workspaces: nextWorkspaces,
removedWorkspaceId,
dissolvedWorkspaceId,
lastRemainingSessionId,
};
}
/**
* Apply a close-session action to the session list using the layout result.
* When a 2-pane workspace dissolves to one terminal, that remaining session
* must become an orphan tab — not stay bound to a deleted workspaceId.
* Since issue #4098 phase 2 workspaces survive member loss (no dissolve), the
* remaining members keep their workspace binding.
*/
export function applyCloseSessionToSessions(
sessions: readonly TerminalSession[],
sessionId: string,
layoutResult: Pick<CloseSessionWorkspaceLayoutResult, "lastRemainingSessionId">,
): TerminalSession[] {
const remaining = sessions.filter((session) => session.id !== sessionId);
const lastRemainingSessionId = layoutResult.lastRemainingSessionId;
if (!lastRemainingSessionId) return remaining;
return remaining.map((session) => (
session.id === lastRemainingSessionId
? { ...session, workspaceId: undefined }
: session
));
return sessions.filter((session) => session.id !== sessionId);
}
export function isPreferredTabAvailableAfterClose(
@@ -161,12 +128,6 @@ export function isPreferredTabAvailableAfterClose(
} {
const { preferredTabId, closedSessionId, layoutResult, remainingSessions } = input;
if (!preferredTabId || preferredTabId === closedSessionId) return false;
if (
preferredTabId === layoutResult.dissolvedWorkspaceId
|| preferredTabId === layoutResult.removedWorkspaceId
) {
return false;
}
if (preferredTabId === "vault" || preferredTabId === "sftp") return true;
if (layoutResult.workspaces.some((workspace) => workspace.id === preferredTabId)) return true;
return remainingSessions.some((session) => (
@@ -179,7 +140,6 @@ export function isPreferredTabAvailableAfterClose(
export function resolveActiveTabAfterCloseSession({
currentActiveTabId,
closedSessionId,
workspaceId,
layoutResult,
remainingSessions,
preferredTabId,
@@ -202,18 +162,14 @@ export function resolveActiveTabAfterCloseSession({
const preferredFallback = isPreferredTabAvailableAfterClose(preferredInput)
? preferredInput.preferredTabId
: undefined;
const fallback = layoutResult.lastRemainingSessionId
?? preferredFallback
const fallback = preferredFallback
?? fallbackWorkspace?.id
?? fallbackSolo?.id
?? "vault";
if (
currentActiveTabId === closedSessionId
|| (layoutResult.dissolvedWorkspaceId && currentActiveTabId === layoutResult.dissolvedWorkspaceId)
|| (layoutResult.removedWorkspaceId && currentActiveTabId === layoutResult.removedWorkspaceId)
|| (workspaceId && currentActiveTabId === workspaceId && !layoutResult.workspaces.some((ws) => ws.id === workspaceId))
) {
// Workspaces survive member loss (#4098 phase 2), so only a closed session
// tab that was active needs a replacement.
if (currentActiveTabId === closedSessionId) {
return fallback;
}
@@ -227,6 +183,7 @@ export function closeSessionsState({
currentActiveTabId,
preferredTabId,
tabOrder,
aiSessions,
}: {
sessions: readonly TerminalSession[];
workspaces: readonly Workspace[];
@@ -234,6 +191,7 @@ export function closeSessionsState({
currentActiveTabId: string | null;
preferredTabId?: string | null;
tabOrder: readonly string[];
aiSessions?: readonly AIChatRecencyEntry[];
}): CloseSessionsStateResult {
let nextSessions = [...sessions];
let nextWorkspaces = [...workspaces];
@@ -250,17 +208,10 @@ export function closeSessionsState({
nextWorkspaces,
workspaceId,
sessionId,
aiSessions,
);
nextWorkspaces = layoutResult.workspaces;
nextSessions = applyCloseSessionToSessions(nextSessions, sessionId, layoutResult);
if (layoutResult.dissolvedWorkspaceId && layoutResult.lastRemainingSessionId) {
nextTabOrder = replaceDissolvedWorkspaceTabOrder(
nextTabOrder,
layoutResult.dissolvedWorkspaceId,
[layoutResult.lastRemainingSessionId],
);
}
nextSessions = applyCloseSessionToSessions(nextSessions, sessionId);
const activeTabAfterClose = resolveActiveTabAfterCloseSession({
currentActiveTabId: nextActiveTabId,
@@ -288,6 +239,7 @@ export function detachSessionFromWorkspaceState({
sessions,
workspaces,
sessionId,
aiSessions,
}: DetachSessionFromWorkspaceStateOptions): DetachSessionFromWorkspaceStateResult {
const session = sessions.find((candidate) => candidate.id === sessionId);
if (!session?.workspaceId) {
@@ -301,40 +253,36 @@ export function detachSessionFromWorkspaceState({
}
const prunedRoot = pruneWorkspaceNode(targetWorkspace.root, sessionId);
let nextSessions = sessions.map((candidate) => (
const nextSessions = sessions.map((candidate) => (
candidate.id === sessionId ? { ...candidate, workspaceId: undefined } : candidate
));
if (!prunedRoot) {
// Last member dragged out: the workspace entity survives with an empty
// root (#4098 phase 2) so its id and anchored AI chats stay stable.
return {
changed: true,
sessions: nextSessions,
workspaces: workspaces.filter((workspace) => workspace.id !== workspaceId),
workspaces: workspaces.map((workspace) => (
workspace.id === workspaceId
? {
...workspace,
root: createEmptyWorkspaceRoot(),
focusedSessionId: undefined,
focusSessionOrder: [],
}
: workspace
)),
activeTabId: sessionId,
dissolvedWorkspaceId: workspaceId,
replacementTabIds: [sessionId],
};
}
const remainingSessionIds = collectSessionIds(prunedRoot);
if (remainingSessionIds.length === 1) {
nextSessions = nextSessions.map((candidate) => (
candidate.id === remainingSessionIds[0] ? { ...candidate, workspaceId: undefined } : candidate
));
return {
changed: true,
sessions: nextSessions,
workspaces: workspaces.filter((workspace) => workspace.id !== workspaceId),
activeTabId: sessionId,
dissolvedWorkspaceId: workspaceId,
replacementTabIds: [sessionId, ...remainingSessionIds],
};
}
const nextFocusedSessionId = remainingSessionIds.includes(targetWorkspace.focusedSessionId)
? targetWorkspace.focusedSessionId
: remainingSessionIds[0];
const nextFocusedSessionId = resolveSurvivingFocusMemberId(
remainingSessionIds,
targetWorkspace.focusedSessionId,
aiSessions,
);
const nextFocusSessionOrder = (targetWorkspace.focusSessionOrder ?? [])
.filter((candidateId, index, list) => (
candidateId !== sessionId &&
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { SftpPane } from "./types";
import type { SftpArchiveCreationResult } from "../../../domain/sftpArchiveCreation";
import { createSftpArchiveForPane } from "./createSftpArchive.ts";
function setup() {
let pane = {
id: "pane-a", connection: { id: "connection-a", isLocal: false }, filenameEncoding: "gb18030",
} as SftpPane;
const calls: unknown[][] = [];
const refreshes: string[] = [];
const params = {
getPane: () => pane,
target: { paneId: "pane-a", connectionId: "connection-a" },
options: { directory: "/srv", paths: ["中文", "logs"], archiveName: "backup.zip", format: "zip" as const },
getSftpIdForConnection: (id: string) => id === "connection-a" ? "sftp-a" : undefined,
bridge: {
createSftpArchive: async (...args: unknown[]): Promise<SftpArchiveCreationResult> => {
calls.push(args);
return { success: true };
},
},
refresh: async (id: string) => { refreshes.push(id); },
t: (key: string) => key,
};
return { params, calls, refreshes, setPane: (value: SftpPane) => { pane = value; } };
}
test("archive creation passes selected paths and encoding to the captured remote session", async () => {
const { params, calls, refreshes } = setup();
assert.deepEqual(await createSftpArchiveForPane(params), { success: true });
assert.deepEqual(calls, [["sftp-a", params.options, "gb18030"]]);
assert.deepEqual(refreshes, ["pane-a"]);
});
test("a switched or disconnected pane cannot compress files on another host", async () => {
for (const change of [
{ id: "pane-b" },
{ connection: { id: "connection-b", isLocal: false } },
{ connection: null },
]) {
const { params, calls, setPane } = setup();
setPane({ ...params.getPane(), ...change } as SftpPane);
await assert.rejects(createSftpArchiveForPane(params), /connectionChanged/);
assert.equal(calls.length, 0);
}
});
test("archive creation requires a remote session and a supported bridge", async () => {
const { params, calls, setPane } = setup();
await assert.rejects(createSftpArchiveForPane({ ...params, bridge: undefined }), /unavailable/);
await assert.rejects(createSftpArchiveForPane({ ...params, getSftpIdForConnection: () => undefined }), /unavailable/);
setPane({ ...params.getPane(), connection: { id: "connection-a", isLocal: true } } as SftpPane);
await assert.rejects(createSftpArchiveForPane(params), /unavailable/);
assert.equal(calls.length, 0);
});
test("existing archives are returned for confirmation without retry or refresh", async () => {
const { params, refreshes } = setup();
const conflict = { success: false, code: "EEXIST", error: "Already exists" };
params.bridge.createSftpArchive = async () => conflict;
assert.equal(await createSftpArchiveForPane(params), conflict);
assert.deepEqual(refreshes, []);
});
test("finishing after a tab switch does not refresh the new connection", async () => {
const { params, refreshes, setPane } = setup();
params.bridge.createSftpArchive = async () => {
setPane({ ...params.getPane(), id: "pane-b" } as SftpPane);
return { success: true };
};
assert.deepEqual(await createSftpArchiveForPane(params), { success: true });
assert.deepEqual(refreshes, []);
});
test("a failed operation is not refreshed or converted to success", async () => {
const { params, refreshes } = setup();
params.bridge.createSftpArchive = async () => { throw new Error("zip is not installed"); };
await assert.rejects(createSftpArchiveForPane(params), /zip is not installed/);
assert.deepEqual(refreshes, []);
});
test("a listing error after publication does not invite a second archive creation", async () => {
const { params, calls } = setup();
params.refresh = async () => { throw new Error("Disconnected after publication"); };
assert.deepEqual(await createSftpArchiveForPane(params), { success: true });
assert.equal(calls.length, 1);
});
@@ -0,0 +1,46 @@
import type {
SftpArchiveCreationOptions,
SftpArchiveCreationResult,
SftpArchiveCreationTarget,
} from "../../../domain/sftpArchiveCreation";
import type { SftpPane } from "./types";
import { logger } from "../../../lib/logger";
interface CreateSftpArchiveParams {
getPane: () => Pick<SftpPane, "id" | "connection" | "filenameEncoding">;
target: SftpArchiveCreationTarget;
options: SftpArchiveCreationOptions;
bridge: Pick<NetcattyBridge, "createSftpArchive"> | undefined;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
refresh: (paneId: string) => Promise<void>;
t: (key: string) => string;
}
/** Bind the selected files to the pane/connection that opened the dialog. */
export async function createSftpArchiveForPane({
getPane, target, options, bridge, getSftpIdForConnection, refresh, t,
}: CreateSftpArchiveParams): Promise<SftpArchiveCreationResult> {
const pane = getPane();
if (pane.id !== target.paneId || pane.connection?.id !== target.connectionId) {
throw new Error(t("sftp.archive.connectionChanged"));
}
const sftpId = getSftpIdForConnection?.(target.connectionId);
if (pane.connection.isLocal || !sftpId || !bridge?.createSftpArchive) {
throw new Error(t("sftp.archive.unavailable"));
}
const result = await bridge.createSftpArchive(sftpId, options, pane.filenameEncoding);
if (!result.success) return result;
// A tab switch during compression must not refresh an unrelated connection.
const current = getPane();
if (current.id === target.paneId && current.connection?.id === target.connectionId) {
try {
await refresh(target.paneId);
} catch (error) {
// The archive has already been published. A listing failure must not
// invite the user to repeat a successful operation (or overwrite it).
logger.warn("[SFTP] Archive created but directory refresh failed:", error);
}
}
return result;
}
@@ -0,0 +1,131 @@
/** @test issue #4132 — a one-click duplicate copies next to the source without a conflict prompt */
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import path from "node:path";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { useSftpTransfers } from "./useSftpTransfers";
import { createEmptyPane } from "./types";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
test("duplicate transfers resolve same-name conflicts to (copy) without prompting", async () => {
const dir = await fs.mkdtemp(path.join(process.cwd(), ".duplicate-entries-"));
const ownerId = `duplicate-entries-${crypto.randomUUID()}`;
const previousWindow = globalThis.window;
const previousStorage = globalThis.localStorage;
const globals = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
globals.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let ops!: ReturnType<typeof useSftpTransfers>;
// A duplicate has to cover both files and folders: the conflict type key
// differs between the two and the seeded defaults must match both.
const fileNames = ["report.txt"];
const folderNames = ["photos"];
for (const name of fileNames) {
await fs.writeFile(path.join(dir, name), "original data");
}
for (const name of folderNames) {
await fs.mkdir(path.join(dir, name));
await fs.writeFile(path.join(dir, name, "nested.txt"), "nested data");
}
const pane = createEmptyPane("duplicate-pane");
pane.connection = { id: ownerId, isLocal: true, currentPath: dir, status: "connected" } as NonNullable<typeof pane.connection>;
const statPath = async (value: string) => {
try {
const stat = await fs.lstat(value);
return { type: stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : "file", size: stat.size, lastModified: stat.mtimeMs };
} catch {
return null;
}
};
(globalThis as { window?: unknown }).window = { requestAnimationFrame: (callback: () => void) => setTimeout(callback, 0), cancelAnimationFrame: clearTimeout, netcatty: {
realpathLocal: fs.realpath, statLocal: statPath, lstatLocal: statPath,
mkdirLocal: async (value: string) => { await fs.mkdir(value, { recursive: true }); },
deleteLocalFile: async (value: string) => { await fs.rm(value, { recursive: true, force: true }); },
renameLocalFile: async (source: string, target: string) => { await fs.rename(source, target); },
startStreamTransfer: async (options: { sourcePath: string; targetPath: string; transferId: string }) => {
await fs.copyFile(options.sourcePath, options.targetPath);
sftpTransferCenterStore.ingestBackgroundEvent({ type: "completed", transferId: options.transferId, transferred: 13, totalBytes: 13, lifecycleEpoch: 0 });
return {};
},
} };
(globalThis as { localStorage?: unknown }).localStorage = { getItem: () => null, setItem: () => undefined, removeItem: () => undefined };
function Probe() {
ops = useSftpTransfers({
ownerId, getActivePane: () => pane, getPaneByConnectionId: () => pane, getTabByConnectionId: () => ({ side: "left", tabId: pane.id, pane }),
updateTab: () => undefined, refresh: async () => undefined,
clearCacheForConnection: () => undefined, handleSessionError: () => undefined,
sftpSessionsRef: { current: new Map() }, connectionCacheKeyMapRef: { current: new Map() },
listRemoteFiles: async () => [],
listLocalFiles: async (value: string) => Promise.all((await fs.readdir(value)).map(async name => {
const stat = await fs.lstat(path.join(value, name));
return { name, type: stat.isSymbolicLink() ? "symlink" as const : stat.isDirectory() ? "directory" as const : "file" as const, size: stat.size, sizeFormatted: "", lastModified: stat.mtimeMs, lastModifiedFormatted: "" };
})),
});
return null;
}
const waitForSettledRoots = async (expected: number) => {
await act(async () => {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const roots = sftpTransferCenterStore.getOwnerTasks(ownerId).filter(row => !row.parentTaskId);
if (roots.length === expected && roots.every(row => ["completed", "failed"].includes(row.status))) return;
await new Promise(resolve => setTimeout(resolve, 20));
}
});
};
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
const sources = [...fileNames, ...folderNames].map(name => ({ name, isDirectory: folderNames.includes(name) }));
await act(async () => {
await ops.startTransfer(sources, "left", "left", { sourcePath: dir, targetPath: dir, duplicate: true });
});
// The duplicate option must resolve conflicts by itself; a prompt here
// would defeat the one-click action the issue asks for.
assert.deepEqual(ops.conflicts, []);
await waitForSettledRoots(sources.length);
const roots = sftpTransferCenterStore.getOwnerTasks(ownerId).filter(row => !row.parentTaskId);
assert.equal(roots.length, sources.length, JSON.stringify(roots.map(row => row.fileName)));
assert.ok(roots.every(row => row.status === "completed"), JSON.stringify(roots.map(row => ({ status: row.status, error: row.error }))));
for (const name of fileNames) {
assert.equal(await fs.readFile(path.join(dir, name), "utf8"), "original data");
}
assert.equal(await fs.readFile(path.join(dir, "report (copy).txt"), "utf8"), "original data");
assert.equal(await fs.readFile(path.join(dir, "photos (copy)", "nested.txt"), "utf8"), "nested data");
// A second duplicate must pick the next free name instead of colliding
// with the copy created by the first run.
await act(async () => {
await ops.startTransfer(sources, "left", "left", { sourcePath: dir, targetPath: dir, duplicate: true });
});
assert.deepEqual(ops.conflicts, []);
await waitForSettledRoots(sources.length * 2);
assert.equal(await fs.readFile(path.join(dir, "report (copy 2).txt"), "utf8"), "original data");
assert.equal(await fs.readFile(path.join(dir, "photos (copy 2)", "nested.txt"), "utf8"), "nested data");
// The tree's ".." navigation row must never be duplicated: it would copy
// an ancestor into itself.
const tasksBefore = sftpTransferCenterStore.getOwnerTasks(ownerId).length;
let navigationResults: unknown;
await act(async () => {
navigationResults = await ops.startTransfer(
[{ name: "..", isDirectory: true }],
"left",
"left",
{ sourcePath: dir, targetPath: dir, duplicate: true },
);
});
assert.deepEqual(navigationResults, []);
assert.equal(sftpTransferCenterStore.getOwnerTasks(ownerId).length, tasksBefore);
assert.deepEqual(ops.conflicts, []);
} finally {
await act(async () => { renderer?.unmount(); });
for (const row of sftpTransferCenterStore.getOwnerTasks(ownerId)) sftpTransferCenterStore.dismiss(row.id);
(globalThis as { window?: unknown }).window = previousWindow;
(globalThis as { localStorage?: unknown }).localStorage = previousStorage;
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
await fs.rm(dir, { recursive: true, force: true });
}
});
@@ -0,0 +1,109 @@
/** @test issue #4132 — a duplicate must not reuse a destination an earlier copy still holds */
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import path from "node:path";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { useSftpTransfers } from "./useSftpTransfers";
import { createEmptyPane } from "./types";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
test("duplicate names around a destination an in-flight copy has not created yet", async () => {
const dir = await fs.mkdtemp(path.join(process.cwd(), ".duplicate-inflight-"));
const ownerId = `duplicate-inflight-${crypto.randomUUID()}`;
const previousWindow = globalThis.window;
const previousStorage = globalThis.localStorage;
const globals = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
globals.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let ops!: ReturnType<typeof useSftpTransfers>;
let releaseFirst: (() => void) | undefined;
const firstCopyGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
let streamStarts = 0;
await fs.writeFile(path.join(dir, "report.txt"), "original data");
const pane = createEmptyPane("duplicate-inflight-pane");
pane.connection = { id: ownerId, isLocal: true, currentPath: dir, status: "connected" } as NonNullable<typeof pane.connection>;
const statPath = async (value: string) => {
try {
const stat = await fs.lstat(value);
return { type: stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : "file", size: stat.size, lastModified: stat.mtimeMs };
} catch {
return null;
}
};
(globalThis as { window?: unknown }).window = { requestAnimationFrame: (callback: () => void) => setTimeout(callback, 0), cancelAnimationFrame: clearTimeout, netcatty: {
realpathLocal: fs.realpath, statLocal: statPath, lstatLocal: statPath,
mkdirLocal: async (value: string) => { await fs.mkdir(value, { recursive: true }); },
deleteLocalFile: async (value: string) => { await fs.rm(value, { recursive: true, force: true }); },
renameLocalFile: async (source: string, target: string) => { await fs.rename(source, target); },
startStreamTransfer: async (options: { sourcePath: string; targetPath: string; transferId: string }) => {
streamStarts += 1;
// Hold the first copy before it writes its destination: the second
// duplicate then sees no "(copy)" on disk even though one is reserved.
if (streamStarts === 1) await firstCopyGate;
await fs.copyFile(options.sourcePath, options.targetPath);
sftpTransferCenterStore.ingestBackgroundEvent({ type: "completed", transferId: options.transferId, transferred: 13, totalBytes: 13, lifecycleEpoch: 0 });
return {};
},
} };
(globalThis as { localStorage?: unknown }).localStorage = { getItem: () => null, setItem: () => undefined, removeItem: () => undefined };
function Probe() {
ops = useSftpTransfers({
ownerId, getActivePane: () => pane, getPaneByConnectionId: () => pane, getTabByConnectionId: () => ({ side: "left", tabId: pane.id, pane }),
updateTab: () => undefined, refresh: async () => undefined,
clearCacheForConnection: () => undefined, handleSessionError: () => undefined,
sftpSessionsRef: { current: new Map() }, connectionCacheKeyMapRef: { current: new Map() },
listRemoteFiles: async () => [],
listLocalFiles: async (value: string) => Promise.all((await fs.readdir(value)).map(async name => {
const stat = await fs.lstat(path.join(value, name));
return { name, type: stat.isSymbolicLink() ? "symlink" as const : stat.isDirectory() ? "directory" as const : "file" as const, size: stat.size, sizeFormatted: "", lastModified: stat.mtimeMs, lastModifiedFormatted: "" };
})),
});
return null;
}
const sources = [{ name: "report.txt", isDirectory: false }];
const options = { sourcePath: dir, targetPath: dir, duplicate: true };
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
// First duplicate starts copying and blocks before writing "(copy)".
let firstRun: ReturnType<typeof ops.startTransfer> | undefined;
await act(async () => {
firstRun = ops.startTransfer(sources, "left", "left", options);
const deadline = Date.now() + 3000;
while (streamStarts === 0 && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 5));
}
});
assert.equal(streamStarts, 1, "the first copy should be in flight");
// Second duplicate runs while "(copy)" is still absent from the disk.
await act(async () => { await ops.startTransfer(sources, "left", "left", options); });
assert.equal(ops.conflicts.length, 0, "duplicate must not prompt for a reserved name");
releaseFirst?.();
await act(async () => { await firstRun; });
await act(async () => {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const rows = sftpTransferCenterStore.getOwnerTasks(ownerId).filter(row => !row.parentTaskId);
if (rows.length === 2 && rows.every(row => ["completed", "failed"].includes(row.status))) return;
await new Promise(resolve => setTimeout(resolve, 20));
}
});
const roots = sftpTransferCenterStore.getOwnerTasks(ownerId).filter(row => !row.parentTaskId);
assert.deepEqual(roots.map(row => row.fileName).sort(), ["report (copy 2).txt", "report (copy).txt"]);
assert.ok(roots.every(row => row.status === "completed"), JSON.stringify(roots.map(row => ({ status: row.status, error: row.error }))));
assert.equal(await fs.readFile(path.join(dir, "report (copy).txt"), "utf8"), "original data");
assert.equal(await fs.readFile(path.join(dir, "report (copy 2).txt"), "utf8"), "original data");
} finally {
releaseFirst?.();
await act(async () => { renderer?.unmount(); });
for (const row of sftpTransferCenterStore.getOwnerTasks(ownerId)) sftpTransferCenterStore.dismiss(row.id);
(globalThis as { window?: unknown }).window = previousWindow;
(globalThis as { localStorage?: unknown }).localStorage = previousStorage;
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
await fs.rm(dir, { recursive: true, force: true });
}
});
@@ -541,3 +541,98 @@ test("late pause acknowledgement cannot restart a cancelling stream before settl
await pause;
assert.equal(resumes, 0);
});
for (const rejected of [false, true]) {
test(`folder pause retains successful children without claiming failed children paused: rejected=${rejected}`, async (t) => {
t.after(resetTransferPauseLatchesForTests);
let fail = true;
let resumes = 0;
const id = `partial-folder-${rejected}`;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async (childId) => {
if (fail && childId.endsWith('-bad')) {
if (rejected) throw new Error('pause IPC unavailable');
return { success: false, reason: 'This transfer cannot be paused safely' };
}
return { success: true, checkpointBytes: 10 };
},
resumeTransfer: async () => { resumes++; return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /pause/i);
assert.equal(getTasks()[1].status, 'paused');
assert.equal(getTasks()[2].status, 'transferring');
assert.equal(isTransferPauseLatched(id), true);
assert.equal(resumes, 0, 'failed pause must not resume successful siblings');
fail = false;
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.ok(getTasks().every(row => row.status === 'paused'));
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
});
}
test('folder pause does not claim success while acknowledgements are pending or retry budget expires', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'slow-start-folder';
let calls = 0;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: async () => {
calls++;
return { success: false, reason: 'This transfer cannot be paused yet' };
} }));
assert.equal(await softPauseTransfer(host, id), 'pausing');
assert.equal(getTasks()[0].status, 'pausing');
// Wait for the bounded startup retry budget (four 40ms delays).
await new Promise(resolve => setTimeout(resolve, 220));
assert.equal(calls, 5);
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /cannot be paused yet/);
assert.equal(getTasks()[1].status, 'transferring');
});
test('explicit resume after partial folder pause releases successful siblings and walk latch', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'resume-partial-folder';
const resumed: string[] = [];
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async childId => childId.endsWith('-ok')
? { success: true } : { success: false, reason: 'Pause rejected' },
resumeTransfer: async childId => { resumed.push(childId); return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal((await softResumeTransfer(host, id)).handled, true);
assert.equal(isTransferPauseLatched(id), false);
assert.ok(getTasks().every(row => row.status === 'transferring'));
assert.deepEqual(resumed.sort(), [`${id}-bad`, `${id}-ok`]);
});
test('child completion during a rejected folder pause does not leave a false failure', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'completed-during-folder-pause';
let finish!: (result: { success: boolean; reason: string }) => void;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: () => new Promise(resolve => { finish = resolve; }) }));
await softPauseTransfer(host, id);
host.setTasks(getTasks().map(row => row.parentTaskId ? { ...row, status: 'completed' } : row));
finish({ success: false, reason: 'Pause rejected' });
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'paused');
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
assert.equal(getTasks()[1].status, 'completed');
});
@@ -184,7 +184,7 @@ export async function softPauseTransfer(
try { globalSftpTransferScheduler.pause(id); } catch { /* best-effort */ }
}
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
const immediateStatus = "pausing" as const;
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
host.setTasks(paintTreeStatus(
host.getTasks(),
@@ -271,7 +271,11 @@ export async function softPauseTransfer(
if (!pauseStillCurrent()) {
return { id, result: { success: false, reason: "Pause superseded by resume" } };
}
const result = await pauseOne(id);
// A rejected IPC is a failed acknowledgement, not proof of pause.
const result: Awaited<ReturnType<NonNullable<TransferControlBridge["pauseTransfer"]>>> = await pauseOne(id).catch((error: unknown) => ({
success: false,
reason: error instanceof Error ? error.message : "Could not pause transfer",
}));
if (wasSuperseded(result)) return { id, result };
const live = host.getTasks().find((candidate) => candidate.id === taskId);
const userResumed = !pauseStillCurrent()
@@ -293,16 +297,26 @@ export async function softPauseTransfer(
if (after.status !== "paused" && after.status !== "pausing") return;
const byId = new Map(pauseResults.map((row) => [row.id, row.result]));
const bridgeEpoch = maxBridgeLifecycleEpoch(pauseResults.map((row) => row.result));
// Final directory paint: parent + unfinished children all go paused (do not
// leave children stuck on transferring under a paused parent).
const liveTasks = host.getTasks();
const failed = pauseResults.filter(({ id, result }) => {
const live = liveTasks.find((candidate) => candidate.id === id);
return live && !["completed", "cancelled", "failed"].includes(live.status)
&& !result.success && !isBenignPauseMiss(result.reason);
});
// Keep acknowledged children paused and retain the walk latch. Never
// auto-resume siblings to roll back a partial pause. Failed children may
// still be streaming; expose that truth and allow an explicit retry.
const pauseFailure = failed.length > 0
? (failed[0].result.reason || "Could not pause all folder transfers")
: undefined;
host.setTasks(host.getTasks().map((candidate) => {
if (candidate.id === taskId) {
return {
...candidate,
status: "paused" as const,
status: pauseFailure ? "pausing" as const : "paused" as const,
speed: 0,
checkpointBytes: candidate.transferredBytes,
pauseUnavailableReason: undefined,
pauseUnavailableReason: pauseFailure,
phase: undefined,
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
@@ -311,24 +325,25 @@ export async function softPauseTransfer(
if (candidate.parentTaskId !== taskId && !backendIds.includes(candidate.id)) return candidate;
if (["completed", "cancelled", "failed"].includes(candidate.status)) return candidate;
const result = byId.get(candidate.id);
const childFailed = result && !result.success && !isBenignPauseMiss(result.reason);
const childEpoch = Number.isFinite(result?.lifecycleEpoch)
? (result!.lifecycleEpoch as number)
: bridgeEpoch;
: childFailed ? undefined : bridgeEpoch;
return {
...candidate,
status: "paused" as const,
status: childFailed ? "transferring" as const : "paused" as const,
speed: 0,
checkpointBytes: result?.checkpointBytes ?? candidate.checkpointBytes ?? candidate.transferredBytes,
resumeStage: result?.resumeStage ?? candidate.resumeStage,
downloadCheckpointBytes: result?.downloadCheckpointBytes ?? candidate.downloadCheckpointBytes,
uploadCheckpointBytes: result?.uploadCheckpointBytes ?? candidate.uploadCheckpointBytes,
sourceFingerprint: result?.sourceFingerprint ?? candidate.sourceFingerprint,
pauseUnavailableReason: undefined,
pauseUnavailableReason: childFailed ? (result.reason || "Could not pause transfer") : undefined,
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
};
}));
})().catch(() => { /* best-effort */ });
return "paused";
return "pausing";
}
// Single-file: await soft-drain with supersede guards.
@@ -61,10 +61,11 @@ export function useSftpTransferConflictOps() {
const getDuplicateTarget = useCallback(
async (
task: TransferTask,
task: Pick<TransferTask, "fileName" | "isDirectory" | "targetPath">,
targetPane: SftpPane,
targetSftpId: string | null,
targetEncoding: SftpFilenameEncoding,
isTargetTaken?: (targetPath: string) => boolean,
) => {
const parentPath = getParentPath(task.targetPath);
const { baseName, ext } = splitNameForDuplicate(task.fileName, task.isDirectory);
@@ -73,6 +74,9 @@ export function useSftpTransferConflictOps() {
const suffix = index === 1 ? " (copy)" : ` (copy ${index})`;
const fileName = `${baseName}${suffix}${ext}`;
const targetPath = joinPath(parentPath, fileName);
// A queued/paused duplicate may not have created its destination yet,
// so the filesystem alone would hand out the same name twice.
if (isTargetTaken?.(targetPath)) continue;
// Unsupported LSTAT must propagate — do not treat as a free name.
const existing = await statTargetPath(targetPane, targetSftpId, targetPath, targetEncoding);
if (!existing) return { fileName, targetPath };
@@ -122,8 +122,11 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
resetGlobals();
const resumeCalls: string[] = [];
let dedicatedHandlerCalls = 0;
let acknowledgePause!: () => void;
installBridge(t, {
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
pauseTransfer: () => new Promise((resolve) => {
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
}),
resumeTransfer: async (id) => {
resumeCalls.push(id);
return { success: true };
@@ -151,6 +154,9 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
]);
await runtime.pause("folder");
assert.equal(runtime.getTask("folder")?.status, "pausing");
acknowledgePause();
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(runtime.getTask("folder")?.status, "paused");
assert.equal(isTransferPauseLatched("folder"), true);
assert.equal(isTransferWalkInFlight("folder"), true);
@@ -0,0 +1,161 @@
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 type { SftpArchiveCreationResult } from "../../../domain/sftpArchiveCreation";
import { useSftpArchiveDialog } from "./useSftpArchiveDialog";
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; });
type Params = Parameters<typeof useSftpArchiveDialog>[0];
async function mount(overrides: Partial<Params> = {}) {
let params: Params = {
paneId: "pane-1", connectionId: "conn-1", isLocal: false, isActive: true,
t: (key) => key, onCreateArchive: async () => ({ success: true }), onCreated: () => {},
...overrides,
};
let current!: ReturnType<typeof useSftpArchiveDialog>;
function Probe() {
current = useSftpArchiveDialog(params);
return null;
}
let renderer!: ReactTestRenderer;
await act(async () => { renderer = create(React.createElement(Probe)); });
return {
get value() { return current; },
async update(changes: Partial<Params>) {
params = { ...params, ...changes };
await act(async () => { renderer.update(React.createElement(Probe)); });
},
async unmount() { await act(async () => { renderer.unmount(); }); },
};
}
test("archive dialog snapshots nested selections, format, and connection identity", async (t) => {
const requests: unknown[] = [];
const reloaded: string[] = [];
const harness = await mount({
onCreateArchive: async (options, target) => { requests.push({ options, target }); return { success: true }; },
onCreated: (directory) => { reloaded.push(directory); },
});
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site/assets", "/srv/site/assets/logo.png", "/srv/site/config/app.json"]); });
assert.deepEqual(harness.value.state?.paths, ["assets", "config/app.json"]);
assert.equal(harness.value.state?.directory, "/srv/site");
await act(async () => { harness.value.setArchiveName("backup.tar.gz"); harness.value.setFormat("zip"); });
assert.equal(harness.value.state?.archiveName, "backup.zip");
await act(async () => { await harness.value.submit(); });
assert.deepEqual(requests, [{
options: { directory: "/srv/site", paths: ["assets", "config/app.json"], archiveName: "backup.zip", format: "zip", overwrite: false },
target: { paneId: "pane-1", connectionId: "conn-1" },
}]);
assert.deepEqual(reloaded, ["/srv/site"]);
assert.equal(harness.value.state, null);
});
test("archive dialog requires a separate overwrite decision and revokes it on edits", async (t) => {
const overwriteFlags: Array<boolean | undefined> = [];
const harness = await mount({ onCreateArchive: async (options) => {
overwriteFlags.push(options.overwrite);
return options.overwrite ? { success: true } : { success: false, code: "EEXIST" };
} });
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site"]); });
await act(async () => { await harness.value.submit(true); });
assert.deepEqual(overwriteFlags, [], "overwrite is unavailable before a collision");
await act(async () => { await harness.value.submit(); });
assert.equal(harness.value.state?.confirmOverwrite, true);
await act(async () => { await harness.value.submit(); });
assert.deepEqual(overwriteFlags, [false], "Enter must not confirm overwrite");
await act(async () => { harness.value.setArchiveName("other.tar.gz"); });
assert.equal(harness.value.state?.confirmOverwrite, false);
await act(async () => { await harness.value.submit(true); });
assert.deepEqual(overwriteFlags, [false]);
await act(async () => { await harness.value.submit(); });
await act(async () => { await harness.value.submit(true); });
assert.deepEqual(overwriteFlags, [false, false, true]);
assert.equal(harness.value.state, null);
});
test("pending archive creation blocks duplicate submits, edits, and dismissal", async (t) => {
let finish!: (result: SftpArchiveCreationResult) => void;
let requests = 0;
const harness = await mount({ onCreateArchive: async () => {
requests += 1;
return new Promise<SftpArchiveCreationResult>((resolve) => { finish = resolve; });
} });
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site"]); });
let pending!: Promise<void>;
await act(async () => {
pending = harness.value.submit();
void harness.value.submit();
harness.value.close();
harness.value.setArchiveName("changed.tar.gz");
harness.value.open(["/different"]);
});
assert.equal(requests, 1);
assert.equal(harness.value.state?.busy, true);
assert.equal(harness.value.state?.archiveName, "site.tar.gz");
await act(async () => { finish({ success: true }); await pending; });
assert.equal(harness.value.state, null);
});
test("switching connections dismisses the old dialog and ignores its late result", async (t) => {
let finish!: (result: SftpArchiveCreationResult) => void;
const reloaded: string[] = [];
let requests = 0;
const harness = await mount({
onCreateArchive: async () => {
requests += 1;
return new Promise<SftpArchiveCreationResult>((resolve) => { finish = resolve; });
},
onCreated: (directory) => { reloaded.push(directory); },
});
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site"]); });
let pending!: Promise<void>;
await act(async () => { pending = harness.value.submit(); });
await harness.update({ connectionId: "conn-2" });
assert.equal(harness.value.state, null);
await act(async () => { harness.value.open(["/srv/new-site"]); });
await act(async () => { finish({ success: false, code: "EEXIST" }); await pending; });
assert.equal(requests, 1);
assert.equal(harness.value.state?.archiveName, "new-site.tar.gz");
assert.equal(harness.value.state?.confirmOverwrite, false);
assert.deepEqual(reloaded, []);
});
test("tab switches invalidate the old form even when its connection stays mounted", async (t) => {
let requests = 0;
const harness = await mount({ onCreateArchive: async () => { requests += 1; return { success: true }; } });
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site"]); });
const staleSubmit = harness.value.submit;
await harness.update({ isActive: false });
await act(async () => { await staleSubmit(); });
assert.equal(harness.value.state, null);
assert.equal(requests, 0);
await harness.update({ isActive: true, isLocal: true });
await act(async () => { harness.value.open(["/srv/site"]); });
assert.equal(harness.value.state, null);
});
test("invalid names do not invoke the backend; failures keep a retryable form", async (t) => {
let requests = 0;
const harness = await mount({ onCreateArchive: async () => { requests += 1; throw new Error("zip is not installed"); } });
t.after(() => harness.unmount());
await act(async () => { harness.value.open(["/srv/site"]); harness.value.setArchiveName("../backup.tar.gz"); });
await act(async () => { await harness.value.submit(); });
assert.equal(requests, 0);
assert.equal(harness.value.state?.error, "sftp.archive.invalidName");
await act(async () => { harness.value.setArchiveName("backup.tar.gz"); });
await act(async () => { await harness.value.submit(); });
assert.equal(requests, 1);
assert.equal(harness.value.state?.busy, false);
assert.equal(harness.value.state?.error, "zip is not installed");
});
@@ -0,0 +1,162 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
prepareSftpArchiveSelection,
validateSftpArchiveName,
withSftpArchiveExtension,
type SftpArchiveCreationOptions,
type SftpArchiveCreationResult,
type SftpArchiveCreationTarget,
type SftpArchiveFormat,
} from "../../../domain/sftpArchiveCreation";
export type SftpArchiveTarget = SftpArchiveCreationTarget;
export interface SftpArchiveDialogState {
target: SftpArchiveTarget;
directory: string;
paths: string[];
archiveName: string;
format: SftpArchiveFormat;
busy: boolean;
error: string | null;
confirmOverwrite: boolean;
}
interface UseSftpArchiveDialogParams {
paneId: string;
connectionId?: string;
isLocal: boolean;
isActive: boolean;
t: (key: string, params?: Record<string, unknown>) => string;
onCreateArchive?: (
options: SftpArchiveCreationOptions,
target: SftpArchiveTarget,
) => Promise<SftpArchiveCreationResult>;
onCreated: (directory: string) => void;
}
export function useSftpArchiveDialog(params: UseSftpArchiveDialogParams) {
const [state, setState] = useState<SftpArchiveDialogState | null>(null);
const stateRef = useRef(state);
const paramsRef = useRef(params);
paramsRef.current = params;
const generation = useRef(0);
const update = useCallback((next: SftpArchiveDialogState | null) => {
stateRef.current = next;
setState(next);
}, []);
const matchesTarget = useCallback((target: SftpArchiveTarget) => {
const current = paramsRef.current;
return current.isActive && !current.isLocal
&& current.paneId === target.paneId
&& current.connectionId === target.connectionId;
}, []);
// A dialog belongs to the connection and pane on which it was opened. A tab
// switch may leave its component mounted, so visibility is part of identity.
useEffect(() => {
if (stateRef.current && !matchesTarget(stateRef.current.target)) {
generation.current += 1;
update(null);
}
}, [params.paneId, params.connectionId, params.isLocal, params.isActive, matchesTarget, update]);
useEffect(() => () => { generation.current += 1; }, []);
const open = useCallback((sourcePaths: string[]) => {
const current = paramsRef.current;
if (!current.connectionId || current.isLocal || !current.isActive
|| !current.onCreateArchive || stateRef.current?.busy) return;
generation.current += 1;
const target = { paneId: current.paneId, connectionId: current.connectionId };
try {
const selection = prepareSftpArchiveSelection(sourcePaths);
update({
target,
directory: selection.directory,
paths: selection.paths,
archiveName: withSftpArchiveExtension(selection.defaultName, "tar.gz"),
format: "tar.gz",
busy: false,
error: null,
confirmOverwrite: false,
});
} catch {
update({
target, directory: "", paths: [], archiveName: "", format: "tar.gz",
busy: false, error: current.t("sftp.archive.invalidSelection"), confirmOverwrite: false,
});
}
}, [update]);
const close = useCallback(() => {
if (stateRef.current?.busy) return;
generation.current += 1;
update(null);
}, [update]);
const setArchiveName = useCallback((archiveName: string) => {
const current = stateRef.current;
if (!current || current.busy) return;
update({ ...current, archiveName, error: null, confirmOverwrite: false });
}, [update]);
const setFormat = useCallback((format: SftpArchiveFormat) => {
const current = stateRef.current;
if (!current || current.busy) return;
update({
...current, format,
archiveName: withSftpArchiveExtension(current.archiveName, format),
error: null, confirmOverwrite: false,
});
}, [update]);
const submit = useCallback(async (overwrite = false) => {
const current = stateRef.current;
const { onCreateArchive, t } = paramsRef.current;
if (!current || current.busy || !onCreateArchive || !matchesTarget(current.target)
|| current.paths.length === 0 || (overwrite && !current.confirmOverwrite)) return;
// Enter in the name field must not implicitly confirm replacement.
if (current.confirmOverwrite && !overwrite) return;
const validationError = validateSftpArchiveName(current.archiveName, current.format);
if (validationError) {
update({ ...current, error: t(validationError) });
return;
}
const requestGeneration = generation.current;
update({ ...current, busy: true, error: null });
try {
const result = await onCreateArchive({
directory: current.directory,
paths: current.paths,
archiveName: current.archiveName,
format: current.format,
overwrite,
}, current.target);
if (generation.current !== requestGeneration || !matchesTarget(current.target)) return;
if (!result.success) {
update({
...current, busy: false,
confirmOverwrite: result.code === "EEXIST",
error: result.code === "EEXIST" ? null : result.error || t("sftp.archive.failed"),
});
return;
}
update(null);
paramsRef.current.onCreated(current.directory);
} catch (error) {
if (generation.current !== requestGeneration || !matchesTarget(current.target)) return;
update({
...current, busy: false, confirmOverwrite: false,
error: error instanceof Error ? error.message : String(error),
});
}
}, [matchesTarget, update]);
return {
state: state && matchesTarget(state.target) ? state : null,
open, close, setArchiveName, setFormat, submit,
};
}
@@ -6,6 +6,7 @@ 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";
import { buildCacheKey } from "./sharedRemoteHostCache";
for (const direction of ["download", "upload"] as const) {
test(`failed ${direction} connection replaces Waiting with the actual error (#3698)`, async () => {
@@ -999,3 +1000,86 @@ test("no-conflict local copy awaits discovery so a late stat cannot overwrite th
restore();
}
});
for (const scenario of ["folder-cp", "folder-fallback", "file-cp", "different-key", "missing-key", "non-utf8"] as const) {
test(`fresh remote copy selects a consistent strategy: ${scenario} (#4207)`, async () => {
const isDirectory = scenario.startsWith("folder");
const source = makePane("left");
const target = makePane("left");
target.connection = { ...target.connection!, id: "target-conn", currentPath: "/usr/tmp" };
if (scenario === "non-utf8") target.filenameEncoding = "gb18030";
const key = buildCacheKey("host-1", "debian", 22, "ssh", false, "user", "sftp");
const keys = new Map([["remote-conn", key], ["target-conn", key]]);
if (scenario === "different-key") keys.set("target-conn", buildCacheKey("host-2", "debian", 22, "ssh", false, "user", "sftp"));
if (scenario === "missing-key") keys.delete("target-conn");
const ownerId = `same-host-${scenario}-4207`;
const streams: Array<{ resumable: boolean; sameHost?: boolean; parentTaskId?: string }> = [];
const copies: unknown[][] = [];
let listings = 0;
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
const restore = installGlobals({
statSftp: async (id: string) => id === "sftp-source"
? { type: "file", size: 3626, lastModified: 1758000001000 }
: null,
mkdirSftp: async () => undefined,
sameHostCopyDirectory: async (...args: unknown[]) => {
copies.push(args);
assert.equal(sftpTransferCenterStore.getTask(args[4] as string)?.resumable, false);
return { success: scenario !== "folder-fallback" };
},
startStreamTransfer: async (options: { transferId: string; resumable: boolean; sameHost?: boolean; parentTaskId?: string }) => {
streams.push(options);
assert.equal(sftpTransferCenterStore.getTask(options.transferId)?.resumable, options.resumable);
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: options.transferId,
transferred: 3626, totalBytes: 3626, lifecycleEpoch: 0,
});
return {};
},
});
function Probe() {
ops = useSftpTransfers({
ownerId,
getActivePane: (side) => side === "left" ? source : target,
getPaneByConnectionId: () => null,
getTabByConnectionId: () => null,
updateTab: () => undefined,
refresh: async () => undefined,
clearCacheForConnection: () => undefined,
handleSessionError: () => undefined,
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-source"], ["target-conn", "sftp-target"]]) },
connectionCacheKeyMapRef: { current: keys },
listLocalFiles: async () => [],
listRemoteFiles: async () => { listings++; return source.files; },
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
const results = await ops!.startTransfer(
[{ name: isDirectory ? "bt_mine" : "aops_dns_view_demo.sh", isDirectory }], "left", "right",
);
assert.equal(results[0]?.status, "completed");
});
const eligible = ["folder-cp", "folder-fallback", "file-cp"].includes(scenario);
const rows = sftpTransferCenterStore.getOwnerTasks(ownerId);
assert.ok(rows.length > 0);
assert.ok(rows.every(row => row.resumable === !eligible));
assert.equal(copies.length, isDirectory ? 1 : 0);
if (isDirectory) assert.deepEqual(copies[0]?.slice(0, 4), ["sftp-source", "/opt/bt_mine", "/usr/tmp/bt_mine", "auto"]);
assert.equal(listings, scenario === "folder-fallback" ? 1 : 0);
assert.equal(streams.length, scenario === "folder-cp" ? 0 : 1);
if (streams.length) {
assert.equal(streams[0].resumable, !eligible);
assert.equal(streams[0].sameHost, !["different-key", "missing-key"].includes(scenario) || undefined);
if (isDirectory) assert.ok(streams[0].parentTaskId);
}
} finally {
await act(async () => { renderer?.unmount(); });
for (const row of sftpTransferCenterStore.getOwnerTasks(ownerId)) sftpTransferCenterStore.dismiss(row.id);
restore();
}
});
}
+57 -5
View File
@@ -1326,6 +1326,13 @@ export const useSftpTransfers = ({
sourcePath?: string;
sourceConnectionId?: string;
targetPath?: string;
/**
* Create copies next to the originals instead of prompting for the
* same-name conflict. Each source name is resolved to the next free
* `name (copy)`, `name (copy 2)`, ... before the transfer starts.
* Used by the SFTP context menu's Duplicate action.
*/
duplicate?: boolean;
onTransferComplete?: (result: TransferResult) => void | Promise<void>;
},
) => {
@@ -1341,6 +1348,17 @@ export const useSftpTransfers = ({
const sourceConnectionId = options?.sourceConnectionId ?? sourcePane.connection.id;
const batchId = crypto.randomUUID();
const usesLegacyScp = sourcePane.connection.fileProtocol === "scp" || targetPane.connection.fileProtocol === "scp";
const sourceCacheKey = connectionCacheKeyMapRef.current.get(sourcePane.connection.id);
const targetCacheKey = connectionCacheKeyMapRef.current.get(targetPane.connection.id);
const encodingSafeForExec = [sourcePane.filenameEncoding, targetPane.filenameEncoding]
.every((encoding) => !encoding || encoding === "utf-8" || encoding === "auto");
// Select the existing non-resumable cp route only for newly created copies.
// Resume/recovery keeps its saved strategy and checkpoints. If cp fails,
// recursive/download+upload fallback also remains non-resumable.
const useSameHostCopy = !usesLegacyScp
&& !sourcePane.connection.isLocal && !targetPane.connection.isLocal
&& !!sourceCacheKey && sourceCacheKey === targetCacheKey
&& encodingSafeForExec;
const newTasks: TransferTask[] = [];
const skippedResults: TransferResult[] = [];
@@ -1429,6 +1447,10 @@ export const useSftpTransfers = ({
}
for (const file of sourceFiles) {
// "." / ".." are navigation rows, not real entries. Duplicating one
// would resolve to an ancestor (e.g. "/") and could walk the copy into
// its own output.
if (options?.duplicate && (file.name === "." || file.name === "..")) continue;
const direction: TransferDirection =
sourcePane.connection!.isLocal && !targetPane.connection!.isLocal
? "upload"
@@ -1461,8 +1483,36 @@ export const useSftpTransfers = ({
: (freshMetadata?.lastModified ?? fileEntry?.lastModified ?? 0);
const nextSourcePath = joinPath(sourcePath, file.name);
const nextTargetPath = joinPath(targetPath, file.name);
const targetIsLocal = targetPane.connection!.isLocal;
// A duplicate targets the folder the item already lives in, so the
// same-name conflict is guaranteed. Resolve the "(copy)" name up front
// instead of routing through the conflict dialog: the one-click action
// must not prompt, and resolving it inside processTransfer would
// re-enter the same task while it is still marked in flight.
const duplicateTarget = options?.duplicate
? await getDuplicateTarget(
{ fileName: file.name, isDirectory: file.isDirectory, targetPath: joinPath(targetPath, file.name) },
targetPane,
targetIsLocal ? null : (sftpSessionsRef.current.get(targetPane.connection!.id) ?? null),
targetIsLocal ? "auto" : (targetPane.filenameEncoding || "auto"),
// A queued or paused copy has not created its destination on disk
// yet, so the next duplicate would pick the same name and surface
// a conflict dialog. Reserve active destinations while naming.
(candidatePath) => Boolean(findActivePathConflict(
[...sftpTransferCenterStore.getSnapshot().tasks, ...transfersRef.current, ...newTasks],
{
id: "",
targetPath: candidatePath,
targetConnectionId: targetIsLocal ? "local" : targetPane.connection!.id,
targetHostId: targetIsLocal ? undefined : targetPane.connection!.hostId,
targetHostLabel: targetIsLocal ? "Local" : targetPane.connection!.hostLabel,
isDirectory: file.isDirectory,
},
)),
)
: null;
const nextFileName = duplicateTarget?.fileName ?? file.name;
const nextTargetPath = duplicateTarget?.targetPath ?? joinPath(targetPath, file.name);
const pathTaken = findActivePathConflict(
[...sftpTransferCenterStore.getSnapshot().tasks, ...transfersRef.current, ...newTasks],
{
@@ -1481,7 +1531,7 @@ export const useSftpTransfers = ({
const attentionTask: TransferTask = {
id: crypto.randomUUID(),
batchId,
fileName: file.name,
fileName: nextFileName,
originalFileName: file.name,
sourcePath: nextSourcePath,
targetPath: nextTargetPath,
@@ -1522,7 +1572,7 @@ export const useSftpTransfers = ({
newTasks.push({
id: taskId,
batchId,
fileName: file.name,
fileName: nextFileName,
originalFileName: file.name,
sourcePath: nextSourcePath,
targetPath: nextTargetPath,
@@ -1543,8 +1593,10 @@ export const useSftpTransfers = ({
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,
resumable: !usesLegacyScp && !useSameHostCopy,
pauseUnavailableReason: usesLegacyScp
? "This server uses legacy SCP; cancel and retry from the beginning instead"
: useSameHostCopy ? "Same-host copies cannot be paused; cancel and retry from the beginning instead" : undefined,
phase: file.isDirectory ? "scanning" : "transferring",
});
}
@@ -36,6 +36,12 @@ export interface UseSftpTransfersResult {
sourcePath?: string;
sourceConnectionId?: string;
targetPath?: string;
/**
* Create copies next to the originals instead of prompting for the
* same-name conflict. Each source name is resolved to the next free
* `name (copy)`, `name (copy 2)`, ... before the transfer starts.
*/
duplicate?: boolean;
onTransferComplete?: (result: TransferResult) => void | Promise<void>;
},
) => Promise<TransferResult[]>;
@@ -1505,6 +1505,7 @@ test("pause after terminal close works without any React owner", async () => {
await store.pause("stale-dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "stale-dir")?.status, "paused");
assert.equal(isTransferPauseLatched("stale-dir"), true);
assert.ok(pauseCalls.includes("stale-child"));
@@ -2413,6 +2414,7 @@ test("dedicated directory resume after soft-pause winds down then startFresh (no
// Soft-pause paints paused under dedicated-resume.
await store.pause("dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "dir")?.status, "paused");
// Resume must cancel soft-paused children, clear sticky latches, await wind-down, then startFresh.
@@ -2621,7 +2623,7 @@ test("async folder soft-drain does not re-pause after immediate resume", async (
// Pause returns immediately (async soft-drain).
await store.pause("dir-race");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "pausing");
// User hits resume before soft-drain finishes — full store resume (bumps epoch
// + releases latch tree), which is what the UI does.
@@ -2690,21 +2692,33 @@ test("orphan directory pause stays latched even when some children hard-miss pau
await store.pause("dir");
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
// Folder pause stays pending until the child acknowledgements settle.
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
assert.equal(dir?.status, "paused", "folder parent must paint paused without waiting on children");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-ok")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-fail")?.status, "paused");
// Soft-drain is fire-and-forget — give it a tick to hit the bridge.
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(dir?.status, "pausing");
const ownerSnapshotDuringDrain = store.getSnapshot().tasks.map((row) => ({ ...row }));
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.deepEqual(pauseCalls.sort(), ["c-fail", "c-ok"]);
// Latch-first: do not bridge-resume partial successes (that re-opened the queue).
assert.deepEqual(resumeCalls, []);
assert.equal(
store.getSnapshot().tasks.find((task) => task.id === "dir")?.status,
"paused",
"hard-miss soft-drain must not demote folder out of paused",
"pausing",
"hard miss keeps the folder latched without claiming a successful pause",
);
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
store.publishOwner("dedicated-resume", ownerSnapshotDuringDrain);
assert.equal(store.getTask("dir")?.status, "pausing");
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
store.ingestBackgroundEvent({ type: "progress", transferId: "c-fail", transferred: 25, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 25);
store.patchTask("c-fail", { transferredBytes: 50, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 50);
});
test("dedicated resume source-changed marks attention and can reset checkpoint", async () => {
+27 -11
View File
@@ -353,7 +353,22 @@ export function mergeOwnerPublishedTask(
// Only a strictly newer lifecycle epoch may re-open transferring (resume).
const incomingPaused = incoming.status === "paused" || incoming.status === "pausing";
const existingPaused = existing.status === "paused" || existing.status === "pausing";
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
// The panel can publish a snapshot from before the child acknowledgements
// arrived. Only a newer control decision may clear the folder's failure.
const rejectedFolderPause = existing.isDirectory && !existing.parentTaskId
&& existing.status === "pausing" && !!existing.pauseUnavailableReason
&& incomingLifecycleEpoch <= existingLifecycleEpoch
&& isTransferPauseLatched(existing.id);
const rejectedChildPause = parentStatus === "pausing"
&& !!existing.parentTaskId && existing.status === "transferring" && !!existing.pauseUnavailableReason;
if (rejectedFolderPause) {
merged.status = "pausing";
merged.speed = 0;
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (rejectedChildPause && incomingLifecycleEpoch <= existingLifecycleEpoch) {
merged.status = "transferring";
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
merged.status = incoming.status;
merged.speed = 0;
// Pin the visible bar while paused/latched. Soft-drain must not keep
@@ -392,6 +407,7 @@ export function mergeOwnerPublishedTask(
const parentHoldsPause = parentStatus === "paused" || parentStatus === "pausing";
if (
parentHoldsPause
&& !rejectedChildPause
&& !["completed", "cancelled", "failed"].includes(merged.status)
&& (merged.status === "transferring" || merged.status === "pending" || merged.status === "queued")
) {
@@ -1722,17 +1738,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// Soft-drain / walk progress must not move the visible bar after Pause.
// Latch or paused/pausing freezes transferredBytes/speed unless this patch
// is an explicit resume (transferring + epoch, or dedicated-resume).
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
const parent = task.parentTaskId ? tasks.find((candidate) => candidate.id === task.parentTaskId) : undefined;
const rejectedChildPause = parent?.status === "pausing" && !!parent.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const pauseHeld = !rejectedChildPause && (isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|| isTransferPauseLatched(task.id)
|| task.status === "paused"
|| task.status === "pausing"
|| (!!task.parentTaskId && (
isTransferPauseLatched(task.parentTaskId)
|| (() => {
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
return parent?.status === "paused" || parent?.status === "pausing";
})()
));
|| parent?.status === "paused"
|| parent?.status === "pausing");
if (pauseHeld && !explicitResume) {
// Keep lifecycle at paused/pausing; allow checkpoint metadata only.
if (task.status === "pausing" || task.status === "paused") {
@@ -2451,10 +2465,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
task.parentTaskId ?? task.id,
task.id,
) || isTransferPauseLatched(task.id);
const uiPauseLatched = task.status === "paused"
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|| task.status === "pausing"
|| parentHoldsPause
|| selfLatched;
|| selfLatched);
const explicitResume = lifecycleStatus === "transferring"
&& event.lifecycleEpoch !== undefined
&& incomingEpoch > currentEpoch;
@@ -0,0 +1,57 @@
import { useEffect, type RefObject } from 'react';
import { logger } from '../../lib/logger';
const closeCaptures = new Map<string, Set<() => void>>();
/** Notify owning terminals before explicit session removal, never on runtime cleanup. */
export function captureClosingTerminalSessions(sessionIds: readonly string[]): void {
for (const sessionId of new Set(sessionIds)) {
for (const capture of closeCaptures.get(sessionId) ?? []) capture();
}
}
export function useTerminalSessionCloseCapture({
sessionId,
enabled,
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture,
}: {
sessionId: string;
enabled: boolean;
hasConnectedRef: RefObject<boolean>;
terminalDataCapturedRef: RefObject<boolean>;
finalizeTerminalLogData: () => string;
onTerminalDataCapture: (
sessionId: string,
data: string,
options: { finalized: true },
) => void | Promise<void>;
}): void {
useEffect(() => {
if (!enabled) return;
const capture = () => {
// Connected terminals retain their existing drain/serialize close path.
if (hasConnectedRef.current || terminalDataCapturedRef.current) return;
try {
// A never-connected runtime is disposed synchronously on unmount.
// Finish its log now, even if empty, so persistence can set endTime.
void Promise.resolve(onTerminalDataCapture(
sessionId, finalizeTerminalLogData(), { finalized: true },
)).catch((err: unknown) => {
logger.warn('Failed to capture terminal log on session close', err);
});
} catch (err) {
logger.warn('Failed to capture terminal log on session close', err);
}
};
const captures = closeCaptures.get(sessionId) ?? new Set<() => void>();
closeCaptures.set(sessionId, captures);
captures.add(capture);
return () => {
captures.delete(capture);
if (!captures.size) closeCaptures.delete(sessionId);
};
}, [sessionId, enabled, hasConnectedRef, terminalDataCapturedRef, finalizeTerminalLogData, onTerminalDataCapture]);
}
@@ -0,0 +1,18 @@
/** Install isolated browser storage for hook tests, including Node without Web Storage. */
export function installTestLocalStorage(): () => void {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
const values = new Map<string, string>();
const storage: Storage = {
get length() { return values.size; },
clear: () => values.clear(),
getItem: key => values.get(String(key)) ?? null,
key: index => [...values.keys()][index] ?? null,
removeItem: key => { values.delete(String(key)); },
setItem: (key, value) => { values.set(String(key), String(value)); },
};
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: storage });
return () => {
if (previous) Object.defineProperty(globalThis, 'localStorage', previous);
else Reflect.deleteProperty(globalThis, 'localStorage');
};
}
+2
View File
@@ -127,6 +127,8 @@ export interface SendToCattyContext {
}
export interface SendToExternalContext {
scopeType?: 'terminal' | 'workspace' | 'global';
scopeTargetId?: string;
existingSessionId?: string;
updateExternalSessionId?: (sessionId: string, externalSessionId: string | undefined) => void;
historyMessages?: Array<{ role: 'user' | 'assistant'; content: string }>;
+2
View File
@@ -1597,6 +1597,7 @@ export function useAIState() {
previousMemberTerminalIds: readonly string[];
currentMemberTerminalIds: readonly string[];
preferredTerminalId?: string | null;
activeTargetIds?: ReadonlySet<string>;
}) => {
const currentMap =
latestAIActiveSessionMapSnapshot
@@ -1612,6 +1613,7 @@ export function useAIState() {
previousMemberTerminalIds: input.previousMemberTerminalIds,
currentMemberTerminalIds: input.currentMemberTerminalIds,
preferredTerminalId: input.preferredTerminalId,
activeTargetIds: input.activeTargetIds,
});
if (!result.changed) return;
@@ -0,0 +1,59 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { parsePluginGitHubRepository } from '@/domain/pluginGitHubRepository.cjs';
export function usePluginGitHubInstall(onInstalled: () => Promise<unknown>) {
const [preview, setPreview] = useState<NetcattyGitHubPluginPreview | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const token = useRef<string | null>(null);
const active = useRef(false);
const mounted = useRef(true);
const reset = useCallback(() => {
const previous = token.current;
token.current = null;
setPreview(null);
setError(null);
if (previous) void netcattyBridge.get()?.discardGitHubPlugin?.(previous).catch(() => {});
}, []);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
if (token.current) void netcattyBridge.get()?.discardGitHubPlugin?.(token.current).catch(() => {});
};
}, []);
const run = async (operation: () => Promise<void>) => {
if (active.current) return;
active.current = true;
setBusy(true);
setError(null);
try { await operation(); }
catch (cause) { if (mounted.current) setError(cause instanceof Error ? cause.message : String(cause)); }
finally { active.current = false; if (mounted.current) setBusy(false); }
};
return {
preview, busy, error, reset,
prepare: (input: string) => run(async () => {
const { origin } = parsePluginGitHubRepository(input);
const bridge = netcattyBridge.require();
if (!bridge.prepareGitHubPlugin) throw new Error('GitHub plugin installation unavailable');
reset();
const result = await bridge.prepareGitHubPlugin(origin);
if (!mounted.current) { await bridge.discardGitHubPlugin?.(result.token); return; }
token.current = result.token;
setPreview(result);
}),
install: () => run(async () => {
const bridge = netcattyBridge.require();
if (!bridge.installGitHubPlugin || !token.current) throw new Error('Download and review a GitHub plugin first');
const selected = token.current;
// The host consumes the selection even on failure; retry starts with a new review.
token.current = null;
setPreview(null);
await bridge.installGitHubPlugin(selected);
await onInstalled();
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
}),
};
}
@@ -4,6 +4,9 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { useSessionState } from "./useSessionState.ts";
import { installTestLocalStorage } from "./testSupport/localStorage.ts";
test.beforeEach((t) => { t.after(installTestLocalStorage()); });
type SessionState = ReturnType<typeof useSessionState>;
@@ -4,6 +4,9 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { useSessionState } from "./useSessionState.ts";
import { installTestLocalStorage } from "./testSupport/localStorage.ts";
test.beforeEach((t) => { t.after(installTestLocalStorage()); });
type SessionState = ReturnType<typeof useSessionState>;
@@ -86,6 +89,15 @@ test("global broadcast availability follows visible orphan session count", async
await act(async () => {
current().removeSessionFromWorkspace(second.id);
});
// The one-member workspace stays intact; only the detached terminal is
// an orphan, so global broadcast remains unavailable until another opens.
assert.equal(current().workspaces.length, 1);
assert.equal(current().sessions.find(session => session.id === first.id)?.workspaceId, current().workspaces[0].id);
assert.deepEqual(current().orphanSessions.map(session => session.id), [second.id]);
assert.equal(current().canUseGlobalBroadcast, false);
assert.equal(current().isGlobalBroadcastEnabled, false);
await act(async () => { current().createLocalTerminal({ shellName: "04" }); });
assert.equal(current().orphanSessions.length, 2);
assert.equal(current().canUseGlobalBroadcast, true);
assert.equal(current().isGlobalBroadcastEnabled, false);
} finally {
@@ -0,0 +1,92 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { Workspace } from '../../domain/models';
import { collectSessionIds } from '../../domain/workspace';
import { moveWorkspacePaneInWorkspaces } from './useSessionState';
// Issue #4037: moving a member pane must rearrange only the tree shape.
// Session ids, workspace id, anchorChatId (AI binding), focus fields and tab
// order all live outside the touched surface, and these tests pin that.
const workspace = (id = 'ws-1'): Workspace => ({
id,
title: 'Workspace',
focusedSessionId: 's1',
focusSessionOrder: ['s1', 's2', 's3'],
anchorChatId: 'chat-anchor-1',
root: {
id: 'split-1',
type: 'split',
direction: 'vertical',
children: [
{ id: 'pane-1', type: 'pane', sessionId: 's1' },
{ id: 'pane-2', type: 'pane', sessionId: 's2' },
{ id: 'pane-3', type: 'pane', sessionId: 's3' },
],
sizes: [1, 1, 1],
},
});
test('moveWorkspacePaneInWorkspaces rearranges the tree and preserves every identity field', () => {
const ws = workspace();
const next = moveWorkspacePaneInWorkspaces([ws], 'ws-1', 's3', {
direction: 'vertical',
position: 'left',
targetSessionId: 's1',
});
assert.equal(next.length, 1);
const moved = next[0];
assert.equal(moved.id, ws.id, 'workspace id (AI binding key) unchanged');
assert.equal(moved.title, ws.title);
assert.equal(moved.anchorChatId, 'chat-anchor-1', 'anchorChatId unchanged');
assert.equal(moved.focusedSessionId, 's1', 'focus stays on the same session id');
assert.deepEqual(moved.focusSessionOrder, ['s1', 's2', 's3'], 'tab/focus order unchanged');
assert.deepEqual(collectSessionIds(moved.root), ['s3', 's1', 's2']);
assert.notEqual(moved.root, ws.root, 'the tree shape actually changed');
});
test('moveWorkspacePaneInWorkspaces leaves other workspaces and no-op cases untouched', () => {
const ws1 = workspace('ws-1');
const ws2 = workspace('ws-2');
// Same-reference no-op: pane dropped onto itself.
const selfDrop = moveWorkspacePaneInWorkspaces([ws1, ws2], 'ws-1', 's2', {
direction: 'vertical',
position: 'left',
targetSessionId: 's2',
});
assert.equal(selfDrop[0], ws1, 'no-op workspace keeps its reference');
assert.equal(selfDrop[1], ws2);
// Unknown session / foreign workspace id: nothing moves.
const ghost = moveWorkspacePaneInWorkspaces([ws1, ws2], 'ws-1', 'ghost', {
direction: 'vertical',
position: 'left',
targetSessionId: 's1',
});
assert.equal(ghost[0], ws1);
assert.equal(ghost[1], ws2);
const foreign = moveWorkspacePaneInWorkspaces([ws1, ws2], 'ws-other', 's1', {
direction: 'vertical',
position: 'left',
targetSessionId: 's2',
});
assert.equal(foreign[0], ws1);
assert.equal(foreign[1], ws2);
});
test('moveWorkspacePaneInWorkspaces only rewrites the targeted workspace entry', () => {
const ws1 = workspace('ws-1');
const ws2 = workspace('ws-2');
const next = moveWorkspacePaneInWorkspaces([ws1, ws2], 'ws-2', 's2', {
direction: 'vertical',
position: 'right',
targetSessionId: 's3',
});
assert.equal(next[0], ws1, 'sibling workspaces keep their references');
assert.notEqual(next[1], ws2);
assert.deepEqual(collectSessionIds(next[1].root), ['s1', 's3', 's2']);
});
+71 -8
View File
@@ -19,6 +19,7 @@ createWorkspaceFromSessionIds,
FocusDirection,
getNextFocusSessionId,
insertPaneIntoWorkspace,
movePaneInWorkspace,
pruneWorkspaceNode,
reorderWorkspaceFocusSessionOrder,
setWorkspaceFocusedSessionId,
@@ -42,8 +43,9 @@ import {
import {
closeSessionsState,
detachSessionFromWorkspaceState,
replaceDissolvedWorkspaceTabOrder,
} from './sessionWorkspaceDetach';
import { getAISessionsSnapshot } from './aiSessionsStore';
import { getPersistedAiSessionsSnapshot } from './aiStateSnapshots';
import {
createCopiedTerminalSessionClone,
createSplitTerminalSessionClone,
@@ -73,6 +75,7 @@ import {
getSessionConnectionLabel,
} from '../../domain/sessionTabTitle';
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import { useVaultSnapshotField } from './vaultSnapshotStore';
@@ -122,6 +125,26 @@ export function appendWorkspaceRootPaneIfMissing(
});
}
/**
* Issue #4037: rearrange an existing member pane within its own workspace.
* Only `workspaces[].root` shape changes — session ids, tab order, focus
* fields and every AI binding (anchorChatId / activeSessionIdMap scopes) are
* untouched, because the moved session keeps its id and its workspaceId.
*/
export function moveWorkspacePaneInWorkspaces(
workspaces: Workspace[],
workspaceId: string,
sessionId: string,
hint: SplitHint,
): Workspace[] {
return workspaces.map(ws => {
if (ws.id !== workspaceId) return ws;
if (!collectSessionIds(ws.root).includes(sessionId)) return ws;
const nextRoot = movePaneInWorkspace(ws.root, sessionId, hint);
return nextRoot === ws.root ? ws : { ...ws, root: nextRoot };
});
}
export function insertCopiedTabOrderIdOnce(
prevTabOrder: string[],
sourceTabId: string,
@@ -581,6 +604,7 @@ export const useSessionState = ({
const closedIds = sessionsRef.current
.filter(session => session.workspaceId === workspaceId)
.map(session => session.id);
captureClosingTerminalSessions(closedIds);
cleanupClosedTerminalSessions(closedIds);
for (const sessionId of closedIds) {
sessionPresentationStore.clearSession(sessionId);
@@ -604,6 +628,7 @@ export const useSessionState = ({
}, [setActiveTabId]);
const closeSessions = useCallback((sessionIds: string[]) => {
captureClosingTerminalSessions(sessionIds);
cleanupClosedTerminalSessions(sessionIds);
for (const sessionId of sessionIds) {
sessionPresentationStore.clearSession(sessionId);
@@ -615,6 +640,11 @@ export const useSessionState = ({
currentActiveTabId: activeTabStore.getActiveTabId(),
preferredTabId: activeTabStore.getPreviousActiveTabId(),
tabOrder: tabOrderRef.current,
// AI chat recency decides which surviving member receives focus/anchor
// after member loss (#4098 phase 2); hot store first, persisted fallback.
aiSessions: getAISessionsSnapshot().sessions.length > 0
? getAISessionsSnapshot().sessions
: getPersistedAiSessionsSnapshot(),
});
setWorkspaces(result.workspaces);
@@ -822,6 +852,20 @@ export const useSessionState = ({
});
}, [setActiveTabId]);
// Issue #4037: drop an existing member pane back into its own workspace to
// rearrange it. Deliberately touches nothing but the pane tree: no session
// fields, no tab order, no focus changes (focusedSessionId keeps pointing
// at the same session id, so focus visually follows the moved pane), and
// no AI state — the anchorChatId lives on the workspace, which keeps its id.
const moveWorkspacePane = useCallback((
workspaceId: string,
sessionId: string,
hint: SplitHint
) => {
if (!hint) return;
setWorkspaces(prev => moveWorkspacePaneInWorkspaces(prev, workspaceId, sessionId, hint));
}, []);
// Merge two tabs into one workspace. When one of them already belongs to a
// workspace, that workspace (and its id) is reused instead of dissolving
// and recreating: the id is what workspace-scoped AI chats bind to, so
@@ -1106,6 +1150,25 @@ export const useSessionState = ({
setWorkspaces(prev => setWorkspaceFocusedSessionId(prev, workspaceId, sessionId));
}, []);
// Issue #4098 phase 2: pin the AI chat a workspace scope is anchored to.
// Written by the AI side panel when a chat becomes active in the workspace
// scope; consumed by the non-positional fallbacks and persisted to the
// session restore snapshot.
const setWorkspaceAnchorChat = useCallback((workspaceId: string, chatId: string | null) => {
setWorkspaces(prev => {
const index = prev.findIndex(ws => ws.id === workspaceId);
if (index < 0) return prev;
if (prev[index].anchorChatId === (chatId ?? undefined)) return prev;
const next = prev.slice();
next[index] = chatId
? { ...prev[index], anchorChatId: chatId }
: Object.fromEntries(
Object.entries(prev[index]).filter(([key]) => key !== 'anchorChatId'),
) as Workspace;
return next;
});
}, []);
const reorderWorkspaceSessions = useCallback((
workspaceId: string,
draggedSessionId: string,
@@ -1435,18 +1498,16 @@ export const useSessionState = ({
sessions: sessionsRef.current,
workspaces: workspacesRef.current,
sessionId,
aiSessions: getAISessionsSnapshot().sessions.length > 0
? getAISessionsSnapshot().sessions
: getPersistedAiSessionsSnapshot(),
});
if (!result.changed) return;
setWorkspaces(result.workspaces);
setSessions(result.sessions);
setTabOrder((prevTabOrder) => {
const replacedOrder = replaceDissolvedWorkspaceTabOrder(
prevTabOrder,
result.dissolvedWorkspaceId,
result.replacementTabIds,
);
if (!tabInsertionTarget) return replacedOrder;
if (!tabInsertionTarget) return prevTabOrder;
const allTabIds = [
...result.sessions.filter((s) => !s.workspaceId).map((s) => s.id),
@@ -1455,7 +1516,7 @@ export const useSessionState = ({
...(tabInsertionTarget.additionalTabIds ?? []),
];
return reorderWorkTabIds(
replacedOrder,
prevTabOrder,
allTabIds,
sessionId,
tabInsertionTarget.tabId,
@@ -1515,6 +1576,7 @@ export const useSessionState = ({
createWorkspaceFromTargets,
createWorkspaceFromSessions,
addSessionToWorkspace,
moveWorkspacePane,
removeSessionFromWorkspace,
appendHostToWorkspace,
appendHostToWorkspaceConfirmed,
@@ -1523,6 +1585,7 @@ export const useSessionState = ({
splitSession,
toggleWorkspaceViewMode,
setWorkspaceFocusedSession,
setWorkspaceAnchorChat,
reorderWorkspaceSessions,
moveFocusInWorkspace,
runSnippet,
@@ -4,6 +4,10 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { useSessionState } from "./useSessionState.ts";
import { installTestLocalStorage } from "./testSupport/localStorage.ts";
import { collectSessionIds } from "../../domain/workspace.ts";
test.beforeEach((t) => { t.after(installTestLocalStorage()); });
type SessionState = ReturnType<typeof useSessionState>;
@@ -121,6 +125,15 @@ test("merged tab titles follow the workspace lifecycle until the user renames it
assert.equal(workspace(workspaceId).title, "Pinned");
assert.equal(workspace(workspaceId).generatedTitle, false);
await act(async () => { current().closeSession(firstSessionId); });
assert.equal(workspace(workspaceId).title, "Pinned");
assert.deepEqual(collectSessionIds(workspace(workspaceId).root), [secondSessionId]);
assert.equal(current().sessions.find(session => session.id === secondSessionId)?.workspaceId, workspaceId);
await act(async () => { current().closeSession(secondSessionId); });
assert.equal(workspace(workspaceId).title, "Pinned");
assert.equal(workspace(workspaceId).generatedTitle, false);
assert.deepEqual(collectSessionIds(workspace(workspaceId).root), []);
let leftBaseSessionId = "";
let leftJoiningSessionId = "";
await act(async () => {
+48 -9
View File
@@ -50,6 +50,7 @@ import {
tryBeginSendForKey,
} from './ai/draftSendGate';
import { draftsByScopeEqualIgnoringComposerText, selectDraftForAgentSwitch } from '../application/state/aiDraftState';
import { latestAIActiveSessionMapSnapshot, latestAISessionsSnapshot } from '../application/state/aiStateSnapshots';
import { sanitizeContextWindow } from '../infrastructure/ai/contextCompaction';
import {
buildPromptWithTerminalSelectionAttachments,
@@ -316,6 +317,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
scopeHostIds,
scopeLabel,
focusedSessionId,
onSetWorkspaceAnchorChat,
workspaces = [],
terminalSessions = [],
liveScopeTargetIds,
@@ -444,9 +446,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
preferredTerminalId: focusedSessionId,
visibleSessionIds: visibleHistorySessionIds,
});
// Issue #4098 phase 2: this workspace's anchored chat — used by the panel
// view resolver before any positional fallback could apply.
const workspaceAnchorChatId = scopeType === 'workspace'
? workspaces.find((workspace) => workspace.id === scopeTargetId)?.anchorChatId
: undefined;
// getScopedHistorySessions orders by scope match first, recency second.
const preferredHistorySessionId = historySessions[0]?.id ?? null;
const normalizedPanelView = useMemo<AIPanelView>(
() => resolveDisplayedPanelView(explicitPanelView, currentDraft != null, historySessions, persistedSessionId, scopeType),
[explicitPanelView, currentDraft, historySessions, persistedSessionId, scopeType],
() => resolveDisplayedPanelView(explicitPanelView, currentDraft != null, historySessions, persistedSessionId, scopeType, workspaceAnchorChatId, preferredHistorySessionId),
[explicitPanelView, currentDraft, historySessions, persistedSessionId, scopeType, workspaceAnchorChatId, preferredHistorySessionId],
);
const activeSession = useMemo(
() => resolveDisplayedSession(normalizedPanelView, historySessions),
@@ -641,6 +650,21 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}, { initialDelayMs: 250 });
}, [isVisible, terminalSessions, activeSessionId]);
// Workspace maintenance can retarget an inherited chat earlier in this same
// passive-effect flush. Before clearing a selection, recheck its membership
// against the synchronous snapshot instead of this render's old history.
const isSessionVisibleInCurrentScope = useCallback((sessionId: string) => (
getScopedHistorySessions(
latestAISessionsSnapshot ?? sessions,
scopeType,
scopeTargetId,
scopeHostIds,
activeTerminalSessionIds,
workspaceMemberTerminalIds,
latestAIActiveSessionMapSnapshot ?? activeSessionIdMap,
).some((session) => session.id === sessionId)
), [sessions, scopeType, scopeTargetId, scopeHostIds, activeTerminalSessionIds, workspaceMemberTerminalIds, activeSessionIdMap]);
useEffect(() => {
if (!isVisible) return;
// Predicate must match normalizePanelView's list (scoped history), not the
@@ -648,16 +672,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
if (!shouldForceDraftViewSync(
explicitPanelView,
normalizedPanelView,
(sessionId) => historySessions.some((session) => session.id === sessionId),
isSessionVisibleInCurrentScope,
)) {
return;
}
showDraftView(scopeKey);
}, [isVisible, normalizedPanelView, explicitPanelView, scopeKey, historySessions, showDraftView]);
}, [isVisible, normalizedPanelView, explicitPanelView, scopeKey, isSessionVisibleInCurrentScope, showDraftView]);
useEffect(() => {
if (!activeSession) return;
// Issue #4098 phase 2: a chat becoming active in the workspace scope pins
// the workspace's anchorChatId so member loss / restart resolve by id,
// never by position.
if (scopeType === 'workspace' && scopeTargetId && isVisible) {
onSetWorkspaceAnchorChat?.(scopeTargetId, activeSession.id);
}
if (isVisible && activeSessionIdMap[scopeKey] !== activeSession.id) {
setActiveSessionId(activeSession.id);
}
@@ -665,18 +696,24 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
activeSession,
activeSessionIdMap,
scopeKey,
scopeType,
scopeTargetId,
isVisible,
onSetWorkspaceAnchorChat,
setActiveSessionId,
]);
useEffect(() => {
if (!isVisible) return;
if (normalizedPanelView.mode !== 'draft') return;
// Keep ownership while an explicit session is still displayable in this
// scope (normalize has not demoted it). Out-of-scope / missing ids clear.
// Keep a selection that maintenance just made displayable, but always
// honor an explicit New Chat draft. Out-of-scope / missing ids still clear.
const selectedSessionId = explicitPanelView?.mode === 'session'
? explicitPanelView.sessionId : persistedSessionId;
if (
explicitPanelView?.mode === 'session'
&& historySessions.some((session) => session.id === explicitPanelView.sessionId)
explicitPanelView?.mode !== 'draft'
&& selectedSessionId
&& isSessionVisibleInCurrentScope(selectedSessionId)
) {
return;
}
@@ -686,7 +723,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
isVisible,
normalizedPanelView.mode,
explicitPanelView,
historySessions,
isSessionVisibleInCurrentScope,
persistedSessionId,
setActiveSessionId,
]);
@@ -1788,6 +1825,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
try {
const existingExternalSessionId = currentSession?.externalSessionId;
await sendToExternalAgent(sessionId, assistantMsgId, modelPrompt, agentConfig, abortController, modelAttachments, {
scopeType,
scopeTargetId,
existingSessionId: existingExternalSessionId,
updateExternalSessionId: updateSessionExternalSessionId,
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
+4 -2
View File
@@ -109,8 +109,10 @@ export interface AIChatSidePanelProps {
scopeLabel?: string;
/** Workspace focused pane; preferred when inheriting AI chat after merge. */
focusedSessionId?: string;
/** Live workspaces, used to resolve workspace titles for `/chats`. */
workspaces?: Array<{ id: string; title: string }>;
/** Issue #4098 phase 2: pin the AI chat a workspace scope is anchored to. */
onSetWorkspaceAnchorChat?: (workspaceId: string, chatId: string | null) => void;
/** Live workspaces (with their anchor chat), used for scope titles and anchor resolution. */
workspaces?: Array<{ id: string; title: string; anchorChatId?: string }>;
/** All currently live terminal (and workspace) scope target ids. */
liveScopeTargetIds?: Set<string>;
+8 -5
View File
@@ -436,7 +436,7 @@ function TransferRow({
task: TransferTask;
children: TransferTask[];
} | null>(null);
if (task.status === "pausing") {
if (task.status === "pausing" && !task.pauseUnavailableReason) {
if (!pausingSnapshotRef.current) {
pausingSnapshotRef.current = {
task: { ...task },
@@ -464,20 +464,23 @@ function TransferRow({
&& !task.error;
const sharedResuming = useSftpTransferResuming(task.id);
const isResuming = sharedResuming || storeResuming;
const canPause = task.resumable !== false && task.status === "transferring" && canControl && !isResuming;
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
// Orphaned tasks after app restart (interrupted / attention / paused without a
// live panel owner) must still expose resume/cancel from the global center.
// Conflict rows must use resolveConflict — Resume would overwrite blindly.
// Non-resumable attention rows (e.g. duplicate-destination refusals) are
// terminal: resuming them would start a second writer on the same path.
// Do not show Resume during soft-drain "pausing" — play + spinner together
// makes the row twitch as buttons appear/disappear mid-drain.
// makes the row twitch as buttons appear/disappear mid-drain. A settled
// partial failure is different: offer Retry Pause and explicit Resume.
const canResume = !isResuming && !task.conflict && (
["paused", "interrupted"].includes(task.status)
|| (pauseFailed && task.resumable !== false)
|| (task.status === "attention" && task.resumable !== false)
|| (task.status === "failed" && task.resumable !== false && (task.checkpointBytes ?? 0) > 0)
) && canControl;
const isPausing = task.status === "pausing";
const isPausing = task.status === "pausing" && !pauseFailed;
const canCancel = ["pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention"].includes(task.status) && canControl;
const canRetry = task.status === "failed" && task.retryable !== false && canControl;
const isTerminal = ["completed", "failed", "cancelled"].includes(task.status);
@@ -577,7 +580,7 @@ function TransferRow({
<Pause size={13} />
</TransferAction>
)}
{task.status === "pausing" && (
{task.status === "pausing" && !pauseFailed && (
<div className="flex h-8 w-8 items-center justify-center" role="status" aria-label={t("sftp.transferCenter.status.pausing")}>
<Loader2 size={13} className="animate-spin text-amber-500" />
</div>
+19 -4
View File
@@ -49,11 +49,13 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
showAlgorithmOverrides,
setShowAlgorithmOverrides,
chainedHosts,
hostChainInherited = false,
setActiveSubPanel,
clearHostChain,
proxySummaryType,
proxySummaryLabel,
proxySummaryTooltip,
proxyInherited = false,
clearProxyConfig,
}) => {
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
@@ -641,9 +643,16 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
title={t("hostDetails.jumpHosts")}
action={
chainedHosts.length > 0 ? (
<Badge variant="secondary" className="text-xs">
{t("hostDetails.jumpHosts.hops", { count: chainedHosts.length })}
</Badge>
<div className="flex items-center gap-1">
{hostChainInherited && (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("vault.groups.details.inherited")}
</Badge>
)}
<Badge variant="secondary" className="text-xs">
{t("hostDetails.jumpHosts.hops", { count: chainedHosts.length })}
</Badge>
</div>
) : (
<Badge variant="outline" className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.direct")}
@@ -664,8 +673,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
/>
<span className="text-xs text-muted-foreground">
{t("hostDetails.jumpHosts.hops", { count: chainedHosts.length })}
{hostChainInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</div>
{!hostChainInherited && (
<X
size={14}
className="text-muted-foreground hover:text-destructive flex-shrink-0"
@@ -674,6 +685,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
clearHostChain();
}}
/>
)}
</div>
<div className="w-full space-y-1 pl-5">
{chainedHosts.slice(0, 5).map((h, idx) => (
@@ -735,7 +747,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
<X size={14} />
</Button>
</div>
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId ? (
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId || proxyInherited ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<button
type="button"
@@ -750,6 +762,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
<TooltipTrigger asChild>
<span className="block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{proxySummaryLabel}
{proxyInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</TooltipTrigger>
<TooltipContent side="bottom" align="start" className="max-w-xs break-all">
@@ -758,6 +771,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Tooltip>
</TooltipProvider>
</button>
{!proxyInherited && (
<Button
type="button"
variant="ghost"
@@ -768,6 +782,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<X size={14} />
</Button>
)}
</div>
) : (
<Button
+67
View File
@@ -1,4 +1,5 @@
import type { GroupConfig } from "../domain/models";
import { applyGroupDefaults } from "../domain/groupConfig";
import {
findProxyProfile,
hasIncompleteProxyIdentity,
@@ -157,3 +158,69 @@ export const prepareProxyConfigForSave = (params: {
normalizedProxyConfig: normalizeManualProxyConfig(params.proxyConfig),
};
};
export const EMPTY_CUSTOM_PROXY_DRAFT: ProxyConfig = { type: "http", host: "", port: 8080 };
export const resolveDisplayProxyProfileId = (
form: Pick<Host, "directProxy" | "proxyProfileId" | "proxyConfig">,
inheritedProfileId?: string,
): string | undefined => {
if (form.directProxy || form.proxyConfig !== undefined) return form.proxyProfileId;
return form.proxyProfileId ?? inheritedProfileId;
};
export const nextFormAfterSelectProxyProfile = (
prev: Host,
profileId: string | undefined,
groupDefaults?: Partial<GroupConfig>,
): Host => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) {
const inheritedConfig = !prev.directProxy
&& prev.proxyProfileId === undefined
&& prev.proxyConfig === undefined
&& groupDefaults
? applyGroupDefaults(prev, groupDefaults).proxyConfig
: undefined;
return {
...rest,
proxyConfig: prev.proxyConfig ?? inheritedConfig ?? EMPTY_CUSTOM_PROXY_DRAFT,
} as Host;
}
return { ...rest, proxyProfileId: profileId } as Host;
};
export const resolveFormHostChainIds = (
host: Host,
groupDefaults?: Partial<GroupConfig>,
): string[] => {
if (host.hostChain !== undefined) return host.hostChain.hostIds || [];
if (!groupDefaults) return [];
return applyGroupDefaults(host, groupDefaults).hostChain?.hostIds || [];
};
export const nextFormAfterClearHostChain = (
prev: Host,
groupDefaults?: Partial<GroupConfig>,
): Host => {
const groupWouldRestore = Boolean(
groupDefaults
&& applyGroupDefaults({ ...prev, hostChain: undefined }, groupDefaults).hostChain?.hostIds?.length,
);
if (prev.hostChain === undefined || groupWouldRestore) {
return { ...prev, hostChain: { hostIds: [] } };
}
const { hostChain: _hostChain, ...rest } = prev;
return rest as Host;
};
export const nextFormAfterRemoveHostFromChain = (
prev: Host,
index: number,
groupDefaults?: Partial<GroupConfig>,
): Host => {
const ids = resolveFormHostChainIds(prev, groupDefaults).filter((_, i) => i !== index);
if (ids.length > 0) return { ...prev, hostChain: { hostIds: ids } };
return nextFormAfterClearHostChain(prev, groupDefaults);
};
@@ -6,12 +6,17 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { Host, Identity } from "../types.ts";
import HostDetailsPanel, { parseOptionalPortInput } from "./HostDetailsPanel.tsx";
import { applyGroupDefaults } from "../domain/groupConfig.ts";
import {
prepareProxyConfigForSave,
prepareTelnetCredentialsForSave,
resolvePrimaryProtocolSavePort,
resolvePrimaryProtocolSwitchPort,
validateProxyConfigForSave,
nextFormAfterSelectProxyProfile,
nextFormAfterClearHostChain,
nextFormAfterRemoveHostFromChain,
resolveDisplayProxyProfileId,
} from "./HostDetailsPanel.helpers.ts";
import { TooltipProvider } from "./ui/tooltip.tsx";
@@ -549,3 +554,198 @@ test("HostDetailsPanel expands notes when the host already has notes", () => {
"expected notes to render after connection settings",
);
});
const networkSshHost: Host = {
...hostWithMissingProxyProfile,
proxyProfileId: undefined,
group: "network",
};
const jumpHost: Host = {
id: "jump-1",
label: "Bastion",
hostname: "bastion.example.com",
username: "root",
tags: [],
os: "linux",
port: 22,
protocol: "ssh",
authMethod: "password",
createdAt: 1,
};
const hostOwnedJump: Host = {
...jumpHost,
id: "jump-host",
label: "Edge",
hostname: "edge.example.com",
};
const renderHostDetailsWithGroup = (
initialData: Host,
groupConfig: Record<string, unknown>,
extraHosts: Host[] = [],
) =>
renderToStaticMarkup(
React.createElement(
I18nProvider,
{ locale: "en" },
React.createElement(
TooltipProvider,
null,
React.createElement(HostDetailsPanel, {
initialData,
availableKeys: [],
identities: [],
proxyProfiles: [],
groups: ["network"],
managedSources: [],
allTags: [],
allHosts: extraHosts,
terminalThemeId: "default",
terminalFontSize: 14,
groupConfigs: [{ path: "network", ...groupConfig }],
onSave: () => {},
onCancel: () => {},
}),
),
),
);
test("HostDetailsPanel displays inherited group HTTP proxy", () => {
const markup = renderHostDetailsWithGroup(networkSshHost, {
proxyConfig: { type: "http", host: "group-proxy.example.com", port: 8080 },
});
assert.match(markup, /group-proxy\.example\.com/);
assert.match(markup, /Inherited from group/);
});
test("HostDetailsPanel host proxy override wins over the group proxy", () => {
const markup = renderHostDetailsWithGroup({
...networkSshHost,
proxyConfig: { type: "http", host: "host-proxy.example.com", port: 9090 },
}, {
proxyConfig: { type: "http", host: "group-proxy.example.com", port: 8080 },
});
assert.match(markup, /host-proxy\.example\.com/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel direct proxy hides inherited group proxy", () => {
const markup = renderHostDetailsWithGroup({
...networkSshHost,
directProxy: true,
}, {
proxyConfig: { type: "http", host: "group-proxy.example.com", port: 8080 },
});
assert.match(markup, /Direct \(no proxy\)/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
});
test("HostDetailsPanel displays inherited group jump hosts", () => {
const markup = renderHostDetailsWithGroup(networkSshHost, {
hostChain: { hostIds: ["jump-1"] },
}, [jumpHost]);
assert.match(markup, /bastion\.example\.com/);
assert.match(markup, /Inherited from group/);
});
test("HostDetailsPanel host jump-host override wins over the group chain", () => {
const markup = renderHostDetailsWithGroup({
...networkSshHost,
hostChain: { hostIds: ["jump-host"] },
}, {
hostChain: { hostIds: ["jump-1"] },
}, [jumpHost, hostOwnedJump]);
assert.match(markup, /edge\.example\.com/);
assert.doesNotMatch(markup, /bastion\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("selecting Custom while inheriting a saved proxy keeps a custom draft instead of the profile", () => {
const group = { proxyProfileId: "office-proxy" };
const next = nextFormAfterSelectProxyProfile(networkSshHost, undefined, group);
assert.equal(next.proxyProfileId, undefined);
assert.equal(next.directProxy, undefined);
assert.deepEqual(next.proxyConfig, { type: "http", host: "", port: 8080 });
assert.equal(resolveDisplayProxyProfileId(next, "office-proxy"), undefined);
assert.equal(applyGroupDefaults(next, group).proxyProfileId, undefined);
});
test("removing the last hop of a multi-hop inherited chain keeps an empty override", () => {
const group = { hostChain: { hostIds: ["jump-1", "jump-host"] } };
const afterFirst = nextFormAfterRemoveHostFromChain(networkSshHost, 0, group);
assert.deepEqual(afterFirst.hostChain, { hostIds: ["jump-host"] });
const afterLast = nextFormAfterRemoveHostFromChain(afterFirst, 0, group);
assert.deepEqual(afterLast.hostChain, { hostIds: [] });
assert.deepEqual(applyGroupDefaults(afterLast, group).hostChain, { hostIds: [] });
});
test("clearing an inherited-only chain keeps an empty override instead of restoring group hops", () => {
const group = { hostChain: { hostIds: ["jump-1", "jump-host"] } };
const cleared = nextFormAfterClearHostChain(networkSshHost, group);
assert.deepEqual(cleared.hostChain, { hostIds: [] });
assert.deepEqual(applyGroupDefaults(cleared, group).hostChain, { hostIds: [] });
});
test("HostDetailsPanel custom proxy draft hides the inherited saved proxy", () => {
const markup = renderToStaticMarkup(
React.createElement(
I18nProvider,
{ locale: "en" },
React.createElement(
TooltipProvider,
null,
React.createElement(HostDetailsPanel, {
initialData: {
...networkSshHost,
proxyConfig: { type: "http", host: "", port: 8080 },
},
availableKeys: [],
identities: [],
proxyProfiles: [{
id: "office-proxy",
label: "Office Proxy",
config: { type: "http", host: "office-proxy.example.com", port: 8080 },
createdAt: 1,
}],
groups: ["network"],
managedSources: [],
allTags: [],
allHosts: [],
terminalThemeId: "default",
terminalFontSize: 14,
groupConfigs: [{ path: "network", proxyProfileId: "office-proxy" }],
onSave: () => {},
onCancel: () => {},
}),
),
),
);
assert.doesNotMatch(markup, /Office Proxy/);
assert.doesNotMatch(markup, /office-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel empty jump-host override hides the inherited group chain", () => {
const markup = renderHostDetailsWithGroup({
...networkSshHost,
hostChain: { hostIds: [] },
}, {
hostChain: { hostIds: ["jump-1", "jump-host"] },
}, [jumpHost, hostOwnedJump]);
assert.doesNotMatch(markup, /bastion\.example\.com/);
assert.doesNotMatch(markup, /edge\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
+52 -31
View File
@@ -55,6 +55,11 @@ import {
resolvePrimaryProtocolSwitchPort,
prepareTelnetCredentialsForSave,
prepareProxyConfigForSave,
nextFormAfterSelectProxyProfile,
nextFormAfterClearHostChain,
nextFormAfterRemoveHostFromChain,
resolveFormHostChainIds,
resolveDisplayProxyProfileId,
} from "./HostDetailsPanel.helpers";
export { parseOptionalPortInput } from "./HostDetailsPanel.helpers";
import { TerminalEncodingSelect } from "./TerminalEncodingSelect";
@@ -424,24 +429,34 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const effectiveFormDistro = getEffectiveHostDistro(form);
const hasHostProxyOverride = form.directProxy === true
|| form.proxyProfileId !== undefined
|| form.proxyConfig !== undefined;
const displayProxyProfileId = resolveDisplayProxyProfileId(form, effectiveAuthHost.proxyProfileId);
const displayProxyConfig = form.directProxy
? undefined
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
const selectedProxyProfile = useMemo(
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
[form.proxyProfileId, proxyProfiles],
() => proxyProfiles.find((profile) => profile.id === displayProxyProfileId),
[displayProxyProfileId, proxyProfiles],
);
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
) && Boolean(effectiveGroupDefaults?.proxyProfileId || effectiveGroupDefaults?.proxyConfig);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
: formatProxyConfigType(selectedProxyProfile?.config || displayProxyConfig) || "HTTP";
const proxySummaryLabel = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
: formatProxyConfigEndpoint(displayProxyConfig);
const proxySummaryTooltip = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
: `${formatProxyConfigType(displayProxyConfig)} ${formatProxyConfigEndpoint(displayProxyConfig)}`;
const handleDistroModeChange = useCallback((mode: "auto" | "manual") => {
setForm((prev) => ({
@@ -458,13 +473,19 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
setForm((prev) => {
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
const inheritedConfig = !prev.directProxy
&& prev.proxyProfileId === undefined
&& prev.proxyConfig === undefined
&& effectiveGroupDefaults
? applyGroupDefaults(prev, effectiveGroupDefaults).proxyConfig
: undefined;
return {
...rest,
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
proxyConfig: updateProxyConfigField(prev.proxyConfig ?? inheritedConfig, field, value),
} as Host;
});
},
[],
[effectiveGroupDefaults],
);
const clearProxyConfig = useCallback(() => {
@@ -475,12 +496,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}, []);
const selectProxyProfile = useCallback((profileId: string | undefined) => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) return rest as Host;
return { ...rest, proxyProfileId: profileId } as Host;
});
}, []);
setForm((prev) => nextFormAfterSelectProxyProfile(prev, profileId, effectiveGroupDefaults));
}, [effectiveGroupDefaults]);
const selectDirectProxy = useCallback(() => {
setForm((prev) => {
@@ -493,24 +510,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setForm((prev) => ({
...prev,
hostChain: {
hostIds: [...(prev.hostChain?.hostIds || []), hostId],
hostIds: [...resolveFormHostChainIds(prev, effectiveGroupDefaults), hostId],
},
}));
};
const removeHostFromChain = (index: number) => {
setForm((prev) => {
const ids = (prev.hostChain?.hostIds || []).filter((_, i) => i !== index);
return { ...prev, hostChain: ids.length > 0 ? { hostIds: ids } : undefined };
});
setForm((prev) => nextFormAfterRemoveHostFromChain(prev, index, effectiveGroupDefaults));
};
const clearHostChain = useCallback(() => {
setForm((prev) => {
const { hostChain: _hostChain, ...rest } = prev;
return rest as Host;
});
}, []);
setForm((prev) => nextFormAfterClearHostChain(prev, effectiveGroupDefaults));
}, [effectiveGroupDefaults]);
const [newEnvName, setNewEnvName] = useState("");
const [newEnvValue, setNewEnvValue] = useState("");
@@ -773,8 +784,16 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setActiveSubPanel("none");
};
const displayHostChainIds = useMemo(
() => form.hostChain !== undefined
? (form.hostChain.hostIds || [])
: (effectiveAuthHost.hostChain?.hostIds || []),
[effectiveAuthHost.hostChain?.hostIds, form.hostChain],
);
const hostChainInherited = form.hostChain === undefined && displayHostChainIds.length > 0;
const availableHostsForChain = useMemo(() => {
const chainedIds = new Set(form.hostChain?.hostIds || []);
const chainedIds = new Set(displayHostChainIds);
// Chain hops are SSH ProxyJump hops; never offer local/serial/telnet/plugin
// entries (e.g. saved local shells) as jump hosts.
return allHosts.filter((h) =>
@@ -782,14 +801,13 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
&& !chainedIds.has(h.id)
&& canServeAsSshJumpHost(h),
);
}, [allHosts, form.id, form.hostChain?.hostIds]);
}, [allHosts, displayHostChainIds, form.id]);
const chainedHosts = useMemo(() => {
const ids = form.hostChain?.hostIds || [];
return ids
return displayHostChainIds
.map((id) => allHosts.find((h) => h.id === id))
.filter(Boolean) as Host[];
}, [allHosts, form.hostChain?.hostIds]);
}, [allHosts, displayHostChainIds]);
const groupOptions: ComboboxOption[] = useMemo(() => {
return groups.map((g) => ({
@@ -905,11 +923,12 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
if (activeSubPanel === "proxy") {
return (
<ProxyPanel
proxyConfig={form.proxyConfig}
proxyConfig={displayProxyConfig}
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={form.proxyProfileId}
selectedProxyProfileId={displayProxyProfileId}
directProxy={form.directProxy}
allowClear={hasHostProxyOverride}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
onSelectDirectProxy={selectDirectProxy}
@@ -1237,11 +1256,13 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
showAlgorithmOverrides={showAlgorithmOverrides}
setShowAlgorithmOverrides={setShowAlgorithmOverrides}
chainedHosts={chainedHosts}
hostChainInherited={hostChainInherited}
setActiveSubPanel={setActiveSubPanel}
clearHostChain={clearHostChain}
proxySummaryType={proxySummaryType}
proxySummaryLabel={proxySummaryLabel}
proxySummaryTooltip={proxySummaryTooltip}
proxyInherited={proxyInherited}
clearProxyConfig={clearProxyConfig}
/>
@@ -0,0 +1,229 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JSDOM } from "jsdom";
import type { Identity, Host } from "../types";
async function withWizard(
run: (fixture: Awaited<ReturnType<typeof mountWizard>>) => Promise<void>,
identities: Identity[] = [],
) {
const fixture = await mountWizard(identities);
try {
await run(fixture);
} finally {
await fixture.cleanup();
}
}
async function mountWizard(identities: Identity[]) {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
url: "http://localhost", pretendToBeVisual: true,
});
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of ["window", "document", "navigator", "HTMLElement", "HTMLInputElement", "Element", "Node", "MutationObserver", "Event", "CustomEvent", "MouseEvent", "KeyboardEvent", "FocusEvent"] as const) {
install(key, key === "window" ? dom.window : dom.window[key]);
}
install("getComputedStyle", dom.window.getComputedStyle.bind(dom.window));
install("requestAnimationFrame", dom.window.requestAnimationFrame.bind(dom.window));
install("cancelAnimationFrame", dom.window.cancelAnimationFrame.bind(dom.window));
install("IS_REACT_ACT_ENVIRONMENT", true);
const { act, useState } = await import("react");
const { createRoot } = await import("react-dom/client");
const { I18nProvider } = await import("../application/i18n/I18nProvider");
const { default: QuickConnectWizard } = await import("./QuickConnectWizard");
const target = { hostname: "example.com" };
const connected: Host[] = [];
const saved: Host[] = [];
let closeCount = 0;
function Fixture() {
const [open, setOpen] = useState(true);
return (
<I18nProvider locale="en">
{open && <QuickConnectWizard
open target={target} keys={[]} identities={identities}
onConnect={(host) => connected.push(host)}
onSaveHost={(host) => saved.push(host)}
onClose={() => { closeCount++; setOpen(false); }}
/>}
</I18nProvider>
);
}
const root = createRoot(document.getElementById("root")!);
await act(async () => { root.render(<Fixture />); });
const button = (name: string) => {
const element = [...document.querySelectorAll<HTMLButtonElement>("button")]
.find((candidate) => candidate.getAttribute("aria-label") === name || candidate.textContent?.trim() === name);
assert.ok(element, `Button ${name} is present`);
return element;
};
const input = (selector: string) => {
const element = document.querySelector<HTMLInputElement>(selector);
assert.ok(element, `Input ${selector} is present`);
return element;
};
const overlay = () => {
const element = document.querySelector<HTMLElement>(".fixed.inset-0");
assert.ok(element, "Quick Connect is still open");
return element;
};
const click = async (element: HTMLElement) => {
await act(async () => { element.click(); });
};
const type = async (selector: string, value: string) => {
await act(async () => {
const element = input(selector);
Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, "value")!.set!.call(element, value);
element.dispatchEvent(new dom.window.Event("input", { bubbles: true }));
});
assert.equal(input(selector).value, value);
};
const key = async (element: HTMLElement, key: string) => {
await act(async () => { element.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key, bubbles: true })); });
};
const settle = async () => { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); };
const outsideClick = async () => {
await act(async () => {
overlay().dispatchEvent(new dom.window.MouseEvent("mousedown", { bubbles: true }));
overlay().click();
});
assert.equal(closeCount, 0, "Background clicks must not close Quick Connect");
overlay();
};
return {
button, input, overlay, click, type, key, settle, outsideClick, connected, saved,
closeCount: () => closeCount,
async cleanup() {
await act(async () => { root.unmount(); });
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
test("background clicks preserve each Quick Connect step and typed connection details", async () => {
await withWizard(async (f) => {
await f.type('input[type="number"]', "2222");
await f.outsideClick();
assert.equal(f.input('input[type="number"]').value, "2222");
await f.click(f.button("Continue"));
await f.type("#quick-username", "alice");
await f.outsideClick();
assert.equal(f.input("#quick-username").value, "alice");
await f.click(f.button("Continue"));
await f.type("#quick-password", "partly configured password");
await f.outsideClick();
await f.key(f.input("#quick-password"), "Escape");
assert.equal(f.closeCount(), 0);
assert.equal(f.input("#quick-password").value, "partly configured password");
await f.click(f.button("Back"));
assert.equal(f.input("#quick-username").value, "alice");
await f.click(f.button("Back"));
assert.equal(f.input('input[type="number"]').value, "2222");
await f.click(f.button("Continue"));
await f.click(f.button("Continue"));
assert.equal(f.input("#quick-password").value, "partly configured password");
await f.click(f.button("Continue"));
assert.equal(f.connected.length, 1);
assert.equal(f.connected[0].username, "alice");
assert.equal(f.connected[0].port, 2222);
assert.equal(f.connected[0].password, "partly configured password");
assert.equal(f.closeCount(), 1);
assert.equal(document.querySelector("h2"), null);
});
});
test("the portaled credential picker retains the wizard and selected identity", async () => {
await withWizard(async (f) => {
await f.type('input[type="number"]', "2222");
await f.click(f.input('[role="combobox"]'));
await f.settle();
const option = document.querySelector<HTMLElement>('[role="option"]');
assert.ok(option);
assert.equal(f.overlay().contains(option), false, "Options are portaled outside the wizard DOM");
await f.click(option);
assert.equal(f.closeCount(), 0);
assert.equal(f.input('[role="combobox"]').value, "Production identity");
assert.equal(f.input('input[type="number"]').value, "2222");
await f.outsideClick();
await f.click(f.button("Connect with preset"));
assert.equal(f.connected.length, 1);
assert.equal(f.connected[0].identityId, "identity-alice");
assert.equal(f.connected[0].username, "alice");
assert.equal(f.connected[0].port, 2222);
assert.equal(f.closeCount(), 1);
}, [{ id: "identity-alice", label: "Production identity", username: "alice", authMethod: "password", password: "preset secret", created: 1 }]);
});
test("the portaled save menu preserves credentials until explicit save and connect", async () => {
await withWizard(async (f) => {
await f.click(f.button("Continue"));
await f.type("#quick-username", "alice");
await f.key(f.input("#quick-username"), "Enter");
await f.type("#quick-password", "secret");
const trigger = f.button("Continue & Save");
await f.click(trigger);
await f.settle();
const menuItem = [...document.querySelectorAll<HTMLButtonElement>("button")]
.find((candidate) => candidate.textContent === "Continue & Save");
assert.ok(menuItem);
assert.equal(f.overlay().contains(menuItem), false, "Save menu is portaled outside the wizard DOM");
await f.click(menuItem.parentElement!);
assert.equal(f.closeCount(), 0);
assert.equal(f.input("#quick-password").value, "secret");
await f.key(document.body, "Escape");
assert.equal(trigger.getAttribute("aria-expanded"), "false");
assert.equal(f.closeCount(), 0);
await f.click(trigger);
await f.settle();
await f.outsideClick();
assert.equal(trigger.getAttribute("aria-expanded"), "false");
assert.equal(f.input("#quick-password").value, "secret");
await f.click(trigger);
await f.settle();
const save = [...document.querySelectorAll<HTMLButtonElement>("button")]
.find((candidate) => candidate.textContent === "Continue & Save");
assert.ok(save);
await f.click(save);
assert.equal(f.saved.length, 1);
assert.equal(f.connected.length, 1);
assert.equal(f.saved[0], f.connected[0]);
assert.equal(f.connected[0].username, "alice");
assert.equal(f.connected[0].password, "secret");
assert.equal(f.closeCount(), 1);
});
});
test("explicit Close dismisses the protocol step", async () => {
await withWizard(async (f) => {
await f.click(f.button("Close"));
assert.equal(f.closeCount(), 1);
assert.equal(document.querySelector("h2"), null);
assert.equal(f.connected.length, 0);
});
});
for (const step of ["username", "auth"]) {
test(`the header X explicitly closes the ${step} step`, async () => {
await withWizard(async (f) => {
await f.click(f.button("Continue"));
await f.type("#quick-username", "alice");
if (step === "auth") {
await f.click(f.button("Continue"));
await f.type("#quick-password", "secret");
}
const close = f.button("Close");
assert.ok(close.querySelector("svg.lucide-x"), "A visible X is provided on steps with Back");
await f.click(close);
assert.equal(f.closeCount(), 1);
assert.equal(document.querySelector("h2"), null);
assert.equal(f.connected.length, 0);
});
});
}
+13 -2
View File
@@ -8,6 +8,7 @@ import {
Plug,
Plus,
User,
X,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import { createPortal } from "react-dom";
@@ -675,7 +676,6 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
const wizard = (
<div
className="fixed inset-0 z-50 flex items-center justify-center"
onClick={onClose}
>
<div
className="w-[560px] max-w-[90vw] bg-background border border-border rounded-2xl animate-in fade-in-0 zoom-in-95 duration-200"
@@ -686,7 +686,7 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="px-6 py-4 border-b border-border/50">
<div className="px-6 py-4 border-b border-border/50 flex items-center justify-between gap-4">
<div className="flex items-center gap-2 min-w-0">
<Plug size={18} className="shrink-0 text-foreground" />
<div className="min-w-0">
@@ -696,6 +696,17 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
) : null}
</div>
</div>
{step !== "protocol" && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
aria-label={t("common.close")}
onClick={onClose}
>
<X size={16} />
</Button>
)}
</div>
+1
View File
@@ -409,6 +409,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const nestedDelayMs = (request.aiSubTab || request.syncSubTab) ? 80 : 40;
const focusHandle = window.setTimeout(() => {
void focusSettingsAnchor(request.anchorId, {
fallbackAnchorId: request.fallbackAnchorId,
attempts: 48,
delayMs: 50,
}).finally(() => {
+17
View File
@@ -206,6 +206,23 @@ test("surfaces pause unavailable reason on a transferring row", () => {
assert.match(markup, /This transfer cannot be paused yet/);
});
test("shows a settled folder pause failure with retry and resume instead of a spinner", () => {
const markup = renderTransferItem({
...baseTask,
isDirectory: true,
status: "pausing",
error: undefined,
speed: 0,
resumable: true,
pauseUnavailableReason: "This transfer cannot be paused yet",
}, { onPause: () => {}, onResume: () => {} });
assert.match(markup, /This transfer cannot be paused yet/);
assert.match(markup, /aria-label="Pause: archive\.tar\.gz"/);
assert.match(markup, /aria-label="Resume: archive\.tar\.gz"/);
assert.doesNotMatch(markup, /aria-busy="true"|aria-label="Pausing:/);
});
test("renders child resize handle as a keyboard-reachable separator", () => {
const markup = renderTransferItem(
{
+1 -1
View File
@@ -759,7 +759,7 @@ const SftpViewInner: React.FC<SftpViewProps> = ({
data-section="pane-magnification-hint"
>
{t('terminal.paneMagnification.hint')}: {t('terminal.layer.sftp')}
{paneMagnificationShortcutLabel ? ` · ${paneMagnificationShortcutLabel} / Esc` : ' · Esc'}
{paneMagnificationShortcutLabel ? ` · ${paneMagnificationShortcutLabel}` : ''}
</div>
)}
</div>
+23
View File
@@ -82,6 +82,7 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean";
import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString";
import { performSessionLogAction, type SessionLogAction } from "../application/state/sessionLogActions";
import { useSessionLogBackend } from "../application/state/useSessionLogBackend";
import { useTerminalSessionCloseCapture } from "../application/state/terminalSessionCloseCapture";
import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore";
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
import {
@@ -1676,6 +1677,28 @@ const TerminalComponent: React.FC<TerminalProps> = ({
return captureHandler(capturedSessionId, capturedData);
}, [finalizeTerminalLogData]);
useTerminalSessionCloseCapture({
sessionId,
enabled: !attachExistingSession && restoreState !== "restored-disconnected",
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture: handleTerminalDataCaptureOnce,
});
useEffect(() => {
// Attached popups do not own the ConnectionLog; the home terminal captures it.
if (attachExistingSession) return;
return netcattyBridge.get()?.onFinalizeSessionLogs?.(async () => {
if (terminalDataCapturedRef.current || (restoreState === "restored-disconnected" && statusRef.current === "disconnected")) return;
const term = termRef.current;
if (term && !await flushPendingTerminalWritesBeforeHibernate(term)) {
throw new Error("Terminal output did not drain before quit capture");
}
await handleTerminalDataCaptureOnce(sessionId, finalizeTerminalLogData(), { finalized: true });
});
}, [attachExistingSession, restoreState, sessionId, finalizeTerminalLogData, handleTerminalDataCaptureOnce]);
const attachHomeWebContentsIdRef = useRef<number | null | undefined>(undefined);
useEffect(() => {
+4
View File
@@ -245,12 +245,14 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onTerminalDataCapture,
onCreateWorkspaceFromSessions,
onAddSessionToWorkspace,
onMoveWorkspacePane,
onRequestAddToWorkspace,
onAppendHostToWorkspace,
onUpdateSplitSizes,
onSetDraggingSessionId,
onToggleWorkspaceViewMode,
onSetWorkspaceFocusedSession,
onSetWorkspaceAnchorChat,
onReorderWorkspaceSessions,
onReorderTabs,
onCopySession,
@@ -2712,6 +2714,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
systemMountedTabIds,
themeMountedTabIds,
onAddSessionToWorkspace,
onMoveWorkspacePane,
onConnectToHost,
onCreateLocalTerminal,
onCreateWorkspaceFromSessions,
@@ -2726,6 +2729,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onSessionData,
onSetDraggingSessionId,
onSetWorkspaceFocusedSession,
onSetWorkspaceAnchorChat,
onStartSessionRename,
onSubmitSessionRename,
onRemoveSessionFromWorkspace,
+29 -2
View File
@@ -15,13 +15,13 @@ import {
shouldForceDraftViewSync,
} from "./aiPanelViewState.ts";
function createSession(id: string): AISession {
function createSession(id: string, updatedAt = 1): AISession {
return {
id,
title: `Session ${id}`,
messages: [],
createdAt: 1,
updatedAt: 1,
updatedAt,
agentId: "catty",
scope: {
type: "terminal",
@@ -133,6 +133,33 @@ test("missing explicit panel view resumes the most recent matching history when
);
});
test("auto-resume prefers the anchored chat over recency and position (#4098 phase 2)", () => {
const sessions = [createSession("session-2", 9), createSession("session-1", 4)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace", "session-1"),
{ mode: "session", sessionId: "session-1" },
);
});
test("auto-resume without an anchor picks the most recently updated chat, not sessions[0]", () => {
const sessions = [createSession("session-2", 4), createSession("session-1", 9)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace"),
{ mode: "session", sessionId: "session-1" },
);
});
test("a stale anchor that left the scope falls through to recency", () => {
const sessions = [createSession("session-2", 4), createSession("session-1", 9)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace", "deleted-chat"),
{ mode: "session", sessionId: "session-1" },
);
});
test("missing explicit panel view restores the persisted active session instead of the newest", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
+35 -2
View File
@@ -39,6 +39,8 @@ export function resolveDisplayedPanelView(
sessions: AISession[],
persistedSessionId?: string | null,
scopeType: "terminal" | "workspace" = "workspace",
anchorChatId?: string | null,
preferredHistorySessionId?: string | null,
): AIPanelView {
if (panelView) {
return normalizePanelView(panelView, sessions);
@@ -66,13 +68,44 @@ export function resolveDisplayedPanelView(
return DEFAULT_PANEL_VIEW;
}
if (sessions[0]) {
return { mode: "session", sessionId: sessions[0].id };
// Prefer the workspace anchor, then the candidate selected by scoped
// history's match-rank/recency ordering. Callers without a ranked candidate
// retain the recency fallback below.
if (anchorChatId && sessions.some((s) => s.id === anchorChatId)) {
return { mode: "session", sessionId: anchorChatId };
}
// Scoped history already ranks exact/member matches before other scopes,
// then sorts each rank by recency. Preserve its selected candidate instead
// of letting a newer chat from another workspace overtake that match.
const mostRecent = preferredHistorySessionId === undefined
? resolveMostRecentlyUpdatedSession(sessions)
: sessions.find((session) => session.id === preferredHistorySessionId);
if (mostRecent) {
return { mode: "session", sessionId: mostRecent.id };
}
return DEFAULT_PANEL_VIEW;
}
/**
* The most recently updated session by `updatedAt`, or null when the list is
* empty. Ties keep the earlier entry so the result is deterministic.
*/
export function resolveMostRecentlyUpdatedSession(
sessions: AISession[],
): AISession | null {
let best: AISession | null = null;
let bestUpdatedAt = 0;
for (const session of sessions) {
const updatedAt = session.updatedAt ?? 0;
if (best === null || updatedAt > bestUpdatedAt) {
best = session;
bestUpdatedAt = updatedAt;
}
}
return bestUpdatedAt > 0 ? best : null;
}
export function normalizePanelView(
panelView: AIPanelView,
sessions: AISession[],
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import type { AISession } from "../../infrastructure/ai/types.ts";
import { resolveDisplayedPanelView } from "./aiPanelViewState.ts";
import {
_getScopedHistoryCacheSizeForTests,
getScopedHistorySessions,
@@ -23,6 +24,49 @@ function createSession(
};
}
test("workspace auto-resume keeps scope rank ahead of recency", () => {
const sessions = [
createSession("exact-older", { type: "workspace", targetId: "workspace-current" }, 1),
createSession("member-newer", { type: "terminal", targetId: "member" }, 2),
createSession("other-newest", { type: "workspace", targetId: "workspace-other" }, 20),
];
const history = getScopedHistorySessions(
sessions, "workspace", "workspace-current", [], new Set(), new Set(["member"]),
);
assert.deepEqual(history.map((session) => session.id), ["member-newer", "exact-older", "other-newest"]);
const preferredId = history[0]?.id ?? null;
assert.deepEqual(resolveDisplayedPanelView(undefined, false, history, undefined, "workspace", undefined, preferredId),
{ mode: "session", sessionId: "member-newer" });
// The ranking only controls implicit fallback, never an explicit selection,
// saved selection, anchor, or deliberate new-chat draft.
for (const [view, persisted, anchor] of [
[{ mode: "session", sessionId: "other-newest" }, undefined, undefined],
[undefined, "other-newest", undefined],
[undefined, undefined, "other-newest"],
] as const) {
assert.deepEqual(resolveDisplayedPanelView(view, false, history, persisted, "workspace", anchor, preferredId),
{ mode: "session", sessionId: "other-newest" });
}
assert.deepEqual(resolveDisplayedPanelView({ mode: "draft" }, true, history, undefined, "workspace", undefined, preferredId),
{ mode: "draft" });
assert.deepEqual(resolveDisplayedPanelView(undefined, false, history, undefined, "terminal", undefined, preferredId),
{ mode: "draft" });
});
test("workspace auto-resume prefers an exact match and retains history fallback when none exists", () => {
const exact = createSession("exact", { type: "workspace", targetId: "workspace-current" }, 1);
const others = [
createSession("other-old", { type: "workspace", targetId: "workspace-other" }, 5),
createSession("other-new", { type: "workspace", targetId: "workspace-other" }, 10),
];
for (const [sessions, expected] of [[others, "other-new"], [[...others, exact], "exact"], [[], undefined]] as const) {
const history = getScopedHistorySessions([...sessions], "workspace", "workspace-current", [], new Set());
assert.deepEqual(resolveDisplayedPanelView(undefined, false, history, undefined, "workspace", undefined, history[0]?.id ?? null),
expected ? { mode: "session", sessionId: expected } : { mode: "draft" });
}
});
test("workspace history remains visible after the original workspace target is gone", () => {
const staleWorkspaceSession = createSession(
"workspace-stale",
+3 -1
View File
@@ -34,6 +34,7 @@ export interface ProxyPanelProps {
onClearProxy: () => void;
onBack: () => void;
onCancel: () => void;
allowClear?: boolean;
layout?: AsidePanelLayout;
}
@@ -51,6 +52,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
onClearProxy,
onBack,
onCancel,
allowClear = true,
layout = 'overlay',
resizable,
persistWidthStorageKey,
@@ -346,7 +348,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
</>
)}
{(proxyConfig?.host || proxyConfig?.command || selectedProxyProfileId || directProxy) && (
{allowClear && (proxyConfig?.host || proxyConfig?.command || selectedProxyProfileId || directProxy) && (
<Button variant="ghost" className="w-full h-10 text-destructive" onClick={onClearProxy}>
<Trash2 size={14} className="mr-2" /> {t('hostDetails.proxyPanel.remove')}
</Button>
@@ -459,6 +459,17 @@ test("note markdown toolbar remains usable in narrow panes", () => {
);
});
test("MDX link dialog overlay stays inside the retained notes editor container", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
// Default MDXEditor popup target is document.body. Keep the overlay in the
// editor container so section `hidden` and vault visibility:hidden hide it (#4257).
assert.match(source, /const \[overlayContainer, setOverlayContainer\] = useState<HTMLElement \| null>\(null\);/);
assert.match(source, /setOverlayContainer\(\(current\) => \(current === node \? current : node\)\);/);
assert.match(source, /ref=\{setEditorContainer\}/);
assert.match(source, /overlayContainer=\{overlayContainer \?\? undefined\}/);
});
test("preview mode opens links directly without showing the edit hover action", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
+10 -1
View File
@@ -946,6 +946,14 @@ export const InlineMarkdownEditor = React.memo(
});
const containerRef = useRef<HTMLDivElement>(null);
// MDXEditor portals .mdxeditor-popup-container to document.body unless
// overlayContainer is set. Notes stays mounted and is only CSS-hidden, so a
// body portal would leave the link preview toolbar over other pages (#4257).
const [overlayContainer, setOverlayContainer] = useState<HTMLElement | null>(null);
const setEditorContainer = useCallback((node: HTMLDivElement | null) => {
containerRef.current = node;
setOverlayContainer((current) => (current === node ? current : node));
}, []);
const getSelectedText = useCallback((): string => {
const container = containerRef.current;
@@ -2063,7 +2071,7 @@ export const InlineMarkdownEditor = React.memo(
return (
<div
ref={containerRef}
ref={setEditorContainer}
className="relative flex h-full flex-col"
style={{
["--note-font-family" as string]: noteFontFamily || undefined,
@@ -2223,6 +2231,7 @@ export const InlineMarkdownEditor = React.memo(
<MDXEditor
key={editorMode}
ref={editorRef}
overlayContainer={overlayContainer ?? undefined}
markdown={
mdxRetry !== null && value === mdxRetry.staleValue
? normalizeNotePublicAssetPaths(mdxRetry.markdown)
+2 -2
View File
@@ -16,8 +16,8 @@ export function PluginAuthorRow({ entry, plugin, sourceId, showSource = false }:
const showImage = avatar && avatar.length <= 700_000 && /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(avatar) && failed !== imageKey;
const source = plugin?.source;
const sourceKey = source?.kind === 'third-party' ? 'thirdparty' : source?.kind === 'official' || source?.kind === 'local' ? source.kind : undefined;
const sourceLabel = t(sourceKey ? `settings.plugins.sources.short.${sourceKey}` : 'settings.plugins.landing.sourceUnknown');
const sourceDescription = sourceKey
const sourceLabel = source?.kind === 'github' ? 'GitHub' : t(sourceKey ? `settings.plugins.sources.short.${sourceKey}` : 'settings.plugins.landing.sourceUnknown');
const sourceDescription = source?.kind === 'github' ? [source.origin, source.tag, source.commit].filter(Boolean).join(' · ') : sourceKey
? [t(`settings.plugins.sources.${sourceKey}`), source?.name, source?.origin].filter(Boolean).join(' · ')
: sourceLabel;
const SourceIcon = source?.kind === 'local' ? HardDrive : source?.kind === 'official' ? Store : Globe;
@@ -93,6 +93,7 @@ export function SettingsSearchControl({
aiSubTab: hit.entry.aiSubTab,
syncSubTab: hit.entry.syncSubTab,
anchorId: hit.entry.id,
fallbackAnchorId: hit.entry.fallbackAnchorId,
});
collapseSearch(false);
};
+97 -1
View File
@@ -1,6 +1,102 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import test, { type TestContext } from "node:test";
import { settingsAnchorDomId } from "../../domain/settingsSearchCatalog.ts";
import { focusSettingsAnchor } from "./settingsFocus.ts";
function setupFocusDom(t: TestContext) {
t.mock.timers.enable({ apis: ["setTimeout"] });
const anchors = new Map<string, HTMLElement>();
const focused: string[] = [];
const scrolled: string[] = [];
const globals = {
document: {
getElementById: (id: string) => anchors.get(id) ?? null,
querySelectorAll: () => [],
documentElement: {},
body: {},
},
window: { setTimeout, clearTimeout },
CSS: { escape: (value: string) => value },
requestAnimationFrame: (callback: FrameRequestCallback) => { callback(0); return 0; },
};
for (const [key, value] of Object.entries(globals)) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { configurable: true, value });
t.after(() => {
if (previous) Object.defineProperty(globalThis, key, previous);
else Reflect.deleteProperty(globalThis, key);
});
}
const mount = (id: string, visible = true) => {
const classes = new Set<string>();
const el = {
closest: () => null,
checkVisibility: () => visible,
classList: { add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name) },
matches: () => true,
hasAttribute: () => true,
focus: () => focused.push(id),
scrollIntoView: () => scrolled.push(id),
} as unknown as HTMLElement;
anchors.set(settingsAnchorDomId(id), el);
return classes;
};
return { mount, focused, scrolled };
}
test("missing search target focuses and highlights its visible parent after a short mount window", async (t) => {
const { mount, focused, scrolled } = setupFocusDom(t);
const parentClasses = mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent", attempts: 48, delayMs: 50 });
for (let retry = 0; retry < 3; retry += 1) t.mock.timers.tick(50);
t.mock.timers.tick(49);
assert.deepEqual(focused, []);
t.mock.timers.tick(1);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
assert.deepEqual(scrolled, ["parent"]);
assert.ok(parentClasses.has("settings-search-highlight"));
});
test("search focus prefers a visible primary over its fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
const childClasses = mount("child");
const parentClasses = mount("parent");
assert.equal(await focusSettingsAnchor("child", { fallbackAnchorId: "parent" }), true);
assert.deepEqual(focused, ["child"]);
assert.ok(childClasses.has("settings-search-highlight"));
assert.equal(parentClasses.has("settings-search-highlight"), false);
});
test("search focus waits for a lazy primary before using a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
t.mock.timers.tick(50);
t.mock.timers.tick(50);
mount("child");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["child"]);
});
test("search focus skips a hidden primary and waits for a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("child", false);
mount("parent", false);
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
for (let retry = 0; retry < 4; retry += 1) t.mock.timers.tick(50);
assert.deepEqual(focused, []);
mount("parent");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
});
test("system setting hints sit below their cards with a shared top gap", () => {
const uiSource = readFileSync(new URL("./settings-ui.tsx", import.meta.url), "utf8");
+24 -15
View File
@@ -4,12 +4,15 @@ const HIGHLIGHT_CLASS = "settings-search-highlight";
const HIGHLIGHT_MS = 1600;
/** Keep focused anchors slightly below the top of the settings content pane. */
const SCROLL_TOP_PADDING_PX = 24;
/** Allow 200ms at the default retry delay for lazy tab / sub-tab mounts. */
const FALLBACK_AFTER_ATTEMPTS = 5;
export type SettingsFocusTarget = {
tab: string;
aiSubTab?: string;
syncSubTab?: string;
anchorId: string;
fallbackAnchorId?: string;
};
let focusGeneration = 0;
@@ -30,6 +33,18 @@ function isAnchorVisible(el: HTMLElement): boolean {
return el.getClientRects().length > 0;
}
function findVisibleAnchor(anchorId: string): HTMLElement | undefined {
const candidates = [
document.getElementById(settingsAnchorDomId(anchorId)),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
return candidates.find((node) => isAnchorVisible(node));
}
function focusAnchorElement(el: HTMLElement): void {
const focusable = el.matches("button, a, input, select, textarea, [tabindex]")
? el
@@ -103,15 +118,16 @@ export function scrollSettingsAnchorIntoView(
/**
* Scroll the settings content pane to a catalog anchor and briefly highlight it.
* Retries to cover lazy tab mounts / nested sub-tab switches.
* After a short mount window, use a visible parent fallback for gated rows.
*/
export function focusSettingsAnchor(
anchorId: string,
options?: { attempts?: number; delayMs?: number },
options?: { attempts?: number; delayMs?: number; fallbackAnchorId?: string },
): Promise<boolean> {
const attempts = options?.attempts ?? 40;
const delayMs = options?.delayMs ?? 50;
const generation = ++focusGeneration;
let remaining = attempts;
let attempt = 0;
return new Promise((resolve) => {
const finish = (ok: boolean) => {
@@ -125,20 +141,13 @@ export function focusSettingsAnchor(
return;
}
const domId = settingsAnchorDomId(anchorId);
const candidates = [
document.getElementById(domId),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
const el = candidates.find((node) => isAnchorVisible(node));
attempt += 1;
let el = findVisibleAnchor(anchorId);
if (!el && options?.fallbackAnchorId && attempt >= Math.min(FALLBACK_AFTER_ATTEMPTS, attempts)) {
el = findVisibleAnchor(options.fallbackAnchorId);
}
if (!el) {
remaining -= 1;
if (remaining > 0) {
if (attempt < attempts) {
window.setTimeout(tryFocus, delayMs);
return;
}
@@ -258,6 +258,7 @@ export const AppLockSettingsSection: React.FC<AppLockSettingsSectionProps> = ({
</SettingRow>
<SettingRow
anchorId="system-app-lock-timeout"
label={t('settings.appLock.timeout')}
description={t('settings.appLock.timeoutDesc')}
>
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
for (const locale of ['en', 'es', 'ru', 'zh-CN', 'zh-TW']) test(`real dialog (${locale}) reviews permissions and requires fresh trust after failed installation for same-package retries and different repositories`, async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'KeyboardEvent', 'MouseEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
install('IS_REACT_ACT_ENVIRONMENT', true);
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { I18nProvider } = await import('../../../application/i18n/I18nProvider');
const { loadLocaleMessages, getLoadedLocaleMessages } = await import('../../../application/i18n/messages');
await loadLocaleMessages(locale);
const messages = getLoadedLocaleMessages(locale)!;
const t = (key: string) => messages[key]!;
const { PluginGitHubInstall } = await import('./PluginGitHubInstall');
const root = createRoot(document.getElementById('root')!);
const requests: string[] = [];
const installed: string[] = [];
const discarded: string[] = [];
let refreshed = 0;
let resolveDownload: ((value: NetcattyGitHubPluginPreview) => void) | undefined;
Object.defineProperty(window, 'netcatty', { configurable: true, value: {
prepareGitHubPlugin: async (input: string) => { requests.push(input); if (requests.length === 1) throw new Error('GitHub API rate limit reached. Try again later'); return new Promise<NetcattyGitHubPluginPreview>(resolve => { resolveDownload = resolve; }); },
installGitHubPlugin: async (token: string) => { installed.push(token); if (installed.length <= 2) throw new Error('GitHub package preview expired. Download and review it again'); return {} as NetcattyInstalledPlugin; },
discardGitHubPlugin: async (token: string) => { discarded.push(token); },
} as NetcattyBridge });
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
const button = (text: string) => [...document.querySelectorAll<HTMLButtonElement>('button')].find(el => el.textContent === text)!;
const click = async (el: HTMLElement) => { assert.ok(el); await act(async () => { el.click(); await settle(); }); };
const type = async (text: string) => {
await act(async () => {
const input = document.querySelector<HTMLInputElement>('input:not([type=checkbox])')!;
Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!.call(input, text);
input.dispatchEvent(new Event('input', { bubbles: true }));
await settle();
});
};
const preview = { token: 'reviewed-token', source: { id: 'github:fixture', kind: 'github', name: 'owner/repo', origin: 'https://github.com/owner/repo', tag: 'v1.0.0', commit: 'a'.repeat(40) }, assetName: 'plugin.ncpkg', size: 400,
archiveSha256: 'b'.repeat(64), manifest: { manifestVersion: 1, id: 'com.example.fixture', name: 'fixture', publisher: 'example', version: '1.0.0', engines: { netcatty: '*', api: '*' }, main: { browser: 'index.js' }, permissions: { required: [{ permission: 'network', resources: ['https://example.com'], reason: 'Read only fixture' }] } } } as NetcattyGitHubPluginPreview;
try {
await act(async () => root.render(<I18nProvider locale={locale}><PluginGitHubInstall disabled={false} onInstalled={async () => { refreshed++; }} /></I18nProvider>));
const trigger = button(t('settings.plugins.github.install'));
await click(trigger);
assert.equal(document.activeElement?.tagName, 'INPUT');
assert.ok(button(t('settings.plugins.github.download')).disabled);
await type('https://evil.com/owner/repo');
await click(button(t('settings.plugins.github.download')));
assert.equal(document.querySelector('[role=alert] p')!.textContent, t('settings.plugins.github.error.invalidRepository'));
assert.equal(requests.length, 0);
if (locale !== 'en') {
// The existing error follows provider state without repeating the host call.
await act(async () => root.render(<I18nProvider locale="en"><PluginGitHubInstall disabled={false} onInstalled={async () => { refreshed++; }} /></I18nProvider>));
assert.match(document.querySelector('[role=alert]')!.textContent!, /repository only/);
await act(async () => root.render(<I18nProvider locale={locale}><PluginGitHubInstall disabled={false} onInstalled={async () => { refreshed++; }} /></I18nProvider>));
assert.equal(document.querySelector('[role=alert] p')!.textContent, t('settings.plugins.github.error.invalidRepository'));
assert.equal(requests.length, 0);
}
await type('github.com/Owner/Repo.git/');
await click(button(t('settings.plugins.github.download')));
assert.equal(document.querySelector('[role=alert] p')!.textContent, t('settings.plugins.github.error.rateLimit'));
assert.deepEqual(requests, ['https://github.com/owner/repo']);
await click(button(t('settings.plugins.github.download')));
assert.ok(button(t('settings.plugins.github.download')).disabled);
assert.equal(document.querySelector('form')?.getAttribute('aria-busy'), 'true');
assert.equal(document.querySelector<HTMLInputElement>('input')?.disabled, true);
await act(async () => { resolveDownload!(preview); await settle(); });
const review = document.querySelector('[data-plugin-github-preview]')!;
assert.match(review.textContent!, /https:\/\/github.com\/owner\/repo/);
assert.match(review.textContent!, /v1\.0\.0.*aaaaaaaa/);
assert.match(review.textContent!, /https:\/\/example.com/);
assert.ok(button(t('settings.plugins.github.confirm')).disabled);
await click(document.querySelector('input[type=checkbox]')!);
assert.equal(button(t('settings.plugins.github.confirm')).disabled, false);
await click(button(t('settings.plugins.github.confirm')));
assert.deepEqual(installed, ['reviewed-token']);
assert.equal(document.querySelector('[role=alert] p')!.textContent, t('settings.plugins.github.error.expired'));
assert.equal(document.querySelector('[data-plugin-github-preview]'), null);
assert.equal(refreshed, 0);
// A retry of the very same archive/repository is a fresh preview too.
await click(button(t('settings.plugins.github.download')));
await act(async () => { resolveDownload!({ ...preview, token: 'retry-token' }); await settle(); });
assert.equal(document.querySelector<HTMLInputElement>('input[type=checkbox]')!.checked, false);
assert.ok(button(t('settings.plugins.github.confirm')).disabled);
await click(button(t('settings.plugins.github.confirm')));
assert.deepEqual(installed, ['reviewed-token']);
await click(document.querySelector('input[type=checkbox]')!);
assert.equal(button(t('settings.plugins.github.confirm')).disabled, false);
await click(button(t('settings.plugins.github.confirm')));
assert.equal(document.querySelector('[role=alert] p')!.textContent, t('settings.plugins.github.error.expired'));
await type('another/plugin');
await click(button(t('settings.plugins.github.download')));
await act(async () => { resolveDownload!({ ...preview, token: 'different-token', source: { ...preview.source, origin: 'https://github.com/another/plugin', name: 'another/plugin' } }); await settle(); });
assert.equal(requests.at(-1), 'https://github.com/another/plugin');
assert.match(document.querySelector('[data-plugin-github-preview]')!.textContent!, /https:\/\/github.com\/another\/plugin/);
assert.equal(document.querySelector<HTMLInputElement>('input[type=checkbox]')!.checked, false);
assert.ok(button(t('settings.plugins.github.confirm')).disabled);
await click(button(t('settings.plugins.github.confirm')));
assert.deepEqual(installed, ['reviewed-token', 'retry-token']);
await click(document.querySelector('input[type=checkbox]')!);
await click(document.querySelector('input[type=checkbox]')!);
assert.ok(button(t('settings.plugins.github.confirm')).disabled);
await click(document.querySelector('input[type=checkbox]')!);
await click(button(t('settings.plugins.github.confirm')));
assert.deepEqual(installed, ['reviewed-token', 'retry-token', 'different-token']);
assert.equal(refreshed, 1);
assert.equal(document.querySelector('[role=dialog]'), null);
await click(trigger);
assert.equal(document.querySelector('[data-plugin-github-preview]'), null);
assert.equal(document.querySelector<HTMLInputElement>('input')?.value, '');
await type('owner/repo');
await click(button(t('settings.plugins.github.download')));
await act(async () => { resolveDownload!({ ...preview, token: 'cancel-token' }); await settle(); });
await click(button(t('common.back')));
assert.deepEqual(discarded, ['cancel-token']);
await act(async () => { document.activeElement?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); await settle(); });
assert.equal(document.querySelector('[role=dialog]'), null);
assert.equal(document.activeElement, trigger);
} finally {
await act(async () => root.unmount());
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
dom.window.close();
}
});
@@ -0,0 +1,58 @@
import { useState } from 'react';
import { Github } from 'lucide-react';
import { usePluginGitHubInstall } from '../../../application/state/usePluginGitHubInstall';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '../../ui/dialog';
import { PluginPackageDetails } from './PluginPackageManager';
import { describePluginGitHubInstallError } from '../../../domain/pluginGitHubInstallError';
export function PluginGitHubInstall({ disabled, onInstalled }: { disabled: boolean; onInstalled: () => Promise<unknown> }) {
const { t, resolvedLocale } = useI18n();
const [open, setOpen] = useState(false);
const [input, setInput] = useState('');
const [accepted, setAccepted] = useState(false);
const flow = usePluginGitHubInstall(async () => { await onInstalled(); setOpen(false); });
const preview = flow.preview;
const error = flow.error ? describePluginGitHubInstallError(flow.error) : null;
return <Dialog open={open} onOpenChange={(next) => {
if (flow.busy) return;
setOpen(next); flow.reset(); setAccepted(false); setInput('');
}}>
<DialogTrigger asChild><Button variant="outline" size="sm" disabled={disabled}><Github size={14} className="mr-2" />{t('settings.plugins.github.install')}</Button></DialogTrigger>
<DialogContent hideCloseButton={flow.busy} className="app-no-drag max-h-[85dvh] overflow-y-auto sm:max-w-xl" data-plugin-github-install="">
<DialogHeader>
<DialogTitle>{t('settings.plugins.github.install')}</DialogTitle>
<DialogDescription>{t('settings.plugins.github.description')}</DialogDescription>
</DialogHeader>
<form className="space-y-4" aria-busy={flow.busy} onSubmit={(event) => { event.preventDefault(); if (!flow.busy && input.trim() && !preview) void flow.prepare(input); }}>
<label className="block space-y-2 text-sm"><span>{t('settings.plugins.github.repository')}</span>
<Input autoFocus value={input} disabled={flow.busy || Boolean(preview)} maxLength={512} placeholder="https://github.com/owner/repo" onChange={(event) => setInput(event.target.value)} />
</label>
<p className="text-xs text-muted-foreground">{t('settings.plugins.github.formats')}</p>
{flow.busy && <p role="status" className="text-sm text-muted-foreground">{t('settings.plugins.github.busy')}</p>}
{error && <div role="alert" className="break-words text-sm text-destructive">
<p>{t(error.key, error.values)}</p>
{error.details && <details className="mt-2 text-xs"><summary>{t('settings.plugins.github.error.details')}</summary><p className="whitespace-pre-wrap">{error.details}</p></details>}
</div>}
{preview && <div className="space-y-3" data-plugin-github-preview="">
<p className="break-words text-sm font-medium">{preview.manifest.name} · {preview.manifest.version}</p>
<div className="break-all rounded-md bg-muted/40 p-3 text-xs">
<p>{preview.source.origin}</p><p>{preview.source.tag} · {preview.source.commit}</p>
<p>{preview.assetName} · {preview.size.toLocaleString(resolvedLocale)} B</p>
</div>
<p className="text-xs text-muted-foreground">{t('settings.plugins.github.review')}</p>
<PluginPackageDetails plugin={{ id: preview.manifest.id, enabled: false, activeVersion: preview.manifest.version, manifest: preview.manifest,
archiveSha256: preview.archiveSha256, runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } }} />
<label className="flex items-start gap-2 text-sm"><input type="checkbox" checked={accepted} disabled={flow.busy} onChange={(event) => setAccepted(event.target.checked)} className="mt-1" />{t('settings.plugins.github.accept')}</label>
</div>}
<DialogFooter>
<Button type="button" variant="outline" disabled={flow.busy} onClick={() => { if (preview) { flow.reset(); setAccepted(false); } else setOpen(false); }}>{t(preview ? 'common.back' : 'common.cancel')}</Button>
{preview ? <Button type="button" disabled={flow.busy || !accepted} onClick={() => { setAccepted(false); void flow.install(); }}>{t('settings.plugins.github.confirm')}</Button>
: <Button type="submit" disabled={flow.busy || !input.trim()}>{t('settings.plugins.github.download')}</Button>}
</DialogFooter>
</form>
</DialogContent>
</Dialog>;
}
@@ -66,9 +66,15 @@ test('local logging controls default off, disclose verbose risk, and call host-o
assert.match(document.querySelector('[role=alert]')!.textContent!, /synthetic preferences write failed/);
await act(async () => button('Close').click());
assert.equal(document.querySelector('[role=dialog]'), null);
assert.equal(document.activeElement, configure);
// Radix restores focus in a setTimeout(0) after the dialog unmounts.
// act() can finish before that timer, so drain it before checking focus.
await new Promise((resolve) => setTimeout(resolve, 0));
// Comparing DOM objects directly makes Node inspect the entire JSDOM graph
// on failure, which can stall the test process while formatting the diff.
assert.ok(document.activeElement === configure, `expected focus on Configure, got ${document.activeElement?.tagName}`);
} finally {
await act(async () => root.unmount());
await new Promise((resolve) => setTimeout(resolve, 0));
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
@@ -30,6 +30,7 @@ export function PluginPackageDetails({ plugin }: { plugin: NetcattyInstalledPlug
<dt className="text-muted-foreground">Netcatty</dt><dd>{manifest.engines.netcatty}</dd>
<dt className="text-muted-foreground">API</dt><dd>{manifest.engines.api}</dd>
<dt className="text-muted-foreground">SHA-256</dt><dd className="break-all font-mono">{plugin.archiveSha256 ?? '-'}</dd>
{plugin.source?.kind === 'github' && <><dt>GitHub</dt><dd className="break-all">{plugin.source.origin}<br />{plugin.source.tag}<br /><span className="font-mono">{plugin.source.commit}</span></dd></>}
</dl>
<p className={!policy.browserOnly && !policy.dataOnly ? 'text-destructive' : 'text-muted-foreground'}>{policy.dataOnly ? t('settings.plugins.manager.dataTheme') : t(`settings.plugins.manager.${runtimeLabel}`)}</p>
<div className="space-y-2">
@@ -9,6 +9,13 @@ test("SFTP settings imports the shared Toggle used by its option rows", () => {
assert.match(source, /Toggle,\s*\n\s*Select,/);
});
test("folder compression row exposes its settings search anchor", () => {
assert.match(
source,
/<SettingRow\s+anchorId="sftp-compressed-upload"\s+label=\{t\('settings\.sftp\.compressedUpload\.enable'\)\}/,
);
});
function functionBody(functionName: string): string {
const start = source.indexOf(`const ${functionName} = useCallback`);
assert.notEqual(start, -1, `${functionName} should exist`);
@@ -180,6 +180,7 @@ export default function SettingsFileAssociationsTab() {
<SectionHeader title={t('settings.sftp.compressedUpload')} />
<SettingCard>
<SettingRow
anchorId="sftp-compressed-upload"
label={t('settings.sftp.compressedUpload.enable')}
description={t('settings.sftp.compressedUpload.enableDesc')}
>
@@ -231,12 +232,14 @@ export default function SettingsFileAssociationsTab() {
</div>
</SettingRow>
<SettingRow
anchorId="sftp-skip-unchanged"
label={t('settings.sftp.skipUnchanged.enable')}
description={t('settings.sftp.skipUnchanged.enableDesc')}
>
<Toggle checked={sftpSkipUnchanged} onChange={setSftpSkipUnchanged} />
</SettingRow>
<SettingRow
anchorId="sftp-transport-idle-ttl"
label={t('settings.ssh.transportIdleTtl')}
description={t('settings.ssh.transportIdleTtl.desc')}
>
@@ -1,4 +1,5 @@
import { PluginThirdPartyMarket } from './PluginThirdPartyMarket';
import { PluginGitHubInstall } from './PluginGitHubInstall';
import { usePluginUpdateCheck } from '../../../application/state/usePluginUpdateCheck';
import { usePluginManager } from '../../../application/state/usePluginManager';
import { PluginManagementDialog } from './PluginManagementDialog';
@@ -35,6 +36,7 @@ function PluginManagementContent({ manager }: {
<div className="flex items-center gap-2">
{pluginView === 'installed' && <PluginStatus noVault={manager.credentialStorageAvailable === false} />}
<div ref={setCatalogToolbar} className="flex items-center gap-2" />
<PluginGitHubInstall disabled={!manager.available || manager.busy} onInstalled={async () => { setPluginView('installed'); await manager.refresh(); }} />
<Button variant="outline" size="sm" disabled={!manager.available || manager.busy} onClick={() => { setPluginView('installed'); void manager.importPackage(); }}><FolderOpen size={14} className="mr-2" />{t('settings.plugins.manager.import')}</Button>
</div>
</div>
@@ -693,6 +693,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
{httpNetworkProxy.mode === "custom" && (
<>
<SettingRow
anchorId="system-network-proxy-url"
label={t("settings.system.networkProxy.url")}
description={t("settings.system.networkProxy.url.desc")}
>
@@ -710,6 +711,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
/>
</SettingRow>
<SettingRow
anchorId="system-network-proxy-bypass"
label={t("settings.system.networkProxy.bypass")}
description={t("settings.system.networkProxy.bypass.desc")}
>
@@ -1088,7 +1090,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
</SettingRow>
{/* Directory Selection */}
<div className="space-y-2">
<SettingsAnchor anchorId="system-session-logs-directory" className="space-y-2">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{t("settings.sessionLogs.directory")}</span>
</div>
@@ -1125,10 +1127,11 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
<p className="text-xs text-muted-foreground">
{t("settings.sessionLogs.directoryHint")}
</p>
</div>
</SettingsAnchor>
{/* Format Selection */}
<SettingRow
anchorId="system-session-logs-format"
label={t("settings.sessionLogs.format")}
description={t("settings.sessionLogs.formatDesc")}
>
@@ -1141,6 +1144,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
</SettingRow>
<SettingRow
anchorId="system-session-logs-timestamps"
label={t("settings.sessionLogs.timestamps")}
description={t("settings.sessionLogs.timestampsDesc")}
>
@@ -814,6 +814,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-side-panel-auto-open-pane"
label={t("settings.terminal.sidePanel.autoOpenPane")}
description={t("settings.terminal.sidePanel.autoOpenPane.desc")}
>
@@ -841,6 +842,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-local-shell-side-panel-auto-open-pane"
label={t("settings.terminal.localShellSidePanel.autoOpenPane")}
description={t("settings.terminal.localShellSidePanel.autoOpenPane.desc")}
>
@@ -945,6 +947,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-local-shell-start-dir"
label={t("settings.terminal.localShell.startDir")}
description={t("settings.terminal.localShell.startDir.desc")}
>
@@ -1048,6 +1051,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-keepalive-count-max"
label={t("settings.terminal.connection.keepaliveCountMax")}
description={t("settings.terminal.connection.keepaliveCountMax.desc")}
>
@@ -1082,6 +1086,7 @@ function SettingsTerminalTab(props: {
<SectionHeader title={t("settings.terminal.section.serverStats")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-host-info-bar-show"
label={t("settings.terminal.hostInfoBar.show")}
description={t("settings.terminal.hostInfoBar.show.desc")}
>
@@ -1092,6 +1097,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
{terminalSettings.showHostInfoBar && (
<SettingRow
anchorId="terminal-host-info-bar-title-mode"
label={t("settings.terminal.hostInfoBar.titleMode")}
description={t("settings.terminal.hostInfoBar.titleMode.desc")}
>
@@ -1119,6 +1125,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.showServerStats && (
<SettingRow
anchorId="terminal-server-stats-refresh-interval"
label={t("settings.terminal.serverStats.refreshInterval")}
description={t("settings.terminal.serverStats.refreshInterval.desc")}
>
@@ -1145,6 +1152,7 @@ function SettingsTerminalTab(props: {
<SectionHeader title={t("settings.terminal.section.systemManager")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-system-manager-process-refresh-interval"
label={t("settings.terminal.systemManager.processRefreshInterval")}
description={t("settings.terminal.systemManager.processRefreshInterval.desc")}
>
@@ -1166,6 +1174,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-tmux-refresh-interval"
label={t("settings.terminal.systemManager.tmuxRefreshInterval")}
description={t("settings.terminal.systemManager.tmuxRefreshInterval.desc")}
>
@@ -1187,6 +1196,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-docker-list-refresh-interval"
label={t("settings.terminal.systemManager.dockerListRefreshInterval")}
description={t("settings.terminal.systemManager.dockerListRefreshInterval.desc")}
>
@@ -1208,6 +1218,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-docker-stats-refresh-interval"
label={t("settings.terminal.systemManager.dockerStatsRefreshInterval")}
description={t("settings.terminal.systemManager.dockerStatsRefreshInterval.desc")}
>
@@ -1249,6 +1260,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-hidden-tabs"
label={t("settings.terminal.rendering.hibernateHiddenTabs")}
description={t("settings.terminal.rendering.hibernateHiddenTabs.desc")}
>
@@ -1260,6 +1272,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.hibernateHiddenTabs && (
<>
<SettingRow
anchorId="terminal-hibernate-hidden-tabs-delay"
label={t("settings.terminal.rendering.hibernateHiddenTabsDelay")}
description={t("settings.terminal.rendering.hibernateHiddenTabsDelay.desc")}
>
@@ -1281,6 +1294,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-skip-alt-screen"
label={t("settings.terminal.rendering.hibernateSkipAltScreen")}
description={t("settings.terminal.rendering.hibernateSkipAltScreen.desc")}
>
@@ -1290,6 +1304,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-keep-renderer-count"
label={t("settings.terminal.rendering.hibernateKeepRendererCount")}
description={t("settings.terminal.rendering.hibernateKeepRendererCount.desc")}
>
@@ -1308,6 +1323,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-replay-chunk-bytes"
label={t("settings.terminal.rendering.hibernateReplayChunkBytes")}
description={t("settings.terminal.rendering.hibernateReplayChunkBytes.desc")}
>
@@ -1327,6 +1343,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-prefer-wasm-serialize"
label={t("settings.terminal.rendering.hibernatePreferWasmSerialize")}
description={t("settings.terminal.rendering.hibernatePreferWasmSerialize.desc")}
>
@@ -1354,6 +1371,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.inlineImagesEnabled && (
<>
<SettingRow
anchorId="terminal-inline-images-kitty"
label={t("settings.terminal.inlineImages.kitty")}
description={t("settings.terminal.inlineImages.kitty.desc")}
>
@@ -1363,6 +1381,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-sixel"
label={t("settings.terminal.inlineImages.sixel")}
description={t("settings.terminal.inlineImages.sixel.desc")}
>
@@ -1372,6 +1391,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-iip"
label={t("settings.terminal.inlineImages.iip")}
description={t("settings.terminal.inlineImages.iip.desc")}
>
@@ -1381,6 +1401,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-storage-limit"
label={t("settings.terminal.inlineImages.storageLimit")}
description={t("settings.terminal.inlineImages.storageLimit.desc")}
>
@@ -1406,6 +1427,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-max-megapixels"
label={t("settings.terminal.inlineImages.maxMegapixels")}
description={t("settings.terminal.inlineImages.maxMegapixels.desc")}
>
@@ -1431,6 +1453,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-sequence-limit"
label={t("settings.terminal.inlineImages.sequenceLimit")}
description={t("settings.terminal.inlineImages.sequenceLimit.desc")}
>
@@ -1496,6 +1519,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-ghost-text"
label={t("settings.terminal.autocomplete.ghostText")}
description={t("settings.terminal.autocomplete.ghostText.desc")}
>
@@ -1506,6 +1530,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-popup-menu"
label={t("settings.terminal.autocomplete.popupMenu")}
description={t("settings.terminal.autocomplete.popupMenu.desc")}
>
@@ -1516,6 +1541,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-history-scope"
label={t("settings.terminal.autocomplete.historyScope")}
description={t("settings.terminal.autocomplete.historyScope.desc")}
>
@@ -101,6 +101,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-right-click-long-press-menu"
label={t("settings.terminal.behavior.rightClick.longPressMenu")}
description={t("settings.terminal.behavior.rightClick.longPressMenu.desc")}
>
@@ -111,6 +112,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-right-click-fullscreen-menu"
label={t("settings.terminal.behavior.rightClick.fullscreenMenu")}
description={t("settings.terminal.behavior.rightClick.fullscreenMenu.desc")}
>
@@ -228,6 +230,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-shift-enter-newline-text"
label={t("settings.terminal.behavior.shiftEnterNewlineText")}
description={t("settings.terminal.behavior.shiftEnterNewlineText.desc")}
>
@@ -260,6 +263,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-preserve-selection-on-input"
label={t("settings.terminal.behavior.preserveSelectionOnInput")}
description={t("settings.terminal.behavior.preserveSelectionOnInput.desc")}
>
@@ -267,6 +271,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-force-prompt-new-line"
label={t("settings.terminal.behavior.forcePromptNewLine")}
description={t("settings.terminal.behavior.forcePromptNewLine.desc")}
>
@@ -341,6 +346,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-input"
label={t("settings.terminal.behavior.scrollOnInput")}
description={t("settings.terminal.behavior.scrollOnInput.desc")}
>
@@ -348,6 +354,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-output"
label={t("settings.terminal.behavior.scrollOnOutput")}
description={t("settings.terminal.behavior.scrollOnOutput.desc")}
>
@@ -355,6 +362,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-key-press"
label={t("settings.terminal.behavior.scrollOnKeyPress")}
description={t("settings.terminal.behavior.scrollOnKeyPress.desc")}
>
@@ -362,6 +370,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-paste"
label={t("settings.terminal.behavior.scrollOnPaste")}
description={t("settings.terminal.behavior.scrollOnPaste.desc")}
>
@@ -369,6 +378,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-smooth-scrolling"
label={t("settings.terminal.behavior.smoothScrolling")}
description={t("settings.terminal.behavior.smoothScrolling.desc")}
>
@@ -392,6 +402,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-link-modifier"
label={t("settings.terminal.behavior.linkModifier")}
description={t("settings.terminal.behavior.linkModifier.desc")}
>
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more