Compare commits

...
Author SHA1 Message Date
bincxz 07d1a6f2c1 fix(sftp): focus the safe conflict action on open 2026-09-25 15:24:09 +08:00
626e0ce5bd fix(quick-connect): accept multi-@ jump chains like JumpServer (#3525)
* fix(#3523): automated AI fix

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

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

* fix(#3523): guard JumpServer credential presets

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

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

---------

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

* fix: address Codex review on PR #3524

* fix: address Codex review on PR #3524

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

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

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

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-09-24 17:48:22 +08:00
陈大猫 0261931f95 fix(terminal): keep broadcast going on vim ex command-line (#3467)
* fix(terminal): keep broadcast going on vim ex command-line

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

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

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

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

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

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

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

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

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

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

* fix: address Codex review on PR #3456

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

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

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

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

---------

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

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

* fix: address Codex review on PR #3451

---------

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

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

* fix: address Codex review on PR #3400

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

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

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

* test(terminal): cover paced input write options

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

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

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

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

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

* fix: record paced paste commands after transport writes

* fix: omit paste receipts for filtered input

* fix: cancel superseded paste batches across input paths

* fix: classify each acknowledged paste line before recording

* fix: stop paced paste when editing buffered serial input

* fix: preserve recording pause boundaries and serial edit cancellation

* fix: treat paced terminal pastes as user input

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

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

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

---------

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

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: address Codex review on PR #3409

* fix: preserve physical releases for Command-period interrupts

* fix: allow Command-period with selected terminal text

* style: keep Command-period additions ASCII-only

* test: validate Command-period fixture without renderer errors

* fix: support logical period across macOS keyboard layouts

---------

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

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: address Codex review on PR #3418

* fix: guard serial quick login and reconnect startup commands

* fix: preserve serial startup while tabs sleep

---------

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

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

---------

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

* test: clean up drag-drop suppression expiry watchdog

---------

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

* fix: address Codex review on PR #3402

* fix: address Codex review on PR #3402

* fix: address Codex review on PR #3402

---------

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

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

* fix: wire local shell side panel settings

* fix: restore undefined check for local shell protocol detection

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

* fix: enable SFTP sidebar for local shell sessions

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

* chore: bump version to 1.1.83-fork.1

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

* feat: show SFTP button in local shell toolbar

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

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

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

* feat: support PowerShell and CMD in session restore

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

* fix: bound local shell panel preferences and synchronize settings

---------

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

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

* feat(mcp): guide agents toward Netcatty tools

* feat(mcp): load Netcatty toolsets on demand

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

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

* feat(mcp): add universal client setup prompt

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

* chore(ai): refresh generated tool specs

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

---------

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

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: address Codex review on PR #3391

* fix: preserve SecureCRT launch targets and operand boundaries

* fix: redact SecureCRT credentials before legacy switch scrubbing

* fix: reject ambiguous SecureCRT launch destinations

* fix: reject unknown slash switches consistently

* fix: reject mixed client switches in SecureCRT launches

---------

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

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

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

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

* fix(terminal): preserve unknown GPU memory totals

---------

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

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

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

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

* fix(terminal): preserve WSL command argument boundaries

* fix(terminal): retain legacy WSL distribution selectors

---------

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

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

---------

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

* fix: address Codex review on PR #3427

* fix: keep autocomplete detail reserve within narrow panes

---------

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

* fix: address Codex review on PR #3429

* fix: address Codex review on PR #3429

* fix: address Codex review on PR #3429

* fix: require confirmation for changed managed deletion files

* fix: bind managed deletion confirmation to group scope

---------

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

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

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

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

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

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

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

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

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

* fix: warn when CSV proxy credentials cannot be exported

---------

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

No files matched your search

+2
View File
@@ -11,6 +11,7 @@ import { TooltipProvider } from './components/ui/tooltip';
import { ScriptAutomationRoot } from './components/scripts/ScriptAutomationRoot';
import { ExternalMcpApprovalsHost } from './components/ai/ExternalMcpApprovalsHost';
import { PluginAuthenticationHost } from './components/plugins/PluginAuthenticationHost';
import { MultilinePasteConfirmHost } from './components/terminal/MultilinePasteConfirmDialog';
import { useExternalMcpGrantPersister } from './components/ai/useExternalMcpGrantPersister';
import { setupMcpApprovalBridge } from './infrastructure/ai/shared/approvalGate';
import { setupCodexAppServerInteractionBridge } from './infrastructure/ai/shared/codexAppServerInteractions';
@@ -81,6 +82,7 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
<ScriptAutomationRoot />
<ExternalMcpApprovalsHost />
<PluginAuthenticationHost />
<MultilinePasteConfirmHost />
<VaultPublisher>
<SessionPublisher persistSessionRestore={!isPeerSessionWindow}>
<App />
@@ -698,3 +698,51 @@ test('connection log host snapshot includes custom host icon fields', () => {
},
);
});
for (const scenario of [
{ name: 'single orphan', active: 'one', sessions: [{ id: 'one' }], available: false, expected: null },
{ name: 'two orphans', active: 'one', sessions: [{ id: 'one' }, { id: 'two' }], available: true, expected: 'global' },
{ name: 'hidden active session', active: 'hidden', sessions: [{ id: 'one' }, { id: 'two' }, { id: 'hidden', hiddenFromTabs: true }], available: true, expected: null },
{ name: 'non-terminal tab', active: 'vault', sessions: [{ id: 'one' }, { id: 'two' }], available: true, expected: null },
{ name: 'workspace', active: 'workspace', sessions: [{ id: 'one', workspaceId: 'workspace' }, { id: 'two', workspaceId: 'workspace' }], available: false, expected: 'workspace' },
]) {
for (const scheme of ['pc', 'mac'] as const) {
test(`broadcast shortcut ${scheme}: ${scenario.name} only consumes an executed toggle`, () => {
const target = new FakeHTMLElement();
let prevented = 0;
let stopped = 0;
let globalEnabled = false;
let workspaceEnabled = false;
const toggles: string[] = [];
const event = {
key: 'b', code: 'KeyB', ctrlKey: scheme === 'pc', metaKey: scheme === 'mac',
altKey: false, shiftKey: false, target, composedPath: () => [target],
preventDefault: () => { prevented += 1; },
stopPropagation: () => { stopped += 1; },
} as unknown as KeyboardEvent;
const actionCtx = {
activeTabStore: { getActiveTabId: () => scenario.active },
editorTabs: [], orderedTabs: [], settings: {}, toEditorTabId: (id: string) => id,
sessions: scenario.sessions,
workspaces: scenario.active === 'workspace' ? [{ id: 'workspace' }] : [],
canUseGlobalBroadcast: scenario.available,
toggleGlobalBroadcast: () => { globalEnabled = !globalEnabled; toggles.push('global'); },
toggleBroadcast: (id: string) => { assert.equal(id, 'workspace'); workspaceEnabled = !workspaceEnabled; toggles.push('workspace'); },
};
const invoke = () => handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false, closeTabKeyStr: '', hotkeyScheme: scheme,
keyBindings: DEFAULT_KEY_BINDINGS, matchesKeyBinding,
executeHotkeyAction: (action: string, e: KeyboardEvent) => executeHotkeyActionImpl(() => actionCtx, action, e),
}), event);
invoke();
assert.equal(globalEnabled, scenario.expected === 'global');
assert.equal(workspaceEnabled, scenario.expected === 'workspace');
invoke();
assert.equal(globalEnabled, false);
assert.equal(workspaceEnabled, false);
assert.deepEqual(toggles, scenario.expected ? [scenario.expected, scenario.expected] : []);
assert.equal(prevented, scenario.expected ? 2 : 0);
assert.equal(stopped, scenario.expected ? 2 : 0);
});
}
}
+14 -2
View File
@@ -313,6 +313,16 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
continue;
}
// An unavailable broadcast action must leave the chord to the terminal
// (notably tmux's Ctrl+B prefix). Dispatch once before consuming it.
if (binding.action === 'broadcast') {
if (executeHotkeyAction(binding.action, e) === true) {
e.preventDefault();
e.stopPropagation();
}
return;
}
e.preventDefault();
e.stopPropagation();
if (HOTKEY_DEBUG) {
@@ -963,12 +973,14 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
const activeWs = workspaces.find(w => w.id === currentId);
if (activeWs) {
toggleBroadcast(activeWs.id);
return true;
} else if (sessions.some((session: TerminalSession) => (
session.id === currentId && !session.workspaceId
session.id === currentId && !session.workspaceId && !session.hiddenFromTabs
)) && canUseGlobalBroadcast) {
toggleGlobalBroadcast();
return true;
}
break;
return false;
}
case 'openSettings':
handleOpenSettingsRef.current();
+7
View File
@@ -252,6 +252,8 @@ export function AppSideEffects() {
runSnippet,
getOrderedWorkTabs,
toggleBroadcast,
toggleGlobalBroadcast,
canUseGlobalBroadcast,
logViews,
closeLogView,
copySession,
@@ -906,6 +908,8 @@ export function AppSideEffects() {
// array thrash does not rebuild appTerminalDomain (see domain isolation).
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
const canUseGlobalBroadcastRef = useRef(canUseGlobalBroadcast);
canUseGlobalBroadcastRef.current = canUseGlobalBroadcast;
// Logs live in connectionLogsStore — keep a ref fresh without re-rendering App.
const connectionLogsRef = useRef(getConnectionLogsSnapshot().connectionLogs);
useEffect(() => {
@@ -1076,6 +1080,8 @@ export function AppSideEffects() {
terminalPaneMagnificationRef,
toEditorTabId,
toggleBroadcast,
toggleGlobalBroadcast,
canUseGlobalBroadcast: canUseGlobalBroadcastRef.current,
toggleScriptsSidePanelRef,
toggleSidePanelRef,
toggleWorkspaceViewMode,
@@ -1090,6 +1096,7 @@ export function AppSideEffects() {
splitSessionWithCurrentShell,
moveFocusInWorkspace,
toggleBroadcast,
toggleGlobalBroadcast,
toggleWorkspaceViewMode,
confirmIfBusyLocalTerminal,
]);
+4
View File
@@ -300,6 +300,8 @@ function AppViewInner({ domains }: AppViewProps) {
restoreTerminalCwd,
terminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
} = useSettingsChromeStore();
const { setTheme, setWindowOpacity } = useSettingsChromeActions();
@@ -752,6 +754,8 @@ function AppViewInner({ domains }: AppViewProps) {
sftpAutoOpenSidebar={sftpAutoOpenSidebar}
terminalSidePanelAutoOpen={terminalSidePanelAutoOpen}
terminalSidePanelAutoOpenTab={terminalSidePanelAutoOpenTab}
localShellSidePanelAutoOpen={localShellSidePanelAutoOpen}
localShellSidePanelAutoOpenTab={localShellSidePanelAutoOpenTab}
sftpFollowTerminalCwd={sftpFollowTerminalCwd}
setSftpFollowTerminalCwd={setSftpFollowTerminalCwd}
editorWordWrap={editorWordWrap}
+22 -6
View File
@@ -1,10 +1,12 @@
import type { TransferOwnerObservation } from "../state/sftp/waitForTransferOwner";
import type { TransferStatus, TransferTask } from "../../domain/models";
export const DEDICATED_RESUME_LARGE_HISTORY_THRESHOLD = 4_096;
export const DEDICATED_RESUME_CHILD_UPDATE_BATCH_SIZE = 512;
export interface DedicatedResumeChildUpdateBatcher {
push(task: TransferTask): void;
push(task: TransferTask, observation?: TransferOwnerObservation): void;
discard(taskId: string): void;
flush(): void;
}
@@ -24,25 +26,39 @@ export function createDedicatedResumeChildUpdateBatcher(deps: {
hasTask: (taskId: string) => boolean;
upsertTasks: (tasks: readonly TransferTask[]) => void;
}): DedicatedResumeChildUpdateBatcher {
const pending = new Map<string, TransferTask>();
const pending = new Map<string, { task: TransferTask; observation?: TransferOwnerObservation }>();
const flush = () => {
if (pending.size === 0) return;
const batch = [...pending.values()];
pending.clear();
deps.upsertTasks(batch);
try {
const updates = batch.filter(({ observation }) => !observation?.hasIdentityConflict()).map(({ task }) => task);
if (updates.length) deps.upsertTasks(updates);
} finally {
for (const { observation } of batch) observation?.dispose();
}
};
return {
push(task) {
push(task, observation) {
if (observation?.hasIdentityConflict()) {
pending.get(task.id)?.observation?.dispose();
pending.delete(task.id);
observation.dispose();
return;
}
const shouldBatch = !!task.parentTaskId
&& deps.getTaskCount() >= DEDICATED_RESUME_LARGE_HISTORY_THRESHOLD
&& deps.hasTask(task.id);
if (!shouldBatch) {
deps.upsertTasks([task]);
try { deps.upsertTasks([task]); } finally { observation?.dispose(); }
return;
}
pending.set(task.id, task);
const previous = pending.get(task.id);
if (previous?.observation && previous.observation !== observation) previous.observation.dispose();
pending.set(task.id, { task, observation });
if (pending.size >= DEDICATED_RESUME_CHILD_UPDATE_BATCH_SIZE) flush();
},
discard: (taskId) => { pending.get(taskId)?.observation?.dispose(); pending.delete(taskId); },
flush,
};
}
+5 -2
View File
@@ -181,11 +181,14 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
},
{
children,
onChildUpdate: (child) => {
onChildUpdate: (child, observation) => {
if (acceptsResumeCallbacks) {
childUpdateBatcher.push({ ...child, ownerId: "dedicated-resume" });
childUpdateBatcher.push({ ...child, ownerId: "dedicated-resume" }, observation);
return true;
}
},
onChildSuperseded: (taskId) => childUpdateBatcher.discard(taskId),
flushChildUpdates: () => childUpdateBatcher.flush(),
onDirectoryCheckpointUpdate: (checkpoint) => {
if (acceptsResumeCallbacks) {
sftpTransferCenterStore.patchTask(task.id, {
+11 -5
View File
@@ -364,21 +364,24 @@ export const enAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Other',
'ai.externalMcp.cliCommand': 'CLI command',
'ai.externalMcp.configSnippet': 'Config snippet',
'ai.externalMcp.universalSetupPrompt': 'Universal setup prompt',
'ai.externalMcp.addToCodex': 'Add to Codex',
'ai.externalMcp.addToClaude': 'Add to Claude Code',
'ai.externalMcp.addToGrok': 'Add to Grok',
'ai.externalMcp.codexAdded': 'Codex MCP entry added. Restart Codex or open a new Codex session.',
'ai.externalMcp.claudeAdded': 'Claude Code MCP entry added. Restart Claude Code or open a new Claude Code session.',
'ai.externalMcp.grokAdded': 'Grok MCP entry added. Restart Grok or open a new Grok session.',
'ai.externalMcp.codexAdded': 'Codex MCP entry and Netcatty skill added. Restart Codex or open a new Codex session.',
'ai.externalMcp.claudeAdded': 'Claude Code MCP entry and Netcatty skill added. Restart Claude Code or open a new Claude Code session.',
'ai.externalMcp.grokAdded': 'Grok MCP entry and Netcatty skill added. Restart Grok or open a new Grok session.',
'ai.externalMcp.installCodex': 'Install Codex separately, then click Refresh.',
'ai.externalMcp.installClaude': 'Install Claude Code separately, then click Refresh.',
'ai.externalMcp.installGrok': 'Install the Grok CLI separately, then click Refresh.',
'ai.externalMcp.conflict.description': 'A netcatty-external entry already exists and points elsewhere. Remove or edit it manually.',
'ai.externalMcp.enableForLauncher': 'Enable External MCP to get a usable launcher path.',
'ai.externalMcp.cursor.title': 'Cursor / other clients',
'ai.externalMcp.cursor.description': 'Merge this into your MCP config (for example ~/.cursor/mcp.json). Do not replace the whole file if you already have other servers.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Merge this into your Cursor MCP configuration without replacing existing servers.',
'ai.externalMcp.other.description': 'Copy the setup prompt into another terminal agent, or merge the MCP snippet into its client configuration.',
'ai.externalMcp.status.unavailable': 'Unavailable',
'ai.externalMcp.status.disabled': 'Disabled',
'ai.externalMcp.status.running': 'Running',
@@ -599,6 +602,9 @@ export const enAiMessages: Messages = {
'terminal.layer.movePanelRight': 'Move panel to right',
'terminal.layer.closePanel': 'Close panel',
'terminal.layer.closePane': 'Close split',
'terminal.layer.saveLayoutAsDefault': 'Save layout as default',
'terminal.layer.layoutSavedAsDefault': 'Layout saved as default',
'terminal.layer.layoutSaveFailed': 'Could not save layout',
'terminal.layer.resizeSplit': 'Resize split',
'terminal.layer.splitHorizontal': 'Split top and bottom',
'terminal.layer.splitVertical': 'Split left and right',
+17
View File
@@ -649,6 +649,12 @@ Highlight the focused split pane:
'settings.terminal.sidePanel.pane.system': 'System',
'settings.terminal.sidePanel.pane.notes': 'Notes',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': 'Local Shell Side Panel',
'settings.terminal.localShellSidePanel.autoOpen': 'Open side panel with local shell',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Automatically open a side panel when opening a local shell.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Default side panel',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Choose which panel opens first.',
'settings.terminal.localShellSidePanel.pane.files': 'Files',
'settings.terminal.accessibility.minimumContrastRatio.desc':
'Adjust colors to meet contrast requirements (1 = disabled, 21 = max)',
'settings.terminal.behavior.rightClick': 'Right-click behavior',
@@ -691,6 +697,12 @@ Highlight the focused split pane:
'settings.terminal.behavior.autoUploadClipboardImage': 'Auto-upload clipboard images on paste',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'When the clipboard holds an image, pasting in a remote session uploads it via SFTP to .netcatty-paste-images/ under the remote working directory and inserts the remote path instead of pasting text.',
'settings.terminal.behavior.confirmMultilinePaste': 'Ask before pasting multiple lines',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Show a confirmation dialog before pasting multiple lines, with the line/character count, an editable preview, and Send / Send line by line / Cancel actions. Protects switch and firewall CLIs (Cisco IOS, Huawei VRP, H3C Comware) that do not support bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Confirmation threshold (lines)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Ask for confirmation when a paste contains at least this many lines.',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter text',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Send configured text instead of normal Enter when pressing Shift+Enter in the terminal.',
@@ -1048,6 +1060,10 @@ Highlight the focused split pane:
'vault.groups.deleteDialogTitle': 'Delete Group',
'vault.groups.deleteDialog.desc': 'This will permanently delete the group and move all hosts to the root level.',
'vault.groups.deleteDialog.managedDesc': 'This is a managed SSH config group. Deleting it will also delete all hosts and unlink from the source file.',
'vault.groups.deleteDialog.mixedDesc': 'This group contains hosts imported from a linked SSH config file. Every host under its managed subgroup will be deleted, even hosts not managed by that file. All other hosts will move to the root level unless you also delete them below.',
'vault.groups.deleteDialog.managedWarning': 'Deleting this group will also clear its entries from the linked SSH config file. Entries that came from that file may be lost for other apps that use it. Back up the file before continuing.',
'vault.groups.deleteDialog.sourcesChanged': 'The managed files affected by this deletion have changed. Review the files and confirm again.',
'vault.groups.deleteDialog.managedFile': 'Linked file: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Also delete all hosts in this group',
'vault.groups.deleteDialog.bulkTitle': 'Delete Selected Groups',
'vault.groups.deleteDialog.bulkDesc': 'This will permanently delete the selected groups and move their hosts to the root level.',
@@ -1106,6 +1122,7 @@ Highlight the focused split pane:
'vault.hosts.export.toast.success': 'Exported {count} hosts to CSV',
'vault.hosts.export.toast.successWithSkipped': 'Exported {count} hosts to CSV ({skipped} unsupported hosts skipped)',
'vault.hosts.export.toast.passphrasesSkipped': '{count} saved key passphrases could not be read and were left blank',
'vault.hosts.export.toast.proxyCredentialsSkipped': '{count} saved proxy passwords could not be read and were left blank',
'vault.hosts.export.toast.noHosts': 'No hosts to export',
'vault.hosts.allHosts': 'All hosts',
'vault.hosts.pinned': 'Pinned',
+12
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const enTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Save current screen',
'terminal.saveScreen.failed': 'Failed to save terminal screen.',
// Multi-line paste confirmation dialog (#3398)
'terminal.pasteConfirm.title': 'Paste multiple lines?',
'terminal.pasteConfirm.summary': '{lines} lines ({chars} characters) will be sent to the session.',
'terminal.pasteConfirm.preview': 'Preview (editable)',
'terminal.pasteConfirm.send': 'Send',
'terminal.pasteConfirm.sendLineByLine': 'Send line by line',
'terminal.pasteConfirm.cancel': 'Cancel',
'terminal.sudoHint.pressEnter': 'Press Enter to paste saved password',
'terminal.passwordPicker.title': 'Saved passwords',
'terminal.passwordPicker.empty': 'No saved passwords',
@@ -93,6 +100,7 @@ export const enTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Reconnect this session',
'terminal.serverStats.cpu': 'CPU Usage',
'terminal.serverStats.cpuCores': 'CPU Core Usage',
'terminal.serverStats.gpu': 'GPU Usage',
'terminal.serverStats.memory': 'Memory Usage',
'terminal.serverStats.memoryDetails': 'Memory Details',
'terminal.serverStats.memUsed': 'Used',
@@ -827,6 +835,10 @@ export const enTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'e.g. Arduino Uno',
'serial.connectAndSave': 'Connect & Save',
'serial.edit.title': 'Serial Port Settings',
'serial.field.username': 'Username',
'serial.field.password': 'Password',
'serial.field.autoLoginDesc': 'When set, Login/Password prompts on the serial console are answered automatically with these saved credentials.',
'serial.field.clearPassword': 'Clear saved password',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Authentication Required',
+8 -5
View File
@@ -355,21 +355,24 @@ export const esAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Otros',
'ai.externalMcp.cliCommand': 'Comando CLI',
'ai.externalMcp.configSnippet': 'Fragmento de configuración',
'ai.externalMcp.universalSetupPrompt': 'Prompt de instalación universal',
'ai.externalMcp.addToCodex': 'Agregar a Codex',
'ai.externalMcp.addToClaude': 'Agregar a Claude Code',
'ai.externalMcp.addToGrok': 'Agregar a Grok',
'ai.externalMcp.codexAdded': 'Entrada de MCP de Codex agregada. Reinicia Codex o abre una nueva sesión de Codex.',
'ai.externalMcp.claudeAdded': 'Entrada de MCP de Claude Code agregada. Reinicia Claude Code o abre una nueva sesión de Claude Code.',
'ai.externalMcp.grokAdded': 'Entrada de MCP de Grok agregada. Reinicia Grok o abre una nueva sesión de Grok.',
'ai.externalMcp.codexAdded': 'Entrada MCP de Codex y skill de Netcatty agregados. Reinicia Codex o abre una nueva sesión de Codex.',
'ai.externalMcp.claudeAdded': 'Entrada MCP de Claude Code y skill de Netcatty agregados. Reinicia Claude Code o abre una nueva sesión de Claude Code.',
'ai.externalMcp.grokAdded': 'Entrada MCP de Grok y skill de Netcatty agregados. Reinicia Grok o abre una nueva sesión de Grok.',
'ai.externalMcp.installCodex': 'Instala Codex por separado y luego haz clic en Actualizar.',
'ai.externalMcp.installClaude': 'Instala Claude Code por separado y luego haz clic en Actualizar.',
'ai.externalMcp.installGrok': 'Instala la CLI de Grok por separado y luego haz clic en Actualizar.',
'ai.externalMcp.conflict.description': 'Ya existe una entrada netcatty-external que apunta a otro lugar. Quítala o edítala manualmente.',
'ai.externalMcp.enableForLauncher': 'Habilita el MCP externo para obtener una ruta de launcher utilizable.',
'ai.externalMcp.cursor.title': 'Cursor / otros clientes',
'ai.externalMcp.cursor.description': 'Combina esto en tu configuración de MCP (por ejemplo, ~/.cursor/mcp.json). No reemplaces todo el archivo si ya tienes otros servidores.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Combina esto con la configuración MCP de Cursor sin reemplazar los servidores existentes.',
'ai.externalMcp.other.description': 'Copia el prompt de instalación en otro agente de terminal o combina el fragmento MCP con la configuración de su cliente.',
'ai.externalMcp.status.unavailable': 'No disponible',
'ai.externalMcp.status.disabled': 'Desactivado',
'ai.externalMcp.status.running': 'En ejecución',
+17
View File
@@ -564,6 +564,12 @@ Resalta el panel dividido enfocado:
'settings.terminal.sidePanel.pane.system': 'Sistema',
'settings.terminal.sidePanel.pane.notes': 'Notas',
'settings.terminal.sidePanel.pane.ai': 'IA',
'settings.terminal.section.localShellSidePanel': 'Panel lateral de Shell local',
'settings.terminal.localShellSidePanel.autoOpen': 'Expandir panel lateral al abrir Shell local',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Abre automáticamente un panel lateral después de abrir el Shell local.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Panel lateral predeterminado',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Elige qué panel se abre primero.',
'settings.terminal.localShellSidePanel.pane.files': 'Archivos',
'settings.terminal.accessibility.minimumContrastRatio.desc':
'Ajusta los colores para cumplir con los requisitos de contraste (1 = desactivado, 21 = máximo)',
'settings.terminal.behavior.rightClick': 'Comportamiento del clic derecho',
@@ -606,6 +612,12 @@ Resalta el panel dividido enfocado:
'settings.terminal.behavior.autoUploadClipboardImage': 'Subir automáticamente imágenes del portapapeles al pegar',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'Cuando el portapapeles contiene una imagen, pegarla en una sesión remota la sube por SFTP a .netcatty-paste-images/ dentro del directorio de trabajo remoto e inserta la ruta remota en lugar de pegar texto.',
'settings.terminal.behavior.confirmMultilinePaste': 'Preguntar antes de pegar varias líneas',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Muestra un diálogo de confirmación antes de pegar varias líneas, con el número de líneas y caracteres, una vista previa editable y las acciones Enviar / Enviar línea por línea / Cancelar. Protege las CLI de dispositivos de red (Cisco IOS, Huawei VRP, H3C Comware) que no admiten bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Umbral de confirmación (líneas)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Pedir confirmación cuando el texto pegado contenga al menos esta cantidad de líneas.',
'settings.terminal.behavior.shiftEnterNewline': 'Texto de Shift+Enter',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Envía el texto configurado en lugar del Enter normal al presionar Shift+Enter en la terminal.',
@@ -1006,6 +1018,10 @@ Resalta el panel dividido enfocado:
'vault.groups.deleteDialogTitle': 'Eliminar grupo',
'vault.groups.deleteDialog.desc': 'Esto eliminará permanentemente el grupo y moverá todos los hosts al nivel raíz.',
'vault.groups.deleteDialog.managedDesc': 'Este es un grupo administrado de configuración SSH. Eliminarlo también eliminará todos los hosts y lo desvinculará del archivo de origen.',
'vault.groups.deleteDialog.mixedDesc': 'Este grupo contiene hosts importados de un archivo de configuración SSH vinculado. Todos los hosts bajo su subgrupo administrado se eliminarán, incluso los hosts no administrados por ese archivo. Los demás hosts se moverán al nivel raíz a menos que también los elimine abajo.',
'vault.groups.deleteDialog.managedWarning': 'Al eliminar este grupo también se borrarán sus entradas del archivo de configuración SSH vinculado. Las entradas provenientes de ese archivo pueden perderse y también afectará a otras aplicaciones que lo usen. Haz una copia de seguridad del archivo antes de continuar.',
'vault.groups.deleteDialog.sourcesChanged': 'Los archivos administrados afectados por esta eliminación han cambiado. Revisa los archivos y vuelve a confirmar.',
'vault.groups.deleteDialog.managedFile': 'Archivo vinculado: {file}',
'vault.groups.deleteDialog.deleteHosts': 'También eliminar todos los hosts de este grupo',
'vault.groups.deleteDialog.bulkTitle': 'Eliminar grupos seleccionados',
'vault.groups.deleteDialog.bulkDesc': 'Esto eliminará permanentemente los grupos seleccionados y moverá sus hosts al nivel raíz.',
@@ -1064,6 +1080,7 @@ Resalta el panel dividido enfocado:
'vault.hosts.export.toast.success': 'Se exportaron {count} hosts a CSV',
'vault.hosts.export.toast.successWithSkipped': 'Se exportaron {count} hosts a CSV (se omitieron {skipped} hosts no compatibles)',
'vault.hosts.export.toast.passphrasesSkipped': 'No se pudieron leer {count} frases de contraseña de claves guardadas y se dejaron en blanco',
'vault.hosts.export.toast.proxyCredentialsSkipped': 'No se pudieron leer {count} contraseñas de proxy guardadas y se dejaron en blanco',
'vault.hosts.export.toast.noHosts': 'No hay hosts para exportar',
'vault.hosts.allHosts': 'Todos los hosts',
'vault.hosts.pinned': 'Fijados',
+12
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const esTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Guardar pantalla actual',
'terminal.saveScreen.failed': 'No se pudo guardar la pantalla del terminal.',
// Diálogo de confirmación de pegado multilínea (#3398)
'terminal.pasteConfirm.title': '¿Pegar varias líneas?',
'terminal.pasteConfirm.summary': 'Se enviarán {lines} líneas ({chars} caracteres) a la sesión.',
'terminal.pasteConfirm.preview': 'Vista previa (editable)',
'terminal.pasteConfirm.send': 'Enviar',
'terminal.pasteConfirm.sendLineByLine': 'Enviar línea por línea',
'terminal.pasteConfirm.cancel': 'Cancelar',
'terminal.sudoHint.pressEnter': 'Presiona Enter para pegar la contraseña guardada',
'terminal.passwordPicker.title': 'Contraseñas guardadas',
'terminal.passwordPicker.empty': 'No hay contraseñas guardadas',
@@ -93,6 +100,7 @@ export const esTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Reconectar esta sesión',
'terminal.serverStats.cpu': 'Uso de CPU',
'terminal.serverStats.cpuCores': 'Uso de núcleos de CPU',
'terminal.serverStats.gpu': 'Uso de GPU',
'terminal.serverStats.memory': 'Uso de memoria',
'terminal.serverStats.memoryDetails': 'Detalles de memoria',
'terminal.serverStats.memUsed': 'Usada',
@@ -827,6 +835,10 @@ export const esTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'p. ej., Arduino Uno',
'serial.connectAndSave': 'Conectar y guardar',
'serial.edit.title': 'Configuración del puerto serial',
'serial.field.username': 'Usuario',
'serial.field.password': 'Contraseña',
'serial.field.autoLoginDesc': 'Si se establecen, los mensajes Login/Password de la consola serial se responden automáticamente con estas credenciales guardadas.',
'serial.field.clearPassword': 'Borrar la contraseña guardada',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Se requiere autenticación',
+8 -5
View File
@@ -323,21 +323,24 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': 'Другие',
'ai.externalMcp.cliCommand': 'CLI-команда',
'ai.externalMcp.configSnippet': 'Фрагмент конфига',
'ai.externalMcp.universalSetupPrompt': 'Универсальный запрос установки',
'ai.externalMcp.addToCodex': 'Добавить в Codex',
'ai.externalMcp.addToClaude': 'Добавить в Claude Code',
'ai.externalMcp.addToGrok': 'Добавить в Grok',
'ai.externalMcp.codexAdded': 'Запись MCP для Codex добавлена. Перезапустите Codex или откройте новую сессию.',
'ai.externalMcp.claudeAdded': 'Запись MCP для Claude Code добавлена. Перезапустите Claude Code или откройте новую сессию.',
'ai.externalMcp.grokAdded': 'Запись MCP для Grok добавлена. Перезапустите Grok или откройте новую сессию.',
'ai.externalMcp.codexAdded': 'Запись MCP для Codex и навык Netcatty добавлены. Перезапустите Codex или откройте новую сессию.',
'ai.externalMcp.claudeAdded': 'Запись MCP для Claude Code и навык Netcatty добавлены. Перезапустите Claude Code или откройте новую сессию.',
'ai.externalMcp.grokAdded': 'Запись MCP для Grok и навык Netcatty добавлены. Перезапустите Grok или откройте новую сессию.',
'ai.externalMcp.installCodex': 'Сначала установите Codex, затем нажмите Обновить.',
'ai.externalMcp.installClaude': 'Сначала установите Claude Code, затем нажмите Обновить.',
'ai.externalMcp.installGrok': 'Сначала установите Grok CLI, затем нажмите Обновить.',
'ai.externalMcp.conflict.description': 'Запись netcatty-external уже существует и указывает в другое место. Удалите или измените её вручную.',
'ai.externalMcp.enableForLauncher': 'Включите External MCP, чтобы получить путь launcher.',
'ai.externalMcp.cursor.title': 'Cursor / другие клиенты',
'ai.externalMcp.cursor.description': 'Объедините с MCP-конфигом (например ~/.cursor/mcp.json). Не заменяйте весь файл, если там уже есть другие серверы.',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': 'Добавьте этот фрагмент в конфигурацию MCP Cursor, сохранив существующие серверы.',
'ai.externalMcp.other.description': 'Скопируйте запрос установки в другой терминальный агент или добавьте фрагмент MCP в конфигурацию его клиента.',
'ai.externalMcp.status.unavailable': 'Недоступно',
'ai.externalMcp.status.disabled': 'Выключено',
'ai.externalMcp.status.running': 'Работает',
+16
View File
@@ -648,6 +648,12 @@ export const ruCoreMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': 'Авто-загрузка изображений буфера обмена при вставке',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'Когда в буфере обмена есть изображение, вставка в удалённой сессии загружает его по SFTP в каталог .netcatty-paste-images/ в текущем удалённом каталоге и вводит удалённый путь вместо вставки текста.',
'settings.terminal.behavior.confirmMultilinePaste': 'Спрашивать перед вставкой нескольких строк',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'Перед вставкой нескольких строк показывать диалог подтверждения с количеством строк и символов, редактируемым предпросмотром и действиями «Отправить» / «Отправить построчно» / «Отмена». Защищает CLI сетевых устройств (Cisco IOS, Huawei VRP, H3C Comware), не поддерживающих bracketed paste.',
'settings.terminal.behavior.confirmMultilinePasteMinLines': 'Порог подтверждения (строк)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'Запрашивать подтверждение, если вставка содержит не меньше этого числа строк.',
'settings.terminal.behavior.shiftEnterNewline': 'Текст для Shift+Enter',
'settings.terminal.behavior.shiftEnterNewline.desc':
'Отправлять настроенный текст вместо обычного Enter при нажатии Shift+Enter в терминале.',
@@ -750,6 +756,12 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShell.startDir.placeholder': 'Домашний каталог',
'settings.terminal.localShell.startDir.notFound': 'Каталог не найден',
'settings.terminal.localShell.startDir.isFile': 'Путь указывает на файл, а не на каталог',
'settings.terminal.section.localShellSidePanel': 'Боковая панель локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen': 'Развернуть боковую панель при открытии локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
'settings.terminal.localShellSidePanel.autoOpenPane': 'Боковая панель по умолчанию',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.localShellSidePanel.pane.files': 'Файлы',
'settings.terminal.section.connection': 'Подключение',
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
'settings.terminal.connection.keepaliveInterval.desc': 'Как часто (в секундах) отправлять keepalive-пакеты на уровне SSH. Установите 0, чтобы отключить глобально. Учтите, что отдельные хосты могут переопределять это значение в своих настройках.',
@@ -1030,6 +1042,10 @@ export const ruCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': 'Удалить группу',
'vault.groups.deleteDialog.desc': 'Группа будет безвозвратно удалена, а все хосты будут перемещены в корень.',
'vault.groups.deleteDialog.managedDesc': 'Это управляемая группа SSH-конфига. При её удалении также будут удалены все хосты и снята связь с исходным файлом.',
'vault.groups.deleteDialog.mixedDesc': 'Эта группа содержит хосты, импортированные из связанного SSH-конфига. Все хосты под управляемой подгруппой будут удалены, включая хосты, не управляемые этим файлом. Остальные хосты будут перемещены в корень, если вы также не удалите их ниже.',
'vault.groups.deleteDialog.managedWarning': 'При удалении этой группы её записи также будут удалены из связанного файла конфигурации SSH. Записи, импортированные из этого файла, могут быть утеряны, это затронет и другие приложения, использующие файл. Сделайте резервную копию файла перед продолжением.',
'vault.groups.deleteDialog.sourcesChanged': 'Управляемые файлы, затрагиваемые этим удалением, изменились. Проверьте файлы и подтвердите удаление снова.',
'vault.groups.deleteDialog.managedFile': 'Связанный файл: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Также удалить все хосты в этой группе',
'vault.groups.deleteDialog.bulkTitle': 'Удалить выбранные группы',
'vault.groups.deleteDialog.bulkDesc': 'Выбранные группы будут безвозвратно удалены, а их хосты перемещены в корень.',
+12
View File
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const ruTerminalMessages: Messages = {
'terminal.menu.saveScreen': 'Сохранить текущий экран',
'terminal.saveScreen.failed': 'Не удалось сохранить экран терминала.',
// Диалог подтверждения многострочной вставки (#3398)
'terminal.pasteConfirm.title': 'Вставить несколько строк?',
'terminal.pasteConfirm.summary': 'В сессию будет отправлено строк: {lines} (символов: {chars}).',
'terminal.pasteConfirm.preview': 'Предпросмотр (можно изменить)',
'terminal.pasteConfirm.send': 'Отправить',
'terminal.pasteConfirm.sendLineByLine': 'Отправить построчно',
'terminal.pasteConfirm.cancel': 'Отмена',
'terminal.sudoHint.pressEnter': 'Нажмите Enter, чтобы вставить сохранённый пароль',
'terminal.passwordPicker.title': 'Сохранённые пароли',
'terminal.passwordPicker.empty': 'Нет сохранённых паролей',
@@ -114,6 +121,7 @@ export const ruTerminalMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': 'Переподключить эту сессию',
'terminal.serverStats.cpu': 'Использование CPU',
'terminal.serverStats.cpuCores': 'Использование ядер CPU',
'terminal.serverStats.gpu': 'Использование GPU',
'terminal.serverStats.memory': 'Использование памяти',
'terminal.serverStats.memoryDetails': 'Сведения о памяти',
'terminal.serverStats.memUsed': 'Использовано',
@@ -834,6 +842,10 @@ export const ruTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': 'например, Arduino Uno',
'serial.connectAndSave': 'Подключить и сохранить',
'serial.edit.title': 'Настройки последовательного порта',
'serial.field.username': 'Имя пользователя',
'serial.field.password': 'Пароль',
'serial.field.autoLoginDesc': 'Если задано, запросы Login/Password в последовательной консоли автоматически заполняются этими сохранёнными учётными данными.',
'serial.field.clearPassword': 'Очистить сохранённый пароль',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': 'Требуется аутентификация',
+1
View File
@@ -108,6 +108,7 @@ export const ruVaultMessages: Messages = {
'vault.hosts.export.toast.success': 'Экспортировано {count} хостов в CSV',
'vault.hosts.export.toast.successWithSkipped': 'Экспортировано {count} хостов в CSV ({skipped} неподдерживаемых хостов пропущено)',
'vault.hosts.export.toast.passphrasesSkipped': 'Не удалось прочитать {count} сохранённых парольных фраз ключей; они оставлены пустыми',
'vault.hosts.export.toast.proxyCredentialsSkipped': 'Не удалось прочитать {count} сохранённых паролей прокси; они оставлены пустыми',
'vault.hosts.export.toast.noHosts': 'Нет хостов для экспорта',
'vault.hosts.allHosts': 'Все хосты',
'vault.hosts.pinned': 'Закреплённые',
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import en from './en.ts';
import ru from './ru.ts';
import es from './es.ts';
import zhCN from './zh-CN.ts';
import zhTW from './zh-TW.ts';
const KEYS = [
'vault.groups.deleteDialog.managedDesc',
'vault.groups.deleteDialog.mixedDesc',
'vault.groups.deleteDialog.managedWarning',
'vault.groups.deleteDialog.managedFile',
] as const;
test('managed group delete warning copy exists in every locale', () => {
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const missing = KEYS.filter((key) => !messages[key]);
assert.deepEqual(missing, [], `${locale} is missing managed group delete copy`);
}
});
test('managed group delete warning mentions data loss in every locale', () => {
const MARKERS = ['备份', '備份', 'copia de seguridad', 'резервную копию', 'Back up'];
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const text = messages['vault.groups.deleteDialog.managedWarning'];
assert.match(
text ?? '',
/SSH/,
`${locale} warning should reference the SSH config file`,
);
assert.ok(
MARKERS.some((marker) => text?.includes(marker)),
`${locale} warning should tell the user to back up the file`,
);
}
});
test('linked file line interpolates the file path', () => {
for (const messages of [en, ru, es, zhCN, zhTW]) {
assert.match(
messages['vault.groups.deleteDialog.managedFile'] ?? '',
/\{file\}/,
'managedFile copy should include the {file} placeholder',
);
}
});
+11 -5
View File
@@ -364,21 +364,24 @@ export const zhCNAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': '其他',
'ai.externalMcp.cliCommand': 'CLI 命令',
'ai.externalMcp.configSnippet': '配置片段',
'ai.externalMcp.universalSetupPrompt': '通用安装提示词',
'ai.externalMcp.addToCodex': '添加到 Codex',
'ai.externalMcp.addToClaude': '添加到 Claude Code',
'ai.externalMcp.addToGrok': '添加到 Grok',
'ai.externalMcp.codexAdded': '已添加 Codex MCP 条目。请重启 Codex 或打开新会话。',
'ai.externalMcp.claudeAdded': '已添加 Claude Code MCP 条目。请重启 Claude Code 或打开新会话。',
'ai.externalMcp.grokAdded': '已添加 Grok MCP 条目。请重启 Grok 或打开新会话。',
'ai.externalMcp.codexAdded': '已添加 Codex MCP 条目和 Netcatty Skill。请重启 Codex 或打开新会话。',
'ai.externalMcp.claudeAdded': '已添加 Claude Code MCP 条目和 Netcatty Skill。请重启 Claude Code 或打开新会话。',
'ai.externalMcp.grokAdded': '已添加 Grok MCP 条目和 Netcatty Skill。请重启 Grok 或打开新会话。',
'ai.externalMcp.installCodex': '请先单独安装 Codex,然后点击刷新。',
'ai.externalMcp.installClaude': '请先单独安装 Claude Code,然后点击刷新。',
'ai.externalMcp.installGrok': '请先单独安装 Grok CLI,然后点击刷新。',
'ai.externalMcp.conflict.description': '已存在指向其他位置的 netcatty-external 条目,请手动删除或修改。',
'ai.externalMcp.enableForLauncher': '请先启用对外 MCP,以获取可用的 launcher 路径。',
'ai.externalMcp.cursor.title': 'Cursor / 其他客户端',
'ai.externalMcp.cursor.description': '合并到 MCP 配置文件(例如 ~/.cursor/mcp.json)。若已有其他服务器,请勿整文件覆盖。',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': '将片段合并到 Cursor MCP 配置中,并保留已有服务器。',
'ai.externalMcp.other.description': '将安装提示词复制到其他终端 Agent,或把 MCP 片段合并到对应客户端配置。',
'ai.externalMcp.status.unavailable': '不可用',
'ai.externalMcp.status.disabled': '已关闭',
'ai.externalMcp.status.running': '运行中',
@@ -599,6 +602,9 @@ export const zhCNAiMessages: Messages = {
'terminal.layer.movePanelRight': '面板移至右侧',
'terminal.layer.closePanel': '关闭面板',
'terminal.layer.closePane': '关闭分屏',
'terminal.layer.saveLayoutAsDefault': '将布局保存为默认',
'terminal.layer.layoutSavedAsDefault': '布局已保存为默认',
'terminal.layer.layoutSaveFailed': '布局保存失败',
'terminal.layer.resizeSplit': '调整分屏大小',
'terminal.layer.splitHorizontal': '上下分屏',
'terminal.layer.splitVertical': '左右分屏',
+11
View File
@@ -120,6 +120,12 @@ export const zhCNCoreMessages: Messages = {
'settings.terminal.sidePanel.pane.system': '系统',
'settings.terminal.sidePanel.pane.notes': '笔记',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': '本地 Shell 侧边栏',
'settings.terminal.localShellSidePanel.autoOpen': '打开本地 Shell 时展开侧边栏',
'settings.terminal.localShellSidePanel.autoOpen.desc': '打开本地 Shell 后自动打开一个侧边栏。',
'settings.terminal.localShellSidePanel.autoOpenPane': '默认侧边栏',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': '选择优先打开哪个面板。',
'settings.terminal.localShellSidePanel.pane.files': '文件',
// Settings > System
'settings.system.title': '系统',
@@ -678,6 +684,10 @@ export const zhCNCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '删除分组',
'vault.groups.deleteDialog.desc': '这将永久删除该分组并将所有主机移动到根级别。',
'vault.groups.deleteDialog.managedDesc': '这是一个托管的 SSH config 分组。删除后将同时删除所有主机并断开与源文件的连接。',
'vault.groups.deleteDialog.mixedDesc': '该分组包含从关联 SSH config 文件导入的主机。其托管子分组下的所有主机都将被删除,包括不受该文件管理的主机;其余主机将移动到根级别,除非您在下方选择同时删除。',
'vault.groups.deleteDialog.managedWarning': '删除该分组会同时清空关联 SSH config 文件中的对应条目,从该文件导入的配置可能会丢失,其他使用该文件的应用也会受到影响。请先备份文件再继续。',
'vault.groups.deleteDialog.sourcesChanged': '此次删除涉及的托管文件已发生变化。请检查文件并重新确认。',
'vault.groups.deleteDialog.managedFile': '关联文件:{file}',
'vault.groups.deleteDialog.deleteHosts': '同时删除该分组下的所有主机',
'vault.groups.deleteDialog.bulkTitle': '删除所选分组',
'vault.groups.deleteDialog.bulkDesc': '这将永久删除所选分组,并把其中的主机移动到根级别。',
@@ -736,6 +746,7 @@ export const zhCNCoreMessages: Messages = {
'vault.hosts.export.toast.success': '已导出 {count} 个主机到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已导出 {count} 个主机到 CSV(跳过 {skipped} 个不支持的主机)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 个已保存的密钥口令无法读取,导出时已留空',
'vault.hosts.export.toast.proxyCredentialsSkipped': '有 {count} 个已保存的代理密码无法读取,导出时已留空',
'vault.hosts.export.toast.noHosts': '没有主机可导出',
'vault.hosts.allHosts': '全部主机',
'vault.hosts.pinned': '已置顶',
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const zhCNTerminalMessages: Messages = {
'terminal.menu.saveScreen': '保存当前屏幕',
'terminal.saveScreen.failed': '保存终端屏幕失败。',
// 多行粘贴确认对话框(#3398)
'terminal.pasteConfirm.title': '要粘贴多行文本吗?',
'terminal.pasteConfirm.summary': '将向会话发送 {lines} 行({chars} 个字符)。',
'terminal.pasteConfirm.preview': '预览(可编辑)',
'terminal.pasteConfirm.send': '发送',
'terminal.pasteConfirm.sendLineByLine': '逐行发送',
'terminal.pasteConfirm.cancel': '取消',
'terminal.sudoHint.pressEnter': '按 Enter 粘贴已保存的密码',
'terminal.passwordPicker.title': '已保存的密码',
'terminal.passwordPicker.empty': '没有已保存的密码',
@@ -326,6 +333,12 @@ export const zhCNTerminalMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': '粘贴时自动上传剪贴板图片',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'当剪贴板包含图片时,在远程会话中粘贴会通过 SFTP 将图片上传到远端当前目录的 .netcatty-paste-images/ 文件夹,并在终端输入远端路径,而不是粘贴文本。',
'settings.terminal.behavior.confirmMultilinePaste': '粘贴多行前先询问',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'粘贴多行文本时先弹出确认对话框,显示行数和字符数、可编辑的预览,并提供发送 / 逐行发送 / 取消操作。可保护不支持括号粘贴的网络设备 CLI(Cisco IOS、华为 VRP、H3C Comware)。',
'settings.terminal.behavior.confirmMultilinePasteMinLines': '确认阈值(行数)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'粘贴内容达到该行数时才弹出确认对话框。',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter 发送文本',
'settings.terminal.behavior.shiftEnterNewline.desc':
'在终端中按 Shift+Enter 时发送配置的文本,而不是普通回车。',
@@ -918,6 +931,10 @@ export const zhCNTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': '例如 Arduino Uno',
'serial.connectAndSave': '连接并保存',
'serial.edit.title': '串口设置',
'serial.field.username': '用户名',
'serial.field.password': '密码',
'serial.field.autoLoginDesc': '设置后,串口终端出现 Login/Password 登录提示时,会自动填充此处保存的用户名和密码。',
'serial.field.clearPassword': '清除已保存的密码',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': '需要验证',
+1
View File
@@ -503,6 +503,7 @@ export const zhCNVaultMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': '重新连接当前会话',
'terminal.serverStats.cpu': 'CPU 使用率',
'terminal.serverStats.cpuCores': 'CPU 核心使用率',
'terminal.serverStats.gpu': 'GPU 使用率',
'terminal.serverStats.memory': '内存使用',
'terminal.serverStats.memoryDetails': '内存详情',
'terminal.serverStats.memUsed': '已用',
+11 -5
View File
@@ -354,21 +354,24 @@ export const zhTWAiMessages: Messages = {
'ai.externalMcp.client.claude': 'Claude Code',
'ai.externalMcp.client.grok': 'Grok',
'ai.externalMcp.client.cursor': 'Cursor',
'ai.externalMcp.client.other': '其他',
'ai.externalMcp.cliCommand': 'CLI 命令',
'ai.externalMcp.configSnippet': '設定片段',
'ai.externalMcp.universalSetupPrompt': '通用安裝提示詞',
'ai.externalMcp.addToCodex': '新增到 Codex',
'ai.externalMcp.addToClaude': '新增到 Claude Code',
'ai.externalMcp.addToGrok': '新增到 Grok',
'ai.externalMcp.codexAdded': '已新增 Codex MCP 項目。請重新啟動 Codex 或開啟新工作階段。',
'ai.externalMcp.claudeAdded': '已新增 Claude Code MCP 項目。請重新啟動 Claude Code 或開啟新工作階段。',
'ai.externalMcp.grokAdded': '已新增 Grok MCP 項目。請重新啟動 Grok 或開啟新工作階段。',
'ai.externalMcp.codexAdded': '已新增 Codex MCP 項目和 Netcatty Skill。請重新啟動 Codex 或開啟新工作階段。',
'ai.externalMcp.claudeAdded': '已新增 Claude Code MCP 項目和 Netcatty Skill。請重新啟動 Claude Code 或開啟新工作階段。',
'ai.externalMcp.grokAdded': '已新增 Grok MCP 項目和 Netcatty Skill。請重新啟動 Grok 或開啟新工作階段。',
'ai.externalMcp.installCodex': '請先另外安裝 Codex,然後按重新整理。',
'ai.externalMcp.installClaude': '請先另外安裝 Claude Code,然後按重新整理。',
'ai.externalMcp.installGrok': '請先另外安裝 Grok CLI,然後按重新整理。',
'ai.externalMcp.conflict.description': '已存在指向其他位置的 netcatty-external 項目,請手動刪除或修改。',
'ai.externalMcp.enableForLauncher': '請先啟用對外 MCP,以取得可用的 launcher 路徑。',
'ai.externalMcp.cursor.title': 'Cursor / 其他用戶端',
'ai.externalMcp.cursor.description': '合併到 MCP 設定檔(例如 ~/.cursor/mcp.json)。若已有其他伺服器,請勿整檔覆蓋。',
'ai.externalMcp.cursor.title': 'Cursor',
'ai.externalMcp.cursor.description': '將片段合併到 Cursor MCP 設定中,並保留已有伺服器。',
'ai.externalMcp.other.description': '將安裝提示詞複製到其他終端 Agent,或把 MCP 片段合併到對應用戶端設定。',
'ai.externalMcp.status.unavailable': '無法使用',
'ai.externalMcp.status.disabled': '已關閉',
'ai.externalMcp.status.running': '執行中',
@@ -589,6 +592,9 @@ export const zhTWAiMessages: Messages = {
'terminal.layer.movePanelRight': '面板移至右側',
'terminal.layer.closePanel': '關閉面板',
'terminal.layer.closePane': '關閉分割',
'terminal.layer.saveLayoutAsDefault': '將佈局儲存為預設',
'terminal.layer.layoutSavedAsDefault': '佈局已儲存為預設',
'terminal.layer.layoutSaveFailed': '佈局儲存失敗',
'terminal.layer.resizeSplit': '調整分割大小',
'terminal.layer.splitHorizontal': '上下分割',
'terminal.layer.splitVertical': '左右分割',
+11
View File
@@ -122,6 +122,12 @@ export const zhTWCoreMessages: Messages = {
'settings.terminal.sidePanel.pane.system': '系統',
'settings.terminal.sidePanel.pane.notes': '筆記',
'settings.terminal.sidePanel.pane.ai': 'AI',
'settings.terminal.section.localShellSidePanel': '本機 Shell 側邊欄',
'settings.terminal.localShellSidePanel.autoOpen': '開啟本機 Shell 時展開側邊欄',
'settings.terminal.localShellSidePanel.autoOpen.desc': '開啟本機 Shell 後自動開啟一個側邊欄。',
'settings.terminal.localShellSidePanel.autoOpenPane': '預設側邊欄',
'settings.terminal.localShellSidePanel.autoOpenPane.desc': '選擇優先開啟哪個面板。',
'settings.terminal.localShellSidePanel.pane.files': '檔案',
// Settings > System
'settings.system.title': '系統',
@@ -680,6 +686,10 @@ export const zhTWCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '刪除群組',
'vault.groups.deleteDialog.desc': '這將永久刪除該群組並將所有主機移動到根層級。',
'vault.groups.deleteDialog.managedDesc': '這是一個託管的 SSH config 群組。刪除後將同時刪除所有主機並斷開與原始檔的連線。',
'vault.groups.deleteDialog.mixedDesc': '該群組包含從關聯 SSH config 檔案匯入的主機。其受管理子群組下的所有主機都將被刪除,包括不受該檔案管理的主機;其餘主機將移動到根層級,除非您在下方選擇同時刪除。',
'vault.groups.deleteDialog.managedWarning': '刪除該群組會同時清空關聯 SSH config 檔案中的對應條目,從該檔案匯入的設定可能會遺失,其他使用該檔案的應用也會受到影響。請先備份檔案再繼續。',
'vault.groups.deleteDialog.sourcesChanged': '此次刪除涉及的受管理檔案已發生變化。請檢查檔案並重新確認。',
'vault.groups.deleteDialog.managedFile': '關聯檔案:{file}',
'vault.groups.deleteDialog.deleteHosts': '同時刪除該群組下的所有主機',
'vault.groups.deleteDialog.bulkTitle': '刪除所選群組',
'vault.groups.deleteDialog.bulkDesc': '這將永久刪除所選群組,並把其中的主機移動到根層級。',
@@ -738,6 +748,7 @@ export const zhTWCoreMessages: Messages = {
'vault.hosts.export.toast.success': '已匯出 {count} 個主機到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已匯出 {count} 個主機到 CSV(跳過 {skipped} 個不支援的主機)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 個已儲存的金鑰密碼無法讀取,匯出時已留空',
'vault.hosts.export.toast.proxyCredentialsSkipped': '有 {count} 個已儲存的代理密碼無法讀取,匯出時已留空',
'vault.hosts.export.toast.noHosts': '沒有主機可匯出',
'vault.hosts.allHosts': '全部主機',
'vault.hosts.pinned': '已置頂',
@@ -3,6 +3,13 @@ import type { Messages } from '../types';
export const zhTWTerminalMessages: Messages = {
'terminal.menu.saveScreen': '儲存目前畫面',
'terminal.saveScreen.failed': '儲存終端畫面失敗。',
// 多行貼上確認對話框(#3398)
'terminal.pasteConfirm.title': '要貼上多行文字嗎?',
'terminal.pasteConfirm.summary': '將向工作階段傳送 {lines} 行({chars} 個字元)。',
'terminal.pasteConfirm.preview': '預覽(可編輯)',
'terminal.pasteConfirm.send': '傳送',
'terminal.pasteConfirm.sendLineByLine': '逐行傳送',
'terminal.pasteConfirm.cancel': '取消',
'terminal.sudoHint.pressEnter': '按 Enter 貼上已儲存的密碼',
'terminal.passwordPicker.title': '已儲存的密碼',
'terminal.passwordPicker.empty': '沒有已儲存的密碼',
@@ -326,6 +333,12 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.behavior.autoUploadClipboardImage': '貼上時自動上傳剪貼簿圖片',
'settings.terminal.behavior.autoUploadClipboardImage.desc':
'當剪貼簿包含圖片時,在遠端工作階段中貼上會透過 SFTP 將圖片上傳到遠端目前目錄的 .netcatty-paste-images/ 資料夾,並在終端輸入遠端路徑,而不是貼上文字。',
'settings.terminal.behavior.confirmMultilinePaste': '貼上多行前先詢問',
'settings.terminal.behavior.confirmMultilinePaste.desc':
'貼上多行文字時先彈出確認對話框,顯示行數和字元數、可編輯的預覽,並提供傳送 / 逐行傳送 / 取消操作。可保護不支援括號貼上的網路設備 CLI(Cisco IOS、華為 VRP、H3C Comware)。',
'settings.terminal.behavior.confirmMultilinePasteMinLines': '確認門檻(行數)',
'settings.terminal.behavior.confirmMultilinePasteMinLines.desc':
'貼上內容達到該行數時才彈出確認對話框。',
'settings.terminal.behavior.shiftEnterNewline': 'Shift+Enter 傳送文字',
'settings.terminal.behavior.shiftEnterNewline.desc':
'在終端中按 Shift+Enter 時傳送設定的文字,而不是一般 Enter。',
@@ -918,6 +931,10 @@ export const zhTWTerminalMessages: Messages = {
'serial.field.configLabelPlaceholder': '例如 Arduino Uno',
'serial.connectAndSave': '連線並儲存',
'serial.edit.title': '序列埠設定',
'serial.field.username': '使用者名稱',
'serial.field.password': '密碼',
'serial.field.autoLoginDesc': '設定後,序列埠終端出現 Login/Password 登入提示時,會自動填入此處儲存的使用者名稱和密碼。',
'serial.field.clearPassword': '清除已儲存的密碼',
// Keyboard Interactive Authentication (2FA/MFA)
'keyboard.interactive.title': '需要驗證',
+1
View File
@@ -503,6 +503,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.statusbar.reconnect.tooltip': '重新連線目前工作階段',
'terminal.serverStats.cpu': 'CPU 使用率',
'terminal.serverStats.cpuCores': 'CPU 核心使用率',
'terminal.serverStats.gpu': 'GPU 使用率',
'terminal.serverStats.memory': '記憶體使用',
'terminal.serverStats.memoryDetails': '記憶體詳情',
'terminal.serverStats.memUsed': '已用',
@@ -0,0 +1,62 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
getPendingMultilinePasteConfirm,
requestMultilinePasteConfirm,
respondMultilinePasteConfirm,
subscribeMultilinePasteConfirm,
} from "./multilinePasteConfirmStore";
test("request stores the pending paste and respond resolves it", async () => {
const pending = requestMultilinePasteConfirm({
text: "line1\nline2",
lineCount: 2,
charCount: 12,
});
assert.equal(getPendingMultilinePasteConfirm()?.lineCount, 2);
respondMultilinePasteConfirm("line-by-line", "line1\nline2\nline3");
const response = await pending;
assert.deepEqual(response, { action: "line-by-line", text: "line1\nline2\nline3" });
assert.equal(getPendingMultilinePasteConfirm(), null);
});
test("respond without text falls back to the original request text", async () => {
const pending = requestMultilinePasteConfirm({
text: "line1\nline2",
lineCount: 2,
charCount: 12,
});
respondMultilinePasteConfirm("send");
const response = await pending;
assert.deepEqual(response, { action: "send", text: "line1\nline2" });
});
test("a newer paste request supersedes the pending one as cancelled", async () => {
const first = requestMultilinePasteConfirm({ text: "a\nb", lineCount: 2, charCount: 3 });
const second = requestMultilinePasteConfirm({ text: "c\nd", lineCount: 2, charCount: 3 });
assert.equal(getPendingMultilinePasteConfirm()?.text, "c\nd");
respondMultilinePasteConfirm("send", "c\nd");
assert.deepEqual(await first, { action: "cancel", text: "a\nb" });
assert.deepEqual(await second, { action: "send", text: "c\nd" });
});
test("respond without a pending request is a no-op and listeners are notified", async () => {
respondMultilinePasteConfirm("send");
assert.equal(getPendingMultilinePasteConfirm(), null);
const events: Array<string | null> = [];
const unsubscribe = subscribeMultilinePasteConfirm(() => {
events.push(getPendingMultilinePasteConfirm()?.id ?? "cleared");
});
const pending = requestMultilinePasteConfirm({ text: "x", lineCount: 1, charCount: 1 });
const pendingId = getPendingMultilinePasteConfirm()?.id ?? null;
respondMultilinePasteConfirm("cancel", "x");
await pending;
unsubscribe();
assert.ok(pendingId);
assert.deepEqual(events, [pendingId, "cleared"]);
});
@@ -0,0 +1,81 @@
/**
* App-level store for the "paste multiple lines" confirmation dialog (#3398).
*
* Terminal paste handlers call `requestMultilinePasteConfirm` from anywhere in
* the renderer and await the user's decision; `MultilinePasteConfirmHost`
* (mounted once in App) renders the dialog and resolves the pending request.
*/
export type MultilinePasteConfirmAction = "send" | "line-by-line" | "cancel";
export interface MultilinePasteConfirmRequest {
id: string;
/** Clipboard text the dialog previews (editable by the user). */
text: string;
lineCount: number;
charCount: number;
/** Restore the originating terminal's focus after the modal releases it. */
onClose?: () => void;
}
export interface MultilinePasteConfirmResponse {
action: MultilinePasteConfirmAction;
/** Text to send: the preview content, possibly edited by the user. */
text: string;
}
interface PendingRequest {
request: MultilinePasteConfirmRequest;
resolve: (response: MultilinePasteConfirmResponse) => void;
}
let pending: PendingRequest | null = null;
let nextRequestId = 0;
const listeners = new Set<() => void>();
const emit = (): void => {
for (const listener of listeners) listener();
};
export function requestMultilinePasteConfirm(
request: Omit<MultilinePasteConfirmRequest, "id">,
): Promise<MultilinePasteConfirmResponse> {
// Only one confirmation dialog can be pending; a newer paste supersedes the
// older one (the stale promise resolves as "cancel" so its paste is dropped).
if (pending) {
const stale = pending;
pending = null;
stale.resolve({ action: "cancel", text: stale.request.text });
}
nextRequestId += 1;
const requestWithId: MultilinePasteConfirmRequest = {
...request,
id: `multiline-paste-${nextRequestId}`,
};
return new Promise((resolve) => {
pending = { request: requestWithId, resolve };
emit();
});
}
export function respondMultilinePasteConfirm(
action: MultilinePasteConfirmAction,
text?: string,
): void {
const current = pending;
if (!current) return;
pending = null;
current.resolve({ action, text: text ?? current.request.text });
emit();
}
/** Snapshot for `useSyncExternalStore`; stable reference while pending. */
export const getPendingMultilinePasteConfirm =
(): MultilinePasteConfirmRequest | null => pending?.request ?? null;
export function subscribeMultilinePasteConfirm(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
+7 -1
View File
@@ -37,6 +37,8 @@ export type SettingsChromeSnapshot = {
restoreTerminalCwd: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
localShellSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
};
/**
@@ -70,6 +72,8 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
restoreTerminalCwd: true,
terminalSidePanelAutoOpen: false,
terminalSidePanelAutoOpenTab: 'ai',
localShellSidePanelAutoOpen: false,
localShellSidePanelAutoOpenTab: 'scripts',
} satisfies SettingsChromeSnapshot);
export function settingsChromeSnapshotsEqual(
@@ -95,7 +99,9 @@ export function settingsChromeSnapshotsEqual(
&& a.showTabNumberBadges === b.showTabNumberBadges
&& a.restoreTerminalCwd === b.restoreTerminalCwd
&& a.terminalSidePanelAutoOpen === b.terminalSidePanelAutoOpen
&& a.terminalSidePanelAutoOpenTab === b.terminalSidePanelAutoOpenTab;
&& a.terminalSidePanelAutoOpenTab === b.terminalSidePanelAutoOpenTab
&& a.localShellSidePanelAutoOpen === b.localShellSidePanelAutoOpen
&& a.localShellSidePanelAutoOpenTab === b.localShellSidePanelAutoOpenTab;
}
class SettingsChromeStore {
@@ -0,0 +1,79 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { useState } from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { useSettingsIpcSync } from './settingsIpcSync.ts';
import { useSettingsStorageSync } from './settingsStorageSync.ts';
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen.ts';
import {
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN as enabledKey,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB as tabKey,
} from '../../infrastructure/config/storageKeys.ts';
for (const pathway of ['ipc', 'storage'] as const) {
test(`${pathway} receives local shell settings, rejects invalid tabs and cleans up`, async (t) => {
let receive: ((payload: { key: string; value: unknown }) => void) | undefined;
let unsubscribed = false;
const fakeWindow = Object.assign(new EventTarget(), {
netcatty: {
onSettingsChanged(callback: typeof receive) {
receive = callback;
return () => { unsubscribed = true; };
},
},
});
for (const [key, value] of Object.entries({ window: fakeWindow, IS_REACT_ACT_ENVIRONMENT: true })) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { value, configurable: true });
t.after(() => {
if (previous) Object.defineProperty(globalThis, key, previous);
else Reflect.deleteProperty(globalThis, key);
});
}
let current = { enabled: false, tab: 'scripts' };
let renderer: ReactTestRenderer | undefined;
function Harness() {
const [enabled, setEnabled] = useState(false);
const [tab, setTab] = useState<TerminalSidePanelAutoOpenTab>('scripts');
current = { enabled, tab };
const params = {
localShellSidePanelAutoOpen: enabled,
localShellSidePanelAutoOpenTab: tab,
setLocalShellSidePanelAutoOpenState: setEnabled,
setLocalShellSidePanelAutoOpenTabState: setTab,
};
// Only local-shell events are dispatched; unrelated settings are not used.
useSettingsIpcSync({ ...params, enabled: pathway === 'ipc' } as unknown as Parameters<typeof useSettingsIpcSync>[0]);
useSettingsStorageSync({ ...params, enabled: pathway === 'storage' } as Parameters<typeof useSettingsStorageSync>[0]);
return null;
}
async function send(key: string, value: unknown) {
await act(async () => {
if (pathway === 'ipc') receive!({ key, value });
else fakeWindow.dispatchEvent(Object.assign(new Event('storage'), { key, newValue: value === null ? null : String(value) }));
});
}
try {
await act(async () => { renderer = create(React.createElement(Harness)); });
await send(enabledKey, true);
await send(tabKey, 'notes');
assert.deepEqual(current, { enabled: true, tab: 'notes' });
await send(tabKey, 'invalid');
await send(tabKey, null);
await send(enabledKey, null);
assert.deepEqual(current, { enabled: true, tab: 'notes' });
if (pathway === 'ipc') {
await send(enabledKey, 'false');
assert.equal(current.enabled, true);
}
await send(enabledKey, false);
await send(tabKey, 'history');
assert.deepEqual(current, { enabled: false, tab: 'history' });
await act(async () => { renderer!.unmount(); });
renderer = undefined;
if (pathway === 'ipc') assert.equal(unsubscribed, true);
} finally {
await act(async () => { renderer?.unmount(); });
}
});
}
+14
View File
@@ -48,6 +48,8 @@ import {
STORAGE_KEY_TAB_BAR_POSITION,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_APP_ICON_VARIANT,
STORAGE_KEY_HTTP_NETWORK_PROXY,
@@ -106,6 +108,8 @@ interface UseSettingsIpcSyncParams {
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setLocalShellSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setDisableTerminalFontZoomState: Dispatch<SetStateAction<boolean>>;
setRestorePreviousSessionState: Dispatch<SetStateAction<boolean>>;
setRestoreTerminalCwdState: Dispatch<SetStateAction<boolean>>;
@@ -153,6 +157,8 @@ export function useSettingsIpcSync({
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
@@ -316,6 +322,12 @@ export function useSettingsIpcSync({
if (key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB && isTerminalSidePanelAutoOpenTab(value)) {
setTerminalSidePanelAutoOpenTabState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN && typeof value === 'boolean') {
setLocalShellSidePanelAutoOpenState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB && isTerminalSidePanelAutoOpenTab(value)) {
setLocalShellSidePanelAutoOpenTabState((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM && typeof value === 'boolean') {
setDisableTerminalFontZoomState((prev) => (prev === value ? prev : value));
}
@@ -371,6 +383,8 @@ export function useSettingsIpcSync({
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
+23 -4
View File
@@ -39,6 +39,8 @@ import {
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
@@ -97,6 +99,8 @@ interface UseSettingsStorageSyncParams {
showHostTreeSidebar: boolean;
terminalSidePanelAutoOpen: boolean;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
localShellSidePanelAutoOpen: boolean;
localShellSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
shellOnlyTabNumberShortcuts: boolean;
showTabNumberBadges: boolean;
disableTerminalFontZoom: boolean;
@@ -147,6 +151,8 @@ interface UseSettingsStorageSyncParams {
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
setLocalShellSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
setShellOnlyTabNumberShortcutsState: Dispatch<SetStateAction<boolean>>;
setShowTabNumberBadgesState: Dispatch<SetStateAction<boolean>>;
setDisableTerminalFontZoomState: Dispatch<SetStateAction<boolean>>;
@@ -180,7 +186,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode, applyIncomingCustomAccent,
@@ -189,7 +195,7 @@ export function useSettingsStorageSync({
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState,
setGlobalHotkeyEnabled, setWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
@@ -204,7 +210,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
});
@@ -214,7 +220,7 @@ export function useSettingsStorageSync({
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
};
@@ -461,6 +467,17 @@ export function useSettingsStorageSync({
setTerminalSidePanelAutoOpenTabState(e.newValue);
}
}
if (e.key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.localShellSidePanelAutoOpen) {
setLocalShellSidePanelAutoOpenState(newValue);
}
}
if (e.key === STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB && e.newValue !== null) {
if (isTerminalSidePanelAutoOpenTab(e.newValue) && e.newValue !== s.localShellSidePanelAutoOpenTab) {
setLocalShellSidePanelAutoOpenTabState(e.newValue);
}
}
if (e.key === STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.shellOnlyTabNumberShortcuts) {
@@ -581,6 +598,8 @@ export function useSettingsStorageSync({
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setShowRecentHostsState,
setTabBarPositionState, setShowSftpTabState,
setShellOnlyTabNumberShortcutsState,
@@ -41,8 +41,12 @@ const host = (id: string, label: string, hostname = label): Host => ({
for (const retainedStatus of [undefined, "interrupted", "failed", "paused"] as const) {
for (const newerPause of retainedStatus === "paused" ? [false, true] : [false]) {
for (const ownerChange of retainedStatus === "interrupted" || retainedStatus === undefined ? ["same", "active", "completed"] : ["same"]) {
for (const completedBeforeReplacement of ownerChange === "active" ? [false, true] : [false]) {
for (const flushBeforeReply of ownerChange === "same" || retainedStatus === undefined ? [false] : [false, true]) {
for (const replyRejects of ownerChange !== "same" && !completedBeforeReplacement && !flushBeforeReply ? [false, true] : [false]) {
const batchExistingIdentity = retainedStatus !== undefined;
test(`superseded folder child settles when its completion was compacted into the parent: retained=${retainedStatus ?? "none"}, newerPause=${newerPause}`, async (t) => {
test(`superseded folder child settles when its completion was compacted into the parent: retained=${retainedStatus ?? "none"}, newerPause=${newerPause}, owner=${ownerChange}, flush=${flushBeforeReply}, priorComplete=${completedBeforeReplacement}, reject=${replyRejects}`, async (t) => {
const { sftpTransferCenterStore } = await import("../sftpTransferCenterStore");
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
@@ -75,14 +79,19 @@ test(`superseded folder child settles when its completion was compacted into the
...parent, id: "retained-child", parentTaskId: parent.id, isDirectory: false,
sourcePath: "/local/folder/a.bin", targetPath: "/remote/folder/a.bin",
totalBytes: 10, sourceLastModified: 1, status: retainedStatus ?? "interrupted",
directoryEntryIndex: 0, directoryEntryIdentity: "a".repeat(64),
directoryEntryIndex: 0,
directoryEntryIdentity: newerPause ? createDirectoryEntryIdentity({
sourcePath: "/local/folder/a.bin", targetPath: "/remote/folder/a.bin", size: 10, lastModified: 1,
}) : "a".repeat(64),
};
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
// Exercise the real large-history batching branch with one relevant retained row.
const childBatcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096,
hasTask: (id) => id === persisted.id,
upsertTasks: (updates) => sftpTransferCenterStore.upsertTasks(updates),
hasTask: (id) => id === persisted.id || id.startsWith("flush-peer-"),
// Peer rows only drive the real 512-entry flush; keep the relevant store
// fixture small so unrelated history maintenance cannot mask ownership.
upsertTasks: (updates) => sftpTransferCenterStore.upsertTasks(updates.filter((task) => !task.id.startsWith("flush-peer-"))),
});
sftpTransferCenterStore.publishOwner("compacted-owner", [parent, ...(batchExistingIdentity ? [persisted] : [])]);
(netcattyBridge as { get: () => unknown }).get = () => ({
@@ -106,20 +115,50 @@ test(`superseded folder child settles when its completion was compacted into the
directoryEntryIndex: options.directoryEntryIndex,
directoryEntryIdentity: options.directoryEntryIdentity,
});
// A newer same-id owner completes before this older invocation rejoins.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: 0,
});
return { superseded: true };
if (ownerChange !== "same") {
const current = sftpTransferCenterStore.getTask(childId)!;
if (completedBeforeReplacement) {
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: 0,
});
}
sftpTransferCenterStore.upsertTasks([{
...current, status: "transferring", directoryEntryIdentity: "e".repeat(64), lifecycleEpoch: 1,
}]);
}
if (ownerChange !== "active") {
// A newer same-id owner completes before this older invocation rejoins.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 10, totalBytes: 10, lifecycleEpoch: ownerChange === "same" ? 0 : 1,
});
}
if (flushBeforeReply) {
for (let index = 0; index < 512; index += 1) {
childBatcher.push({ ...persisted, id: `flush-peer-${index}`, status: "transferring" });
}
if (ownerChange === "active") {
assert.equal(sftpTransferCenterStore.getTask(childId)?.directoryEntryIdentity, "e".repeat(64),
"automatic flush before the displaced reply must preserve the new owner");
} else assert.equal(sftpTransferCenterStore.getTask(childId), undefined,
"automatic flush must not recreate the compacted new owner");
}
if (replyRejects) throw new Error("old invocation transport failed");
return completedBeforeReplacement ? {} : { superseded: true };
},
});
running = resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box", "1.2.3.4")], keys: [], identities: [],
}, undefined, {
children: batchExistingIdentity ? [persisted] : [], shouldAbort: () => abort,
onChildUpdate: (child) => batchExistingIdentity
? childBatcher.push(child)
: sftpTransferCenterStore.publishOwner("compacted-owner", [parent, child]),
onChildSuperseded: (id) => childBatcher.discard(id),
flushChildUpdates: () => childBatcher.flush(),
onChildUpdate: (child, observation) => {
if (batchExistingIdentity) {
childBatcher.push(child, observation);
return true;
}
sftpTransferCenterStore.publishOwner("compacted-owner", [parent, child]);
},
});
const result = await Promise.race([
running,
@@ -133,6 +172,15 @@ test(`superseded folder child settles when its completion was compacted into the
}
assert.notEqual(result, "still-waiting", "completed compacted child must not leave its folder waiting forever");
assert.ok(childId);
if (ownerChange !== "same") {
childBatcher.flush();
assert.equal((result as { success: boolean }).success, false, "the displaced walk must not report success");
if (ownerChange === "active") {
assert.equal(sftpTransferCenterStore.getTask(childId)?.status, "transferring");
assert.equal(sftpTransferCenterStore.getTask(childId)?.directoryEntryIdentity, "e".repeat(64));
} else assert.equal(sftpTransferCenterStore.getTask(childId), undefined, "old waiter must not recreate a failed row");
return;
}
assert.equal(sftpTransferCenterStore.getTask(childId), undefined, "completed row was compacted");
assert.equal(sftpTransferCenterStore.getTask(parent.id)?.directoryResumeCheckpoint?.completedEntries, 1);
assert.notEqual(result, "still-waiting", "completed compacted child must not leave its folder waiting forever");
@@ -140,6 +188,10 @@ test(`superseded folder child settles when its completion was compacted into the
});
}
}
}
}
}
}
test("resolveDirectoryResumeTargetRoot prefers staged replace path", () => {
assert.equal(
@@ -696,6 +748,67 @@ test("single-file restart resume continues from checkpoint without page callback
}
});
test("stat-less SCP download resume keeps saved progress instead of restarting", async (t) => {
resetDedicatedSessionOpenGateForTests();
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: { getItem: () => "2", setItem: () => {}, removeItem: () => {} },
});
t.after(() => {
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
});
const originalGet = netcattyBridge.get;
let startOptions: Record<string, unknown> | undefined;
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated-sftp",
closeSftp: async () => {},
// Stat-less SCP host: size cannot be measured, so the bridge reports the
// placeholder 0 with sizeKnown false.
statSftp: async () => ({ type: "file", size: 0, lastModified: 5, sizeKnown: false }),
startStreamTransfer: async (options: Record<string, unknown>) => {
startOptions = options;
return { transferId: "scp-download-resume" };
},
});
try {
const result = await resumeTransferWithDedicatedSession({
id: "scp-download-resume",
fileName: "file.bin",
sourcePath: "/remote/file.bin",
targetPath: "/local/file.bin",
sourceConnectionId: "old-sftp",
sourceHostId: "h1",
sourceHostLabel: "box",
targetConnectionId: "local",
direction: "download",
status: "interrupted",
totalBytes: 100,
transferredBytes: 20,
checkpointBytes: 20,
sourceLastModified: 5,
speed: 0,
startTime: 1,
isDirectory: false,
reconnectRequired: true,
}, {
hosts: [host("h1", "box", "1.2.3.4")],
keys: [],
identities: [],
});
assert.equal(result.success, true, result.error);
// Unknown size must not misread the saved checkpoint as a shrunk source;
// the download resumes from byte 20 instead of silently restarting.
assert.equal(startOptions?.checkpointBytes, 20);
assert.equal(startOptions?.totalBytes, 100);
} finally {
(netcattyBridge as { get: typeof originalGet }).get = originalGet;
resetDedicatedSessionOpenGateForTests();
}
});
test("folder restart resume reports file-count progress without child page callbacks", async (t) => {
resetDedicatedSessionOpenGateForTests();
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
@@ -2131,3 +2244,202 @@ for (const scenario of ["deleted-id", "ambiguous-legacy-label"] as const) {
assert.equal(uploads, 0);
});
}
for (const completeDuringSetup of [false, true]) {
test(`large-history replace recovery retransfers retained completed children into its empty stage: late=${completeDuringSetup}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const originalGet = netcattyBridge.get;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true, value: { getItem: () => "2", setItem: () => {}, removeItem: () => {} },
});
const { createRequire } = await import("node:module");
const tempDirBridge = createRequire(import.meta.url)("../../../electron/bridges/tempDirBridge.cjs");
const root = await fs.promises.mkdtemp(`${tempDirBridge.getTempFilePath("folder-rebuild-test")}-`);
const finalPath = path.join(root, "final");
const stage = `${finalPath}.netcatty-retained-replace.part`;
await fs.promises.mkdir(stage);
await fs.promises.writeFile(path.join(stage, "b.txt"), "old contents");
const parent: TransferTask = {
id: "retained-replace", fileName: "folder", sourcePath: "/remote/folder", targetPath: finalPath,
stagedTargetPath: stage, replaceExistingTarget: true, sourceConnectionId: "old-sftp", targetConnectionId: "local",
sourceHostId: "h1", direction: "download", status: "transferring", totalBytes: 2,
transferredBytes: 1, speed: 0, startTime: 1, isDirectory: true, progressMode: "files", reconnectRequired: true,
};
const retained: TransferTask = {
...parent, id: "retained-replace-b", parentTaskId: parent.id, isDirectory: false,
sourcePath: "/remote/folder/b.txt", targetPath: `${stage}/b.txt`, fileName: "b.txt",
status: completeDuringSetup ? "interrupted" : "completed", totalBytes: 10, transferredBytes: 10, checkpointBytes: 10,
sourceLastModified: 2, directoryEntryIndex: 1,
directoryEntryIdentity: createDirectoryEntryIdentity({
sourcePath: "/remote/folder/b.txt", targetPath: `${stage}/b.txt`, size: 10, lastModified: 2,
}),
};
store.upsertTasks([parent, retained]);
assert.ok(store.getTask(retained.id), "missing earlier manifest index retains the completed row");
const batcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096,
hasTask: (id) => !!store.getTask(id),
upsertTasks: (updates) => store.upsertTasks(updates),
});
let releaseFirst!: () => void;
const secondDispatched = new Promise<void>((resolve) => { releaseFirst = resolve; });
t.after(async () => {
await fs.promises.rm(root, { recursive: true, force: true });
netcattyBridge.get = originalGet;
store.patchTask(parent.id, { status: "completed" });
store.dismiss(parent.id);
if (previousLocalStorage) Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
resetDedicatedSessionOpenGateForTests();
});
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated-sftp", closeSftp: async () => {},
listSftp: async (_id: string, remotePath: string) => {
if (completeDuringSetup) store.patchTask(retained.id, { status: "completed", ownerId: "dedicated-resume" });
return remotePath === parent.sourcePath
? ["a.txt", "b.txt"].map((name) => ({ name, type: "file", size: 10, lastModified: 2 })) : [];
},
mkdirLocal: async (target: string) => { await fs.promises.mkdir(target, { recursive: true }); },
statLocal: async (target: string) => {
try {
const stat = await fs.promises.stat(target);
return { type: stat.isDirectory() ? "directory" : "file", size: stat.size, lastModified: stat.mtimeMs };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
},
statSftp: async (_id: string, source: string) => {
if (source.endsWith("a.txt")) await secondDispatched;
return { type: "file", size: 10, lastModified: 2 };
},
deleteLocalFile: async (target: string) => { await fs.promises.rm(target, { recursive: true }); },
renameLocalFile: async (source: string, target: string) => { await fs.promises.rename(source, target); },
startStreamTransfer: async (options: { targetPath: string; checkpointBytes: number }) => {
assert.equal(options.checkpointBytes, 0, "an empty replacement stage cannot reuse byte checkpoints");
await fs.promises.writeFile(options.targetPath, `new ${path.basename(options.targetPath)}`);
return {};
},
});
const result = await resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box")], keys: [], identities: [],
}, undefined, {
children: [retained],
flushChildUpdates: () => batcher.flush(),
onChildUpdate: (task, observation) => {
batcher.push(task, observation);
if (task.id === retained.id && task.status === "completed") releaseFirst();
return true;
},
onDirectoryCheckpointUpdate: (value) => store.patchTask(parent.id, { directoryResumeCheckpoint: value }),
});
batcher.flush();
assert.equal(result.success, true, result.error);
assert.deepEqual((await fs.promises.readdir(finalPath)).sort(), ["a.txt", "b.txt"],
"published replacement must include the previously completed file");
assert.equal(await fs.promises.readFile(path.join(finalPath, "b.txt"), "utf8"), "new b.txt");
});
}
for (const boundary of ["before-admission", "source-missing", "source-modified", "after-completion", "after-commit"] as const) {
test(`dedicated recovery preserves replacement ownership ${boundary}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const originalGet = netcattyBridge.get;
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: {
getItem: () => "2", setItem: () => {}, removeItem: () => {},
} });
const parent: TransferTask = {
id: `ownership-${boundary}`, fileName: "folder", sourcePath: "/local/folder", targetPath: "/remote/folder",
sourceConnectionId: "local", targetConnectionId: "old", targetHostId: "h1", direction: "upload",
status: "transferring", totalBytes: 2, transferredBytes: 0, speed: 0, startTime: 1,
isDirectory: true, progressMode: "files", reconnectRequired: true,
};
const child: TransferTask = {
...parent, id: `${parent.id}-a`, parentTaskId: parent.id, isDirectory: false,
sourcePath: "/local/folder/a", targetPath: "/remote/folder/a", fileName: "a", totalBytes: 1,
status: "interrupted", directoryEntryIndex: 0, directoryEntryIdentity: "a".repeat(64), sourceLastModified: 1,
};
store.upsertTasks([parent, boundary === "before-admission"
? { ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }
: child]);
const batch = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096, hasTask: (id) => id === child.id || id.startsWith("peer-"),
upsertTasks: (rows) => store.upsertTasks(rows.filter((row) => !row.id.startsWith("peer-"))),
});
if (boundary === "before-admission") {
for (let n = 0; n < 511; n++) batch.push({ ...child, id: `peer-${n}` });
}
let releaseB!: () => void;
const bGate = new Promise<void>((resolve) => { releaseB = resolve; });
let timedOut = false;
const watchdog = setTimeout(() => { timedOut = true; releaseB(); }, 1000);
t.after(() => {
clearTimeout(watchdog);
releaseB();
batch.flush();
store.patchTask(parent.id, { status: "completed" });
store.dismiss(parent.id);
netcattyBridge.get = originalGet;
if (originalStorage) Object.defineProperty(globalThis, "localStorage", originalStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
resetDedicatedSessionOpenGateForTests();
});
let starts = 0;
let displaced = 0;
let replaced = false;
(netcattyBridge as { get: () => unknown }).get = () => ({
openSftp: async () => "dedicated", closeSftp: async () => {
if (boundary === "after-commit") {
assert.equal(store.getTask(child.id), undefined, "completion must be committed before async cleanup");
store.upsertTasks([{ ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
}
},
listLocalTree: async () => (boundary === "after-completion" ? ["a", "b"] : ["a"]).map((name) => ({
localPath: `/local/folder/${name}`, relativePath: name, type: "file", size: 1, lastModified: 1,
})),
mkdirSftp: async () => {}, statLocal: async () => {
if (boundary === "source-missing" || boundary === "source-modified") {
store.upsertTasks([{ ...child, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
if (boundary === "source-missing") return null;
return { type: "file", size: 1, lastModified: 2 };
}
return { type: "file", size: 1, lastModified: 1 };
},
startStreamTransfer: async (options: { sourcePath: string }) => {
starts++;
if (options.sourcePath.endsWith("/b")) await bGate;
return {};
},
});
const result = await resumeTransferWithDedicatedSession(parent, {
hosts: [host("h1", "box")], keys: [], identities: [],
}, undefined, {
children: [child],
onChildSuperseded: (id) => { displaced++; batch.discard(id); },
flushChildUpdates: () => batch.flush(),
onChildUpdate: (task, observation) => {
batch.push(task, observation);
if (boundary === "after-completion" && task.id === child.id && task.status === "completed" && !replaced) {
replaced = true;
queueMicrotask(() => {
try {
store.upsertTasks([{ ...task, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
} finally { releaseB(); }
});
}
return true;
},
});
batch.flush();
assert.equal(timedOut, false);
assert.equal(result.success, boundary === "after-commit", "only a committed success may precede a legitimate replacement");
assert.equal(store.getTask(child.id)?.directoryEntryIdentity, "b".repeat(64));
assert.equal(store.getTask(child.id)?.status, "transferring");
if (boundary !== "after-completion" && boundary !== "after-commit") assert.equal(starts, 0, "source validation and a full batch must not bypass ownership");
else assert.equal(displaced, boundary === "after-commit" ? 0 : 1);
});
}
@@ -1,4 +1,4 @@
import { runTransferAndWaitForOwner } from "./waitForTransferOwner";
import { runTransferAndWaitForOwner, TransferOwnerChangedError, type TransferOwnerObservation } from "./waitForTransferOwner";
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings, TransferTask } from "../../../domain/models";
import { validateTransferResumeSource } from "../../../domain/sftpTransferCenter";
import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY } from "../../../infrastructure/config/storageKeys";
@@ -62,7 +62,10 @@ export type DedicatedResumeResult = {
export type DedicatedResumeOptions = {
children?: readonly TransferTask[];
onChildUpdate?: (child: TransferTask) => void;
/** Return true only when the consumer takes responsibility for disposing the observation. */
onChildUpdate?: (child: TransferTask, observation?: TransferOwnerObservation) => unknown;
onChildSuperseded?: (taskId: string) => void;
flushChildUpdates?: () => void;
onDirectoryCheckpointUpdate?: (checkpoint: TransferTask["directoryResumeCheckpoint"]) => void;
shouldAbort?: () => boolean;
};
@@ -671,6 +674,7 @@ async function resumeSingleFileWithDedicatedSession(
const validationError = validateTransferResumeSource(task, {
size: sourceStat.size,
lastModified: sourceStat.lastModified,
sizeKnown: sourceStat.sizeKnown,
}, { allowSourceGrowth });
const classified = classifyResumeSourceValidationError(validationError);
if (classified.kind === "modified") {
@@ -1090,6 +1094,12 @@ async function resumeDirectoryWithDedicatedSession(
// the source since the interrupted attempt, so rebuild it from empty.
await resetDirectoryReplaceStage(parent, endpoints, targetSftpId);
}
// Session setup and traversal may finish more children. Capture only
// after resetting the stage/checkpoint: all these completions refer to
// the discarded destination, while later completions remain valid.
const completedAtRestart = new Map(sftpTransferCenterStore.getSnapshot().tasks
.filter((child) => child.parentTaskId === parent.id && child.status === "completed")
.map((child) => [child.id, child]));
const destRoot = resolveDirectoryResumeTargetRoot(parent);
if (endpoints.isDownload) await ensureLocalDir(destRoot);
if (targetSftpId) await ensureRemoteDir(targetSftpId, destRoot);
@@ -1188,8 +1198,25 @@ async function resumeDirectoryWithDedicatedSession(
}
if (targetSftpId) await ensureRemoteDir(targetSftpId, getParentPath(file.targetPath));
let countedCompleted = false;
const onOwnerChanged = () => {
if (countedCompleted) {
countedCompleted = false;
completedCount -= 1;
failedCount += 1;
}
options?.onChildSuperseded?.(childId);
};
let childObservation: TransferOwnerObservation | undefined = sftpTransferCenterStore.observeTaskSettlement(
childBase, resetPersistedCheckpoint ? completedAtRestart.get(childId) : undefined, onOwnerChanged,
);
const publishChild = (child: TransferTask) => {
if (childObservation?.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before child update");
if (options?.onChildUpdate?.(child, childObservation) === true) childObservation = undefined;
};
try {
if (options?.shouldAbort?.()) throw new Error("Transfer cancelled");
if (childObservation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before source validation");
const sourceType = endpoints.isUpload ? "local" as const : "sftp" as const;
const targetType = endpoints.isDownload ? "local" as const : "sftp" as const;
@@ -1206,6 +1233,7 @@ async function resumeDirectoryWithDedicatedSession(
const validationError = validateTransferResumeSource(childBase, {
size: sourceStat.size,
lastModified: sourceStat.lastModified,
sizeKnown: sourceStat.sizeKnown,
}, { allowSourceGrowth });
const classified = classifyResumeSourceValidationError(validationError);
if (classified.kind === "restart") {
@@ -1217,8 +1245,7 @@ async function resumeDirectoryWithDedicatedSession(
sourceLastModified: sourceStat.lastModified,
};
} else if (classified.kind === "modified") {
attentionCount += 1;
options?.onChildUpdate?.({
publishChild({
...childBase,
status: "attention",
error: classified.message || validationError || "Source was modified",
@@ -1227,6 +1254,7 @@ async function resumeDirectoryWithDedicatedSession(
phase: undefined,
retryable: true,
});
attentionCount += 1;
return;
} else if (classified.kind === "fatal") {
throw new Error(classified.message || validationError || "Resume validation failed");
@@ -1236,56 +1264,71 @@ async function resumeDirectoryWithDedicatedSession(
// zero-byte plans (`||` would incorrectly promote to grown size).
const plannedBytes = Number(childBase.totalBytes);
const hasPlannedBytes = Number.isFinite(plannedBytes) && plannedBytes >= 0;
// Stat-less SCP sources report size as a placeholder 0; keep the
// planned size rather than re-planning to a fake zero.
const sourceSizeKnown = sourceStat.sizeKnown !== false && Number.isFinite(sourceStat.size);
childBase = {
...childBase,
totalBytes: allowSourceGrowth
? (hasPlannedBytes ? plannedBytes : sourceStat.size)
: (sourceStat.size || childBase.totalBytes),
sourceLastModified: allowSourceGrowth
&& hasPlannedBytes
&& sourceStat.size > plannedBytes
? (childBase.sourceLastModified ?? sourceStat.lastModified)
: (sourceStat.lastModified ?? childBase.sourceLastModified),
totalBytes: !sourceSizeKnown
? childBase.totalBytes
: allowSourceGrowth
? (hasPlannedBytes ? plannedBytes : sourceStat.size)
: (sourceStat.size || childBase.totalBytes),
sourceLastModified: !sourceSizeKnown
? (sourceStat.lastModified ?? childBase.sourceLastModified)
: allowSourceGrowth
&& hasPlannedBytes
&& sourceStat.size > plannedBytes
? (childBase.sourceLastModified ?? sourceStat.lastModified)
: (sourceStat.lastModified ?? childBase.sourceLastModified),
};
}
// Re-check abort after async stat before inserting a transferring child.
if (options?.shouldAbort?.()) throw new Error("Transfer cancelled");
options?.onChildUpdate?.(childBase);
const streamResult = await runTransferAndWaitForOwner(childBase, () => {
// Publish only after admission, while identity changes are observed.
options?.onChildUpdate?.(childBase);
return bridge.startStreamTransfer!({
transferId: childId,
// Lifecycle events must carry the current identity even while
// large-history renderer child updates remain batched.
parentTaskId: childBase.parentTaskId,
directoryEntryIndex: childBase.directoryEntryIndex,
directoryEntryIdentity: childBase.directoryEntryIdentity,
sourcePath: file.sourcePath,
targetPath: file.targetPath,
sourceType,
targetType,
sourceSftpId,
targetSftpId,
sourceHostId: endpoints.sourceHost?.id,
targetHostId: endpoints.targetHost?.id,
totalBytes: Number.isFinite(childBase.totalBytes)
? childBase.totalBytes
: (file.size || undefined),
resumable: parent.resumable !== false,
checkpointBytes: childBase.checkpointBytes ?? 0,
resumeStage: childBase.resumeStage,
downloadCheckpointBytes: childBase.downloadCheckpointBytes,
uploadCheckpointBytes: childBase.uploadCheckpointBytes,
sourceFingerprint: childBase.sourceFingerprint,
skipAdmission: true,
});
}, () => options?.shouldAbort?.() === true, pausedAtResume.get(childId),
resetPersistedCheckpoint ? completedAtRestart.get(childId) : undefined,
// Drop queued UI updates at the ownership change itself: waiting
// for this invocation's reply may allow an intervening batch flush.
onOwnerChanged,
(observation) => { childObservation = observation; return true; }, childObservation);
const streamResult = await runTransferAndWaitForOwner(childBase, () => bridge.startStreamTransfer!({
transferId: childId,
// Lifecycle events must carry the current identity even while
// large-history renderer child updates remain batched.
parentTaskId: childBase.parentTaskId,
directoryEntryIndex: childBase.directoryEntryIndex,
directoryEntryIdentity: childBase.directoryEntryIdentity,
sourcePath: file.sourcePath,
targetPath: file.targetPath,
sourceType,
targetType,
sourceSftpId,
targetSftpId,
sourceHostId: endpoints.sourceHost?.id,
targetHostId: endpoints.targetHost?.id,
totalBytes: Number.isFinite(childBase.totalBytes)
? childBase.totalBytes
: (file.size || undefined),
resumable: parent.resumable !== false,
checkpointBytes: childBase.checkpointBytes ?? 0,
resumeStage: childBase.resumeStage,
downloadCheckpointBytes: childBase.downloadCheckpointBytes,
uploadCheckpointBytes: childBase.uploadCheckpointBytes,
sourceFingerprint: childBase.sourceFingerprint,
skipAdmission: true,
}), () => options?.shouldAbort?.() === true, pausedAtResume.get(childId));
if (childObservation?.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before child update");
if (streamResult?.error || streamResult?.cancelled) {
throw new Error(streamResult.error || "Transfer cancelled");
}
completedCount += 1;
options?.onChildUpdate?.({
publishChild({
...childBase,
status: "completed",
transferredBytes: Number.isFinite(childBase.totalBytes)
@@ -1297,13 +1340,21 @@ async function resumeDirectoryWithDedicatedSession(
reconnectRequired: false,
phase: undefined,
});
countedCompleted = true;
completedCount += 1;
bumpParentProgress(0);
} catch (error) {
if (options?.shouldAbort?.() || /cancelled|canceled/i.test(error instanceof Error ? error.message : String(error))) {
throw error instanceof Error ? error : new Error(String(error));
}
failedCount += 1;
options?.onChildUpdate?.({
// Another invocation owns this ID now. Report this walk's failure
// without replacing the winner or recreating its compacted row.
if (error instanceof TransferOwnerChangedError || childObservation?.hasIdentityConflict()) {
options?.onChildSuperseded?.(childId);
return;
}
publishChild({
...childBase,
status: "failed",
error: error instanceof Error ? error.message : String(error),
@@ -1312,6 +1363,8 @@ async function resumeDirectoryWithDedicatedSession(
reconnectRequired: false,
phase: undefined,
});
} finally {
childObservation?.dispose();
}
},
);
@@ -1322,6 +1375,10 @@ async function resumeDirectoryWithDedicatedSession(
if (result?.error) throw new Error(result.error);
// Commit deferred child outcomes before deciding success or promoting a stage.
// Async connection cleanup must not outlive provisional completion evidence.
options?.flushChildUpdates?.();
if (attentionCount > 0 && failedCount === 0 && completedCount + attentionCount >= totalFiles) {
return {
success: false,
@@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveDownloadSourceSnapshot } from "./downloadSourceSnapshot.ts";
const stat = (overrides: Partial<SftpStatResult> = {}): SftpStatResult => ({
name: "f",
size: 50_000,
type: "file",
lastModified: 0,
sizeKnown: true,
...overrides,
});
for (const listedSize of [25_000, 100_000]) {
test(`recreated file uses the current 50k size rather than listed ${listedSize}`, async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async (_id, path, encoding) => {
assert.equal(path, "/tmp/f");
assert.equal(encoding, "auto");
return stat();
},
"sftp-1", "/tmp/f", "auto",
);
assert.deepEqual(snapshot, { size: 50_000, isDirectory: false });
assert.notEqual(snapshot.size, listedSize);
});
}
test("a stale file entry replaced by a directory uses directory routing", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 0, type: "directory" }),
"sftp-1", "/tmp/x", "auto",
);
assert.deepEqual(snapshot, { size: 0, isDirectory: true });
});
test("a stale directory entry replaced by a file uses file routing", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 12, type: "file" }),
"sftp-1", "/tmp/x", "auto",
);
assert.deepEqual(snapshot, { size: 12, isDirectory: false });
});
test("missing, failed and unsupported stats reject instead of using a stale listing", async () => {
const rejected = [
undefined,
async () => null as unknown as SftpStatResult,
async () => { throw new Error("File not found"); },
async () => stat({ type: "symlink" }),
async () => stat({ size: Number.NaN }),
async () => stat({ size: -1 }),
];
for (const candidate of rejected) {
await assert.rejects(
resolveDownloadSourceSnapshot(candidate, "sftp-1", "/tmp/f", "auto"),
/Cannot verify the current remote source before download/,
);
}
});
test("stat-less SCP file leaves sizing to the transfer instead of using listed bytes", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: 0, sizeKnown: false }),
"scp-1", "/tmp/f", "auto",
);
assert.deepEqual(snapshot, { size: undefined, isDirectory: false });
});
test("SCP links retain their resolved file or directory routing without using link size", async () => {
for (const target of ["file", "directory"] as const) {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ type: "symlink", size: 8 }),
"scp-1", "/tmp/link", "auto",
async (_id, parent, encoding) => {
assert.equal(parent, "/tmp");
assert.equal(encoding, "auto");
return [{ name: "link", type: "symlink", linkTarget: target, size: "8 bytes", lastModified: "" }];
},
);
assert.deepEqual(snapshot, { size: undefined, isDirectory: target === "directory" });
}
});
test("SCP link whose current target cannot be confirmed stops safely", async () => {
for (const entries of [
[],
[{ name: "link", type: "symlink" as const, linkTarget: null, size: "8 bytes", lastModified: "" }],
[{ name: "link", type: "file" as const, size: "8 bytes", lastModified: "" }],
]) {
await assert.rejects(
resolveDownloadSourceSnapshot(
async () => stat({ type: "symlink" }),
"scp-1", "/tmp/link", "auto", async () => entries,
),
/Cannot verify the current remote source before download/,
);
}
});
test("directory routing does not require a file byte count", async () => {
const snapshot = await resolveDownloadSourceSnapshot(
async () => stat({ size: Number.NaN, sizeKnown: false, type: "directory" }),
"sftp-1", "/tmp/d", "auto",
);
assert.deepEqual(snapshot, { size: 0, isDirectory: true });
});
@@ -0,0 +1,67 @@
import type { SftpFilenameEncoding } from "../../../domain/models/sftp";
import type { RemoteFile } from "../../../domain/models/workspace";
import { getFileName, getParentPath } from "./utils";
export type DownloadSourceSnapshot = {
/** Unknown for stat-less SCP files and links; the transfer reads its wire size. */
size: number | undefined;
isDirectory: boolean;
};
type StatSftp = (
sftpId: string,
path: string,
encoding?: SftpFilenameEncoding,
) => Promise<SftpStatResult>;
type ListSftp = (
sftpId: string,
path: string,
encoding?: SftpFilenameEncoding,
) => Promise<RemoteFile[]>;
const sourceUnavailable = () => new Error("Cannot verify the current remote source before download");
/** A stale listing must never supply the size or type of a new download. */
export const resolveDownloadSourceSnapshot = async (
statSftp: StatSftp | undefined,
sftpId: string,
sourcePath: string,
encoding: SftpFilenameEncoding | undefined,
listSftp?: ListSftp,
): Promise<DownloadSourceSnapshot> => {
if (!statSftp) throw sourceUnavailable();
let stat: SftpStatResult | null;
try {
stat = await statSftp(sftpId, sourcePath, encoding);
} catch (cause) {
throw new Error("Cannot verify the current remote source before download", { cause });
}
if (!stat) {
throw sourceUnavailable();
}
if (stat.type === "directory") return { size: 0, isDirectory: true };
if (stat.type === "symlink") {
// SFTP STAT follows links; legacy SCP describes the link node. Re-list its
// parent to resolve the current target kind rather than trusting the pane.
if (!listSftp) throw sourceUnavailable();
let entries: RemoteFile[];
try {
entries = await listSftp(sftpId, getParentPath(sourcePath), encoding);
} catch (cause) {
throw new Error("Cannot verify the current remote source before download", { cause });
}
const current = entries.find((entry) => entry.name === getFileName(sourcePath));
if (current?.type !== "symlink"
|| (current.linkTarget !== "file" && current.linkTarget !== "directory")) {
throw sourceUnavailable();
}
// The link's own size is never a valid file plan; SCP's wire header is.
return { size: undefined, isDirectory: current.linkTarget === "directory" };
}
if (stat.type !== "file") throw sourceUnavailable();
if (stat.sizeKnown === false) return { size: undefined, isDirectory: false };
if (!Number.isSafeInteger(stat.size) || stat.size < 0) throw sourceUnavailable();
return { size: stat.size, isDirectory: false };
};
@@ -0,0 +1,174 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge';
import { JSDOM } from 'jsdom';
import {
startSftpFileDrag, takeLocalFileDragSources, getLocalFileDragSources,
clearLocalFileDrag, clearLocalFileDragForPane, localDragPathKey, localFileDragMoveEffect,
} from './localFileDrag';
function setup(t: test.TestContext) {
const dom = new JSDOM('<!doctype html><html><body></body></html>');
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
Object.defineProperty(globalThis, 'window', { value: dom.window, configurable: true });
const calls: { requestId: string; paths: string[] }[] = [];
const cancels: string[] = [];
const errors: string[] = [];
const remote: unknown[] = [];
const bridge = {
startLocalFileDrag: async (payload) => { calls.push(payload); return { started: true }; },
cancelLocalFileDrag: (id) => cancels.push(id),
getPathForFile: (file) => (file as unknown as { path: string }).path,
} as unknown as NetcattyBridge;
Object.defineProperty(window, "netcatty", { value: bridge, configurable: true });
t.after(() => {
clearLocalFileDrag();
dom.window.close();
if (previous) Object.defineProperty(globalThis, 'window', previous);
else Reflect.deleteProperty(globalThis, 'window');
});
const transfer = (paths: string[] = []) => ({
types: ['Files'], files: paths.map((path) => ({ path })),
effectAllowed: '', setData: (...args: string[]) => remote.push(args),
}) as unknown as DataTransfer;
const sources = [
{ name: 'certificate.txt', sourcePath: '/local', sourceConnectionId: 'local', isDirectory: false },
{ name: 'folder', sourcePath: '/another path', sourceConnectionId: 'local', isDirectory: true },
];
let prevented = 0;
const start = (isLocal: boolean | undefined = true, selection = sources) => startSftpFileDrag({
event: { dataTransfer: transfer(), preventDefault: () => { prevented++; } },
paneId: 'pane', connection: { id: 'local', isLocal }, sources: selection, side: 'left',
onRemoteDrag: (...args) => remote.push(args), onError: (error) => errors.push(error),
});
return { calls, cancels, errors, remote, transfer, sources, start, prevented: () => prevented, dom };
}
test('local multi-selection retains individual tree paths and never exports plain text', async (t) => {
const h = setup(t);
h.start();
assert.equal(h.prevented(), 1);
assert.equal(h.remote.length, 0);
assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt', '/another path/folder']);
const payload = h.transfer([...h.calls[0].paths].reverse());
assert.equal(getLocalFileDragSources(payload)?.length, 2);
assert.deepEqual(takeLocalFileDragSources(payload), h.sources.map((source) => ({ ...source, side: 'left' })));
assert.equal(takeLocalFileDragSources(payload), null, 'a native gesture is consumed exactly once');
assert.equal(getLocalFileDragSources(payload), null);
});
test('native paths retain symlink-parent segments and match the returning internal drop', (t) => {
const h = setup(t);
const sources = [{ ...h.sources[0], sourcePath: '/local/link/.././folder' }];
h.start(true, sources);
assert.deepEqual(h.calls[0].paths, ['/local/link/.././folder/certificate.txt']);
const payload = h.transfer(h.calls[0].paths);
assert.deepEqual(takeLocalFileDragSources(payload), sources.map(source => ({ ...source, side: 'left' })));
assert.equal(takeLocalFileDragSources(payload), null);
});
test('remote origin preserves HTML payload and callbacks, including absent isLocal', (t) => {
const h = setup(t);
h.start(false);
assert.equal(h.prevented(), 0);
assert.equal(h.calls.length, 0);
assert.deepEqual(h.remote, [['text/plain', 'certificate.txt\nfolder'], [h.sources, 'left']]);
startSftpFileDrag({ event: { dataTransfer: h.transfer(), preventDefault: () => assert.fail('remote drag canceled') },
paneId: 'remote', connection: { id: 'remote' }, sources: h.sources, side: 'right',
onRemoteDrag: () => {}, onError: assert.fail });
assert.equal(h.calls.length, 0);
});
test('unrelated external files cannot reuse a previous local gesture', (t) => {
const h = setup(t);
h.start();
assert.equal(takeLocalFileDragSources(h.transfer(['/different/certificate.txt'])), null);
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
assert.equal(takeLocalFileDragSources(h.transfer(['/local/certificate.txt'])), null, 'partial selection is not an internal transfer');
});
test('local failure cancels without text fallback and stale async errors cannot clear a newer gesture', async (t) => {
const h = setup(t);
let reject!: (error: Error) => void;
netcattyBridge.require().startLocalFileDrag = () => new Promise((_resolve, rejectPromise) => { reject = rejectPromise; });
h.start();
const oldReject = reject;
h.start();
oldReject(new Error('obsolete'));
await new Promise((resolve) => setImmediate(resolve));
assert.equal(h.errors.length, 0);
assert.ok(getLocalFileDragSources(h.transfer()));
reject(new Error('file disappeared'));
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(h.errors, ['file disappeared']);
assert.equal(getLocalFileDragSources(h.transfer()), null);
assert.equal(h.remote.length, 0);
});
test('native state is cleared on physical cancellation, external completion, connection disposal and new gestures', async (t) => {
const h = setup(t);
for (const event of [new h.dom.window.KeyboardEvent('keydown', { key: 'Escape' }),
new h.dom.window.MouseEvent('mousemove', { buttons: 0 }), new h.dom.window.MouseEvent('mousedown'),
new h.dom.window.Event('blur'), new h.dom.window.Event('pagehide')]) {
h.start();
await Promise.resolve();
window.dispatchEvent(event);
assert.equal(getLocalFileDragSources(h.transfer()), null, event.type);
}
h.start();
clearLocalFileDragForPane('another-pane');
assert.ok(getLocalFileDragSources(h.transfer()));
clearLocalFileDragForPane('pane');
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
h.start(false);
assert.equal(getLocalFileDragSources(h.transfer()), null);
});
test('invalid local selections and missing bridge are rejected; parent entry is excluded', (t) => {
const h = setup(t);
h.start(true, [{ ...h.sources[0], name: '..' }]);
assert.equal(h.calls.length, 0);
h.start(true, [{ ...h.sources[0], sourceConnectionId: 'remote' }]);
assert.equal(h.calls.length, 0);
h.start(true, [h.sources[0], { ...h.sources[0], name: '..' }]);
assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt']);
netcattyBridge.require().startLocalFileDrag = undefined;
h.start();
assert.equal(h.errors.length, 3);
assert.equal(h.remote.length, 0);
});
test('path matching preserves POSIX whitespace, Unicode and backslashes, and accepts Windows separators', () => {
assert.equal(localDragPathKey('C:\\Users\\david\\certificate.pem'), 'C:/Users/david/certificate.pem');
assert.equal(localDragPathKey('\\\\server\\share\\folder'), '//server/share/folder');
assert.equal(localDragPathKey('/local/é \\name '), '/local/é \\name ');
assert.notEqual(localDragPathKey('/local/A'), localDragPathKey('/local/a'));
});
test('local move accepts the copy-only native transport on Windows/Linux without changing the operation', () => {
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyLink' }), 'copy');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copy' }), 'copy');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'all' }), 'move');
assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyMove' }), 'move');
});
test('native drop cleanup survives the browser microtask checkpoint before React receives the drop', async (t) => {
const h = setup(t);
h.start();
window.dispatchEvent(new h.dom.window.Event('drop'));
// Unlike dispatchEvent in jsdom, native browser events can drain microtasks
// after the window capture callback, before the React root bubble callback.
await Promise.resolve();
assert.ok(getLocalFileDragSources(h.transfer()), 'capture must not erase native identity before React handles drop');
assert.deepEqual(takeLocalFileDragSources(h.transfer(h.calls[0].paths)), h.sources.map(source => ({ ...source, side: 'left' })));
await new Promise(resolve => setTimeout(resolve, 5));
assert.equal(getLocalFileDragSources(h.transfer()), null);
h.start();
window.dispatchEvent(new h.dom.window.Event('drop'));
await new Promise(resolve => setTimeout(resolve, 5));
assert.equal(getLocalFileDragSources(h.transfer()), null, 'unhandled drops also release the gesture');
});
+177
View File
@@ -0,0 +1,177 @@
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { joinPath } from "./utils";
export interface LocalDragSource {
name: string;
isDirectory: boolean;
sourcePath?: string;
sourceConnectionId?: string;
targetPath?: string;
side: "left" | "right";
}
interface DragSession {
requestId: string;
paneId: string;
connectionId: string;
paths: string[];
sources: LocalDragSource[];
started?: boolean;
}
// Windows separators can differ between the SFTP UI and Electron webUtils.
// POSIX backslashes, whitespace, and case must remain significant.
export function localDragPathKey(value: string): string {
if (/^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value)) {
return value.replace(/\\/g, "/").replace(/\/$/, "");
}
return value.length > 1 ? value.replace(/\/$/, "") : value;
}
class LocalFileDragState {
session: DragSession | null = null;
clear(requestId?: string) {
if (!requestId || this.session?.requestId === requestId) this.session = null;
}
take(paths: string[]): LocalDragSource[] | null {
const session = this.session;
this.clear();
if (!session || paths.length === 0 || paths.some((path) => !path)) return null;
const expected = new Set(session.paths.map(localDragPathKey));
const actual = new Set(paths.map(localDragPathKey));
if (expected.size !== actual.size || [...expected].some((path) => !actual.has(path))) return null;
return session.sources;
}
}
const state = new LocalFileDragState();
let detach: (() => void) | undefined;
export function clearLocalFileDrag(requestId?: string) {
if (requestId && state.session?.requestId !== requestId) return;
const previous = state.session;
state.clear();
detach?.();
detach = undefined;
if (previous) netcattyBridge.get()?.cancelLocalFileDrag?.(previous.requestId);
}
export function clearLocalFileDragForPane(paneId: string) {
if (state.session?.paneId === paneId) clearLocalFileDrag();
}
function observeGestureEnd() {
let dropCleanupTimer: ReturnType<typeof setTimeout> | undefined;
// Electron has no cross-platform native-drag completion callback. A canceled
// HTML drag's dragend is not a native completion signal. Clear on drop and
// on the next physical input/focus transition, including Escape and returning
// after a drop outside the window. Never retain state into a new gesture.
const clear = () => clearLocalFileDrag();
const key = (event: KeyboardEvent) => { if (event.key === "Escape") clear(); };
const move = (event: MouseEvent) => { if (state.session?.started && event.buttons === 0) clear(); };
const drop = () => {
const requestId = state.session?.requestId;
// Native event dispatch can run microtasks BETWEEN capture and React's
// bubble listener. Use a macrotask so the row/pane can consume the gesture.
dropCleanupTimer = setTimeout(() => { if (requestId) clearLocalFileDrag(requestId); }, 0);
};
// preventDefault() on dragstart produces a synthetic mouseup in Chromium.
// It must not cancel the native handoff. Observe later input instead.
window.addEventListener("mousedown", clear, true);
window.addEventListener("mousemove", move, true);
window.addEventListener("keydown", key, true);
window.addEventListener("blur", clear);
window.addEventListener("pagehide", clear);
window.addEventListener("drop", drop, true);
detach = () => {
if (dropCleanupTimer !== undefined) clearTimeout(dropCleanupTimer);
window.removeEventListener("mousedown", clear, true);
window.removeEventListener("mousemove", move, true);
window.removeEventListener("keydown", key, true);
window.removeEventListener("blur", clear);
window.removeEventListener("pagehide", clear);
window.removeEventListener("drop", drop, true);
};
}
type DragEventLike = Pick<DragEvent, "dataTransfer" | "preventDefault">;
export function startSftpFileDrag({ event, paneId, connection, sources, side, onRemoteDrag, onError }: {
event: DragEventLike;
paneId: string;
connection?: { id: string; isLocal?: boolean } | null;
sources: Omit<LocalDragSource, "side">[];
side: "left" | "right";
onRemoteDrag: (sources: Omit<LocalDragSource, "side">[], side: "left" | "right") => void;
onError: (message: string) => void;
}) {
clearLocalFileDrag();
if (connection?.isLocal !== true) {
event.dataTransfer!.effectAllowed = "copyMove";
event.dataTransfer!.setData("text/plain", sources.map((file) => file.name).join("\n"));
onRemoteDrag(sources, side);
return;
}
event.preventDefault();
const bridge = netcattyBridge.get();
if (!bridge?.startLocalFileDrag) {
onError("Native file drag is unavailable. Restart Netcatty after updating.");
return;
}
const files = sources.filter((source) => source.name !== "..");
if (!files.length || files.some((file) => !file.sourcePath || file.sourceConnectionId !== connection.id)) {
onError("The local file selection is no longer available.");
return;
}
const requestId = crypto.randomUUID();
const paths = [...new Set(files.map((file) => joinPath(file.sourcePath!, file.name)))];
state.session = { requestId, paneId, connectionId: connection.id, paths, sources: files.map((file) => ({ ...file, side })) };
observeGestureEnd();
// Send during dragstart, without awaiting in the renderer. Do not interpret
// the reply as a completed transfer or use it to clear an active gesture.
try {
void bridge.startLocalFileDrag({ requestId, paths }).then((result) => {
if (result.started && state.session?.requestId === requestId) state.session.started = true;
if (!result.started && state.session?.requestId === requestId) {
clearLocalFileDrag(requestId);
if (result.error) onError(result.error);
}
}).catch((error: unknown) => {
if (state.session?.requestId !== requestId) return;
clearLocalFileDrag(requestId);
onError(error instanceof Error ? error.message : "Unable to drag local files");
});
} catch (error) {
clearLocalFileDrag(requestId);
onError(error instanceof Error ? error.message : "Unable to drag local files");
}
}
export function getLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null {
return dataTransfer.types.includes("Files") ? state.session?.sources ?? null : null;
}
export function localFileDragMoveEffect(dataTransfer: Pick<DataTransfer, "effectAllowed">): "copy" | "move" {
// Electron's Windows/Linux native source advertises COPY | LINK, not MOVE.
// Negotiate an allowed transport effect; our existing same-pane callback is
// responsible for the actual local move (the OS must not delete originals).
return ["all", "copyMove", "linkMove", "move"].includes(dataTransfer.effectAllowed) ? "move" : "copy";
}
export function takeLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null {
if (!state.session) return null;
const bridge = netcattyBridge.get();
const session = state.session;
try {
return state.take(Array.from(dataTransfer.files).map((file) => bridge?.getPathForFile?.(file) ?? ""));
} catch {
state.clear();
return null;
} finally {
detach?.();
detach = undefined;
bridge?.cancelLocalFileDrag?.(session.requestId);
}
}
@@ -334,7 +334,8 @@ test("live directory download rejects a Windows backslash traversal entry", asyn
}
});
test("live folder settles a superseded child whose completed row was compacted", async () => {
for (const ownerChange of ["same", "changed-active", "changed-completed"] as const) {
test(`live folder settles superseded ownership without clobbering its replacement: ${ownerChange}`, async () => {
const { sftpTransferCenterStore } = await import("../sftpTransferCenterStore");
const previousWindow = (globalThis as { window?: unknown }).window;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
@@ -355,10 +356,18 @@ test("live folder settles a superseded child whose completed row was compacted",
startStreamTransfer: async (options: { transferId: string }) => {
childId = options.transferId;
sftpTransferCenterStore.publishOwner("live-compacted-owner", tasks);
// The winning invocation has already completed; history compaction drops its row.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 1, totalBytes: 1, lifecycleEpoch: 0,
});
if (ownerChange !== "same") {
const current = sftpTransferCenterStore.getTask(childId)!;
sftpTransferCenterStore.admitTaskRun({ ...current, directoryEntryIdentity: "b".repeat(64) });
}
if (ownerChange !== "changed-active") {
// The winning invocation completed; history compaction drops its row.
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: childId, transferred: 1, totalBytes: 1, lifecycleEpoch: 0,
});
}
tasks = [...sftpTransferCenterStore.getSnapshot().tasks];
transfersRef.current = tasks;
return { superseded: true };
},
} };
@@ -387,10 +396,15 @@ test("live folder settles a superseded child whose completed row was compacted",
new Promise<"still-waiting">((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
]);
assert.ok(childId);
assert.equal(sftpTransferCenterStore.getTask(childId), undefined);
assert.equal(sftpTransferCenterStore.getTask(root.id)?.directoryResumeCheckpoint?.completedEntries, 1);
if (ownerChange === "changed-active") {
assert.equal(tasks.find((task) => task.id === childId)?.status, "transferring");
assert.equal(tasks.find((task) => task.id === childId)?.directoryEntryIdentity, "b".repeat(64));
} else {
assert.equal(tasks.find((task) => task.id === childId), undefined, "old waiter must not reinsert a compacted child");
assert.equal(sftpTransferCenterStore.getTask(root.id)?.directoryResumeCheckpoint?.completedEntries, 1);
}
assert.notEqual(result, "still-waiting", "compacted completion must settle the live folder");
assert.equal(result, 0);
assert.equal(result, ownerChange === "same" ? 0 : 1);
} finally {
cancelledTasksRef.current.add(root.id);
await running?.catch(() => {});
@@ -404,3 +418,4 @@ test("live folder settles a superseded child whose completed row was compacted",
}
});
}
@@ -1,5 +1,5 @@
import { reconcileSupersededControls } from "./globalSftpTransferControl";
import { runTransferAndWaitForOwner } from "./waitForTransferOwner";
import { runTransferAndWaitForOwner, TransferOwnerChangedError } from "./waitForTransferOwner";
import { useCallback, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
import type { Host, SftpFileEntry, SftpFilenameEncoding, TransferStatus, TransferTask } from "../../../domain/models";
import {
@@ -118,6 +118,10 @@ async function tryStatTransferPath(
if (!sftpId) return null;
const stat = await netcattyBridge.get()?.statSftp?.(sftpId, filePath, encoding);
if (!stat || stat.type === "directory") return null;
// Stat-less SCP endpoints report size as a placeholder 0 (sizeKnown false).
// Treat that as missing metadata so skip-unchanged is disabled rather than
// comparing a fake zero against the other endpoint (Codex P1).
if (stat.sizeKnown === false) return null;
return { size: Number(stat.size) || 0, lastModified: Number(stat.lastModified) || 0, type: stat.type };
} catch {
return null;
@@ -978,6 +982,10 @@ export function useSftpDirectoryTransferOps({
errors.push(err instanceof Error ? err : new Error(message));
return;
}
if (err instanceof TransferOwnerChangedError) {
errors.push(err);
return;
}
// Mark child as failed
setTransfers((prev) =>
prev.map((t) =>
@@ -169,3 +169,284 @@ test("fresh directory recovery authorizes only an unchanged retained pause under
store.patchTask("root", { status: "paused", lifecycleEpoch: 6 });
assert.equal(store.admitTaskRun(task, currentPause), "paused", "parent pause still wins");
});
for (const compactNewOwner of [false, true]) {
test(`superseded waiter rejects a changed identity even after new owner compaction: ${compactNewOwner}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: `changed-owner-${compactNewOwner}`, parentTaskId: `changed-root-${compactNewOwner}` };
store.upsertTasks([{ ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true }, task]);
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => {
const changed = { ...task, directoryEntryIdentity: "b".repeat(64) };
assert.equal(store.admitTaskRun(changed), "ready");
if (compactNewOwner) {
store.patchTask(changed.id, { status: "completed" });
assert.equal(store.getTask(changed.id), undefined);
}
return { superseded: true };
}, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
await settled;
store.patchTask(task.parentTaskId, { status: "completed" });
store.dismiss(task.parentTaskId);
});
assert.match(String(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
])), /identity changed/i);
});
}
test("destination rebuild restarts only the captured completion and preserves newer controls", async (t) => {
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const store = createSftpTransferCenterStore();
const task = { ...child(), parentTaskId: undefined, status: "completed" as const, checkpointBytes: 10 };
store.upsertTasks([task]);
const captured = store.getTask(task.id)!;
const restart = { ...task, status: "transferring" as const, checkpointBytes: 0, transferredBytes: 0 };
latchTransferPause(task.id);
t.after(resetTransferPauseLatchesForTests);
assert.equal(store.admitTaskRun(restart, undefined, captured), "paused");
resetTransferPauseLatchesForTests();
assert.equal(store.admitTaskRun(restart, undefined, captured), "ready");
assert.equal(store.getTask(task.id)?.checkpointBytes, 0);
store.patchTask(task.id, { status: "completed" });
assert.equal(store.admitTaskRun(restart, undefined, captured), "completed", "new completion must not be restarted");
store.patchTask(task.id, { status: "cancelled" });
assert.equal(store.admitTaskRun(restart, undefined, captured), "cancelled");
});
test("destination rebuild waiting on pause reuses a newer compacted completion", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "restart-wait-child", parentTaskId: "restart-wait-root", directoryEntryIndex: 1 };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, { ...task, status: "completed" }]);
const captured = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort, undefined, captured);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
// An unrelated lifecycle emit must not pin the old completion in the observation.
store.patchTask(root.id, { reconnectRequired: true });
assert.equal(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 230)),
]), "still-waiting", "old completion cannot finish recovery while a new transfer is still needed");
assert.equal(starts, 0);
resetTransferPauseLatchesForTests();
store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 1 });
store.upsertTasks([{ ...task, id: "restart-wait-first", directoryEntryIndex: 0, status: "completed" }]);
store.patchTask(task.id, { status: "completed", lifecycleEpoch: 2 });
assert.equal(store.getTask(task.id), undefined);
assert.equal(await settled, "completed");
assert.equal(starts, 0, "new completion after stage rebuild must be reused even when its row was compacted");
});
test("paused admission cannot reclaim an identity replaced while it waited", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "paused-displaced", parentTaskId: undefined };
store.upsertTasks([{ ...task, status: "paused" }]);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
await settled;
store.patchTask(task.id, { status: "completed" });
store.dismiss(task.id);
});
store.upsertTasks([{ ...task, status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
assert.match(await settled, /identity changed/i);
assert.equal(starts, 0);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
for (const identityChangesDuringWait of [false, true]) {
test(`paused recovery distinguishes initial stale identity from later ownership: changed=${identityChangesDuringWait}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: `paused-origin-${identityChangesDuringWait}`, parentTaskId: `paused-origin-root-${identityChangesDuringWait}` };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, {
...task, status: identityChangesDuringWait ? "failed" : "paused",
directoryEntryIdentity: identityChangesDuringWait ? task.directoryEntryIdentity : "b".repeat(64),
}]);
const initialPause = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
let conflicts = 0;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort,
identityChangesDuringWait ? undefined : initialPause, undefined, () => { conflicts += 1; });
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
// This captures the prior failed result, or republishes the unchanged
// initial old identity. Neither is evidence of a replacement by itself.
store.patchTask(root.id, { reconnectRequired: true });
resetTransferPauseLatchesForTests();
if (identityChangesDuringWait) {
store.patchTask(task.id, { status: "transferring", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 });
}
const outcome = await settled;
if (identityChangesDuringWait) {
assert.match(outcome, /identity changed/i);
assert.equal(starts, 0);
assert.equal(conflicts, 1);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
} else {
assert.equal(outcome, "completed");
assert.equal(starts, 1);
assert.equal(conflicts, 0);
}
});
}
test("paused retry observes newer same-identity completion after an old failure", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "failed-then-completed", parentTaskId: "failed-then-completed-root" };
const root = { ...task, id: task.parentTaskId, parentTaskId: undefined, isDirectory: true };
store.upsertTasks([root, { ...task, status: "failed" }]);
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
});
store.patchTask(root.id, { reconnectRequired: true });
resetTransferPauseLatchesForTests();
store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 1 });
store.patchTask(task.id, { status: "completed", lifecycleEpoch: 2 });
assert.equal(store.getTask(task.id), undefined);
assert.equal(await settled, "completed");
assert.equal(starts, 0, "a newer completed attempt must replace the captured old failure");
});
test("an unchanged owner retains its original transport rejection", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "unchanged-rejected-owner", parentTaskId: undefined };
store.upsertTasks([task]);
t.after(() => { store.patchTask(task.id, { status: "completed" }); store.dismiss(task.id); });
const error = new Error("original transport failure");
await assert.rejects(runTransferAndWaitForOwner(task, async () => { throw error; }, () => false),
(actual) => actual === error);
});
for (const activation of ["patch", "progress", "owner"] as const) {
test(`initial stale identity exemption ends when another owner activates that row: ${activation}`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { latchTransferPause, resetTransferPauseLatchesForTests } = await import("./transferPauseLatch");
const task = { ...child(), id: "activated-initial-identity", parentTaskId: undefined };
store.upsertTasks([{ ...task, status: "paused", directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
const initial = store.getTask(task.id)!;
latchTransferPause(task.id);
let starts = 0;
let abort = false;
const running = runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => abort, initial);
const settled = running.then(() => "completed", (error: Error) => error.message);
t.after(async () => {
abort = true;
resetTransferPauseLatchesForTests();
await settled;
store.patchTask(task.id, { status: "completed" });
store.dismiss(task.id);
});
resetTransferPauseLatchesForTests();
if (activation === "progress") {
store.ingestBackgroundEvent({ type: "progress", transferId: task.id,
transferred: 1, lifecycleEpoch: 2, lifecycleState: "transferring" });
} else if (activation === "owner") store.patchTask(task.id, { ownerId: "replacement-owner" });
else store.patchTask(task.id, { status: "transferring", lifecycleEpoch: 2 });
assert.match(String(await Promise.race([
settled, new Promise((resolve) => setTimeout(() => resolve("still-waiting"), 450)),
])), /identity changed/i);
assert.equal(starts, 0);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
}
test("already active different identity is rejected before first admission", async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const task = { ...child(), id: "already-active-identity", parentTaskId: undefined };
store.upsertTasks([{ ...task, directoryEntryIdentity: "b".repeat(64), lifecycleEpoch: 1 }]);
t.after(() => { store.patchTask(task.id, { status: "completed" }); store.dismiss(task.id); });
let starts = 0;
let conflicts = 0;
await assert.rejects(runTransferAndWaitForOwner(task, async () => { starts += 1; return {}; }, () => false,
undefined, undefined, () => { conflicts += 1; }), /identity changed/i);
assert.equal(starts, 0);
assert.equal(conflicts, 1);
assert.equal(store.getTask(task.id)?.directoryEntryIdentity, "b".repeat(64));
});
for (const replacementStatus of ["transferring", "completed"] as const) {
for (const oldStatus of ["completed", "failed"] as const) {
test(`deferred ${oldStatus} cannot overwrite a ${replacementStatus} replacement after waiter exit`, async () => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { runTransferAndWaitForOwner } = await import("./waitForTransferOwner");
const { createDedicatedResumeChildUpdateBatcher } = await import("../../app/dedicatedResumeProgress");
const task = child();
const root = { ...task, id: task.parentTaskId!, parentTaskId: undefined, isDirectory: true };
const batcher = createDedicatedResumeChildUpdateBatcher({
getTaskCount: () => 4096, hasTask: () => true,
upsertTasks: (updates) => store.upsertTasks(updates),
});
store.upsertTasks([root, task]);
let observation: ReturnType<typeof store.observeTaskSettlement> | undefined;
try {
await runTransferAndWaitForOwner(task, async () => {
store.patchTask(task.id, { status: oldStatus });
return {};
}, () => false, undefined, undefined, () => batcher.discard(task.id), (value) => {
observation = value;
return true;
});
assert.ok(observation);
batcher.push({ ...task, status: oldStatus }, observation);
store.upsertTasks([{ ...task, directoryEntryIdentity: "b".repeat(64), status: replacementStatus }]);
const replacement = store.getTask(task.id);
batcher.flush();
assert.equal(store.getTask(task.id), replacement);
if (replacementStatus === "transferring") assert.equal(replacement?.directoryEntryIdentity, "b".repeat(64));
else assert.equal(replacement, undefined, "the replacement remains compacted");
assert.equal(observation.read(), undefined, "the retained observation is disposed");
} finally {
batcher.flush();
observation?.dispose();
store.patchTask(root.id, { status: "completed" });
store.dismiss(root.id);
}
});
}
}
+24 -5
View File
@@ -1,6 +1,11 @@
import type { TransferTask } from "../../../domain/models";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
/** The displaced invocation may fail its walk, but no longer owns the child row. */
export class TransferOwnerChangedError extends Error {}
export type TransferOwnerObservation = ReturnType<typeof sftpTransferCenterStore.observeTaskSettlement>;
type StreamResult = { error?: string; cancelled?: boolean; superseded?: boolean } | undefined;
/** A live waiter owns bounded settlement evidence; persisted history stays compact. */
@@ -9,33 +14,47 @@ export async function runTransferAndWaitForOwner(
start: () => Promise<StreamResult>,
shouldAbort: () => boolean,
pausedAtResume?: TransferTask,
completedAtRestart?: TransferTask,
onOwnerChanged?: () => void,
retainObservation?: (observation: TransferOwnerObservation) => boolean,
existingObservation?: TransferOwnerObservation,
): Promise<StreamResult> {
// Register before admission/start: an owner may finish while dispatch waits for resume.
let observation = sftpTransferCenterStore.observeTaskSettlement(task);
let observation = existingObservation ?? sftpTransferCenterStore.observeTaskSettlement(task, completedAtRestart, onOwnerChanged);
try {
for (;;) {
if (shouldAbort()) throw new Error("Transfer cancelled");
const admission = sftpTransferCenterStore.admitTaskRun(task, pausedAtResume);
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed before dispatch");
const admission = sftpTransferCenterStore.admitTaskRun(task, pausedAtResume, completedAtRestart);
if (admission === "cancelled") throw new Error("Transfer cancelled");
if (admission === "completed" || observation.read()?.status === "completed") return {};
if (admission === "conflict") throw new Error("Transfer identity changed before dispatch");
if (admission === "conflict") throw new TransferOwnerChangedError("Transfer identity changed before dispatch");
if (admission === "ready") break;
await new Promise((resolve) => setTimeout(resolve, 200));
}
// Admission begins a new attempt; discard any previous failed settlement.
observation.dispose();
observation = sftpTransferCenterStore.observeTaskSettlement(task);
observation = sftpTransferCenterStore.observeTaskSettlement(task, undefined, onOwnerChanged);
const result = await start();
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
if (!result?.superseded) return result;
for (;;) {
if (shouldAbort()) throw new Error("Transfer cancelled");
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
const latest = observation.read();
if (latest?.status === "completed") return { ...result, superseded: false };
if (latest?.status === "failed") throw new Error(latest.error || "Transfer failed");
if (latest?.status === "cancelled") throw new Error("Transfer cancelled");
await new Promise((resolve) => setTimeout(resolve, 200));
}
} catch (error) {
// A displaced invocation can reject instead of returning superseded. Its
// transport error must not regain permission to write the winning row.
if (observation.hasIdentityConflict()) throw new TransferOwnerChangedError("Transfer identity changed while waiting for its owner");
throw error;
} finally {
observation.dispose();
// A deferred child update may outlive the invocation. Its caller must either
// retain this evidence through the write or release it after handling exit.
if (!retainObservation?.(observation)) observation.dispose();
}
}
+71 -16
View File
@@ -42,6 +42,14 @@ import { restoreSftpTransferHistoryCooperatively } from "./sftp/transferHistoryR
import { cancelExternalUploadRuntime } from "./sftp/externalUploadRuntime";
type Listener = () => void;
type TaskSettlementObserver = {
expected: TransferTask;
initialInactiveRow?: TransferTask;
settled?: TransferTask;
conflicted?: boolean;
ignoredCompletion?: TransferTask;
onIdentityConflict?: () => void;
};
// Ordinary bounded history restores synchronously so existing callers receive
// it immediately. Legacy directory snapshots can contain tens of thousands of
@@ -98,9 +106,9 @@ export interface SftpTransferCenterStore {
/** Single task row — same object identity until that row is patched. */
getTask(taskId: string): TransferTask | undefined;
/** Observe exact task settlement before completed child rows are compacted. */
observeTaskSettlement(task: TransferTask): { read(): TransferTask | undefined; dispose(): void };
observeTaskSettlement(task: TransferTask, ignoredCompletion?: TransferTask, onIdentityConflict?: () => void): { read(): TransferTask | undefined; hasIdentityConflict(): boolean; dispose(): void };
/** Publish an explicit dispatch identity without flushing large child-history batches. */
admitTaskRun(task: TransferTask, pausedAtResume?: TransferTask): "ready" | "paused" | "completed" | "cancelled" | "conflict";
admitTaskRun(task: TransferTask, pausedAtResume?: TransferTask, completedAtRestart?: TransferTask): "ready" | "paused" | "completed" | "cancelled" | "conflict";
getOwnerTasks(ownerId: string): TransferTask[];
publishOwner(ownerId: string, tasks: readonly TransferTask[]): void;
registerOwner(ownerId: string, controls: SftpTransferOwnerControls): () => void;
@@ -405,7 +413,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
let snapshotDirty = false;
const listeners = new Set<Listener>();
const progressListeners = new Set<Listener>();
const settlementObservers = new Map<string, Set<{ expected: TransferTask; settled?: TransferTask }>>();
const settlementObservers = new Map<string, Set<TaskSettlementObserver>>();
const matchesObservedTask = (expected: TransferTask, candidate: TransferTask) => (
expected.id === candidate.id
&& expected.sourcePath === candidate.sourcePath
@@ -414,6 +422,29 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
&& expected.directoryEntryIndex === candidate.directoryEntryIndex
&& expected.directoryEntryIdentity === candidate.directoryEntryIdentity
);
const captureObservedTask = (task: TransferTask) => {
for (const observer of settlementObservers.get(task.id) ?? []) {
if (observer.conflicted || task === observer.ignoredCompletion) continue;
const matchesExpected = matchesObservedTask(observer.expected, task);
// A retry may plan a new source identity while its initial stale row is
// still paused. Only the unchanged initial attempt is exempt: activating
// it or replacing its owner/epoch must not let the stale plan reclaim it.
if (!matchesExpected && observer.initialInactiveRow
&& matchesObservedTask(observer.initialInactiveRow, task)
&& observer.initialInactiveRow.status === task.status
&& observer.initialInactiveRow.lifecycleEpoch === task.lifecycleEpoch
&& observer.initialInactiveRow.ownerId === task.ownerId) continue;
observer.initialInactiveRow = undefined;
if (!matchesExpected) {
observer.conflicted = true;
observer.onIdentityConflict?.();
} else if (observer.settled?.status !== "completed") {
// Failed/cancelled evidence belongs to the latest observed attempt. A
// resumed owner can supersede it; exact successful completion stays final.
observer.settled = TERMINAL_OWNER_STATUSES.has(task.status) ? task : undefined;
}
}
};
const refreshBadgeSnapshot = () => {
const next = buildBadgeSnapshot(tasks);
if (
@@ -633,12 +664,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// settles; everything else can release its whole tree here.
settleFinishedTransferControlState(tasks, tasks);
if (settlementObservers.size > 0) {
for (const task of tasks) {
if (!TERMINAL_OWNER_STATUSES.has(task.status)) continue;
for (const observer of settlementObservers.get(task.id) ?? []) {
if (!observer.settled && matchesObservedTask(observer.expected, task)) observer.settled = task;
}
}
for (const task of tasks) captureObservedTask(task);
}
const beforePrune = tasks;
tasks = pruneSftpTransferHistory(tasks);
@@ -1338,7 +1364,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
},
getSnapshot: () => ensureSnapshot(),
getBadgeSnapshot: () => badgeSnapshot,
admitTaskRun(incoming, pausedAtResume) {
admitTaskRun(incoming, pausedAtResume, completedAtRestart) {
const rootId = incoming.parentTaskId ?? incoming.id;
if (isTransferOrRootCancelled(rootId, incoming.id)) return "cancelled";
const parent = incoming.parentTaskId ? tasks.find((task) => task.id === rootId) : undefined;
@@ -1348,7 +1374,10 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if (existing && (existing.sourcePath !== incoming.sourcePath || existing.targetPath !== incoming.targetPath
|| existing.parentTaskId !== incoming.parentTaskId)) return "conflict";
if (existing?.status === "cancelled") return "cancelled";
if (existing?.status === "completed") {
// Only the exact completion captured at the destination reset is
// stale. A newer completion or user control must keep its authority.
const restartsCompletion = existing?.status === "completed" && existing === completedAtRestart;
if (existing?.status === "completed" && !restartsCompletion) {
return matchesObservedTask(incoming, existing) ? "completed" : "conflict";
}
const resumesUnchangedPause = existing === pausedAtResume
@@ -1369,6 +1398,14 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
...existing,
directoryEntryIndex: incoming.directoryEntryIndex,
directoryEntryIdentity: incoming.directoryEntryIdentity,
...(restartsCompletion ? {
checkpointBytes: incoming.checkpointBytes,
transferredBytes: incoming.transferredBytes,
resumeStage: incoming.resumeStage,
downloadCheckpointBytes: incoming.downloadCheckpointBytes,
uploadCheckpointBytes: incoming.uploadCheckpointBytes,
sourceFingerprint: incoming.sourceFingerprint,
} : {}),
...(existing.status === "transferring" ? {} : {
status: "transferring" as const,
lifecycleEpoch: undefined,
@@ -1378,25 +1415,36 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
}),
};
tasks = next;
captureObservedTask(next[index]);
emitProgress(false);
return "ready";
},
observeTaskSettlement(expected) {
const observer: { expected: TransferTask; settled?: TransferTask } = { expected: { ...expected } };
observeTaskSettlement(expected, ignoredCompletion, onIdentityConflict) {
const initial = tasks.find((task) => task.id === expected.id);
const observer: TaskSettlementObserver = {
expected: { ...expected }, ignoredCompletion, onIdentityConflict,
initialInactiveRow: initial && ["paused", "failed", "interrupted", "attention"].includes(initial.status)
&& !matchesObservedTask(expected, initial) ? { ...initial } : undefined,
};
const observers = settlementObservers.get(expected.id) ?? new Set();
observers.add(observer);
settlementObservers.set(expected.id, observers);
// A different active owner may predate registration. Detect it now,
// before admission can publish the stale caller's identity over it.
if (initial) captureObservedTask(initial);
let disposed = false;
return {
read() {
if (disposed) return undefined;
if (observer.settled) return observer.settled;
const current = tasks.find((task) => task.id === expected.id);
return current && matchesObservedTask(observer.expected, current) ? current : undefined;
return current && current !== ignoredCompletion && matchesObservedTask(observer.expected, current) ? current : undefined;
},
hasIdentityConflict: () => !disposed && observer.conflicted === true,
dispose() {
disposed = true;
observer.settled = undefined;
observer.conflicted = undefined;
observers.delete(observer);
if (observers.size === 0) settlementObservers.delete(expected.id);
},
@@ -1662,6 +1710,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
const next = tasks.slice();
next[index] = nextTask;
tasks = next;
captureObservedTask(nextTask);
if (changed) {
const lifecycleChanged = (
(updates.status !== undefined && updates.status !== task.status)
@@ -2023,7 +2072,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
backgroundEventsDuringRestore.set(event.transferId, pending);
return;
}
let existing = tasks.find((task) => task.id === event.transferId);
let existingIndex = tasks.findIndex((task) => task.id === event.transferId);
let existing = tasks[existingIndex];
const eventParent = event.parentTaskId
? tasks.find((task) => task.id === event.parentTaskId)
: undefined;
@@ -2039,7 +2089,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
directoryEntryIdentity: event.directoryEntryIdentity ?? task.directoryEntryIdentity,
background: false,
} : task);
existing = tasks.find((task) => task.id === event.transferId);
existing = tasks[existingIndex];
captureObservedTask(existing);
}
// A delayed child progress event can arrive after the renderer compacted
// that completed child into its parent checkpoint. Never resurrect it as
@@ -2119,6 +2170,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if ((event.type === "queued" || event.type === "started" || event.type === "progress") && !existing) {
const sourcePath = event.sourcePath ?? "";
const targetPath = event.targetPath ?? "";
existingIndex = tasks.length;
tasks.push({
id: event.transferId,
ownerId: eventParent?.ownerId
@@ -2352,6 +2404,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
phase: undefined,
} : task);
}
// Ownership changes must be observed synchronously even when a progress
// event takes the lightweight UI path. Reuse the located row, not a scan.
if (existingIndex >= 0) captureObservedTask(tasks[existingIndex]);
// Progress-only ticks skip prune + coalesce listener paints; lifecycle
// events still take the full emit path so UI never lags on pause/cancel.
if (event.type === "progress" && !persistImmediately) {
+155
View File
@@ -352,3 +352,158 @@ test("manual stop still returns its recording and permits a clean restart", asyn
assert.equal(recorder!.isRecording, true);
await act(async () => renderer!.unmount());
});
test("confirmed line-by-line recording awaits each send and prompt step in order", async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
let appendGate: Promise<void> | undefined;
let stopCalls = 0;
const steps: Array<{ type: string; value?: unknown; sensitive?: boolean }> = [];
const eventTarget = new EventTarget();
Object.assign(eventTarget, {
netcatty: {
scriptRecordingStart: async () => ({ ok: true }),
scriptRecordingStop: async () => { stopCalls++; return { steps: [...steps], code: "" }; },
scriptRecordingAppendStep: async (_id: string, step: typeof steps[number]) => {
await appendGate;
await new Promise(resolve => setImmediate(resolve));
steps.push(step);
return { stopped: false };
},
},
setInterval, clearInterval,
});
Object.defineProperty(globalThis, "window", { configurable: true, value: eventTarget });
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
let recorder!: Recorder;
let renderer!: ReactTestRenderer;
function Probe() { recorder = useScriptRecorder("session-1"); return null; }
await act(async () => { renderer = create(React.createElement(Probe)); });
try {
await act(async () => { await recorder.startRecording(); });
await act(async () => {
recorder.recordInput("echo ");
const recordLine = recorder.captureSubmittedLineRecorder()!;
recorder.recordInput("new input");
await Promise.all([recordLine("echo first"), recordLine("cd /tmp")]);
});
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "echo first"], ["waitForPrompt", undefined],
["send", "cd /tmp"], ["waitForPrompt", undefined],
]);
steps.length = 0;
await act(async () => {
await recorder.recordEnter();
assert.equal(steps[0].value, "new input");
steps.length = 0;
const recordLine = recorder.captureSubmittedLineRecorder()!;
await Promise.all([recordLine("secret", { sensitive: true }), recordLine("second secret", { sensitive: true })]);
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.sensitive), [true, true]);
const staleRecorder = recorder.captureSubmittedLineRecorder()!;
await act(async () => { await recorder.stopRecording(); await recorder.startRecording(); });
steps.length = 0;
await act(async () => { await staleRecorder("never sent in this recording"); });
assert.deepEqual(steps, []);
const pauseGate = deferred<void>();
appendGate = pauseGate.promise;
const beforePause = recorder.captureSubmittedLineRecorder()!;
const pausedFirst = beforePause("sent before pause 1");
const pausedSecond = beforePause("sent before pause 2");
await flushReact();
act(() => recorder.pauseRecording());
await beforePause("ignored while paused");
pauseGate.resolve();
await act(async () => { await Promise.all([pausedFirst, pausedSecond]); });
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "sent before pause 1"], ["waitForPrompt", undefined],
["send", "sent before pause 2"], ["waitForPrompt", undefined],
]);
act(() => recorder.resumeRecording());
steps.length = 0;
const gate = deferred<void>();
appendGate = gate.promise;
const recordLine = recorder.captureSubmittedLineRecorder()!;
const first = recordLine("sent first");
const second = recordLine("sent second");
await flushReact();
let stopped!: ReturnType<Recorder["stopRecording"]>;
act(() => { stopped = recorder.stopRecording(); });
assert.equal(stopCalls, 1);
await recordLine("arrived after stop");
gate.resolve();
await act(async () => { await Promise.all([first, second, stopped]); });
assert.equal(stopCalls, 2);
assert.deepEqual(steps.map(step => [step.type, step.value]), [
["send", "sent first"], ["waitForPrompt", undefined],
["send", "sent second"], ["waitForPrompt", undefined],
]);
} finally {
await act(async () => renderer.unmount());
}
});
test("paced recording uses its captured prefix and never imports text typed while paused", async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const steps: Array<{ type: string; value?: unknown }> = [];
const target = new EventTarget();
Object.assign(target, {
netcatty: {
scriptRecordingStart: async () => ({ ok: true }),
scriptRecordingAppendStep: async (_id: string, step: typeof steps[number]) => {
steps.push(step);
return { stopped: false };
},
}, setInterval, clearInterval,
});
Object.defineProperty(globalThis, "window", { configurable: true, value: target });
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
let recorder!: Recorder;
let renderer!: ReactTestRenderer;
function Probe() { recorder = useScriptRecorder("s"); return null; }
await act(async () => { renderer = create(React.createElement(Probe)); });
try {
await act(async () => {
await recorder.startRecording();
recorder.recordInput("echo ");
recorder.pauseRecording();
recorder.recordInput("PAUSED_");
recorder.resumeRecording();
const lineRecorder = recorder.captureSubmittedLineRecorder()!;
recorder.recordInput("next input");
await lineRecorder("first", { includePendingInput: true });
await lineRecorder("second");
await recorder.recordEnter();
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["echo first", "second", "next input"]);
steps.length = 0;
await act(async () => {
recorder.recordInput("preserved ");
recorder.captureSubmittedLineRecorder(); // No write receipt: rejected batch.
recorder.recordInput("draft");
await recorder.recordEnter();
assert.equal(steps.find(step => step.type === "send")?.value, "preserved draft");
steps.length = 0;
recorder.recordInput("old ");
const lateReceipt = recorder.captureSubmittedLineRecorder()!;
recorder.recordClearLine();
recorder.recordInput("old new draft");
await lateReceipt("sent", { includePendingInput: true });
await recorder.recordEnter();
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["old sent", "old new draft"]);
steps.length = 0;
recorder.recordInput("prefix for a dropped first line");
const lineRecorder = recorder.captureSubmittedLineRecorder()!;
await lineRecorder("second was sent", { consumePendingInput: false });
await recorder.recordEnter();
});
assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["second was sent", "prefix for a dropped first line"]);
} finally {
await act(async () => renderer.unmount());
}
});
+67 -20
View File
@@ -27,12 +27,16 @@ export function useScriptRecorder(sessionId: string | undefined) {
const [elapsedMs, setElapsedMs] = useState(0);
const startedAtRef = useRef<number | null>(null);
const inputBufferRef = useRef('');
const inputRevisionRef = useRef(0);
const lastStepAtRef = useRef<number>(Date.now());
const isRecordingRef = useRef(false);
const isPausedRef = useRef(false);
const isStoppingRef = useRef(false);
const stopPromiseRef = useRef<Promise<ScriptRecordingResult> | null>(null);
const sessionIdRef = useRef(sessionId);
const recordingGenerationRef = useRef(0);
const pendingRecordStepsRef = useRef(Promise.resolve());
const isDrainingRecordingRef = useRef(false);
sessionIdRef.current = sessionId;
@@ -60,8 +64,10 @@ export function useScriptRecorder(sessionId: string | undefined) {
const bridge = netcattyBridge.get();
if (!sid || !bridge?.scriptRecordingStart) return;
await bridge.scriptRecordingStart(sid);
recordingGenerationRef.current += 1;
startedAtRef.current = Date.now();
lastStepAtRef.current = Date.now();
inputRevisionRef.current += 1;
inputBufferRef.current = '';
setElapsedMs(0);
setIsPaused(false);
@@ -76,27 +82,26 @@ export function useScriptRecorder(sessionId: string | undefined) {
const sid = sessionIdRef.current;
const bridge = netcattyBridge.get();
isStoppingRef.current = true;
isDrainingRecordingRef.current = true;
isRecordingRef.current = false;
isPausedRef.current = false;
setIsRecording(false);
setIsPaused(false);
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
if (!sid || !bridge?.scriptRecordingStop) {
isStoppingRef.current = false;
isDrainingRecordingRef.current = false;
return emptyScriptRecordingResult();
}
let stopRequest: Promise<ScriptRecordingResult>;
try {
stopRequest = Promise.resolve(bridge.scriptRecordingStop(sid));
} catch (error) {
stopRequest = Promise.reject(error);
}
const stopRequest = pendingRecordStepsRef.current.catch(() => {}).then(() => bridge.scriptRecordingStop!(sid));
let stopPromise: Promise<ScriptRecordingResult>;
stopPromise = stopRequest.finally(() => {
if (stopPromiseRef.current === stopPromise) {
stopPromiseRef.current = null;
isStoppingRef.current = false;
isDrainingRecordingRef.current = false;
}
});
stopPromiseRef.current = stopPromise;
@@ -104,8 +109,10 @@ export function useScriptRecorder(sessionId: string | undefined) {
}, []);
const finishAutomaticStop = useCallback((detail: ScriptRecordingLimitDetail) => {
isDrainingRecordingRef.current = false;
isRecordingRef.current = false;
isPausedRef.current = false;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
setIsRecording(false);
@@ -126,10 +133,13 @@ export function useScriptRecorder(sessionId: string | undefined) {
setIsPaused(false);
}, []);
const appendStep = useCallback(async (step: ScriptRecordingStep) => {
const appendStep = useCallback(async (step: ScriptRecordingStep, accepted = false) => {
const sid = sessionIdRef.current;
if (!sid || !isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
if (!sid || (!(accepted && isDrainingRecordingRef.current)
&& (!isRecordingRef.current || (!accepted && isPausedRef.current) || isStoppingRef.current))) return;
const generation = recordingGenerationRef.current;
const result = await netcattyBridge.get()?.scriptRecordingAppendStep?.(sid, step);
if (generation !== recordingGenerationRef.current || sid !== sessionIdRef.current) return;
if (result?.stopped) {
finishAutomaticStop({
sessionId: sid,
@@ -154,6 +164,7 @@ export function useScriptRecorder(sessionId: string | undefined) {
isStoppingRef.current = true;
isRecordingRef.current = false;
isPausedRef.current = false;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
startedAtRef.current = null;
setIsRecording(false);
@@ -188,33 +199,68 @@ export function useScriptRecorder(sessionId: string | undefined) {
const recordBackspace = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
inputRevisionRef.current += 1;
inputBufferRef.current = inputBufferRef.current.slice(0, -1);
}, []);
const recordClearLine = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return;
inputRevisionRef.current += 1;
inputBufferRef.current = '';
}, []);
const recordEnter = useCallback(async (options?: { sensitive?: boolean }) => {
const recordEnter = useCallback(async (options?: { sensitive?: boolean; submittedLine?: string }) => {
const sid = sessionIdRef.current;
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current || !sid) return;
const line = inputBufferRef.current;
inputBufferRef.current = '';
const line = options?.submittedLine ?? inputBufferRef.current;
if (options?.submittedLine === undefined) {
inputRevisionRef.current += 1;
inputBufferRef.current = '';
}
const now = Date.now();
const gap = now - lastStepAtRef.current;
if (gap > 1000) {
await appendStep({ type: 'sleep', value: gap });
}
await appendStep({
type: 'send',
value: line,
sensitive: options?.sensitive,
});
await appendStep({ type: 'waitForPrompt', timeoutMs: DEFAULT_RECORDING_PROMPT_TIMEOUT_MS });
lastStepAtRef.current = now;
const generation = recordingGenerationRef.current;
const pending = pendingRecordStepsRef.current.catch(() => {}).then(async () => {
const isCurrent = () => generation === recordingGenerationRef.current && sid === sessionIdRef.current
&& (isRecordingRef.current || isDrainingRecordingRef.current);
if (!isCurrent()) return;
if (gap > 1000) await appendStep({ type: 'sleep', value: gap }, true);
if (!isCurrent()) return;
await appendStep({ type: 'send', value: line, sensitive: options?.sensitive }, true);
if (!isCurrent()) return;
await appendStep({ type: 'waitForPrompt', timeoutMs: DEFAULT_RECORDING_PROMPT_TIMEOUT_MS }, true);
});
pendingRecordStepsRef.current = pending;
await pending;
}, [appendStep]);
// Delayed paste receipts must not consume newly typed input or leak into a
// recording started after the paste. Each receipt records one actual write.
const captureSubmittedLineRecorder = useCallback(() => {
if (!isRecordingRef.current || isPausedRef.current || isStoppingRef.current) return undefined;
const generation = recordingGenerationRef.current;
const sid = sessionIdRef.current;
const pendingInput = inputBufferRef.current;
const revision = inputRevisionRef.current;
let consumed = false;
const isCurrent = () => generation === recordingGenerationRef.current
&& sid === sessionIdRef.current && isRecordingRef.current
&& !isPausedRef.current && !isStoppingRef.current;
return (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }): Promise<void> => {
// Capturing a batch is not a write. Retain its prefix if no receipt
// arrives; only its prefixed first line can consume the still-owned draft.
if (options?.consumePendingInput !== false && !consumed && generation === recordingGenerationRef.current && sid === sessionIdRef.current
&& revision === inputRevisionRef.current && inputBufferRef.current.startsWith(pendingInput)) {
inputBufferRef.current = inputBufferRef.current.slice(pendingInput.length);
inputRevisionRef.current += 1;
}
if (options?.consumePendingInput !== false) consumed = true;
if (!isCurrent()) return Promise.resolve();
return recordEnter({ sensitive: options?.sensitive, submittedLine: options?.includePendingInput ? `${pendingInput}${line}` : line });
};
}, [recordEnter]);
return {
isRecording,
isPaused,
@@ -227,5 +273,6 @@ export function useScriptRecorder(sessionId: string | undefined) {
recordBackspace,
recordClearLine,
recordEnter,
captureSubmittedLineRecorder,
};
}
+12
View File
@@ -33,6 +33,10 @@ export interface ServerStats {
cpu: number | null; // CPU usage percentage (0-100)
cpuCores: number | null; // Number of CPU cores
cpuPerCore: number[]; // Per-core CPU usage array
gpu: number | null; // NVIDIA GPU utilization percentage (0-100), null when no GPU data
gpuName: string | null; // First GPU name (tooltip)
gpuMemUsed: number | null; // Summed VRAM used in MB
gpuMemTotal: number | null; // Summed VRAM total in MB
memTotal: number | null; // Total memory in MB
memUsed: number | null; // Used memory in MB (excluding buffers/cache)
memFree: number | null; // Free memory in MB
@@ -107,6 +111,10 @@ function createEmptyServerStats(): ServerStats {
cpu: null,
cpuCores: null,
cpuPerCore: [],
gpu: null,
gpuName: null,
gpuMemUsed: null,
gpuMemTotal: null,
memTotal: null,
memUsed: null,
memFree: null,
@@ -200,6 +208,10 @@ function normalizeServerStats(stats: Partial<ServerStats>): ServerStats {
cpu: stats.cpu ?? null,
cpuCores: stats.cpuCores ?? null,
cpuPerCore: stats.cpuPerCore || [],
gpu: stats.gpu ?? null,
gpuName: stats.gpuName ?? null,
gpuMemUsed: stats.gpuMemUsed ?? null,
gpuMemTotal: stats.gpuMemTotal ?? null,
memTotal: stats.memTotal ?? null,
memUsed: stats.memUsed ?? null,
memFree: stats.memFree ?? null,
+46 -3
View File
@@ -83,6 +83,8 @@ import {
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
@@ -434,6 +436,14 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
const stored = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
return isTerminalSidePanelAutoOpenTab(stored) ? stored : DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB;
});
const [localShellSidePanelAutoOpen, setLocalShellSidePanelAutoOpenState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN);
return stored ?? false;
});
const [localShellSidePanelAutoOpenTab, setLocalShellSidePanelAutoOpenTabState] = useState<TerminalSidePanelAutoOpenTab>(() => {
const stored = readStoredString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB);
return isTerminalSidePanelAutoOpenTab(stored) ? stored : 'scripts';
});
const [shellOnlyTabNumberShortcuts, setShellOnlyTabNumberShortcutsState] = useState<boolean>(() => {
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
return stored ?? DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS;
@@ -1030,6 +1040,14 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
? storedTerminalSidePanelAutoOpenTab
: DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
);
const storedLocalShellSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN);
setLocalShellSidePanelAutoOpenState(storedLocalShellSidePanelAutoOpen ?? false);
const storedLocalShellSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB);
setLocalShellSidePanelAutoOpenTabState(
isTerminalSidePanelAutoOpenTab(storedLocalShellSidePanelAutoOpenTab)
? storedLocalShellSidePanelAutoOpenTab
: 'scripts',
);
const storedShellOnlyTabNumberShortcuts = localStorageAdapter.readBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
setShellOnlyTabNumberShortcutsState(storedShellOnlyTabNumberShortcuts ?? DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
const storedShowTabNumberBadges = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_TAB_NUMBER_BADGES);
@@ -1208,6 +1226,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setShowHostTreeSidebarState,
setTerminalSidePanelAutoOpenState,
setTerminalSidePanelAutoOpenTabState,
setLocalShellSidePanelAutoOpenState,
setLocalShellSidePanelAutoOpenTabState,
setDisableTerminalFontZoomState,
setRestorePreviousSessionState,
setRestoreTerminalCwdState,
@@ -1261,7 +1281,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode,
@@ -1271,7 +1291,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setTabBarPositionState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
@@ -1438,6 +1458,21 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
notifySettingsChanged(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB, next);
}, [notifySettingsChanged]);
const setLocalShellSidePanelAutoOpen = useCallback((enabled: boolean) => {
setLocalShellSidePanelAutoOpenState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, enabled);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, enabled);
}, [notifySettingsChanged]);
const setLocalShellSidePanelAutoOpenTab = useCallback((tab: TerminalSidePanelAutoOpenTab) => {
const next = isTerminalSidePanelAutoOpenTab(tab) ? tab : 'scripts';
setLocalShellSidePanelAutoOpenTabState(next);
localStorageAdapter.writeString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, next);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, next);
}, [notifySettingsChanged]);
const setShellOnlyTabNumberShortcuts = useCallback((enabled: boolean) => {
setShellOnlyTabNumberShortcutsState(enabled);
localStorageAdapter.writeBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS, enabled);
@@ -1894,6 +1929,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
restoreTerminalCwd,
terminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
});
}, [
darkUiThemeId,
@@ -1916,6 +1953,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
theme,
uiLanguage,
windowOpacity,
localShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
]);
useLayoutEffect(() => {
@@ -2090,6 +2129,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
setTerminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
setLocalShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
setLocalShellSidePanelAutoOpenTab,
shellOnlyTabNumberShortcuts,
setShellOnlyTabNumberShortcuts,
showTabNumberBadges,
@@ -2158,7 +2201,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
terminalThemeId, terminalFontFamilyId, terminalFontSize, terminalSettings,
customKeyBindings, editorWordWrap,
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, tabBarPosition, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom,
customThemes, workspaceFocusStyle, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
]),
};
+11 -3
View File
@@ -202,13 +202,19 @@ export const useTerminalBackend = () => {
bridge?.writeToSession?.(sessionId, data, options);
}, []);
const interruptSession = useCallback((sessionId: string, trace?: NetcattyTerminalInterruptTrace) => {
const notifyUserInput = useCallback((sessionId: string) => {
const bridge = netcattyBridge.get();
bridge?.notifySessionUserInput?.(sessionId);
}, []);
const interruptSession = useCallback((...args: Parameters<NonNullable<NetcattyBridge["interruptSession"]>>) => {
const [sessionId, , options] = args;
const bridge = netcattyBridge.get();
if (bridge?.interruptSession) {
bridge.interruptSession(sessionId, trace);
bridge.interruptSession(...args);
return;
}
bridge?.writeToSession?.(sessionId, "\x03");
if (!options?.cancelPendingWritesOnly) bridge?.writeToSession?.(sessionId, "\x03");
}, []);
const resizeSession = useCallback((sessionId: string, cols: number, rows: number) => {
@@ -593,6 +599,7 @@ export const useTerminalBackend = () => {
getSessionDistroInfo,
getServerStats,
writeToSession,
notifyUserInput,
interruptSession,
resizeSession,
clearSessionPtyBuffer,
@@ -675,6 +682,7 @@ export const useTerminalBackend = () => {
getSessionDistroInfo,
getServerStats,
writeToSession,
notifyUserInput,
interruptSession,
resizeSession,
clearSessionPtyBuffer,
@@ -4,7 +4,7 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { GroupConfig, ManagedSource } from "../../domain/models.ts";
import { useVaultGroupDeletion } from "./useVaultGroupDeletion.ts";
import { useVaultGroupDeletion, VaultGroupDeletionConfirmationChangedError } from "./useVaultGroupDeletion.ts";
test("group deletion removes saved settings in the same Vault transaction", async () => {
const actEnvironment = globalThis as typeof globalThis & {
@@ -132,7 +132,7 @@ test("group deletion restores managed files when the persisted Vault cannot be r
assert.equal(commitCount, 0);
});
test("group deletion retries file clearing when another managed source enters the group", async () => {
test("group deletion rejects retry when another managed source enters the group", async () => {
const actEnvironment = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
};
@@ -198,7 +198,7 @@ test("group deletion retries file clearing when another managed source enters th
renderer = create(React.createElement(Probe));
});
await act(async () => {
await deleteGroups?.(["Production"]);
await assert.rejects(deleteGroups!(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
} finally {
await act(async () => {
@@ -209,10 +209,9 @@ test("group deletion retries file clearing when another managed source enters th
assert.deepEqual(clearedSourceIds, [
["managed-first"],
["managed-concurrent", "managed-first"],
]);
assert.equal(restoreCount, 1);
assert.equal(commitCount, 1);
assert.equal(commitCount, 0);
});
test("group deletion restores managed files and does not report success when commit fails", async () => {
@@ -278,3 +277,209 @@ test("group deletion restores managed files and does not report success when com
assert.equal(restoreCount, 1);
assert.equal(reportedCount, 0);
});
const confirmedSource: ManagedSource = {
id: "managed-production",
type: "ssh_config",
filePath: "/tmp/managed-production.conf",
groupName: "Production",
lastSyncedAt: 1,
};
async function withDeletionProbe(
options: Partial<Parameters<typeof useVaultGroupDeletion>[0]>,
run: (getDelete: () => ReturnType<typeof useVaultGroupDeletion>, rerender: (sources: ManagedSource[]) => Promise<void>) => Promise<void>,
) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let deleteGroups!: ReturnType<typeof useVaultGroupDeletion>;
const defaults: Parameters<typeof useVaultGroupDeletion>[0] = {
customGroups: ["Production"], hosts: [], groupConfigs: [],
managedSources: [confirmedSource],
onReadPersistedHosts: async () => [],
onReadPersistedManagedSources: () => [confirmedSource],
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [],
managedSources: [confirmedSource], snippets: [],
}),
...options,
};
const Probe = ({ sources }: { sources: ManagedSource[] }) => {
deleteGroups = useVaultGroupDeletion({ ...defaults, managedSources: sources });
return null;
};
try {
await act(async () => {
renderer = create(<Probe sources={defaults.managedSources} />);
});
await run(() => deleteGroups, async (sources) => {
await act(async () => { renderer!.update(<Probe sources={sources} />); });
});
} finally {
await act(async () => { renderer?.unmount(); });
environment.IS_REACT_ACT_ENVIRONMENT = previous;
}
}
for (const [name, rendered, persisted] of [
["changed file path", [confirmedSource], [{ ...confirmedSource, filePath: "/tmp/other.conf" }]],
["changed source id", [confirmedSource], [{ ...confirmedSource, id: "replacement" }]],
["added source", [confirmedSource], [confirmedSource, { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" }]],
["first source", [], [confirmedSource]],
["source moved up within selection", [{ ...confirmedSource, groupName: "Production/Sub" }], [confirmedSource]],
["source moved into selection", [{ ...confirmedSource, groupName: "Staging" }], [confirmedSource]],
] as const) {
test(`group deletion rejects initially persisted ${name} before clearing files`, async () => {
let clearCount = 0;
let commitCount = 0;
let reportedCount = 0;
await withDeletionProbe({
managedSources: [...rendered],
onReadPersistedManagedSources: () => [...persisted],
onClearAndRemoveManagedSources: async () => {
clearCount += 1;
return async () => {};
},
onCommitVaultGroupMutation: async () => {
commitCount += 1;
throw new Error("unexpected commit");
},
onDeletedPaths: () => { reportedCount += 1; },
}, async (getDelete) => {
// A failed attempt refreshes latestRef without refreshing the warning.
for (let attempt = 0; attempt < 2; attempt += 1) {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
}
});
assert.equal(clearCount, 0);
assert.equal(commitCount, 0);
assert.equal(reportedCount, 0);
});
}
test("group deletion keeps old callbacks bound to their rendered confirmation", async () => {
const changed = { ...confirmedSource, filePath: "/tmp/changed.conf" };
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => [changed],
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => {};
},
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [], managedSources: [changed], snippets: [],
}),
}, async (getDelete, rerender) => {
const staleDelete = getDelete();
await rerender([changed]);
assert.notEqual(getDelete(), staleDelete);
await assert.rejects(staleDelete(["Production"]), VaultGroupDeletionConfirmationChangedError);
assert.deepEqual(cleared, []);
await getDelete()(["Production"]);
});
assert.deepEqual(cleared, [changed.filePath]);
});
for (const retry of ["snapshot", "commit", "superseded"] as const) {
test(`group deletion retains safe ${retry} retries for the same confirmed file`, async () => {
const updated = { ...confirmedSource, lastSyncedAt: 2 };
let reads = 0;
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => {
reads += 1;
return [retry === "snapshot" && reads > 1 ? updated : confirmedSource];
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
if (retry === "superseded" && commits === 1) return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [],
managedSources: [retry === "snapshot" || (retry === "commit" && commits === 1) ? updated : confirmedSource],
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => { await getDelete()(["Production"]); });
assert.deepEqual(cleared, [confirmedSource.filePath, confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, retry === "snapshot" ? 1 : 2);
assert.equal(reported, 1);
});
}
for (const retry of ["commit", "superseded"] as const) {
test(`group deletion rejects new files after a ${retry} retry`, async () => {
const added = { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" };
let persisted = [confirmedSource];
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => persisted,
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource, added];
if (retry === "superseded") return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [], managedSources: persisted,
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, [confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, 1);
assert.equal(reported, 0);
});
}
for (const phase of ["snapshot", "commit"] as const) {
test(`group deletion rejects a managed subgroup moved to its parent during ${phase}`, async () => {
const subgroup = { ...confirmedSource, groupName: "Production/Sub" };
let persisted = [subgroup];
let reads = 0;
let restores = 0;
let commits = 0;
const cleared: string[] = [];
await withDeletionProbe({
managedSources: [subgroup],
onReadPersistedManagedSources: () => {
if (phase === "snapshot" && ++reads > 1) persisted = [confirmedSource];
return persisted;
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.groupName));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource];
return mutate({
groups: ["Production", "Production/Sub"], configs: [], hosts: [],
managedSources: persisted, snippets: [],
});
},
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, ["Production/Sub"]);
assert.equal(restores, 1);
assert.equal(commits, phase === "snapshot" ? 0 : 1);
});
}
@@ -14,6 +14,17 @@ import {
const RETRY_VAULT_GROUP_DELETION = Symbol("retry-vault-group-deletion");
export class VaultGroupDeletionConfirmationChangedError extends Error {
constructor() {
super("The managed files affected by this deletion have changed. Review the files and confirm again.");
this.name = "VaultGroupDeletionConfirmationChangedError";
}
}
const managedSourceDeletionIdentity = (source: ManagedSource): string => (
JSON.stringify([source.id, source.type, source.filePath, source.groupName])
);
const managedSourceSnapshotsMatch = (
left: ManagedSource[],
right: ManagedSource[],
@@ -59,6 +70,14 @@ export function useVaultGroupDeletion({
additionallyDeletedHostIds: ReadonlySet<string> = new Set(),
) => {
const selectedPaths = [...paths];
// Bind confirmation to the sources rendered with this callback, not the
// latest persisted snapshot (which reads and retries update independently).
const confirmedFiles = new Set(buildVaultGroupDeletion({
...latestRef.current,
selectedPaths,
deleteHosts,
managedSources,
}).sourcesToRemove.map(managedSourceDeletionIdentity));
let deletedRoots: string[] = [];
while (true) {
let restoreManagedFiles: (() => Promise<void>) | undefined;
@@ -82,6 +101,12 @@ export function useVaultGroupDeletion({
return { status: "empty" as const };
}
if (deletion.sourcesToRemove.some((source) => (
!confirmedFiles.has(managedSourceDeletionIdentity(source))
))) {
throw new VaultGroupDeletionConfirmationChangedError();
}
if (deletion.sourcesToRemove.length > 0) {
if (onClearAndRemoveManagedSources) {
restoreManagedFiles = await onClearAndRemoveManagedSources(deletion.sourcesToRemove);
@@ -194,6 +219,7 @@ export function useVaultGroupDeletion({
}
onDeletedPaths?.(deletedRoots);
}, [
managedSources,
onClearAndRemoveManagedSource,
onClearAndRemoveManagedSources,
onCommitVaultGroupMutation,
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import {
collectSidePanelPanes,
createSidePanelLayout,
splitSidePanelPane,
type SidePanelLayout,
} from '../../domain/sidePanelLayout.ts';
import { STORAGE_KEY_WORKSPACE_LAYOUT_PRESET } from '../../infrastructure/config/storageKeys.ts';
import { useWorkspaceLayoutPresetState } from './useWorkspaceLayoutPresetState.ts';
function buildSplitLayout(): SidePanelLayout {
let layout = createSidePanelLayout('scripts', 'pane-scripts');
layout = splitSidePanelPane(layout, 'pane-scripts', 'sftp', 'horizontal', {
paneId: 'pane-sftp',
splitId: 'split-root',
}, 400);
return layout;
}
test('saved default resolves per session with fresh ids and protocol-aware pruning', async () => {
const values = new Map<string, string>();
const fakeStorage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => { values.set(key, value); },
removeItem: (key: string) => { values.delete(key); },
};
const globals = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
localStorage?: typeof fakeStorage;
};
const previousActEnvironment = globals.IS_REACT_ACT_ENVIRONMENT;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
globals.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(globalThis, 'localStorage', {
value: fakeStorage,
configurable: true,
});
let state: ReturnType<typeof useWorkspaceLayoutPresetState> | null = null;
const Probe = () => {
state = useWorkspaceLayoutPresetState();
return null;
};
try {
await act(async () => {
create(React.createElement(Probe));
});
assert.ok(state);
// Nothing saved yet: no preset to apply.
assert.equal(state.resolveDefaultLayoutForSession({ protocol: 'ssh' }), null);
let saved = false;
await act(async () => {
saved = state?.saveWorkspaceLayoutAsDefault(buildSplitLayout()) ?? false;
});
assert.equal(saved, true);
assert.ok(values.has(STORAGE_KEY_WORKSPACE_LAYOUT_PRESET));
// SSH sessions keep their SFTP pane; ids are rekeyed per application.
const sshResolved = state.resolveDefaultLayoutForSession({ protocol: 'ssh' });
assert.ok(sshResolved);
assert.equal(sshResolved.protocol, 'ssh');
assert.deepEqual(
collectSidePanelPanes(sshResolved.layout.root).map((pane) => pane.tool),
['scripts', 'sftp'],
);
assert.notEqual(sshResolved.layout.root.id, buildSplitLayout().root.id);
assert.equal(sshResolved.focusedTool, 'sftp');
// Protocols that cannot serve SFTP lose that pane.
const telnetResolved = state.resolveDefaultLayoutForSession({ protocol: 'telnet' });
assert.ok(telnetResolved);
assert.deepEqual(
collectSidePanelPanes(telnetResolved.layout.root).map((pane) => pane.tool),
['scripts'],
);
assert.equal(telnetResolved.focusedTool, 'scripts');
// A second resolve rekeys again so parallel workspaces share no node ids.
const again = state.resolveDefaultLayoutForSession({ protocol: 'ssh' });
assert.ok(again);
assert.notEqual(again.layout.root.id, sshResolved.layout.root.id);
} finally {
if (previousLocalStorage) {
Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
} else {
delete (globalThis as { localStorage?: unknown }).localStorage;
}
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
});
test('saving falls back to false when persistence rejects the write', async () => {
const fakeStorage = {
getItem: () => null,
setItem: () => {
const quotaError = new DOMException('full', 'QuotaExceededError');
throw quotaError;
},
removeItem: () => undefined,
};
const globals = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
localStorage?: typeof fakeStorage;
};
const previousActEnvironment = globals.IS_REACT_ACT_ENVIRONMENT;
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
globals.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(globalThis, 'localStorage', {
value: fakeStorage,
configurable: true,
});
let state: ReturnType<typeof useWorkspaceLayoutPresetState> | null = null;
const Probe = () => {
state = useWorkspaceLayoutPresetState();
return null;
};
try {
await act(async () => {
create(React.createElement(Probe));
});
assert.ok(state);
let saved = true;
await act(async () => {
saved = state?.saveWorkspaceLayoutAsDefault(buildSplitLayout()) ?? true;
});
assert.equal(saved, false);
} finally {
if (previousLocalStorage) {
Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
} else {
delete (globalThis as { localStorage?: unknown }).localStorage;
}
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
});
@@ -0,0 +1,69 @@
import { useCallback } from 'react';
import {
getFocusedSidePanelPane,
type SidePanelLayout,
type SidePanelTool,
} from '../../domain/sidePanelLayout';
import {
createWorkspaceLayoutPreset,
rekeySidePanelLayout,
withoutUnavailableSidePanelTools,
} from '../../domain/workspaceLayoutPreset';
import {
readWorkspaceLayoutPreset,
writeWorkspaceLayoutPreset,
} from './workspaceLayoutPresetStore';
/** Protocols whose sessions can actually serve an SFTP pane. */
function canServeSftp(protocol: string): boolean {
return protocol === 'local' || protocol === 'ssh' || protocol === 'mosh';
}
export type ResolvedWorkspaceLayoutPreset = {
layout: SidePanelLayout;
focusedTool: SidePanelTool;
/** Connection protocol used for availability filtering (`session.protocol ?? 'ssh'`). */
protocol: string;
};
/**
* Application boundary for the saved default workspace side panel layout.
* Owns the preset persistence lifecycle (read, validate, write) so UI
* components consume handlers instead of touching the store directly.
*/
export function useWorkspaceLayoutPresetState() {
/**
* Resolve the saved default preset into a fresh layout for a newly
* connected session. Panes the session cannot serve (SFTP on non-file
* protocols) are pruned, and ids are rekeyed so several workspaces can
* run the same preset in parallel. Returns null when there is no preset
* or nothing survives availability filtering.
*/
const resolveDefaultLayoutForSession = useCallback(
(session: { protocol?: string | null }): ResolvedWorkspaceLayoutPreset | null => {
const preset = readWorkspaceLayoutPreset();
if (!preset) return null;
const proto = session.protocol ?? 'ssh';
const usable = withoutUnavailableSidePanelTools(
preset.layout,
(tool) => tool !== 'sftp' || canServeSftp(proto),
);
if (!usable) return null;
const layout = rekeySidePanelLayout(usable, () => crypto.randomUUID());
return { layout, focusedTool: getFocusedSidePanelPane(layout).tool, protocol: proto };
},
[],
);
/** Validate and persist a live layout as the default. False when invalid or the write failed. */
const saveWorkspaceLayoutAsDefault = useCallback((layout: SidePanelLayout): boolean => {
const preset = createWorkspaceLayoutPreset(layout);
if (!preset) return false;
return writeWorkspaceLayoutPreset(preset);
}, []);
return { resolveDefaultLayoutForSession, saveWorkspaceLayoutAsDefault };
}
@@ -0,0 +1,18 @@
import { STORAGE_KEY_WORKSPACE_LAYOUT_PRESET } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
sanitizeWorkspaceLayoutPreset,
type WorkspaceLayoutPreset,
} from '../../domain/workspaceLayoutPreset';
/**
* Saved default workspace side panel layout. Device-local only: it is not
* part of the sync payload because pane arrangements are client-side chrome.
*/
export function readWorkspaceLayoutPreset(): WorkspaceLayoutPreset | null {
return sanitizeWorkspaceLayoutPreset(localStorageAdapter.read(STORAGE_KEY_WORKSPACE_LAYOUT_PRESET));
}
export function writeWorkspaceLayoutPreset(preset: WorkspaceLayoutPreset): boolean {
return localStorageAdapter.write(STORAGE_KEY_WORKSPACE_LAYOUT_PRESET, preset);
}
+37
View File
@@ -1964,6 +1964,43 @@ test("applySyncPayload applies pluginSidecars through the production applier hoo
assert.equal((applied as SyncPayload["pluginSidecars"])?.entries[0].value.clock, 3);
});
test("local shell side panel settings round-trip independently and trigger auto-sync", async () => {
for (const key of [storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB]) {
assert.ok((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key));
}
for (const enabled of [true, false]) {
localStorage.clear();
localStorage.setItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, String(enabled));
localStorage.setItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, "notes");
localStorage.setItem(storageKeys.STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, String(!enabled));
localStorage.setItem(storageKeys.STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB, "scripts");
const payload = await buildSyncPayload(vault());
assert.equal(payload.settings?.localShellSidePanelAutoOpen, enabled);
assert.equal(payload.settings?.localShellSidePanelAutoOpenTab, "notes");
localStorage.clear();
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN), String(enabled));
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB), "notes");
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN), String(!enabled));
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB), "scripts");
}
});
test("missing local shell settings and invalid tabs preserve existing settings", async () => {
const payload = await buildSyncPayload(vault());
assert.equal(payload.settings?.localShellSidePanelAutoOpen, undefined);
assert.equal(payload.settings?.localShellSidePanelAutoOpenTab, undefined);
localStorage.setItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, "true");
localStorage.setItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, "notes");
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN), "true");
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB), "notes");
await applySyncPayload({ ...payload, settings: { localShellSidePanelAutoOpenTab: "invalid" } } as unknown as SyncPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB), "notes");
localStorage.setItem(storageKeys.STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, "invalid");
assert.equal((await buildSyncPayload(vault())).settings?.localShellSidePanelAutoOpenTab, undefined);
});
test("tab bar position survives settings export and import, with a safe fallback", async () => {
localStorage.clear();
localStorage.setItem(storageKeys.STORAGE_KEY_TAB_BAR_POSITION, "bottom");
+17
View File
@@ -78,6 +78,8 @@ import {
STORAGE_KEY_TERM_SETTINGS,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
STORAGE_KEY_EDITOR_WORD_WRAP,
STORAGE_KEY_SFTP_DOUBLE_CLICK_BEHAVIOR,
@@ -266,6 +268,7 @@ const SYNCABLE_TERMINAL_KEYS = [
'linkModifier', 'keywordHighlightEnabled', 'keywordHighlightRules',
'keepaliveInterval', 'keepaliveCountMax', 'disableBracketedPaste', 'clearWipesScrollback',
'autoUploadClipboardImageOnPaste',
'confirmBeforeMultilinePaste', 'multilinePasteConfirmMinLines',
'preserveSelectionOnInput', 'forcePromptNewLine', 'osc52Clipboard', 'oscNotifications', 'dynamicTabTitleMode', 'tabDoubleClickBehavior',
'autoCloseOnExit', 'disconnectedNoticeMode',
'showHostInfoBar', 'hostInfoBarTitleMode', 'showServerStats',
@@ -302,6 +305,8 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [
STORAGE_KEY_TERM_SETTINGS,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_CUSTOM_THEMES,
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
STORAGE_KEY_EDITOR_WORD_WRAP,
@@ -481,6 +486,12 @@ export function collectSyncableSettings(): SyncPayload['settings'] {
if (isTerminalSidePanelAutoOpenTab(terminalSidePanelAutoOpenTab)) {
settings.terminalSidePanelAutoOpenTab = terminalSidePanelAutoOpenTab;
}
const localShellSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN);
if (localShellSidePanelAutoOpen != null) settings.localShellSidePanelAutoOpen = localShellSidePanelAutoOpen;
const localShellSidePanelAutoOpenTab = localStorageAdapter.readString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB);
if (isTerminalSidePanelAutoOpenTab(localShellSidePanelAutoOpenTab)) {
settings.localShellSidePanelAutoOpenTab = localShellSidePanelAutoOpenTab;
}
// Terminal settings (syncable subset only)
const termSettingsRaw = localStorageAdapter.readString(STORAGE_KEY_TERM_SETTINGS);
@@ -732,6 +743,12 @@ async function applySyncableSettings(
if (isTerminalSidePanelAutoOpenTab(settings.terminalSidePanelAutoOpenTab)) {
localStorageAdapter.writeString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB, settings.terminalSidePanelAutoOpenTab);
}
if (settings.localShellSidePanelAutoOpen != null) {
localStorageAdapter.writeBoolean(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN, settings.localShellSidePanelAutoOpen);
}
if (isTerminalSidePanelAutoOpenTab(settings.localShellSidePanelAutoOpenTab)) {
localStorageAdapter.writeString(STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB, settings.localShellSidePanelAutoOpenTab);
}
// Terminal settings - merge with existing to preserve platform-specific keys
if (settings.terminalSettings) {
+5 -4
View File
@@ -16,6 +16,7 @@ import { formatHostPort } from "../domain/host";
import {
buildQuickConnectHost,
getQuickConnectDefaultPort,
isQuickConnectIdentityCompatible,
isQuickConnectIdentityUsable,
type QuickConnectAuthMethod,
type QuickConnectProtocol,
@@ -104,13 +105,13 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
[keys, protocol, selectedIdentity],
);
const identityOptions = useMemo(
() => identities.map((identity) => ({
() => identities.filter((identity) => isQuickConnectIdentityCompatible(identity, target)).map((identity) => ({
value: identity.id,
label: identity.label,
sublabel: identity.username,
icon: <User size={14} />,
})),
[identities],
[identities, target],
);
const detachSelectedIdentity = () => {
@@ -131,7 +132,7 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
return;
}
const identity = identities.find((candidate) => candidate.id === identityId);
if (!identity) return;
if (!identity || !isQuickConnectIdentityCompatible(identity, target)) return;
setSelectedIdentityId(identity.id);
setUsername(identity.username);
setAuthMethod(identity.authMethod);
@@ -431,7 +432,7 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
</div>
</div>
{protocol !== "telnet" && identities.length > 0 && (
{protocol !== "telnet" && identityOptions.length > 0 && (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-3">
<Label className="text-sm font-medium">{t("quickConnect.identity.label")}</Label>
+80 -1
View File
@@ -2,7 +2,7 @@
* Serial Host Details Panel
* A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel)
*/
import { ChevronDown, ChevronUp, Save, Tag, Usb } from 'lucide-react';
import { ChevronDown, ChevronUp, Eye, EyeOff, Save, Tag, Usb, X } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import { useTerminalBackend } from '../application/state/useTerminalBackend';
@@ -75,9 +75,22 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
const [ports, setPorts] = useState<SerialPort[]>([]);
const [isLoadingPorts, setIsLoadingPorts] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
const [showPassword, setShowPassword] = useState(false);
// Form state
const [label, setLabel] = useState(initialData.label);
const [username, setUsername] = useState(initialData.username || '');
const [password, setPassword] = useState(initialData.password || '');
// Tracks whether the user edited the password field this session. An empty
// password is a meaningful serial credential (the auto-login detector
// submits a blank line at a Password prompt), so an explicit edit to blank
// must be saved as '' while an untouched field preserves the stored value.
const [passwordChanged, setPasswordChanged] = useState(false);
// Explicit "remove the saved credential" flag. An empty password field is a
// meaningful serial credential (a present blank password), so blanking the
// input alone cannot restore `password` to undefined — the user needs a
// dedicated control to delete the credential entirely.
const [passwordCleared, setPasswordCleared] = useState(false);
const [selectedPort, setSelectedPort] = useState(initialData.hostname || initialData.serialConfig?.path || '');
const [baudRate, setBaudRate] = useState(initialData.serialConfig?.baudRate || initialData.port || 115200);
const [dataBits, setDataBits] = useState<5 | 6 | 7 | 8>(initialData.serialConfig?.dataBits || 8);
@@ -140,6 +153,16 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
label: label.trim() || `Serial: ${portName}`,
hostname: selectedPort,
port: baudRate,
username: username.trim() || undefined,
// An empty password is meaningful for serial auto-login: the detector
// distinguishes an absent password from a present empty string and
// submits the required blank line at a Password prompt. An explicit edit
// saves exactly what the user typed (including a blank line); the
// dedicated clear control removes the credential entirely (undefined);
// an untouched field preserves the stored credential as-is.
password: passwordChanged
? (passwordCleared ? undefined : password)
: (initialData.password ?? undefined),
tags,
group,
charset,
@@ -276,6 +299,62 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
)}
</div>
{/* Login credentials (auto-login) */}
<div className="space-y-2">
<Label htmlFor="serial-username">{t('serial.field.username')}</Label>
<Input
id="serial-username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder={t('serial.field.username')}
autoComplete="off"
/>
<div className="relative">
<Input
id="serial-password"
value={password}
type={showPassword ? 'text' : 'password'}
onChange={(e) => {
setPassword(e.target.value);
setPasswordChanged(true);
if (e.target.value !== '') {
setPasswordCleared(false);
}
}}
placeholder={t('serial.field.password')}
autoComplete="off"
className="pr-16"
/>
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5">
{(initialData.password !== undefined || password !== '') && (
<button
type="button"
onClick={() => {
setPassword('');
setPasswordChanged(true);
setPasswordCleared(true);
}}
title={t('serial.field.clearPassword')}
aria-label={t('serial.field.clearPassword')}
className="p-1 text-muted-foreground hover:text-foreground transition-colors"
>
<X size={14} />
</button>
)}
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="p-1 text-muted-foreground hover:text-foreground transition-colors"
>
{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</div>
<p className="text-xs text-muted-foreground">
{t('serial.field.autoLoginDesc')}
</p>
</div>
{/* Tags */}
<div className="space-y-2">
<Label className="flex items-center gap-2">
+16
View File
@@ -135,6 +135,10 @@ type TerminalTabSettingsProps = Pick<
| 'setTerminalSidePanelAutoOpen'
| 'terminalSidePanelAutoOpenTab'
| 'setTerminalSidePanelAutoOpenTab'
| 'localShellSidePanelAutoOpen'
| 'setLocalShellSidePanelAutoOpen'
| 'localShellSidePanelAutoOpenTab'
| 'setLocalShellSidePanelAutoOpenTab'
| 'workspaceFocusStyle'
| 'setWorkspaceFocusStyle'
>;
@@ -161,6 +165,10 @@ const SettingsTerminalTabContainer = React.memo<TerminalTabSettingsProps>(functi
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
setTerminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
setLocalShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
setLocalShellSidePanelAutoOpenTab,
workspaceFocusStyle,
setWorkspaceFocusStyle,
}) {
@@ -189,6 +197,10 @@ const SettingsTerminalTabContainer = React.memo<TerminalTabSettingsProps>(functi
setTerminalSidePanelAutoOpen={setTerminalSidePanelAutoOpen}
terminalSidePanelAutoOpenTab={terminalSidePanelAutoOpenTab}
setTerminalSidePanelAutoOpenTab={setTerminalSidePanelAutoOpenTab}
localShellSidePanelAutoOpen={localShellSidePanelAutoOpen}
setLocalShellSidePanelAutoOpen={setLocalShellSidePanelAutoOpen}
localShellSidePanelAutoOpenTab={localShellSidePanelAutoOpenTab}
setLocalShellSidePanelAutoOpenTab={setLocalShellSidePanelAutoOpenTab}
availableFonts={availableFonts}
workspaceFocusStyle={workspaceFocusStyle}
setWorkspaceFocusStyle={setWorkspaceFocusStyle}
@@ -583,6 +595,10 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
setTerminalSidePanelAutoOpen={settings.setTerminalSidePanelAutoOpen}
terminalSidePanelAutoOpenTab={settings.terminalSidePanelAutoOpenTab}
setTerminalSidePanelAutoOpenTab={settings.setTerminalSidePanelAutoOpenTab}
localShellSidePanelAutoOpen={settings.localShellSidePanelAutoOpen}
setLocalShellSidePanelAutoOpen={settings.setLocalShellSidePanelAutoOpen}
localShellSidePanelAutoOpenTab={settings.localShellSidePanelAutoOpenTab}
setLocalShellSidePanelAutoOpenTab={settings.setLocalShellSidePanelAutoOpenTab}
workspaceFocusStyle={settings.workspaceFocusStyle}
setWorkspaceFocusStyle={settings.setWorkspaceFocusStyle}
/>
+5
View File
@@ -347,6 +347,7 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
listLocalDir,
listDrives,
openPath,
statSftp,
} = useSftpBackend();
const sftpRef = useRef(sftp);
@@ -1337,6 +1338,7 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
selectDirectory={selectDirectory}
listLocalDir={listLocalDir}
listDrives={listDrives}
statSftp={statSftp}
openPath={openPath}
t={t}
/>
@@ -1389,6 +1391,7 @@ type SftpSidePanelInteractiveBodyProps = {
selectDirectory: ReturnType<typeof useSftpBackend>["selectDirectory"];
listLocalDir: ReturnType<typeof useSftpBackend>["listLocalDir"];
listDrives: ReturnType<typeof useSftpBackend>["listDrives"];
statSftp: ReturnType<typeof useSftpBackend>["statSftp"];
openPath: ReturnType<typeof useSftpBackend>["openPath"];
t: ReturnType<typeof useI18n>["t"];
};
@@ -1431,6 +1434,7 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
selectDirectory,
listLocalDir,
listDrives,
statSftp,
openPath,
t,
}) => {
@@ -1540,6 +1544,7 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
showSaveDialog,
selectDirectory,
getSftpIdForConnection: sftp.getSftpIdForConnection,
statSftp,
listLocalFiles: listLocalDir,
listDrives,
});
+2
View File
@@ -193,6 +193,7 @@ const SftpViewInner: React.FC<SftpViewProps> = ({
listLocalDir,
listDrives,
openPath,
statSftp,
} = useSftpBackend();
// Store sftp in a ref so callbacks can access the latest instance
@@ -424,6 +425,7 @@ const SftpViewInner: React.FC<SftpViewProps> = ({
showSaveDialog,
selectDirectory,
getSftpIdForConnection: sftp.getSftpIdForConnection,
statSftp,
listLocalFiles: listLocalDir,
listDrives,
});
+30 -3
View File
@@ -1,3 +1,4 @@
import { clearTerminalBroadcastUserInput, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast";
import { publishTerminalCommandCompletion } from "../application/state/terminalCommandCompletion";
import { createTerminalReflowReadingPosition } from "./terminal/terminalReflowReadingPosition";
import { resolveHostOs } from '../domain/host';
@@ -52,6 +53,7 @@ import { CONNECTION_PROGRESS_START } from "./terminal/connectionProgress";
import { supportsZmodemTerminalDragDrop } from "../lib/zmodemDragDrop";
import { resolveHostAuth, resolveHostAutofillPassword } from "../domain/sshAuth";
import { resolveEffectiveTerminalProtocol } from "../domain/terminalProtocol";
import { MULTILINE_PASTE_CONFIRM_MIN_LINES_DEFAULT } from "../domain/terminalPasteConfirm";
import { isPluginHostProtocol } from "../domain/pluginConnection";
import { clearTerminalBootEpoch, setTerminalBootEpoch } from "../domain/terminalBootEpoch";
import {
@@ -434,6 +436,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
sessionId,
() => passwordPromptActiveRef.current,
), [sessionId]);
useEffect(() => () => clearTerminalBroadcastUserInput(sessionId), [sessionId]);
const sensitivePromptOutputTailRef = useRef("");
const [activeScriptRun, setActiveScriptRun] = useState<import('@/types/global/netcatty-bridge-script.d.ts').ScriptRun | undefined>(undefined);
const dismissedScriptRunIdsRef = useRef(new Set<string>());
@@ -998,6 +1001,10 @@ const TerminalComponent: React.FC<TerminalProps> = ({
autocompleteAcceptTextRef.current = (text: string) => {
const id = sessionRef.current;
if (id && text) {
markTerminalBroadcastUserInput(sessionId);
if (["\r", "\n", "\b", "\x7f", "\x15"].some(control => text.includes(control))) {
xtermRuntimeRef.current?.invalidatePendingPasteDraft();
}
const sensitive = passwordPromptActiveRef.current;
let textToWrite = text;
let handledSubmittedInput = false;
@@ -1953,7 +1960,12 @@ const TerminalComponent: React.FC<TerminalProps> = ({
sensitivePromptOutputTailRef.current,
chunk,
);
const promptSecurityOptions = { allowHostStyleGreaterThan: isNetworkDevice };
const promptSecurityOptions = {
allowHostStyleGreaterThan: isNetworkDevice,
alternateScreen: termRef.current
? isTerminalAlternateScreenActive(termRef.current)
: false,
};
if (typeof meta?.pluginPipelineSensitiveInput === "boolean") {
passwordPromptActiveRef.current = meta.pluginPipelineSensitiveInput;
if (meta.pluginPipelineSensitiveInput) {
@@ -3216,6 +3228,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
normalizeTextOnCopyRef.current = terminalSettings?.normalizeTextOnCopy ?? true;
const autoUploadClipboardImageOnPasteRef = useRef(terminalSettings?.autoUploadClipboardImageOnPaste ?? false);
autoUploadClipboardImageOnPasteRef.current = terminalSettings?.autoUploadClipboardImageOnPaste ?? false;
const multilinePasteConfirmRef = useRef({
enabled: terminalSettings?.confirmBeforeMultilinePaste ?? false,
minLines: terminalSettings?.multilinePasteConfirmMinLines ?? MULTILINE_PASTE_CONFIRM_MIN_LINES_DEFAULT,
});
multilinePasteConfirmRef.current = {
enabled: terminalSettings?.confirmBeforeMultilinePaste ?? false,
minLines: terminalSettings?.multilinePasteConfirmMinLines ?? MULTILINE_PASTE_CONFIRM_MIN_LINES_DEFAULT,
};
const scrollToBottomAfterProgrammaticInput = useCallback((data: string) => {
if (!termRef.current) return;
@@ -3240,14 +3260,17 @@ const TerminalComponent: React.FC<TerminalProps> = ({
termRef.current?.scrollToBottom();
}, [activeScriptRun]);
const broadcastUserPasteData = useCallback((data: string) => {
const broadcastUserPasteData = useCallback((
data: string,
options?: { lineDelayMs?: number },
) => {
if (
!passwordPromptActiveRef.current
&& sessionRef.current
&& isBroadcastEnabledRef.current
&& onBroadcastInputRef.current
) {
onBroadcastInputRef.current(data, sessionId);
onBroadcastInputRef.current(data, sessionId, options);
return true;
}
return false;
@@ -3299,6 +3322,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
? AUTO_RUN_SNIPPET_LINE_DELAY_MS
: undefined;
const isMultiLine = data.includes('\n');
if (lineDelayMs) markTerminalBroadcastUserInput(sessionId);
// Wrap in bracketed paste BEFORE appending \r so the Enter is sent
// outside the paste markers — otherwise shells treat it as pasted text
// instead of a submit action.
@@ -3317,6 +3341,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const sensitive = passwordPromptActiveRef.current;
if (!sensitive && options?.broadcast !== false && isBroadcastEnabledRef.current && onBroadcastInputRef.current) {
onBroadcastInputRef.current(data, sessionId, {
automated: true,
noAutoRun,
...(lineDelayMs ? { lineDelayMs } : {}),
});
@@ -3391,6 +3416,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
isLocalConnection,
supportsRemoteImagePaste,
autoUploadClipboardImageOnPasteRef,
multilinePasteConfirmRef,
terminalBackend,
getRemoteCwd: () => resolveSftpInitialPath({ preferFreshBackend: true }),
scrollToBottomAfterProgrammaticInput,
@@ -3972,6 +3998,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
containerRef,
autoUploadClipboardImage:
supportsRemoteImagePaste && terminalSettings?.autoUploadClipboardImageOnPaste === true,
multilinePasteConfirmRef,
getRemoteCwd: () => resolveSftpInitialPath({ preferFreshBackend: true }),
onClipboardImageUploadResult: handleClipboardImageUploadResult,
});
+5
View File
@@ -306,3 +306,8 @@ test("TerminalLayer re-renders when terminalFontFamilyId changes", () => {
false,
);
});
test("local shell auto-open preferences invalidate terminal layer memo", () => {
assert.equal(terminalLayerAreEqual(baseProps as never, { ...baseProps, localShellSidePanelAutoOpen: true } as never), false);
assert.equal(terminalLayerAreEqual(baseProps as never, { ...baseProps, localShellSidePanelAutoOpenTab: "sftp" } as never), false);
});
+159 -24
View File
@@ -1,3 +1,4 @@
import { captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast";
import { pruneComposeBarHistory } from '../application/state/composeBarHistoryStore';
import { FolderTree, History, MessageSquare, PanelLeft, PanelRight, Palette, X, Zap } from 'lucide-react';
import React, { memo, startTransition, useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -105,7 +106,7 @@ import {
} from './terminalLayer/terminalLayerSessionRouting';
import {
DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
resolveTerminalSidePanelAutoOpen,
resolveSessionSidePanelAutoOpen,
} from '../domain/terminalSidePanelAutoOpen';
import { shouldProbeCommandCwd } from './terminalLayer/commandCwdProbe';
import {
@@ -118,8 +119,10 @@ import { classifyDistroId, shouldProbeSessionCwd } from '../domain/host';
import {
collectSidePanelPanes,
sidePanelLayoutHasTool,
type SidePanelLayout,
type SidePanelSplitDirection,
} from '../domain/sidePanelLayout';
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
import {
isPaneMagnificationSelectionValid,
resolvePaneMagnificationCandidate,
@@ -262,6 +265,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
sftpAutoOpenSidebar,
terminalSidePanelAutoOpen = false,
terminalSidePanelAutoOpenTab = DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
localShellSidePanelAutoOpen = false,
localShellSidePanelAutoOpenTab = 'scripts',
sftpFollowTerminalCwd,
setSftpFollowTerminalCwd,
editorWordWrap,
@@ -445,9 +450,101 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
terminalSidePanelAutoOpenRef.current = terminalSidePanelAutoOpen;
const terminalSidePanelAutoOpenTabRef = useRef(terminalSidePanelAutoOpenTab);
terminalSidePanelAutoOpenTabRef.current = terminalSidePanelAutoOpenTab;
const localShellSidePanelAutoOpenRef = useRef(localShellSidePanelAutoOpen);
localShellSidePanelAutoOpenRef.current = localShellSidePanelAutoOpen;
const localShellSidePanelAutoOpenTabRef = useRef(localShellSidePanelAutoOpenTab);
localShellSidePanelAutoOpenTabRef.current = localShellSidePanelAutoOpenTab;
const sftpFollowTerminalCwdRef = useRef(sftpFollowTerminalCwd);
sftpFollowTerminalCwdRef.current = sftpFollowTerminalCwd;
// Destructure the stable hook callbacks: the hook returns a fresh object
// each render, and depending on that object would recreate the preset
// callbacks (and in turn handleStatusChange) on unrelated state updates,
// defeating the terminal pane memoization.
const { resolveDefaultLayoutForSession, saveWorkspaceLayoutAsDefault: persistWorkspaceLayoutAsDefault } =
useWorkspaceLayoutPresetState();
const applyWorkspaceLayoutPresetForSession = useCallback((session: TerminalSession, tabId: string) => {
// Preset persistence and resolution live in the application layer; the
// component only mounts the resolved panes into its UI state.
const resolved = resolveDefaultLayoutForSession(session);
if (!resolved) return false;
const { layout, focusedTool, protocol: proto } = resolved;
for (const pane of collectSidePanelPanes(layout.root)) {
if (pane.tool === 'ai') {
setAiMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId));
} else if (pane.tool === 'scripts') {
setScriptsMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId));
} else if (pane.tool === 'theme') {
setThemeMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId));
} else if (pane.tool === 'system') {
setSystemMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId));
} else if (pane.tool === 'notes') {
setNotesMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId));
} else if (pane.tool === 'sftp') {
// Mirror the normal SFTP open path: a previously retained panel (kept
// mounted while transfers or external edits finished after close) must
// not keep suppressing command-triggered refreshes once the preset
// reopens SFTP for this tab. Mark the tab as opening first so an
// activity callback firing before React commits the open state still
// sees the panel as open instead of pruning the retained host state.
const cleanupTimer = sftpRetainedCleanupTimersRef.current.get(tabId);
if (cleanupTimer !== undefined) {
window.clearTimeout(cleanupTimer);
sftpRetainedCleanupTimersRef.current.delete(tabId);
}
sftpOpeningTabIdsRef.current.add(tabId);
sftpRetainedAfterCloseTabIdsRef.current.delete(tabId);
sftpPaneClosedTabIdsRef.current.delete(tabId);
const host = hostsRef.current.find(h => h.id === session.hostId);
const hostWithOverrides: Host = host
? {
...host,
protocol: session.protocol ?? host.protocol,
port: session.port ?? host.port,
moshEnabled: session.moshEnabled ?? host.moshEnabled,
etEnabled: session.etEnabled ?? host.etEnabled,
}
: {
id: session.hostId || session.id,
hostname: session.hostname,
username: session.username,
port: session.port ?? 22,
protocol: proto,
label: session.customName || session.hostLabel || session.hostname,
} as Host;
setSftpHostForTab(prev => {
const next = new Map(prev);
next.set(tabId, hostWithOverrides);
return next;
});
}
}
setSidePanelLayouts((prev) => {
const next = new Map(prev);
next.set(tabId, layout);
return next;
});
lastSidePanelTabRef.current.set(tabId, focusedTool);
setSidePanelOpenTabs(prev => {
const next = new Map(prev);
next.set(tabId, focusedTool);
return next;
});
return true;
}, [resolveDefaultLayoutForSession, setSidePanelLayouts, setSidePanelOpenTabs]);
const handleSaveWorkspaceLayoutAsDefault = useCallback((layout: SidePanelLayout): boolean => {
if (!persistWorkspaceLayoutAsDefault(layout)) {
toast.error(t('terminal.layer.layoutSaveFailed'));
return false;
}
toast.success(t('terminal.layer.layoutSavedAsDefault'));
return true;
}, [persistWorkspaceLayoutAsDefault, t]);
const handleStatusChange = useCallback((sessionId: string, status: TerminalSession['status']) => {
onUpdateSessionStatus(sessionId, status);
@@ -455,41 +552,62 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const session = sessionsRef.current.find(s => s.id === sessionId);
if (!session) return;
const proto = session.protocol;
const sftpAvailable = proto === 'ssh' || proto === 'mosh';
const tabId = session.workspaceId || sessionId;
const workspaceId = session.workspaceId;
const tabId = workspaceId || sessionId;
// Within a workspace every member session maps to the same tab id, so the
// preset (and any auto-open host binding) must come from the workspace's
// focused session; otherwise whichever pane connects first would decide
// SFTP pruning and host selection regardless of focus.
let presetSession = session;
if (workspaceId) {
const focusedSessionId = workspacesRef.current.find(ws => ws.id === workspaceId)?.focusedSessionId;
const focusedSession = focusedSessionId
? sessionsRef.current.find(s => s.id === focusedSessionId)
: undefined;
if (focusedSession) presetSession = focusedSession;
}
const proto = presetSession.protocol ?? 'ssh';
if (sidePanelOpenTabsRef.current.has(tabId)) return;
const sessionAutoOpenTarget = session.autoOpenSidePanel === 'sftp' && sftpAvailable ? 'sftp' : null;
const autoOpenTarget = sessionAutoOpenTarget ?? resolveTerminalSidePanelAutoOpen({
enabled: terminalSidePanelAutoOpenRef.current,
selectedTab: terminalSidePanelAutoOpenTabRef.current,
sftpAvailable,
const targetPanel = resolveSessionSidePanelAutoOpen({
session: presetSession,
terminalEnabled: terminalSidePanelAutoOpenRef.current,
terminalTab: terminalSidePanelAutoOpenTabRef.current,
localEnabled: localShellSidePanelAutoOpenRef.current,
localTab: localShellSidePanelAutoOpenTabRef.current,
legacySftpEnabled: sftpAutoOpenSidebarRef.current,
});
const targetPanel = autoOpenTarget ?? (sftpAutoOpenSidebarRef.current && sftpAvailable ? 'sftp' : null);
if (!targetPanel) return;
// Explicit SFTP (JumpServer deep link / host.autoOpenSftpPanel) wins over a
// saved default that may omit file transfer — only when SFTP is actually
// available. Ordinary auto-open still yields to the saved default.
if (targetPanel !== "sftp") {
if (applyWorkspaceLayoutPresetForSession(presetSession, tabId)) return;
if (!targetPanel) return;
}
lastSidePanelTabRef.current.set(tabId, targetPanel);
if (targetPanel === 'sftp') {
sftpPaneClosedTabIdsRef.current.delete(tabId);
const host = hostsRef.current.find(h => h.id === session.hostId);
const host = hostsRef.current.find(h => h.id === presetSession.hostId);
const hostWithOverrides: Host = host
? {
...host,
protocol: session.protocol ?? host.protocol,
port: session.port ?? host.port,
moshEnabled: session.moshEnabled ?? host.moshEnabled,
etEnabled: session.etEnabled ?? host.etEnabled,
protocol: presetSession.protocol ?? host.protocol,
port: presetSession.port ?? host.port,
moshEnabled: presetSession.moshEnabled ?? host.moshEnabled,
etEnabled: presetSession.etEnabled ?? host.etEnabled,
}
: {
id: session.hostId || sessionId,
hostname: session.hostname,
username: session.username,
port: session.port ?? 22,
id: presetSession.hostId || presetSession.id,
hostname: presetSession.hostname,
username: presetSession.username,
port: presetSession.port ?? 22,
protocol: proto,
label: session.label || session.hostname,
label: presetSession.customName || presetSession.hostLabel || presetSession.hostname,
} as Host;
setSftpHostForTab(prev => {
@@ -514,7 +632,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
next.set(tabId, targetPanel);
return next;
});
}, [onUpdateSessionStatus, setSidePanelOpenTabs, sidePanelOpenTabsRef]);
}, [applyWorkspaceLayoutPresetForSession, onUpdateSessionStatus, setSidePanelOpenTabs, sidePanelOpenTabsRef]);
const handleSessionExit = useCallback((sessionId: string, evt: TerminalSessionExitEvent) => {
const intent = resolveTerminalSessionExitIntent(
@@ -1064,12 +1182,26 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
sourceSessionId: string,
options?: TerminalBroadcastInputOptions,
) => {
const paced = options?.pacedBroadcast;
if (paced && !options?.preparePacedBroadcast) {
if (!paced.targets || isTerminalSensitiveInputActive(sourceSessionId)) return [];
paced.targets = paced.targets.filter(target => isTerminalBroadcastInputCurrent(target)
&& !isTerminalSensitiveInputActive(target.sessionId));
}
const targetSessionIds = resolveTerminalBroadcastTargetIds({
sessions: sessionsRef.current,
sourceSessionId,
globalBroadcastEnabled: isGlobalBroadcastEnabled,
directTargetSessionIds: options?.kittyKeyboardTargetSessionIds,
});
}).filter(id => !paced?.targets || paced.targets.some(target => target.sessionId === id));
if (options?.preparePacedBroadcast && paced) {
paced.targets = targetSessionIds.filter(id => !isTerminalSensitiveInputActive(id)).map(id => {
markTerminalBroadcastUserInput(id);
terminalBackend.interruptSession(id, undefined, { cancelPendingWritesOnly: true });
return captureTerminalBroadcastInput(id);
});
return paced.targets.map(target => target.sessionId);
}
if (targetSessionIds.length === 0) return [];
const targetSessionIdSet = new Set(targetSessionIds);
@@ -1078,6 +1210,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
for (const session of sessionsRef.current) {
if (!targetSessionIdSet.has(session.id)) continue;
if (!canUseDirectSessionWriteFallback(session)) continue;
if (!paced && (options?.automated !== true || options.lineDelayMs)) markTerminalBroadcastUserInput(session.id);
if (options?.kittyKeyboardInput) {
dispatchKittyKeyboardBroadcastInput(session.id, options.kittyKeyboardInput, {
@@ -1094,6 +1227,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
&& isPluginHostProtocol(session.protocol)
&& terminalBackend.signalPluginConnection) {
broadcastInterruptPrioritizersRef.current.get(session.id)?.();
terminalBackend.interruptSession(session.id, undefined, { cancelPendingWritesOnly: true });
void terminalBackend.signalPluginConnection(session.id, "interrupt").catch(() => {
terminalBackend.interruptSession(session.id);
});
@@ -1107,7 +1241,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}
if (isTerminalSensitiveInputActive(session.id)) continue;
terminalBackend.writeToSession(session.id, data, {
automated: true,
automated: options?.automated === true,
sensitive: false,
...(lineDelayMs ? { lineDelayMs } : {}),
});
@@ -2400,6 +2534,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
setSftpFollowTerminalCwd,
setSftpHostForTab,
setSftpInitialLocationForTab,
onSaveWorkspaceLayoutAsDefault: handleSaveWorkspaceLayoutAsDefault,
setSftpPendingUploadsForTab,
showHostTreeSidebar,
sidePanelOpenTabs,
+2 -2
View File
@@ -145,11 +145,11 @@ test('popup terminals use their window-local vault readiness', () => {
assert.match(source, /vaultInitializedOverride=\{vaultInitialized\}/);
});
test('popup provider tree mounts the plugin authentication host', () => {
test('popup provider tree mounts authentication and paste confirmation hosts', () => {
assert.match(source, /import \{ PluginAuthenticationHost \} from '\.\/plugins\/PluginAuthenticationHost';/);
assert.match(
source,
/<I18nProvider locale=\{settings\.uiLanguage\}>\s+<TerminalPopupPageInner\s+settings=\{settings\}\s+allowTerminalStart=\{allowTerminalStart\}\s+\/>\s+<PluginAuthenticationHost \/>\s+<\/I18nProvider>/,
/<I18nProvider locale=\{settings\.uiLanguage\}>\s+<TerminalPopupPageInner\s+settings=\{settings\}\s+allowTerminalStart=\{allowTerminalStart\}\s+\/>\s+<PluginAuthenticationHost \/>\s+<MultilinePasteConfirmHost \/>\s+<\/I18nProvider>/,
);
});
+2
View File
@@ -2,6 +2,7 @@ import { setupVaultAgentBridge } from "../infrastructure/ai/vaultAgentBridgeClie
import { Copy, Minus, Square, Unplug, X } from 'lucide-react';
import React, { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { I18nProvider, useI18n } from '../application/i18n/I18nProvider';
import { MultilinePasteConfirmHost } from './terminal/MultilinePasteConfirmDialog';
import { useTerminalPopupWindow } from '../application/state/useTerminalPopupWindow';
import { useVaultState } from '../application/state/useVaultState';
import { useWindowControls } from '../application/state/useWindowControls';
@@ -547,6 +548,7 @@ export default function TerminalPopupPage({
allowTerminalStart={allowTerminalStart}
/>
<PluginAuthenticationHost />
<MultilinePasteConfirmHost />
</I18nProvider>
);
}
+36 -30
View File
@@ -77,6 +77,7 @@ import {
remapSnippetTargetGroupPaths,
} from "../domain/hostGroupPathMutations";
import {
canReorderVaultHosts,
reorderVaultItems,
reorderVaultStrings,
type VaultOrderPosition,
@@ -697,12 +698,15 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
keyPassphrases,
unreadablePassphraseCount,
} = await buildVaultCsvCredentialOptions(hosts, keys);
const { csv, exportedCount, skippedCount } = exportHostsToCsvWithStats(
const { csv, exportedCount, skippedCount, unreadableProxyCredentialCount } = exportHostsToCsvWithStats(
hosts,
{
keyPassphrases,
keyPassphrasesById,
keyPathsById,
proxyProfiles,
identities,
groupConfigs,
},
);
@@ -728,6 +732,13 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
}),
);
}
if (unreadableProxyCredentialCount > 0) {
toast.warning(
t("vault.hosts.export.toast.proxyCredentialsSkipped", {
count: unreadableProxyCredentialCount,
}),
);
}
if (skippedCount > 0) {
toast.warning(
t("vault.hosts.export.toast.successWithSkipped", {
@@ -740,7 +751,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
t("vault.hosts.export.toast.success", { count: exportedCount }),
);
}
}, [hosts, keys, t]);
}, [hosts, keys, proxyProfiles, identities, groupConfigs, t]);
// Copy hostname/IP for cross-host paste without opening the editor
const handleCopyHostname = useCallback(
@@ -1181,34 +1192,13 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
const source = hostsRef.current.find((host) => host.id === sourceHostId);
const target = hostsRef.current.find((host) => host.id === targetHostId);
if (!source || !target) return;
const targetGroup = target.group || "";
const targetManagedSource = managedSources
.filter(
(sourceInfo) =>
targetGroup === sourceInfo.groupName ||
targetGroup.startsWith(`${sourceInfo.groupName}/`),
)
.sort((a, b) => b.groupName.length - a.groupName.length)[0];
const updatedHosts = hostsRef.current.map((host) =>
host.id === sourceHostId
? {
...host,
label:
targetManagedSource &&
(!host.protocol || host.protocol === "ssh")
? host.label.replace(/\s/g, "")
: host.label,
group: targetGroup,
managedSourceId:
targetManagedSource &&
(!host.protocol || host.protocol === "ssh")
? targetManagedSource.id
: undefined,
}
: host,
);
// Card-to-card drags only reorder hosts within the same group; moving a
// host into a different group must go through the group folder drop
// (moveHostToGroup), otherwise dragging two grouped cards past each
// other silently swaps their group membership.
if (!canReorderVaultHosts(source.group, target.group)) return;
const reorderedHosts = reorderVaultItems<Host>(
updatedHosts,
hostsRef.current,
sourceHostId,
targetHostId,
position,
@@ -1217,7 +1207,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
onUpdateHosts(reorderedHosts);
setSortMode("manual");
},
[managedSources, onUpdateHosts, setSortMode],
[onUpdateHosts, setSortMode],
);
const reorderGroup = useCallback(
@@ -1289,6 +1279,21 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
t,
});
const managedFilesByGroupPath = useMemo(() => {
const map = new Map<string, string[]>();
for (const source of managedSources) {
if (source.filePath) {
const files = map.get(source.groupName);
if (files) {
files.push(source.filePath);
} else {
map.set(source.groupName, [source.filePath]);
}
}
}
return map;
}, [managedSources]);
const {
startInlineNewGroup,
startInlineRenameGroup,
@@ -1380,6 +1385,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
<>
<HostTreeGroupDeleteDialog
managedGroupPaths={managedGroupPaths}
managedFilesByGroupPath={managedFilesByGroupPath}
onConfirmDelete={deleteGroupPath}
/>
<VaultViewLayout
+54 -6
View File
@@ -5,6 +5,8 @@ import {
hostTreeInlineGroupDeleteStore,
useHostTreeInlineGroupDeleteTarget,
} from '../../application/state/hostTreeInlineGroupDeleteStore';
import { VaultGroupDeletionConfirmationChangedError } from '../../application/state/useVaultGroupDeletion';
import { toast } from '../ui/toast';
import { Button } from '../ui/button';
import {
Dialog,
@@ -17,11 +19,13 @@ import {
type HostTreeGroupDeleteDialogProps = {
managedGroupPaths?: Set<string>;
managedFilesByGroupPath?: Map<string, string[]>;
onConfirmDelete: (groupPath: string, deleteHosts: boolean) => void | Promise<void>;
};
export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps> = ({
managedGroupPaths,
managedFilesByGroupPath,
onConfirmDelete,
}) => {
const { t } = useI18n();
@@ -29,6 +33,23 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
const [deleteHosts, setDeleteHosts] = useState(false);
const isOpen = Boolean(targetPath);
const isManaged = Boolean(targetPath && managedGroupPaths?.has(targetPath));
const descendantManagedFiles: string[] = [];
if (targetPath && managedFilesByGroupPath) {
for (const [groupPath, files] of managedFilesByGroupPath) {
if (
(groupPath === targetPath || groupPath.startsWith(`${targetPath}/`))
) {
for (const filePath of files) {
if (
filePath
&& !descendantManagedFiles.includes(filePath)
) {
descendantManagedFiles.push(filePath);
}
}
}
}
}
useEffect(() => {
if (!isOpen) {
@@ -49,7 +70,9 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
<DialogDescription className="break-words [overflow-wrap:anywhere]">
{isManaged
? t('vault.groups.deleteDialog.managedDesc')
: t('vault.groups.deleteDialog.desc')}
: descendantManagedFiles.length > 0
? t('vault.groups.deleteDialog.mixedDesc')
: t('vault.groups.deleteDialog.desc')}
</DialogDescription>
</DialogHeader>
<div className="min-w-0 space-y-4 py-4">
@@ -59,6 +82,25 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
{t('vault.groups.pathLabel')}:{' '}
<span className="font-mono">{targetPath}</span>
</p>
{descendantManagedFiles.length > 0 && (
<div className="space-y-1 rounded-md border border-destructive/40 bg-destructive/10 p-3">
<p className="text-sm text-destructive">
{t('vault.groups.deleteDialog.managedWarning')}
</p>
{descendantManagedFiles.length > 0 && (
<div className="max-h-40 space-y-1 overflow-y-auto">
{descendantManagedFiles.map((filePath) => (
<p
key={filePath}
className="break-all font-mono text-xs text-muted-foreground"
>
{t('vault.groups.deleteDialog.managedFile', { file: filePath })}
</p>
))}
</div>
)}
</div>
)}
{!isManaged && (
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input
@@ -79,12 +121,18 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
</Button>
<Button
variant="destructive"
onClick={() => {
onClick={async () => {
if (!targetPath) return;
void Promise.resolve(onConfirmDelete(targetPath, isManaged || deleteHosts)).finally(() => {
hostTreeInlineGroupDeleteStore.close();
setDeleteHosts(false);
});
try {
await onConfirmDelete(targetPath, isManaged || deleteHosts);
} catch (error) {
toast.error(error instanceof VaultGroupDeletionConfirmationChangedError
? t('vault.groups.deleteDialog.sourcesChanged')
: error instanceof Error ? error.message : t('common.error'));
return;
}
hostTreeInlineGroupDeleteStore.close();
setDeleteHosts(false);
}}
>
{t('common.delete')}
@@ -80,6 +80,10 @@ function SettingsTerminalTab(props: {
setTerminalSidePanelAutoOpen: (enabled: boolean) => void;
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
setTerminalSidePanelAutoOpenTab: (tab: TerminalSidePanelAutoOpenTab) => void;
localShellSidePanelAutoOpen: boolean;
setLocalShellSidePanelAutoOpen: (enabled: boolean) => void;
localShellSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
setLocalShellSidePanelAutoOpenTab: (tab: TerminalSidePanelAutoOpenTab) => void;
availableFonts: TerminalFont[];
workspaceFocusStyle: 'dim' | 'border';
setWorkspaceFocusStyle: (style: 'dim' | 'border') => void;
@@ -106,6 +110,10 @@ function SettingsTerminalTab(props: {
setTerminalSidePanelAutoOpen,
terminalSidePanelAutoOpenTab,
setTerminalSidePanelAutoOpenTab,
localShellSidePanelAutoOpen,
setLocalShellSidePanelAutoOpen,
localShellSidePanelAutoOpenTab,
setLocalShellSidePanelAutoOpenTab,
availableFonts,
workspaceFocusStyle,
setWorkspaceFocusStyle,
@@ -750,6 +758,33 @@ function SettingsTerminalTab(props: {
</SettingRow>
</div>
<SectionHeader title={t("settings.terminal.section.localShellSidePanel")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-local-shell-side-panel-auto-open"
label={t("settings.terminal.localShellSidePanel.autoOpen")}
description={t("settings.terminal.localShellSidePanel.autoOpen.desc")}
>
<Toggle checked={localShellSidePanelAutoOpen} onChange={setLocalShellSidePanelAutoOpen} />
</SettingRow>
<SettingRow
label={t("settings.terminal.localShellSidePanel.autoOpenPane")}
description={t("settings.terminal.localShellSidePanel.autoOpenPane.desc")}
>
<Select
value={localShellSidePanelAutoOpenTab}
options={TERMINAL_SIDE_PANEL_AUTO_OPEN_TABS.map((tab) => ({
value: tab,
label: t(`settings.terminal.sidePanel.pane.${tab}`),
}))}
onChange={(value) => setLocalShellSidePanelAutoOpenTab(value as TerminalSidePanelAutoOpenTab)}
disabled={!localShellSidePanelAutoOpen}
className="w-36"
/>
</SettingRow>
</div>
<SectionHeader title={t("settings.terminal.section.keywordHighlight")} />
<SettingsAnchor anchorId="terminal-keyword-highlight" className="rounded-lg border bg-card p-4">
<div className="flex items-center justify-between mb-4">
@@ -859,6 +894,7 @@ function SettingsTerminalTab(props: {
)}
</div>
</SettingRow>
</div>
<SectionHeader title={t("settings.terminal.section.connection")} />
@@ -180,6 +180,37 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
/>
</SettingRow>
<SettingRow
anchorId="terminal-confirm-multiline-paste"
label={t("settings.terminal.behavior.confirmMultilinePaste")}
description={t("settings.terminal.behavior.confirmMultilinePaste.desc")}
>
<Toggle
checked={terminalSettings.confirmBeforeMultilinePaste ?? false}
onChange={(v) => updateTerminalSetting("confirmBeforeMultilinePaste", v)}
/>
</SettingRow>
<SettingRow
anchorId="terminal-confirm-multiline-paste-min-lines"
label={t("settings.terminal.behavior.confirmMultilinePasteMinLines")}
description={t("settings.terminal.behavior.confirmMultilinePasteMinLines.desc")}
>
<Input
type="number"
min={1}
max={1000}
value={terminalSettings.multilinePasteConfirmMinLines ?? 2}
onChange={(e) => {
const val = parseInt(e.target.value);
if (!isNaN(val) && val >= 1 && val <= 1000) {
updateTerminalSetting("multilinePasteConfirmMinLines", val);
}
}}
className="w-24"
/>
</SettingRow>
<SettingRow
anchorId="terminal-shift-enter-newline"
label={t("settings.terminal.behavior.shiftEnterNewline")}
+46 -16
View File
@@ -21,9 +21,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../../../ui/tooltip";
import { Select, SettingCard, SettingRow, Toggle } from "../../../settings/settings-ui";
import { getBridge } from "./types";
type ExternalMcpClient = "codex" | "claude" | "grok" | "cursor";
type ExternalMcpClient = "codex" | "claude" | "grok" | "cursor" | "other";
const CLIENT_TABS: ExternalMcpClient[] = ["codex", "claude", "grok", "cursor"];
const CLIENT_TABS: ExternalMcpClient[] = ["codex", "claude", "grok", "cursor", "other"];
type CopyableCodeBlockProps = {
label?: string;
@@ -304,6 +304,7 @@ export const ExternalMcpCard: React.FC = () => {
const [codexStatus, setCodexStatus] = useState<ClientSetupStatus | null>(null);
const [claudeStatus, setClaudeStatus] = useState<ClientSetupStatus | null>(null);
const [grokStatus, setGrokStatus] = useState<ClientSetupStatus | null>(null);
const [universalSetupPrompt, setUniversalSetupPrompt] = useState("");
const [isRefreshing, setIsRefreshing] = useState(false);
const [isAddingCodex, setIsAddingCodex] = useState(false);
const [isAddingClaude, setIsAddingClaude] = useState(false);
@@ -386,11 +387,19 @@ export const ExternalMcpCard: React.FC = () => {
if (!options?.quiet) setIsRefreshing(true);
try {
if (includeClients) {
const [nextStatus, nextCodexStatus, nextClaudeStatus, nextGrokStatus] = await Promise.all([
const [
nextStatus,
nextCodexStatus,
nextClaudeStatus,
nextGrokStatus,
nextUniversalPrompt,
] = await Promise.all([
bridge.externalMcpGetStatus(),
bridge.externalMcpCodexGetStatus(),
bridge.externalMcpClaudeGetStatus(),
bridge.externalMcpGrokGetStatus(),
bridge.externalMcpGetUniversalSetupPrompt?.()
?? Promise.resolve({ ok: false, prompt: "" }),
]);
setStatus(nextStatus as ExternalMcpStatus);
if (enabled && nextStatus?.ok && !nextStatus.enabled) {
@@ -399,6 +408,11 @@ export const ExternalMcpCard: React.FC = () => {
setCodexStatus(nextCodexStatus as ClientSetupStatus);
setClaudeStatus(nextClaudeStatus as ClientSetupStatus);
setGrokStatus(nextGrokStatus as ClientSetupStatus);
setUniversalSetupPrompt(
nextUniversalPrompt.ok && typeof nextUniversalPrompt.prompt === "string"
? nextUniversalPrompt.prompt
: "",
);
} else {
const nextStatus = await bridge.externalMcpGetStatus();
setStatus(nextStatus as ExternalMcpStatus);
@@ -540,7 +554,7 @@ export const ExternalMcpCard: React.FC = () => {
}, [refreshStatus, t]);
const selectedClientMeta = useMemo(() => {
if (selectedClient === "cursor") {
if (selectedClient === "cursor" || selectedClient === "other") {
return {
kind: "snippet" as const,
statusView: null as StatusView | null,
@@ -817,7 +831,7 @@ export const ExternalMcpCard: React.FC = () => {
<div
role="tablist"
aria-label={t("ai.externalMcp.clientConfiguration")}
className="grid grid-cols-4 gap-1 rounded-md bg-muted p-1"
className="grid grid-cols-5 gap-1 rounded-md bg-muted p-1"
>
{CLIENT_TABS.map((client) => {
const active = selectedClient === client;
@@ -866,7 +880,9 @@ export const ExternalMcpCard: React.FC = () => {
</div>
) : (
<p className="text-xs text-muted-foreground leading-5">
{t("ai.externalMcp.cursor.description")}
{t(selectedClient === "other"
? "ai.externalMcp.other.description"
: "ai.externalMcp.cursor.description")}
</p>
)}
@@ -894,16 +910,30 @@ export const ExternalMcpCard: React.FC = () => {
/>
</>
) : (
<CopyableCodeBlock
label={t("ai.externalMcp.configSnippet")}
value={selectedClientMeta.snippet}
copyKey="cursor"
copied={copied}
onCopy={copyText}
copyLabel={t("ai.externalMcp.copy")}
copiedLabel={t("ai.externalMcp.copied")}
emptyLabel={t("ai.externalMcp.unavailable")}
/>
<>
<CopyableCodeBlock
label={t("ai.externalMcp.configSnippet")}
value={selectedClientMeta.snippet}
copyKey="cursor"
copied={copied}
onCopy={copyText}
copyLabel={t("ai.externalMcp.copy")}
copiedLabel={t("ai.externalMcp.copied")}
emptyLabel={t("ai.externalMcp.unavailable")}
/>
{selectedClient === "other" ? (
<CopyableCodeBlock
label={t("ai.externalMcp.universalSetupPrompt")}
value={universalSetupPrompt}
copyKey="universal-setup-prompt"
copied={copied}
onCopy={copyText}
copyLabel={t("ai.externalMcp.copy")}
copiedLabel={t("ai.externalMcp.copied")}
emptyLabel={t("ai.externalMcp.unavailable")}
/>
) : null}
</>
)}
</div>
</div>
+5
View File
@@ -178,6 +178,11 @@ export interface NetcattyAiBridge {
idleTimeoutMinutes?: number;
sessionIdleTimeoutMinutes?: number;
}) => Promise<Record<string, unknown>>;
externalMcpGetUniversalSetupPrompt?: () => Promise<{
ok: boolean;
prompt?: string;
error?: string | null;
}>;
externalMcpCodexGetStatus?: () => Promise<Record<string, unknown>>;
externalMcpCodexAdd?: () => Promise<Record<string, unknown>>;
externalMcpClaudeGetStatus?: () => Promise<Record<string, unknown>>;
@@ -0,0 +1,71 @@
import test from "node:test";
import assert from "node:assert/strict";
import React from "react";
import {
createDomRenderer,
dispatchDomEvent,
flushEffects,
installDomEnvironment,
} from "../test-support/renderReactDom.tsx";
const cases = [
{ name: "file", isDirectory: false, existingType: "file", action: "replace", label: "Replace" },
{ name: "folder", isDirectory: true, existingType: "directory", action: "merge", label: "Merge" },
{ name: "folder with a file target", isDirectory: true, existingType: "file", action: "duplicate", label: "Duplicate" },
{ name: "folder with unknown target type", isDirectory: true, existingType: undefined, action: "duplicate", label: "Duplicate" },
{ name: "legacy file with unknown target type", isDirectory: false, existingType: undefined, action: "duplicate", label: "Duplicate" },
] as const;
for (const scenario of cases) {
test(`initial ${scenario.name} conflict focuses ${scenario.label} and runs that action`, async (t) => {
const env = installDomEnvironment();
const previousMutationObserver = globalThis.MutationObserver;
const previousNodeFilter = globalThis.NodeFilter;
const previousHTMLInputElement = globalThis.HTMLInputElement;
Object.defineProperty(globalThis, "MutationObserver", { configurable: true, writable: true, value: env.window.MutationObserver });
Object.defineProperty(globalThis, "NodeFilter", { configurable: true, writable: true, value: env.window.NodeFilter });
Object.defineProperty(globalThis, "HTMLInputElement", { configurable: true, writable: true, value: env.window.HTMLInputElement });
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { SftpConflictDialog } = await import("./SftpConflictDialog.tsx");
const renderer = await createDomRenderer(env.document);
const resolved: Array<{ id: string; action: string }> = [];
t.after(async () => {
await renderer.unmount();
await new Promise((resolve) => setTimeout(resolve, 20));
Object.defineProperty(globalThis, "MutationObserver", { configurable: true, writable: true, value: previousMutationObserver });
Object.defineProperty(globalThis, "NodeFilter", { configurable: true, writable: true, value: previousNodeFilter });
Object.defineProperty(globalThis, "HTMLInputElement", { configurable: true, writable: true, value: previousHTMLInputElement });
env.cleanup();
});
await renderer.render(React.createElement(
I18nProvider,
{ locale: "en" },
React.createElement(SftpConflictDialog, {
conflicts: [{
transferId: scenario.name,
fileName: "test.txt",
sourcePath: "/src/test.txt",
targetPath: "/dst/test.txt",
isDirectory: scenario.isDirectory,
existingType: scenario.existingType,
existingSize: 1,
newSize: 2,
existingModified: 1,
newModified: 2,
}],
onResolve: (id, action) => resolved.push({ id, action }),
formatFileSize: (size: number) => `${size} B`,
}),
));
await flushEffects();
await new Promise((resolve) => setTimeout(resolve, 20));
const focused = env.document.activeElement;
assert.equal(focused?.textContent, scenario.label);
assert.ok(focused, "a conflict action should receive focus");
await dispatchDomEvent(focused, new env.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(resolved, [{ id: scenario.name, action: scenario.action }]);
});
}
+11 -7
View File
@@ -107,6 +107,11 @@ const SftpConflictDialogInner: React.FC<SftpConflictDialogProps> = ({ conflicts,
const conflict = conflicts[0]; // Handle first conflict
const currentCanMerge = conflict?.isDirectory === true && conflict.existingType === 'directory';
const currentCanReplace = conflict ? canReplaceConflict(conflict) : false;
const preferredActionRef = currentCanMerge
? mergeButtonRef
: currentCanReplace && conflict?.existingType
? replaceButtonRef
: duplicateButtonRef;
useEffect(() => {
const currentConflictId = conflict?.transferId;
@@ -114,11 +119,7 @@ const SftpConflictDialogInner: React.FC<SftpConflictDialogProps> = ({ conflicts,
previousConflictIdRef.current = currentConflictId;
if (!currentConflictId || !previousConflictId || currentConflictId === previousConflictId) return;
const nextAction = currentCanMerge
? mergeButtonRef.current
: currentCanReplace
? replaceButtonRef.current
: duplicateButtonRef.current;
const nextAction = preferredActionRef.current;
if (!nextAction) return;
// If the previously focused action disappears or becomes disabled,
@@ -130,7 +131,7 @@ const SftpConflictDialogInner: React.FC<SftpConflictDialogProps> = ({ conflicts,
}
const timer = globalThis.setTimeout(() => nextAction.focus(), 0);
return () => globalThis.clearTimeout(timer);
}, [conflict?.transferId, currentCanMerge, currentCanReplace]);
}, [conflict?.transferId, preferredActionRef]);
if (!conflict) return null;
@@ -160,6 +161,10 @@ const SftpConflictDialogInner: React.FC<SftpConflictDialogProps> = ({ conflicts,
<DialogContent
className="gap-4 p-5 sm:max-w-[600px] sm:p-6"
aria-describedby={describedBy}
onOpenAutoFocus={(event) => {
event.preventDefault();
preferredActionRef.current?.focus();
}}
>
<DialogHeader className="space-y-1.5 pr-8">
<DialogTitle
@@ -262,7 +267,6 @@ const SftpConflictDialogInner: React.FC<SftpConflictDialogProps> = ({ conflicts,
size="sm"
onClick={() => handleAction('merge')}
disabled={!canMerge}
autoFocus={presentation.showDirectoryReplaceWarning}
className="min-w-24 border border-primary"
>
{t('sftp.conflict.action.merge')}
+17 -12
View File
@@ -14,6 +14,8 @@ import type { SftpTransferSource } from './SftpContext';
import type { SftpPaneTreeViewProps } from './SftpPaneTreeView.types';
import { sftpTreeSelectionStore, useSftpTreeSelectionState } from '../../application/state/sftp/sftpTreeSelectionStore';
import { sftpKeyboardSelectionStore, sftpTreeEnterStore } from './hooks/useSftpKeyboardShortcuts';
import { startSftpFileDrag, localFileDragMoveEffect, getLocalFileDragSources, takeLocalFileDragSources, type LocalDragSource } from '../../application/state/sftp/localFileDrag';
import { toast } from '../ui/toast';
import { useI18n } from '../../application/i18n/I18nProvider';
import { SftpColumnMenuItems } from './SftpColumnMenuItems';
import {
@@ -686,10 +688,11 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
sourcePath: getParentPath(entryPath),
});
}
e.dataTransfer.effectAllowed = 'copyMove';
e.dataTransfer.setData('text/plain', files.map((f) => f.name).join('\n'));
onDragStartRef.current(files, sideRef.current);
}, [getActionPaths, pane.connection?.id, toTransferSources]);
startSftpFileDrag({ event: e, paneId: pane.id, connection: pane.connection,
sources: files, side: sideRef.current, onRemoteDrag: onDragStartRef.current,
onError: (message) => toast.error(message, "SFTP"),
});
}, [getActionPaths, pane.id, pane.connection, toTransferSources]);
const stableOnDragEnd = useCallback(() => onDragEndRef.current(), []);
const applyLocalMoveMutation = useCallback((
sourceParentPaths: string[],
@@ -793,8 +796,7 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
setIsMoving(false);
}
}, [moveToPath, isMoving, executeMoveAction, moveTargetPaths]);
const getSamePaneDragPaths = useCallback((): string[] | null => {
const dragged = draggedFilesRef.current;
const getSamePaneDragPaths = useCallback((dragged: LocalDragSource[] | null): string[] | null => {
if (!dragged || dragged.length === 0) return null;
if (dragged[0]?.side !== sideRef.current) return null;
const currentConnectionId = pane.connection?.id;
@@ -807,15 +809,16 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
const entry = entryByPathRef.current.get(entryPath);
if (!entry) return;
const isDir = isNavigableDirectory(entry);
const samePaneDragPaths = getSamePaneDragPaths();
const sources = draggedFilesRef.current ?? getLocalFileDragSources(e.dataTransfer);
const samePaneDragPaths = getSamePaneDragPaths(sources);
if (samePaneDragPaths && isDir && entry.name !== '..') {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.dropEffect = draggedFilesRef.current ? 'move' : localFileDragMoveEffect(e.dataTransfer);
setDragOverNodePath(entryPath);
return;
}
const isInternalDrag = draggedFilesRef.current && draggedFilesRef.current[0]?.side !== sideRef.current;
const isInternalDrag = sources && sources[0]?.side !== sideRef.current;
if (isInternalDrag && isDir && entry.name !== '..') {
e.preventDefault();
e.stopPropagation();
@@ -835,7 +838,9 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
const entry = entryByPathRef.current.get(entryPath);
if (!entry) return;
const isDir = isNavigableDirectory(entry);
const samePaneDragPaths = getSamePaneDragPaths();
const sources = draggedFilesRef.current ?? (isDir && entry.name !== '..'
? takeLocalFileDragSources(e.dataTransfer) : null);
const samePaneDragPaths = getSamePaneDragPaths(sources);
if (samePaneDragPaths && isDir && entry.name !== '..') {
e.preventDefault();
e.stopPropagation();
@@ -863,13 +868,13 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
return;
}
const hasFiles = e.dataTransfer.types.includes('Files');
const isInternalDrag = draggedFilesRef.current && draggedFilesRef.current[0]?.side !== sideRef.current;
const isInternalDrag = sources && sources[0]?.side !== sideRef.current;
if (isInternalDrag && isDir && entry.name !== '..') {
e.preventDefault();
e.stopPropagation();
setDragOverNodePath(null);
onReceiveFromOtherPaneRef.current(
draggedFilesRef.current.map((file) => ({ ...file, targetPath: entryPath })),
sources!.map((file) => ({ ...file, targetPath: entryPath })),
);
return;
}
@@ -2,13 +2,16 @@ import React, { useCallback, useEffect, useRef, useState } from "react";
import type { SftpFileEntry } from "../../../types";
import type { SftpPaneCallbacks, SftpDragCallbacks, SftpTransferSource } from "../SftpContext";
import { isNavigableDirectory } from "../utils";
import { toast } from "../../ui/toast";
import { startSftpFileDrag, localFileDragMoveEffect, getLocalFileDragSources, takeLocalFileDragSources, clearLocalFileDragForPane, type LocalDragSource } from "../../../application/state/sftp/localFileDrag";
import { joinPath } from "../../../application/state/sftp/utils";
interface UseSftpPaneDragAndSelectParams {
side: "left" | "right";
pane: {
id: string;
selectedFiles: Set<string>;
connection?: { currentPath: string; id: string } | null;
connection?: { currentPath: string; id: string; isLocal?: boolean } | null;
};
sortedDisplayFiles: SftpFileEntry[];
draggedFiles: (SftpTransferSource & { side: "left" | "right" })[] | null;
@@ -73,8 +76,10 @@ export const useSftpPaneDragAndSelect = ({
}
}, [pane.selectedFiles.size]);
const getSamePaneDragPaths = useCallback((): string[] | null => {
const dragged = draggedFilesRef.current;
useEffect(() => () => clearLocalFileDragForPane(pane.id),
[pane.id, pane.connection?.id, pane.connection?.isLocal, pane.connection?.currentPath]);
const getSamePaneDragPaths = useCallback((dragged: LocalDragSource[] | null): string[] | null => {
if (!dragged || dragged.length === 0) return null;
if (dragged[0]?.side !== side) return null;
@@ -115,9 +120,10 @@ export const useSftpPaneDragAndSelect = ({
setIsDragOverPane(false);
setDragOverEntry(null);
if (draggedFilesRef.current && draggedFilesRef.current.length > 0) {
if (draggedFilesRef.current[0]?.side !== side) {
onReceiveRef.current(draggedFilesRef.current);
const sources = draggedFilesRef.current ?? takeLocalFileDragSources(e.dataTransfer);
if (sources && sources.length > 0) {
if (sources[0]?.side !== side) {
onReceiveRef.current(sources);
}
return;
}
@@ -153,26 +159,28 @@ export const useSftpPaneDragAndSelect = ({
side,
},
];
e.dataTransfer.effectAllowed = "copyMove";
e.dataTransfer.setData("text/plain", files.map((f) => f.name).join("\n"));
onDragStart(files, side);
startSftpFileDrag({ event: e, paneId: pane.id, connection: pane.connection,
sources: files, side, onRemoteDrag: onDragStart,
onError: (message) => toast.error(message, "SFTP"),
});
},
[onDragStart, pane.connection?.currentPath, pane.connection?.id, side],
[onDragStart, pane.id, pane.connection, side],
);
const handleEntryDragOver = useCallback(
(entry: SftpFileEntry, e: React.DragEvent) => {
const samePaneDragPaths = getSamePaneDragPaths();
const sources = draggedFilesRef.current ?? getLocalFileDragSources(e.dataTransfer);
const samePaneDragPaths = getSamePaneDragPaths(sources);
if (samePaneDragPaths && isNavigableDirectory(entry) && entry.name !== "..") {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "move";
e.dataTransfer.dropEffect = draggedFilesRef.current ? "move" : localFileDragMoveEffect(e.dataTransfer);
setDragOverEntry(entry.name);
return;
}
// Handle cross-pane internal drag
if (draggedFilesRef.current && draggedFilesRef.current[0]?.side !== side) {
if (sources && sources[0]?.side !== side) {
if (isNavigableDirectory(entry) && entry.name !== "..") {
e.preventDefault();
e.stopPropagation();
@@ -194,7 +202,10 @@ export const useSftpPaneDragAndSelect = ({
const handleEntryDrop = useCallback(
async (entry: SftpFileEntry, e: React.DragEvent) => {
const samePaneDragPaths = getSamePaneDragPaths();
// Let a non-directory drop bubble to the pane before consuming a native gesture.
const sources = draggedFilesRef.current ?? (isNavigableDirectory(entry) && entry.name !== ".."
? takeLocalFileDragSources(e.dataTransfer) : null);
const samePaneDragPaths = getSamePaneDragPaths(sources);
if (samePaneDragPaths && isNavigableDirectory(entry) && entry.name !== "..") {
e.preventDefault();
e.stopPropagation();
@@ -210,7 +221,7 @@ export const useSftpPaneDragAndSelect = ({
}
// Handle cross-pane internal drag
if (draggedFilesRef.current && draggedFilesRef.current[0]?.side !== side) {
if (sources && sources[0]?.side !== side) {
if (isNavigableDirectory(entry) && entry.name !== "..") {
e.preventDefault();
e.stopPropagation();
@@ -220,7 +231,7 @@ export const useSftpPaneDragAndSelect = ({
? joinPath(pane.connection.currentPath, entry.name)
: undefined;
onReceiveRef.current(
draggedFilesRef.current.map((file) => ({ ...file, targetPath })),
sources.map((file) => ({ ...file, targetPath })),
);
}
return;
+50 -11
View File
@@ -11,6 +11,7 @@ import { toast } from "../../ui/toast";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { getFileExtension, getLanguageId, FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import { isNavigableDirectory } from "../utils";
import { resolveDownloadSourceSnapshot } from "../../../application/state/sftp/downloadSourceSnapshot";
import { reportSftpUploadResults } from "../reportSftpUploadResults";
import { editorTabStore } from "../../../application/state/editorTabStore";
import { toEditorTabId, activeTabStore } from "../../../application/state/activeTabStore";
@@ -36,6 +37,8 @@ export const useSftpViewFileOps = ({
showSaveDialog,
selectDirectory,
getSftpIdForConnection,
statSftp,
listSftp,
}: UseSftpViewFileOpsParams): UseSftpViewFileOpsResult => {
const [permissionsState, setPermissionsState] = useState<{
file: SftpFileEntry;
@@ -404,7 +407,7 @@ export const useSftpViewFileOps = ({
if (!pane.connection) return;
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name);
const isDirectory = isNavigableDirectory(file);
let isDirectory = isNavigableDirectory(file);
try {
// For local files, use blob download.
@@ -442,6 +445,18 @@ export const useSftpViewFileOps = ({
throw new Error("SFTP session not found");
}
// The listed entry can be stale when the file was deleted / recreated
// in the terminal without refreshing the side panel. Re-stat so the
// planned snapshot size and entry type match the real source.
const sourceSnapshot = await resolveDownloadSourceSnapshot(
statSftp,
sftpId,
resolvedFullPath,
pane.filenameEncoding,
listSftp,
);
isDirectory = sourceSnapshot.isDirectory;
if (isDirectory) {
if (!selectDirectory) {
toast.error(t("sftp.error.downloadFailed"), "SFTP");
@@ -451,6 +466,15 @@ export const useSftpViewFileOps = ({
const selectedDirectory = await selectDirectory(t("sftp.context.download"));
if (!selectedDirectory) return;
// The picker may stay open while the remote entry changes again.
const selectedSnapshot = await resolveDownloadSourceSnapshot(
statSftp,
sftpId, resolvedFullPath, pane.filenameEncoding,
listSftp,
);
if (!selectedSnapshot.isDirectory) {
throw new Error("Remote source changed while choosing the download target");
}
const targetPath = joinFsPath(selectedDirectory, file.name);
try {
@@ -481,14 +505,17 @@ export const useSftpViewFileOps = ({
return;
}
// Show save dialog to get target path
const targetPath = await showSaveDialog(file.name);
if (!targetPath) {
// User cancelled
return;
}
if (!targetPath) return;
const fileSize = typeof file.size === "string" ? parseInt(file.size, 10) || 0 : (file.size || 0);
const selectedSnapshot = await resolveDownloadSourceSnapshot(
statSftp,
sftpId, resolvedFullPath, pane.filenameEncoding,
listSftp,
);
if (selectedSnapshot.isDirectory) {
throw new Error("Remote source changed while choosing the download target");
}
// Route through downloadToLocal so FileZilla-style transfer pool
// sessions are used (browse session stays free for listing).
const status = await sftpRef.current.downloadToLocal({
@@ -501,7 +528,7 @@ export const useSftpViewFileOps = ({
sourceHostLabel: pane.connection.hostLabel,
sourceEncoding: pane.filenameEncoding,
isDirectory: false,
totalBytes: fileSize,
totalBytes: selectedSnapshot.size,
});
if (status === "completed") {
toast.success(`${t("sftp.context.download")}: ${file.name}`, "SFTP");
@@ -523,6 +550,8 @@ export const useSftpViewFileOps = ({
showSaveDialog,
selectDirectory,
getSftpIdForConnection,
statSftp,
listSftp,
],
);
@@ -633,8 +662,16 @@ export const useSftpViewFileOps = ({
try {
const sourcePath = sftpRef.current.joinPath(pane.connection.currentPath, file.name);
const targetPath = joinFsPath(selectedDirectory, file.name);
const isDirectory = isNavigableDirectory(file);
const fileSize = typeof file.size === "string" ? parseInt(file.size, 10) || 0 : (file.size || 0);
// Re-stat each root: the listed entries can be stale after
// terminal-side delete + recreate without a refresh.
const sourceSnapshot = await resolveDownloadSourceSnapshot(
statSftp,
sftpId,
sourcePath,
pane.filenameEncoding,
listSftp,
);
const isDirectory = sourceSnapshot.isDirectory;
const status = await sftpRef.current.downloadToLocal({
fileName: file.name,
@@ -646,7 +683,7 @@ export const useSftpViewFileOps = ({
sourceHostLabel: pane.connection.hostLabel,
sourceEncoding: pane.filenameEncoding,
isDirectory,
totalBytes: isDirectory ? undefined : fileSize,
totalBytes: isDirectory ? undefined : sourceSnapshot.size,
});
results[index] = { status: "fulfilled", value: { file, status } };
} catch (reason) {
@@ -679,6 +716,8 @@ export const useSftpViewFileOps = ({
t,
selectDirectory,
getSftpIdForConnection,
statSftp,
listSftp,
handleDownloadFileForSide,
],
);
@@ -1,6 +1,6 @@
import type React from "react";
import type { MutableRefObject } from "react";
import type { SftpFileEntry } from "../../../types";
import type { RemoteFile, SftpFileEntry, SftpFilenameEncoding } from "../../../types";
import type { SftpStateApi } from "../../../application/state/useSftpState";
import type { FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import type { TextEditorModalSnapshot } from "../../TextEditorModal";
@@ -21,6 +21,9 @@ export interface UseSftpViewFileOpsParams {
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
/** Application-layer fresh stat for download source snapshots (kept off the raw bridge). */
statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<SftpStatResult>;
listSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<RemoteFile[]>;
}
export interface UseSftpViewFileOpsResult {
@@ -28,6 +28,7 @@ interface UseSftpViewPaneCallbacksParams {
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<SftpStatResult>;
listLocalFiles: (path: string) => Promise<RemoteFile[]>;
mkdirLocal?: (path: string) => Promise<void>;
deleteLocalFile?: (path: string) => Promise<void>;
@@ -45,6 +46,7 @@ export const useSftpViewPaneCallbacks = ({
showSaveDialog,
selectDirectory,
getSftpIdForConnection,
statSftp,
listLocalFiles,
listDrives,
}: UseSftpViewPaneCallbacksParams) => {
@@ -59,6 +61,8 @@ export const useSftpViewPaneCallbacks = ({
showSaveDialog,
selectDirectory,
getSftpIdForConnection,
statSftp,
listSftp,
});
const listLocalFilesRef = useRef(listLocalFiles);
@@ -0,0 +1,87 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import { useSftpPaneDragAndSelect } from './hooks/useSftpPaneDragAndSelect';
import { clearLocalFileDrag } from '../../application/state/sftp/localFileDrag';
import type { SftpFileEntry } from '../../types';
test('list hook preserves local copy/move routing, remote HTML drag, selection and connection cleanup', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [name, value] of Object.entries({ window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true })) {
previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
Object.defineProperty(globalThis, name, { configurable: true, value });
}
const starts: { paths: string[] }[] = [];
Object.defineProperty(dom.window, 'netcatty', { value: {
startLocalFileDrag: async (payload: { paths: string[] }) => { starts.push(payload); return { started: true }; },
cancelLocalFileDrag() {},
getPathForFile: (file: { path: string }) => file.path,
}});
const entries: SftpFileEntry[] = [
{ name: 'a.txt', type: 'file' }, { name: 'b.txt', type: 'file' }, { name: 'folder', type: 'directory' },
].map(entry => ({ ...entry, size: 0, sizeFormatted: '', lastModified: 0, lastModifiedFormatted: '' })) as SftpFileEntry[];
const actions: { kind: string; args: unknown[] }[] = [];
const record = (kind: string) => (...args: unknown[]) => { actions.push({ kind, args }); };
let left!: ReturnType<typeof useSftpPaneDragAndSelect>;
let right!: ReturnType<typeof useSftpPaneDragAndSelect>;
let remoteDrag: Parameters<typeof useSftpPaneDragAndSelect>[0]['draggedFiles'] = null;
function Harness({ local = true, connectionId = 'left' }) {
const usePane = (side: 'left' | 'right') => useSftpPaneDragAndSelect({
side, pane: { id: side, selectedFiles: new Set(['a.txt', 'folder']),
connection: { id: side === 'left' ? connectionId : 'right', currentPath: '/files', isLocal: side === 'right' || local } },
sortedDisplayFiles: entries, draggedFiles: remoteDrag,
onDragStart: (files, origin) => { remoteDrag = files.map(file => ({ ...file, side: origin })); record('remote')(files); },
onReceiveFromOtherPane: record('copy'), onMoveEntriesToPath: async (...args) => record('move')(...args),
onUploadExternalFiles: async () => record('external')(), onOpenEntry() {}, onRangeSelect() {}, onToggleSelection() {},
});
left = usePane('left'); right = usePane('right');
return null;
}
const event = (paths: string[] = []) => ({
preventDefault() {}, stopPropagation() {},
dataTransfer: { types: paths.length ? ['Files'] : [], files: paths.map(path => ({ path })), items: paths.map(() => ({})),
effectAllowed: '', dropEffect: '', setData: record('text') },
}) as unknown as React.DragEvent;
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await act(async () => root.render(React.createElement(Harness)));
await act(async () => left.handleFileDragStart(entries[0], event()));
assert.deepEqual(starts.at(-1)?.paths, ['/files/a.txt', '/files/folder']);
await act(async () => right.handlePaneDrop(event(starts.at(-1)!.paths)));
assert.deepEqual(actions.map(a => a.kind), ['copy']);
assert.equal((actions[0].args[0] as unknown[]).length, 2);
actions.length = 0;
await act(async () => left.handleFileDragStart(entries[1], event()));
assert.deepEqual(starts.at(-1)?.paths, ['/files/b.txt'], 'dragging an unselected row excludes the old selection');
await act(async () => left.handleEntryDrop(entries[2], event(starts.at(-1)!.paths)));
assert.deepEqual(actions, [{ kind: 'move', args: [['/files/b.txt'], '/files/folder'] }]);
actions.length = 0;
await act(async () => left.handleFileDragStart(entries[1], event()));
await act(async () => root.render(React.createElement(Harness, { connectionId: 'replacement' })));
await act(async () => right.handlePaneDrop(event(['/files/b.txt'])));
assert.deepEqual(actions.map(a => a.kind), ['external'], 'connection replacement invalidates internal native identity');
actions.length = 0;
await act(async () => root.render(React.createElement(Harness, { local: false })));
const before = starts.length;
await act(async () => left.handleFileDragStart(entries[1], event()));
assert.equal(starts.length, before, 'remote path never reaches native bridge');
assert.deepEqual(actions.map(a => a.kind), ['text', 'remote']);
await act(async () => root.render(React.createElement(Harness, { local: false })));
await act(async () => right.handlePaneDrop(event()));
assert.equal(actions.at(-1)?.kind, 'copy');
} finally {
await act(async () => root.unmount());
clearLocalFileDrag();
dom.window.close();
for (const [name, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
else Reflect.deleteProperty(globalThis, name);
}
}
});
@@ -0,0 +1,125 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { SftpFileEntry } from "../../types";
import type { SftpStateApi } from "../../application/state/useSftpState";
import { useSftpViewFileOps } from "./hooks/useSftpViewFileOps";
const file = (
name: string, size: number, type: SftpFileEntry["type"] = "file",
linkTarget?: SftpFileEntry["linkTarget"],
): SftpFileEntry => ({
name, size, type, linkTarget, lastModified: 0, sizeFormatted: "", lastModifiedFormatted: "",
});
test("single and batch downloads route by current remote type and size", async () => {
const globals = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
globals.IS_REACT_ACT_ENVIRONMENT = true;
const current = new Map<string, SftpStatResult>([
["/remote/smaller", { name: "smaller", size: 50_000, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/larger", { name: "larger", size: 50_000, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/became-dir", { name: "became-dir", size: 0, sizeKnown: true, type: "directory", lastModified: 0 }],
["/remote/became-file", { name: "became-file", size: 12, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/changes-in-picker", { name: "changes-in-picker", size: 15, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/type-changes-in-picker", { name: "type-changes-in-picker", size: 15, sizeKnown: true, type: "file", lastModified: 0 }],
["/remote/statless", { name: "statless", size: 0, sizeKnown: false, type: "file", lastModified: 0 }],
["/remote/file-link", { name: "file-link", size: 9, sizeKnown: true, type: "symlink", lastModified: 0 }],
["/remote/dir-link", { name: "dir-link", size: 9, sizeKnown: true, type: "symlink", lastModified: 0 }],
]);
const downloads: Array<{ sourcePath: string; totalBytes?: number; isDirectory: boolean }> = [];
let saveCalls = 0;
let directoryCalls = 0;
let onSave: (name: string) => void = () => undefined;
const connection = { id: "conn-1", hostId: "host-1", hostLabel: "Host", currentPath: "/remote", isLocal: false };
const pane = { connection, filenameEncoding: "auto" };
const sftpRef = { current: {
leftPane: pane, rightPane: pane,
joinPath: (parent: string, name: string) => `${parent}/${name}`,
downloadToLocal: async (params: { sourcePath: string; totalBytes?: number; isDirectory: boolean }) => {
downloads.push(params);
return "completed";
},
} as unknown as SftpStateApi };
let ops: ReturnType<typeof useSftpViewFileOps> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpViewFileOps({
sftpRef,
behaviorRef: { current: "" },
autoSyncRef: { current: false },
getOpenerForFileRef: { current: () => null },
setOpenerForExtension: () => undefined,
t: (key) => key,
showSaveDialog: async (name) => { saveCalls++; onSave(name); return `/downloads/${name}`; },
selectDirectory: async () => { directoryCalls++; return "/downloads"; },
getSftpIdForConnection: () => "sftp-1",
statSftp: async (_id, path) => current.get(path) ?? null as unknown as SftpStatResult,
listSftp: async (_id, parent) => {
assert.equal(parent, "/remote");
return [
{ name: "file-link", type: "symlink", linkTarget: "file", size: "9 bytes", lastModified: "" },
{ name: "dir-link", type: "symlink", linkTarget: "directory", size: "9 bytes", lastModified: "" },
];
},
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
const single = ops!.onDownloadFileLeft as unknown as (entry: SftpFileEntry) => Promise<void>;
const batch = ops!.onDownloadFilesLeft as unknown as (entries: SftpFileEntry[]) => Promise<void>;
await act(async () => { await single(file("smaller", 100_000)); });
await act(async () => { await single(file("larger", 25_000)); });
assert.deepEqual(downloads.map(({ totalBytes }) => totalBytes), [50_000, 50_000]);
assert.equal(saveCalls, 2, "save dialog still opens for every single-file download");
onSave = (name) => {
if (name === "changes-in-picker") current.set("/remote/changes-in-picker", {
name, size: 30, sizeKnown: true, type: "file", lastModified: 0,
});
if (name === "type-changes-in-picker") current.set("/remote/type-changes-in-picker", {
name, size: 0, sizeKnown: true, type: "directory", lastModified: 0,
});
};
await act(async () => { await single(file("changes-in-picker", 100)); });
assert.equal(downloads.at(-1)?.totalBytes, 30, "size is checked again after Save As");
const countBeforeTypeChange = downloads.length;
await act(async () => { await single(file("type-changes-in-picker", 100)); });
assert.equal(downloads.length, countBeforeTypeChange, "type changes during Save As abort the transfer");
const countBeforeMissing = saveCalls;
await act(async () => { await single(file("missing", 100_000)); });
assert.equal(saveCalls, countBeforeMissing, "missing source never opens Save As");
await act(async () => { await single(file("statless", 100_000)); });
assert.equal(downloads.at(-1)?.totalBytes, undefined, "stat-less SCP does not use listed size");
await act(async () => { await single(file("file-link", 9, "symlink", "directory")); });
assert.equal(downloads.at(-1)?.isDirectory, false);
assert.equal(downloads.at(-1)?.totalBytes, undefined, "link node size is not file size");
await act(async () => { await single(file("became-dir", 100_000)); });
assert.equal(downloads.at(-1)?.isDirectory, true);
assert.equal(directoryCalls, 1);
await act(async () => {
await batch([
file("became-file", 0, "directory"),
file("missing", 100_000),
file("dir-link", 9, "symlink", "file"),
]);
});
assert.equal(directoryCalls, 2, "batch chooses one directory");
const becameFile = downloads.find(({ sourcePath }) => sourcePath === "/remote/became-file");
assert.equal(becameFile?.isDirectory, false);
assert.equal(becameFile?.totalBytes, 12);
assert.equal(downloads.find(({ sourcePath }) => sourcePath === "/remote/dir-link")?.isDirectory, true);
assert.equal(downloads.some(({ sourcePath }) => sourcePath === "/remote/missing"), false);
} finally {
await act(async () => { renderer?.unmount(); });
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
}
});
@@ -0,0 +1,206 @@
import test from "node:test";
import assert from "node:assert/strict";
import { JSDOM } from "jsdom";
/**
* Regression test for #3426: hovering autocomplete rows must not change the
* popup's rendered geometry. The detail tooltip used to mount/unmount and
* resize per hovered row, which fed the wrapper's measured size into the
* position clamp and moved the popup under a stationary pointer — flipping
* the hovered row and self-oscillating (violent mousemove jitter).
*/
test("autocomplete popup keeps a fixed geometry while hovering rows (#3426)", async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: "http://localhost",
});
const window = dom.window;
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
const installGlobal = (key: string, value: unknown) => {
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value,
});
};
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
installGlobal("window", window);
installGlobal("document", window.document);
installGlobal("navigator", window.navigator);
installGlobal("HTMLElement", window.HTMLElement);
installGlobal("Element", window.Element);
installGlobal("Node", window.Node);
installGlobal("getComputedStyle", window.getComputedStyle.bind(window));
installGlobal("requestAnimationFrame", window.requestAnimationFrame.bind(window));
installGlobal("cancelAnimationFrame", window.cancelAnimationFrame.bind(window));
installGlobal("ResizeObserver", ResizeObserverStub);
installGlobal("IS_REACT_ACT_ENVIRONMENT", true);
try {
const { default: React, act } = await import("react");
const { createRoot } = await import("react-dom/client");
const AutocompletePopup = (await import("./autocomplete/AutocompletePopup.tsx")).default;
type CompletionSuggestion = import("./autocomplete/completionEngine.ts").CompletionSuggestion;
const suggestions: CompletionSuggestion[] = [
{
text: "git status",
displayText: "git status",
description: "Show the working tree status",
source: "command",
score: 10,
},
{
text: "src",
displayText: "src/",
source: "path",
fileType: "directory",
score: 9,
},
{
text: "git commit",
displayText: "git commit",
description: "Record changes to the repository",
source: "command",
score: 8,
},
];
const containerRef = { current: null } as React.RefObject<HTMLDivElement | null>;
const rootNode = window.document.getElementById("root");
assert.ok(rootNode);
const root = createRoot(rootNode);
await act(async () => {
root.render(
<AutocompletePopup
suggestions={suggestions}
selectedIndex={-1}
anchorViewport={{ left: 100, top: 300, bottom: 316 }}
visible
themeColors={{ background: "#1e1e2e", foreground: "#cdd6f4", selection: "#444", cursor: "#f5e0dc" }}
onSelect={() => {}}
containerRef={containerRef}
/>,
);
});
const findWrapper = (): HTMLElement => {
const el = Array.from(rootNode.querySelectorAll<HTMLElement>("div"))
.find((candidate) => candidate.style.zIndex === "10000");
assert.ok(el, "popup wrapper should be mounted");
return el;
};
const findDetailPanel = (): HTMLElement | null =>
Array.from(rootNode.querySelectorAll<HTMLElement>("div"))
.find((el) => el.style.width === "280px") ?? null;
const wrapper = findWrapper();
const initialLeft = wrapper.style.left;
const initialTop = wrapper.style.top;
assert.ok(initialLeft && initialTop, "popup should be fixed-positioned");
// Nothing hovered/selected: the detail panel is mounted but hidden so its
// box is already reserved (matches the placement pass's reservation).
const hiddenPanel = findDetailPanel();
assert.ok(hiddenPanel, "detail panel should stay mounted for the whole set");
assert.equal(hiddenPanel.style.visibility, "hidden");
const fixedHeight = hiddenPanel.style.height;
assert.ok(fixedHeight && fixedHeight !== "0px", "detail panel should reserve a fixed height");
const hoverRow = async (rowIndex: number) => {
const label = Array.from(rootNode.querySelectorAll<HTMLElement>("span"))
.find((el) => el.textContent === suggestions[rowIndex].displayText);
assert.ok(label, `row for ${suggestions[rowIndex].displayText} should be rendered`);
const row = label.closest<HTMLElement>("div[style*='cursor']");
assert.ok(row, "row container should be a hoverable div");
await act(async () => {
row.dispatchEvent(new window.MouseEvent("mouseover", { bubbles: true }));
});
};
// Hover the describable row: detail becomes visible, geometry unchanged.
await hoverRow(0);
assert.equal(wrapper.style.left, initialLeft, "hover must not shift popup left");
assert.equal(wrapper.style.top, initialTop, "hover must not change popup top");
const shownPanel = findDetailPanel();
assert.ok(shownPanel);
assert.equal(shownPanel.style.visibility, "visible");
assert.equal(shownPanel.style.height, fixedHeight, "detail box must be hover-independent");
assert.ok(shownPanel.textContent?.includes("Show the working tree status"));
// Hover the path row (no detail): panel hides via visibility, stays
// mounted with the same fixed box, and the popup does not move.
await hoverRow(1);
assert.equal(wrapper.style.left, initialLeft, "hovering a path row must not move the popup");
assert.equal(wrapper.style.top, initialTop, "hovering a path row must not shift the popup");
const panelAfterPathHover = findDetailPanel();
assert.ok(panelAfterPathHover, "detail panel must remain mounted while hovering path rows");
assert.equal(panelAfterPathHover.style.visibility, "hidden");
assert.equal(panelAfterPathHover.style.height, fixedHeight);
assert.equal(panelAfterPathHover.style.width, "280px");
// Hovering another describable row is equally geometry-stable.
await hoverRow(2);
assert.equal(wrapper.style.left, initialLeft);
assert.equal(wrapper.style.top, initialTop);
// A hidden detail reserve must not intercept clicks through the wrapper.
assert.equal(wrapper.style.pointerEvents, "none");
await hoverRow(1);
assert.equal(findDetailPanel()?.style.pointerEvents, "none");
await hoverRow(0);
assert.equal(findDetailPanel()?.style.pointerEvents, "auto");
// Exercise pane sizes down to the supported split minimum. JSDOM cannot
// perform flex layout, so check the constraints that let Chromium shrink
// both panels without tying their size to the hovered description.
for (const width of [400, 240, 120]) {
const container = window.document.createElement("div");
container.getBoundingClientRect = () => ({
left: 0, top: 0, right: width, bottom: 600,
width, height: 600, x: 0, y: 0, toJSON: () => ({}),
});
await act(async () => {
root.render(
<AutocompletePopup
suggestions={suggestions}
selectedIndex={-1}
anchorViewport={{ left: width - 30, top: 500, bottom: 516 }}
visible
onSelect={() => {}}
containerRef={{ current: container }}
/>,
);
});
assert.equal(findWrapper().style.maxWidth, `${width - 16}px`);
const list = rootNode.querySelector<HTMLElement>(".xterm-autocomplete-popup");
assert.ok(list);
assert.ok(parseFloat(list.style.minWidth) <= (width - 16) / 2);
for (const index of [0, 1, 2]) {
await hoverRow(index);
const detail = findDetailPanel();
assert.ok(detail);
assert.equal(detail.style.minWidth, "0px");
assert.equal(detail.style.flexShrink, "1");
}
}
await act(async () => {
root.unmount();
});
} finally {
for (const [key, descriptor] of previousGlobals) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else delete (globalThis as Record<string, unknown>)[key];
}
}
});
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
test('multiline paste dialog returns decisions and restores terminal focus after closing', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: 'http://localhost',
});
const window = dom.window;
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
const installGlobal = (key: string, value: unknown) => {
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value,
});
};
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
installGlobal('window', window);
installGlobal('document', window.document);
installGlobal('navigator', window.navigator);
installGlobal('HTMLElement', window.HTMLElement);
installGlobal('HTMLInputElement', window.HTMLInputElement);
installGlobal('HTMLTextAreaElement', window.HTMLTextAreaElement);
installGlobal('Element', window.Element);
installGlobal('SVGElement', window.SVGElement);
installGlobal('Node', window.Node);
installGlobal('NodeFilter', window.NodeFilter);
installGlobal('MutationObserver', window.MutationObserver);
installGlobal('CustomEvent', window.CustomEvent);
installGlobal('DOMRect', window.DOMRect);
installGlobal('Event', window.Event);
installGlobal('KeyboardEvent', window.KeyboardEvent);
installGlobal('MouseEvent', window.MouseEvent);
installGlobal('getComputedStyle', window.getComputedStyle.bind(window));
installGlobal('requestAnimationFrame', window.requestAnimationFrame.bind(window));
installGlobal('cancelAnimationFrame', window.cancelAnimationFrame.bind(window));
installGlobal('ResizeObserver', ResizeObserverStub);
installGlobal('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.tsx');
const { MultilinePasteConfirmHost } = await import('./MultilinePasteConfirmDialog.tsx');
const { requestMultilinePasteConfirm } = await import('../../application/state/multilinePasteConfirmStore.ts');
const terminalInput = window.document.createElement('textarea');
window.document.body.appendChild(terminalInput);
const root = createRoot(window.document.getElementById('root')!);
try {
await act(async () => root.render(<I18nProvider locale="en"><MultilinePasteConfirmHost /></I18nProvider>));
for (const [label, action] of [['Send', 'send'], ['Send line by line', 'line-by-line'], ['Cancel', 'cancel']]) {
terminalInput.focus();
let decision!: ReturnType<typeof requestMultilinePasteConfirm>;
await act(async () => {
decision = requestMultilinePasteConfirm({
text: 'show run\nshow version', lineCount: 2, charCount: 21,
onClose: () => terminalInput.focus(),
});
});
assert.ok(window.document.querySelector('[role="dialog"]'));
const button = Array.from(window.document.querySelectorAll('button')).find(item => item.textContent === label);
assert.ok(button);
await act(async () => button.click());
await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
assert.deepEqual(await decision, { action, text: 'show run\nshow version' });
assert.equal(window.document.querySelector('[role="dialog"]'), null);
assert.equal(window.document.activeElement, terminalInput, `${label} should restore focus`);
}
} finally {
await act(async () => root.unmount());
window.close();
for (const [key, descriptor] of previousGlobals) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
@@ -0,0 +1,88 @@
import React, { useState } from "react";
import { useSyncExternalStore } from "react";
import { useI18n } from "../../application/i18n/I18nProvider";
import {
getPendingMultilinePasteConfirm,
respondMultilinePasteConfirm,
subscribeMultilinePasteConfirm,
} from "../../application/state/multilinePasteConfirmStore";
import { Button } from "../ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
import { Textarea } from "../ui/textarea";
import type { MultilinePasteConfirmRequest } from "../../application/state/multilinePasteConfirmStore";
/**
* Always-mounted host: renders the multi-line paste confirmation dialog while
* a paste request is pending (#3398). The preview is editable — the edited
* content is what actually gets sent.
*/
export const MultilinePasteConfirmHost: React.FC = () => {
const request = useSyncExternalStore(
subscribeMultilinePasteConfirm,
getPendingMultilinePasteConfirm,
getPendingMultilinePasteConfirm,
);
if (!request) return null;
return <MultilinePasteConfirmDialog key={request.id} request={request} />;
};
const MultilinePasteConfirmDialog: React.FC<{ request: MultilinePasteConfirmRequest }> = ({
request,
}) => {
const { t } = useI18n();
const [previewText, setPreviewText] = useState(request.text);
const respond = (action: "send" | "line-by-line") =>
respondMultilinePasteConfirm(action, previewText);
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) respondMultilinePasteConfirm("cancel");
}}
>
<DialogContent
className="sm:max-w-[520px]"
onCloseAutoFocus={(event) => {
if (request.onClose) {
event.preventDefault();
request.onClose();
}
}}
>
<DialogHeader>
<DialogTitle>{t("terminal.pasteConfirm.title")}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{t("terminal.pasteConfirm.summary", {
lines: request.lineCount,
chars: request.charCount,
})}
</p>
<div className="space-y-1">
<label className="text-xs text-muted-foreground">
{t("terminal.pasteConfirm.preview")}
</label>
<Textarea
value={previewText}
onChange={(e) => setPreviewText(e.target.value)}
className="max-h-64 min-h-32 font-mono text-xs"
spellCheck={false}
autoFocus
/>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => respondMultilinePasteConfirm("cancel")}>
{t("terminal.pasteConfirm.cancel")}
</Button>
<Button variant="outline" onClick={() => respond("line-by-line")}>
{t("terminal.pasteConfirm.sendLineByLine")}
</Button>
<Button onClick={() => respond("send")}>{t("terminal.pasteConfirm.send")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -17,3 +17,15 @@ test("server stats stay subscribed while the terminal is in the background", ()
assert.doesNotMatch(source, /usePaneVisible/);
assert.doesNotMatch(source, /isVisible,/);
});
test("GPU chip only renders when the remote reports GPU utilization", () => {
const source = readFileSync(new URL("./TerminalServerStats.tsx", import.meta.url), "utf8");
// Conditional render — hosts without nvidia-smi must not show an empty GPU chip.
assert.match(source, /\{serverStats\.gpu !== null && \(/);
// Sits directly after the CPU chip, before the memory chip.
assert.match(
source,
/terminal\.serverStats\.gpu[\s\S]{0,2000}terminal\.serverStats\.memory/,
);
});
+24 -1
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { Activity, ArrowDownToLine, ArrowUpFromLine, Cpu, HardDrive, MemoryStick } from 'lucide-react';
import { Activity, ArrowDownToLine, ArrowUpFromLine, Cpu, Gpu, HardDrive, MemoryStick } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { cn } from '../../lib/utils';
@@ -122,6 +122,29 @@ export const TerminalServerStats: React.FC<TerminalServerStatsProps> = ({
</div>
</HoverCardContent>
</HoverCard>
{/* GPU — only rendered when the remote reports NVIDIA GPU data (Linux nvidia-smi) */}
{serverStats.gpu !== null && (
<div
className="flex items-center gap-0.5 min-w-0 shrink"
aria-label={t("terminal.serverStats.gpu")}
title={
[
serverStats.gpuName,
serverStats.gpuMemUsed !== null && serverStats.gpuMemTotal !== null && serverStats.gpuMemTotal > 0
? `VRAM ${(serverStats.gpuMemUsed / 1024).toFixed(1)}/${(serverStats.gpuMemTotal / 1024).toFixed(1)}G`
: null,
].filter(Boolean).join(' · ') || undefined
}
>
<Gpu size={10} className="flex-shrink-0" />
<span className="truncate">
{serverStats.gpu}%
{serverStats.gpuMemUsed !== null && serverStats.gpuMemTotal !== null && serverStats.gpuMemTotal > 0
? ` (${(serverStats.gpuMemUsed / 1024).toFixed(1)}/${(serverStats.gpuMemTotal / 1024).toFixed(1)}G)`
: ''}
</span>
</div>
)}
{/* Memory with HoverCard for htop-style bar and top processes */}
<HoverCard openDelay={200} closeDelay={100}>
<HoverCardTrigger asChild>
+8 -2
View File
@@ -108,14 +108,14 @@ test("marks manual session log button active while logging", () => {
);
});
test("hides SFTP for local terminal sessions", () => {
test("shows SFTP for local terminal sessions", () => {
const markup = renderToolbar({
...sshHost,
id: "local-1",
protocol: "local",
});
assert.equal(markup.includes('aria-label="Open SFTP"'), false);
assert.equal(markup.includes('aria-label="Open SFTP"'), true);
});
test("hides SSH history for plugin terminal sessions", () => {
@@ -192,3 +192,9 @@ test("compact scripts popover hosts bulk-delete confirm outside the popover", ()
false,
);
});
for (const host of [serialHost, pluginHost]) {
test(`hides SFTP for ${host.protocol} sessions`, () => {
assert.equal(renderToolbar(host).includes('aria-label="Open SFTP"'), false);
});
}
+1 -1
View File
@@ -212,7 +212,7 @@ export const TerminalToolbar: React.FC<TerminalToolbarProps> = ({
// (test daemons, forwarded endpoints) still have a real backend
// decoder we can drive.
const encodingSwitchSupported = !isLocalTerminal && !isMoshSession && !isEtSession && !isPluginConnection;
const hidesSftp = isLocalTerminal || isSerialTerminal || isPluginConnection;
const hidesSftp = isSerialTerminal || isPluginConnection;
const historySupported =
!!onOpenHistory && !isLocalTerminal && !isSerialTerminal && !isPluginConnection && host?.protocol !== 'telnet';
const unavailableYmodemSendLabel = `${t('terminal.toolbar.sendYmodem')} - ${t('terminal.toolbar.availableAfterConnect')}`;
@@ -229,7 +229,11 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
if (frameId) cancelAnimationFrame(frameId);
observer?.disconnect();
};
}, [hoveredIndex, selectedIndex, subDirPanels, suggestions, visible]);
// hoveredIndex intentionally not a dependency: the detail panel below has
// a fixed box (width/height), so hovering cannot change the wrapper's
// size — re-measuring per hover would only feed the resize back into the
// position clamp and jitter the popup under the pointer (#3426).
}, [selectedIndex, subDirPanels, suggestions, visible]);
// Dismiss popup when clicking outside
useEffect(() => {
@@ -273,6 +277,16 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
const setMayShowDetailPanel = suggestions.some(
(s) => s.source !== "path" && Boolean(s.description && s.description.length > 0),
);
// The tooltip is only visible for the hovered/selected non-path row, but it
// is MOUNTED for the whole set with a fixed box (width = the reserved
// DETAIL_PANEL_MAX_WIDTH, height = the reserved estimatedDetailHeight) and
// toggled with visibility instead of mounting/unmounting. A hover-driven
// size change would flow through the measured-size clamp below and move the
// popup under a stationary pointer, which flips the hovered row and
// self-oscillates — the violent mousemove jitter from #3426.
const detailVisible = Boolean(
showDetail && detailItem && detailItem.source !== "path",
);
const fixedLeft = anchorViewport.left;
const fixedLineTop = anchorViewport.top;
@@ -281,6 +295,7 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
const viewportPadding = 8;
const anchorGap = 8;
const clampViewport = resolveAutocompleteClampViewport(containerRef?.current ?? null);
const availableWidth = Math.max(0, clampViewport.width - viewportPadding * 2);
const estimatedPopupHeight = Math.min(maxHeight, suggestions.length * 28 + 8);
// Reserve the detail height for the whole set (not the hovered row) so the
// chosen direction/height stays stable while hovering.
@@ -322,6 +337,10 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
});
const renderUpward = placement.renderUpward;
const effectiveMaxHeight = placement.maxHeight;
// Fixed tooltip height: matches the 96px the placement pass reserved
// (estimatedDetailHeight), capped by the space actually available so the
// mounted-but-hidden panel can never push the wrapper past the clamp.
const detailPanelHeight = Math.max(0, Math.min(96, effectiveMaxHeight));
const anchoredTop = placement.top;
const clampedLeft = placement.left;
const finalGeometry = measuredSize
@@ -360,13 +379,16 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
top: `${finalGeometry.top}px`,
zIndex: 10000,
display: "flex",
maxWidth: `${availableWidth}px`,
alignItems: renderUpward ? "flex-end" : "flex-start",
gap: "4px",
pointerEvents: "auto", // Re-enable on popup itself (parent is pointer-events-none)
}}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
// Hit-test transparent: the wrapper's box spans the whole assembly,
// including the mounted-but-hidden detail reserve, so leaving it
// auto would make the transparent area around a short list a dead
// zone (clicks there preventDefault + stopPropagation and never
// reach the terminal or the outside-dismiss handler). Children
// re-enable pointer events individually. (#3427 review)
pointerEvents: "none",
}}
>
{/* Main suggestion list */}
@@ -376,12 +398,19 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
style={{
...sharedBoxStyle,
maxHeight: `${effectiveMaxHeight}px`,
minWidth: "180px",
minWidth: `${Math.min(180, setMayShowDetailPanel ? availableWidth / 2 : availableWidth)}px`,
maxWidth: "400px",
overflowY: "auto",
overflowX: "hidden",
padding: "4px 0",
userSelect: "none",
pointerEvents: "auto",
}}
// Keep the terminal focused when clicking the list's padding or
// scrollbar (row clicks handle this themselves).
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
{suggestions.map((suggestion, index) => {
@@ -517,6 +546,13 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
padding: "4px 0",
userSelect: "none",
alignSelf: "flex-start",
pointerEvents: "auto",
}}
// Keep the terminal focused when clicking the panel's padding or
// scrollbar (row clicks handle this themselves).
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
{panel.entries.map((entry, idx) => {
@@ -559,51 +595,70 @@ const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
</div>
))}
{/* Detail tooltip panel — shows full description for non-path items */}
{showDetail && detailItem && detailItem.source !== "path" && (
{/* Detail tooltip panel — shows full description for non-path items.
Mounted for the whole set with a fixed, hover-independent box and
toggled via visibility so hovering rows can never resize (and thus
re-clamp the position of) the popup (#3426). */}
{setMayShowDetailPanel && (
<div
style={{
...sharedBoxStyle,
padding: "10px 12px",
maxWidth: "280px",
minWidth: "160px",
width: "280px",
minWidth: 0,
height: `${detailPanelHeight}px`,
// The width remains independent of content/hover, but can shrink
// with the assembly inside a narrow terminal pane.
flexShrink: 1,
// Bound the tooltip too: a long multi-line snippet description must
// scroll, not push the panel past the viewport edge (#1202).
maxHeight: `${effectiveMaxHeight}px`,
overflowY: "auto",
alignSelf: renderUpward ? "flex-end" : "flex-start",
visibility: detailVisible ? "visible" : "hidden",
// visibility:hidden already skips hit testing, but keep the
// hidden reserve explicitly non-interactive so the mounted
// panel can never swallow clicks meant for the terminal.
pointerEvents: detailVisible ? "auto" : "none",
}}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "6px" }}>
<span style={{ fontWeight: 600, fontSize: "13px" }}>{detailItem.displayText}</span>
<span style={{
fontSize: "10px",
color: SOURCE_LABELS[detailItem.source].fallbackColor,
padding: "1px 5px",
borderRadius: "3px",
backgroundColor: `${SOURCE_LABELS[detailItem.source].fallbackColor}15`,
}}>
{SOURCE_LABELS[detailItem.source].fullLabel}
</span>
</div>
<div style={{ fontSize: "12px", color: dimTextColor, lineHeight: "1.5", wordBreak: "break-word" }}>
{detailItem.source === "snippet" ? (
<pre
style={{
margin: 0,
whiteSpace: "pre-wrap",
wordBreak: "break-word",
fontFamily: "var(--terminal-font, monospace)",
fontSize: "11px",
lineHeight: 1.4,
}}
>
{detailItem.description}
</pre>
) : (
detailItem.description
)}
</div>
{detailVisible && detailItem && (
<>
<div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "6px" }}>
<span style={{ fontWeight: 600, fontSize: "13px" }}>{detailItem.displayText}</span>
<span style={{
fontSize: "10px",
color: SOURCE_LABELS[detailItem.source].fallbackColor,
padding: "1px 5px",
borderRadius: "3px",
backgroundColor: `${SOURCE_LABELS[detailItem.source].fallbackColor}15`,
}}>
{SOURCE_LABELS[detailItem.source].fullLabel}
</span>
</div>
<div style={{ fontSize: "12px", color: dimTextColor, lineHeight: "1.5", wordBreak: "break-word" }}>
{detailItem.source === "snippet" ? (
<pre
style={{
margin: 0,
whiteSpace: "pre-wrap",
wordBreak: "break-word",
fontFamily: "var(--terminal-font, monospace)",
fontSize: "11px",
lineHeight: 1.4,
}}
>
{detailItem.description}
</pre>
) : (
detailItem.description
)}
</div>
</>
)}
</div>
)}
</div>
@@ -1,15 +1,17 @@
import type { Terminal as XTerm } from "@xterm/xterm";
import { useCallback, useRef } from "react";
import type { RefObject } from "react";
import { requestMultilinePasteConfirm } from "../../../application/state/multilinePasteConfirmStore";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { logger } from "../../../lib/logger";
import { pasteTextIntoTerminal } from "../runtime/terminalUserPaste";
import type { MultilinePasteConfirmGate } from "../terminalClipboardPaste";
import type { TerminalBroadcastInputOptions } from "../terminalHelpers";
import { clearTerminalViewportAndSyncPty } from "../clearTerminalViewport";
import {
handleRemoteClipboardImageUpload,
type RemoteClipboardImageUploadResult,
} from "../clipboardImagePaste";
import { handleTerminalClipboardPaste } from "../terminalClipboardPaste";
import { handleTerminalClipboardPaste, pasteTextWithMultilineConfirm } from "../terminalClipboardPaste";
import { pulseCopyOnSelectUserCommand } from "../copyOnSelect";
import { getTerminalSelectionForClipboard } from "../normalizeTerminalSelection";
import {
@@ -27,7 +29,9 @@ type BroadcastPasteRefs = {
sourceSessionId: string;
sessionRef: RefObject<string | null>;
isBroadcastEnabledRef?: RefObject<boolean | undefined>;
onBroadcastInputRef?: RefObject<((data: string, sourceSessionId: string) => void) | undefined>;
onBroadcastInputRef?: RefObject<
((data: string, sourceSessionId: string, options?: TerminalBroadcastInputOptions) => void) | undefined
>;
passwordPromptActiveRef?: RefObject<boolean | undefined>;
};
@@ -40,6 +44,7 @@ export const broadcastTerminalPasteData = (
onBroadcastInputRef,
passwordPromptActiveRef,
}: BroadcastPasteRefs,
options?: TerminalBroadcastInputOptions,
): boolean => {
if (
passwordPromptActiveRef?.current !== true
@@ -47,7 +52,7 @@ export const broadcastTerminalPasteData = (
&& isBroadcastEnabledRef?.current
&& onBroadcastInputRef?.current
) {
onBroadcastInputRef.current(data, sourceSessionId);
onBroadcastInputRef.current(data, sourceSessionId, options);
return true;
}
return false;
@@ -66,6 +71,7 @@ export const useTerminalContextActions = ({
isLocalConnection,
supportsRemoteImagePaste,
autoUploadClipboardImageOnPasteRef,
multilinePasteConfirmRef,
clearWipesScrollbackRef,
normalizeTextOnCopyRef,
terminalBackend,
@@ -80,12 +86,16 @@ export const useTerminalContextActions = ({
onHasSelectionChange?: (hasSelection: boolean) => void;
scrollOnPasteRef?: RefObject<boolean>;
isBroadcastEnabledRef?: RefObject<boolean | undefined>;
onBroadcastInputRef?: RefObject<((data: string, sourceSessionId: string) => void) | undefined>;
onBroadcastInputRef?: RefObject<
((data: string, sourceSessionId: string, options?: TerminalBroadcastInputOptions) => void) | undefined
>;
passwordPromptActiveRef?: RefObject<boolean | undefined>;
isLocalConnection: boolean;
supportsRemoteImagePaste: boolean;
/** When true, paste auto-uploads a clipboard image (remote sessions only). */
autoUploadClipboardImageOnPasteRef?: RefObject<boolean | undefined>;
/** Multi-line paste confirmation gate (#3398); undefined keeps confirm off. */
multilinePasteConfirmRef?: RefObject<Omit<MultilinePasteConfirmGate, "requestConfirm"> | undefined>;
clearWipesScrollbackRef?: RefObject<boolean | undefined>;
/** When false, copy uses raw getSelection(). Default true when unset. */
normalizeTextOnCopyRef?: RefObject<boolean | undefined>;
@@ -126,14 +136,14 @@ export const useTerminalContextActions = ({
}
}, [sessionName, t, termRef]);
const broadcastUserPasteData = useCallback((data: string) => {
const broadcastUserPasteData = useCallback((data: string, options?: TerminalBroadcastInputOptions) => {
return broadcastTerminalPasteData(data, {
sourceSessionId,
sessionRef,
isBroadcastEnabledRef,
onBroadcastInputRef,
passwordPromptActiveRef,
});
}, options);
}, [isBroadcastEnabledRef, onBroadcastInputRef, passwordPromptActiveRef, sessionRef, sourceSessionId]);
const onCopy = useCallback(() => {
@@ -161,6 +171,10 @@ export const useTerminalContextActions = ({
autoUploadClipboardImage:
supportsRemoteImagePaste && autoUploadClipboardImageOnPasteRef?.current === true,
clipboardImageBridge: bridge ?? undefined,
confirmMultilinePaste: multilinePasteConfirmRef?.current
? { ...multilinePasteConfirmRef.current, requestConfirm: requestMultilinePasteConfirm }
: undefined,
getCurrentSessionId: () => sessionRef.current,
getRemoteCwd,
isLocalConnection,
isSensitiveInput: () => passwordPromptActiveRef?.current === true,
@@ -179,6 +193,7 @@ export const useTerminalContextActions = ({
}, [
autoUploadClipboardImageOnPasteRef,
broadcastUserPasteData,
multilinePasteConfirmRef,
getRemoteCwd,
isLocalConnection,
onClipboardImageUploadResult,
@@ -221,7 +236,7 @@ export const useTerminalContextActions = ({
terminalBackend,
]);
const onPasteSelection = useCallback(() => {
const onPasteSelection = useCallback(async () => {
const term = termRef.current;
if (!term) return;
const selection = getHistoryPreviewSelectionFromRoot(term.element?.parentElement)
@@ -232,11 +247,33 @@ export const useTerminalContextActions = ({
if (!selection || !sessionRef.current) return;
requestHistoryPreviewHide(term.element?.parentElement);
term.focus();
pasteTextIntoTerminal(term, selection, {
scrollOnPaste: scrollOnPasteRef?.current ?? false,
// Route through the multi-line paste confirmation gate (#3398) so a
// selected multi-line region cannot be sent without review, just like
// the clipboard paste path.
await pasteTextWithMultilineConfirm(selection, {
confirmMultilinePaste: multilinePasteConfirmRef?.current
? { ...multilinePasteConfirmRef.current, requestConfirm: requestMultilinePasteConfirm }
: undefined,
getCurrentSessionId: () => sessionRef.current,
isSensitiveInput: () => passwordPromptActiveRef?.current === true,
onPasteData: broadcastUserPasteData,
scrollOnPaste: scrollOnPasteRef?.current ?? false,
scrollToBottomAfterProgrammaticInput,
sessionId: sessionRef.current,
terminalBackend,
term,
});
}, [broadcastUserPasteData, normalizeTextOnCopyRef, sessionRef, termRef, scrollOnPasteRef]);
}, [
broadcastUserPasteData,
multilinePasteConfirmRef,
normalizeTextOnCopyRef,
passwordPromptActiveRef,
scrollToBottomAfterProgrammaticInput,
sessionRef,
termRef,
scrollOnPasteRef,
terminalBackend,
]);
const onSelectAll = useCallback(() => {
const term = termRef.current;
@@ -2,10 +2,12 @@ import type { Terminal as XTerm } from "@xterm/xterm";
import type React from "react";
import { useEffect } from "react";
import { requestMultilinePasteConfirm } from "../../../application/state/multilinePasteConfirmStore";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { logger } from "../../../lib/logger";
import type { TerminalSession } from "../../../types";
import type { RemoteClipboardImageUploadResult } from "../clipboardImagePaste";
import type { MultilinePasteConfirmGate } from "../terminalClipboardPaste";
import { handleTerminalClipboardPaste } from "../terminalClipboardPaste";
interface UseTerminalFilePasteOptions {
@@ -18,11 +20,13 @@ interface UseTerminalFilePasteOptions {
};
isSensitiveInput?: () => boolean;
scrollOnPasteRef?: React.RefObject<boolean>;
onPasteData?: (data: string) => boolean | void;
onPasteData?: (data: string, options?: { lineDelayMs?: number }) => boolean | void;
scrollToBottomAfterProgrammaticInput: (data: string) => void;
containerRef: React.RefObject<HTMLDivElement | null>;
/** Remote sessions only: auto-upload a clipboard image on paste. */
autoUploadClipboardImage?: boolean;
/** Multi-line paste confirmation gate (#3398); undefined keeps confirm off. */
multilinePasteConfirmRef?: React.RefObject<Omit<MultilinePasteConfirmGate, "requestConfirm"> | undefined>;
getRemoteCwd?: () => Promise<string | null | undefined>;
onClipboardImageUploadResult?: (result: RemoteClipboardImageUploadResult) => void;
}
@@ -39,6 +43,7 @@ export function useTerminalFilePaste({
scrollToBottomAfterProgrammaticInput,
containerRef,
autoUploadClipboardImage = false,
multilinePasteConfirmRef,
getRemoteCwd,
onClipboardImageUploadResult,
}: UseTerminalFilePasteOptions) {
@@ -55,7 +60,15 @@ export function useTerminalFilePaste({
autoUploadClipboardImage && !isLocalConnection && !!bridge?.readClipboardImage;
const canHandleLocalPaste =
isLocalConnection && !!(bridge?.readClipboardFiles || bridge?.hasClipboardImage);
if (!wantsImageUpload && !canHandleLocalPaste) return;
// The multi-line paste confirmation (#3398) must also intercept plain
// remote keyboard pastes; otherwise xterm's default handler would send
// the lines without the safety dialog when neither image upload nor
// local file handling applies.
const shouldInterceptPaste =
wantsImageUpload
|| canHandleLocalPaste
|| !!multilinePasteConfirmRef?.current?.enabled;
if (!shouldInterceptPaste) return;
// ⚡ Must call preventDefault SYNCHRONOUSLY — the event lifecycle
// is synchronous; calling it after an await is too late and the
@@ -63,6 +76,12 @@ export function useTerminalFilePaste({
event.preventDefault();
event.stopPropagation();
// Capture the pasted text synchronously: navigator.clipboard.readText()
// can be rejected (permissions / platform quirks) even though the event
// already carries the text, so prefer it and only fall back to the
// async clipboard API when the event has no text data.
const eventText = event.clipboardData?.getData("text/plain") ?? "";
void (async () => {
try {
const term = termRef.current;
@@ -71,11 +90,21 @@ export function useTerminalFilePaste({
bridge,
autoUploadClipboardImage: wantsImageUpload,
clipboardImageBridge: bridge ?? undefined,
confirmMultilinePaste: multilinePasteConfirmRef?.current
? { ...multilinePasteConfirmRef.current, requestConfirm: requestMultilinePasteConfirm }
: undefined,
// The confirm dialog can outlive the captured session (disconnect
// / auto-reconnect), so revalidate against the live session ref
// like the context-menu and shortcut callers do.
getCurrentSessionId: () => sessionRef.current,
getRemoteCwd,
isLocalConnection,
isSensitiveInput,
onClipboardImageUploadResult,
readClipboardText: () => navigator.clipboard.readText(),
readClipboardText: async () => {
if (eventText) return eventText;
return navigator.clipboard.readText();
},
scrollOnPaste: scrollOnPasteRef?.current ?? false,
onPasteData,
sessionId: sessionRef.current,
@@ -96,6 +125,7 @@ export function useTerminalFilePaste({
}, [
autoUploadClipboardImage,
containerRef,
multilinePasteConfirmRef,
getRemoteCwd,
isLocalConnection,
isSensitiveInput,
@@ -0,0 +1,419 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createTerminalSessionStarters } from "./createTerminalSessionStarters";
const noop = () => undefined;
const ENCRYPTED_CREDENTIAL_PLACEHOLDER = "enc:v1:djEwdGVzdAAAAAAAAAAAAAAAAA==";
const buildBackend = (overrides: Partial<Record<string, unknown>> = {}) => ({
backendAvailable: () => true,
telnetAvailable: () => true,
moshAvailable: () => true,
localAvailable: () => true,
serialAvailable: () => true,
execAvailable: () => true,
startSSHSession: async () => "ssh-session",
startTelnetSession: async () => "telnet-session",
startMoshSession: async () => "mosh-session",
startLocalSession: async () => "local-session",
startSerialSession: async () => "serial-session",
execCommand: async () => ({}),
onSessionData: () => noop,
onSessionExit: () => noop,
onChainProgress: () => noop,
writeToSession: noop,
resizeSession: noop,
...overrides,
});
const buildCtx = (backend: unknown, extra: Record<string, unknown> = {}) => ({
host: {
id: "serial-1",
label: "Serial: ttyUSB0",
hostname: "/dev/ttyUSB0",
protocol: "serial",
charset: "UTF-8",
},
keys: [],
identities: [],
sessionId: "session-1",
serialConfig: {
path: "/dev/ttyUSB0",
baudRate: 115200,
dataBits: 8,
stopBits: 1,
parity: "none",
flowControl: "none",
},
terminalSettings: {},
terminalBackend: backend,
sessionRef: { current: null },
hasConnectedRef: { current: false },
hasRunStartupCommandRef: { current: false },
disposeDataRef: { current: null },
disposeExitRef: { current: null },
fitAddonRef: { current: null },
serializeAddonRef: { current: null },
pendingAuthRef: { current: null },
bootEpochRef: { current: 0 },
updateStatus: noop,
setStatus: noop,
setError: noop,
setNeedsAuth: noop,
setAuthRetryMessage: noop,
setAuthPassword: noop,
setProgressLogs: noop,
setProgressValue: noop,
...extra,
});
const term = {
cols: 120,
rows: 32,
write: noop,
writeln: noop,
scrollToBottom: noop,
};
test("startSerial passes saved host credentials for auto-login", async () => {
let capturedOptions: Record<string, unknown> | null = null;
const backend = buildBackend({
startSerialSession: async (options: Record<string, unknown>) => {
capturedOptions = options;
return "serial-session";
},
});
await createTerminalSessionStarters(buildCtx(backend, {
host: {
id: "serial-1",
label: "Serial: ttyUSB0",
hostname: "/dev/ttyUSB0",
protocol: "serial",
username: "admin",
password: "secret",
},
}) as never).startSerial(term as never);
assert.ok(capturedOptions);
assert.equal(capturedOptions.username, "admin");
assert.equal(capturedOptions.password, "secret");
});
test("startSerial omits credentials when none are saved", async () => {
let capturedOptions: Record<string, unknown> | null = null;
const backend = buildBackend({
startSerialSession: async (options: Record<string, unknown>) => {
capturedOptions = options;
return "serial-session";
},
});
await createTerminalSessionStarters(buildCtx(backend) as never).startSerial(term as never);
assert.ok(capturedOptions);
assert.equal(capturedOptions.username, undefined);
assert.equal("password" in capturedOptions, false);
});
test("startSerial rejects an undecryptable saved password instead of partial auto-login", async () => {
let started = false;
const errors: (string | null)[] = [];
const backend = buildBackend({
startSerialSession: async () => {
started = true;
return "serial-session";
},
});
await createTerminalSessionStarters(buildCtx(backend, {
host: {
id: "serial-1",
hostname: "/dev/ttyUSB0",
protocol: "serial",
username: "admin",
password: ENCRYPTED_CREDENTIAL_PLACEHOLDER,
},
setError: (message: string | null) => errors.push(message),
}) as never).startSerial(term as never);
// A saved username paired with an undecryptable password must not start a
// partial auto-login; ask the user to re-enter the credential instead.
assert.equal(started, false);
assert.ok(errors[0]);
});
test("startSerial waits for auto-login before running the startup command", async () => {
const writtenCommands: string[] = [];
const executedCommands: string[] = [];
let autoLoginComplete: ((evt: { sessionId: string }) => void) | null = null;
let resolveCommand: (() => void) | null = null;
const commandWritten = new Promise<void>((resolve) => {
resolveCommand = resolve;
});
const backend = buildBackend({
startSerialSession: async () => "serial-session",
onTelnetAutoLoginComplete: (
_sessionId: string,
cb: (evt: { sessionId: string }) => void,
) => {
autoLoginComplete = cb;
return noop;
},
onTelnetAutoLoginCancelled: () => noop,
writeToSession: (_sessionId: string, data: string) => {
writtenCommands.push(data);
resolveCommand?.();
},
});
const ctx = buildCtx(backend, {
host: {
id: "serial-1",
hostname: "/dev/ttyUSB0",
protocol: "serial",
username: "admin",
password: "secret",
startupCommand: "show version",
},
onCommandExecuted: (command: string) => {
executedCommands.push(command);
},
});
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
assert.ok(autoLoginComplete);
// The startup command must not fire on the default 600ms delay while the
// main-process auto-login is still answering prompts.
await new Promise((resolve) => setTimeout(resolve, 700));
assert.deepEqual(writtenCommands, []);
assert.deepEqual(executedCommands, []);
autoLoginComplete?.({ sessionId: "session-1" });
await Promise.race([
commandWritten,
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timed out waiting for startup command")), 1000),
),
]);
assert.deepEqual(writtenCommands, ["show version\r"]);
assert.deepEqual(executedCommands, ["show version"]);
});
test("startSerial schedules the startup command when auto-login completes before attach", async () => {
const writtenCommands: string[] = [];
const executedCommands: string[] = [];
let autoLoginComplete: ((evt: { sessionId: string }) => void) | null = null;
const backend = buildBackend({
startSerialSession: async () => {
// The login exchange completes before the startSerialSession promise
// resolves, so the completion event fires while the session is still
// unattached. The startup command must be scheduled after attach, not
// dropped against the unset session ref.
autoLoginComplete?.({ sessionId: "session-1" });
return "serial-session";
},
onTelnetAutoLoginComplete: (
_sessionId: string,
cb: (evt: { sessionId: string }) => void,
) => {
autoLoginComplete = cb;
return noop;
},
onTelnetAutoLoginCancelled: () => noop,
writeToSession: (_sessionId: string, data: string) => {
writtenCommands.push(data);
},
});
const ctx = buildCtx(backend, {
host: {
id: "serial-1",
hostname: "/dev/ttyUSB0",
protocol: "serial",
username: "admin",
password: "secret",
startupCommand: "show version",
},
onCommandExecuted: (command: string) => {
executedCommands.push(command);
},
});
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
await Promise.race([
new Promise<void>((resolve) => {
const tick = () => {
if (writtenCommands.length > 0) {
resolve();
return;
}
setTimeout(tick, 20);
};
tick();
}),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timed out waiting for startup command")), 2000),
),
]);
assert.deepEqual(writtenCommands, ["show version\r"]);
assert.deepEqual(executedCommands, ["show version"]);
});
test("startSerial runs the startup command without waiting when no credentials are saved", async () => {
const writtenCommands: string[] = [];
const backend = buildBackend({
startSerialSession: async () => "serial-session",
writeToSession: (_sessionId: string, data: string) => {
writtenCommands.push(data);
},
});
const ctx = buildCtx(backend, {
host: {
id: "serial-1",
hostname: "/dev/ttyUSB0",
protocol: "serial",
startupCommand: "show version",
},
});
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
await Promise.race([
new Promise<void>((resolve) => {
const tick = () => {
if (writtenCommands.length > 0) {
resolve();
return;
}
setTimeout(tick, 20);
};
tick();
}),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timed out waiting for startup command")), 2000),
),
]);
assert.deepEqual(writtenCommands, ["show version\r"]);
});
test("startSerial does not arm the fallback when auto-login is cancelled before attach", async () => {
const writtenCommands: string[] = [];
let autoLoginCancelled: ((evt: { sessionId: string }) => void) | null = null;
const backend = buildBackend({
startSerialSession: async () => {
// A stalled exchange (e.g. only a username is saved and the device moves
// on to a Password prompt the detector cannot answer) cancels auto-login
// before the startSerialSession promise resolves.
autoLoginCancelled?.({ sessionId: "session-1" });
return "serial-session";
},
onTelnetAutoLoginComplete: () => noop,
onTelnetAutoLoginCancelled: (
_sessionId: string,
cb: (evt: { sessionId: string }) => void,
) => {
autoLoginCancelled = cb;
return noop;
},
writeToSession: (_sessionId: string, data: string) => {
writtenCommands.push(data);
},
});
const ctx = buildCtx(backend, {
host: {
id: "serial-1",
hostname: "/dev/ttyUSB0",
protocol: "serial",
username: "admin",
startupCommand: "show version",
},
});
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
assert.ok(autoLoginCancelled);
// The 65s quiet-device fallback must not be armed after the cancellation,
// or it would type the startup command into the pending password prompt.
await new Promise((resolve) => setTimeout(resolve, 700));
assert.deepEqual(writtenCommands, []);
});
for (const runMode of ['paste', 'lineDelay', 'noAutoRun']) {
test(`serial reconnect discards the previous delayed startup command (${runMode})`, async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const writes: string[] = [];
const completions: Array<(evt: {sessionId: string; bootEpoch: number}) => void> = [];
const backend = buildBackend({
startSerialSession: async () => 'session-1',
onTelnetAutoLoginComplete: (_id: string, cb: typeof completions[number]) => {
completions.push(cb);
return noop;
},
onTelnetAutoLoginCancelled: () => noop,
writeToSession: (_id: string, data: string) => writes.push(data),
});
const ctx = buildCtx(backend, {
host: { id: 'serial-1', protocol: 'serial', username: 'admin', startupCommand: 'show version', startupCommandRunMode: runMode === 'lineDelay' ? 'lineDelay' : 'paste' },
terminalSettings: { startupCommandDelayMs: 100 },
noAutoRun: runMode === 'noAutoRun',
});
const starters = createTerminalSessionStarters(ctx as never);
await starters.startSerial(term as never);
completions[0]({sessionId: 'session-1', bootEpoch: 0});
ctx.bootEpochRef.current = 1;
ctx.hasRunStartupCommandRef.current = false;
await starters.startSerial(term as never);
t.mock.timers.tick(100);
assert.deepEqual(writes, []);
completions[1]({sessionId: 'session-1', bootEpoch: 1});
t.mock.timers.tick(100);
assert.deepEqual(writes, [runMode === 'noAutoRun' ? 'show version' : 'show version\r']);
});
}
test('serial quick connect does not synthesize auto-login credentials', async () => {
const { createSerialTerminalSession } = await import('../../../application/state/sessionFactories');
const { resolveTerminalSessionHost } = await import('../../../domain/terminalHostResolution');
const session = createSerialTerminalSession('quick', {path: '/dev/ttyUSB0', baudRate: 115200});
const host = resolveTerminalSessionHost({session, hosts: [], groupConfigs: [], proxyProfiles: [], localOs: 'macos'});
let options: Record<string, unknown> = {};
const backend = buildBackend({startSerialSession: async (value: Record<string, unknown>) => {options = value; return 'quick';}});
await createTerminalSessionStarters(buildCtx(backend, {host}) as never).startSerial(term as never);
assert.equal(options.username, undefined);
assert.equal(options.password, undefined);
});
for (const sleepBeforeCompletion of [true, false]) {
test(`serial startup survives tab sleep (before completion: ${sleepBeforeCompletion})`, async (t) => {
t.mock.timers.enable({apis: ['setTimeout']});
const writes: string[] = [];
let complete: (evt: {sessionId: string; bootEpoch: number}) => void = noop;
const backend = buildBackend({
startSerialSession: async () => 'session-1',
onTelnetAutoLoginComplete: (_id: string, cb: typeof complete) => { complete = cb; return noop; },
onTelnetAutoLoginCancelled: () => noop,
writeToSession: (_id: string, data: string) => writes.push(data),
});
const isBootActiveRef = {current: true};
const ctx = buildCtx(backend, {
host: {id: 'serial-1', protocol: 'serial', username: 'admin', startupCommand: 'show version'},
terminalSettings: {startupCommandDelayMs: 100}, isBootActiveRef,
});
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
if (sleepBeforeCompletion) isBootActiveRef.current = false;
complete({sessionId: 'session-1', bootEpoch: 0});
isBootActiveRef.current = false;
t.mock.timers.tick(100);
assert.deepEqual(writes, ['show version\r']);
});
}
@@ -1947,12 +1947,137 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
return;
}
// Serial auto-login (#3417): mirror Telnet — the main process answers
// Login/Password prompts with the credentials saved on the host. When a
// startup command is pending, defer it until auto-login finishes so it is
// not typed at a login prompt. Quiet devices (no prompt, no banner) never
// emit a completion event, so fall back after the main-process auto-login
// window (60s) plus margin.
const SERIAL_AUTO_LOGIN_FALLBACK_MS = 65_000;
// A sleeping tab keeps its established serial connection. Only an abort
// or a new connection generation invalidates its delayed startup work.
const isSerialConnectionCurrent = () => options?.signal?.aborted !== true
&& (ctx.bootEpochRef?.current ?? 0) === bootEpoch;
let disposeAutoLoginComplete: (() => void) | undefined;
let disposeAutoLoginCancelled: (() => void) | undefined;
let cancelPendingStartupCommand: (() => void) | undefined;
let autoLoginFallbackTimer: ReturnType<typeof setTimeout> | undefined;
let serialSessionId = ctx.sessionId;
// A login exchange can complete before the startSerialSession promise
// resolves, so the completion event may arrive while the session is not
// attached yet. Record it and schedule the startup command only after
// attach, otherwise scheduleStartupCommand marks it as run and its timer
// then drops it against the unset ctx.sessionRef.current.
let autoLoginCompletedBeforeAttach = false;
// Auto-login can be cancelled (stalled exchange or user input) before the
// startSerialSession promise resolves; the fallback must not be armed
// after attach in that case, or it would blindly type the startup command
// at whatever prompt is pending.
let autoLoginCancelledBeforeAttach = false;
let autoLoginAttached = false;
const clearAutoLoginFallbackTimer = () => {
if (autoLoginFallbackTimer) {
clearTimeout(autoLoginFallbackTimer);
autoLoginFallbackTimer = undefined;
}
};
const disposeAutoLoginListener = () => {
disposeAutoLoginComplete?.();
disposeAutoLoginComplete = undefined;
};
const disposeAutoLoginCancelListener = () => {
disposeAutoLoginCancelled?.();
disposeAutoLoginCancelled = undefined;
};
const cleanupSerialStartupWait = () => {
clearAutoLoginFallbackTimer();
disposeAutoLoginListener();
disposeAutoLoginCancelListener();
cancelPendingStartupCommand?.();
cancelPendingStartupCommand = undefined;
};
const scheduleStartupAfterAutoLogin = () => {
if (!isSerialConnectionCurrent()) {
cleanupSerialStartupWait();
return;
}
disposeAutoLoginListener();
cancelPendingStartupCommand = scheduleStartupCommand(ctx, term, serialSessionId, () => {
cancelPendingStartupCommand = undefined;
disposeAutoLoginCancelListener();
}, isSerialConnectionCurrent);
};
try {
logger.info("[Serial] Starting serial session", {
port: ctx.serialConfig.path,
baudRate: ctx.serialConfig.baudRate,
});
const serialUsername = (ctx.host.username ?? "").trim();
const serialPassword = sanitizeCredentialValue(ctx.host.password);
// Mirror the Telnet path: an undecryptable saved password must not start
// a partial auto-login (username without password), which would leave a
// startup command waiting on a password prompt that is never answered.
if (isEncryptedCredentialPlaceholder(ctx.host.password)) {
const message = tr(
"terminal.auth.credentialsUnavailable",
"Saved credentials cannot be decrypted on this device. Please re-enter and save them again.",
);
ctx.setNeedsAuth(false);
ctx.setAuthRetryMessage(null);
ctx.setError(message);
writeTerminalLine(ctx, term, `\r\n[${message}]`);
ctx.updateStatus("disconnected");
return;
}
const hasSerialAutoLoginCredentials = Boolean(
serialUsername || serialPassword !== undefined,
);
const commandToRun = resolveStartupCommand(ctx);
const waitsForAutoLogin = Boolean(
commandToRun &&
hasSerialAutoLoginCredentials &&
ctx.terminalBackend.onTelnetAutoLoginComplete,
);
if (waitsForAutoLogin) {
disposeAutoLoginComplete = ctx.terminalBackend.onTelnetAutoLoginComplete?.(
ctx.sessionId,
(evt) => {
if (
Number.isFinite(bootEpoch)
&& Number.isFinite(evt?.bootEpoch)
&& evt.bootEpoch !== bootEpoch
) {
return;
}
clearAutoLoginFallbackTimer();
if (!autoLoginAttached) {
disposeAutoLoginListener();
autoLoginCompletedBeforeAttach = true;
return;
}
scheduleStartupAfterAutoLogin();
},
);
disposeAutoLoginCancelled = ctx.terminalBackend.onTelnetAutoLoginCancelled?.(
ctx.sessionId,
(evt) => {
if (
Number.isFinite(bootEpoch)
&& Number.isFinite(evt?.bootEpoch)
&& evt.bootEpoch !== bootEpoch
) {
return;
}
if (!autoLoginAttached) {
autoLoginCancelledBeforeAttach = true;
}
cleanupSerialStartupWait();
},
);
}
const id = await ctx.terminalBackend.startSerialSession({
sessionId: ctx.sessionId,
path: ctx.serialConfig.path,
@@ -1964,7 +2089,11 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
charset: ctx.host.charset,
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
bootEpoch,
...(hasSerialAutoLoginCredentials
? { username: serialUsername || undefined, password: serialPassword }
: {}),
});
serialSessionId = id;
if (!tryAttachSessionToTerminal(ctx, term, id, {
isCurrentAttempt,
@@ -1973,18 +2102,51 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
`\r\n[serial port closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
// Convert lone LF to CRLF to prevent "staircase effect" in serial terminals
convertLfToCrlf: true,
onExit: () => cleanupSerialStartupWait(),
})) {
// Only the current attempt may clear UI; a stale attach must not
// disconnect a newer reconnect that already re-armed boot.
cleanupSerialStartupWait();
if (isCurrentAttempt()) abortSessionStartAfterUnmount();
return;
}
// Serial connection is established once the session is attached to the terminal.
autoLoginAttached = true;
ctx.updateStatus("connected");
ctx.setProgressValue(100);
writeTerminalLine(ctx, term, `[Connected to ${ctx.serialConfig.path} at ${ctx.serialConfig.baudRate} baud]`);
if (waitsForAutoLogin) {
if (autoLoginCompletedBeforeAttach) {
// Login already completed before the session attached; schedule now
// that ctx.sessionRef.current points at this session.
scheduleStartupAfterAutoLogin();
return;
}
if (autoLoginCancelledBeforeAttach) {
// Auto-login was cancelled before the session attached (stalled
// exchange at a prompt the detector cannot answer, or the user took
// over). The quiet-device fallback must not fire: the startup
// command would be consumed as the answer to the pending prompt.
cleanupSerialStartupWait();
return;
}
// Arm the fallback only now that the port is open and the session is
// attached: the main-process 60s auto-login window starts when the
// port's open callback creates the detector, so a slow/busy port open
// must not consume the fallback budget.
autoLoginFallbackTimer = setTimeout(() => {
autoLoginFallbackTimer = undefined;
if (!disposeAutoLoginComplete) return;
if ((ctx.bootEpochRef?.current ?? 0) !== bootEpoch) return;
scheduleStartupAfterAutoLogin();
}, SERIAL_AUTO_LOGIN_FALLBACK_MS);
return;
}
scheduleStartupCommand(ctx, term, id, undefined, isSerialConnectionCurrent);
} catch (err) {
cleanupSerialStartupWait();
if (ignoreStaleAttemptUi()) return;
const message = err instanceof Error ? err.message : String(err);
ctx.setError(message);
@@ -101,7 +101,9 @@ export type TerminalBackendApi = {
cb: (sessionId: string, sourceSessionId?: string) => void,
) => (() => void) | undefined;
writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean; lineDelayMs?: number; logRewrite?: ProgrammaticCommandLogRewrite }) => void;
interruptSession?: (sessionId: string, trace?: NetcattyTerminalInterruptTrace) => void;
/** Signal buffered user input so main-process auto-login cancels. */
notifyUserInput?: (sessionId: string) => void;
interruptSession?: NetcattyBridge["interruptSession"];
resizeSession: (sessionId: string, cols: number, rows: number) => void;
closeSession: (sessionId: string, options?: { bootEpoch?: number }) => void | Promise<void>;
/** Pause/resume the source stream for output back-pressure (optional). */
@@ -996,9 +996,9 @@ test("multi-character plain text goes out as per-character writes (#3077)", asyn
// Every chunk carries the same write options as the original single write.
const writeLoopIdx = source.indexOf("for (const chunk of getTextInputWireChunks(outData");
assert.ok(writeLoopIdx >= 0);
const writeLoop = source.slice(writeLoopIdx, writeLoopIdx + 320);
const writeLoop = source.slice(writeLoopIdx, source.indexOf("});", writeLoopIdx) + 3);
assert.match(writeLoop, /for \(const chunk of/);
assert.match(writeLoop, /writeToSession\(id, chunk, \{ sensitive, serialEraseChar \}\)/);
assert.match(writeLoop, /writeToSession\(id, chunk, \{\s*sensitive,\s*serialEraseChar,[\s\S]*?\}\)/);
// IME commits split the committed glyph, not the Kitty CSI-u encoding.
assert.match(
@@ -1029,3 +1029,62 @@ test("multi-character plain text goes out as per-character writes (#3077)", asyn
assert.match(writeSite, /ctx\.onOutputTriggerUserInputRef\?\.current\?\.\(outData\)/);
assert.match(source, /onBroadcastInput\?\.\(broadcastData, ctx\.sessionId\)/);
});
test("Command+Period interrupt press is keyed apart from an outstanding physical KeyC press (#3409)", async () => {
const { readFileSync } = await import("node:fs");
const source = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8");
// The normalized Ctrl+C press shares its event identity with a possibly
// outstanding physical KeyC press, so it must be recorded under a dedicated
// map key: upserting under "KeyC" replaced the held key's press and the
// Period keyup deleted that shared entry while C was still down.
assert.match(
source,
/const pressIdentity =\s*macCommandPeriodInterrupt\s*\?\s*kittyNormalizedPressIdentity\(identity\)\s*:\s*identity,?/,
);
assert.match(source, /kittyNormalizedPressAliases\.set\(kittyKeyIdentity\(e\), pressIdentity\)/);
assert.match(
source,
/upsertKittyKeyboardForwardedPress\(\s*kittyForwardedKeys,\s*pressIdentity,/,
);
assert.match(
source,
/upsertKittyKeyboardForwardedPress\(\s*broadcastForwardedKeys,\s*pressIdentity,/,
);
// The aliased Period keyup releases the interrupt press under its dedicated
// key, leaving the physical KeyC press entry intact.
assert.match(source, /\{ \.\.\.aliasedRelease\.event, type: "keyup" \},\s*aliasedRelease\.identity/);
assert.match(source, /releaseForwardedKittyPress\(toKittyKeyboardEvent\(releaseEvent\)\) \|\| releasedInterrupt/);
// The dedicated identity crosses the broadcast boundary: peers key their
// pairing state from it, so the interrupt cannot collapse with an
// outstanding physical KeyC press on legacy or Kitty peers (#3409).
assert.match(
source,
/broadcastKittyInput\(\{\s*kind: "key",\s*event: kittyEvent,\s*keyIdentity: pressIdentity,\s*\}\)/,
);
assert.match(
source,
/broadcastKittyInput\(\{\s*kind: "legacy",\s*data: "\\x03",\s*keyIdentity: pressIdentity,/,
);
// The paired release carries the identity the press was recorded under.
assert.match(
source,
/\{ kind: "key", event, keyIdentity: identity \}/,
);
// Native keyups retain the physical event even after releasing an alias.
assert.match(source, /const hasForwardedWin32KeyDown = win32InputModeForwardedKeys\.delete\(identity\);/);
});
test("Command+Period interrupt yields to a user-assigned snippet or shortcut chord (#3409)", async () => {
const { readFileSync } = await import("node:fs");
const source = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8");
// The snippet/app-shortcut editors accept Command+Period (their conflict checks only
// cover configured bindings), so the hard-coded interrupt must give a
// configured chord precedence instead of silently swallowing it (#3409).
assert.match(
source,
/const macCommandPeriodInterrupt =\s*isMacPlatform\(\)\s*&& isMacCommandPeriodInterruptChord\(e\)\s*&& !\(ctx\.snippetsRef\?\.current \?\? \[\]\)\.some\(\(snippet\) => \(\s*snippet\.shortkey && matchesKeyBinding\(e, snippet\.shortkey, isMac\)\s*\)\)\s*&& !\(currentScheme !== "disabled"\s*&& checkAppShortcut\(e, ctx\.keyBindingsRef\.current, isMac\) !== null\);/,
);
});
+355 -30
View File
@@ -1,4 +1,6 @@
import { clearTerminalBroadcastUserInput, captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent, markTerminalBroadcastUserInput, type TerminalPacedBroadcast } from "./terminalPacedBroadcast";
import { stringCellWidth } from "../autocomplete/terminalStringCellWidth";
import type { TerminalBroadcastInputOptions } from "../terminalHelpers";
import { FitAddon } from "@xterm/addon-fit";
import { ImageAddon } from "@xterm/addon-image";
import { SearchAddon } from "@xterm/addon-search";
@@ -103,6 +105,7 @@ import {
resolveMiddleClickBehavior,
} from "./middleClickBehavior";
import { handleSerialLineModeInput } from "./serialLineInput";
import { isTerminalReportSequence } from "./terminalReportSequence";
import {
doesKittyEncodingPreserveShiftEnter,
getShiftEnterSubmittedInput,
@@ -119,6 +122,7 @@ import {
shouldFlushDeferredImeTextInputOnKeyUp,
shouldFlushStaleDeferredImeTextInput,
} from "./terminalImeTextInput";
import { keepImeCommittedTextThroughModifierKeyDowns } from "./imeModifierKeyDownSeenGuard";
import { formatSerialLocalEcho } from "./serialLocalEcho";
import { getLastChar, removeLastChar, isPrintableInput } from "../../../domain/serialCharMetrics";
import { mapTerminalBackspaceInput } from "./terminalBackspaceInput";
@@ -161,7 +165,10 @@ import {
type TerminalOutputHistoryPreview,
} from "./terminalOutputHistory";
import { shouldPassThroughCopyShortcut } from "./terminalCopyShortcut";
import { shouldUseUrgentTerminalInterrupt } from "./terminalInterruptShortcut";
import {
isMacCommandPeriodInterruptChord,
shouldUseUrgentTerminalInterrupt,
} from "./terminalInterruptShortcut";
import {
createTerminalInterruptTrace,
logTerminalInterruptTrace,
@@ -177,15 +184,18 @@ import {
} from "./terminalOutputPipeline";
import {
markExpectedTerminalCursorPositionReport,
pasteTextIntoTerminal,
registerTerminalLinePasteHandler,
shouldBroadcastTerminalUserInput,
shouldOverrideTerminalUserPasteSensitivity,
shouldSuppressTerminalInputScrollForUserPaste,
} from "./terminalUserPaste";
import { pasteTextWithMultilineConfirm } from "../terminalClipboardPaste";
import { requestMultilinePasteConfirm } from "../../../application/state/multilinePasteConfirmStore";
import {
consumeOsc133CommandCompletion,
type PromptLineBreakState,
} from "./promptLineBreak";
import { recordTerminalCommandExecution } from "./terminalCommandExecution";
import { isSensitiveTerminalCommandInput, recordTerminalCommandExecution } from "./terminalCommandExecution";
import {
getSingleBracketedPasteLine,
getSinglePastedCommand,
@@ -208,8 +218,9 @@ import {
type TerminalBackendApi = {
openExternalAvailable: () => boolean;
openExternal: (url: string) => Promise<void>;
writeToSession: (sessionId: string, data: string) => void;
interruptSession?: (sessionId: string, trace?: NetcattyTerminalInterruptTrace) => void;
writeToSession: NetcattyBridge["writeToSession"];
notifyUserInput?: (sessionId: string) => void;
interruptSession?: NetcattyBridge["interruptSession"];
signalPluginConnection?: (
sessionId: string,
signal?: "interrupt" | "terminate" | "kill" | "eof" | "break",
@@ -243,6 +254,7 @@ export type XTermRuntime = {
dispose: () => void;
/** Track the pending final line of a serial snippet left for editing. */
recordSerialSnippetInput: (data: string) => void;
invalidatePendingPasteDraft: () => void;
/** Current working directory detected via OSC 7 */
currentCwd: string | undefined;
keywordHighlighter: KeywordHighlighter;
@@ -314,7 +326,7 @@ export type CreateXTermRuntimeContext = {
((
data: string,
sourceSessionId: string,
options?: { kittyKeyboardInput?: KittyKeyboardBroadcastInput },
options?: TerminalBroadcastInputOptions,
) => void) | undefined
>;
@@ -356,6 +368,7 @@ export type CreateXTermRuntimeContext = {
recordBackspace: () => void;
recordClearLine: () => void;
recordEnter: (options?: { sensitive?: boolean }) => Promise<void>;
captureSubmittedLineRecorder?: () => ((line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }) => Promise<void>) | undefined;
} | undefined>;
passwordPromptActiveRef?: RefObject<boolean>;
allowHostStyleGreaterThanPrompt?: boolean;
@@ -619,6 +632,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
},
});
installSearchDecorationTracker(term);
// Sogou on Windows commits pending preedit text when Shift toggles
// Chinese/English mode; a pure modifier keydown must not arm xterm's
// insertText dedupe guard or the committed text is dropped (#3441).
keepImeCommittedTextThroughModifierKeyDowns(term);
type MaybeRenderer = {
constructor?: { name?: string };
@@ -926,13 +943,16 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const appLevelActions = getAppLevelActions();
const terminalActions = getTerminalPassthroughActions();
const broadcastUserPasteData = (data: string) => {
const broadcastUserPasteData = (
data: string,
options?: TerminalBroadcastInputOptions,
) => {
if (
ctx.passwordPromptActiveRef?.current !== true
&& ctx.isBroadcastEnabledRef.current
&& ctx.onBroadcastInputRef.current
) {
ctx.onBroadcastInputRef.current(data, ctx.sessionId);
ctx.onBroadcastInputRef.current(data, ctx.sessionId, options);
return true;
}
return false;
@@ -1156,6 +1176,11 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
// nonempty (hibernation wake: the pre-hibernation cursor may have been
// moved away from the tail, so we conservatively assume it is not).
let lastInputWasPrintable = !ctx.commandBufferRef?.current;
let commandBufferRevision = 0;
const invalidatePendingPasteDraft = () => {
commandBufferRevision += 1;
markTerminalBroadcastUserInput(ctx.sessionId);
};
const restoreSerialTailForEmptyInput = (data: string) => {
// Apply the same rule to typed text, pasted text, and editable snippets.
@@ -1172,6 +1197,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
: data;
const lastLineBreak = Math.max(text.lastIndexOf("\r"), text.lastIndexOf("\n"));
if (lastLineBreak >= 0) {
commandBufferRevision += 1;
ctx.commandBufferRef.current = "";
lastInputWasPrintable = true;
}
@@ -1198,6 +1224,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
logicalData?: string | null;
/** Skip string broadcast when peers will re-resolve from a key chord. */
skipBroadcast?: boolean;
/** Confirmed paste: preserve classification and backend pacing. */
sensitive?: boolean;
lineDelayMs?: number;
pasteRequestId?: string;
/**
* Send plain text as one write per character. Strict bastion prompts
* (QAX) treat one channel write as a keystroke and drop multi-character
@@ -1230,7 +1260,21 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const inputSource = options?.source ?? "terminal";
const id = ctx.sessionRef.current;
const dataToWrite = data;
const sensitive = ctx.passwordPromptActiveRef?.current === true;
// A programmatic paste can carry a sensitivity snapshot taken before a
// confirm-dialog await (terminalUserPaste.ts): remote output or a
// reconnect may have cleared passwordPromptActiveRef while the dialog was
// open, so the live ref alone would downgrade the secret to nonsensitive.
// The override is consumed only for the flagged paste data.
const sensitive = ctx.passwordPromptActiveRef?.current === true
|| options?.sensitive === true
|| shouldOverrideTerminalUserPasteSensitivity(term, logicalData ?? data);
if (!options?.lineDelayMs && logicalData !== null
&& !isPrintableInput(logicalData) && !isTerminalReportSequence(logicalData)) {
commandBufferRevision += 1;
}
if (!options?.lineDelayMs && logicalData !== null && !isTerminalReportSequence(logicalData)) {
markTerminalBroadcastUserInput(ctx.sessionId);
}
let handledSubmittedInput = false;
const submittedInput: { text: string; lineEnding: "\r\n" | "\r" | "\n" } | null =
logicalData === null
@@ -1258,7 +1302,12 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
hasBroadcastInputHandler: !!onBroadcastInput,
});
const willBroadcastInput = canBroadcastInput && options?.skipBroadcast !== true;
if (ctx.statusRef.current === "connected" && submittedInput) {
if (ctx.statusRef.current === "connected" && options?.lineDelayMs && logicalData) {
// Keep the draft until the backend confirms a write. A rejected or
// canceled batch must not discard input already present at the prompt.
if (ctx.passwordPromptActiveRef) ctx.passwordPromptActiveRef.current = false;
handledSubmittedInput = true;
} else if (ctx.statusRef.current === "connected" && submittedInput) {
if (submittedInput.text) {
ctx.commandBufferRef.current += submittedInput.text;
ctx.scriptRecorderRef?.current?.recordInput(submittedInput.text);
@@ -1329,16 +1378,50 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
ctx.serialLineMode &&
ctx.serialLineBufferRef
) {
// Local line editing sends no transport write, so cancel queued paste
// work explicitly. Only actual protocol replies are exempt; keyboard
// escape sequences also edit the local buffer.
if (!options?.lineDelayMs && !isTerminalReportSequence(dataToWrite)
&& (dataToWrite === "\b" || dataToWrite === "\x15"
|| dataToWrite.charCodeAt(0) >= 32 || dataToWrite.length > 1)) {
ctx.terminalBackend.interruptSession?.(id, undefined, { cancelPendingWritesOnly: true });
}
// Line mode never reaches writeToSession until Enter, so buffered
// keystrokes are invisible to the main-process auto-login detector.
// The first buffered keystroke means the user is taking control:
// cancel the detector exactly like character-mode input would.
// Submit (\r/\n) and Ctrl+C already write to the session, which
// cancels it on that path. Automatic terminal-report replies (DA1,
// CPR, ...) also surface through onData, but they originate from the
// device negotiating with xterm, not from the user — the main process
// excludes them from its write-path cancellation via
// isTerminalReportSequence, so apply the same classification here.
const isSessionWrite = dataToWrite === "\r" || dataToWrite === "\n" || dataToWrite === "\x03";
if (!isSessionWrite && !isTerminalReportSequence(dataToWrite)) {
ctx.terminalBackend.notifyUserInput?.(id);
}
const pacedWrites: string[] = [];
handleSerialLineModeInput(dataToWrite, {
bufferRef: ctx.serialLineBufferRef,
localEcho: ctx.serialLocalEcho,
writeToSession: (nextData) => {
ctx.onOutputTriggerUserInputRef?.current?.(nextData);
ctx.terminalBackend.writeToSession(id, nextData, { sensitive });
if (options?.lineDelayMs) pacedWrites.push(nextData);
else ctx.terminalBackend.writeToSession(id, nextData, { sensitive });
},
writeToTerminal: writeLocalTerminalData,
term,
});
// Submit one batch so the backend spaces the lines apart. Separate
// calls would each start at delay zero and lose the paste pacing.
if (pacedWrites.length > 0) {
ctx.terminalBackend.writeToSession(id, pacedWrites.join(""), {
automated: false,
sensitive,
lineDelayMs: options?.lineDelayMs,
pasteRequestId: options?.pasteRequestId,
});
}
} else {
// Character mode sends input immediately. Byte-oriented devices opt in
// to expansion in the backend, using the session's actual wire encoder.
@@ -1368,7 +1451,15 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
ctx.onOutputTriggerUserInputRef?.current?.(outData);
for (const chunk of getTextInputWireChunks(outData, options?.perCharacterWrites === true)) {
ctx.terminalBackend.writeToSession(id, chunk, { sensitive, serialEraseChar });
ctx.terminalBackend.writeToSession(id, chunk, {
sensitive,
serialEraseChar,
...(options?.lineDelayMs ? {
automated: false,
lineDelayMs: options.lineDelayMs,
pasteRequestId: options.pasteRequestId,
} : {}),
});
}
// Local echo for serial connections only when explicitly enabled
@@ -1486,6 +1577,14 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const kittyForwardedKeys = new Map<string, KittyKeyboardForwardedPress>();
const broadcastForwardedKeys = new Map<string, KittyKeyboardForwardedPress>();
const win32BroadcastForwardedKeys = new Map<string, KittyKeyboardForwardedPress>();
// Command+Period interrupt presses are recorded under their normalized Ctrl+C identity
// (KeyC) so broadcast legacy pairing stays matched (#3408), but under a
// dedicated map key so they cannot clobber an outstanding physical KeyC
// press; map the physical chord identity (Period) to it so the later keyup
// can pair the release.
const kittyNormalizedPressAliases = new Map<string, string>();
const kittyNormalizedPressIdentity = (identity: string): string =>
`${identity}\u0000mac-period-interrupt`;
const broadcastEncodedKeys = new Set<string>();
const broadcastLegacySuppressedKeys = new Set<string>();
const kittyKeyIdentity = (event: KeyboardEvent): string => event.code || event.key;
@@ -1671,13 +1770,20 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
*/
const releaseForwardedKittyPress = (
event: Pick<KittyKeyboardEvent, "code" | "key"> & KittyKeyboardEvent,
identityOverride?: string,
): boolean => {
const identity = event.code || event.key;
// The Command+Period interrupt press is keyed independently from its normalized
// Ctrl+C event identity, so its release must delete the entry it was
// stored under rather than the physical key's (#3408).
const identity = identityOverride ?? (event.code || event.key);
const forwardedPress = broadcastForwardedKeys.get(identity);
if (forwardedPress) {
broadcastForwardedKeys.delete(identity);
broadcastKittyInput(
{ kind: "key", event },
// Carry the identity the press was recorded under so peers pair this
// release with that press instead of the event's physical code - the
// Command+Period interrupt press lives under a dedicated normalized key (#3409).
{ kind: "key", event, keyIdentity: identity },
true,
forwardedPress.targetSessionIds,
);
@@ -1693,6 +1799,30 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
}
return false;
};
/**
* Resolve a forwarded press whose recorded identity is not the physical
* key identity: the Command+Period interrupt press was recorded as the normalized
* Ctrl+C event (KeyC), but the browser delivers the physical release as
* Period. Pair that release from the stored event so Kitty consumers do
* not see Ctrl+C held until focus loss (#3408).
*/
const resolveKittyNormalizedPressRelease = (
physicalEvent: KeyboardEvent,
): { event: KittyKeyboardEvent; identity: string } | null => {
const physicalIdentity = kittyKeyIdentity(physicalEvent);
const normalizedIdentity = kittyNormalizedPressAliases.get(physicalIdentity);
if (!normalizedIdentity) return null;
const forwardedPress =
broadcastForwardedKeys.get(normalizedIdentity)
?? kittyForwardedKeys.get(normalizedIdentity);
// Consume the alias on every path once it has been paired (or
// invalidated): a later keyup for the same physical key while another
// KeyC press is outstanding must not be rewritten as the normalized
// release (#3408).
kittyNormalizedPressAliases.delete(physicalIdentity);
if (!forwardedPress) return null;
return { event: forwardedPress.event, identity: normalizedIdentity };
};
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
// Preserve mouse selection across keystrokes when enabled. xterm.js
@@ -1770,6 +1900,15 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
releaseForwardedKittyPress({ ...deferredKittyEvent, type: "keyup" });
}
}
// Release the normalized interrupt separately: the same physical key
// may already have a forwarded press from before Command was held.
// Keep the saved layout-independent event rather than translating KeyC
// through the current keyboard layout again.
const aliasedRelease = resolveKittyNormalizedPressRelease(e);
const releasedInterrupt = aliasedRelease !== null && releaseForwardedKittyPress(
{ ...aliasedRelease.event, type: "keyup" },
aliasedRelease.identity,
);
const identity = kittyKeyIdentity(releaseEvent);
const hasForwardedWin32KeyDown = win32InputModeForwardedKeys.delete(identity);
if (broadcastLegacyDataPending === identity) clearBroadcastLegacyDataPending();
@@ -1792,7 +1931,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
};
return true;
}
if (releaseForwardedKittyPress(toKittyKeyboardEvent(releaseEvent))) {
if (releaseForwardedKittyPress(toKittyKeyboardEvent(releaseEvent)) || releasedInterrupt) {
e.preventDefault();
e.stopPropagation();
return false;
@@ -1981,10 +2120,27 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
kittyKeyboardProtocolEnabled
? encodeKittyKeyEvent(kittyKeyboardMode, toKittyKeyboardEvent(e))
: null;
if (
const urgentInterrupt =
(!kittySequenceForKeyDown || kittySequenceForKeyDown === "\x03") &&
shouldUseUrgentTerminalInterrupt(e, { hasSelection: hasCopyableSelection })
) {
shouldUseUrgentTerminalInterrupt(e, { hasSelection: hasCopyableSelection });
const currentScheme = ctx.hotkeySchemeRef.current;
// Use shared utility for platform detection when hotkey scheme is disabled
const isMac = currentScheme === "mac" || (currentScheme === "disabled" && isMacPlatform());
// macOS Terminal convention: Command+Period interrupts the running command like
// Ctrl+C (#3408), including while text is selected. A
// user-assigned snippet or configured shortcut on this chord keeps
// precedence: the editors accept Command+Period (their conflict check only covers
// configured bindings), so the hard-coded interrupt must not silently
// swallow a chord the user actually assigned (#3409).
const macCommandPeriodInterrupt =
isMacPlatform()
&& isMacCommandPeriodInterruptChord(e)
&& !(ctx.snippetsRef?.current ?? []).some((snippet) => (
snippet.shortkey && matchesKeyBinding(e, snippet.shortkey, isMac)
))
&& !(currentScheme !== "disabled"
&& checkAppShortcut(e, ctx.keyBindingsRef.current, isMac) !== null);
if (urgentInterrupt || macCommandPeriodInterrupt) {
const id = ctx.sessionRef.current;
if (id && ctx.statusRef.current === "connected") {
const rendererKeyAt = Date.now();
@@ -2019,10 +2175,13 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
onAutocompleteInput: ctx.onAutocompleteInput,
});
lastInputWasPrintable = true;
invalidatePendingPasteDraft();
ctx.scriptRecorderRef?.current?.recordClearLine();
if (ctx.passwordPromptActiveRef) {
ctx.passwordPromptActiveRef.current = false;
}
if (isPluginHostProtocol(ctx.host.protocol) && ctx.terminalBackend.signalPluginConnection) {
ctx.terminalBackend.interruptSession?.(id, interruptTrace, { cancelPendingWritesOnly: true });
void ctx.terminalBackend.signalPluginConnection(id, "interrupt").catch(() => {
if (ctx.terminalBackend.interruptSession) {
ctx.terminalBackend.interruptSession(id, interruptTrace);
@@ -2035,8 +2194,53 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
} else {
ctx.terminalBackend.writeToSession(id, "\x03");
}
const kittyEvent = toKittyKeyboardEvent(e);
const identity = kittyKeyIdentity(e);
// Report the interrupt to Kitty as Ctrl+C even when it came from the
// Command+Period chord: the broadcast legacy \x03 is keyed by this identity, so
// forwarding Super+Period would leave peers with an unmatched
// Super+Period press and suppress the interrupt instead (#3408).
const interruptEventForKitty: KeyboardEvent = macCommandPeriodInterrupt
? {
type: e.type,
key: "c",
code: "KeyC",
location: e.location,
repeat: e.repeat,
isComposing: e.isComposing,
keyCode: 67,
shiftKey: false,
altKey: false,
ctrlKey: true,
metaKey: false,
getModifierState: (key: string) => key === "Control" && e.getModifierState("Control"),
} as unknown as KeyboardEvent
: e;
const kittyEvent = toKittyKeyboardEvent(interruptEventForKitty);
if (macCommandPeriodInterrupt) {
// The synthesized event's code ("KeyC") is the physical QWERTY
// position of the chord key, so toKittyKeyboardEvent()'s layout
// lookup returns that position's character on non-QWERTY layouts
// (e.g. "n" under Dvorak) and getUnicodeKeyCode() prioritizes it,
// encoding the interrupt as the wrong key instead of Ctrl+C's 99
// - a broadcast peer would then suppress the legacy \x03 fallback
// and never be interrupted. Force the layout-independent identity.
kittyEvent.unshiftedKey = "c";
}
const identity = kittyKeyIdentity(interruptEventForKitty);
// The normalized press shares the Ctrl+C event identity (KeyC) with a
// possibly outstanding physical KeyC press; record it under a dedicated
// map key even when the layout maps period to physical KeyC. Its keyup
// releases (and deletes) only the
// interrupt press instead of the held physical key's entry (#3409).
const pressIdentity =
macCommandPeriodInterrupt
? kittyNormalizedPressIdentity(identity)
: identity;
if (pressIdentity !== identity) {
// The physical release arrives under its original layout key while
// the press was recorded as the normalized Ctrl+C event; pair them
// at keyup so the interrupt release is not lost (#3408).
kittyNormalizedPressAliases.set(kittyKeyIdentity(e), pressIdentity);
}
if (
!term.modes.win32InputMode &&
kittyKeyboardProtocolEnabled &&
@@ -2044,23 +2248,31 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
) {
upsertKittyKeyboardForwardedPress(
kittyForwardedKeys,
identity,
pressIdentity,
kittyEvent,
[],
);
}
const forwarded = broadcastKittyInput({ kind: "key", event: kittyEvent });
// The dedicated press identity must cross the broadcast boundary:
// peers key their pairing state from it, so broadcasting only the
// normalized event would collapse the interrupt with an outstanding
// physical KeyC press on every peer (#3409).
const forwarded = broadcastKittyInput({
kind: "key",
event: kittyEvent,
keyIdentity: pressIdentity,
});
if (forwarded) {
upsertKittyKeyboardForwardedPress(
broadcastForwardedKeys,
identity,
pressIdentity,
kittyEvent,
forwarded.targetSessionIds,
);
broadcastKittyInput({
kind: "legacy",
data: "\x03",
keyIdentity: identity,
keyIdentity: pressIdentity,
urgentInterrupt: true,
});
}
@@ -2069,10 +2281,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
}
}
const currentScheme = ctx.hotkeySchemeRef.current;
// Use shared utility for platform detection when hotkey scheme is disabled
const isMac = currentScheme === "mac" || (currentScheme === "disabled" && isMacPlatform());
// Check snippet shortcuts first (even if hotkeys are disabled)
const snippets = ctx.snippetsRef?.current;
if (snippets && snippets.length > 0) {
@@ -2146,9 +2354,24 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const id = ctx.sessionRef.current;
if (selection && id) {
hideHistoryPreview();
pasteTextIntoTerminal(term, selection, {
scrollOnPaste: shouldScrollOnTerminalPaste(ctx.terminalSettingsRef.current),
// Route through the multi-line paste confirmation gate
// (#3398) so a selected multi-line region cannot be sent to
// the session (and broadcast peers) without review, just
// like the clipboard paste path.
void pasteTextWithMultilineConfirm(selection, {
confirmMultilinePaste: {
enabled: ctx.terminalSettingsRef.current?.confirmBeforeMultilinePaste === true,
minLines: ctx.terminalSettingsRef.current?.multilinePasteConfirmMinLines,
requestConfirm: requestMultilinePasteConfirm,
},
getCurrentSessionId: () => ctx.sessionRef.current,
isSensitiveInput: () => ctx.passwordPromptActiveRef?.current === true,
onPasteData: broadcastUserPasteData,
scrollOnPaste: shouldScrollOnTerminalPaste(ctx.terminalSettingsRef.current),
scrollToBottomAfterProgrammaticInput: scrollToBottomAfterInput,
sessionId: id,
terminalBackend: ctx.terminalBackend,
term,
});
}
break;
@@ -2479,6 +2702,16 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
win32InputModePendingEvent = null;
win32InputModeForwardedKeys.clear();
kittyForwardedKeys.clear();
// broadcastForwardedKeys is retained so pending peer releases still pair
// after a reconnect; keep the aliases whose normalized press is still
// owed a broadcast release, otherwise the physical keyup can no longer
// find the dedicated identity and peers keep the key logically pressed
// until blur (#3409).
for (const [physicalIdentity, normalizedIdentity] of kittyNormalizedPressAliases) {
if (!broadcastForwardedKeys.has(normalizedIdentity)) {
kittyNormalizedPressAliases.delete(physicalIdentity);
}
}
clearKittyKeyboardBroadcastPairingState(
broadcastEncodedKeys,
broadcastLegacySuppressedKeys,
@@ -2554,6 +2787,93 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
ctx.container.addEventListener("input", markKittyTextInput, true);
textarea?.addEventListener("blur", clearKittyTransientInputState);
const pendingLinePastes = new Map<string, {
sessionId: string;
commands: string[];
firstPastedLine: string;
pendingInput: string;
serialPendingInput?: string;
sourceInput: ReturnType<typeof captureTerminalBroadcastInput>;
broadcast?: TerminalPacedBroadcast;
inputRevision: number;
sensitive: boolean;
recorded: Set<number>;
recordLine?: (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }) => Promise<void>;
}>();
const disposePasteWriteReceipts = netcattyBridge.get()?.onTerminalPasteWrite?.((receipt) => {
const pending = pendingLinePastes.get(receipt.requestId);
if (!pending || pending.sessionId !== receipt.sessionId) return;
if (ctx.sessionRef.current !== pending.sessionId) {
pendingLinePastes.delete(receipt.requestId);
return;
}
const index = receipt.index;
if (index !== undefined && Number.isInteger(index) && index >= 0
&& index < pending.commands.length && !pending.recorded.has(index)) {
if (index === 0 && pending.inputRevision === commandBufferRevision
&& ctx.commandBufferRef.current.startsWith(pending.pendingInput)) {
ctx.commandBufferRef.current = ctx.commandBufferRef.current.slice(pending.pendingInput.length);
if (pending.serialPendingInput !== undefined && ctx.serialLineBufferRef?.current.startsWith(pending.serialPendingInput)) {
ctx.serialLineBufferRef.current = ctx.serialLineBufferRef.current.slice(pending.serialPendingInput.length);
}
commandBufferRevision += 1;
}
pending.recorded.add(index);
const command = pending.commands[index];
const sensitive = isSensitiveTerminalCommandInput(
term, pending.sensitive || ctx.passwordPromptActiveRef?.current === true,
);
// Receipts can arrive after the user starts typing another command.
// Never consume that live input buffer or reconcile with a newer screen.
recordTerminalCommandExecution(command, { ...ctx, commandBufferRef: { current: "" } }, term, {
sensitive,
allowHostStyleGreaterThanPrompt: ctx.allowHostStyleGreaterThanPrompt,
useProvidedCommand: true,
acknowledgedWrite: true,
});
if (pending.broadcast && isTerminalBroadcastInputCurrent(pending.sourceInput)
&& ctx.isBroadcastEnabledRef.current && !sensitive) {
ctx.onBroadcastInputRef.current?.(`${index === 0 ? pending.firstPastedLine : command}\r`, ctx.sessionId, {
pacedBroadcast: pending.broadcast,
});
}
void pending.recordLine?.(index === 0 ? pending.firstPastedLine : command, {
sensitive, includePendingInput: index === 0, consumePendingInput: index === 0,
}).catch((error) => {
logger.warn("Failed to record confirmed paste write", error);
});
}
if (receipt.done) pendingLinePastes.delete(receipt.requestId);
});
const disposeLinePasteHandler = registerTerminalLinePasteHandler(term, (data, options) => {
const sessionId = ctx.sessionRef.current;
if (!sessionId) return;
markTerminalBroadcastUserInput(ctx.sessionId);
const sourceInput = captureTerminalBroadcastInput(ctx.sessionId);
const broadcast: TerminalPacedBroadcast | undefined = options.broadcast && !options.sensitive
&& ctx.isBroadcastEnabledRef.current ? {} : undefined;
if (broadcast) ctx.onBroadcastInputRef.current?.("", ctx.sessionId, { pacedBroadcast: broadcast, preparePacedBroadcast: true });
const requestId = crypto.randomUUID();
const commands = data.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
if (commands.at(-1) === "") commands.pop();
const firstPastedLine = commands[0] ?? "";
if (commands.length) {
commands[0] = `${ctx.commandBufferRef.current}${commands[0]}`;
}
const serialPendingInput = ctx.host.protocol === "serial" && ctx.serialLineMode
? ctx.serialLineBufferRef?.current : undefined;
const recorded = new Set<number>();
pendingLinePastes.set(requestId, {
sessionId, sourceInput, broadcast, commands, firstPastedLine, sensitive: options.sensitive, recorded, serialPendingInput,
pendingInput: ctx.commandBufferRef.current, inputRevision: commandBufferRevision,
recordLine: ctx.scriptRecorderRef?.current?.captureSubmittedLineRecorder?.(),
});
handleTerminalInputData(data, { ...options, pasteRequestId: requestId, skipBroadcast: true });
if (recorded.size === 0 && serialPendingInput !== undefined && ctx.serialLineBufferRef) {
ctx.serialLineBufferRef.current = serialPendingInput;
}
});
term.onData((data) => {
const win32Input = win32InputModePendingEvent;
if (
@@ -2997,8 +3317,13 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
getKittyKeyboardProtocolEnabled: () => kittyKeyboardProtocolEnabled,
setKittyKeyboardProtocolEnabled,
recordSerialSnippetInput,
invalidatePendingPasteDraft,
dispose: () => {
runtimeDisposed = true;
disposeLinePasteHandler?.();
disposePasteWriteReceipts?.();
pendingLinePastes.clear();
clearTerminalBroadcastUserInput(ctx.sessionId);
resizeScheduler.dispose();
webglController.dispose();
term.element?.removeEventListener("copy", handleNativeCopy, true);
@@ -0,0 +1,99 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import {
isModifierOnlyKeyDownEvent,
keepImeCommittedTextThroughModifierKeyDowns,
} from "./imeModifierKeyDownSeenGuard";
const runtimeSource = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "createXTermRuntime.ts"),
"utf8",
);
test("isModifierOnlyKeyDownEvent accepts both DOM key and classic keyCode shapes", () => {
assert.equal(isModifierOnlyKeyDownEvent({ key: "Shift", keyCode: 16 }), true);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Shift" }), true);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Control", keyCode: 17 }), true);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Alt", keyCode: 18 }), true);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Meta", keyCode: 91 }), true);
assert.equal(isModifierOnlyKeyDownEvent({ key: "CapsLock" }), true);
});
test("isModifierOnlyKeyDownEvent rejects real keys and IME process events", () => {
assert.equal(isModifierOnlyKeyDownEvent({ key: "a", keyCode: 65 }), false);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Process", keyCode: 229 }), false);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Enter", keyCode: 13 }), false);
assert.equal(isModifierOnlyKeyDownEvent({ key: "Dead", keyCode: 221 }), false);
});
type FakeCore = {
_keyDown: (event: Pick<KeyboardEvent, "key" | "keyCode">) => boolean;
_keyDownSeen: boolean;
_keyUp: () => void;
};
function createFakeCore(initialSeen = false): {
core: FakeCore;
term: { _core: FakeCore };
} {
const core: FakeCore = {
_keyDownSeen: initialSeen,
_keyDown(_event) {
// Mirrors xterm: every keydown arms the insertText dedupe guard.
this._keyDownSeen = true;
return true;
},
_keyUp() {
this._keyDownSeen = false;
},
};
return { core, term: { _core: core } };
}
test("keepImeCommittedTextThroughModifierKeyDowns preserves seen state across Shift keydown", () => {
// Sogou Shift commit: a previous real keydown armed the guard, and the
// Shift keydown must not re-arm (or clear) it before the composed input.
const { core, term } = createFakeCore(false);
keepImeCommittedTextThroughModifierKeyDowns(term as never);
core._keyDown({ key: "Shift", keyCode: 16 } as KeyboardEvent);
assert.equal(core._keyDownSeen, false);
});
test("keepImeCommittedTextThroughModifierKeyDowns keeps guard armed for real keydowns", () => {
const { core, term } = createFakeCore(false);
keepImeCommittedTextThroughModifierKeyDowns(term as never);
core._keyDown({ key: "a", keyCode: 65 } as KeyboardEvent);
assert.equal(core._keyDownSeen, true);
});
test("keepImeCommittedTextThroughModifierKeyDowns preserves an already-armed guard", () => {
const { core, term } = createFakeCore(true);
keepImeCommittedTextThroughModifierKeyDowns(term as never);
core._keyDown({ key: "Shift" } as KeyboardEvent);
assert.equal(core._keyDownSeen, true);
});
test("keepImeCommittedTextThroughModifierKeyDowns leaves non-modifier behavior intact", () => {
const { core, term } = createFakeCore(false);
keepImeCommittedTextThroughModifierKeyDowns(term as never);
core._keyDown({ key: "Process", keyCode: 229 } as KeyboardEvent);
assert.equal(core._keyDownSeen, true);
core._keyDown({ key: "Control", keyCode: 17 } as KeyboardEvent);
assert.equal(core._keyDownSeen, true, "Control still restored to true (was true)");
});
test("guard tolerates a terminal without an introspectable core", () => {
assert.doesNotThrow(() => {
keepImeCommittedTextThroughModifierKeyDowns({} as never);
});
});
test("runtime installs the guard when the terminal is created", () => {
assert.match(
runtimeSource,
/keepImeCommittedTextThroughModifierKeyDowns\(term\)/,
);
});
@@ -0,0 +1,56 @@
/**
* xterm.js arms its `insertText` dedupe guard (`_keyDownSeen`) on every
* keydown and only clears it on keyup. A pure modifier keydown never emits
* text itself, but on Windows Sogou Pinyin commits the pending preedit text
* when Shift toggles Chinese/English mode — and the composed `input` event
* that carries the commit is delivered right after the Shift keydown. The
* armed guard then suppresses that event, so the committed text never
* reaches `onData` and the preedit text vanishes (#3441).
*
* Same root cause as upstream xtermjs/xterm.js#6054: a modifier keydown
* never produces text itself, so it must not arm the "a real keydown was
* already handled" heuristic. Preserve the pre-keydown guard state for
* modifier-only keydowns (both `key === "Shift"` and legacy keyCode 16/17/
* 18 shapes) so composed IME commits still arrive through `_inputEvent`.
*/
import type { Terminal as XTerm } from "@xterm/xterm";
import { isModifierOnlyKey } from "./terminalImeTextInput";
/** Classic keyCodes that stand for a modifier-only keydown. */
const MODIFIER_KEY_CODES = new Set([16, 17, 18, 91, 92, 93, 224]);
export function isModifierOnlyKeyDownEvent(event: {
key: string;
keyCode?: number;
}): boolean {
return (
isModifierOnlyKey(event.key)
|| (event.keyCode !== undefined && MODIFIER_KEY_CODES.has(event.keyCode))
);
}
type XTermInputCore = {
_keyDown?: (event: KeyboardEvent) => boolean | undefined;
_keyDownSeen?: boolean;
};
/**
* Wrap xterm's keydown entry so a pure modifier keydown cannot arm the
* `insertText` dedupe guard. Installed per-terminal instance; the prototype
* method stays untouched.
*/
export function keepImeCommittedTextThroughModifierKeyDowns(term: XTerm): void {
const core = (term as XTerm & { _core?: XTermInputCore })._core;
if (!core || typeof core._keyDown !== "function") return;
const originalKeyDown = core._keyDown.bind(core);
core._keyDown = (event: KeyboardEvent) => {
if (!isModifierOnlyKeyDownEvent(event)) return originalKeyDown(event);
const seenBefore = core._keyDownSeen;
try {
return originalKeyDown(event);
} finally {
core._keyDownSeen = seenBefore;
}
};
}
@@ -1021,3 +1021,80 @@ test("a key pressed while disconnected cannot produce an orphan release after re
});
assert.deepEqual(writes, []);
});
test("a dedicated keyIdentity pairs the interrupt press with its release (#3409)", () => {
const options = () => {
// Disambiguate + event-type flags so Ctrl+C press/release encode as CSI-u.
const mode = createKittyKeyboardModeState();
setKittyKeyboardModeFlags(mode, 1 | 2);
return {
kittyProtocolEnabled: true,
kittyMode: mode,
applicationCursorMode: false,
encodedKeys: new Set<string>(),
legacySuppressedKeys: new Set<string>(),
};
};
// A Command+Period interrupt is normalized to a Ctrl+C event but paired under a
// dedicated identity, so it must not collapse with an outstanding physical
// KeyC press on the peer: the press, the legacy suppression and the release
// all use the propagated identity, while the physical KeyC state survives.
const pressOptions = options();
const interruptPress = resolveKittyKeyboardBroadcastInput({
kind: "key",
event: { type: "keydown", key: "c", code: "KeyC", ctrlKey: true },
keyIdentity: "KeyC mac-period-interrupt",
urgentInterrupt: true,
}, pressOptions);
assert.equal(interruptPress?.data, "\x1b[99;5u");
assert.ok(pressOptions.encodedKeys.has("KeyC mac-period-interrupt"));
assert.ok(pressOptions.legacySuppressedKeys.has("KeyC mac-period-interrupt"));
// The physical KeyC press keeps its own entry.
assert.equal(pressOptions.encodedKeys.has("KeyC"), false);
// The legacy \x03 fan-out under the dedicated identity is suppressed on a
// Kitty peer (already encoded) but delivered on a legacy peer.
assert.equal(resolveKittyKeyboardBroadcastInput({
kind: "legacy",
data: "\x03",
keyIdentity: "KeyC mac-period-interrupt",
urgentInterrupt: true,
}, pressOptions), null);
const legacyPeerOptions = options();
const legacyInterrupt = resolveKittyKeyboardBroadcastInput({
kind: "legacy",
data: "\x03",
keyIdentity: "KeyC mac-period-interrupt",
urgentInterrupt: true,
}, legacyPeerOptions);
assert.equal(legacyInterrupt?.data, "\x03");
assert.equal(legacyInterrupt?.urgentInterrupt, true);
// The release pairs under the dedicated identity, leaving the physical
// KeyC press entry intact for its own keyup.
const releaseOptions = options();
releaseOptions.encodedKeys.add("KeyC mac-period-interrupt");
releaseOptions.encodedKeys.add("KeyC");
releaseOptions.legacySuppressedKeys.add("KeyC");
const interruptRelease = resolveKittyKeyboardBroadcastInput({
kind: "key",
event: { type: "keyup", key: "c", code: "KeyC", ctrlKey: true },
keyIdentity: "KeyC mac-period-interrupt",
}, releaseOptions);
assert.equal(interruptRelease?.data, "\x1b[99;5:3u");
assert.ok(releaseOptions.encodedKeys.has("KeyC"));
assert.equal(releaseOptions.encodedKeys.has("KeyC mac-period-interrupt"), false);
// Without an explicit identity, pairing still keys from the event code.
const defaultOptions = options();
defaultOptions.encodedKeys.add("KeyA");
const defaultRelease = resolveKittyKeyboardBroadcastInput({
kind: "key",
event: { type: "keyup", key: "a", code: "KeyA" },
}, defaultOptions);
assert.equal(defaultRelease?.data, "\x1b[97;1:3u");
assert.equal(defaultOptions.encodedKeys.has("KeyA"), false);
});
@@ -19,6 +19,12 @@ export type KittyKeyboardBroadcastInput =
event: KittyKeyboardEvent;
fallbackToLegacy?: boolean;
urgentInterrupt?: boolean;
/**
* Pairing identity for peers whose state is keyed by correlation id
* rather than the event's physical code. Defaults to the event's code
* so ordinary key broadcasts are unchanged.
*/
keyIdentity?: string;
}
| {
kind: "win32";
@@ -196,6 +202,10 @@ export const flushKittyKeyboardBroadcastReleases = (
pending.delete(identity);
forward({
kind: "key",
// Keep the identity the press was recorded under so a peer whose
// pairing diverges from the event's physical code (e.g. a Command+Period interrupt
// normalized to Ctrl+C) still pairs this synthetic release (#3409).
keyIdentity: identity,
event: createKittyKeyboardSyntheticRelease(
forwardedPress.event,
Array.from(pending.values(), (pendingPress) => pendingPress.event),
@@ -309,7 +319,7 @@ export const resolveKittyKeyboardBroadcastInput = (
}, options);
}
const identity = input.event.code || input.event.key;
const identity = input.keyIdentity ?? (input.event.code || input.event.key);
const legacySuppressedKeys = options.legacySuppressedKeys ?? options.encodedKeys;
const hasPairedKeyDown = input.event.type === "keyup"
? options.encodedKeys.delete(identity)
@@ -10,7 +10,7 @@ const ts=require('typescript');
const bridge=require(root+'/electron/bridges/terminalBridge.cjs');
test('serial input combinations preserve the preceding device bytes after CJK deletion', async () => {
const modules = await Promise.all([
'domain/serialCharMetrics.ts', 'components/terminal/runtime/terminalInputSanitize.ts',
'components/terminal/runtime/terminalPacedBroadcast.ts', 'components/terminal/runtime/terminalReportSequence.ts', 'domain/serialCharMetrics.ts', 'components/terminal/runtime/terminalInputSanitize.ts',
'components/terminal/runtime/terminalBackspaceInput.ts', 'components/terminal/runtime/terminalPerCharacterInput.ts',
'components/terminal/runtime/terminalSudoAutofill.ts', 'components/terminal/runtime/terminalCommandExecution.ts',
'components/terminal/runtime/serialLocalEcho.ts', 'components/terminal/autocomplete/terminalStringCellWidth.ts',
@@ -27,7 +27,7 @@ for (const prefix of ['fresh','empty-arrow','submit','paste-submit','interrupt',
const session={encoding, serialPort:{write(data: string | Buffer){for(const byte of Buffer.from(data)) { if(byte===127||byte===8) wire=wire.subarray(0,Math.max(0,wire.length-1)); else wire=Buffer.concat([wire,Buffer.from([byte])]);}}}};
bridge.init({sessions:new Map([['s',session]]),electronModule:{}});
const ctx={host:{protocol:'serial',id:'h',label:'h'},sessionId:'s',sessionRef:{current:'s'},statusRef:{current:'connected'},commandBufferRef:{current:''},onBroadcastInputRef:{current:null},isBroadcastEnabledRef:{current:false},terminalBackend:{writeToSession(id:string,data:string,opts: {serialEraseChar?: string; sensitive?: boolean}){bridge.writeToSession({}, {sessionId:id,data,...opts})}},serialByteOrientedBackspace:true,serialLocalEcho:false};
const env={...Object.assign({},...modules),api: undefined as unknown as {handleTerminalInputData: (data: string) => void; recordSerialSnippetInput: (data: string) => void},ctx,term:{buffer:{active:{cursorX:0,cursorY:0,baseY:0,getLine:()=>undefined}},cols:80},suppressNextTerminalDataBroadcast:false,handlingKittyBroadcast:false,shouldBroadcastTerminalUserInput:()=>false,prioritizeTerminalInput:()=>{},getFlowControllerForTerm:()=>null,shouldSuppressTerminalInputScrollForUserPaste:()=>true,scrollToBottomAfterInput:()=>{},writeLocalTerminalData:()=>{}};
const env={...Object.assign({},...modules),api: undefined as unknown as {handleTerminalInputData: (data: string) => void; recordSerialSnippetInput: (data: string) => void},ctx,term:{buffer:{active:{cursorX:0,cursorY:0,baseY:0,getLine:()=>undefined}},cols:80},suppressNextTerminalDataBroadcast:false,handlingKittyBroadcast:false,shouldBroadcastTerminalUserInput:()=>false,prioritizeTerminalInput:()=>{},getFlowControllerForTerm:()=>null,shouldSuppressTerminalInputScrollForUserPaste:()=>true,shouldOverrideTerminalUserPasteSensitivity:()=>false,scrollToBottomAfterInput:()=>{},writeLocalTerminalData:()=>{}};
vm.runInNewContext(code,env); const {handleTerminalInputData:input,recordSerialSnippetInput:snippet}=env.api;
if(prefix==='empty-arrow') input('\x1b[D');
if(prefix==='submit') {input('旧');input('\x1b[D');input('\r');}
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more