mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 10:53:56 +00:00
Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ae0e17501 | ||
|
|
645d7a4f5d | ||
|
|
9d99c675ab | ||
|
|
9a49ac33bf | ||
|
|
da162f050b | ||
|
|
834ca122c4 | ||
|
|
ac885e2a36 | ||
|
|
fea4e1eda0 | ||
|
|
cb87b71603 | ||
|
|
b1de01546f | ||
|
|
d5acb4641e | ||
|
|
60841628d6 | ||
|
|
99197b3e18 | ||
|
|
d052a8597c | ||
|
|
d4f819b885 | ||
|
|
8930270820 | ||
|
|
5789b28014 | ||
|
|
8c66f8786d | ||
|
|
29be836550 | ||
|
|
703148c84f | ||
|
|
5b33d410f9 | ||
|
|
c27a40e5f0 | ||
|
|
30f9a91576 | ||
|
|
6461acb575 | ||
|
|
2347f33bc8 | ||
|
|
22e6b02ce2 | ||
|
|
58bc929a17 | ||
|
|
7e94183b89 | ||
|
|
b8d05b3074 | ||
|
|
e99ab5a8eb | ||
|
|
9a2d6ef7bf | ||
|
|
27a6f2e7a6 | ||
|
|
c52ca5f730 | ||
|
|
0aeb1df039 | ||
|
|
b8f3577cd8 | ||
|
|
412f6c4ec6 | ||
|
|
32b1b633db | ||
|
|
e2b0f83ea9 | ||
|
|
4d7906a710 | ||
|
|
9c14e3934f | ||
|
|
59db998ec4 | ||
|
|
78c7d30648 | ||
|
|
4c3f0ce80b | ||
|
|
fd732dff9c | ||
|
|
93bec7497c | ||
|
|
fa9b28adde | ||
|
|
0eefb9ea46 | ||
|
|
ed90d61014 | ||
|
|
d066f1f082 | ||
|
|
b64c36fd40 | ||
|
|
403c690061 | ||
|
|
a4805b3e3d | ||
|
|
5a1352aab0 | ||
|
|
a9cf94aeba | ||
|
|
196132621c | ||
|
|
0098f2e670 | ||
|
|
730c8cad59 | ||
|
|
d9cb9a8fbc | ||
|
|
bbbcf72b81 | ||
|
|
10ad09fe34 | ||
|
|
040aec53b2 | ||
|
|
2bf8611919 | ||
|
|
1d53af5a51 | ||
|
|
3c3319eead | ||
|
|
50dbb5cb5f | ||
|
|
462c2adb2a | ||
|
|
610da46a6f | ||
|
|
30e9609b1b | ||
|
|
6527d5596f | ||
|
|
a791d0b8c4 | ||
|
|
bcce829294 | ||
|
|
6cdf6b836b | ||
|
|
182531d7a7 | ||
|
|
abd074fe95 | ||
|
|
fedab5ec3b | ||
|
|
ad612aeb0c |
No files matched your search
@@ -154,5 +154,12 @@ jobs:
|
||||
NETCATTY_SSH_TEST_RUNTIME: electron
|
||||
run: node --test electron/bridges/sshChaChaTransport.test.cjs
|
||||
|
||||
- name: Exercise native PowerShell and CMD directory navigation in ConPTY
|
||||
env:
|
||||
NETCATTY_DIRECTORY_WINDOWS_LIVE: "1"
|
||||
run: |
|
||||
$env:NETCATTY_TEST_PWSH = (Get-Command pwsh -ErrorAction Stop).Source
|
||||
node --test --test-force-exit --import tsx infrastructure/services/terminalDirectory.windows.test.ts
|
||||
|
||||
- name: Exercise two SSH password prompts in the desktop app
|
||||
run: node scripts/terminal-broadcast-ssh.live.cjs
|
||||
@@ -100,7 +100,7 @@ Placement rules (`resolveAgentKinds` in `toolSurfaces.cjs`):
|
||||
| Vault bridge | `electron/bridges/aiBridge/vaultAgentBridge.cjs` + `infrastructure/ai/vaultAgentBridgeClient.ts` | Renderer vault state; **never** returns password/privateKey |
|
||||
| AI context | `buildAITerminalSessionInfo` + `useTerminalAiContexts` | Per-session `hostChain` + `activePortForwards`; mirrored in `getContext` and Catty system prompt |
|
||||
|
||||
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes.
|
||||
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes. `terminal_execute_bulk` (2–20 sessions, loaded via the `terminal_bulk` toolset) is all-or-nothing before sending and sets `policy.requiresFreshApproval`: remembered grants and external-client session approval never satisfy it. See `docs/features/terminal-execute-bulk.md`.
|
||||
|
||||
**Handles:** `ToolOutputStore` persists across turns per chat session; cleared on chat session delete. Large `sftp.read` results spill to `tool_output_read`.
|
||||
|
||||
|
||||
@@ -145,6 +145,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
|
||||
- **File workflows** — drag & drop uploads/downloads
|
||||
- **Edit in place** — built-in editor for quick changes
|
||||
- **Create remote archives** — select files or folders, right-click **Compress...**, and create a named `.tar.gz` or `.zip` archive in the displayed destination directory; the server needs `tar`/`gzip` or `zip` for the chosen format.
|
||||
- **Packed downloads** — download folders or multiple items in one stream, then automatically restore their original layout locally without leaving an archive on the server. Enabled by default in SFTP settings; unsupported connections use regular downloads. [Details and compatibility](docs/features/sftp-packed-download.md).
|
||||
|
||||
### 🎨 Personalization
|
||||
- **Custom themes** — tune the app appearance to your taste
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
- **文件工作流** —— 拖拽上传/下载更直观
|
||||
- **就地编辑** —— 内置编辑器快速修改文件
|
||||
- **远程压缩** —— 单选或多选文件、文件夹,右键选择“压缩…”,在对话框显示的保存目录生成指定名称的 `.tar.gz` 或 `.zip` 压缩包;服务器需安装对应的 `tar`/`gzip` 或 `zip`。
|
||||
- **打包下载** —— 下载文件夹或多个项目时,将所选内容一次传回并在本地自动还原原有目录结构,服务器不留压缩包。SFTP 设置中默认开启;不支持时使用普通下载。[使用说明与兼容性](docs/features/sftp-packed-download.md)。
|
||||
|
||||
### 🎨 个性化
|
||||
- **自定义主题** —— 按喜好调整应用外观
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
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 { createLocalShellHost } from '../domain/localShellHost';
|
||||
import { collectSessionIds } from '../domain/workspace';
|
||||
import { executeHotkeyActionImpl, handleGlobalHotkeyKeyDownImpl } from './app/AppHandlers';
|
||||
import { DEFAULT_KEY_BINDINGS, matchesKeyBinding } from '../domain/models/keyBindings';
|
||||
import { activeTabStore } from './state/activeTabStore';
|
||||
import { resolveCloseIntent } from './state/resolveCloseIntent';
|
||||
import { useSessionState } from './state/useSessionState';
|
||||
|
||||
async function setup(t: test.TestContext, paneCount: number | 'standalone', terminalFocus = true) {
|
||||
const dom = new JSDOM(
|
||||
'<div id="root"></div><div data-session-id="focused"><textarea class="xterm-helper-textarea"></textarea></div><button>Outside terminal</button>',
|
||||
{ url: 'http://localhost' },
|
||||
);
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of Object.entries({
|
||||
window: dom.window,
|
||||
document: dom.window.document,
|
||||
HTMLElement: dom.window.HTMLElement,
|
||||
localStorage: dom.window.localStorage,
|
||||
CustomEvent: dom.window.CustomEvent,
|
||||
Event: dom.window.Event,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
});
|
||||
let state: ReturnType<typeof useSessionState>;
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
await act(async () => root.render(React.createElement(Probe)));
|
||||
await act(async () => {
|
||||
if (paneCount === 'standalone') state.createLocalTerminal();
|
||||
else state.createWorkspaceWithHosts('Split tab', Array.from({ length: paneCount }, (_, index) => (
|
||||
createLocalShellHost({ id: `local-${index}` })
|
||||
)));
|
||||
});
|
||||
// Choose the second pane so closing an arbitrary first pane cannot pass.
|
||||
if (paneCount !== 'standalone' && paneCount > 1) {
|
||||
await act(async () => state.setWorkspaceFocusedSession(state.workspaces[0].id, state.sessions[1].id));
|
||||
}
|
||||
document.querySelector<HTMLElement>(terminalFocus ? 'textarea' : 'button')!.focus();
|
||||
const confirmations: string[][] = [];
|
||||
const closeTabInFlightRef = { current: false };
|
||||
const execute = (action: string, event: KeyboardEvent) => executeHotkeyActionImpl(() => ({
|
||||
activeTabStore,
|
||||
closeSession: state.closeSession,
|
||||
closeWorkspace: state.closeWorkspace,
|
||||
closeTabInFlightRef,
|
||||
collectSessionIds,
|
||||
confirmIfBusyLocalTerminal: async (ids: string[]) => { confirmations.push(ids); return true; },
|
||||
editorTabs: [],
|
||||
isEditorTabId: () => false,
|
||||
orderedTabs: [],
|
||||
resolveCloseIntent,
|
||||
sessions: state.sessions,
|
||||
settings: {},
|
||||
workspaces: state.workspaces,
|
||||
}), action, event);
|
||||
return {
|
||||
get state() { return state!; },
|
||||
confirmations,
|
||||
async press(shiftKey = false, scheme: 'mac' | 'pc' = 'mac') {
|
||||
const event = new dom.window.KeyboardEvent('keydown', {
|
||||
key: 'w', code: 'KeyW', metaKey: scheme === 'mac', ctrlKey: scheme === 'pc', shiftKey,
|
||||
bubbles: true, cancelable: true,
|
||||
});
|
||||
document.activeElement!.addEventListener('keydown', (e) => handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: scheme === 'mac' ? '\u2318 + W' : 'Ctrl + W',
|
||||
executeHotkeyAction: execute,
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
}), e as KeyboardEvent), { once: true });
|
||||
await act(async () => { document.activeElement!.dispatchEvent(event); });
|
||||
assert.equal(event.defaultPrevented, true);
|
||||
assert.equal(closeTabInFlightRef.current, false);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
for (const scheme of ['mac', 'pc'] as const) {
|
||||
for (const terminalFocus of [true, false]) {
|
||||
test(`${scheme} close-tab closes every pane and the tab with terminal focus ${terminalFocus}`, async (t) => {
|
||||
const harness = await setup(t, 2, terminalFocus);
|
||||
const ids = harness.state.sessions.map((session) => session.id);
|
||||
await harness.press(false, scheme);
|
||||
assert.deepEqual(harness.state.sessions, []);
|
||||
assert.deepEqual(harness.state.workspaces, []);
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault');
|
||||
assert.deepEqual(harness.confirmations, [ids]);
|
||||
});
|
||||
}
|
||||
|
||||
test(`${scheme} close-pane closes only the focused pane in a split tab`, async (t) => {
|
||||
const harness = await setup(t, 2);
|
||||
const workspace = harness.state.workspaces[0];
|
||||
const focusedId = workspace.focusedSessionId;
|
||||
const survivorId = harness.state.sessions[0].id;
|
||||
await harness.press(true, scheme);
|
||||
assert.deepEqual(harness.state.sessions.map((session) => session.id), [survivorId]);
|
||||
assert.equal(harness.state.workspaces.length, 1);
|
||||
assert.deepEqual(collectSessionIds(harness.state.workspaces[0].root), [survivorId]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
|
||||
assert.deepEqual(harness.confirmations, [[focusedId]]);
|
||||
});
|
||||
|
||||
for (const paneCount of [1, 'standalone'] as const) {
|
||||
test(`${scheme} close-pane closes a ${paneCount} pane tab`, async (t) => {
|
||||
const harness = await setup(t, paneCount);
|
||||
const id = harness.state.sessions[0].id;
|
||||
await harness.press(true, scheme);
|
||||
assert.deepEqual(harness.state.sessions, []);
|
||||
assert.deepEqual(harness.state.workspaces, []);
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault');
|
||||
assert.deepEqual(harness.confirmations, [[id]]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1032,3 +1032,108 @@ test('host list shortcut calls the same store toggle as the toolbar button', ()
|
||||
const source = readFileSync(new URL('./app/AppSideEffects.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /toggleHostTree:\s*\(\)\s*=>\s*terminalHostTreeStore\.toggle\(\)/);
|
||||
});
|
||||
|
||||
test('Cmd+Shift+T on macOS and Ctrl+Shift+T on PC dispatch reopenClosedTab and stay out of text inputs', () => {
|
||||
for (const [scheme, keyProps] of [
|
||||
['mac', { metaKey: true, ctrlKey: false }],
|
||||
['pc', { metaKey: false, ctrlKey: true }],
|
||||
] as const) {
|
||||
const target = new FakeHTMLElement();
|
||||
const actions: string[] = [];
|
||||
let prevented = false;
|
||||
let stopped = false;
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
executeHotkeyAction: (action: string) => {
|
||||
actions.push(action);
|
||||
},
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
}), {
|
||||
key: 'T',
|
||||
code: 'KeyT',
|
||||
...keyProps,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented = true; },
|
||||
stopPropagation: () => { stopped = true; },
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(actions, ['reopenClosedTab']);
|
||||
assert.equal(prevented, true);
|
||||
assert.equal(stopped, true);
|
||||
|
||||
const input = new FakeInputHTMLElement();
|
||||
const inputActions: string[] = [];
|
||||
handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
executeHotkeyAction: (action: string) => {
|
||||
inputActions.push(action);
|
||||
},
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
}), {
|
||||
key: 'T',
|
||||
code: 'KeyT',
|
||||
...keyProps,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
target: input,
|
||||
composedPath: () => [input],
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(inputActions, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and records connection logs for reopened workspace panes', () => {
|
||||
const logs: Array<Record<string, unknown>> = [];
|
||||
let receivedHostIds: string[] = [];
|
||||
const hostsById = new Map([
|
||||
['h-1', { id: 'h-1', label: 'Prod', hostname: 'prod.test', username: 'ops', port: 22, os: 'linux', group: '', tags: [] }],
|
||||
]);
|
||||
|
||||
executeHotkeyActionImpl(() => ({
|
||||
activeTabStore: { getActiveTabId: () => 'vault' },
|
||||
addConnectionLogRef: { current: (log: Record<string, unknown>) => logs.push(log) },
|
||||
editorTabs: [],
|
||||
hostsById,
|
||||
orderedTabs: [],
|
||||
reopenLastClosedTab: (opts: { availableHostIds?: ReadonlySet<string> }) => {
|
||||
receivedHostIds = [...(opts.availableHostIds ?? [])];
|
||||
return {
|
||||
kind: 'workspace',
|
||||
tabId: 'ws-new',
|
||||
workspace: { id: 'ws-new', title: 'Prod Split', root: { id: 'p', type: 'pane', sessionId: 's-new-1' } },
|
||||
sessions: [
|
||||
{ id: 's-new-1', hostId: 'h-1', hostLabel: 'Prod', hostname: 'prod.test', username: 'ops', status: 'connecting', protocol: 'ssh', workspaceId: 'ws-new' },
|
||||
{ id: 's-new-2', hostId: 'local-terminal', hostLabel: 'Local Terminal', hostname: 'localhost', username: 'local', status: 'connecting', protocol: 'local', workspaceId: 'ws-new' },
|
||||
],
|
||||
};
|
||||
},
|
||||
sessions: [],
|
||||
settings: {},
|
||||
systemInfoRef: { current: { username: 'dev', hostname: 'laptop' } },
|
||||
toEditorTabId: (id: string) => id,
|
||||
workspaces: [],
|
||||
}), 'reopenClosedTab', {} as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(receivedHostIds, ['h-1']);
|
||||
assert.equal(logs.length, 2);
|
||||
assert.equal(logs[0].sessionId, 's-new-1');
|
||||
assert.equal(logs[0].hostId, 'h-1');
|
||||
assert.equal(logs[0].username, 'ops');
|
||||
assert.equal(logs[1].sessionId, 's-new-2');
|
||||
assert.equal(logs[1].hostId, '');
|
||||
assert.equal(logs[1].username, 'dev');
|
||||
assert.equal(logs[1].protocol, 'local');
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import type { TerminalSession } from "../domain/models";
|
||||
import { copySessionToNewWindowWithCurrentShellImpl } from "./app/AppHandlers";
|
||||
import { copySessionToNewWindowWithCurrentShellImpl, moveSessionToNewWindowImpl } from "./app/AppHandlers";
|
||||
|
||||
const sourceSession = (overrides: Partial<TerminalSession> = {}): TerminalSession => ({
|
||||
id: "session-1",
|
||||
@@ -187,3 +187,164 @@ test("copySessionToNewWindowWithCurrentShellImpl shows an error when the bridge
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(errors, ["Could not open"]);
|
||||
});
|
||||
|
||||
const moveCtx = (openTerminalPopup: ((payload: Record<string, unknown>) => Promise<unknown>) | undefined) => {
|
||||
const calls: unknown[][] = [];
|
||||
const errors: string[] = [];
|
||||
const getCtx = () => ({
|
||||
netcattyBridge: { get: () => (openTerminalPopup ? { openTerminalPopup } : {}) },
|
||||
sessions: [sourceSession({ id: "other" }), sourceSession()],
|
||||
setActiveTabId: (id: string) => calls.push(["active", id]),
|
||||
setSessionPoppedOut: (id: string, poppedOut: boolean) => calls.push(["poppedOut", id, poppedOut]),
|
||||
t: (key: string) => key,
|
||||
toast: { error: (message: string) => errors.push(message) },
|
||||
});
|
||||
return { calls, errors, getCtx };
|
||||
};
|
||||
|
||||
test("moveSessionToNewWindowImpl hides the tab and attaches a popup to the same live session", async () => {
|
||||
const payloads: Record<string, unknown>[] = [];
|
||||
const { calls, errors, getCtx } = moveCtx(async (payload) => {
|
||||
payloads.push(payload);
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
assert.equal(await moveSessionToNewWindowImpl(getCtx, "session-1"), true);
|
||||
assert.deepEqual(calls, [["poppedOut", "session-1", true], ["active", "other"]]);
|
||||
assert.equal(payloads[0].attachSessionId, "session-1");
|
||||
assert.equal(payloads[0].moveSession, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl leaves the tab untouched when the popup fails to attach", async () => {
|
||||
const { calls, errors, getCtx } = moveCtx(async () => ({ success: false, error: "boom" }));
|
||||
|
||||
assert.equal(await moveSessionToNewWindowImpl(getCtx, "session-1"), false);
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(errors, ["boom"]);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl waits for popup attachment before hiding the tab", async () => {
|
||||
let resolveOpen: ((value: unknown) => void) | null = null;
|
||||
const { calls, getCtx } = moveCtx(
|
||||
() => new Promise((resolve) => { resolveOpen = resolve; }),
|
||||
);
|
||||
|
||||
const pending = moveSessionToNewWindowImpl(getCtx, "session-1");
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(calls, []);
|
||||
|
||||
resolveOpen?.({ success: true });
|
||||
assert.equal(await pending, true);
|
||||
assert.deepEqual(calls, [["poppedOut", "session-1", true], ["active", "other"]]);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl ignores tabs without a live backend", async () => {
|
||||
const { calls, getCtx } = moveCtx(async () => ({ success: true }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({ ...ctx, sessions: [sourceSession({ status: "disconnected" })] }),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl ignores plugin-backed sessions", async () => {
|
||||
const { calls, getCtx } = moveCtx(async () => ({ success: true }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({ ...ctx, sessions: [sourceSession({ protocol: "plugin:com.acme.db" })] }),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl ignores workspace panes", async () => {
|
||||
const { calls, getCtx } = moveCtx(async () => ({ success: true }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({ ...ctx, sessions: [sourceSession({ workspaceId: "ws-1" })] }),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl preserves active tab focus when moving an inactive tab", async () => {
|
||||
const { calls, errors, getCtx } = moveCtx(async () => ({ success: true }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({
|
||||
...ctx,
|
||||
getActiveTabId: () => "ws-1",
|
||||
getOrderedTabs: () => ["ws-1", "session-1"],
|
||||
}),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(calls, [["poppedOut", "session-1", true]]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl does not steal focus when moving an inactive tab fails", async () => {
|
||||
const { calls, errors, getCtx } = moveCtx(async () => ({ success: false, error: "nope" }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({
|
||||
...ctx,
|
||||
getActiveTabId: () => "editor:1",
|
||||
getOrderedTabs: () => ["editor:1", "session-1"],
|
||||
}),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, false);
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(errors, ["nope"]);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl selects the adjacent ordered visible tab when moving the active tab", async () => {
|
||||
const { calls, getCtx } = moveCtx(async () => ({ success: true }));
|
||||
const ctx = getCtx();
|
||||
const result = await moveSessionToNewWindowImpl(
|
||||
() => ({
|
||||
...ctx,
|
||||
sessions: [sourceSession()],
|
||||
getActiveTabId: () => "session-1",
|
||||
getOrderedTabs: () => ["ws-1", "session-1", "editor:1"],
|
||||
}),
|
||||
"session-1",
|
||||
);
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(calls, [["poppedOut", "session-1", true], ["active", "ws-1"]]);
|
||||
});
|
||||
|
||||
test("moveSessionToNewWindowImpl closes the popup if the tab moved into a workspace during startup", async () => {
|
||||
const closedPopups: string[] = [];
|
||||
let sessions: TerminalSession[] = [sourceSession()];
|
||||
const calls: unknown[][] = [];
|
||||
const getCtx = () => ({
|
||||
netcattyBridge: {
|
||||
get: () => ({
|
||||
openTerminalPopup: async () => {
|
||||
sessions = [sourceSession({ workspaceId: "ws-late" })];
|
||||
return { success: true, popupId: "popup-late" };
|
||||
},
|
||||
closeTerminalPopup: async (popupId: string) => {
|
||||
closedPopups.push(popupId);
|
||||
return { success: true };
|
||||
},
|
||||
}),
|
||||
},
|
||||
sessions,
|
||||
setActiveTabId: (id: string) => calls.push(["active", id]),
|
||||
setSessionPoppedOut: (id: string, poppedOut: boolean) => calls.push(["poppedOut", id, poppedOut]),
|
||||
t: (key: string) => key,
|
||||
toast: { error: () => {} },
|
||||
});
|
||||
|
||||
assert.equal(await moveSessionToNewWindowImpl(getCtx, "session-1"), false);
|
||||
assert.deepEqual(closedPopups, ["popup-late"]);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
@@ -63,6 +63,34 @@ test("handleTrayJumpToSessionImpl opens a terminal popup for AI silent sessions"
|
||||
assert.deepEqual(opened[0], buildAiSilentSessionPopupPayload(session({ hiddenFromTabs: true })));
|
||||
});
|
||||
|
||||
test("handleTrayJumpToSessionImpl reasserts poppedOut after reopening a moved tab", async () => {
|
||||
const poppedCalls: Array<[string, boolean]> = [];
|
||||
const opened: unknown[] = [];
|
||||
await handleTrayJumpToSessionImpl(
|
||||
() => ({
|
||||
sessions: [session({ hiddenFromTabs: true, poppedOut: true })],
|
||||
setActiveTabId: () => {},
|
||||
setSessionPoppedOut: (id: string, poppedOut: boolean) => poppedCalls.push([id, poppedOut]),
|
||||
setWorkspaceFocusedSession: () => {},
|
||||
getActiveTabId: () => "vault",
|
||||
netcattyBridge: {
|
||||
get: () => ({
|
||||
openTerminalPopup: async (payload: unknown) => {
|
||||
opened.push(payload);
|
||||
return { success: true, popupId: "popup-reopen" };
|
||||
},
|
||||
}),
|
||||
},
|
||||
toast: { error: () => {} },
|
||||
t: (k: string) => k,
|
||||
}),
|
||||
"session-1",
|
||||
);
|
||||
|
||||
assert.equal((opened[0] as { moveSession?: boolean }).moveSession, true);
|
||||
assert.deepEqual(poppedCalls, [["session-1", true]]);
|
||||
});
|
||||
|
||||
test("handleTrayJumpToSessionImpl still activates normal solo sessions in the main window", async () => {
|
||||
let activeTabId = "vault";
|
||||
let openedMain = 0;
|
||||
|
||||
+346
-28
@@ -8,6 +8,26 @@ import { resolveHostDefaultLocalShell } from '../../domain/localShellHost';
|
||||
import { getAvailablePaneMagnificationController } from '../../domain/paneMagnification';
|
||||
import { sanitizeHostIconFields } from '../../domain/hostIcon';
|
||||
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
|
||||
import { isPluginHostProtocol } from '../../domain/pluginConnection';
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
buildHostForProtocolOverride,
|
||||
isRemoteDesktopProtocol,
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
shouldPromptHostProtocolOnConnect,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import { resolveTerminalChainHosts } from '../../domain/terminalHostResolution';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import {
|
||||
buildSystemRemoteDesktopPayload,
|
||||
isRemoteDesktopGrabReleaseChord,
|
||||
isTargetInsideRemoteDesktopCapture,
|
||||
} from '../../components/remoteDesktop/remoteDesktopHelpers';
|
||||
import {
|
||||
getConnectionLogsActions,
|
||||
getConnectionLogsSnapshot,
|
||||
} from '../state/connectionLogsStore';
|
||||
import { getTerminalPassthroughActions } from '../state/useGlobalHotkeys';
|
||||
import { getSettingsChromeSnapshot } from '../state/settingsChromeStore';
|
||||
import { isHostTreeWorkTabSurface } from './workTabSurface';
|
||||
@@ -73,7 +93,7 @@ export const getLogHostVisualSnapshot = (host: Host) => {
|
||||
* spawning a new shell via connection reuse.
|
||||
*/
|
||||
export function buildAiSilentSessionPopupPayload(session: TerminalSession): TerminalPopupPayload {
|
||||
const { hiddenFromTabs: _hiddenFromTabs, ...sourceSession } = session;
|
||||
const { hiddenFromTabs: _hiddenFromTabs, poppedOut: _poppedOut, ...sourceSession } = session;
|
||||
return {
|
||||
title: session.hostLabel || 'Terminal',
|
||||
parentSessionId: session.id,
|
||||
@@ -89,6 +109,7 @@ export async function handleTrayJumpToSessionImpl(getCtx: AppContextGetter, sess
|
||||
const {
|
||||
sessions,
|
||||
setActiveTabId,
|
||||
setSessionPoppedOut,
|
||||
setWorkspaceFocusedSession,
|
||||
netcattyBridge,
|
||||
toast,
|
||||
@@ -111,13 +132,20 @@ export async function handleTrayJumpToSessionImpl(getCtx: AppContextGetter, sess
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await bridge.openTerminalPopup(buildAiSilentSessionPopupPayload(session));
|
||||
const payload = session.poppedOut
|
||||
? { ...buildAiSilentSessionPopupPayload(session), moveSession: true }
|
||||
: buildAiSilentSessionPopupPayload(session);
|
||||
const result = await bridge.openTerminalPopup(payload);
|
||||
if (!result?.success) {
|
||||
toast?.error?.(
|
||||
result?.error
|
||||
|| t?.('tabs.copyTabToNewWindowFailed')
|
||||
|| 'Failed to open tab in a new window',
|
||||
);
|
||||
} else if (session.poppedOut) {
|
||||
// Reassert popped-out state in case a stale attach-closed event from a
|
||||
// prior crashed popup arrived while the replacement popup was attaching.
|
||||
setSessionPoppedOut?.(sessionId, true);
|
||||
}
|
||||
} catch (err) {
|
||||
toast?.error?.(
|
||||
@@ -244,6 +272,13 @@ export function flushQueuedTrayPanelConnectHostsImpl(getCtx: AppContextGetter) {
|
||||
export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEvent) {
|
||||
const { HOTKEY_DEBUG, closeTabKeyStr, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
|
||||
{
|
||||
if (
|
||||
isTargetInsideRemoteDesktopCapture(e.target, e.composedPath?.bind(e))
|
||||
&& !isRemoteDesktopGrabReleaseChord(e)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isMac = hotkeyScheme === 'mac';
|
||||
const target = e.target as HTMLElement;
|
||||
const isCloseTabHotkey = closeTabKeyStr ? matchesKeyBinding(e, closeTabKeyStr, isMac) : false;
|
||||
@@ -695,6 +730,96 @@ export async function copySessionToNewWindowWithCurrentShellImpl(getCtx: AppCont
|
||||
}
|
||||
}
|
||||
|
||||
const inFlightMoveSessions = new Set<string>();
|
||||
|
||||
/**
|
||||
* Move a solo tab into its own window without reconnecting: an attach popup
|
||||
* takes over the same live PTY (no second login, e.g. on a bastion with seat
|
||||
* limits). The tab is hidden only after the popup actually attaches, and
|
||||
* closing the popup brings it back via onTerminalPopupAttachClosed.
|
||||
*/
|
||||
export async function moveSessionToNewWindowImpl(getCtx: AppContextGetter, sessionId: string) {
|
||||
if (inFlightMoveSessions.has(sessionId)) return false;
|
||||
const {
|
||||
getActiveTabId,
|
||||
getOrderedTabs,
|
||||
netcattyBridge,
|
||||
sessions,
|
||||
setActiveTabId,
|
||||
setSessionPoppedOut,
|
||||
t,
|
||||
toast,
|
||||
} = getCtx();
|
||||
const session = sessions.find((item: TerminalSession) => item.id === sessionId);
|
||||
// Attach mode only takes over a live non-plugin backend; plugin connections
|
||||
// remain owned by their source renderer until plugin lifetime transfer exists.
|
||||
if (
|
||||
!session
|
||||
|| session.workspaceId
|
||||
|| session.hiddenFromTabs
|
||||
|| session.status !== 'connected'
|
||||
|| isPluginHostProtocol(session.protocol)
|
||||
|| (typeof session.protocol === 'string' && session.protocol.startsWith('plugin:'))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const fail = (error?: string) => {
|
||||
toast?.error?.(error || (t?.('tabs.moveTabToNewWindowFailed') ?? 'Failed to move tab to a new window'));
|
||||
return false;
|
||||
};
|
||||
const bridge = netcattyBridge?.get?.();
|
||||
if (!bridge?.openTerminalPopup) return fail();
|
||||
|
||||
inFlightMoveSessions.add(sessionId);
|
||||
try {
|
||||
const result = await bridge.openTerminalPopup({ ...buildAiSilentSessionPopupPayload(session), moveSession: true });
|
||||
if (!result?.success) return fail(result?.error);
|
||||
|
||||
const latestCtx = getCtx();
|
||||
const latestSessions: TerminalSession[] = latestCtx.sessions ?? sessions;
|
||||
const stillPresent = latestSessions.find((item: TerminalSession) => item.id === sessionId);
|
||||
if (!stillPresent || stillPresent.workspaceId || stillPresent.hiddenFromTabs) {
|
||||
if (typeof result.popupId === 'string' && result.popupId) {
|
||||
void bridge.closeTerminalPopup?.(result.popupId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const latestGetActiveTabId = latestCtx.getActiveTabId ?? getActiveTabId;
|
||||
const latestGetOrderedTabs = latestCtx.getOrderedTabs ?? getOrderedTabs;
|
||||
const latestSetActiveTabId = latestCtx.setActiveTabId ?? setActiveTabId;
|
||||
const latestSetSessionPoppedOut = latestCtx.setSessionPoppedOut ?? setSessionPoppedOut;
|
||||
const isActive = typeof latestGetActiveTabId === 'function' ? latestGetActiveTabId() === sessionId : true;
|
||||
|
||||
latestSetSessionPoppedOut(sessionId, true);
|
||||
if (isActive) {
|
||||
const orderedTabs = typeof latestGetOrderedTabs === 'function' ? latestGetOrderedTabs() : null;
|
||||
let fallbackTab: string | undefined;
|
||||
if (Array.isArray(orderedTabs) && orderedTabs.length > 0) {
|
||||
const index = orderedTabs.indexOf(sessionId);
|
||||
const candidate = index >= 0
|
||||
? (orderedTabs[index - 1] ?? orderedTabs[index + 1])
|
||||
: orderedTabs.filter((id: string) => id !== sessionId).slice(-1)[0];
|
||||
if (candidate && candidate !== sessionId) {
|
||||
fallbackTab = candidate;
|
||||
}
|
||||
}
|
||||
if (!fallbackTab) {
|
||||
fallbackTab = latestSessions
|
||||
.filter((item: TerminalSession) => item.id !== sessionId && !item.workspaceId && !item.hiddenFromTabs)
|
||||
.slice(-1)[0]?.id ?? 'vault';
|
||||
}
|
||||
latestSetActiveTabId(fallbackTab);
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
return fail(err instanceof Error ? err.message : undefined);
|
||||
} finally {
|
||||
inFlightMoveSessions.delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmIfBusyLocalTerminalImpl(getCtx: AppContextGetter, sessionIds: string[]) {
|
||||
const { netcattyBridge, sessions, t } = getCtx();
|
||||
{
|
||||
@@ -757,6 +882,40 @@ export function collectBatchBusyProbeSessionIds(
|
||||
return sessionIdsToProbe;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp `endTime` on open RDP/VNC `ConnectionLog` entries when remote desktop
|
||||
* sessions close so they do not stay stuck at "Ongoing" in Connection Logs.
|
||||
*/
|
||||
export function stampRemoteDesktopSessionEndTimes(
|
||||
getCtx: AppContextGetter,
|
||||
closingSessionIds: readonly string[],
|
||||
): number {
|
||||
if (!closingSessionIds.length) return 0;
|
||||
const ctx = getCtx();
|
||||
const sessionsList: TerminalSession[] = Array.isArray(ctx.sessions) ? ctx.sessions : [];
|
||||
const logs = Array.isArray(ctx.connectionLogs)
|
||||
? ctx.connectionLogs
|
||||
: [...getConnectionLogsSnapshot().connectionLogs];
|
||||
const updateLog = ctx.updateConnectionLog ?? getConnectionLogsActions()?.updateConnectionLog;
|
||||
if (!updateLog || logs.length === 0) return 0;
|
||||
|
||||
let stamped = 0;
|
||||
const now = Date.now();
|
||||
for (const sessionId of new Set(closingSessionIds)) {
|
||||
const session = sessionsList.find((candidate) => candidate.id === sessionId);
|
||||
const matchingLog = selectConnectionLogForTerminalDataCapture(logs, {
|
||||
sessionId,
|
||||
hostname: session?.hostname,
|
||||
});
|
||||
if (!matchingLog || matchingLog.endTime) continue;
|
||||
const protocol = session?.protocol ?? matchingLog.protocol;
|
||||
if (!isRemoteDesktopProtocol(protocol)) continue;
|
||||
void Promise.resolve(updateLog(matchingLog.id, { endTime: now })).catch(() => {});
|
||||
stamped += 1;
|
||||
}
|
||||
return stamped;
|
||||
}
|
||||
|
||||
export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: string[]) {
|
||||
const {
|
||||
closeLogView, closeSessions, closeTabsInFlightRef, closeWorkspace,
|
||||
@@ -794,6 +953,12 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
|
||||
sessions.some((session) => session.workspaceId === id && keepTabIds.has(session.id))
|
||||
));
|
||||
const standaloneSessionIds = effectiveRegularIds.filter((id) => sessions.some((session) => session.id === id));
|
||||
const workspaceSessionIds = effectiveRegularIds.flatMap((id) => (
|
||||
workspaces.some((workspace) => workspace.id === id)
|
||||
? sessions.filter((session) => session.workspaceId === id).map((session) => session.id)
|
||||
: []
|
||||
));
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [...standaloneSessionIds, ...workspaceSessionIds]);
|
||||
if (standaloneSessionIds.length) closeSessions(standaloneSessionIds);
|
||||
for (const id of effectiveRegularIds) {
|
||||
if (workspaces.some((workspace) => workspace.id === id)) closeWorkspace(id);
|
||||
@@ -816,7 +981,7 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
|
||||
}
|
||||
|
||||
export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string, e: KeyboardEvent) {
|
||||
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
|
||||
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, hostsById, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, reopenLastClosedTab, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
|
||||
{
|
||||
const shortcutTabs = buildNumberShortcutTabTargets({
|
||||
showSftpTab: settings.showSftpTab ?? true,
|
||||
@@ -875,29 +1040,31 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
const session = sessions.find((s) => s.id === currentId) ?? null;
|
||||
const workspace = workspaces.find((w) => w.id === currentId) ?? null;
|
||||
|
||||
const focusIsInsideTerminal = !!document.activeElement?.closest('[data-session-id]');
|
||||
|
||||
const intent = resolveCloseIntent({
|
||||
activeTabId: currentId,
|
||||
workspace: workspace ? { id: workspace.id, focusedSessionId: workspace.focusedSessionId } : null,
|
||||
sessionForTab: session,
|
||||
focusIsInsideTerminal,
|
||||
});
|
||||
|
||||
closeTabInFlightRef.current = true;
|
||||
(async () => {
|
||||
try {
|
||||
switch (intent.kind) {
|
||||
case 'closeTerminal':
|
||||
case 'closeSingleTab': {
|
||||
const ok = await confirmIfBusyLocalTerminal([intent.sessionId]);
|
||||
if (ok) closeSession(intent.sessionId);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [intent.sessionId]);
|
||||
closeSession(intent.sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'closeWorkspace': {
|
||||
const ids = sessions.filter((s) => s.workspaceId === intent.workspaceId).map((s) => s.id);
|
||||
const ok = await confirmIfBusyLocalTerminal(ids);
|
||||
if (ok) closeWorkspace(intent.workspaceId);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, ids);
|
||||
closeWorkspace(intent.workspaceId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'noop':
|
||||
@@ -932,12 +1099,20 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
: aliveIds[0];
|
||||
if (focusedId) {
|
||||
const ok = await confirmIfBusyLocalTerminal([focusedId]);
|
||||
if (ok) closeSession(focusedId);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [focusedId]);
|
||||
// The pane shortcut closes the tab when only one pane remains.
|
||||
if (aliveIds.length === 1) closeWorkspace(workspace.id);
|
||||
else closeSession(focusedId);
|
||||
}
|
||||
}
|
||||
} else if (session) {
|
||||
// Standalone session tab — close the session
|
||||
const ok = await confirmIfBusyLocalTerminal([session.id]);
|
||||
if (ok) closeSession(session.id);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [session.id]);
|
||||
closeSession(session.id);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
closeTabInFlightRef.current = false;
|
||||
@@ -962,6 +1137,39 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'reopenClosedTab': {
|
||||
const reopened = reopenLastClosedTab?.({
|
||||
availableHostIds: hostsById ? new Set(hostsById.keys()) : undefined,
|
||||
hostsById,
|
||||
});
|
||||
if (reopened && addConnectionLogRef?.current) {
|
||||
const reopenedSessions = reopened.kind === 'session'
|
||||
? [reopened.session]
|
||||
: reopened.sessions;
|
||||
const localUsername = systemInfoRef?.current?.username ?? '';
|
||||
const localHostname = systemInfoRef?.current?.hostname ?? '';
|
||||
const startTime = Date.now();
|
||||
for (const reopenedSession of reopenedSessions) {
|
||||
addConnectionLogRef.current({
|
||||
sessionId: reopenedSession.id,
|
||||
hostId: reopenedSession.protocol === 'local' && reopenedSession.hostId === 'local-terminal'
|
||||
? ''
|
||||
: reopenedSession.hostId,
|
||||
hostLabel: reopenedSession.hostLabel,
|
||||
hostname: reopenedSession.hostname,
|
||||
username: reopenedSession.protocol === 'local'
|
||||
? localUsername
|
||||
: reopenedSession.username,
|
||||
protocol: reopenedSession.protocol || 'ssh',
|
||||
startTime,
|
||||
localUsername,
|
||||
localHostname,
|
||||
saved: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'openHosts':
|
||||
setActiveTabId('vault');
|
||||
break;
|
||||
@@ -1208,7 +1416,11 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
|
||||
// Local-shell vault hosts carry no SSH credentials, so log the system
|
||||
// user like local terminals do (see handleCreateLocalTerminalImpl)
|
||||
// instead of 'root' or an inherited group SSH username.
|
||||
username: protocol === 'local' ? username : (resolvedAuth.username || 'root'),
|
||||
username: protocol === 'local'
|
||||
? username
|
||||
: isRemoteDesktopProtocol(protocol)
|
||||
? (effectiveHost.username || '')
|
||||
: (resolvedAuth.username || 'root'),
|
||||
protocol,
|
||||
...getLogHostVisualSnapshot(effectiveHost),
|
||||
startTime: Date.now(),
|
||||
@@ -1220,6 +1432,85 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
|
||||
}
|
||||
}
|
||||
|
||||
export function handleConnectRemoteDesktopImpl(
|
||||
getCtx: AppContextGetter,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) {
|
||||
const { addConnectionLog, connectToHostRemoteDesktop, identities, resolveEffectiveHost, systemInfoRef } = getCtx();
|
||||
const effectiveHost = resolveEffectiveHost(host);
|
||||
const spec = resolveRemoteDesktopConnectionSpec(effectiveHost, protocol, identities ?? []);
|
||||
const sessionId = connectToHostRemoteDesktop(effectiveHost, protocol, options);
|
||||
if (!sessionId) return null;
|
||||
const { username: localUsername, hostname: localHostname } = systemInfoRef.current;
|
||||
addConnectionLog({
|
||||
sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel: spec.isCompanion ? `${spec.label} (${protocol.toUpperCase()})` : spec.label,
|
||||
hostname: spec.hostHostname,
|
||||
username: spec.username,
|
||||
protocol,
|
||||
...getLogHostVisualSnapshot(effectiveHost),
|
||||
startTime: Date.now(),
|
||||
localUsername,
|
||||
localHostname,
|
||||
saved: false,
|
||||
});
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
export async function handleOpenSystemRemoteDesktopImpl(
|
||||
getCtx: AppContextGetter,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
rawRdpContent?: string,
|
||||
) {
|
||||
const {
|
||||
groupConfigs,
|
||||
hosts,
|
||||
identities,
|
||||
keys,
|
||||
knownHosts,
|
||||
netcattyBridge,
|
||||
proxyProfiles,
|
||||
resolveEffectiveHost,
|
||||
toast,
|
||||
} = getCtx();
|
||||
const rdBridge = netcattyBridge.get()?.remoteDesktop;
|
||||
if (!rdBridge?.openSystemClient) {
|
||||
toast?.error?.('System remote desktop launch is unavailable');
|
||||
return { ok: false };
|
||||
}
|
||||
const effectiveHost = resolveEffectiveHost(host);
|
||||
const chainHosts = resolveTerminalChainHosts({
|
||||
host: effectiveHost,
|
||||
hosts: hosts ?? [],
|
||||
groupConfigs: groupConfigs ?? [],
|
||||
proxyProfiles: proxyProfiles ?? [],
|
||||
});
|
||||
const payload = buildSystemRemoteDesktopPayload({
|
||||
host: effectiveHost,
|
||||
protocol,
|
||||
chainHosts,
|
||||
keys: keys ?? [],
|
||||
identities: identities ?? [],
|
||||
knownHosts: knownHosts ?? [],
|
||||
rawRdpContent,
|
||||
});
|
||||
try {
|
||||
const result = await rdBridge.openSystemClient(payload);
|
||||
if (!result?.ok) {
|
||||
toast?.error?.(result?.error || 'Failed to open system remote desktop client');
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to open system remote desktop client';
|
||||
toast?.error?.(message);
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
|
||||
const { addConnectionLog, systemInfoRef } = getCtx();
|
||||
const { username, hostname } = systemInfoRef.current;
|
||||
@@ -1256,10 +1547,16 @@ export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, se
|
||||
// The IndexedDB replay write commits asynchronously. Waiting here keeps
|
||||
// a crash during session teardown from dropping the newest capture any
|
||||
// more often than the old synchronous localStorage write.
|
||||
await updateConnectionLog(matchingLog.id, {
|
||||
endTime: Date.now(),
|
||||
terminalData: data,
|
||||
});
|
||||
const isRemoteDesktopLog = isRemoteDesktopProtocol(session?.protocol ?? matchingLog.protocol);
|
||||
await updateConnectionLog(
|
||||
matchingLog.id,
|
||||
isRemoteDesktopLog && !data
|
||||
? { endTime: Date.now() }
|
||||
: {
|
||||
endTime: Date.now(),
|
||||
terminalData: data,
|
||||
},
|
||||
);
|
||||
if (IS_DEV) console.log('[handleTerminalDataCapture] Updated log with terminalData');
|
||||
|
||||
// Auto-save is now handled by real-time streaming in the main process
|
||||
@@ -1281,8 +1578,7 @@ export function hasMultipleProtocolsImpl(getCtx: AppContextGetter, host: Host) {
|
||||
// SSH/Telnet pickers driven by an inherited group Telnet flag. Hosts
|
||||
// without an explicit protocol are legacy SSH entries.
|
||||
const effective = resolveEffectiveHost(host);
|
||||
const effectiveProtocol = effective.protocol ?? 'ssh';
|
||||
return effectiveProtocol === 'ssh' && Boolean(effective.telnetEnabled);
|
||||
return shouldPromptHostProtocolOnConnect(effective);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1299,18 +1595,40 @@ export function handleHostConnectWithProtocolCheckImpl(getCtx: AppContextGetter,
|
||||
}
|
||||
}
|
||||
|
||||
export function handleProtocolSelectImpl(getCtx: AppContextGetter, protocol: HostProtocol, port: number) {
|
||||
const { handleConnectToHost, protocolSelectHost, setProtocolSelectHost } = getCtx();
|
||||
export function handleProtocolSelectImpl(
|
||||
getCtx: AppContextGetter,
|
||||
protocol: HostProtocol,
|
||||
port: number,
|
||||
rememberDefault?: boolean,
|
||||
) {
|
||||
const {
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
protocolSelectHost,
|
||||
setProtocolSelectHost,
|
||||
updateHosts,
|
||||
} = getCtx();
|
||||
{
|
||||
if (protocolSelectHost) {
|
||||
const hostWithProtocol: Host = {
|
||||
...protocolSelectHost,
|
||||
protocol: (protocol === 'mosh' || protocol === 'et') ? 'ssh' : protocol,
|
||||
port,
|
||||
moshEnabled: protocol === 'mosh',
|
||||
etEnabled: protocol === 'et',
|
||||
};
|
||||
handleConnectToHost(hostWithProtocol);
|
||||
if (
|
||||
rememberDefault &&
|
||||
typeof updateHosts === 'function' &&
|
||||
(protocol === 'ssh' || protocol === 'mosh' || protocol === 'et' || protocol === 'rdp' || protocol === 'vnc' || protocol === 'telnet')
|
||||
) {
|
||||
updateHosts((prev: Host[]) =>
|
||||
prev.map((h) =>
|
||||
h.id === protocolSelectHost.id
|
||||
? applyHostDefaultConnectProtocol(h, protocol)
|
||||
: h,
|
||||
),
|
||||
);
|
||||
}
|
||||
const dispatch = buildHostForProtocolOverride(protocolSelectHost, protocol, port);
|
||||
if (dispatch.mode === 'remoteDesktop' && typeof handleConnectRemoteDesktop === 'function') {
|
||||
handleConnectRemoteDesktop(dispatch.host, dispatch.protocol);
|
||||
} else {
|
||||
handleConnectToHost(dispatch.host);
|
||||
}
|
||||
setProtocolSelectHost(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { memo, useMemo } from 'react';
|
||||
import React, { memo, useMemo, useRef } from 'react';
|
||||
|
||||
import { useActiveTabId } from '../state/activeTabStore';
|
||||
import { useAppearanceChromeStore } from '../state/appearanceChromeStore';
|
||||
import type { EditorTabChrome } from '../state/editorTabStore';
|
||||
import type { LogView } from '../state/logViewState';
|
||||
import { useTerminalHostTreeOpen } from '../state/terminalHostTreeStore';
|
||||
import { useManualTerminalChromeSurfaceInjection } from '../state/useManualTerminalChromeSurfaceInjection';
|
||||
import { TerminalHostTreeSidebar } from '../../components/terminalLayer/TerminalHostTreeSidebar';
|
||||
import type {
|
||||
@@ -33,6 +34,8 @@ interface AppHostTreeLayerProps {
|
||||
themeById: ReadonlyMap<string, TerminalTheme>;
|
||||
resolveSessionAppearance?: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onNewHost?: (defaultGroup?: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onCreateLocalTerminal?: () => void;
|
||||
@@ -67,6 +70,8 @@ function appHostTreeLayerAreEqual(
|
||||
&& prev.themeById === next.themeById
|
||||
&& prev.resolveSessionAppearance === next.resolveSessionAppearance
|
||||
&& prev.onConnect === next.onConnect
|
||||
&& prev.onConnectRemoteDesktop === next.onConnectRemoteDesktop
|
||||
&& prev.onOpenSystemRemoteDesktop === next.onOpenSystemRemoteDesktop
|
||||
&& prev.onNewHost === next.onNewHost
|
||||
&& prev.onEditHost === next.onEditHost
|
||||
&& prev.onCreateLocalTerminal === next.onCreateLocalTerminal;
|
||||
@@ -88,11 +93,14 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
themeById,
|
||||
resolveSessionAppearance,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onNewHost,
|
||||
onEditHost,
|
||||
onCreateLocalTerminal,
|
||||
}) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const isHostTreeOpen = useTerminalHostTreeOpen();
|
||||
const { accentMode, customAccent } = useAppearanceChromeStore();
|
||||
const sessionIds = useMemo(() => new Set(sessions.map((session) => session.id)), [sessions]);
|
||||
const workspaceIds = useMemo(() => new Set(workspaces.map((workspace) => workspace.id)), [workspaces]);
|
||||
@@ -113,13 +121,18 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
});
|
||||
const sidebarActive = surfaceVisible && enabled && isHostTreeOpen;
|
||||
|
||||
const activeHostId = useMemo(() => resolveWorkTabActiveHostId({
|
||||
activeTabId,
|
||||
editorTabs,
|
||||
sessions,
|
||||
workspaces,
|
||||
}), [activeTabId, editorTabs, sessions, workspaces]);
|
||||
const activeHostId = useMemo(() => (
|
||||
sidebarActive
|
||||
? resolveWorkTabActiveHostId({
|
||||
activeTabId,
|
||||
editorTabs,
|
||||
sessions,
|
||||
workspaces,
|
||||
})
|
||||
: undefined
|
||||
), [activeTabId, editorTabs, sessions, sidebarActive, workspaces]);
|
||||
|
||||
const hostTreeTheme = useMemo(() => (
|
||||
resolveActiveChromeTheme({
|
||||
@@ -150,6 +163,13 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
themeById,
|
||||
workspaceById,
|
||||
]);
|
||||
const lastActiveSidebarThemeRef = useRef(hostTreeTheme);
|
||||
if (sidebarActive) {
|
||||
lastActiveSidebarThemeRef.current = hostTreeTheme;
|
||||
}
|
||||
const sidebarPreviewTheme = sidebarActive
|
||||
? hostTreeTheme
|
||||
: lastActiveSidebarThemeRef.current;
|
||||
|
||||
useManualTerminalChromeSurfaceInjection(
|
||||
hostTreeTheme,
|
||||
@@ -168,9 +188,11 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
hosts={hosts}
|
||||
customGroups={customGroups}
|
||||
groupConfigs={groupConfigs}
|
||||
resolvedPreviewTheme={hostTreeTheme}
|
||||
resolvedPreviewTheme={sidebarPreviewTheme}
|
||||
activeHostId={activeHostId}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onNewHost={onNewHost}
|
||||
onEditHost={onEditHost}
|
||||
onCreateLocalTerminal={onCreateLocalTerminal}
|
||||
|
||||
@@ -22,6 +22,10 @@ test('visible log view leaves room for the terminal host sidebar', () => {
|
||||
assert.deepEqual(getLogViewWrapperStyle(true, 220), {
|
||||
left: 220,
|
||||
});
|
||||
assert.deepEqual(getLogViewWrapperStyle(true, 220, true), {
|
||||
left: 220,
|
||||
transition: 'left 220ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
});
|
||||
});
|
||||
|
||||
test('hidden log view remains hidden while preserving host sidebar offset', () => {
|
||||
@@ -76,3 +80,10 @@ test('terminal layer force-mounts immediately when a hidden MCP session exists',
|
||||
assert.match(appMountsSource, /useState\(isVisible \|\| hasHiddenSession\)/);
|
||||
assert.match(appMountsSource, /if \(isVisible \|\| hasHiddenSession\) setShouldMount\(true\)/);
|
||||
});
|
||||
|
||||
test('AppMounts narrows active-tab subscriptions instead of using useActiveTabId', () => {
|
||||
assert.doesNotMatch(appMountsSource, /\buseActiveTabId\b/);
|
||||
assert.match(appMountsSource, /const isVisible = useIsTabActive\(logView\.id\);/);
|
||||
assert.match(appMountsSource, /const isTerminalSurfaceActive = useIsTerminalSurfaceActive\(sessionIds, workspaceIds\);/);
|
||||
assert.match(appMountsSource, /<LazyLoadBoundary name="Terminal" resetKey=\{isVisible \? "active" : "idle"\}>/);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { Suspense, lazy, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useActiveTabId, useIsSftpActive, useIsVaultActive } from '../state/activeTabStore';
|
||||
import { useTerminalHostTreeLayoutWidth } from '../state/terminalHostTreeStore';
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { activeTabStore, useIsSftpActive, useIsTabActive, useIsVaultActive } from '../state/activeTabStore';
|
||||
import {
|
||||
useTerminalHostTreeLayoutTransitionAnimated,
|
||||
useTerminalHostTreeLayoutWidth,
|
||||
} from '../state/terminalHostTreeStore';
|
||||
import { TERMINAL_HOST_TREE_LEFT_TRANSITION } from '../state/terminalHostTreeAnimation';
|
||||
import { isTerminalContentTabSurface } from './workTabSurface';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { ConnectionLog, TerminalTheme } from '../../types';
|
||||
@@ -68,9 +72,11 @@ interface LogViewWrapperProps {
|
||||
export function getLogViewWrapperStyle(
|
||||
isVisible: boolean,
|
||||
hostTreeLayoutWidth: number,
|
||||
animateLayout = false,
|
||||
): React.CSSProperties {
|
||||
const baseStyle = {
|
||||
const baseStyle: React.CSSProperties = {
|
||||
left: hostTreeLayoutWidth,
|
||||
...(animateLayout ? { transition: TERMINAL_HOST_TREE_LEFT_TRANSITION } : null),
|
||||
};
|
||||
return isVisible
|
||||
? baseStyle
|
||||
@@ -78,11 +84,15 @@ export function getLogViewWrapperStyle(
|
||||
}
|
||||
|
||||
export const LogViewWrapper: React.FC<LogViewWrapperProps> = ({ logView, defaultTerminalTheme, defaultFontSize, onClose, onUpdateLog }) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const isVisible = activeTabId === logView.id;
|
||||
const isVisible = useIsTabActive(logView.id);
|
||||
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
|
||||
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
|
||||
|
||||
const containerStyle = getLogViewWrapperStyle(isVisible, hostTreeLayoutWidth);
|
||||
const containerStyle = getLogViewWrapperStyle(
|
||||
isVisible,
|
||||
hostTreeLayoutWidth,
|
||||
isVisible && hostTreeLayoutAnimated,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -163,15 +173,27 @@ export const SftpViewMount: React.FC<SftpViewProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
export function useIsTerminalSurfaceActive(
|
||||
sessionIds: ReadonlySet<string>,
|
||||
workspaceIds: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const getSnapshot = useCallback(
|
||||
() =>
|
||||
isTerminalContentTabSurface({
|
||||
activeTabId: activeTabStore.getActiveTabId(),
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
}),
|
||||
[sessionIds, workspaceIds],
|
||||
);
|
||||
return useSyncExternalStore(activeTabStore.subscribe, getSnapshot, getSnapshot);
|
||||
}
|
||||
|
||||
export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const sessionIds = useMemo(() => new Set(props.sessions.map((session) => session.id)), [props.sessions]);
|
||||
const workspaceIds = useMemo(() => new Set(props.workspaces.map((workspace) => workspace.id)), [props.workspaces]);
|
||||
const isVisible = isTerminalContentTabSurface({
|
||||
activeTabId,
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
}) || !!props.draggingSessionId;
|
||||
const isTerminalSurfaceActive = useIsTerminalSurfaceActive(sessionIds, workspaceIds);
|
||||
const isVisible = isTerminalSurfaceActive || !!props.draggingSessionId;
|
||||
// Silent MCP sessions never become the activeTabId, so `isVisible` alone
|
||||
// would leave this whole layer (and its PTY-starting TerminalPane) unmounted
|
||||
// for up to 5s (the idle-callback fallback below) after host_open returns —
|
||||
@@ -203,7 +225,7 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
|
||||
if (!shouldRender) return null;
|
||||
|
||||
return (
|
||||
<LazyLoadBoundary name="Terminal" resetKey={activeTabId}>
|
||||
<LazyLoadBoundary name="Terminal" resetKey={isVisible ? "active" : "idle"}>
|
||||
<Suspense fallback={<TerminalLayerFallback visible={isVisible} />}>
|
||||
<LazyTerminalLayer {...props} />
|
||||
</Suspense>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import React, { useEffect, useMemo } from 'react';
|
||||
|
||||
import { PluginContributionHost } from '../../components/plugins/PluginContributionHost';
|
||||
import {
|
||||
isRemoteDesktopGrabReleaseChord,
|
||||
isTargetInsideRemoteDesktopCapture,
|
||||
} from '../../components/remoteDesktop/remoteDesktopHelpers';
|
||||
import type { TerminalSession, Workspace } from '../../types';
|
||||
import { useActiveTabId } from '../state/activeTabStore';
|
||||
import { resolveActivePluginKeybindingContext } from '../state/pluginContributionContexts';
|
||||
@@ -25,6 +29,21 @@ export function AppPluginKeybindingHost({
|
||||
workspaces: Workspace[];
|
||||
}) {
|
||||
const activeTabId = useActiveTabId();
|
||||
|
||||
// Short-circuit plugin keybindings when keyboard focus is inside an active
|
||||
// remote desktop capture surface (except for the grab-release chord).
|
||||
useEffect(() => {
|
||||
const onDocumentKeyDown = (event: KeyboardEvent) => {
|
||||
if (!isTargetInsideRemoteDesktopCapture(event.target, event.composedPath?.bind(event))) {
|
||||
return;
|
||||
}
|
||||
if (isRemoteDesktopGrabReleaseChord(event)) return;
|
||||
event.preventDefault();
|
||||
};
|
||||
document.addEventListener('keydown', onDocumentKeyDown);
|
||||
return () => document.removeEventListener('keydown', onDocumentKeyDown);
|
||||
}, []);
|
||||
|
||||
const keybindingContext = useMemo(() => {
|
||||
// AI chat recency drives the workspace anchor fallback (#4098 phase 2).
|
||||
// Read without subscribing: keybinding context is best-effort and refreshes
|
||||
|
||||
@@ -104,7 +104,8 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
|
||||
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
|
||||
import { createOpenTerminalQueue } from './openTerminalQueue';
|
||||
import { useAppStartupEffects } from './useAppStartupEffects';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, moveSessionToNewWindowImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleConnectRemoteDesktopImpl, handleOpenSystemRemoteDesktopImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
|
||||
type OpenSessionInNewWindowPayload = {
|
||||
title?: string;
|
||||
@@ -260,10 +261,12 @@ export function AppSideEffects() {
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
appendHostToWorkspaceConfirmed,
|
||||
closeSession,
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
reopenLastClosedTab,
|
||||
updateSessionStatus,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
@@ -283,6 +286,7 @@ export function AppSideEffects() {
|
||||
createSessionFromCloneSource,
|
||||
getSessionRestoreCwd,
|
||||
renameSessionInline,
|
||||
setSessionPoppedOut,
|
||||
} = sessionState;
|
||||
|
||||
// Presence-only list: keystrokes must not rebuild App domains / TopTabs structure.
|
||||
@@ -292,6 +296,8 @@ export function AppSideEffects() {
|
||||
() => new Map(hosts.map((host) => [host.id, host])),
|
||||
[hosts],
|
||||
);
|
||||
const hostByIdRef = useRef(hostById);
|
||||
hostByIdRef.current = hostById;
|
||||
const terminalHosts = useMemo(
|
||||
() => (ephemeralHosts.length > 0 ? [...hosts, ...ephemeralHosts] : hosts),
|
||||
[hosts, ephemeralHosts],
|
||||
@@ -604,6 +610,7 @@ export function AppSideEffects() {
|
||||
sessionId,
|
||||
sessions,
|
||||
setActiveTabId,
|
||||
setSessionPoppedOut,
|
||||
setWorkspaceFocusedSession,
|
||||
getActiveTabId: () => activeTabStore.getActiveTabId(),
|
||||
netcattyBridge,
|
||||
@@ -1027,6 +1034,24 @@ export function AppSideEffects() {
|
||||
|
||||
const copySessionToNewWindowWithCurrentShell = useCallback((sessionId: string) => { return copySessionToNewWindowWithCurrentShellImpl(() => ({ classifyLocalShellType, discoveredShells, netcattyBridge, resolveShellSetting, sessions, terminalSettings, t, toast }), sessionId); }, [sessions, terminalSettings, discoveredShells, t]);
|
||||
|
||||
const moveSessionToNewWindow = useCallback((sessionId: string) => {
|
||||
return moveSessionToNewWindowImpl(() => ({
|
||||
getActiveTabId: () => activeTabStore.getActiveTabId(),
|
||||
getOrderedTabs: () => orderedTabsRef.current,
|
||||
netcattyBridge,
|
||||
sessions: Array.from(sessionByIdRef.current.values()),
|
||||
setActiveTabId,
|
||||
setSessionPoppedOut,
|
||||
t,
|
||||
toast,
|
||||
}), sessionId);
|
||||
}, [setActiveTabId, setSessionPoppedOut, t]);
|
||||
|
||||
// A tab moved to its own window returns to the tab bar when that window closes.
|
||||
useEffect(() => netcattyBridge.get()?.onTerminalPopupAttachClosed?.(({ sessionId }) => {
|
||||
setSessionPoppedOut(sessionId, false);
|
||||
}), [setSessionPoppedOut]);
|
||||
|
||||
const closeTabKeyStr = useMemo(() => {
|
||||
if (hotkeyScheme === 'disabled') return null;
|
||||
const closeTabBinding = keyBindings.find((binding) => binding.action === 'closeTab');
|
||||
@@ -1108,12 +1133,14 @@ export function AppSideEffects() {
|
||||
fromEditorTabId,
|
||||
handleOpenSettingsRef,
|
||||
handleRequestCloseEditorTabRef,
|
||||
hostsById: hostByIdRef.current,
|
||||
isEditorTabId,
|
||||
isPluginViewTabId,
|
||||
isQuickSwitcherOpen: isQuickSwitcherOpenRef.current,
|
||||
lastMoveFocusTimeRef,
|
||||
moveFocusInWorkspace,
|
||||
orderedTabs: orderedTabsRef.current,
|
||||
reopenLastClosedTab,
|
||||
resolveCloseIntent,
|
||||
resolveSnippetsShortcutIntent,
|
||||
sessions: sessionsRef.current,
|
||||
@@ -1145,6 +1172,7 @@ export function AppSideEffects() {
|
||||
closePluginViewTab,
|
||||
closeSession,
|
||||
closeWorkspace,
|
||||
reopenLastClosedTab,
|
||||
createLocalTerminalWithCurrentShell,
|
||||
splitSessionWithCurrentShell,
|
||||
moveFocusInWorkspace,
|
||||
@@ -1491,6 +1519,38 @@ export function AppSideEffects() {
|
||||
}), connectionHost, hidden);
|
||||
}, [addConnectionLog, appendHostToWorkspaceConfirmed, connectToHost, resolveEffectiveHost, identities, keys, discoveredShells]);
|
||||
|
||||
const handleConnectRemoteDesktop = useCallback((
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) => {
|
||||
return handleConnectRemoteDesktopImpl(() => ({
|
||||
addConnectionLog,
|
||||
connectToHostRemoteDesktop,
|
||||
identities,
|
||||
resolveEffectiveHost,
|
||||
systemInfoRef,
|
||||
}), host, protocol, options);
|
||||
}, [addConnectionLog, connectToHostRemoteDesktop, identities, resolveEffectiveHost]);
|
||||
|
||||
const handleOpenSystemRemoteDesktop = useCallback((
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
rawRdpContent?: string,
|
||||
) => {
|
||||
void handleOpenSystemRemoteDesktopImpl(() => ({
|
||||
groupConfigs,
|
||||
hosts,
|
||||
identities,
|
||||
keys,
|
||||
knownHosts: knownHostsRef.current,
|
||||
netcattyBridge,
|
||||
proxyProfiles,
|
||||
resolveEffectiveHost,
|
||||
toast,
|
||||
}), host, protocol, rawRdpContent);
|
||||
}, [groupConfigs, hosts, identities, keys, proxyProfiles, resolveEffectiveHost]);
|
||||
|
||||
const handleConnectToHostWithTabName = useCallback((host: Host, tabName?: string) => {
|
||||
const sessionId = handleConnectToHost(host);
|
||||
if (sessionId && tabName) {
|
||||
@@ -1743,6 +1803,33 @@ export function AppSideEffects() {
|
||||
}
|
||||
return;
|
||||
}
|
||||
const targetProtocol = result.target.protocol.toLowerCase();
|
||||
const jumpServerRdpLaunchMode = settings.jumpServerRdpLaunchMode ?? 'builtin';
|
||||
if (
|
||||
targetProtocol === 'rdp'
|
||||
&& jumpServerRdpLaunchMode === 'system'
|
||||
&& result.target.rawRdpFileContent
|
||||
) {
|
||||
const rdBridge = netcattyBridge.get()?.remoteDesktop;
|
||||
if (rdBridge?.openSystemClient) {
|
||||
void rdBridge.openSystemClient({
|
||||
protocol: 'rdp',
|
||||
hostname: result.target.hostname,
|
||||
port: result.target.port,
|
||||
username: result.target.username || undefined,
|
||||
domain: result.target.domain || undefined,
|
||||
label: result.target.label,
|
||||
rdpContent: result.target.rawRdpFileContent,
|
||||
}).then((res) => {
|
||||
if (!res?.ok) {
|
||||
toast.error(res?.error || 'Failed to launch system RDP client');
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to launch system RDP client');
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
const ephemeralHost = buildJmsDeepLinkEphemeralHost(result.target, {
|
||||
id: crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
@@ -1983,7 +2070,26 @@ export function AppSideEffects() {
|
||||
const handleHostConnectWithProtocolCheck = useCallback((host: Host) => { return handleHostConnectWithProtocolCheckImpl(() => ({ handleConnectToHost, hasMultipleProtocols, host, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost }), host); }, [hasMultipleProtocols, handleConnectToHost, resolveEffectiveHost]);
|
||||
|
||||
// Handle protocol selection from dialog
|
||||
const handleProtocolSelect = useCallback((protocol: HostProtocol, port: number) => { return handleProtocolSelectImpl(() => ({ handleConnectToHost, port, protocol, protocolSelectHost, setProtocolSelectHost }), protocol, port); }, [protocolSelectHost, handleConnectToHost]);
|
||||
const handleProtocolSelect = useCallback(
|
||||
(protocol: HostProtocol, port: number, rememberDefault?: boolean) => {
|
||||
return handleProtocolSelectImpl(
|
||||
() => ({
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
port,
|
||||
protocol,
|
||||
protocolSelectHost,
|
||||
rememberDefault,
|
||||
setProtocolSelectHost,
|
||||
updateHosts,
|
||||
}),
|
||||
protocol,
|
||||
port,
|
||||
rememberDefault,
|
||||
);
|
||||
},
|
||||
[protocolSelectHost, handleConnectToHost, handleConnectRemoteDesktop, updateHosts],
|
||||
);
|
||||
|
||||
const handleOpenQuickSwitcher = useCallback(() => {
|
||||
setIsQuickSwitcherOpen(true);
|
||||
@@ -2071,10 +2177,13 @@ export function AppSideEffects() {
|
||||
duplicateSessionWithCurrentShell,
|
||||
copyWorkspaceWithCurrentShell,
|
||||
copySessionToNewWindowWithCurrentShell,
|
||||
moveSessionToNewWindow,
|
||||
createWorkspaceFromTargets: createWorkspaceFromEffectiveTargets,
|
||||
createWorkspaceWithHosts: createWorkspaceWithEffectiveHosts,
|
||||
handleConnectSerial,
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal,
|
||||
handleHotkeyAction,
|
||||
handleSessionStatusChange,
|
||||
@@ -2149,10 +2258,13 @@ export function AppSideEffects() {
|
||||
duplicateSessionWithCurrentShell,
|
||||
copyWorkspaceWithCurrentShell,
|
||||
copySessionToNewWindowWithCurrentShell,
|
||||
moveSessionToNewWindow,
|
||||
createWorkspaceFromEffectiveTargets,
|
||||
createWorkspaceWithEffectiveHosts,
|
||||
handleConnectSerial,
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal,
|
||||
handleHotkeyAction,
|
||||
handleSessionStatusChange,
|
||||
|
||||
@@ -5,7 +5,11 @@ import { activeTabStore, toEditorTabId, useIsEditorTabActive } from '../state/ac
|
||||
import { editorTabStore, tabIsDirty } from '../state/editorTabStore';
|
||||
import { releaseEditorTabSaveCoordinator, saveEditorTab } from '../state/editorTabSave';
|
||||
import { focusEditorInWindow, popOutEditorTab } from '../state/editorWindowClient';
|
||||
import { useTerminalHostTreeLayoutWidth } from '../state/terminalHostTreeStore';
|
||||
import {
|
||||
useTerminalHostTreeLayoutTransitionAnimated,
|
||||
useTerminalHostTreeLayoutWidth,
|
||||
} from '../state/terminalHostTreeStore';
|
||||
import { TERMINAL_HOST_TREE_LEFT_TRANSITION } from '../state/terminalHostTreeAnimation';
|
||||
import { TopTabs } from '../../components/TopTabs';
|
||||
import { VaultView } from '../../components/VaultView';
|
||||
import { QuickAddSnippetDialog } from '../../components/QuickAddSnippetDialog';
|
||||
@@ -67,12 +71,16 @@ const focusEditorWindowTab = (id: string) => { void focusEditorInWindow(id); };
|
||||
const TextEditorTabFallback = ({ tabId }: { tabId: string }) => {
|
||||
const isVisible = useIsEditorTabActive(tabId);
|
||||
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
|
||||
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
...(isVisible ? null : { pointerEvents: 'none', visibility: 'hidden' }),
|
||||
zIndex: 20,
|
||||
left: hostTreeLayoutWidth,
|
||||
...(isVisible && hostTreeLayoutAnimated
|
||||
? { transition: TERMINAL_HOST_TREE_LEFT_TRANSITION }
|
||||
: null),
|
||||
}}
|
||||
className="netcatty-lazy-fade-in absolute top-0 right-0 bottom-0 min-h-0 flex flex-col bg-background"
|
||||
aria-hidden="true"
|
||||
@@ -265,11 +273,11 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
|
||||
const {
|
||||
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit,
|
||||
handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect,
|
||||
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
|
||||
@@ -278,7 +286,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
|
||||
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
|
||||
sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap,
|
||||
setNavigateToSection, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride,
|
||||
setNavigateToSection, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionPromptHost, updateSessionCodingCliProvider, clearSessionFontSizeOverride,
|
||||
setWorkspaceFocusedSession, setWorkspaceAnchorChat, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior,
|
||||
sftpShowHiddenFiles, sftpUseCompressedUpload, snippetPackages, snippets, splitSessionWithCurrentShell, startSessionRename,
|
||||
startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, terminalFontFamilyId, terminalFontSize, terminalSettings, terminalThemeId, themeById,
|
||||
@@ -560,6 +568,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onDuplicateSession={duplicateSessionWithCurrentShell}
|
||||
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onMoveSessionToNewWindow={moveSessionToNewWindow}
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
@@ -612,6 +621,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
themeById={themeById}
|
||||
resolveSessionAppearance={resolveSessionAppearance}
|
||||
onConnect={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
onNewHost={workSurfaceHostEditor.openNew}
|
||||
onEditHost={workSurfaceHostEditor.openEdit}
|
||||
onCreateLocalTerminal={handleCreateLocalTerminal}
|
||||
@@ -652,7 +663,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
customGroups={customGroups}
|
||||
knownHosts={effectiveKnownHosts}
|
||||
managedSources={managedSources}
|
||||
sessionCount={sessions.filter((s) => !s.hiddenFromTabs).length}
|
||||
sessionCount={sessions.filter((s) => !s.hiddenFromTabs || s.poppedOut).length}
|
||||
hotkeyScheme={hotkeyScheme}
|
||||
keyBindings={keyBindings}
|
||||
terminalThemeId={terminalThemeId}
|
||||
@@ -663,6 +674,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onConnectSerial={handleConnectSerial}
|
||||
onDeleteHost={handleDeleteHost}
|
||||
onConnect={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
onOpenHostFromNote={handleOpenHostFromVaultNote}
|
||||
groupConfigs={groupConfigs}
|
||||
onUpdateGroupConfigs={updateGroupConfigs}
|
||||
@@ -760,6 +773,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onUpdateSessionFontSize={updateSessionFontSize}
|
||||
onUpdateSessionRestoreCwd={updateSessionRestoreCwd}
|
||||
onUpdateSessionDynamicTitle={updateSessionDynamicTitle}
|
||||
onUpdateSessionPromptHost={updateSessionPromptHost}
|
||||
onUpdateSessionCodingCliProvider={updateSessionCodingCliProvider}
|
||||
onClearSessionFontSizeOverride={clearSessionFontSizeOverride}
|
||||
onUpdateTerminalFontWeight={handleUpdateTerminalFontWeight}
|
||||
@@ -789,6 +803,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onSplitSession={splitSessionWithCurrentShell}
|
||||
onConnectToHost={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
openNoteRequest={openNoteRequest}
|
||||
onOpenVaultNoteFromChat={handleOpenVaultNoteFromChat}
|
||||
onOpenVaultHostFromChat={handleOpenVaultHostFromChat}
|
||||
|
||||
@@ -179,6 +179,7 @@ export function TerminalHost() {
|
||||
copySessionWithCurrentShell: handlers.copySessionWithCurrentShell,
|
||||
copyWorkspaceWithCurrentShell: handlers.copyWorkspaceWithCurrentShell,
|
||||
copySessionToNewWindowWithCurrentShell: handlers.copySessionToNewWindowWithCurrentShell,
|
||||
moveSessionToNewWindow: handlers.moveSessionToNewWindow,
|
||||
duplicateSessionWithCurrentShell: handlers.duplicateSessionWithCurrentShell,
|
||||
closeWorkspace: sessionActions?.closeWorkspace,
|
||||
createWorkspaceFromSessions: sessionActions?.createWorkspaceFromSessions,
|
||||
@@ -194,6 +195,8 @@ export function TerminalHost() {
|
||||
resolveSessionAppearance: resolveFocusedAppearance,
|
||||
handleConnectSerial: handlers.handleConnectSerial,
|
||||
handleConnectToHost: handlers.handleConnectToHost,
|
||||
handleConnectRemoteDesktop: handlers.handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop: handlers.handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal: handlers.handleCreateLocalTerminal,
|
||||
handleDefaultTerminalThemeChange,
|
||||
handleFollowAppTerminalThemeChange,
|
||||
@@ -256,6 +259,7 @@ export function TerminalHost() {
|
||||
updateSessionFontSize: sessionActions?.updateSessionFontSize,
|
||||
updateSessionRestoreCwd: sessionActions?.updateSessionRestoreCwd,
|
||||
updateSessionDynamicTitle: sessionActions?.updateSessionDynamicTitle,
|
||||
updateSessionPromptHost: sessionActions?.updateSessionPromptHost,
|
||||
updateSessionCodingCliProvider: sessionActions?.updateSessionCodingCliProvider,
|
||||
updateTerminalSetting: terminalSettingsActions?.updateTerminalSetting,
|
||||
workspaces: session.workspaces,
|
||||
|
||||
@@ -0,0 +1,760 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import type { Host, TerminalSession, Workspace } from '../../types';
|
||||
|
||||
function setupDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'Element',
|
||||
'Node',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'DOMException',
|
||||
]) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('localStorage', dom.window.localStorage);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0) as unknown as number);
|
||||
install('cancelAnimationFrame', (id: number) => clearTimeout(id));
|
||||
install(
|
||||
'ResizeObserver',
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flushTabStore = () => new Promise<void>((resolve) => setTimeout(resolve, 25));
|
||||
|
||||
async function waitForAct(
|
||||
act: (fn: () => Promise<void>) => Promise<void>,
|
||||
condition: () => boolean,
|
||||
timeoutMs = 3000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!condition()) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
await act(async () => {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const makeSession = (id: string, hostId: string): TerminalSession => ({
|
||||
id,
|
||||
hostId,
|
||||
hostLabel: `host-${hostId}`,
|
||||
username: 'root',
|
||||
hostname: `${hostId}.example.com`,
|
||||
status: 'connected',
|
||||
});
|
||||
|
||||
const makeWorkspace = (id: string, sessionId: string): Workspace => ({
|
||||
id,
|
||||
title: `Workspace ${id}`,
|
||||
focusedSessionId: sessionId,
|
||||
root: { id: `pane-${id}`, type: 'pane', sessionId },
|
||||
});
|
||||
|
||||
const makeHost = (id: string): Host => ({
|
||||
id,
|
||||
label: `host-${id}`,
|
||||
hostname: `${id}.example.com`,
|
||||
port: 22,
|
||||
username: 'root',
|
||||
authMethod: 'password',
|
||||
tags: [],
|
||||
os: 'linux',
|
||||
});
|
||||
|
||||
test('usePluginVaultPages does not re-render on non-vault tab switches while preserving active state', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { usePluginVaultPages } = await import('../state/usePluginVaultPages');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
Object.assign(env.dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() {
|
||||
return { available: true };
|
||||
},
|
||||
async getPluginContributions() {
|
||||
return { locale: 'en', plugins: [] };
|
||||
},
|
||||
onPluginContributionsChanged() {
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let renders = 0;
|
||||
let lastActive: boolean | null = null;
|
||||
const select = () => {};
|
||||
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
const model = usePluginVaultPages({ locale: 'en', section: 'hosts', select });
|
||||
lastActive = model.active;
|
||||
return <div data-active={String(model.active)} />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastActive, false);
|
||||
const settledRenders = renders;
|
||||
|
||||
// Switching between terminal tabs and other non-vault tabs must cause 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Switching to vault flips active to true with exactly 1 render.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders + 1);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Switching back to a terminal tab flips active back to false.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders + 2);
|
||||
assert.equal(lastActive, false);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useShowHostTreeToggle and TopTabs avoid re-renders when switching between two terminal tabs', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { TopTabs, useShowHostTreeToggle } = await import('../../components/TopTabs');
|
||||
const { I18nProvider } = await import('../i18n/I18nProvider');
|
||||
const { TooltipProvider } = await import('../../components/ui/tooltip');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const session1 = makeSession('session-1', 'h1');
|
||||
const session2 = makeSession('session-2', 'h2');
|
||||
const workspace1 = makeWorkspace('workspace-1', 'session-1');
|
||||
const hosts = [makeHost('h1'), makeHost('h2')];
|
||||
const hostById = new Map(hosts.map((h) => [h.id, h]));
|
||||
const sessions = [session1, session2];
|
||||
const orphanSessions = [session1, session2];
|
||||
const workspaces = [workspace1];
|
||||
const logViews: never[] = [];
|
||||
const orderedTabs = ['session-1', 'session-2', 'workspace-1'];
|
||||
const editorTabs: never[] = [];
|
||||
const pluginViewTabs: never[] = [];
|
||||
const sessionIds = new Set(['session-1', 'session-2']);
|
||||
const workspaceIds = new Set(['workspace-1']);
|
||||
const logViewIds = new Set(['log-1']);
|
||||
|
||||
let selectorRenders = 0;
|
||||
let lastVisible: boolean | null = null;
|
||||
function SelectorHarness({ enabled }: { enabled: boolean }) {
|
||||
selectorRenders += 1;
|
||||
lastVisible = useShowHostTreeToggle({
|
||||
enabled,
|
||||
logViewIds,
|
||||
orderedTabs,
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
});
|
||||
return <div data-show={String(lastVisible)} />;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
// 1. Direct selector test across all tab transitions
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<SelectorHarness enabled={true} />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastVisible, true);
|
||||
const rendersAfterMount = selectorRenders;
|
||||
|
||||
for (const nextTab of ['session-2', 'workspace-1', 'log-1', 'editor:file-1', 'session-1']) {
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(nextTab);
|
||||
await flushTabStore();
|
||||
});
|
||||
}
|
||||
assert.equal(selectorRenders, rendersAfterMount);
|
||||
assert.equal(lastVisible, true);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 1);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 1);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 2);
|
||||
assert.equal(lastVisible, true);
|
||||
|
||||
// Disabled host tree never re-renders on tab switches
|
||||
await act(async () => {
|
||||
root.render(<SelectorHarness enabled={false} />);
|
||||
await flushTabStore();
|
||||
});
|
||||
const rendersWhenDisabled = selectorRenders;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersWhenDisabled);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
// 2. Full TopTabs mount: verify host-tree toggle stays visible across session-1 -> session-2
|
||||
// and hides when switching to vault.
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<TopTabs
|
||||
theme="dark"
|
||||
themePreference="dark"
|
||||
hosts={hosts}
|
||||
sessions={sessions}
|
||||
orphanSessions={orphanSessions}
|
||||
workspaces={workspaces}
|
||||
logViews={logViews}
|
||||
orderedTabs={orderedTabs}
|
||||
draggingSessionId={null}
|
||||
isMacClient={false}
|
||||
onCloseSession={noop}
|
||||
onRenameSession={noop}
|
||||
onCopySession={noop}
|
||||
onCopySessionToNewWindow={noop}
|
||||
onRenameWorkspace={noop}
|
||||
onCopyWorkspace={noop}
|
||||
onCloseWorkspace={noop}
|
||||
onCloseLogView={noop}
|
||||
onCloseTabsBatch={noop}
|
||||
onOpenQuickSwitcher={noop}
|
||||
onThemeChange={noop}
|
||||
onOpenSettings={noop}
|
||||
externalMcpEnabled={false}
|
||||
onToggleExternalMcp={noop}
|
||||
windowOpacity={1}
|
||||
setWindowOpacity={noop}
|
||||
onStartSessionDrag={noop}
|
||||
onEndSessionDrag={noop}
|
||||
onReorderTabs={noop}
|
||||
onRemoveSessionFromWorkspace={noop}
|
||||
showSftpTab={true}
|
||||
showHostTreeSidebar={true}
|
||||
switchTabKeyBinding={null}
|
||||
tabDoubleClickBehavior="copy"
|
||||
editorTabs={editorTabs}
|
||||
pluginViewTabs={pluginViewTabs}
|
||||
onClosePluginViewTab={noop}
|
||||
onRequestCloseEditorTab={noop}
|
||||
hostById={hostById}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
await waitForAct(
|
||||
act,
|
||||
() =>
|
||||
document
|
||||
.querySelector('[data-section="top-tabs-host-tree-toggle"]')
|
||||
?.getAttribute('data-visible') === 'true',
|
||||
);
|
||||
const hostTreeToggleSlot = document.querySelector('[data-section="top-tabs-host-tree-toggle"]')!;
|
||||
assert.equal(hostTreeToggleSlot.getAttribute('data-visible'), 'true');
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(hostTreeToggleSlot.getAttribute('data-visible'), 'true');
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
await waitForAct(
|
||||
act,
|
||||
() => hostTreeToggleSlot.getAttribute('data-visible') === 'false',
|
||||
);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('LogViewWrapper does not re-render on unrelated tab switches', async () => {
|
||||
const env = setupDom();
|
||||
const { Profiler, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { LogViewWrapper } = await import('./AppMounts');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const logView = {
|
||||
id: 'log-view-1',
|
||||
connectionLogId: 'log-1',
|
||||
log: {
|
||||
id: 'log-1',
|
||||
hostId: 'host-1',
|
||||
hostLabel: 'Prod',
|
||||
hostname: 'prod.example.com',
|
||||
username: 'root',
|
||||
protocol: 'ssh' as const,
|
||||
startTime: 1,
|
||||
localUsername: 'local',
|
||||
localHostname: 'localhost',
|
||||
saved: false,
|
||||
terminalData: '',
|
||||
},
|
||||
};
|
||||
const defaultTerminalTheme = {
|
||||
id: 'default',
|
||||
name: 'Default',
|
||||
type: 'dark' as const,
|
||||
colors: {
|
||||
background: '#000000',
|
||||
foreground: '#ffffff',
|
||||
cursor: '#ffffff',
|
||||
selection: '#444444',
|
||||
black: '#000000',
|
||||
red: '#ff0000',
|
||||
green: '#00ff00',
|
||||
yellow: '#ffff00',
|
||||
blue: '#0000ff',
|
||||
magenta: '#ff00ff',
|
||||
cyan: '#00ffff',
|
||||
white: '#ffffff',
|
||||
brightBlack: '#888888',
|
||||
brightRed: '#ff8888',
|
||||
brightGreen: '#88ff88',
|
||||
brightYellow: '#ffff88',
|
||||
brightBlue: '#8888ff',
|
||||
brightMagenta: '#ff88ff',
|
||||
brightCyan: '#88ffff',
|
||||
brightWhite: '#ffffff',
|
||||
},
|
||||
};
|
||||
|
||||
let commitCount = 0;
|
||||
const onRender = () => {
|
||||
commitCount += 1;
|
||||
};
|
||||
const onClose = () => {};
|
||||
const onUpdateLog = () => {};
|
||||
|
||||
const originalConsoleError = console.error;
|
||||
// LazyLogView imports @xterm/xterm/css/xterm.css which is unsupported under Node ESM
|
||||
// and settles into LazyLoadBoundary's alert fallback; silence that expected boundary log.
|
||||
console.error = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Profiler id="log-view-wrapper" onRender={onRender}>
|
||||
<LogViewWrapper
|
||||
logView={logView}
|
||||
defaultTerminalTheme={defaultTerminalTheme}
|
||||
defaultFontSize={14}
|
||||
onClose={onClose}
|
||||
onUpdateLog={onUpdateLog}
|
||||
/>
|
||||
</Profiler>,
|
||||
);
|
||||
});
|
||||
await waitForAct(act, () => document.querySelector('[role="alert"]') !== null);
|
||||
|
||||
const commitsAfterMount = commitCount;
|
||||
const container = document.getElementById('root')!.firstElementChild as HTMLElement;
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
|
||||
// Switching between two terminal tabs and vault must cause 0 re-renders of LogViewWrapper.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
|
||||
// Activating this log view re-renders it and reveals the surface.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(logView.id);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount + 1);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), null);
|
||||
|
||||
// Leaving this log view hides it again.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount + 2);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
} finally {
|
||||
console.error = originalConsoleError;
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useIsTerminalSurfaceActive and TerminalLayerMount avoid re-renders on terminal-to-terminal switches', async () => {
|
||||
const env = setupDom();
|
||||
const { Profiler, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { TerminalLayerMount, useIsTerminalSurfaceActive } = await import('./AppMounts');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const sessions = [makeSession('session-1', 'h1'), makeSession('session-2', 'h2')];
|
||||
const workspaces = [makeWorkspace('workspace-1', 'session-1')];
|
||||
const sessionIds = new Set(['session-1', 'session-2']);
|
||||
const workspaceIds = new Set(['workspace-1']);
|
||||
|
||||
let renders = 0;
|
||||
let lastActive: boolean | null = null;
|
||||
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
lastActive = useIsTerminalSurfaceActive(sessionIds, workspaceIds);
|
||||
return <div data-terminal-active={String(lastActive)} />;
|
||||
}
|
||||
|
||||
const originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastActive, true);
|
||||
const rendersAfterMount = renders;
|
||||
|
||||
// Switching between two terminal sessions and a workspace keeps surface active -> 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Switching to vault flips active true -> false (1 re-render).
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 1);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Switching vault -> sftp -> log view keeps surface inactive -> 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('log-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 1);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Returning to a terminal tab flips false -> true (1 re-render).
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 2);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Verify TerminalLayerMount itself does not re-render on session-1 -> session-2 -> workspace-1
|
||||
let mountCommits = 0;
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Profiler
|
||||
id="terminal-layer-mount"
|
||||
onRender={() => {
|
||||
mountCommits += 1;
|
||||
}}
|
||||
>
|
||||
<TerminalLayerMount
|
||||
{...({
|
||||
sessions,
|
||||
workspaces,
|
||||
draggingSessionId: null,
|
||||
} as unknown as ComponentProps<typeof TerminalLayerMount>)}
|
||||
/>
|
||||
</Profiler>,
|
||||
);
|
||||
});
|
||||
await waitForAct(act, () => document.querySelector('[role="alert"]') !== null);
|
||||
|
||||
const commitsAfterTerminalMount = mountCommits;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(mountCommits, commitsAfterTerminalMount);
|
||||
|
||||
// Switching away to vault flips isVisible (and LazyLoadBoundary resetKey) and triggers a re-render.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.ok(mountCommits > commitsAfterTerminalMount);
|
||||
} finally {
|
||||
console.error = originalConsoleError;
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginAIContextHost does not re-render on tab switches and reads live activeTabId on demand', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { usePluginAIContextHost } = await import('../state/usePluginAIContextHost');
|
||||
const { registerAppAppLockRuntime, getAppAppLockRuntime } = await import('../state/appRuntimeBridge');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const oldLock = getAppAppLockRuntime();
|
||||
registerAppAppLockRuntime({ locked: false } as NonNullable<ReturnType<typeof getAppAppLockRuntime>>);
|
||||
|
||||
const sessions = [makeSession('session-1', 'h1'), makeSession('session-2', 'h2')];
|
||||
const workspaces = [makeWorkspace('workspace-1', 'session-1')];
|
||||
|
||||
let requestHandler: ((req: {
|
||||
kind: string;
|
||||
requestId: string;
|
||||
runtimeId: string;
|
||||
actionToken: string;
|
||||
payload: Record<string, unknown>;
|
||||
}) => void) | null = null;
|
||||
const responses: Array<{ requestId: string; result?: unknown; error?: boolean }> = [];
|
||||
|
||||
Object.assign(env.dom.window, {
|
||||
netcatty: {
|
||||
onPluginAIHostRequest(handler: typeof requestHandler) {
|
||||
requestHandler = handler;
|
||||
return () => {
|
||||
requestHandler = null;
|
||||
};
|
||||
},
|
||||
async setPluginAIHostReady() {},
|
||||
async respondPluginAIHost(payload: { requestId: string; result?: unknown; error?: boolean }) {
|
||||
responses.push(payload);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let renders = 0;
|
||||
let latestChoice: ReturnType<typeof usePluginAIContextHost>['choice'] = null;
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
const host = usePluginAIContextHost({ sessions, workspaces });
|
||||
latestChoice = host.choice;
|
||||
return <div data-testid="ai-context-host" />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
const rendersAfterMount = renders;
|
||||
|
||||
// Switching across any tabs must cause 0 re-renders.
|
||||
for (const nextTab of ['session-2', 'workspace-1', 'vault', 'sftp', 'session-2']) {
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(nextTab);
|
||||
await flushTabStore();
|
||||
});
|
||||
}
|
||||
assert.equal(renders, rendersAfterMount);
|
||||
|
||||
// Triggering selection on demand without re-rendering must read live activeTabId ('session-2').
|
||||
assert.ok(requestHandler, 'expected plugin AI host request listener to be registered');
|
||||
await act(async () => {
|
||||
requestHandler!({
|
||||
kind: 'context.select',
|
||||
requestId: 'req-1',
|
||||
runtimeId: 'rt-1',
|
||||
actionToken: 'tok-1',
|
||||
payload: {},
|
||||
});
|
||||
});
|
||||
await waitForAct(act, () => latestChoice !== null);
|
||||
|
||||
await act(async () => {
|
||||
latestChoice!.confirm('');
|
||||
});
|
||||
await waitForAct(act, () => responses.length === 1);
|
||||
|
||||
assert.equal(responses[0].error, undefined);
|
||||
const result = responses[0].result as {
|
||||
items: Array<{ hostHandle: string; scope: string; title: string; version: string }>;
|
||||
};
|
||||
const sessionItem = result.items.find((item) => item.scope === 'session');
|
||||
assert.ok(sessionItem, 'expected active session source to be included');
|
||||
assert.equal(sessionItem.title, 'host-h2');
|
||||
|
||||
// Switching tabs without re-rendering must make context.current immediately report false.
|
||||
const rendersBeforeSwitch = renders;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersBeforeSwitch);
|
||||
|
||||
await act(async () => {
|
||||
requestHandler!({
|
||||
kind: 'context.current',
|
||||
requestId: 'req-2',
|
||||
runtimeId: 'rt-1',
|
||||
actionToken: 'tok-2',
|
||||
payload: { hostHandle: sessionItem.hostHandle, version: sessionItem.version },
|
||||
});
|
||||
});
|
||||
await waitForAct(act, () => responses.length === 2);
|
||||
assert.deepEqual(responses[1].result, { current: false });
|
||||
} finally {
|
||||
registerAppAppLockRuntime(oldLock);
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -53,6 +53,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
updateSessionStatus,
|
||||
updateSessionFontSize,
|
||||
clearSessionFontSizeOverride,
|
||||
@@ -86,6 +87,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
updateSessionRestoreCwd,
|
||||
getSessionRestoreCwd,
|
||||
updateSessionDynamicTitle,
|
||||
updateSessionPromptHost,
|
||||
updateSessionCodingCliProvider,
|
||||
} = session;
|
||||
|
||||
@@ -140,6 +142,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
updateSessionStatus,
|
||||
updateSessionFontSize,
|
||||
clearSessionFontSizeOverride,
|
||||
@@ -173,6 +176,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
updateSessionRestoreCwd,
|
||||
getSessionRestoreCwd,
|
||||
updateSessionDynamicTitle,
|
||||
updateSessionPromptHost,
|
||||
updateSessionCodingCliProvider,
|
||||
}), [
|
||||
addSessionToWorkspace,
|
||||
@@ -186,6 +190,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
copySession,
|
||||
copyWorkspace,
|
||||
createLocalTerminal,
|
||||
@@ -226,6 +231,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
toggleWorkspaceViewMode,
|
||||
updateSessionCodingCliProvider,
|
||||
updateSessionDynamicTitle,
|
||||
updateSessionPromptHost,
|
||||
updateSessionFontSize,
|
||||
updateSessionRestoreCwd,
|
||||
updateSessionStatus,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { dirname, join, relative, resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
@@ -11,6 +11,83 @@ const read = (path: string) => readFileSync(join(root, path), 'utf8');
|
||||
const staticImports = (source: string) =>
|
||||
[...source.matchAll(/^\s*import\s+(?!type\b)[^;]*?from\s+['"]([^'"]+)['"]/gm)].map((match) => match[1]);
|
||||
|
||||
const STATIC_SPECIFIER_RE =
|
||||
/(?:^|\n)\s*(?:import\s+(?!type\b)(?:[^;'"]*?\s+from\s+)?|export\s+(?!type\b)[^;'"]*?\s+from\s+)['"]([^'"]+)['"]/g;
|
||||
const CJS_REQUIRE_RE = /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g;
|
||||
|
||||
function extractStaticModuleSpecifiers(filePath: string, source: string): string[] {
|
||||
const specs: string[] = [];
|
||||
for (const match of source.matchAll(STATIC_SPECIFIER_RE)) {
|
||||
specs.push(match[1]);
|
||||
}
|
||||
if (filePath.endsWith('.cjs')) {
|
||||
for (const match of source.matchAll(CJS_REQUIRE_RE)) {
|
||||
specs.push(match[1]);
|
||||
}
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
function resolveLocalModule(fromFile: string, specifier: string): string | null {
|
||||
let base: string | null = null;
|
||||
if (specifier.startsWith('@/')) {
|
||||
base = join(root, specifier.slice(2));
|
||||
} else if (specifier.startsWith('.')) {
|
||||
base = resolve(dirname(fromFile), specifier);
|
||||
}
|
||||
if (!base) return null;
|
||||
|
||||
const candidates = [
|
||||
base,
|
||||
`${base}.ts`,
|
||||
`${base}.tsx`,
|
||||
`${base}.js`,
|
||||
`${base}.jsx`,
|
||||
`${base}.mjs`,
|
||||
`${base}.cjs`,
|
||||
join(base, 'index.ts'),
|
||||
join(base, 'index.tsx'),
|
||||
join(base, 'index.js'),
|
||||
join(base, 'index.jsx'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (existsSync(candidate) && statSync(candidate).isFile()) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function collectStartupExternalDependencies(entryRelativePath: string): Map<string, string[]> {
|
||||
const entryAbs = join(root, entryRelativePath);
|
||||
const visited = new Set<string>([entryAbs]);
|
||||
const parentChain = new Map<string, string[]>([[entryAbs, [entryRelativePath]]]);
|
||||
const externalPaths = new Map<string, string[]>();
|
||||
const queue: string[] = [entryAbs];
|
||||
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift()!;
|
||||
const source = readFileSync(current, 'utf8');
|
||||
const chain = parentChain.get(current)!;
|
||||
|
||||
for (const specifier of extractStaticModuleSpecifiers(current, source)) {
|
||||
if (specifier.startsWith('.') || specifier.startsWith('@/')) {
|
||||
const resolved = resolveLocalModule(current, specifier);
|
||||
if (resolved && !visited.has(resolved)) {
|
||||
visited.add(resolved);
|
||||
parentChain.set(resolved, [...chain, relative(root, resolved)]);
|
||||
queue.push(resolved);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!externalPaths.has(specifier)) {
|
||||
externalPaths.set(specifier, [...chain, specifier]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return externalPaths;
|
||||
}
|
||||
|
||||
test('only the English dictionary is bundled with the startup entry', () => {
|
||||
const imports = staticImports(read('application/i18n/messages.ts'));
|
||||
assert.deepEqual(imports.filter((path) => path.startsWith('./locales/')), ['./locales/en']);
|
||||
@@ -34,6 +111,27 @@ test("Vite's preload helper stays out of the vendor-ai chunk", () => {
|
||||
assert.match(read('vite.config.ts'), /vite\/preload-helper'\)\) return 'preload-helper'/);
|
||||
});
|
||||
|
||||
test('the QR decoder is loaded on demand', () => {
|
||||
assert.ok(!staticImports(read('components/HostTotpFields.tsx')).includes('jsqr'));
|
||||
test('the QR decoder and RE2JS regex validator are loaded on demand', () => {
|
||||
const imports = staticImports(read('components/HostTotpFields.tsx'));
|
||||
assert.ok(!imports.includes('jsqr'));
|
||||
assert.ok(!imports.includes('re2js'));
|
||||
});
|
||||
|
||||
test('startup entry does not statically reach re2js, css-tree, @remote-dom/core, or @monaco-editor/react', () => {
|
||||
const externals = collectStartupExternalDependencies('index.tsx');
|
||||
const forbidden = [
|
||||
{ label: 're2js', match: (spec: string) => spec === 're2js' || spec.startsWith('re2js/') },
|
||||
{ label: 'css-tree', match: (spec: string) => spec === 'css-tree' || spec.startsWith('css-tree/') },
|
||||
{ label: '@remote-dom/core', match: (spec: string) => spec === '@remote-dom/core' || spec.startsWith('@remote-dom/core/') },
|
||||
{ label: '@monaco-editor/react', match: (spec: string) => spec === '@monaco-editor/react' || spec.startsWith('@monaco-editor/react/') },
|
||||
];
|
||||
|
||||
for (const rule of forbidden) {
|
||||
const matchEntry = [...externals.entries()].find(([spec]) => rule.match(spec));
|
||||
assert.equal(
|
||||
matchEntry,
|
||||
undefined,
|
||||
`${rule.label} must not be statically reachable from index.tsx (found via ${matchEntry?.[1].join(' -> ')})`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,47 +1,10 @@
|
||||
import type { TerminalTheme } from '../../types';
|
||||
import { resolveReadableForegroundForHsl } from '../../domain/colorContrast';
|
||||
|
||||
function hexToHslToken(hex: string): string {
|
||||
const normalized = hex.startsWith('#') ? hex : `#${hex}`;
|
||||
const r = parseInt(normalized.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(normalized.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(normalized.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightnessToken(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newL = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(newL * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturationToken(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newS = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from '../../domain/colorContrast';
|
||||
|
||||
const setStylePropertyIfChanged = (element: HTMLElement, property: string, value: string) => {
|
||||
if (element.style.getPropertyValue(property) === value) return;
|
||||
|
||||
@@ -53,6 +53,8 @@ for (const accept of [false, true]) {
|
||||
{ id: "already-paused", status: "paused" },
|
||||
{ id: "pausing", status: "pausing" },
|
||||
{ id: "interrupted", status: "interrupted" },
|
||||
{ id: "packed-running", status: "transferring", controlKind: "packed-download", resumable: false },
|
||||
{ id: "packed-queued", status: "queued", controlKind: "packed-download", resumable: false },
|
||||
{ id: "child", parentTaskId: "running", status: "transferring" },
|
||||
],
|
||||
}) as unknown as ReturnType<typeof sftpTransferCenterStore.getSnapshot>);
|
||||
@@ -110,6 +112,44 @@ for (const accept of [false, true]) {
|
||||
});
|
||||
}
|
||||
|
||||
for (const accept of [false, true]) {
|
||||
test(`packed-only quit still asks for confirmation without pausing or resuming (${accept ? "accept" : "cancel"})`, async (t) => {
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
const previousAct = Object.getOwnPropertyDescriptor(globalThis, "IS_REACT_ACT_ENVIRONMENT");
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let prompts = 0;
|
||||
let query!: () => Promise<void>;
|
||||
const reports: Array<[boolean, string | undefined]> = [];
|
||||
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
|
||||
Object.defineProperty(globalThis, "window", { configurable: true, value: {
|
||||
confirm() { prompts++; return accept; },
|
||||
} });
|
||||
t.after(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow); else Reflect.deleteProperty(globalThis, "window");
|
||||
if (previousAct) Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", previousAct); else Reflect.deleteProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT");
|
||||
});
|
||||
t.mock.method(sftpTransferCenterStore, "getSnapshot", () => ({
|
||||
activeCount: 1, queuedCount: 0, attentionCount: 0,
|
||||
tasks: [{ ...makeTask("packed", "transferring"), controlKind: "packed-download", resumable: false }],
|
||||
}));
|
||||
t.mock.method(sftpTransferCenterStore, "pause", async () => { assert.fail("packed downloads cannot be paused"); });
|
||||
t.mock.method(sftpTransferCenterStore, "resume", async () => { assert.fail("packed selections cannot be replayed"); });
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
onCheckDirtyEditors(callback: typeof query) { query = callback; return () => {}; },
|
||||
reportDirtyEditorsResult(dirty: boolean, reason?: string) { reports.push([dirty, reason]); },
|
||||
}));
|
||||
function Probe() {
|
||||
useAppStartupEffects({ enabled: false, updateState: {}, sessions: [], hosts: [], keys: [], identities: [], knownHosts: [], proxyProfiles: [], groupConfigs: [], workspaces: [], portForwardingRules: [], t: (key: string) => key });
|
||||
return null;
|
||||
}
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await query();
|
||||
assert.equal(prompts, 1);
|
||||
assert.deepEqual(reports, [[true, "transfers"], accept ? [false, undefined] : [true, "transfers"]]);
|
||||
});
|
||||
}
|
||||
|
||||
for (const outcome of ["pause-rejected", "pause-expired", "prompt-expired"] as const) {
|
||||
test(`transfer quit refuses ${outcome} and resumes only the formerly active task`, async (t) => {
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
@@ -250,3 +290,71 @@ test("retry Cancel preserves the expired attempt auto-resume ownership", async (
|
||||
assert.equal(resumes, 1, "Cancel must restore work running before the first attempt");
|
||||
assert.deepEqual(replies.at(-1), { dirty: true, requestId: "retry" });
|
||||
});
|
||||
|
||||
test("stale listActivePackedDownloads snapshot cannot resurrect a packed transfer settled while in flight", async (t) => {
|
||||
const previousAct = Object.getOwnPropertyDescriptor(globalThis, "IS_REACT_ACT_ENVIRONMENT");
|
||||
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
const raceId = "packed-snapshot-race-settled";
|
||||
const liveId = "packed-snapshot-race-live";
|
||||
let emitGlobal!: (event: Record<string, unknown>) => void;
|
||||
let resolveActive!: (events: Array<Record<string, unknown>>) => void;
|
||||
const activePromise = new Promise<Array<Record<string, unknown>>>((resolve) => {
|
||||
resolveActive = resolve;
|
||||
});
|
||||
t.after(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
sftpTransferCenterStore.dismiss(raceId);
|
||||
sftpTransferCenterStore.dismiss(liveId);
|
||||
if (previousAct) Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", previousAct);
|
||||
else Reflect.deleteProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT");
|
||||
});
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
onGlobalSftpTransferEvent: (cb: typeof emitGlobal) => { emitGlobal = cb; return () => {}; },
|
||||
listActivePackedDownloads: () => activePromise,
|
||||
}));
|
||||
function Probe() {
|
||||
useAppStartupEffects({
|
||||
enabled: false, updateState: {}, sessions: [], hosts: [], keys: [], identities: [],
|
||||
knownHosts: [], proxyProfiles: [], groupConfigs: [], workspaces: [], portForwardingRules: [],
|
||||
t: (key: string) => key,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
|
||||
// Transfer completes before the active snapshot promise resolves; this window
|
||||
// had no prior row for raceId so the completion event alone creates nothing.
|
||||
emitGlobal({
|
||||
type: "completed",
|
||||
transferId: raceId,
|
||||
controlKind: "packed-download",
|
||||
transferred: 256,
|
||||
totalBytes: 256,
|
||||
endedAt: Date.now(),
|
||||
});
|
||||
assert.equal(sftpTransferCenterStore.getTask(raceId), undefined);
|
||||
|
||||
// Now the stale snapshot arrives containing both the settled raceId and a genuinely live transfer.
|
||||
await act(async () => {
|
||||
resolveActive([
|
||||
{
|
||||
type: "progress", transferId: raceId, direction: "download", fileName: "compose",
|
||||
sourcePath: "/srv/compose", targetPath: "/tmp/compose", isDirectory: true,
|
||||
controlKind: "packed-download", origin: "manual", retryable: false, resumable: false,
|
||||
transferred: 128, phase: "transferring",
|
||||
},
|
||||
{
|
||||
type: "progress", transferId: liveId, direction: "download", fileName: "still-running",
|
||||
sourcePath: "/srv/still-running", targetPath: "/tmp/still-running", isDirectory: true,
|
||||
controlKind: "packed-download", origin: "manual", retryable: false, resumable: false,
|
||||
transferred: 64, phase: "extracting",
|
||||
},
|
||||
]);
|
||||
await activePromise;
|
||||
});
|
||||
|
||||
assert.equal(sftpTransferCenterStore.getTask(raceId), undefined, "settled transfer must not be recreated as stuck transferring");
|
||||
assert.equal(sftpTransferCenterStore.getTask(liveId)?.status, "transferring");
|
||||
assert.equal(sftpTransferCenterStore.getTask(liveId)?.phase, "extracting");
|
||||
});
|
||||
@@ -315,7 +315,8 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
status: s.status,
|
||||
workspaceId: s.workspaceId,
|
||||
workspaceTitle: ws?.title,
|
||||
aiHidden: s.hiddenFromTabs === true,
|
||||
aiHidden: s.hiddenFromTabs === true && !s.poppedOut,
|
||||
poppedOut: s.poppedOut === true,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -393,7 +394,10 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
!task.parentTaskId && !["completed", "failed", "cancelled"].includes(task.status)
|
||||
));
|
||||
if (unfinishedTasks.length > 0) {
|
||||
const resumable = unfinishedTasks.filter((task) => (
|
||||
// Packed streams cannot pause or resume. Keep them in the quit
|
||||
// confirmation, but let them run until the owner actually closes.
|
||||
const pausableTasks = unfinishedTasks.filter((task) => task.controlKind !== "packed-download");
|
||||
const resumable = pausableTasks.filter((task) => (
|
||||
task.status === "transferring" || task.status === "queued"
|
||||
|| previousAttempt?.resumeTaskIds.has(task.id)
|
||||
));
|
||||
@@ -410,7 +414,7 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
};
|
||||
transferQuitPendingRef.current = attempt;
|
||||
bridge.reportDirtyEditorsResult?.(true, reason, { ...response, pending: true });
|
||||
const paused = await Promise.allSettled(unfinishedTasks.map((task) => sftpTransferCenterStore.pause(task.id)));
|
||||
const paused = await Promise.allSettled(pausableTasks.map((task) => sftpTransferCenterStore.pause(task.id)));
|
||||
if (transferQuitPendingRef.current !== attempt) return;
|
||||
const expired = () => request && Date.now() >= request.deadline;
|
||||
if (!expired() && paused.every((result) => result.status === "fulfilled")) {
|
||||
@@ -451,10 +455,34 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
}, [enabled, t]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let pendingActivePackedSync = true;
|
||||
// Any global event observed while the initial active-packed snapshot is in
|
||||
// flight is strictly newer than (or equal to) the snapshot; skip replaying
|
||||
// those IDs so a settled transfer cannot be recreated as stuck "transferring".
|
||||
const observedPackedEventIds = new Set<string>();
|
||||
const bridge = netcattyBridge.get();
|
||||
const unsubscribeEvents = bridge?.onGlobalSftpTransferEvent?.((event) => {
|
||||
if (pendingActivePackedSync && event?.transferId) {
|
||||
observedPackedEventIds.add(event.transferId);
|
||||
}
|
||||
sftpTransferCenterStore.ingestBackgroundEvent(event);
|
||||
});
|
||||
void bridge?.listActivePackedDownloads?.().then((activePacked) => {
|
||||
pendingActivePackedSync = false;
|
||||
if (!active || !Array.isArray(activePacked)) {
|
||||
observedPackedEventIds.clear();
|
||||
return;
|
||||
}
|
||||
for (const event of activePacked) {
|
||||
if (observedPackedEventIds.has(event.transferId)) continue;
|
||||
sftpTransferCenterStore.ingestBackgroundEvent(event);
|
||||
}
|
||||
observedPackedEventIds.clear();
|
||||
}).catch(() => {
|
||||
pendingActivePackedSync = false;
|
||||
observedPackedEventIds.clear();
|
||||
});
|
||||
const restartBackgroundTransfer = async (taskId: string, fromBeginning: boolean) => {
|
||||
const task = sftpTransferCenterStore.getSnapshot().tasks.find((candidate) => candidate.id === taskId);
|
||||
if (!task || !bridge?.openSftpForSession || !bridge.startStreamTransfer) return;
|
||||
@@ -591,6 +619,9 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
pendingActivePackedSync = false;
|
||||
observedPackedEventIds.clear();
|
||||
unsubscribeEvents?.();
|
||||
unregisterOwner();
|
||||
};
|
||||
|
||||
@@ -618,8 +618,8 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Usage: /rebind <number from /chats>',
|
||||
'ai.chat.rebindDone': 'Chat "{title}" rebound to this panel.',
|
||||
'ai.chat.rebindUnavailable': 'No rebind target in this panel scope.',
|
||||
'ai.chat.managerScopeTab': 'Current',
|
||||
'ai.chat.managerAllChatsTab': 'All',
|
||||
'ai.chat.managerScopeTab': 'Current chats',
|
||||
'ai.chat.managerAllChatsTab': 'All chats',
|
||||
'ai.chat.managerSearchPlaceholder': 'Search chat titles…',
|
||||
'ai.chat.managerFilterAllAgents': 'All agents',
|
||||
'ai.chat.managerMoreActions': 'More actions',
|
||||
@@ -722,6 +722,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'sec',
|
||||
'ai.safety.maxIterations': 'Max Iterations',
|
||||
'ai.safety.maxIterations.description': 'Maximum number of AI tool-use loops to prevent runaway execution. External agents may have their own internal iteration limits that take precedence.',
|
||||
'ai.safety.toolOutputMaxChars': 'Built-in AI Tool Output Limit',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Maximum characters kept inline per built-in AI tool result (such as terminal commands or SFTP reads) before truncating and spilling the full output to a saved handle (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'chars',
|
||||
'ai.safety.blocklist': 'Command Blocklist',
|
||||
'ai.safety.blocklist.description': 'Regex patterns to block dangerous commands executed through Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex pattern...',
|
||||
@@ -865,4 +868,21 @@ export const enAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "Settings changed in another window. Your draft is preserved. Cancel and reopen to load the saved settings.",
|
||||
"ai.toolSettings.retry": "Retry",
|
||||
"ai.toolSettings.applyingHttp": "Applying HTTP configuration...",
|
||||
"ai.vision.quickPrompt.explainError": "Explain current error",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Diagnose UI issue",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Summarize screen",
|
||||
"ai.vision.unsupportedModelWarning": "Current model ({model}) does not support image input. Switch to a vision-capable model to read remote screens.",
|
||||
"ai.vision.switchModel": "Switch model",
|
||||
"ai.vision.modelSupportsVision": "Supports image input",
|
||||
"ai.vision.snip.hint": "Drag to select a region · Esc to cancel",
|
||||
"ai.vision.snip.cancel": "Cancel region snip",
|
||||
"ai.vision.snip.ariaLabel": "Select a region of the remote desktop screen",
|
||||
"ai.vision.privacyBlocked": "AI screen reading is blocked for this session.",
|
||||
"ai.vision.viewingScreen": "AI is viewing screen",
|
||||
"ai.vision.askAi": "Ask AI",
|
||||
"ai.vision.captureFullAndAsk": "Capture screen & ask AI",
|
||||
"ai.vision.snipRegionAndAsk": "Snip region & ask AI",
|
||||
"ai.vision.openAiChat": "Open AI assistant",
|
||||
"ai.vision.privacyLockOn": "AI screen reading blocked",
|
||||
"ai.vision.privacyLockOff": "Allow AI to read screen",
|
||||
};
|
||||
@@ -475,7 +475,7 @@ export const enCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Dark palette',
|
||||
'settings.appearance.customCss': 'Custom CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Add custom CSS to personalize the app appearance. Changes apply immediately. Selected top tabs (`.top-tab[data-active="true"]`) read `--top-tab-active-bg`, `--top-tab-active-fg`, and `--top-tab-active-border`. Leave them unset to keep the current look.',
|
||||
'Add custom CSS to personalize the app appearance. Changes apply immediately.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Custom CSS help',
|
||||
'settings.appearance.customCss.help.title': 'Custom CSS guide',
|
||||
'settings.appearance.customCss.help.body': `Major UI regions expose a \`data-section\` attribute you can target. Changes apply as soon as you edit the CSS.
|
||||
@@ -905,7 +905,9 @@ Highlight the focused split pane:
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Network device mode for temporary connections',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'SSH connections with no saved host, including external launches and quick connect, start in network device mode. Saved hosts and groups keep their own device type. Off by default.',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled': 'Automatically reconnect SSH sessions',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'When turned on, established SSH sessions that drop unexpectedly try to reconnect every 5 seconds until the tab is closed or the connection succeeds.',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'Retry unexpectedly disconnected SSH sessions at the configured interval until the tab is closed or the connection succeeds.',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'SSH reconnect interval (seconds)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Wait between automatic reconnect attempts: 5–3600 seconds (default 5). Changes apply to the next scheduled attempt; an existing wait is unchanged.',
|
||||
'settings.terminal.connection.keepaliveInterval': 'Keepalive Interval',
|
||||
'settings.terminal.connection.keepaliveInterval.desc': 'How often (in seconds) to send SSH-level keepalive packets. Set to 0 to disable globally — note that individual hosts can override this in their own settings.',
|
||||
'settings.terminal.connection.keepaliveCountMax': 'Max unanswered keepalives',
|
||||
@@ -1037,6 +1039,7 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.binding.close-tab': 'Close Tab',
|
||||
'settings.shortcuts.binding.close-session': 'Close Session Pane',
|
||||
'settings.shortcuts.binding.new-tab': 'New Local Tab',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Reopen Closed Tab',
|
||||
'settings.shortcuts.binding.copy': 'Copy from Terminal',
|
||||
'settings.shortcuts.binding.paste': 'Paste to Terminal',
|
||||
'settings.shortcuts.binding.paste-selection': 'Paste Selection to Terminal',
|
||||
|
||||
@@ -106,4 +106,16 @@ export const enMonitorMessages = {
|
||||
"monitor.status.disconnected": "Disconnected",
|
||||
"monitor.status.stale": "Out of date",
|
||||
"monitor.status.missing": "Host deleted",
|
||||
"monitor.status.online": "Online",
|
||||
"monitor.status.offline": "Offline",
|
||||
"monitor.checkNow": "Check now",
|
||||
"monitor.openRemoteDesktop": "Open {protocol}",
|
||||
"monitor.latencyTrend": "Latency trend",
|
||||
"monitor.bannerVerified": "Protocol verified",
|
||||
"monitor.bannerUnverified": "Port open (banner unverified)",
|
||||
"monitor.companionDesktops": "Remote Desktop Services",
|
||||
"monitor.reachabilityOnly": "Reachability probe only",
|
||||
"monitor.viaSsh": "via SSH",
|
||||
"monitor.direct": "Direct",
|
||||
"monitor.rttStats": "Min / Avg / Max",
|
||||
};
|
||||
@@ -12,8 +12,12 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.hidden': 'Show hidden directories',
|
||||
'terminal.directory.refresh': 'Refresh',
|
||||
'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
|
||||
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
|
||||
'terminal.directory.busy': 'Wait for an empty shell prompt.',
|
||||
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
|
||||
'terminal.directory.accessDenied': 'Permission denied while listing this directory.',
|
||||
'terminal.directory.changeFailed': 'Could not confirm the directory change. Refresh before retrying.',
|
||||
'terminal.directory.unsupportedPath': 'This directory name cannot be sent safely to the terminal.',
|
||||
'settings.terminal.behavior.contextChips': 'Context Chips',
|
||||
@@ -692,6 +696,8 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
|
||||
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
|
||||
'tabs.closeOthers': 'Close Others',
|
||||
'tabs.closeToLeft': 'Close Tabs to the Left',
|
||||
'tabs.closeToRight': 'Close Tabs to the Right',
|
||||
|
||||
@@ -296,6 +296,12 @@ export const enVaultMessages: Messages = {
|
||||
'sftp.extract.extracting': 'Extracting {fileName}...',
|
||||
'sftp.extract.success': 'Extracted {fileName}',
|
||||
'sftp.extract.error': 'Failed to extract {fileName}: {error}',
|
||||
'sftp.packedDownload.receiving': 'Receiving packed download…',
|
||||
'sftp.packedDownload.extracting': 'Restoring files…',
|
||||
'sftp.packedDownload.fallback': 'Packed download is unavailable. Downloading files individually.',
|
||||
'sftp.packedDownload.selection': '{count} selected items',
|
||||
'sftp.packedDownload.conflict': 'An item with the same name already exists. Choose a different destination folder?',
|
||||
|
||||
'sftp.archive.action': 'Compress...',
|
||||
'sftp.archive.title': 'Compress files',
|
||||
'sftp.archive.description': 'Create an archive on the server from {count} selected items.',
|
||||
@@ -415,6 +421,8 @@ export const enVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Auto',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Go back',
|
||||
'sftp.goForward': 'Go forward',
|
||||
'sftp.goHome': 'Go to home',
|
||||
'sftp.goRoot': 'Go to root',
|
||||
'sftp.folderName': 'Folder name',
|
||||
@@ -485,6 +493,9 @@ export const enVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Copy file path',
|
||||
'sftp.context.insertPathToTerminal': 'Insert path into terminal',
|
||||
'sftp.context.cdInTerminal': 'Open in terminal (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'Cannot insert path while the terminal cursor is inside an unclosed quote or escape',
|
||||
'sftp.context.openWithDefault': 'Open with system default',
|
||||
'sftp.context.openWith': 'Open with...',
|
||||
'sftp.context.edit': 'Edit',
|
||||
@@ -605,6 +616,17 @@ export const enVaultMessages: Messages = {
|
||||
'settings.sftp.compressedUpload.enable': 'Enable folder compression',
|
||||
'settings.sftp.compressedUpload.enableDesc': 'Automatically compress folders using tar before transfer. Requires tar support on the server. Falls back to regular transfer if not available.',
|
||||
|
||||
'settings.sftp.packedDownload': 'Packed downloads',
|
||||
'settings.sftp.packedDownload.enable': 'Pack folders and multiple items for download',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Download the selection in one stream and restore its original layout on this device. If the server cannot pack it, download files individually.',
|
||||
'settings.sftp.downloadLocation': 'Download location',
|
||||
'settings.sftp.downloadLocation.directory': 'Default download folder',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'SFTP download dialogs open in this folder. If it is not set or no longer exists, the system Downloads folder is used.',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'System Downloads folder',
|
||||
'settings.sftp.downloadLocation.browse': 'Browse…',
|
||||
'settings.sftp.downloadLocation.reset': 'Use the system Downloads folder',
|
||||
'settings.sftp.downloadLocation.select': 'Choose default download folder',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Skip unchanged files',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Skip files whose size and modification time already match the destination (rsync-style). Disabled when replacing a folder into a staging path.',
|
||||
|
||||
@@ -654,6 +676,7 @@ export const enVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Choose protocol',
|
||||
'protocolSelect.rememberDefault': 'Remember as default (skip this prompt next time)',
|
||||
'protocolSelect.port': 'port:',
|
||||
|
||||
// Host Details
|
||||
@@ -965,7 +988,22 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Choose how multi-line startup commands are sent after connection.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Send line by line',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Send all at once',
|
||||
'hostDetails.otherProtocols': 'Other Protocols',
|
||||
'hostDetails.otherProtocols': 'Additional Protocols',
|
||||
'hostDetails.otherProtocolsHint': 'Attach secondary access methods to this SSH host without changing its default connection',
|
||||
'hostDetails.protocol.defaultHint': 'Default on double-click ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Enabled as secondary protocol',
|
||||
'hostDetails.protocol.setDefault': 'Set as default',
|
||||
'hostDetails.protocol.remove': 'Remove',
|
||||
'hostDetails.protocol.doubleClick': 'On double-click',
|
||||
'hostDetails.protocol.connectOptionDefault': 'Default: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Ask every time',
|
||||
'hostDetails.protocol.alsoEnable': 'Also enable',
|
||||
'hostDetails.protocol.removeProtocol': 'Remove {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Add {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Connection Behavior',
|
||||
'hostDetails.protocol.notEnabledDesc': '{protocol} is not enabled on this host yet.',
|
||||
'hostDetails.protocol.addSecondary': 'Add {protocol} (keep {defaultProtocol} default)',
|
||||
'hostDetails.protocol.switchOnly': 'Use {protocol} only',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': 'port',
|
||||
'hostDetails.telnet.credentials': 'Credentials',
|
||||
@@ -994,6 +1032,8 @@ export const enVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Runs {command}',
|
||||
'localShell.field.startDir': 'Start directory',
|
||||
'localShell.field.startDirPlaceholder': 'Inherit global start directory (home if unset)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Command to run after shell starts (e.g. npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Runs automatically after the local shell starts in the configured directory.',
|
||||
'localShell.saveAndConnect': 'Save & Connect',
|
||||
|
||||
'hostDetails.plugin.title': 'Plugin connection',
|
||||
@@ -1063,4 +1103,224 @@ export const enVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '{count} more items are included in this import.',
|
||||
'vault.import.plugins.moreDiagnostics': '{count} more diagnostics were omitted from this preview.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'New RDP Host',
|
||||
'vault.hosts.newVncHost': 'New VNC Host',
|
||||
'vault.hosts.connectRdp': 'Connect RDP',
|
||||
'vault.hosts.connectSsh': 'Connect SSH',
|
||||
'vault.hosts.connectVnc': 'Connect VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Open in System RDP',
|
||||
'vault.hosts.openInSystemVnc': 'Open in Screen Sharing',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Open JumpServer RDP in',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Choose whether JumpServer jms:// RDP sessions open in Netcatty\'s built-in client or your system RDP app.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Built-in Client',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'System RDP Client',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Import one or more Microsoft / JumpServer .rdp files.',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm, CSV, and .rdp imports also support RDP and VNC hosts.',
|
||||
'keychain.identity.domain': 'Domain (RDP, optional)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP or AD domain',
|
||||
'quickConnect.rdp.domain': 'Domain (optional)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP or leave empty for local account',
|
||||
'quickConnect.vnc.optionalUsername': 'Username (optional, for Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'Most VNC servers only require a password.',
|
||||
'quickConnect.vnc.passwordHint': 'Leave empty if the VNC server does not require authentication.',
|
||||
'quickConnect.vnc.displayHelper': 'Display {display}',
|
||||
'hostDetails.protocol.label': 'Protocol',
|
||||
'hostDetails.rdp.portLabel': 'RDP on',
|
||||
'hostDetails.vnc.portLabel': 'VNC on',
|
||||
'hostDetails.vnc.displayHint': 'Display {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 or :0',
|
||||
'hostDetails.rdp.domain': 'Domain (optional)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (optional)',
|
||||
'hostDetails.rdp.domainLabel': 'Domain',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Username, DOMAIN\\user, or JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Username (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Optional. Standard VNC servers authenticate with password only.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Username (optional)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Remote Desktop Display & Options',
|
||||
'hostDetails.rdp.resolutionMode': 'Resolution Mode',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Dynamic Resize',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'Fit to Window',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Fixed Size',
|
||||
'hostDetails.rdp.width': 'Width',
|
||||
'hostDetails.rdp.height': 'Height',
|
||||
'hostDetails.rdp.colorDepth': 'Color Depth',
|
||||
'hostDetails.rdp.audio': 'Audio Output',
|
||||
'hostDetails.rdp.audioDesc': 'Play remote desktop sound locally',
|
||||
'hostDetails.rdp.clipboard': 'Clipboard Sync',
|
||||
'hostDetails.rdp.clipboardDesc': 'Share text and images with the remote desktop',
|
||||
'hostDetails.rdp.clipboardFiles': 'Clipboard File Transfer',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Allow copying and dropping files via clipboard',
|
||||
'hostDetails.rdp.securityMode': 'Security Mode',
|
||||
'hostDetails.rdp.securityMode.auto': 'Auto',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'Standard RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Ignore Certificate Errors',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Skip TLS certificate trust prompts (not recommended)',
|
||||
'hostDetails.rdp.advanced': 'Advanced RDP Options',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Load Balance Info',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Alternate Shell',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Optional startup program path',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Working Directory',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Optional startup directory',
|
||||
'hostDetails.vnc.scalingMode': 'Scaling Mode',
|
||||
'hostDetails.vnc.scalingMode.fit': 'Fit to Window',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Actual (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Stretch',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Dynamic Resize',
|
||||
'hostDetails.vnc.quality': 'Image Quality',
|
||||
'hostDetails.vnc.compression': 'Compression Level',
|
||||
'hostDetails.vnc.viewOnly': 'View-Only Mode',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Disable sending mouse and keyboard input',
|
||||
'hostDetails.vnc.sharedSession': 'Shared Session',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Keep other VNC clients connected',
|
||||
'hostDetails.vnc.clipboard': 'Clipboard Sync',
|
||||
'hostDetails.vnc.clipboardDesc': 'Sync UTF-8 clipboard text with remote desktop',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Show Remote Cursor',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Render server-provided cursor shape',
|
||||
'hostDetails.companion.addVnc': 'Add VNC',
|
||||
'hostDetails.companion.addRdp': 'Add RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Tunnel via this host\'s SSH',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Forward through this host\'s SSH connection automatically',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Remote target address',
|
||||
'hostDetails.companion.credentialsSource': 'Credentials',
|
||||
'hostDetails.companion.credentials.host': 'Reuse host SSH credentials',
|
||||
'hostDetails.companion.credentials.manual': 'Custom username / password',
|
||||
'hostDetails.companion.credentials.manualHint': 'Saved securely to Keychain when you save this host',
|
||||
'hostDetails.companion.credentials.identity': 'Keychain Identity',
|
||||
'hostDetails.companion.credentials.ask': 'Ask on connect',
|
||||
'hostDetails.companion.identityPlaceholder': 'Select a saved identity',
|
||||
'hostDetails.companion.saveAsIdentity': 'Save as Identity',
|
||||
'hostDetails.companion.saveIdentityAction': 'Create & Select Identity',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Identity label (e.g. Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Identity saved and selected.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Connect with RDP by default',
|
||||
'hostDetails.companion.setDefaultVnc': 'Connect with VNC by default',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH Host Keys',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Remote Desktop Certificates',
|
||||
'knownHosts.certs.clearAll': 'Clear All',
|
||||
'knownHosts.certs.expired': 'Expired',
|
||||
'knownHosts.certs.expiredNotice': 'This certificate has passed its validity expiration date.',
|
||||
'knownHosts.certs.copied': 'SHA-256 fingerprint copied',
|
||||
'knownHosts.certs.action.inspect': 'Inspect Certificate',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Copy SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Revoke Trust',
|
||||
'knownHosts.certs.empty.title': 'No Trusted Remote Desktop Certificates',
|
||||
'knownHosts.certs.empty.desc': 'TLS certificates you trust while connecting to RDP or VeNCrypt VNC hosts will appear here.',
|
||||
'knownHosts.certs.empty.searchTitle': 'No Matching Certificates',
|
||||
'knownHosts.certs.empty.searchDesc': 'Try a different hostname, port, protocol, or SHA-256 fingerprint.',
|
||||
'knownHosts.certs.detail.subtitle': 'Pinned TLS certificate trusted on this device (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 Fingerprint',
|
||||
'knownHosts.certs.detail.subject': 'Subject',
|
||||
'knownHosts.certs.detail.issuer': 'Issuer',
|
||||
'knownHosts.certs.detail.validFrom': 'Valid From',
|
||||
'knownHosts.certs.detail.validTo': 'Valid To',
|
||||
'knownHosts.certs.detail.trustedAt': 'Trusted At',
|
||||
'knownHosts.certs.detail.lastSeen': 'Last Seen',
|
||||
'knownHosts.certs.revokeConfirm.title': 'Revoke certificate for {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'You will be asked to verify this server\'s TLS certificate again on the next connection.',
|
||||
'knownHosts.certs.clearAllConfirm.title': 'Clear all trusted remote desktop certificates?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'This will revoke all {count} pinned RDP/VNC certificates on this device.',
|
||||
'knownHosts.certs.toast.revoked': 'Certificate trust revoked',
|
||||
'knownHosts.certs.toast.clearedAll': 'Cleared {count} remote desktop certificates',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Test RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Test VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Latency (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Protocol',
|
||||
'hostDetails.connectionTest.probe.security': 'Negotiated Security',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB Version',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Security Types',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 Fingerprint',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Trusted',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'First Seen',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Changed',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Trust Fingerprint',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Certificate fingerprint trusted',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Record session',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Stop recording',
|
||||
'remoteDesktop.toolbar.recording': 'Recording',
|
||||
'remoteDesktop.toolbar.askAi': 'Ask AI',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Capture Screen & Ask AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Select Region & Ask AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'AI screen reading allowed',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'AI screen reading blocked for this session',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI is viewing this screen',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Drop files to send to remote clipboard (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'After dropping, press Ctrl+V inside the remote desktop to paste',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} file(s)',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'File drop is disabled in View-Only mode',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'Clipboard file transfer is disabled for this host',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Folders are not supported over RDP clipboard. Use SFTP or archive them as a .zip file.',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} file(s) · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Send Local Files...',
|
||||
'remoteDesktop.clipboard.uploading': 'Sending via clipboard',
|
||||
'remoteDesktop.clipboard.downloading': 'Receiving via clipboard',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Clipboard file transfer complete',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Clipboard file transfer failed',
|
||||
'remoteDesktop.recording.started': 'Session recording started',
|
||||
'remoteDesktop.recording.saved': 'Session recording saved to Connection Logs',
|
||||
'remoteDesktop.recording.failed': 'Session recording failed',
|
||||
'remoteDesktop.recording.unsupported': 'Session recording is not supported in this environment',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Download .webm',
|
||||
'logView.recording.delete': 'Delete Recording',
|
||||
'logView.recording.loading': 'Loading session recording...',
|
||||
'logView.recording.withAudio': 'Audio',
|
||||
'logView.recording.missingTitle': 'Recording no longer on disk',
|
||||
'logView.recording.missingDesc': 'This .webm file was removed, cleaned up by retention settings, or moved from the recordings folder.',
|
||||
'logView.recording.playbackErrorTitle': 'Unable to play recording',
|
||||
'logView.recording.playbackErrorDesc': 'The video file may be incomplete or unsupported by the built-in player.',
|
||||
'logView.recording.exportSuccess': 'Recording exported',
|
||||
'logView.recording.exportFailed': 'Failed to export recording',
|
||||
'logView.recording.deleted': 'Recording deleted',
|
||||
'logView.recording.deleteFailed': 'Failed to delete recording',
|
||||
'logView.recording.deleteConfirmTitle': 'Delete this session recording?',
|
||||
'logView.recording.deleteConfirmDesc': 'The .webm video file will be permanently removed from disk. The connection log entry itself will remain.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'No screen recording was captured for this session',
|
||||
'logView.remoteDesktop.host': 'Host',
|
||||
'logView.remoteDesktop.protocol': 'Protocol',
|
||||
'logView.remoteDesktop.user': 'Username',
|
||||
'logView.remoteDesktop.started': 'Started',
|
||||
'logView.remoteDesktop.ended': 'Ended',
|
||||
'logView.remoteDesktop.duration': 'Duration',
|
||||
'logView.remoteDesktop.recordingTip': 'Click Record in the remote desktop toolbar or enable Auto-record in Settings -> System to save .webm replays here.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Remote Desktop Recordings',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Auto-record remote desktop sessions',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Automatically start recording RDP and VNC sessions once connected (off by default to conserve disk space).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Recording frame rate',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Higher frame rates look smoother but use more CPU and disk space.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Include RDP audio',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Merge remote desktop audio output into the recorded .webm video when available.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Maximum storage cap',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Oldest unsaved session recordings are automatically removed when total usage exceeds this limit.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Retention period',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Automatically delete unsaved recordings older than this period.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} days',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Unlimited',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Local recording storage',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} files · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Calculating disk usage...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Refresh storage usage',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Open Folder',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Clear All Recordings',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': 'Clear all remote desktop recordings?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
|
||||
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
|
||||
|
||||
};
|
||||
@@ -618,8 +618,8 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Uso: /rebind <número de /chats>',
|
||||
'ai.chat.rebindDone': 'Chat «{title}» reasociado a este panel.',
|
||||
'ai.chat.rebindUnavailable': 'No hay destino de reasociación en el ámbito de este panel.',
|
||||
'ai.chat.managerScopeTab': 'Actual',
|
||||
'ai.chat.managerAllChatsTab': 'Todos',
|
||||
'ai.chat.managerScopeTab': 'Chats actuales',
|
||||
'ai.chat.managerAllChatsTab': 'Todos los chats',
|
||||
'ai.chat.managerSearchPlaceholder': 'Buscar títulos de chats…',
|
||||
'ai.chat.managerFilterAllAgents': 'Todos los agentes',
|
||||
'ai.chat.managerMoreActions': 'Más acciones',
|
||||
@@ -722,6 +722,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'seg',
|
||||
'ai.safety.maxIterations': 'Máximo de iteraciones',
|
||||
'ai.safety.maxIterations.description': 'Máximo de bucles de uso de herramientas de IA para evitar una ejecución descontrolada. Los agentes externos pueden tener sus propios límites de iteración internos que tienen prioridad.',
|
||||
'ai.safety.toolOutputMaxChars': 'Límite de salida de herramientas de IA integrada',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Máximo de caracteres que se mantienen en línea por resultado de herramienta de la IA integrada (como comandos de terminal o lecturas SFTP) antes de truncar y guardar la salida completa en un identificador (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'car.',
|
||||
'ai.safety.blocklist': 'Lista de bloqueo de comandos',
|
||||
'ai.safety.blocklist.description': 'Patrones regex para bloquear comandos peligrosos ejecutados mediante Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Patrón regex...',
|
||||
@@ -865,4 +868,21 @@ export const esAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "La configuración cambió en otra ventana. Se conserva el borrador. Cancela y vuelve a abrir para cargar la configuración guardada.",
|
||||
"ai.toolSettings.retry": "Reintentar",
|
||||
"ai.toolSettings.applyingHttp": "Aplicando la configuración HTTP...",
|
||||
"ai.vision.quickPrompt.explainError": "Explicar el error actual",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Diagnosticar problema de interfaz",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Resumir pantalla",
|
||||
"ai.vision.unsupportedModelWarning": "El modelo actual ({model}) no admite entrada de imágenes. Cambia a un modelo con visión para leer pantallas remotas.",
|
||||
"ai.vision.switchModel": "Cambiar modelo",
|
||||
"ai.vision.modelSupportsVision": "Admite entrada de imágenes",
|
||||
"ai.vision.snip.hint": "Arrastra para seleccionar un área · Esc para cancelar",
|
||||
"ai.vision.snip.cancel": "Cancelar selección",
|
||||
"ai.vision.snip.ariaLabel": "Seleccionar un área de la pantalla del escritorio remoto",
|
||||
"ai.vision.privacyBlocked": "La lectura de pantalla por IA está bloqueada en esta sesión.",
|
||||
"ai.vision.viewingScreen": "La IA está viendo la pantalla",
|
||||
"ai.vision.askAi": "Preguntar a la IA",
|
||||
"ai.vision.captureFullAndAsk": "Capturar pantalla y preguntar a la IA",
|
||||
"ai.vision.snipRegionAndAsk": "Recortar área y preguntar a la IA",
|
||||
"ai.vision.openAiChat": "Abrir asistente de IA",
|
||||
"ai.vision.privacyLockOn": "Lectura de pantalla por IA bloqueada",
|
||||
"ai.vision.privacyLockOff": "Permitir lectura de pantalla por IA",
|
||||
};
|
||||
@@ -475,7 +475,7 @@ export const esCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Paleta oscura',
|
||||
'settings.appearance.customCss': 'CSS personalizado',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Agrega CSS personalizado para personalizar la apariencia de la aplicación. Los cambios se aplican de inmediato. Las pestañas superiores seleccionadas (`.top-tab[data-active="true"]`) leen `--top-tab-active-bg`, `--top-tab-active-fg` y `--top-tab-active-border`. Si no las defines, se conserva el aspecto actual.',
|
||||
'Agrega CSS personalizado para personalizar la apariencia de la aplicación. Los cambios se aplican de inmediato.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Ayuda de CSS personalizado',
|
||||
'settings.appearance.customCss.help.title': 'Guía de CSS personalizado',
|
||||
'settings.appearance.customCss.help.body': `Las principales regiones de la interfaz exponen un atributo \`data-section\` que puedes usar como destino. Los cambios se aplican en cuanto editas el CSS.
|
||||
@@ -905,7 +905,9 @@ Resalta el panel dividido enfocado:
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Modo de dispositivo de red para conexiones temporales',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'Las conexiones SSH sin un host guardado, incluidos los inicios externos y la conexión rápida, se inician en modo de dispositivo de red. Los hosts y grupos guardados conservan su propio tipo de dispositivo. Desactivado de forma predeterminada.',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled': 'Reconectar sesiones SSH automáticamente',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'Cuando está activado, las sesiones SSH establecidas que se caen inesperadamente intentan reconectarse cada 5 segundos hasta que la pestaña se cierra o la conexión se establece.',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'Reintenta las sesiones SSH desconectadas inesperadamente con el intervalo configurado hasta cerrar la pestaña o restablecer la conexión.',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'Intervalo de reconexión SSH (segundos)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Espera entre intentos: 5–3600 segundos (predeterminado 5). Los cambios se aplican al siguiente intento programado, sin alterar una espera en curso.',
|
||||
'settings.terminal.connection.keepaliveInterval': 'Intervalo de keepalive',
|
||||
'settings.terminal.connection.keepaliveInterval.desc': 'Con qué frecuencia (en segundos) enviar paquetes keepalive a nivel de SSH. Pon 0 para desactivarlo globalmente; ten en cuenta que los hosts individuales pueden anular esto en su propia configuración.',
|
||||
'settings.terminal.connection.keepaliveCountMax': 'Máximo de keepalives sin respuesta',
|
||||
@@ -1037,6 +1039,7 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.binding.close-tab': 'Cerrar pestaña',
|
||||
'settings.shortcuts.binding.close-session': 'Cerrar panel de sesión',
|
||||
'settings.shortcuts.binding.new-tab': 'Nueva pestaña local',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Reabrir pestaña cerrada',
|
||||
'settings.shortcuts.binding.copy': 'Copiar desde la terminal',
|
||||
'settings.shortcuts.binding.paste': 'Pegar en la terminal',
|
||||
'settings.shortcuts.binding.paste-selection': 'Pegar selección en la terminal',
|
||||
|
||||
@@ -106,4 +106,16 @@ export const esMonitorMessages = {
|
||||
"monitor.status.disconnected": "Desconectado",
|
||||
"monitor.status.stale": "Sin actualizar",
|
||||
"monitor.status.missing": "Equipo eliminado",
|
||||
"monitor.status.online": "En línea",
|
||||
"monitor.status.offline": "Sin conexión",
|
||||
"monitor.checkNow": "Comprobar ahora",
|
||||
"monitor.openRemoteDesktop": "Abrir {protocol}",
|
||||
"monitor.latencyTrend": "Tendencia de latencia",
|
||||
"monitor.bannerVerified": "Protocolo verificado",
|
||||
"monitor.bannerUnverified": "Puerto abierto (banner sin verificar)",
|
||||
"monitor.companionDesktops": "Servicios de escritorio remoto",
|
||||
"monitor.reachabilityOnly": "Solo sondeo de disponibilidad",
|
||||
"monitor.viaSsh": "vía SSH",
|
||||
"monitor.direct": "Directo",
|
||||
"monitor.rttStats": "Mín / Prom / Máx",
|
||||
};
|
||||
@@ -12,6 +12,10 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.hidden': 'Mostrar directorios ocultos',
|
||||
'terminal.directory.refresh': 'Actualizar',
|
||||
'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.',
|
||||
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
|
||||
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
|
||||
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
|
||||
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
|
||||
'terminal.directory.readFailed': 'No se pudo leer el directorio. Actualiza e inténtalo de nuevo.',
|
||||
'terminal.directory.changeFailed': 'No se pudo confirmar el cambio. Actualiza antes de reintentar.',
|
||||
@@ -694,6 +698,8 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
|
||||
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
|
||||
'tabs.closeOthers': 'Cerrar las demás',
|
||||
'tabs.closeToLeft': 'Cerrar pestañas a la izquierda',
|
||||
'tabs.closeToRight': 'Cerrar pestañas a la derecha',
|
||||
|
||||
@@ -296,6 +296,12 @@ export const esVaultMessages: Messages = {
|
||||
'sftp.extract.extracting': 'Extrayendo {fileName}...',
|
||||
'sftp.extract.success': 'Se extrajo {fileName}',
|
||||
'sftp.extract.error': 'No se pudo extraer {fileName}: {error}',
|
||||
'sftp.packedDownload.receiving': 'Recibiendo la descarga empaquetada…',
|
||||
'sftp.packedDownload.extracting': 'Restaurando archivos…',
|
||||
'sftp.packedDownload.fallback': 'La descarga empaquetada no está disponible. Se descargarán los archivos por separado.',
|
||||
'sftp.packedDownload.selection': '{count} elementos seleccionados',
|
||||
'sftp.packedDownload.conflict': 'Ya existe un elemento con el mismo nombre. ¿Quieres elegir otra carpeta de destino?',
|
||||
|
||||
'sftp.archive.action': 'Comprimir...',
|
||||
'sftp.archive.title': 'Comprimir archivos',
|
||||
'sftp.archive.description': 'Crea un archivo comprimido en el servidor con los {count} elementos seleccionados.',
|
||||
@@ -415,6 +421,8 @@ export const esVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Auto',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Ir atrás',
|
||||
'sftp.goForward': 'Ir adelante',
|
||||
'sftp.goHome': 'Ir al inicio',
|
||||
'sftp.goRoot': 'Ir a la raíz',
|
||||
'sftp.folderName': 'Nombre de la carpeta',
|
||||
@@ -485,6 +493,9 @@ export const esVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Copiar ruta del archivo',
|
||||
'sftp.context.insertPathToTerminal': 'Insertar ruta en la terminal',
|
||||
'sftp.context.cdInTerminal': 'Abrir en la terminal (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'No se puede insertar la ruta mientras el cursor de la terminal esté dentro de una comilla o secuencia de escape sin cerrar',
|
||||
'sftp.context.openWithDefault': 'Abrir con la aplicación predeterminada del sistema',
|
||||
'sftp.context.openWith': 'Abrir con...',
|
||||
'sftp.context.edit': 'Editar',
|
||||
@@ -605,6 +616,17 @@ export const esVaultMessages: Messages = {
|
||||
'settings.sftp.compressedUpload.enable': 'Habilitar la compresión de carpetas',
|
||||
'settings.sftp.compressedUpload.enableDesc': 'Comprime automáticamente las carpetas con tar antes de la transferencia. Requiere soporte de tar en el servidor. Si no está disponible, se recurre a una transferencia normal.',
|
||||
|
||||
'settings.sftp.packedDownload': 'Descargas empaquetadas',
|
||||
'settings.sftp.packedDownload.enable': 'Empaquetar carpetas y selecciones múltiples para descargar',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Descarga la selección en una sola transferencia y restaura su estructura original en este dispositivo. Si el servidor no puede empaquetarla, los archivos se descargan por separado.',
|
||||
'settings.sftp.downloadLocation': 'Ubicación de descarga',
|
||||
'settings.sftp.downloadLocation.directory': 'Carpeta de descarga predeterminada',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'Los diálogos de descarga SFTP se abren en esta carpeta. Si no está configurada o ya no existe, se usa la carpeta Descargas del sistema.',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'Carpeta Descargas del sistema',
|
||||
'settings.sftp.downloadLocation.browse': 'Examinar…',
|
||||
'settings.sftp.downloadLocation.reset': 'Usar la carpeta Descargas del sistema',
|
||||
'settings.sftp.downloadLocation.select': 'Elegir la carpeta de descarga predeterminada',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Omitir archivos sin cambios',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Omite los archivos cuyo tamaño y hora de modificación ya coinciden con el destino (estilo rsync). Deshabilitado al reemplazar una carpeta en una ruta de staging.',
|
||||
|
||||
@@ -654,6 +676,7 @@ export const esVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Elegir protocolo',
|
||||
'protocolSelect.rememberDefault': 'Recordar como predeterminado (no preguntar la próxima vez)',
|
||||
'protocolSelect.port': 'puerto:',
|
||||
|
||||
// Host Details
|
||||
@@ -961,7 +984,22 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Elige cómo se envían los comandos de inicio multilínea después de la conexión.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Enviar línea por línea',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Enviar todo de una vez',
|
||||
'hostDetails.otherProtocols': 'Otros protocolos',
|
||||
'hostDetails.otherProtocols': 'Protocolos adicionales',
|
||||
'hostDetails.otherProtocolsHint': 'Adjunta métodos de acceso secundarios a este host SSH sin cambiar la conexión principal',
|
||||
'hostDetails.protocol.defaultHint': 'Predeterminado al hacer doble clic ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Activado como protocolo secundario',
|
||||
'hostDetails.protocol.setDefault': 'Establecer por defecto',
|
||||
'hostDetails.protocol.remove': 'Quitar',
|
||||
'hostDetails.protocol.doubleClick': 'Al hacer doble clic',
|
||||
'hostDetails.protocol.connectOptionDefault': 'Por defecto: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Preguntar cada vez',
|
||||
'hostDetails.protocol.alsoEnable': 'Activar también',
|
||||
'hostDetails.protocol.removeProtocol': 'Quitar {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Añadir {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Comportamiento de conexión',
|
||||
'hostDetails.protocol.notEnabledDesc': '{protocol} aún no está habilitado en este host.',
|
||||
'hostDetails.protocol.addSecondary': 'Añadir {protocol} (mantener {defaultProtocol})',
|
||||
'hostDetails.protocol.switchOnly': 'Usar solo {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet activado',
|
||||
'hostDetails.port': 'puerto',
|
||||
'hostDetails.telnet.credentials': 'Credenciales',
|
||||
@@ -996,6 +1034,8 @@ export const esVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Ejecuta {command}',
|
||||
'localShell.field.startDir': 'Directorio de inicio',
|
||||
'localShell.field.startDirPlaceholder': 'Heredar directorio inicial global (personal si no se configura)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Comando para ejecutar al iniciar la shell (p. ej., npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Se ejecuta automáticamente cuando la shell local inicia en el directorio configurado.',
|
||||
'localShell.saveAndConnect': 'Guardar y conectar',
|
||||
|
||||
'hostDetails.plugin.title': 'Conexión de plugin',
|
||||
@@ -1065,4 +1105,224 @@ export const esVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '{count} elementos más están incluidos en esta importación.',
|
||||
'vault.import.plugins.moreDiagnostics': '{count} diagnósticos más se omitieron de esta vista previa.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'Nuevo host RDP',
|
||||
'vault.hosts.newVncHost': 'Nuevo host VNC',
|
||||
'vault.hosts.connectRdp': 'Conectar RDP',
|
||||
'vault.hosts.connectSsh': 'Conectar SSH',
|
||||
'vault.hosts.connectVnc': 'Conectar VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Abrir en RDP del sistema',
|
||||
'vault.hosts.openInSystemVnc': 'Abrir en Compartir pantalla',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Abrir RDP de JumpServer en',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Elige si las sesiones RDP de JumpServer jms:// se abren en el cliente integrado de Netcatty o en el cliente RDP del sistema.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Cliente integrado',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'Cliente RDP del sistema',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Importa uno o varios archivos .rdp de Microsoft o JumpServer.',
|
||||
'vault.import.remoteDesktopTip': 'Las importaciones de MobaXterm, CSV y .rdp también admiten hosts RDP y VNC.',
|
||||
'keychain.identity.domain': 'Dominio (RDP, opcional)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP o dominio AD',
|
||||
'quickConnect.rdp.domain': 'Dominio (opcional)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP o déjalo vacío para cuenta local',
|
||||
'quickConnect.vnc.optionalUsername': 'Usuario (opcional, para Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'La mayoría de los servidores VNC solo requieren contraseña.',
|
||||
'quickConnect.vnc.passwordHint': 'Déjalo vacío si el servidor VNC no requiere autenticación.',
|
||||
'quickConnect.vnc.displayHelper': 'Pantalla {display}',
|
||||
'hostDetails.protocol.label': 'Protocolo',
|
||||
'hostDetails.rdp.portLabel': 'RDP en',
|
||||
'hostDetails.vnc.portLabel': 'VNC en',
|
||||
'hostDetails.vnc.displayHint': 'Pantalla {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 o :0',
|
||||
'hostDetails.rdp.domain': 'Dominio (opcional)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (opcional)',
|
||||
'hostDetails.rdp.domainLabel': 'Dominio',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Usuario, DOMINIO\\usuario o JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Usuario (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Opcional. Los servidores VNC estándar solo usan contraseña.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Usuario (opcional)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Pantalla y opciones de escritorio remoto',
|
||||
'hostDetails.rdp.resolutionMode': 'Modo de resolución',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Cambio dinámico',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'Ajustar a la ventana',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Tamaño fijo',
|
||||
'hostDetails.rdp.width': 'Ancho',
|
||||
'hostDetails.rdp.height': 'Alto',
|
||||
'hostDetails.rdp.colorDepth': 'Profundidad de color',
|
||||
'hostDetails.rdp.audio': 'Salida de audio',
|
||||
'hostDetails.rdp.audioDesc': 'Reproducir el audio del escritorio remoto localmente',
|
||||
'hostDetails.rdp.clipboard': 'Sincronización de portapapeles',
|
||||
'hostDetails.rdp.clipboardDesc': 'Compartir texto e imágenes con el escritorio remoto',
|
||||
'hostDetails.rdp.clipboardFiles': 'Transferencia de archivos por portapapeles',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Permitir copiar y arrastrar archivos mediante el portapapeles',
|
||||
'hostDetails.rdp.securityMode': 'Modo de seguridad',
|
||||
'hostDetails.rdp.securityMode.auto': 'Automático',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'RDP estándar',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Ignorar errores de certificado',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Omitir avisos de confianza de certificados TLS (no recomendado)',
|
||||
'hostDetails.rdp.advanced': 'Opciones avanzadas de RDP',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Información de balanceo de carga',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Shell alternativo',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Ruta opcional del programa inicial',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Directorio de trabajo',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Directorio inicial opcional',
|
||||
'hostDetails.vnc.scalingMode': 'Modo de escala',
|
||||
'hostDetails.vnc.scalingMode.fit': 'Ajustar a la ventana',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Tamaño real (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Estirar',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Cambio dinámico',
|
||||
'hostDetails.vnc.quality': 'Calidad de imagen',
|
||||
'hostDetails.vnc.compression': 'Nivel de compresión',
|
||||
'hostDetails.vnc.viewOnly': 'Modo solo lectura',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Desactivar el envío de entradas de ratón y teclado',
|
||||
'hostDetails.vnc.sharedSession': 'Sesión compartida',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Mantener conectados otros clientes VNC',
|
||||
'hostDetails.vnc.clipboard': 'Sincronización de portapapeles',
|
||||
'hostDetails.vnc.clipboardDesc': 'Sincronizar texto UTF-8 del portapapeles con el escritorio remoto',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Mostrar cursor remoto',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Mostrar la forma del cursor enviada por el servidor',
|
||||
'hostDetails.companion.addVnc': 'Añadir VNC',
|
||||
'hostDetails.companion.addRdp': 'Añadir RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Túnel mediante el SSH de este host',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Reenviar automáticamente a través de la conexión SSH de este host',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Dirección de destino remota',
|
||||
'hostDetails.companion.credentialsSource': 'Credenciales',
|
||||
'hostDetails.companion.credentials.host': 'Reutilizar credenciales SSH del host',
|
||||
'hostDetails.companion.credentials.manual': 'Usuario y contraseña propios',
|
||||
'hostDetails.companion.credentials.manualHint': 'Se guarda de forma segura en el llavero al guardar el host',
|
||||
'hostDetails.companion.credentials.identity': 'Identidad del llavero',
|
||||
'hostDetails.companion.credentials.ask': 'Preguntar al conectar',
|
||||
'hostDetails.companion.identityPlaceholder': 'Seleccionar una identidad guardada',
|
||||
'hostDetails.companion.saveAsIdentity': 'Guardar como identidad',
|
||||
'hostDetails.companion.saveIdentityAction': 'Crear y seleccionar identidad',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Nombre de identidad (p. ej. Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Identidad guardada y seleccionada.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Conectar con RDP por defecto',
|
||||
'hostDetails.companion.setDefaultVnc': 'Conectar con VNC por defecto',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'Claves de host SSH',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Certificados de escritorio remoto',
|
||||
'knownHosts.certs.clearAll': 'Borrar todo',
|
||||
'knownHosts.certs.expired': 'Caducado',
|
||||
'knownHosts.certs.expiredNotice': 'Este certificado ha superado su fecha de caducidad.',
|
||||
'knownHosts.certs.copied': 'Huella SHA-256 copiada',
|
||||
'knownHosts.certs.action.inspect': 'Inspeccionar certificado',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Copiar SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Revocar confianza',
|
||||
'knownHosts.certs.empty.title': 'Sin certificados de escritorio remoto confiables',
|
||||
'knownHosts.certs.empty.desc': 'Los certificados TLS en los que confíes al conectar a hosts RDP o VNC VeNCrypt aparecerán aquí.',
|
||||
'knownHosts.certs.empty.searchTitle': 'Sin certificados coincidentes',
|
||||
'knownHosts.certs.empty.searchDesc': 'Prueba con otro nombre de host, puerto, protocolo o huella SHA-256.',
|
||||
'knownHosts.certs.detail.subtitle': 'Certificado TLS fijado en este dispositivo (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'Huella SHA-256',
|
||||
'knownHosts.certs.detail.subject': 'Asunto',
|
||||
'knownHosts.certs.detail.issuer': 'Emisor',
|
||||
'knownHosts.certs.detail.validFrom': 'Válido desde',
|
||||
'knownHosts.certs.detail.validTo': 'Válido hasta',
|
||||
'knownHosts.certs.detail.trustedAt': 'Confiado el',
|
||||
'knownHosts.certs.detail.lastSeen': 'Última conexión',
|
||||
'knownHosts.certs.revokeConfirm.title': '¿Revocar el certificado de {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'Se te pedirá volver a verificar el certificado TLS de este servidor en la próxima conexión.',
|
||||
'knownHosts.certs.clearAllConfirm.title': '¿Borrar todos los certificados confiables de escritorio remoto?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'Se revocarán los {count} certificados RDP/VNC fijados en este dispositivo.',
|
||||
'knownHosts.certs.toast.revoked': 'Confianza del certificado revocada',
|
||||
'knownHosts.certs.toast.clearedAll': 'Se borraron {count} certificados de escritorio remoto',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Probar RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Probar VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Latencia (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Protocolo',
|
||||
'hostDetails.connectionTest.probe.security': 'Seguridad negociada',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'Versión RFB',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Tipos de seguridad',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'Huella SHA-256',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Confiable',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'Primera vez',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Modificado',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Confiar en huella',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Huella del certificado confiada',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Grabar sesión',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Detener grabación',
|
||||
'remoteDesktop.toolbar.recording': 'Grabando',
|
||||
'remoteDesktop.toolbar.askAi': 'Preguntar a la IA',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Capturar pantalla y preguntar a la IA',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Seleccionar región y preguntar a la IA',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'Lectura de pantalla por IA permitida',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'Lectura de pantalla por IA bloqueada en esta sesión',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'La IA está viendo esta pantalla',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Suelta archivos para enviarlos al portapapeles remoto (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'Después de soltar, pulsa Ctrl+V en el escritorio remoto para pegar',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} archivo(s)',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'No se pueden soltar archivos en modo solo lectura',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'La transferencia de archivos por portapapeles está desactivada en este host',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Las carpetas no son compatibles por el portapapeles RDP. Usa SFTP o comprímelas en un archivo .zip.',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} archivo(s) · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Enviar archivos locales...',
|
||||
'remoteDesktop.clipboard.uploading': 'Enviando por portapapeles',
|
||||
'remoteDesktop.clipboard.downloading': 'Recibiendo por portapapeles',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Transferencia de archivos por portapapeles completada',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Error en la transferencia de archivos por portapapeles',
|
||||
'remoteDesktop.recording.started': 'Grabación de sesión iniciada',
|
||||
'remoteDesktop.recording.saved': 'Grabación de sesión guardada en los registros de conexión',
|
||||
'remoteDesktop.recording.failed': 'Error al grabar la sesión',
|
||||
'remoteDesktop.recording.unsupported': 'La grabación de sesiones no es compatible en este entorno',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Descargar .webm',
|
||||
'logView.recording.delete': 'Eliminar grabación',
|
||||
'logView.recording.loading': 'Cargando grabación de sesión...',
|
||||
'logView.recording.withAudio': 'Audio',
|
||||
'logView.recording.missingTitle': 'La grabación ya no está en el disco',
|
||||
'logView.recording.missingDesc': 'Este archivo .webm fue eliminado, limpiado por la política de retención o movido de la carpeta de grabaciones.',
|
||||
'logView.recording.playbackErrorTitle': 'No se puede reproducir la grabación',
|
||||
'logView.recording.playbackErrorDesc': 'El archivo de vídeo puede estar incompleto o no ser compatible con el reproductor integrado.',
|
||||
'logView.recording.exportSuccess': 'Grabación exportada',
|
||||
'logView.recording.exportFailed': 'Error al exportar la grabación',
|
||||
'logView.recording.deleted': 'Grabación eliminada',
|
||||
'logView.recording.deleteFailed': 'Error al eliminar la grabación',
|
||||
'logView.recording.deleteConfirmTitle': '¿Eliminar esta grabación de sesión?',
|
||||
'logView.recording.deleteConfirmDesc': 'El archivo de vídeo .webm se eliminará permanentemente del disco. La entrada del registro de conexión se conservará.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'No se capturó ninguna grabación de pantalla para esta sesión',
|
||||
'logView.remoteDesktop.host': 'Host',
|
||||
'logView.remoteDesktop.protocol': 'Protocolo',
|
||||
'logView.remoteDesktop.user': 'Usuario',
|
||||
'logView.remoteDesktop.started': 'Inicio',
|
||||
'logView.remoteDesktop.ended': 'Fin',
|
||||
'logView.remoteDesktop.duration': 'Duración',
|
||||
'logView.remoteDesktop.recordingTip': 'Haz clic en Grabar en la barra de escritorio remoto o activa la grabación automática en Ajustes → Sistema para guardar repeticiones .webm aquí.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Grabaciones de escritorio remoto',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Grabar automáticamente sesiones de escritorio remoto',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Iniciar la grabación de sesiones RDP y VNC al conectarse (desactivado por defecto para ahorrar espacio en disco).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Frecuencia de fotogramas',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Una mayor frecuencia ofrece más fluidez pero consume más CPU y espacio en disco.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Incluir audio RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Combinar la salida de audio del escritorio remoto en el vídeo .webm cuando esté disponible.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Límite máximo de almacenamiento',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Las grabaciones más antiguas sin guardar se eliminan automáticamente al superar este límite.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Periodo de retención',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Eliminar automáticamente las grabaciones sin guardar más antiguas que este periodo.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} días',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Ilimitado',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Almacenamiento local de grabaciones',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} archivos · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Calculando uso de disco...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Actualizar uso de almacenamiento',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Abrir carpeta',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Borrar todas las grabaciones',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '¿Borrar todas las grabaciones de escritorio remoto?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
|
||||
|
||||
};
|
||||
@@ -210,3 +210,21 @@ test("managed group delete warning mentions SSH config backup in every locale",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("AI tool output limit settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.safety.toolOutputMaxChars",
|
||||
"ai.safety.toolOutputMaxChars.description",
|
||||
"ai.safety.toolOutputMaxChars.unit",
|
||||
] as const;
|
||||
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
@@ -557,8 +557,8 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Использование: /rebind <номер из /chats>',
|
||||
'ai.chat.rebindDone': 'Чат «{title}» привязан к этой панели.',
|
||||
'ai.chat.rebindUnavailable': 'В области этой панели нет цели для привязки.',
|
||||
'ai.chat.managerScopeTab': 'Текущие',
|
||||
'ai.chat.managerAllChatsTab': 'Все',
|
||||
'ai.chat.managerScopeTab': 'Текущие чаты',
|
||||
'ai.chat.managerAllChatsTab': 'Все чаты',
|
||||
'ai.chat.managerSearchPlaceholder': 'Поиск по названиям чатов…',
|
||||
'ai.chat.managerFilterAllAgents': 'Все агенты',
|
||||
'ai.chat.managerMoreActions': 'Ещё действия',
|
||||
@@ -661,6 +661,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'с',
|
||||
'ai.safety.maxIterations': 'Макс. число итераций',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'симв.',
|
||||
'ai.safety.blocklist': 'Чёрный список команд',
|
||||
'ai.safety.blocklist.description': 'Regex-шаблоны для блокировки опасных команд. Применяется как к встроенным, так и к внешним агентам через механизм выполнения Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex-шаблон...',
|
||||
@@ -795,4 +798,21 @@ export const ruAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "Настройки изменены в другом окне. Черновик сохранён. Отмените и откройте окно снова, чтобы загрузить сохранённые настройки.",
|
||||
"ai.toolSettings.retry": "Повторить",
|
||||
"ai.toolSettings.applyingHttp": "Применение настроек HTTP...",
|
||||
"ai.vision.quickPrompt.explainError": "Объяснить текущую ошибку",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Диагностировать проблему интерфейса",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Кратко описать экран",
|
||||
"ai.vision.unsupportedModelWarning": "Текущая модель ({model}) не поддерживает изображения. Переключитесь на модель с поддержкой зрения для просмотра удалённого экрана.",
|
||||
"ai.vision.switchModel": "Сменить модель",
|
||||
"ai.vision.modelSupportsVision": "Поддерживает изображения",
|
||||
"ai.vision.snip.hint": "Выделите область мышью · Esc для отмены",
|
||||
"ai.vision.snip.cancel": "Отменить выделение",
|
||||
"ai.vision.snip.ariaLabel": "Выделить область экрана удалённого рабочего стола",
|
||||
"ai.vision.privacyBlocked": "Чтение экрана ИИ заблокировано для этой сессии.",
|
||||
"ai.vision.viewingScreen": "ИИ просматривает экран",
|
||||
"ai.vision.askAi": "Спросить ИИ",
|
||||
"ai.vision.captureFullAndAsk": "Снимок экрана и вопрос ИИ",
|
||||
"ai.vision.snipRegionAndAsk": "Выделить область и спросить ИИ",
|
||||
"ai.vision.openAiChat": "Открыть ИИ-ассистента",
|
||||
"ai.vision.privacyLockOn": "Чтение экрана ИИ заблокировано",
|
||||
"ai.vision.privacyLockOff": "Разрешить ИИ чтение экрана",
|
||||
};
|
||||
@@ -38,7 +38,6 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.github.error.failed": "Не удалось проверить или установить плагин. Изучите технические подробности перед повторной попыткой.",
|
||||
"settings.plugins.github.error.details": "Технические подробности",
|
||||
|
||||
|
||||
// Common
|
||||
'common.save': 'Сохранить',
|
||||
'common.cancel': 'Отмена',
|
||||
@@ -433,7 +432,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Палитра тёмной темы',
|
||||
'settings.appearance.customCss': 'Пользовательский CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Добавьте пользовательский CSS, чтобы настроить внешний вид. Изменения применяются сразу. Выбранные верхние вкладки (`.top-tab[data-active="true"]`) читают `--top-tab-active-bg`, `--top-tab-active-fg` и `--top-tab-active-border`. Не задавайте их, чтобы сохранить текущий вид.',
|
||||
'Добавьте пользовательский CSS, чтобы настроить внешний вид. Изменения применяются сразу.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Справка по пользовательскому CSS',
|
||||
'settings.appearance.customCss.help.title': 'Руководство по пользовательскому CSS',
|
||||
'settings.appearance.customCss.help.body': `Основные области интерфейса помечены атрибутом \`data-section\` для CSS-селекторов. Изменения применяются сразу после правки.
|
||||
@@ -833,6 +832,8 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.connection.temporaryLegacyAlgorithms.desc': 'SSH-подключения без сохранённого хоста, включая запуск в стиле PuTTY и быстрое подключение, предлагают те же устаревшие алгоритмы, что и настройка хоста. Сохранённые хосты используют свою настройку. По умолчанию выключено: у этих алгоритмов есть известные слабости.',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Режим сетевого устройства для временных подключений',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'SSH-подключения без сохранённого хоста, включая внешний запуск и быстрое подключение, открываются в режиме сетевого устройства. Сохранённые хосты и группы сохраняют свой тип устройства. По умолчанию выключено.',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'Интервал переподключения SSH (секунды)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Ожидание между попытками: 5–3600 секунд (по умолчанию 5). Изменение применяется к следующему ожиданию; уже запущенный таймер не меняется.',
|
||||
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
|
||||
'settings.terminal.connection.keepaliveInterval.desc': 'Как часто (в секундах) отправлять keepalive-пакеты на уровне SSH. Установите 0, чтобы отключить глобально. Учтите, что отдельные хосты могут переопределять это значение в своих настройках.',
|
||||
'settings.terminal.connection.keepaliveCountMax': 'Макс. число пропущенных keepalive',
|
||||
@@ -951,6 +952,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': 'Закрыть вкладку',
|
||||
'settings.shortcuts.binding.close-session': 'Закрыть панель сессии',
|
||||
'settings.shortcuts.binding.new-tab': 'Новая локальная вкладка',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Повторно открыть закрытую вкладку',
|
||||
'settings.shortcuts.binding.copy': 'Копировать из терминала',
|
||||
'settings.shortcuts.binding.paste': 'Вставить в терминал',
|
||||
'settings.shortcuts.binding.paste-selection': 'Вставить выделение в терминал',
|
||||
|
||||
@@ -105,4 +105,16 @@ export const ruMonitorMessages = {
|
||||
"monitor.status.disconnected": "Отключено",
|
||||
"monitor.status.stale": "Устарело",
|
||||
"monitor.status.missing": "Сервер удалён",
|
||||
"monitor.status.online": "В сети",
|
||||
"monitor.status.offline": "Не в сети",
|
||||
"monitor.checkNow": "Проверить сейчас",
|
||||
"monitor.openRemoteDesktop": "Открыть {protocol}",
|
||||
"monitor.latencyTrend": "График задержки",
|
||||
"monitor.bannerVerified": "Протокол подтверждён",
|
||||
"monitor.bannerUnverified": "Порт открыт (баннер не проверен)",
|
||||
"monitor.companionDesktops": "Службы удалённого рабочего стола",
|
||||
"monitor.reachabilityOnly": "Только проверка доступности",
|
||||
"monitor.viaSsh": "через SSH",
|
||||
"monitor.direct": "Напрямую",
|
||||
"monitor.rttStats": "Мин / Сред / Макс",
|
||||
};
|
||||
@@ -12,6 +12,10 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.hidden': 'Показывать скрытые каталоги',
|
||||
'terminal.directory.refresh': 'Обновить',
|
||||
'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.',
|
||||
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
|
||||
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
|
||||
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
|
||||
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
|
||||
'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.',
|
||||
'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.',
|
||||
@@ -706,6 +710,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
|
||||
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
|
||||
'tabs.closeOthers': 'Закрыть остальные',
|
||||
'tabs.closeToLeft': 'Закрыть вкладки слева',
|
||||
'tabs.closeToRight': 'Закрыть вкладки справа',
|
||||
|
||||
@@ -340,6 +340,12 @@ export const ruVaultMessages: Messages = {
|
||||
'sftp.extract.extracting': 'Распаковка {fileName}...',
|
||||
'sftp.extract.success': 'Распакован {fileName}',
|
||||
'sftp.extract.error': 'Не удалось распаковать {fileName}: {error}',
|
||||
'sftp.packedDownload.receiving': 'Получение архива…',
|
||||
'sftp.packedDownload.extracting': 'Распаковка файлов…',
|
||||
'sftp.packedDownload.fallback': 'Упаковка недоступна. Файлы будут скачаны по отдельности.',
|
||||
'sftp.packedDownload.selection': 'Выбрано элементов: {count}',
|
||||
'sftp.packedDownload.conflict': 'Элемент с таким именем уже существует. Выбрать другую папку назначения?',
|
||||
|
||||
'sftp.archive.action': 'Сжать...',
|
||||
'sftp.archive.title': 'Сжать файлы',
|
||||
'sftp.archive.description': 'Создать архив на сервере из выбранных объектов: {count}.',
|
||||
@@ -458,6 +464,8 @@ export const ruVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Авто',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Назад',
|
||||
'sftp.goForward': 'Вперёд',
|
||||
'sftp.goHome': 'Перейти в домашний каталог',
|
||||
'sftp.goRoot': 'Перейти в корень',
|
||||
'sftp.folderName': 'Имя папки',
|
||||
@@ -528,6 +536,9 @@ export const ruVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Копировать путь к файлу',
|
||||
'sftp.context.insertPathToTerminal': 'Вставить путь в терминал',
|
||||
'sftp.context.cdInTerminal': 'Открыть в терминале (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'Невозможно вставить путь, пока курсор терминала находится внутри незакрытых кавычек или экранирования',
|
||||
'sftp.context.openWithDefault': 'Открыть в системном приложении',
|
||||
'sftp.context.openWith': 'Открыть с помощью...',
|
||||
'sftp.context.edit': 'Редактировать',
|
||||
@@ -648,6 +659,17 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.sftp.compressedUpload.enable': 'Включить сжатие папок',
|
||||
'settings.sftp.compressedUpload.enableDesc': 'Автоматически сжимать папки с помощью tar перед передачей. Требует поддержки tar на сервере. Если она недоступна, будет использована обычная передача.',
|
||||
|
||||
'settings.sftp.packedDownload': 'Скачивание архивом',
|
||||
'settings.sftp.packedDownload.enable': 'Упаковывать папки и выбранные вместе файлы перед скачиванием',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Выбранные файлы передаются одним потоком и распаковываются с сохранением структуры папок. Если сервер не поддерживает упаковку, файлы скачиваются по отдельности.',
|
||||
'settings.sftp.downloadLocation': 'Папка для загрузок',
|
||||
'settings.sftp.downloadLocation.directory': 'Папка загрузок по умолчанию',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'Диалоги скачивания по SFTP открываются в этой папке. Если она не задана или больше не существует, используется системная папка «Загрузки».',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'Системная папка «Загрузки»',
|
||||
'settings.sftp.downloadLocation.browse': 'Обзор…',
|
||||
'settings.sftp.downloadLocation.reset': 'Использовать системную папку «Загрузки»',
|
||||
'settings.sftp.downloadLocation.select': 'Выберите папку загрузок по умолчанию',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Пропускать неизменённые файлы',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Пропускать файлы, у которых размер и время изменения уже совпадают с назначением (в стиле rsync). Отключается при замене папки во временный путь.',
|
||||
|
||||
@@ -697,6 +719,7 @@ export const ruVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Выберите протокол',
|
||||
'protocolSelect.rememberDefault': 'Запомнить по умолчанию (больше не спрашивать)',
|
||||
'protocolSelect.port': 'порт:',
|
||||
|
||||
// Host Details
|
||||
@@ -1003,7 +1026,22 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Отправить сразу',
|
||||
'hostDetails.otherProtocols': 'Другие протоколы',
|
||||
'hostDetails.otherProtocols': 'Дополнительные протоколы',
|
||||
'hostDetails.otherProtocolsHint': 'Добавьте вспомогательные способы подключения к этому SSH-хосту без смены основного протокола',
|
||||
'hostDetails.protocol.defaultHint': 'По умолчанию при двойном клике ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Включён как дополнительный протокол',
|
||||
'hostDetails.protocol.setDefault': 'Сделать основным',
|
||||
'hostDetails.protocol.remove': 'Удалить',
|
||||
'hostDetails.protocol.doubleClick': 'По двойному клику',
|
||||
'hostDetails.protocol.connectOptionDefault': 'По умолчанию: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Спрашивать каждый раз',
|
||||
'hostDetails.protocol.alsoEnable': 'Также включить',
|
||||
'hostDetails.protocol.removeProtocol': 'Удалить {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Добавить {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Поведение подключения',
|
||||
'hostDetails.protocol.notEnabledDesc': 'Протокол {protocol} ещё не включён для этого хоста.',
|
||||
'hostDetails.protocol.addSecondary': 'Добавить {protocol} (оставить {defaultProtocol})',
|
||||
'hostDetails.protocol.switchOnly': 'Использовать только {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet на',
|
||||
'hostDetails.port': 'порт',
|
||||
'hostDetails.telnet.credentials': 'Учётные данные',
|
||||
@@ -1032,6 +1070,8 @@ export const ruVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Запускает {command}',
|
||||
'localShell.field.startDir': 'Начальный каталог',
|
||||
'localShell.field.startDirPlaceholder': 'Использовать общий начальный каталог (иначе домашний)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Команда после запуска оболочки (например, npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Выполняется автоматически после запуска локальной оболочки в указанном каталоге.',
|
||||
'localShell.saveAndConnect': 'Сохранить и открыть',
|
||||
|
||||
'hostDetails.plugin.title': 'Подключение плагина',
|
||||
@@ -1081,4 +1121,224 @@ export const ruVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': 'В импорт включено ещё элементов: {count}.',
|
||||
'vault.import.plugins.moreDiagnostics': 'В предварительном просмотре скрыто ещё сообщений: {count}.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'Новый хост RDP',
|
||||
'vault.hosts.newVncHost': 'Новый хост VNC',
|
||||
'vault.hosts.connectRdp': 'Подключить RDP',
|
||||
'vault.hosts.connectSsh': 'Подключить SSH',
|
||||
'vault.hosts.connectVnc': 'Подключить VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Открыть в системном RDP',
|
||||
'vault.hosts.openInSystemVnc': 'Открыть в системном VNC',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Открывать JumpServer RDP в',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Выберите, открывать ли RDP-сессии JumpServer jms:// во встроенном клиенте Netcatty или в системном RDP-клиенте.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Встроенный клиент',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'Системный клиент RDP',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Импорт одного или нескольких файлов Microsoft / JumpServer .rdp.',
|
||||
'vault.import.remoteDesktopTip': 'Импорт MobaXterm, CSV и .rdp также поддерживает хосты RDP и VNC.',
|
||||
'keychain.identity.domain': 'Домен (RDP, необязательно)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP или домен AD',
|
||||
'quickConnect.rdp.domain': 'Домен (необязательно)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP или оставьте пустым для локальной учётной записи',
|
||||
'quickConnect.vnc.optionalUsername': 'Имя пользователя (необязательно, для Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'Большинство серверов VNC требуют только пароль.',
|
||||
'quickConnect.vnc.passwordHint': 'Оставьте пустым, если сервер VNC не требует аутентификации.',
|
||||
'quickConnect.vnc.displayHelper': 'Дисплей {display}',
|
||||
'hostDetails.protocol.label': 'Протокол',
|
||||
'hostDetails.rdp.portLabel': 'RDP на',
|
||||
'hostDetails.vnc.portLabel': 'VNC на',
|
||||
'hostDetails.vnc.displayHint': 'Дисплей {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 или :0',
|
||||
'hostDetails.rdp.domain': 'Домен (необязательно)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (необязательно)',
|
||||
'hostDetails.rdp.domainLabel': 'Домен',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Имя пользователя, DOMAIN\\user или JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Имя пользователя (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Необязательно. Стандартный VNC использует только пароль.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Имя пользователя (необязательно)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Экран и параметры удалённого рабочего стола',
|
||||
'hostDetails.rdp.resolutionMode': 'Режим разрешения',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Динамический размер',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'По размеру окна',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Фиксированный размер',
|
||||
'hostDetails.rdp.width': 'Ширина',
|
||||
'hostDetails.rdp.height': 'Высота',
|
||||
'hostDetails.rdp.colorDepth': 'Глубина цвета',
|
||||
'hostDetails.rdp.audio': 'Вывод звука',
|
||||
'hostDetails.rdp.audioDesc': 'Воспроизводить звук удалённого рабочего стола локально',
|
||||
'hostDetails.rdp.clipboard': 'Синхронизация буфера обмена',
|
||||
'hostDetails.rdp.clipboardDesc': 'Обмен текстом и изображениями с удалённым рабочим столом',
|
||||
'hostDetails.rdp.clipboardFiles': 'Передача файлов через буфер обмена',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Разрешить копирование и перетаскивание файлов через буфер обмена',
|
||||
'hostDetails.rdp.securityMode': 'Режим безопасности',
|
||||
'hostDetails.rdp.securityMode.auto': 'Авто',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'Стандартный RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Игнорировать ошибки сертификатов',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Пропускать проверку доверия TLS-сертификатов (не рекомендуется)',
|
||||
'hostDetails.rdp.advanced': 'Дополнительные параметры RDP',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Информация балансировки (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Альтернативная оболочка',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Необязательный путь к программе запуска',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Рабочий каталог',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Необязательный рабочий каталог запуска',
|
||||
'hostDetails.vnc.scalingMode': 'Масштабирование',
|
||||
'hostDetails.vnc.scalingMode.fit': 'По размеру окна',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Исходный (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Растянуть',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Динамический размер',
|
||||
'hostDetails.vnc.quality': 'Качество изображения',
|
||||
'hostDetails.vnc.compression': 'Уровень сжатия',
|
||||
'hostDetails.vnc.viewOnly': 'Только просмотр',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Отключить передачу ввода мыши и клавиатуры',
|
||||
'hostDetails.vnc.sharedSession': 'Совместная сессия',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Не отключать другие VNC-клиенты',
|
||||
'hostDetails.vnc.clipboard': 'Синхронизация буфера обмена',
|
||||
'hostDetails.vnc.clipboardDesc': 'Синхронизировать текст UTF-8 с удалённым рабочим столом',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Показывать удалённый курсор',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Отображать курсор, передаваемый сервером',
|
||||
'hostDetails.companion.addVnc': 'Добавить VNC',
|
||||
'hostDetails.companion.addRdp': 'Добавить RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Туннель через SSH этого хоста',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Автоматическая переадресация через SSH-подключение этого хоста',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Удалённый целевой адрес',
|
||||
'hostDetails.companion.credentialsSource': 'Учётные данные',
|
||||
'hostDetails.companion.credentials.host': 'Использовать SSH-данные хоста',
|
||||
'hostDetails.companion.credentials.manual': 'Свой логин и пароль',
|
||||
'hostDetails.companion.credentials.manualHint': 'Безопасно сохранится в связке ключей при сохранении хоста',
|
||||
'hostDetails.companion.credentials.identity': 'Учётные данные из связки',
|
||||
'hostDetails.companion.credentials.ask': 'Спрашивать при подключении',
|
||||
'hostDetails.companion.identityPlaceholder': 'Выберите сохранённую учётную запись',
|
||||
'hostDetails.companion.saveAsIdentity': 'Сохранить как учётную запись',
|
||||
'hostDetails.companion.saveIdentityAction': 'Создать и выбрать',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Название (например, Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Учётная запись сохранена и выбрана.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Подключаться по RDP по умолчанию',
|
||||
'hostDetails.companion.setDefaultVnc': 'Подключаться по VNC по умолчанию',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'Ключи хостов SSH',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Сертификаты удалённого рабочего стола',
|
||||
'knownHosts.certs.clearAll': 'Очистить все',
|
||||
'knownHosts.certs.expired': 'Истёк',
|
||||
'knownHosts.certs.expiredNotice': 'Срок действия этого сертификата истёк.',
|
||||
'knownHosts.certs.copied': 'Отпечаток SHA-256 скопирован',
|
||||
'knownHosts.certs.action.inspect': 'Просмотреть сертификат',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Копировать SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Отозвать доверие',
|
||||
'knownHosts.certs.empty.title': 'Нет доверенных сертификатов удалённого рабочего стола',
|
||||
'knownHosts.certs.empty.desc': 'TLS-сертификаты, которым вы доверились при подключении к хостам RDP или VeNCrypt VNC, появятся здесь.',
|
||||
'knownHosts.certs.empty.searchTitle': 'Подходящие сертификаты не найдены',
|
||||
'knownHosts.certs.empty.searchDesc': 'Попробуйте другой хост, порт, протокол или отпечаток SHA-256.',
|
||||
'knownHosts.certs.detail.subtitle': 'Закреплённый TLS-сертификат на этом устройстве (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'Отпечаток SHA-256',
|
||||
'knownHosts.certs.detail.subject': 'Субъект',
|
||||
'knownHosts.certs.detail.issuer': 'Издатель',
|
||||
'knownHosts.certs.detail.validFrom': 'Действителен с',
|
||||
'knownHosts.certs.detail.validTo': 'Действителен до',
|
||||
'knownHosts.certs.detail.trustedAt': 'Доверен с',
|
||||
'knownHosts.certs.detail.lastSeen': 'Последнее подключение',
|
||||
'knownHosts.certs.revokeConfirm.title': 'Отозвать сертификат для {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'При следующем подключении потребуется повторно подтвердить TLS-сертификат этого сервера.',
|
||||
'knownHosts.certs.clearAllConfirm.title': 'Очистить все доверенные сертификаты удалённого рабочего стола?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'Будет отозвано доверие для всех закреплённых сертификатов RDP/VNC ({count}) на этом устройстве.',
|
||||
'knownHosts.certs.toast.revoked': 'Доверие к сертификату отозвано',
|
||||
'knownHosts.certs.toast.clearedAll': 'Очищено сертификатов удалённого рабочего стола: {count}',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Проверить RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Проверить VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Задержка (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Протокол',
|
||||
'hostDetails.connectionTest.probe.security': 'Согласованная защита',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'Версия RFB',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Типы аутентификации',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'Отпечаток SHA-256',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Доверенный',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'Впервые встречен',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Изменён',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Доверять отпечатку',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Отпечаток сертификата добавлен в доверенные',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Записать сессию',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Остановить запись',
|
||||
'remoteDesktop.toolbar.recording': 'Запись',
|
||||
'remoteDesktop.toolbar.askAi': 'Спросить ИИ',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Снять экран и спросить ИИ',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Выбрать область и спросить ИИ',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'Чтение экрана ИИ разрешено',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'Чтение экрана ИИ запрещено для этой сессии',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'ИИ просматривает экран',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Перетащите файлы для отправки в удалённый буфер обмена (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'После перетаскивания нажмите Ctrl+V на удалённом рабочем столе',
|
||||
'remoteDesktop.clipboard.dropFileCount': 'Файлов: {count}',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'Перетаскивание файлов отключено в режиме «Только просмотр»',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'Передача файлов через буфер обмена отключена для этого хоста',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Папки не поддерживаются буфером обмена RDP. Используйте SFTP или упакуйте их в .zip.',
|
||||
'remoteDesktop.clipboard.stagedPill': 'Файлов: {count} · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Выбрать локальные файлы...',
|
||||
'remoteDesktop.clipboard.uploading': 'Отправка через буфер обмена',
|
||||
'remoteDesktop.clipboard.downloading': 'Получение через буфер обмена',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Передача файлов через буфер обмена завершена',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Ошибка передачи файлов через буфер обмена',
|
||||
'remoteDesktop.recording.started': 'Запись сессии начата',
|
||||
'remoteDesktop.recording.saved': 'Запись сессии сохранена в журналах подключений',
|
||||
'remoteDesktop.recording.failed': 'Ошибка записи сессии',
|
||||
'remoteDesktop.recording.unsupported': 'Запись сессий не поддерживается в этой среде',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Скачать .webm',
|
||||
'logView.recording.delete': 'Удалить запись',
|
||||
'logView.recording.loading': 'Загрузка записи сессии...',
|
||||
'logView.recording.withAudio': 'Звук',
|
||||
'logView.recording.missingTitle': 'Файл записи отсутствует на диске',
|
||||
'logView.recording.missingDesc': 'Этот файл .webm был удалён, очищен по сроку хранения или перемещён из папки записей.',
|
||||
'logView.recording.playbackErrorTitle': 'Не удалось воспроизвести запись',
|
||||
'logView.recording.playbackErrorDesc': 'Видеофайл может быть повреждён или не поддерживается встроенным плеером.',
|
||||
'logView.recording.exportSuccess': 'Запись экспортирована',
|
||||
'logView.recording.exportFailed': 'Не удалось экспортировать запись',
|
||||
'logView.recording.deleted': 'Запись удалена',
|
||||
'logView.recording.deleteFailed': 'Не удалось удалить запись',
|
||||
'logView.recording.deleteConfirmTitle': 'Удалить эту запись сессии?',
|
||||
'logView.recording.deleteConfirmDesc': 'Видеофайл .webm будет безвозвратно удалён с диска. Сама запись в журнале подключений сохранится.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'Для этой сессии видеозапись экрана не велась',
|
||||
'logView.remoteDesktop.host': 'Хост',
|
||||
'logView.remoteDesktop.protocol': 'Протокол',
|
||||
'logView.remoteDesktop.user': 'Пользователь',
|
||||
'logView.remoteDesktop.started': 'Начало',
|
||||
'logView.remoteDesktop.ended': 'Окончание',
|
||||
'logView.remoteDesktop.duration': 'Длительность',
|
||||
'logView.remoteDesktop.recordingTip': 'Нажмите «Записать сессию» на панели удалённого рабочего стола или включите автозапись в Настройки → Система, чтобы сохранять повторы .webm.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Записи удалённого рабочего стола',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Автозапись сессий удалённого рабочего стола',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Самые старые несохранённые записи автоматически удаляются при превышении лимита.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Срок хранения',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Автоматически удалять несохранённые записи старше указанного срока.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} дн.',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Без ограничений',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Локальное хранилище записей',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': 'Файлов: {count} · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Подсчёт занятого места...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Обновить статистику',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Открыть папку',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Очистить все записи',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': 'Очистить все записи удалённого рабочего стола?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
|
||||
|
||||
};
|
||||
@@ -618,8 +618,8 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序号>',
|
||||
'ai.chat.rebindDone': '聊天“{title}”已重绑到此面板。',
|
||||
'ai.chat.rebindUnavailable': '当前面板范围内没有可用的重绑目标。',
|
||||
'ai.chat.managerScopeTab': '当前',
|
||||
'ai.chat.managerAllChatsTab': '全部',
|
||||
'ai.chat.managerScopeTab': '当前会话',
|
||||
'ai.chat.managerAllChatsTab': '全部会话',
|
||||
'ai.chat.managerSearchPlaceholder': '搜索会话标题…',
|
||||
'ai.chat.managerFilterAllAgents': '全部 Agent',
|
||||
'ai.chat.managerMoreActions': '更多操作',
|
||||
@@ -722,6 +722,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次数',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控执行的最大工具调用循环次数。外部 Agent 可能有自己的内部迭代限制,以其为准。',
|
||||
'ai.safety.toolOutputMaxChars': '内置 AI 工具输出限制',
|
||||
'ai.safety.toolOutputMaxChars.description': '内置 AI 单次工具调用(如终端命令或 SFTP 读取)直接返回的最大字符数,超出后会截断并将完整结果保存为可读取的句柄(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字符',
|
||||
'ai.safety.blocklist': '命令黑名单',
|
||||
'ai.safety.blocklist.description': '用于拦截通过 Netcatty 执行的危险命令的正则表达式。',
|
||||
'ai.safety.blocklist.placeholder': '正则表达式...',
|
||||
@@ -865,4 +868,21 @@ export const zhCNAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "设置已在另一窗口更改,当前草稿已保留。请取消并重新打开以加载已保存的设置。",
|
||||
"ai.toolSettings.retry": "重试",
|
||||
"ai.toolSettings.applyingHttp": "正在应用 HTTP 配置…",
|
||||
"ai.vision.quickPrompt.explainError": "解释当前报错",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "诊断界面问题",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "总结屏幕内容",
|
||||
"ai.vision.unsupportedModelWarning": "当前模型({model})不支持图片输入,切换至支持视觉的模型即可看图读屏。",
|
||||
"ai.vision.switchModel": "切换模型",
|
||||
"ai.vision.modelSupportsVision": "支持图片输入",
|
||||
"ai.vision.snip.hint": "拖拽框选区域 · 按 Esc 取消",
|
||||
"ai.vision.snip.cancel": "取消框选",
|
||||
"ai.vision.snip.ariaLabel": "框选远程桌面画面区域",
|
||||
"ai.vision.privacyBlocked": "当前会话已禁止 AI 读屏。",
|
||||
"ai.vision.viewingScreen": "AI 正在查看画面",
|
||||
"ai.vision.askAi": "问 AI",
|
||||
"ai.vision.captureFullAndAsk": "一键截屏问 AI",
|
||||
"ai.vision.snipRegionAndAsk": "框选区域问 AI",
|
||||
"ai.vision.openAiChat": "打开 AI 助手",
|
||||
"ai.vision.privacyLockOn": "已禁止 AI 读屏",
|
||||
"ai.vision.privacyLockOff": "允许 AI 读屏",
|
||||
};
|
||||
@@ -482,7 +482,7 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': '深色主题',
|
||||
'settings.appearance.customCss': '自定义 CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'使用自定义 CSS 个性化界面,修改会立即生效。选中的顶部标签(`.top-tab[data-active="true"]`)会读取 `--top-tab-active-bg`、`--top-tab-active-fg` 和 `--top-tab-active-border`。不设置则保持当前外观。',
|
||||
'使用自定义 CSS 个性化界面,修改会立即生效。',
|
||||
'settings.appearance.customCss.help.ariaLabel': '自定义 CSS 说明',
|
||||
'settings.appearance.customCss.help.title': '自定义 CSS 说明',
|
||||
'settings.appearance.customCss.help.body': `主要 UI 区块都暴露了 \`data-section\` 属性,供你用 CSS 定位。编辑后会立即生效。
|
||||
@@ -1043,6 +1043,12 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'sftp.extract.extracting': '正在解压 {fileName}...',
|
||||
'sftp.extract.success': '已解压 {fileName}',
|
||||
'sftp.extract.error': '解压 {fileName} 失败:{error}',
|
||||
'sftp.packedDownload.receiving': '正在接收打包数据…',
|
||||
'sftp.packedDownload.extracting': '正在还原文件…',
|
||||
'sftp.packedDownload.fallback': '当前无法打包下载,已改为逐文件下载。',
|
||||
'sftp.packedDownload.selection': '已选 {count} 项',
|
||||
'sftp.packedDownload.conflict': '目标位置已有同名项目,要选择其他保存文件夹吗?',
|
||||
|
||||
'sftp.archive.action': '压缩…',
|
||||
'sftp.archive.title': '压缩文件',
|
||||
'sftp.archive.description': '将 {count} 个选中项目打包到服务器上的压缩包。',
|
||||
@@ -1161,6 +1167,8 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'sftp.encoding.auto': '自动',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': '后退',
|
||||
'sftp.goForward': '前进',
|
||||
'sftp.goHome': '返回主目录',
|
||||
'sftp.goRoot': '回到根目录',
|
||||
'sftp.folderName': '文件夹名称',
|
||||
|
||||
@@ -101,4 +101,16 @@ export const zhCNMonitorMessages = {
|
||||
"monitor.status.disconnected": "已断开",
|
||||
"monitor.status.stale": "读数过期",
|
||||
"monitor.status.missing": "主机已删除",
|
||||
"monitor.status.online": "在线",
|
||||
"monitor.status.offline": "离线",
|
||||
"monitor.checkNow": "立即检测",
|
||||
"monitor.openRemoteDesktop": "打开 {protocol}",
|
||||
"monitor.latencyTrend": "延迟趋势",
|
||||
"monitor.bannerVerified": "协议已校验",
|
||||
"monitor.bannerUnverified": "端口已开放(未校验协议)",
|
||||
"monitor.companionDesktops": "伴生远程桌面服务",
|
||||
"monitor.reachabilityOnly": "仅在线与延迟探测",
|
||||
"monitor.viaSsh": "经由 SSH",
|
||||
"monitor.direct": "直连",
|
||||
"monitor.rttStats": "最小 / 平均 / 最大",
|
||||
};
|
||||
@@ -12,6 +12,10 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.hidden': '显示隐藏目录',
|
||||
'terminal.directory.refresh': '刷新',
|
||||
'terminal.directory.unavailable': '此会话暂不支持目录导航。',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
|
||||
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
|
||||
'terminal.directory.accessDenied': '没有权限列出此目录。',
|
||||
'terminal.directory.busy': '请等待终端回到空命令提示符。',
|
||||
'terminal.directory.readFailed': '无法读取此目录,请刷新重试。',
|
||||
'terminal.directory.changeFailed': '未能确认目录切换,请刷新后重试。',
|
||||
@@ -95,6 +99,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '复制文件路径',
|
||||
'sftp.context.insertPathToTerminal': '插入路径到终端',
|
||||
'sftp.context.cdInTerminal': '在终端中打开 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '终端光标位于未闭合的引号或转义符内,无法安全插入路径',
|
||||
'sftp.context.openWith': '打开方式...',
|
||||
'sftp.context.edit': '编辑',
|
||||
'sftp.opener.title': '打开方式',
|
||||
@@ -215,6 +222,17 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.sftp.compressedUpload.enable': '启用文件夹压缩',
|
||||
'settings.sftp.compressedUpload.enableDesc': '自动使用 tar 压缩文件夹后再传输。需要服务器支持 tar 命令,不支持时自动回退到普通传输。',
|
||||
|
||||
'settings.sftp.packedDownload': '打包下载',
|
||||
'settings.sftp.packedDownload.enable': '下载文件夹或多选项目时打包',
|
||||
'settings.sftp.packedDownload.enableDesc': '将所选内容一次传回,在本地自动还原原有目录结构。服务器不支持打包时,自动逐文件下载。',
|
||||
'settings.sftp.downloadLocation': '下载位置',
|
||||
'settings.sftp.downloadLocation.directory': '默认下载文件夹',
|
||||
'settings.sftp.downloadLocation.directoryDesc': '下载 SFTP 文件时,保存对话框默认打开此文件夹。未设置或文件夹已不存在时,使用系统“下载”文件夹。',
|
||||
'settings.sftp.downloadLocation.systemDefault': '系统“下载”文件夹',
|
||||
'settings.sftp.downloadLocation.browse': '浏览…',
|
||||
'settings.sftp.downloadLocation.reset': '恢复为系统“下载”文件夹',
|
||||
'settings.sftp.downloadLocation.select': '选择默认下载文件夹',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': '跳过未改文件',
|
||||
'settings.sftp.skipUnchanged.enableDesc': '当目标文件的大小与修改时间已与源一致时跳过传输(类似 rsync)。替换到暂存路径时自动禁用。',
|
||||
|
||||
@@ -457,7 +475,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.terminal.connection.defaultProxy.desc': '主机没有单独设置、也没有从分组继承代理时使用的已保存代理。选择“无”则直接连接。',
|
||||
'settings.terminal.connection.defaultProxy.none': '无',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled': 'SSH 断线后自动重连',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': '打开后,已连上的 SSH 会话意外断开时会每 5 秒尝试重新连接,直到关闭标签页或连接恢复。',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': '打开后,SSH 会话意外断开时会按设定间隔尝试重新连接,直到关闭标签页或连接恢复。',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'SSH 重连间隔(秒)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': '自动重连尝试之间的等待时间:5–3600 秒,默认 5 秒。修改从下次安排重试时生效,不改变已开始的等待。',
|
||||
'settings.terminal.connection.keepaliveInterval': '会话保持间隔',
|
||||
'settings.terminal.connection.keepaliveInterval.desc': '向服务器发送 SSH 保活数据包的频率(秒)。设为 0 表示全局禁用——单个主机可在自己的设置里覆盖此值。',
|
||||
'settings.terminal.connection.keepaliveCountMax': '最大无响应保活次数',
|
||||
@@ -582,6 +602,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': '关闭标签页',
|
||||
'settings.shortcuts.binding.close-session': '关闭会话窗格',
|
||||
'settings.shortcuts.binding.new-tab': '新建本地标签页',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': '重新打开关闭的标签页',
|
||||
'settings.shortcuts.binding.copy': '从终端复制',
|
||||
'settings.shortcuts.binding.paste': '粘贴到终端',
|
||||
'settings.shortcuts.binding.paste-selection': '将选区粘贴到终端',
|
||||
@@ -771,6 +792,8 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
|
||||
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
|
||||
'tabs.closeOthers': '关闭其他标签',
|
||||
'tabs.closeToLeft': '关闭左侧标签',
|
||||
'tabs.closeToRight': '关闭右侧标签',
|
||||
|
||||
@@ -109,6 +109,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': '选择协议',
|
||||
'protocolSelect.rememberDefault': '记住为默认连接(下次不再询问)',
|
||||
'protocolSelect.port': '端口:',
|
||||
// Host Details
|
||||
'hostDetails.title.details': '主机详情',
|
||||
@@ -379,7 +380,22 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': '选择连接后如何发送多行启动命令。',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': '逐行发送',
|
||||
'hostDetails.startupCommand.runMode.paste': '一次性发送',
|
||||
'hostDetails.otherProtocols': '其他协议',
|
||||
'hostDetails.otherProtocols': '附加协议',
|
||||
'hostDetails.otherProtocolsHint': '为当前 SSH 主机挂载辅助连接方式,不影响默认连接',
|
||||
'hostDetails.protocol.defaultHint': '双击默认使用 {protocol}',
|
||||
'hostDetails.protocol.secondaryHint': '已作为附加协议启用',
|
||||
'hostDetails.protocol.setDefault': '设为默认',
|
||||
'hostDetails.protocol.remove': '移除',
|
||||
'hostDetails.protocol.doubleClick': '双击连接',
|
||||
'hostDetails.protocol.connectOptionDefault': '默认 {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': '每次询问',
|
||||
'hostDetails.protocol.alsoEnable': '同时启用',
|
||||
'hostDetails.protocol.removeProtocol': '移除 {protocol}',
|
||||
'hostDetails.protocol.addProtocol': '添加 {protocol}',
|
||||
'hostDetails.section.connectBehavior': '连接行为',
|
||||
'hostDetails.protocol.notEnabledDesc': '当前主机尚未启用 {protocol} 协议。',
|
||||
'hostDetails.protocol.addSecondary': '添加 {protocol}(保留 {defaultProtocol} 默认)',
|
||||
'hostDetails.protocol.switchOnly': '仅使用 {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': '端口',
|
||||
'hostDetails.telnet.credentials': '凭据',
|
||||
@@ -408,6 +424,8 @@ export const zhCNVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': '启动 {command}',
|
||||
'localShell.field.startDir': '启动目录',
|
||||
'localShell.field.startDirPlaceholder': '继承全局起始目录(未设置时为主目录)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Shell 启动后执行的命令(例如:npm run dev)',
|
||||
'localShell.field.startupCommandDesc': '本地 Shell 在启动目录打开后自动执行该命令。',
|
||||
'localShell.saveAndConnect': '保存并打开',
|
||||
|
||||
'hostDetails.plugin.title': '插件连接',
|
||||
@@ -1053,4 +1071,224 @@ export const zhCNVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '本次导入还包含 {count} 个项目。',
|
||||
'vault.import.plugins.moreDiagnostics': '预览中省略了另外 {count} 条诊断信息。',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': '新建 RDP 主机',
|
||||
'vault.hosts.newVncHost': '新建 VNC 主机',
|
||||
'vault.hosts.connectRdp': '连接 RDP',
|
||||
'vault.hosts.connectSsh': '连接 SSH',
|
||||
'vault.hosts.connectVnc': '连接 VNC',
|
||||
'vault.hosts.openInSystemRdp': '在系统 RDP 客户端中打开',
|
||||
'vault.hosts.openInSystemVnc': '在系统屏幕共享中打开',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'JumpServer RDP 打开方式',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': '选择通过 JumpServer jms:// 启动 Windows RDP 会话时使用 Netcatty 内置客户端还是系统 RDP 客户端。',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': '内置客户端',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': '系统 RDP 客户端',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': '导入单个或多个 Microsoft / JumpServer .rdp 文件。',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm、CSV 与 .rdp 导入均支持 RDP 和 VNC 主机。',
|
||||
'keychain.identity.domain': '域 (RDP,可选)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP 或 AD 域名',
|
||||
'quickConnect.rdp.domain': '域(可选)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP 或留空使用本地账户',
|
||||
'quickConnect.vnc.optionalUsername': '用户名(可选,用于 Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': '大多数 VNC 服务器仅需密码认证。',
|
||||
'quickConnect.vnc.passwordHint': '如果 VNC 服务器无需密码,可留空直接连接。',
|
||||
'quickConnect.vnc.displayHelper': '显示器 {display}',
|
||||
'hostDetails.protocol.label': '协议',
|
||||
'hostDetails.rdp.portLabel': 'RDP 端口',
|
||||
'hostDetails.vnc.portLabel': 'VNC 端口',
|
||||
'hostDetails.vnc.displayHint': '显示器 {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 或 :0',
|
||||
'hostDetails.rdp.domain': '域(可选)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP(可选)',
|
||||
'hostDetails.rdp.domainLabel': '域',
|
||||
'hostDetails.rdp.usernamePlaceholder': '用户名、DOMAIN\\user 或 JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': '用户名(Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': '可选。标准 VNC 服务器仅使用密码认证。',
|
||||
'hostDetails.vnc.usernamePlaceholder': '用户名(可选)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': '远程桌面显示与选项',
|
||||
'hostDetails.rdp.resolutionMode': '分辨率模式',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': '动态自适应',
|
||||
'hostDetails.rdp.resolutionMode.fit': '适应窗口',
|
||||
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
|
||||
'hostDetails.rdp.width': '宽度',
|
||||
'hostDetails.rdp.height': '高度',
|
||||
'hostDetails.rdp.colorDepth': '色深',
|
||||
'hostDetails.rdp.audio': '音频输出',
|
||||
'hostDetails.rdp.audioDesc': '在本地播放远程桌面声音',
|
||||
'hostDetails.rdp.clipboard': '剪贴板同步',
|
||||
'hostDetails.rdp.clipboardDesc': '与远程桌面共享文本与图片',
|
||||
'hostDetails.rdp.clipboardFiles': '剪贴板文件传输',
|
||||
'hostDetails.rdp.clipboardFilesDesc': '允许通过剪贴板复制和拖拽传输文件',
|
||||
'hostDetails.rdp.securityMode': '安全模式',
|
||||
'hostDetails.rdp.securityMode.auto': '自动',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': '标准 RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': '忽略证书错误',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': '跳过 TLS 证书信任提示(不推荐)',
|
||||
'hostDetails.rdp.advanced': '高级 RDP 选项',
|
||||
'hostDetails.rdp.loadBalanceInfo': '负载均衡信息 (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': '启动程序 (Alternate Shell)',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': '可选的启动程序路径',
|
||||
'hostDetails.rdp.shellWorkingDir': '工作目录',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': '可选的启动工作目录',
|
||||
'hostDetails.vnc.scalingMode': '缩放模式',
|
||||
'hostDetails.vnc.scalingMode.fit': '适应窗口',
|
||||
'hostDetails.vnc.scalingMode.actual': '原始比例 (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': '拉伸填充',
|
||||
'hostDetails.vnc.scalingMode.dynamic': '动态自适应',
|
||||
'hostDetails.vnc.quality': '画质等级',
|
||||
'hostDetails.vnc.compression': '压缩等级',
|
||||
'hostDetails.vnc.viewOnly': '只读模式',
|
||||
'hostDetails.vnc.viewOnlyDesc': '禁止向远端发送鼠标和键盘输入',
|
||||
'hostDetails.vnc.sharedSession': '共享会话',
|
||||
'hostDetails.vnc.sharedSessionDesc': '连接时保持其他 VNC 客户端不断开',
|
||||
'hostDetails.vnc.clipboard': '剪贴板同步',
|
||||
'hostDetails.vnc.clipboardDesc': '与远程桌面同步 UTF-8 剪贴板文本',
|
||||
'hostDetails.vnc.showRemoteCursor': '显示远程光标',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': '渲染服务端下发的光标样式',
|
||||
'hostDetails.companion.addVnc': '添加 VNC',
|
||||
'hostDetails.companion.addRdp': '添加 RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': '通过当前主机 SSH 隧道直连',
|
||||
'hostDetails.companion.tunnelViaSshDesc': '自动经由当前主机的 SSH 连接转发端口',
|
||||
'hostDetails.companion.tunnelTargetHost': '远端目标地址',
|
||||
'hostDetails.companion.credentialsSource': '凭证来源',
|
||||
'hostDetails.companion.credentials.host': '复用主机 SSH 凭证',
|
||||
'hostDetails.companion.credentials.manual': '独立用户名 / 密码',
|
||||
'hostDetails.companion.credentials.manualHint': '保存主机时自动加密存入钥匙串',
|
||||
'hostDetails.companion.credentials.identity': '钥匙串身份',
|
||||
'hostDetails.companion.credentials.ask': '每次连接时询问',
|
||||
'hostDetails.companion.identityPlaceholder': '选择已保存的身份',
|
||||
'hostDetails.companion.saveAsIdentity': '保存为身份',
|
||||
'hostDetails.companion.saveIdentityAction': '创建并选择身份',
|
||||
'hostDetails.companion.identityLabelPlaceholder': '身份名称(如 Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': '已保存并选中该身份。',
|
||||
'hostDetails.companion.setDefaultRdp': '默认使用 RDP 连接',
|
||||
'hostDetails.companion.setDefaultVnc': '默认使用 VNC 连接',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH 主机密钥',
|
||||
'knownHosts.tabs.remoteDesktopCerts': '远程桌面证书',
|
||||
'knownHosts.certs.clearAll': '全部清空',
|
||||
'knownHosts.certs.expired': '已过期',
|
||||
'knownHosts.certs.expiredNotice': '该证书已超过有效期。',
|
||||
'knownHosts.certs.copied': '已复制 SHA-256 指纹',
|
||||
'knownHosts.certs.action.inspect': '查看证书详情',
|
||||
'knownHosts.certs.action.copyFingerprint': '复制 SHA-256',
|
||||
'knownHosts.certs.action.revoke': '吊销信任',
|
||||
'knownHosts.certs.empty.title': '暂无已信任的远程桌面证书',
|
||||
'knownHosts.certs.empty.desc': '连接 RDP 或 VeNCrypt VNC 主机并选择信任的 TLS 证书将显示在此处。',
|
||||
'knownHosts.certs.empty.searchTitle': '未找到匹配的证书',
|
||||
'knownHosts.certs.empty.searchDesc': '请尝试搜索其他主机名、端口、协议或 SHA-256 指纹。',
|
||||
'knownHosts.certs.detail.subtitle': '本设备已固定信任的 TLS 证书(TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 指纹',
|
||||
'knownHosts.certs.detail.subject': '颁发给 (Subject)',
|
||||
'knownHosts.certs.detail.issuer': '颁发者 (Issuer)',
|
||||
'knownHosts.certs.detail.validFrom': '生效时间',
|
||||
'knownHosts.certs.detail.validTo': '过期时间',
|
||||
'knownHosts.certs.detail.trustedAt': '首次信任',
|
||||
'knownHosts.certs.detail.lastSeen': '最近连接',
|
||||
'knownHosts.certs.revokeConfirm.title': '吊销 {endpoint} 的证书信任?',
|
||||
'knownHosts.certs.revokeConfirm.desc': '下次连接该服务器时将重新要求验证其 TLS 证书指纹。',
|
||||
'knownHosts.certs.clearAllConfirm.title': '清空所有已信任的远程桌面证书?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': '将吊销本设备上全部 {count} 条已固定的 RDP/VNC 证书信任记录。',
|
||||
'knownHosts.certs.toast.revoked': '已吊销证书信任',
|
||||
'knownHosts.certs.toast.clearedAll': '已清空 {count} 条远程桌面证书',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': '测试 RDP',
|
||||
'hostDetails.connectionTest.vnc': '测试 VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': '网络延迟 (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': '协议',
|
||||
'hostDetails.connectionTest.probe.security': '协商安全模式',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB 版本',
|
||||
'hostDetails.connectionTest.probe.securityTypes': '支持的安全类型',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 指纹',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': '已信任',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': '首次见到',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': '指纹已变更',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': '信任此指纹',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': '已信任该证书指纹',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': '录制会话',
|
||||
'remoteDesktop.toolbar.stopRecording': '停止录制',
|
||||
'remoteDesktop.toolbar.recording': '录制中',
|
||||
'remoteDesktop.toolbar.askAi': '问 AI',
|
||||
'remoteDesktop.toolbar.askAiFull': '截全屏问 AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': '框选区域问 AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': '允许 AI 读取屏幕',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': '已禁止 AI 读取当前会话屏幕',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI 正在查看画面',
|
||||
'remoteDesktop.clipboard.dropTitle': '拖放文件以发送到远程剪贴板 (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': '松手后,在远程桌面中按 Ctrl+V 即可粘贴',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} 个文件',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': '只读模式下无法拖放文件',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': '该主机未启用剪贴板文件传输',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'RDP 剪贴板不支持直接发送文件夹,请改用 SFTP 或压缩为 .zip 后发送。',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} 个文件 · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': '选择本地文件发送...',
|
||||
'remoteDesktop.clipboard.uploading': '正在通过剪贴板发送',
|
||||
'remoteDesktop.clipboard.downloading': '正在通过剪贴板接收',
|
||||
'remoteDesktop.clipboard.transferCompleted': '剪贴板文件传输完成',
|
||||
'remoteDesktop.clipboard.transferFailed': '剪贴板文件传输失败',
|
||||
'remoteDesktop.recording.started': '已开始录制会话',
|
||||
'remoteDesktop.recording.saved': '会话录屏已保存到连接日志',
|
||||
'remoteDesktop.recording.failed': '会话录制失败',
|
||||
'remoteDesktop.recording.unsupported': '当前环境不支持会话录制',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': '下载 .webm',
|
||||
'logView.recording.delete': '删除录屏',
|
||||
'logView.recording.loading': '正在加载会话录屏...',
|
||||
'logView.recording.withAudio': '含音频',
|
||||
'logView.recording.missingTitle': '录屏文件已不在磁盘上',
|
||||
'logView.recording.missingDesc': '该 .webm 文件已被删除、因保留策略自动清理或被移出录屏目录。',
|
||||
'logView.recording.playbackErrorTitle': '无法播放录屏',
|
||||
'logView.recording.playbackErrorDesc': '视频文件可能不完整,或内置播放器不支持该编码格式。',
|
||||
'logView.recording.exportSuccess': '已导出录屏文件',
|
||||
'logView.recording.exportFailed': '导出录屏失败',
|
||||
'logView.recording.deleted': '已删除录屏',
|
||||
'logView.recording.deleteFailed': '删除录屏失败',
|
||||
'logView.recording.deleteConfirmTitle': '删除这条会话录屏?',
|
||||
'logView.recording.deleteConfirmDesc': '磁盘上的 .webm 视频文件将被永久删除,连接日志记录本身会保留。',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': '此次远程桌面会话未录制视频',
|
||||
'logView.remoteDesktop.host': '主机',
|
||||
'logView.remoteDesktop.protocol': '协议',
|
||||
'logView.remoteDesktop.user': '用户名',
|
||||
'logView.remoteDesktop.started': '开始时间',
|
||||
'logView.remoteDesktop.ended': '结束时间',
|
||||
'logView.remoteDesktop.duration': '持续时长',
|
||||
'logView.remoteDesktop.recordingTip': '点击远程桌面工具栏的录制按钮,或在「设置 → 系统」中开启自动录制,即可在此回放 .webm 录屏。',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': '远程桌面录屏',
|
||||
'settings.remoteDesktopRecordings.autoRecord': '自动录制远程桌面会话',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'RDP/VNC 会话连接成功后自动开始录制(默认关闭以节省磁盘空间)。',
|
||||
'settings.remoteDesktopRecordings.fps': '录制帧率',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': '帧率越高画面越流畅,但会占用更多 CPU 和磁盘空间。',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': '包含 RDP 音频',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': '在可用时将远程桌面音频合并录制到 .webm 视频中。',
|
||||
'settings.remoteDesktopRecordings.maxStorage': '最大存储空间上限',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': '总占用超出上限时,自动优先清理最早的未收藏会话录屏。',
|
||||
'settings.remoteDesktopRecordings.retentionDays': '录屏保留天数',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': '自动删除超过保留期的未收藏会话录屏。',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} 天',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': '不限制',
|
||||
'settings.remoteDesktopRecordings.storageUsage': '本地录屏存储占用',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} 个文件 · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': '正在计算磁盘占用...',
|
||||
'settings.remoteDesktopRecordings.refresh': '刷新存储统计',
|
||||
'settings.remoteDesktopRecordings.openFolder': '打开文件夹',
|
||||
'settings.remoteDesktopRecordings.clearAll': '清空全部录屏',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '清空全部远程桌面录屏?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
|
||||
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
|
||||
|
||||
};
|
||||
@@ -617,8 +617,8 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序號>',
|
||||
'ai.chat.rebindDone': '聊天「{title}」已重新綁定到此面板。',
|
||||
'ai.chat.rebindUnavailable': '目前面板範圍內沒有可用的重新綁定目標。',
|
||||
'ai.chat.managerScopeTab': '目前',
|
||||
'ai.chat.managerAllChatsTab': '全部',
|
||||
'ai.chat.managerScopeTab': '目前會話',
|
||||
'ai.chat.managerAllChatsTab': '全部會話',
|
||||
'ai.chat.managerSearchPlaceholder': '搜尋會話標題…',
|
||||
'ai.chat.managerFilterAllAgents': '全部 Agent',
|
||||
'ai.chat.managerMoreActions': '更多操作',
|
||||
@@ -721,6 +721,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次數',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控執行的最大工具呼叫迴圈次數。外部 Agent 可能有自己的內部迭代限制,以其為準。',
|
||||
'ai.safety.toolOutputMaxChars': '內建 AI 工具輸出上限',
|
||||
'ai.safety.toolOutputMaxChars.description': '內建 AI 單次工具呼叫(例如終端機指令或 SFTP 讀取)直接傳回的最大字元數,超出時會截斷並將完整輸出儲存為可讀取的控制碼(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字元',
|
||||
'ai.safety.blocklist': '指令黑名單',
|
||||
'ai.safety.blocklist.description': '用於攔截透過 Netcatty 執行的危險指令的正規表示式。',
|
||||
'ai.safety.blocklist.placeholder': '正規表示式...',
|
||||
@@ -864,4 +867,21 @@ export const zhTWAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "設定已在其他視窗變更,目前草稿已保留。請取消並重新開啟以載入已儲存的設定。",
|
||||
"ai.toolSettings.retry": "重試",
|
||||
"ai.toolSettings.applyingHttp": "正在套用 HTTP 設定…",
|
||||
"ai.vision.quickPrompt.explainError": "解釋目前錯誤",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "診斷介面問題",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "總結畫面內容",
|
||||
"ai.vision.unsupportedModelWarning": "目前模型({model})不支援圖片輸入,切換至支援視覺的模型即可看圖讀屏。",
|
||||
"ai.vision.switchModel": "切換模型",
|
||||
"ai.vision.modelSupportsVision": "支援圖片輸入",
|
||||
"ai.vision.snip.hint": "拖曳框選區域 · 按 Esc 取消",
|
||||
"ai.vision.snip.cancel": "取消框選",
|
||||
"ai.vision.snip.ariaLabel": "框選遠端桌面畫面區域",
|
||||
"ai.vision.privacyBlocked": "目前工作階段已禁止 AI 讀屏。",
|
||||
"ai.vision.viewingScreen": "AI 正在檢視畫面",
|
||||
"ai.vision.askAi": "問 AI",
|
||||
"ai.vision.captureFullAndAsk": "一鍵截圖問 AI",
|
||||
"ai.vision.snipRegionAndAsk": "框選區域問 AI",
|
||||
"ai.vision.openAiChat": "開啟 AI 助手",
|
||||
"ai.vision.privacyLockOn": "已禁止 AI 讀屏",
|
||||
"ai.vision.privacyLockOff": "允許 AI 讀屏",
|
||||
};
|
||||
@@ -482,7 +482,7 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': '深色主題',
|
||||
'settings.appearance.customCss': '自訂 CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'使用自訂 CSS 個人化介面,修改會立即生效。選取的頂部分頁(`.top-tab[data-active="true"]`)會讀取 `--top-tab-active-bg`、`--top-tab-active-fg` 和 `--top-tab-active-border`。不設定則維持目前外觀。',
|
||||
'使用自訂 CSS 個人化介面,修改會立即生效。',
|
||||
'settings.appearance.customCss.help.ariaLabel': '自訂 CSS 說明',
|
||||
'settings.appearance.customCss.help.title': '自訂 CSS 說明',
|
||||
'settings.appearance.customCss.help.body': `主要 UI 區塊都公開了 \`data-section\` 屬性,供你用 CSS 定位。編輯後會立即生效。
|
||||
@@ -1043,6 +1043,12 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'sftp.extract.extracting': '正在解壓 {fileName}...',
|
||||
'sftp.extract.success': '已解壓 {fileName}',
|
||||
'sftp.extract.error': '解壓 {fileName} 失敗:{error}',
|
||||
'sftp.packedDownload.receiving': '正在接收封裝資料…',
|
||||
'sftp.packedDownload.extracting': '正在還原檔案…',
|
||||
'sftp.packedDownload.fallback': '目前無法打包下載,已改為逐檔下載。',
|
||||
'sftp.packedDownload.selection': '已選取 {count} 個項目',
|
||||
'sftp.packedDownload.conflict': '目的地已有同名項目,要選擇其他儲存位置嗎?',
|
||||
|
||||
'sftp.archive.action': '壓縮…',
|
||||
'sftp.archive.title': '壓縮檔案',
|
||||
'sftp.archive.description': '將 {count} 個選取項目打包成伺服器上的壓縮檔。',
|
||||
@@ -1161,6 +1167,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'sftp.encoding.auto': '自動',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': '後退',
|
||||
'sftp.goForward': '前進',
|
||||
'sftp.goHome': '返回主目錄',
|
||||
'sftp.goRoot': '回到根目錄',
|
||||
'sftp.folderName': '資料夾名稱',
|
||||
|
||||
@@ -101,4 +101,16 @@ export const zhTWMonitorMessages = {
|
||||
"monitor.status.disconnected": "已中斷",
|
||||
"monitor.status.stale": "讀數過期",
|
||||
"monitor.status.missing": "主機已刪除",
|
||||
"monitor.status.online": "線上",
|
||||
"monitor.status.offline": "離線",
|
||||
"monitor.checkNow": "立即檢測",
|
||||
"monitor.openRemoteDesktop": "開啟 {protocol}",
|
||||
"monitor.latencyTrend": "延遲趨勢",
|
||||
"monitor.bannerVerified": "協定已驗證",
|
||||
"monitor.bannerUnverified": "連接埠已開啟(未驗證協定)",
|
||||
"monitor.companionDesktops": "伴生遠端桌面服務",
|
||||
"monitor.reachabilityOnly": "僅線上與延遲探測",
|
||||
"monitor.viaSsh": "經由 SSH",
|
||||
"monitor.direct": "直連",
|
||||
"monitor.rttStats": "最小 / 平均 / 最大",
|
||||
};
|
||||
@@ -12,6 +12,10 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.hidden': '顯示隱藏目錄',
|
||||
'terminal.directory.refresh': '重新整理',
|
||||
'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
|
||||
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
|
||||
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
|
||||
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
|
||||
'terminal.directory.readFailed': '無法讀取此目錄,請重新整理後重試。',
|
||||
'terminal.directory.changeFailed': '未能確認目錄切換,請重新整理後重試。',
|
||||
@@ -95,6 +99,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '複製檔案路徑',
|
||||
'sftp.context.insertPathToTerminal': '插入路徑到終端機',
|
||||
'sftp.context.cdInTerminal': '在終端機中開啟 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '終端機游標位於未閉合的引號或跳脫字元內,無法安全插入路徑',
|
||||
'sftp.context.openWith': '開啟方式...',
|
||||
'sftp.context.edit': '編輯',
|
||||
'sftp.opener.title': '開啟方式',
|
||||
@@ -215,6 +222,17 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.sftp.compressedUpload.enable': '啟用資料夾壓縮',
|
||||
'settings.sftp.compressedUpload.enableDesc': '自動使用 tar 壓縮資料夾後再傳輸。需要伺服器支援 tar 指令,不支援時自動改用一般傳輸。',
|
||||
|
||||
'settings.sftp.packedDownload': '打包下載',
|
||||
'settings.sftp.packedDownload.enable': '下載資料夾或多個項目時打包',
|
||||
'settings.sftp.packedDownload.enableDesc': '一次傳回所選內容,並在本機自動還原原本的資料夾結構。若伺服器不支援打包,會自動逐檔下載。',
|
||||
'settings.sftp.downloadLocation': '下載位置',
|
||||
'settings.sftp.downloadLocation.directory': '預設下載資料夾',
|
||||
'settings.sftp.downloadLocation.directoryDesc': '下載 SFTP 檔案時,儲存對話框預設開啟此資料夾。未設定或資料夾已不存在時,使用系統「下載」資料夾。',
|
||||
'settings.sftp.downloadLocation.systemDefault': '系統「下載」資料夾',
|
||||
'settings.sftp.downloadLocation.browse': '瀏覽…',
|
||||
'settings.sftp.downloadLocation.reset': '恢復為系統「下載」資料夾',
|
||||
'settings.sftp.downloadLocation.select': '選擇預設下載資料夾',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': '跳過未改檔案',
|
||||
'settings.sftp.skipUnchanged.enableDesc': '當目標檔案的大小與修改時間已與來源一致時跳過傳輸(類似 rsync)。替換到暫存路徑時自動停用。',
|
||||
|
||||
@@ -457,7 +475,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.terminal.connection.defaultProxy.desc': '主機沒有單獨設定、也沒有從群組繼承代理時使用的已儲存代理。選擇「無」則直接連線。',
|
||||
'settings.terminal.connection.defaultProxy.none': '無',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled': 'SSH 斷線後自動重連',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': '開啟後,已連上的 SSH 工作階段意外斷開時會每 5 秒嘗試重新連線,直到關閉分頁或連線恢復。',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': '開啟後,SSH 工作階段意外斷開時會按設定間隔嘗試重新連線,直到關閉分頁或連線恢復。',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'SSH 重連間隔(秒)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': '自動重連嘗試之間的等待時間:5–3600 秒,預設 5 秒。修改從下次安排重試時生效,不改變已開始的等待。',
|
||||
'settings.terminal.connection.keepaliveInterval': '工作階段保持間隔',
|
||||
'settings.terminal.connection.keepaliveInterval.desc': '向伺服器傳送 SSH 保活資料包的頻率(秒)。設為 0 表示全域停用——單個主機可在自己的設定裡覆蓋此值。',
|
||||
'settings.terminal.connection.keepaliveCountMax': '最大無回應保活次數',
|
||||
@@ -582,6 +602,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': '關閉分頁',
|
||||
'settings.shortcuts.binding.close-session': '關閉工作階段窗格',
|
||||
'settings.shortcuts.binding.new-tab': '新增本機分頁',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': '重新開啟關閉的分頁',
|
||||
'settings.shortcuts.binding.copy': '從終端複製',
|
||||
'settings.shortcuts.binding.paste': '貼上到終端',
|
||||
'settings.shortcuts.binding.paste-selection': '將選區貼上到終端',
|
||||
@@ -771,6 +792,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
|
||||
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
|
||||
'tabs.closeOthers': '關閉其他分頁',
|
||||
'tabs.closeToLeft': '關閉左側分頁',
|
||||
'tabs.closeToRight': '關閉右側分頁',
|
||||
|
||||
@@ -109,6 +109,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': '選擇協定',
|
||||
'protocolSelect.rememberDefault': '記住為預設連線(下次不再詢問)',
|
||||
'protocolSelect.port': '埠:',
|
||||
// Host Details
|
||||
'hostDetails.title.details': '主機詳情',
|
||||
@@ -379,7 +380,22 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': '選擇連線後如何傳送多行啟動指令。',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': '逐行傳送',
|
||||
'hostDetails.startupCommand.runMode.paste': '一次性傳送',
|
||||
'hostDetails.otherProtocols': '其他協定',
|
||||
'hostDetails.otherProtocols': '附加協定',
|
||||
'hostDetails.otherProtocolsHint': '為目前 SSH 主機掛載輔助連線方式,不影響預設連線',
|
||||
'hostDetails.protocol.defaultHint': '雙擊預設使用 {protocol}',
|
||||
'hostDetails.protocol.secondaryHint': '已作為附加協定啟用',
|
||||
'hostDetails.protocol.setDefault': '設為預設',
|
||||
'hostDetails.protocol.remove': '移除',
|
||||
'hostDetails.protocol.doubleClick': '雙擊連線',
|
||||
'hostDetails.protocol.connectOptionDefault': '預設 {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': '每次詢問',
|
||||
'hostDetails.protocol.alsoEnable': '同時啟用',
|
||||
'hostDetails.protocol.removeProtocol': '移除 {protocol}',
|
||||
'hostDetails.protocol.addProtocol': '新增 {protocol}',
|
||||
'hostDetails.section.connectBehavior': '連線行為',
|
||||
'hostDetails.protocol.notEnabledDesc': '目前主機尚未啟用 {protocol} 協定。',
|
||||
'hostDetails.protocol.addSecondary': '新增 {protocol}(保留 {defaultProtocol} 預設)',
|
||||
'hostDetails.protocol.switchOnly': '僅使用 {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': '埠',
|
||||
'hostDetails.telnet.credentials': '憑證',
|
||||
@@ -408,6 +424,8 @@ export const zhTWVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': '啟動 {command}',
|
||||
'localShell.field.startDir': '啟動目錄',
|
||||
'localShell.field.startDirPlaceholder': '繼承全域起始目錄(未設定時為主目錄)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Shell 啟動後執行的指令(例如:npm run dev)',
|
||||
'localShell.field.startupCommandDesc': '本地 Shell 在啟動目錄開啟後自動執行該指令。',
|
||||
'localShell.saveAndConnect': '儲存並開啟',
|
||||
|
||||
'hostDetails.plugin.title': '外掛程式連線',
|
||||
@@ -1053,4 +1071,224 @@ export const zhTWVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '本次匯入還包含 {count} 個項目。',
|
||||
'vault.import.plugins.moreDiagnostics': '預覽中省略了另外 {count} 則診斷資訊。',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': '新增 RDP 主機',
|
||||
'vault.hosts.newVncHost': '新增 VNC 主機',
|
||||
'vault.hosts.connectRdp': '連線 RDP',
|
||||
'vault.hosts.connectSsh': '連線 SSH',
|
||||
'vault.hosts.connectVnc': '連線 VNC',
|
||||
'vault.hosts.openInSystemRdp': '在系統 RDP 用戶端中開啟',
|
||||
'vault.hosts.openInSystemVnc': '在系統螢幕共享中開啟',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'JumpServer RDP 開啟方式',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': '選擇透過 JumpServer jms:// 啟動 Windows RDP 工作階段時使用 Netcatty 內建用戶端或系統 RDP 用戶端。',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': '內建用戶端',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': '系統 RDP 用戶端',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': '匯入單一或多個 Microsoft / JumpServer .rdp 檔案。',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm、CSV 與 .rdp 匯入皆支援 RDP 與 VNC 主機。',
|
||||
'keychain.identity.domain': '網域 (RDP,選填)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP 或 AD 網域',
|
||||
'quickConnect.rdp.domain': '網域(選填)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP 或留空使用本機帳戶',
|
||||
'quickConnect.vnc.optionalUsername': '使用者名稱(選填,用於 Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': '多數 VNC 伺服器僅需密碼驗證。',
|
||||
'quickConnect.vnc.passwordHint': '若 VNC 伺服器不需密碼,可留空直接連線。',
|
||||
'quickConnect.vnc.displayHelper': '顯示器 {display}',
|
||||
'hostDetails.protocol.label': '通訊協定',
|
||||
'hostDetails.rdp.portLabel': 'RDP 連接埠',
|
||||
'hostDetails.vnc.portLabel': 'VNC 連接埠',
|
||||
'hostDetails.vnc.displayHint': '顯示器 {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 或 :0',
|
||||
'hostDetails.rdp.domain': '網域(選填)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP(選填)',
|
||||
'hostDetails.rdp.domainLabel': '網域',
|
||||
'hostDetails.rdp.usernamePlaceholder': '使用者名稱、DOMAIN\\user 或 JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': '使用者名稱(Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': '選填。標準 VNC 伺服器僅使用密碼驗證。',
|
||||
'hostDetails.vnc.usernamePlaceholder': '使用者名稱(選填)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': '遠端桌面顯示與選項',
|
||||
'hostDetails.rdp.resolutionMode': '解析度模式',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': '動態自適應',
|
||||
'hostDetails.rdp.resolutionMode.fit': '符合視窗',
|
||||
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
|
||||
'hostDetails.rdp.width': '寬度',
|
||||
'hostDetails.rdp.height': '高度',
|
||||
'hostDetails.rdp.colorDepth': '色彩深度',
|
||||
'hostDetails.rdp.audio': '音訊輸出',
|
||||
'hostDetails.rdp.audioDesc': '在本機播放遠端桌面音效',
|
||||
'hostDetails.rdp.clipboard': '剪貼簿同步',
|
||||
'hostDetails.rdp.clipboardDesc': '與遠端桌面共用文字與圖片',
|
||||
'hostDetails.rdp.clipboardFiles': '剪貼簿檔案傳輸',
|
||||
'hostDetails.rdp.clipboardFilesDesc': '允許透過剪貼簿複製與拖曳傳輸檔案',
|
||||
'hostDetails.rdp.securityMode': '安全性模式',
|
||||
'hostDetails.rdp.securityMode.auto': '自動',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': '標準 RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': '忽略憑證錯誤',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': '略過 TLS 憑證信任提示(不建議)',
|
||||
'hostDetails.rdp.advanced': '進階 RDP 選項',
|
||||
'hostDetails.rdp.loadBalanceInfo': '負載平衡資訊 (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': '啟動程式 (Alternate Shell)',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': '選填的啟動程式路徑',
|
||||
'hostDetails.rdp.shellWorkingDir': '工作目錄',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': '選填的啟動工作目錄',
|
||||
'hostDetails.vnc.scalingMode': '縮放模式',
|
||||
'hostDetails.vnc.scalingMode.fit': '符合視窗',
|
||||
'hostDetails.vnc.scalingMode.actual': '原始比例 (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': '延展填滿',
|
||||
'hostDetails.vnc.scalingMode.dynamic': '動態自適應',
|
||||
'hostDetails.vnc.quality': '畫質等級',
|
||||
'hostDetails.vnc.compression': '壓縮等級',
|
||||
'hostDetails.vnc.viewOnly': '唯讀模式',
|
||||
'hostDetails.vnc.viewOnlyDesc': '停用傳送滑鼠與鍵盤輸入',
|
||||
'hostDetails.vnc.sharedSession': '共用工作階段',
|
||||
'hostDetails.vnc.sharedSessionDesc': '連線時保持其他 VNC 用戶端不斷線',
|
||||
'hostDetails.vnc.clipboard': '剪貼簿同步',
|
||||
'hostDetails.vnc.clipboardDesc': '與遠端桌面同步 UTF-8 剪貼簿文字',
|
||||
'hostDetails.vnc.showRemoteCursor': '顯示遠端游標',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': '呈現伺服器提供的游標形狀',
|
||||
'hostDetails.companion.addVnc': '新增 VNC',
|
||||
'hostDetails.companion.addRdp': '新增 RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': '透過此主機 SSH 通道連線',
|
||||
'hostDetails.companion.tunnelViaSshDesc': '自動經由此主機的 SSH 連線轉發連接埠',
|
||||
'hostDetails.companion.tunnelTargetHost': '遠端目標位址',
|
||||
'hostDetails.companion.credentialsSource': '憑證來源',
|
||||
'hostDetails.companion.credentials.host': '沿用主機 SSH 憑證',
|
||||
'hostDetails.companion.credentials.manual': '獨立使用者名稱 / 密碼',
|
||||
'hostDetails.companion.credentials.manualHint': '儲存主機時自動加密存入鑰匙圈',
|
||||
'hostDetails.companion.credentials.identity': '鑰匙圈身分',
|
||||
'hostDetails.companion.credentials.ask': '每次連線時詢問',
|
||||
'hostDetails.companion.identityPlaceholder': '選擇已儲存的身分',
|
||||
'hostDetails.companion.saveAsIdentity': '儲存為身分',
|
||||
'hostDetails.companion.saveIdentityAction': '建立並選擇身分',
|
||||
'hostDetails.companion.identityLabelPlaceholder': '身分名稱(如 Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': '已儲存並選取該身分。',
|
||||
'hostDetails.companion.setDefaultRdp': '預設使用 RDP 連線',
|
||||
'hostDetails.companion.setDefaultVnc': '預設使用 VNC 連線',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH 主機金鑰',
|
||||
'knownHosts.tabs.remoteDesktopCerts': '遠端桌面憑證',
|
||||
'knownHosts.certs.clearAll': '全部清除',
|
||||
'knownHosts.certs.expired': '已過期',
|
||||
'knownHosts.certs.expiredNotice': '此憑證已超過有效期限。',
|
||||
'knownHosts.certs.copied': '已複製 SHA-256 指紋',
|
||||
'knownHosts.certs.action.inspect': '檢視憑證詳情',
|
||||
'knownHosts.certs.action.copyFingerprint': '複製 SHA-256',
|
||||
'knownHosts.certs.action.revoke': '撤銷信任',
|
||||
'knownHosts.certs.empty.title': '尚無已信任的遠端桌面憑證',
|
||||
'knownHosts.certs.empty.desc': '連線至 RDP 或 VeNCrypt VNC 主機並選擇信任的 TLS 憑證將顯示於此處。',
|
||||
'knownHosts.certs.empty.searchTitle': '找不到符合的憑證',
|
||||
'knownHosts.certs.empty.searchDesc': '請嘗試搜尋其他主機名稱、連接埠、通訊協定或 SHA-256 指紋。',
|
||||
'knownHosts.certs.detail.subtitle': '本裝置已固定信任的 TLS 憑證(TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 指紋',
|
||||
'knownHosts.certs.detail.subject': '主體 (Subject)',
|
||||
'knownHosts.certs.detail.issuer': '簽發者 (Issuer)',
|
||||
'knownHosts.certs.detail.validFrom': '生效時間',
|
||||
'knownHosts.certs.detail.validTo': '到期時間',
|
||||
'knownHosts.certs.detail.trustedAt': '首次信任',
|
||||
'knownHosts.certs.detail.lastSeen': '最近連線',
|
||||
'knownHosts.certs.revokeConfirm.title': '要撤銷 {endpoint} 的憑證信任嗎?',
|
||||
'knownHosts.certs.revokeConfirm.desc': '下次連線至此伺服器時將重新要求驗證其 TLS 憑證指紋。',
|
||||
'knownHosts.certs.clearAllConfirm.title': '要清除所有已信任的遠端桌面憑證嗎?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': '這將撤銷本裝置上全部 {count} 筆已固定的 RDP/VNC 憑證信任紀錄。',
|
||||
'knownHosts.certs.toast.revoked': '已撤銷憑證信任',
|
||||
'knownHosts.certs.toast.clearedAll': '已清除 {count} 筆遠端桌面憑證',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': '測試 RDP',
|
||||
'hostDetails.connectionTest.vnc': '測試 VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': '網路延遲 (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': '通訊協定',
|
||||
'hostDetails.connectionTest.probe.security': '協商安全模式',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB 版本',
|
||||
'hostDetails.connectionTest.probe.securityTypes': '支援的安全類型',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 指紋',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': '已信任',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': '首次見到',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': '指紋已變更',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': '信任此指紋',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': '已信任此憑證指紋',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': '錄製工作階段',
|
||||
'remoteDesktop.toolbar.stopRecording': '停止錄製',
|
||||
'remoteDesktop.toolbar.recording': '錄製中',
|
||||
'remoteDesktop.toolbar.askAi': '詢問 AI',
|
||||
'remoteDesktop.toolbar.askAiFull': '擷取全螢幕詢問 AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': '框選區域詢問 AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': '允許 AI 讀取畫面',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': '已禁止 AI 讀取此工作階段畫面',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI 正在檢視畫面',
|
||||
'remoteDesktop.clipboard.dropTitle': '拖放檔案以傳送到遠端剪貼簿 (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': '放開後,在遠端桌面中按 Ctrl+V 即可貼上',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} 個檔案',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': '唯讀模式下無法拖放檔案',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': '此主機未啟用剪貼簿檔案傳輸',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'RDP 剪貼簿不支援直接傳送資料夾,請改用 SFTP 或壓縮為 .zip 後再傳送。',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} 個檔案 · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': '選擇本機檔案傳送...',
|
||||
'remoteDesktop.clipboard.uploading': '正在透過剪貼簿傳送',
|
||||
'remoteDesktop.clipboard.downloading': '正在透過剪貼簿接收',
|
||||
'remoteDesktop.clipboard.transferCompleted': '剪貼簿檔案傳輸完成',
|
||||
'remoteDesktop.clipboard.transferFailed': '剪貼簿檔案傳輸失敗',
|
||||
'remoteDesktop.recording.started': '已開始錄製工作階段',
|
||||
'remoteDesktop.recording.saved': '工作階段錄影已儲存至連線日誌',
|
||||
'remoteDesktop.recording.failed': '工作階段錄製失敗',
|
||||
'remoteDesktop.recording.unsupported': '目前環境不支援工作階段錄製',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': '下載 .webm',
|
||||
'logView.recording.delete': '刪除錄影',
|
||||
'logView.recording.loading': '正在載入工作階段錄影...',
|
||||
'logView.recording.withAudio': '含音訊',
|
||||
'logView.recording.missingTitle': '錄影檔案已不在磁碟上',
|
||||
'logView.recording.missingDesc': '此 .webm 檔案已被刪除、因保留設定自動清理或移出錄影資料夾。',
|
||||
'logView.recording.playbackErrorTitle': '無法播放錄影',
|
||||
'logView.recording.playbackErrorDesc': '影片檔案可能不完整,或內建播放器不支援此編碼格式。',
|
||||
'logView.recording.exportSuccess': '已匯出錄影檔案',
|
||||
'logView.recording.exportFailed': '匯出錄影失敗',
|
||||
'logView.recording.deleted': '已刪除錄影',
|
||||
'logView.recording.deleteFailed': '刪除錄影失敗',
|
||||
'logView.recording.deleteConfirmTitle': '要刪除此工作階段錄影嗎?',
|
||||
'logView.recording.deleteConfirmDesc': '磁碟上的 .webm 影片檔案將被永久刪除,連線日誌紀錄本身會保留。',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': '此遠端桌面工作階段未錄製影片',
|
||||
'logView.remoteDesktop.host': '主機',
|
||||
'logView.remoteDesktop.protocol': '通訊協定',
|
||||
'logView.remoteDesktop.user': '使用者名稱',
|
||||
'logView.remoteDesktop.started': '開始時間',
|
||||
'logView.remoteDesktop.ended': '結束時間',
|
||||
'logView.remoteDesktop.duration': '持續時間',
|
||||
'logView.remoteDesktop.recordingTip': '點擊遠端桌面工具列的錄製按鈕,或在「設定 → 系統」中開啟自動錄製,即可在此重播 .webm 錄影。',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': '遠端桌面錄影',
|
||||
'settings.remoteDesktopRecordings.autoRecord': '自動錄製遠端桌面工作階段',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'RDP/VNC 工作階段連線成功後自動開始錄製(預設關閉以節省磁碟空間)。',
|
||||
'settings.remoteDesktopRecordings.fps': '錄製影格率',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': '影格率越高畫面越流暢,但會佔用較多 CPU 與磁碟空間。',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': '包含 RDP 音訊',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': '在可用時將遠端桌面音訊合併錄製至 .webm 影片中。',
|
||||
'settings.remoteDesktopRecordings.maxStorage': '最大儲存空間上限',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': '總使用量超出上限時,自動優先清理最早的未收藏工作階段錄影。',
|
||||
'settings.remoteDesktopRecordings.retentionDays': '錄影保留天數',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': '自動刪除超過保留期限的未收藏工作階段錄影。',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} 天',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': '不限制',
|
||||
'settings.remoteDesktopRecordings.storageUsage': '本機錄影儲存使用量',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} 個檔案 · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': '正在計算磁碟使用量...',
|
||||
'settings.remoteDesktopRecordings.refresh': '重新整理儲存統計',
|
||||
'settings.remoteDesktopRecordings.openFolder': '開啟資料夾',
|
||||
'settings.remoteDesktopRecordings.clearAll': '清除全部錄影',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '要清除全部遠端桌面錄影嗎?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
|
||||
|
||||
};
|
||||
@@ -138,6 +138,52 @@ test('DebouncedBackupMirror flushNow writes the pending payload immediately', ()
|
||||
assert.deepEqual(writes, ['{"gen":1}']);
|
||||
});
|
||||
|
||||
test('DebouncedBackupMirror defers lazy serializer execution until debounce timer or flushNow fires', async () => {
|
||||
const writes: string[] = [];
|
||||
const serialized: number[] = [];
|
||||
const mirror = new DebouncedBackupMirror((json) => writes.push(json), 15);
|
||||
|
||||
mirror.schedule(() => {
|
||||
serialized.push(1);
|
||||
return '{"gen":1}';
|
||||
});
|
||||
mirror.schedule(() => {
|
||||
serialized.push(2);
|
||||
return '{"gen":2}';
|
||||
});
|
||||
// Neither producer runs synchronously during burst scheduling.
|
||||
assert.deepEqual(serialized, []);
|
||||
assert.deepEqual(writes, []);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
// Only the final producer in the burst is invoked when the timer fires.
|
||||
assert.deepEqual(serialized, [2]);
|
||||
assert.deepEqual(writes, ['{"gen":2}']);
|
||||
|
||||
// flushNow invokes only the pending lazy producer immediately; reset discards without calling it.
|
||||
mirror.schedule(() => {
|
||||
serialized.push(3);
|
||||
return '{"gen":3}';
|
||||
});
|
||||
mirror.schedule(() => {
|
||||
serialized.push(4);
|
||||
return '{"gen":4}';
|
||||
});
|
||||
assert.deepEqual(serialized, [2]);
|
||||
mirror.flushNow();
|
||||
assert.deepEqual(serialized, [2, 4]);
|
||||
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
|
||||
|
||||
mirror.schedule(() => {
|
||||
serialized.push(5);
|
||||
return '{"gen":5}';
|
||||
});
|
||||
mirror.reset();
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
assert.deepEqual(serialized, [2, 4]);
|
||||
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
|
||||
});
|
||||
|
||||
test('readLiveSessionsArray treats non-array JSON as empty (corrupt)', () => {
|
||||
assert.deepEqual(readLiveSessionsArray(null), []);
|
||||
assert.deepEqual(readLiveSessionsArray(''), []);
|
||||
|
||||
@@ -119,28 +119,37 @@ export function mergeImportedSessions(current: AISession[], imported: AISession[
|
||||
return Array.from(byId.values()).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
|
||||
}
|
||||
|
||||
export type BackupMirrorInput = string | (() => string);
|
||||
|
||||
/**
|
||||
* Debounced mirror scheduler. One rolling timer per process: the last
|
||||
* mutation batch wins, and the write happens `debounceMs` after the batch
|
||||
* settles (at most once per batch, per the durability spec).
|
||||
* Accepts either a pre-serialized JSON string or a lazy serializer invoked
|
||||
* only when the debounce timer or `flushNow()` actually runs.
|
||||
*/
|
||||
export class DebouncedBackupMirror {
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private pendingJson: string | null = null;
|
||||
private pendingInput: BackupMirrorInput | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly write: (json: string) => void,
|
||||
private readonly debounceMs: number = AI_SESSIONS_BACKUP_DEBOUNCE_MS,
|
||||
) {}
|
||||
|
||||
schedule(json: string) {
|
||||
this.pendingJson = json;
|
||||
private emit(input: BackupMirrorInput) {
|
||||
const json = typeof input === 'function' ? input() : input;
|
||||
this.write(json);
|
||||
}
|
||||
|
||||
schedule(input: BackupMirrorInput) {
|
||||
this.pendingInput = input;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
const json = this.pendingJson;
|
||||
this.pendingJson = null;
|
||||
if (json != null) this.write(json);
|
||||
const pending = this.pendingInput;
|
||||
this.pendingInput = null;
|
||||
if (pending != null) this.emit(pending);
|
||||
}, this.debounceMs);
|
||||
}
|
||||
|
||||
@@ -149,14 +158,14 @@ export class DebouncedBackupMirror {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
const json = this.pendingJson;
|
||||
this.pendingJson = null;
|
||||
if (json != null) this.write(json);
|
||||
const pending = this.pendingInput;
|
||||
this.pendingInput = null;
|
||||
if (pending != null) this.emit(pending);
|
||||
}
|
||||
|
||||
reset() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.pendingJson = null;
|
||||
this.pendingInput = null;
|
||||
}
|
||||
}
|
||||
@@ -847,3 +847,75 @@ test('rewriting the same sessions array skips re-serialization and store writes'
|
||||
__resetIdbPersistenceForTests();
|
||||
}
|
||||
});
|
||||
|
||||
test('writeSessionsForStorage defers backup JSON.stringify during bursts and skips unchanged rewrites when sync is disabled', async (t) => {
|
||||
const {
|
||||
writeSessionsForStorage,
|
||||
flushBackupMirror,
|
||||
__flushIdbWritesForTests,
|
||||
__resetBackupMirrorForTests,
|
||||
__resetIdbPersistenceForTests,
|
||||
} = await import('./aiStateSnapshots');
|
||||
__resetBackupMirrorForTests();
|
||||
__resetIdbPersistenceForTests();
|
||||
const idb = installFakeIndexedDb();
|
||||
const backupWrites: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: {
|
||||
netcatty: {
|
||||
aiSessionsBackupWrite: async (payload: { json: string }) => {
|
||||
backupWrites.push(payload.json);
|
||||
return { ok: true };
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
// Default syncEnabled=false path: pruneSessionsForStorage allocates a new array each call.
|
||||
t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
try {
|
||||
const stringify = t.mock.method(JSON, 'stringify');
|
||||
const a1 = makeSession('chat-a', 1, [{ id: 'm1', role: 'assistant', content: 'chunk 1', timestamp: 1 }]);
|
||||
const b = makeSession('chat-b', 0, []);
|
||||
const a2 = makeSession('chat-a', 2, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2', timestamp: 2 }]);
|
||||
const a3 = makeSession('chat-a', 3, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2+3', timestamp: 3 }]);
|
||||
|
||||
// Streaming persist burst: 3 consecutive writes must perform 0 eager JSON.stringify calls.
|
||||
assert.equal(writeSessionsForStorage([a1, b]), true);
|
||||
assert.equal(writeSessionsForStorage([a2, b]), true);
|
||||
assert.equal(writeSessionsForStorage([a3, b]), true);
|
||||
assert.equal(stringify.mock.callCount(), 0, 'JSON.stringify must not run eagerly on writeSessionsForStorage');
|
||||
assert.equal(backupWrites.length, 0);
|
||||
|
||||
// Flushing the debounced mirror serializes only the latest persisted snapshot once.
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 1);
|
||||
assert.equal(backupWrites.length, 1);
|
||||
const flushed = JSON.parse(backupWrites[0]) as AISession[];
|
||||
assert.equal(flushed.find((s) => s.id === 'chat-a')?.messages[0]?.content, 'chunk 1+2+3');
|
||||
|
||||
// Rewriting unchanged sessions with syncEnabled=false (fresh array from pruneSessionsForStorage)
|
||||
// must NOT schedule a redundant mirror or run JSON.stringify on flush.
|
||||
assert.equal(writeSessionsForStorage([a3, b]), true);
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 1, 'unchanged sessions must not re-schedule mirror when sync is disabled');
|
||||
assert.equal(backupWrites.length, 1);
|
||||
|
||||
// Removing a session still schedules and mirrors the updated set.
|
||||
assert.equal(writeSessionsForStorage([a3], { deletedSessionIds: ['chat-b'] }), true);
|
||||
assert.equal(stringify.mock.callCount(), 1, 'deletion backup serialization is also deferred until flush/debounce');
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 2);
|
||||
assert.equal(backupWrites.length, 2);
|
||||
assert.deepEqual((JSON.parse(backupWrites[1]) as AISession[]).map((s) => s.id), ['chat-a']);
|
||||
|
||||
await __flushIdbWritesForTests();
|
||||
} finally {
|
||||
idb.restore();
|
||||
__resetBackupMirrorForTests();
|
||||
__resetIdbPersistenceForTests();
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow });
|
||||
}
|
||||
});
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import { emitAIStateChanged } from './aiStateEvents';
|
||||
import { peekAgentRuntimeCleanup } from '../../infrastructure/ai/harness/agentRuntimeHandle';
|
||||
import { setReversibleModelPrivacy } from '../../infrastructure/ai/harness/modelSecretRedaction';
|
||||
import { DebouncedBackupMirror, readLiveSessionsArray } from './aiSessionsBackup';
|
||||
import { DebouncedBackupMirror, readLiveSessionsArray, type BackupMirrorInput } from './aiSessionsBackup';
|
||||
import {
|
||||
idbDeleteSessionIds,
|
||||
idbPutMeta,
|
||||
@@ -305,6 +305,7 @@ let idbWriteQueue: Promise<void> = Promise.resolve();
|
||||
/** Test hook: reset diff state between tests. */
|
||||
export function __resetIdbPersistenceForTests() {
|
||||
lastPersistedSessionsById = new Map();
|
||||
lastMirroredSessions = null;
|
||||
idbWriteQueue = Promise.resolve();
|
||||
// Tests swap the fake indexedDB factory between cases; the cached open
|
||||
// handle must not survive the swap.
|
||||
@@ -429,12 +430,13 @@ export function flushBackupMirror() {
|
||||
export function __resetBackupMirrorForTests() {
|
||||
backupMirror.reset();
|
||||
aiSessionsBackupRecoveryPending = false;
|
||||
lastMirroredSessions = null;
|
||||
}
|
||||
|
||||
export function scheduleBackupMirror(json: string) {
|
||||
export function scheduleBackupMirror(input: BackupMirrorInput) {
|
||||
if (aiSessionsBackupRecoveryPending) return;
|
||||
try {
|
||||
backupMirror.schedule(json);
|
||||
backupMirror.schedule(input);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
@@ -503,9 +505,11 @@ export function writeSessionsForStorage(
|
||||
const removedIds = Array.from(prevById.keys()).filter(id => !persistedIds.has(id));
|
||||
lastPersistedSessionsById = new Map(persisted.map(session => [session.id, session]));
|
||||
|
||||
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions !== persisted) {
|
||||
scheduleBackupMirror(JSON.stringify(persisted));
|
||||
lastMirroredSessions = persisted;
|
||||
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions === null) {
|
||||
if (!aiSessionsBackupRecoveryPending) {
|
||||
scheduleBackupMirror(() => JSON.stringify(persisted));
|
||||
lastMirroredSessions = persisted;
|
||||
}
|
||||
}
|
||||
queueIdbSessionSync(changed, removedIds, prevById, persisted);
|
||||
return true;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* and detached terminal popups) shares the same clear semantics.
|
||||
*/
|
||||
|
||||
import { tokenizeShellLike } from "../../domain/shellTokenizer";
|
||||
import { localStorageAdapter } from "../../infrastructure/persistence/localStorageAdapter";
|
||||
import {
|
||||
STORAGE_KEY_COMMAND_HISTORY,
|
||||
@@ -499,55 +500,6 @@ function normalizeArgumentToken(token: string): string {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function tokenizeShellLike(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
|
||||
if (escaped) {
|
||||
current += ch;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
current += ch;
|
||||
}
|
||||
|
||||
tokens.push(current);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute a fuzzy match score. Returns 0 for no match.
|
||||
* Higher score = better match quality.
|
||||
|
||||
@@ -3,10 +3,15 @@ import test from 'node:test';
|
||||
|
||||
import {
|
||||
collectPluginTerminalProviderKinds,
|
||||
createWindowPluginTerminalProviderRegistry,
|
||||
isPluginTerminalProviderKindAvailable,
|
||||
PluginTerminalProviderAvailability,
|
||||
PluginTerminalProviderRegistry,
|
||||
} from './pluginTerminalProviderRegistry.ts';
|
||||
import {
|
||||
_resetSharedPluginRuntimeStatusForTests,
|
||||
getSharedPluginRuntimeStatus,
|
||||
} from './pluginRuntimeStatusCache.ts';
|
||||
|
||||
const session: NetcattyTerminalSessionSnapshot = {
|
||||
sessionId: 'session-1',
|
||||
@@ -430,3 +435,142 @@ test('terminal Provider registry forwards contribution lifecycle invalidation',
|
||||
registry.dispose();
|
||||
assert.equal(disposed, true);
|
||||
});
|
||||
|
||||
test('terminal Provider registry short-circuits cloning, snapshots, and IPC when plugin runtime is disabled, and re-probes on contribution change', async (t) => {
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
let changed: (() => void) | undefined;
|
||||
let available = false;
|
||||
let statusCalls = 0;
|
||||
let listCalls = 0;
|
||||
let lifecycleCalls = 0;
|
||||
const requests: NetcattyTerminalProviderRequest[] = [];
|
||||
const events: NetcattyTerminalSessionEvent[] = [];
|
||||
|
||||
const registry = new PluginTerminalProviderRegistry({
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available } as NetcattyPluginRuntimeStatus;
|
||||
},
|
||||
async listPluginTerminalProviders() {
|
||||
listCalls += 1;
|
||||
return [{
|
||||
pluginId: 'com.example.matcher',
|
||||
pluginVersion: '1.0.0',
|
||||
pluginDisplayName: 'Matcher',
|
||||
provider: {
|
||||
id: 'com.example.matcher.output',
|
||||
label: 'Output matcher',
|
||||
kind: 'terminal.matcher',
|
||||
},
|
||||
}];
|
||||
},
|
||||
async providePluginTerminal(request) {
|
||||
requests.push(request);
|
||||
return [];
|
||||
},
|
||||
async cancelPluginTerminalRequest() { return false; },
|
||||
async publishPluginTerminalSessionEvent(event) {
|
||||
lifecycleCalls += 1;
|
||||
events.push(event);
|
||||
return [];
|
||||
},
|
||||
onPluginContributionsChanged(listener) {
|
||||
changed = listener;
|
||||
return () => {};
|
||||
},
|
||||
});
|
||||
|
||||
const cloneSpy = t.mock.method(globalThis, 'structuredClone');
|
||||
try {
|
||||
// Parallel provider enumerations coalesce onto one runtime status check and make 0 provider IPCs.
|
||||
const [matchers, links] = await Promise.all([
|
||||
registry.listProviders({ kind: 'terminal.matcher' }),
|
||||
registry.listProviders({ kind: 'terminal.link' }),
|
||||
]);
|
||||
assert.deepEqual(matchers, []);
|
||||
assert.deepEqual(links, []);
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(listCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0);
|
||||
|
||||
// Lifecycle events while disabled must not clone, snapshot, or call IPC.
|
||||
await registry.publishSessionEvent({
|
||||
type: 'created',
|
||||
session: { ...session, cwd: '/must-not-be-retained', title: 'Hidden title' },
|
||||
});
|
||||
await registry.publishSessionEvent({
|
||||
type: 'cwdChanged',
|
||||
session: { ...session, cwd: '/also-not-retained' },
|
||||
});
|
||||
await registry.publishSessionEvent({
|
||||
type: 'resized',
|
||||
session: { ...session, cols: 120, rows: 40 },
|
||||
});
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(lifecycleCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0, '0 structuredClone calls when plugin host is disabled');
|
||||
|
||||
// Dev-mode hot-enable: onPluginContributionsChanged invalidates cached status and re-probes.
|
||||
available = true;
|
||||
changed?.();
|
||||
|
||||
// Verify no stale session snapshot was retained while disabled.
|
||||
await registry.request({ kind: 'terminal.completion', operation: 'provide', session });
|
||||
assert.equal(Object.hasOwn(requests[0].session, 'cwd'), false, 'disabled publishSessionEvent must not grow #sessionSnapshots');
|
||||
assert.equal(Object.hasOwn(requests[0].session, 'title'), false);
|
||||
|
||||
const enabledProviders = await registry.listProviders({ kind: 'terminal.matcher' });
|
||||
assert.equal(statusCalls, 2, 'onPluginContributionsChanged invalidates shared runtime status cache');
|
||||
assert.equal(listCalls, 1);
|
||||
assert.equal(enabledProviders.length, 1);
|
||||
|
||||
await registry.publishSessionEvent({ type: 'connected', session: { ...session, cwd: '/live' } });
|
||||
assert.equal(lifecycleCalls, 1);
|
||||
assert.equal(events[0].session.cwd, '/live');
|
||||
} finally {
|
||||
registry.dispose();
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
}
|
||||
});
|
||||
|
||||
test('createWindowPluginTerminalProviderRegistry shares runtime status cache with the window bridge', async (t) => {
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
let statusCalls = 0;
|
||||
let listCalls = 0;
|
||||
let lifecycleCalls = 0;
|
||||
const mockBridge = {
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available: false };
|
||||
},
|
||||
async listPluginTerminalProviders() {
|
||||
listCalls += 1;
|
||||
return [];
|
||||
},
|
||||
async providePluginTerminal() { return []; },
|
||||
async cancelPluginTerminalRequest() { return false; },
|
||||
async publishPluginTerminalSessionEvent() {
|
||||
lifecycleCalls += 1;
|
||||
return [];
|
||||
},
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
// Pre-populate shared runtime status cache (as usePluginContributions does on mount).
|
||||
assert.deepEqual(await getSharedPluginRuntimeStatus(mockBridge), { available: false });
|
||||
assert.equal(statusCalls, 1);
|
||||
|
||||
const cloneSpy = t.mock.method(globalThis, 'structuredClone');
|
||||
const registry = createWindowPluginTerminalProviderRegistry(mockBridge);
|
||||
assert.ok(registry);
|
||||
try {
|
||||
assert.deepEqual(await registry.listProviders({ kind: 'terminal.matcher' }), []);
|
||||
await registry.publishSessionEvent({ type: 'created', session });
|
||||
assert.equal(statusCalls, 1, 'reuses cached runtime status from window bridge without extra IPC');
|
||||
assert.equal(listCalls, 0);
|
||||
assert.equal(lifecycleCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0);
|
||||
} finally {
|
||||
registry.dispose();
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
}
|
||||
});
|
||||
@@ -1,8 +1,14 @@
|
||||
import {
|
||||
getSharedPluginRuntimeStatus,
|
||||
invalidateSharedPluginRuntimeStatus,
|
||||
} from './pluginRuntimeStatusCache';
|
||||
|
||||
export interface PluginTerminalProviderBridge {
|
||||
listPluginTerminalProviders(options: NetcattyTerminalProviderQuery): Promise<ReadonlyArray<NetcattyTerminalProviderContribution>>;
|
||||
providePluginTerminal(request: NetcattyTerminalProviderRequest): Promise<ReadonlyArray<NetcattyTerminalProviderResult>>;
|
||||
cancelPluginTerminalRequest(requestId: string): Promise<boolean>;
|
||||
publishPluginTerminalSessionEvent(event: NetcattyTerminalSessionEvent): Promise<ReadonlyArray<{ pluginId: string; delivered: boolean }>>;
|
||||
getPluginRuntimeStatus?(): Promise<NetcattyPluginRuntimeStatus>;
|
||||
onPluginContributionsChanged?(callback: () => void): () => void;
|
||||
}
|
||||
|
||||
@@ -52,6 +58,7 @@ function mergeLifecycleSessionSnapshot(
|
||||
|
||||
export class PluginTerminalProviderRegistry {
|
||||
readonly #bridge: PluginTerminalProviderBridge;
|
||||
readonly #statusBridge: Pick<NetcattyBridge, 'getPluginRuntimeStatus'>;
|
||||
readonly #activeRequests = new Map<string, string>();
|
||||
readonly #sessionSnapshots = new Map<string, NetcattyTerminalSessionSnapshot>();
|
||||
readonly #providerListeners = new Set<() => void>();
|
||||
@@ -62,11 +69,16 @@ export class PluginTerminalProviderRegistry {
|
||||
#bridgeAvailability: 'unknown' | 'available' | 'unavailable' = 'unknown';
|
||||
#disposed = false;
|
||||
|
||||
constructor(bridge: PluginTerminalProviderBridge) {
|
||||
constructor(
|
||||
bridge: PluginTerminalProviderBridge,
|
||||
statusBridge: Pick<NetcattyBridge, 'getPluginRuntimeStatus'> = bridge,
|
||||
) {
|
||||
this.#bridge = bridge;
|
||||
this.#statusBridge = statusBridge;
|
||||
this.#disposeContributionListener = bridge.onPluginContributionsChanged?.(() => {
|
||||
this.#providerListGeneration += 1;
|
||||
this.#bridgeAvailability = 'unknown';
|
||||
invalidateSharedPluginRuntimeStatus(this.#statusBridge);
|
||||
this.#providerListCache.clear();
|
||||
this.#pendingProviderLists.clear();
|
||||
for (const requestId of this.#activeRequests.values()) {
|
||||
@@ -79,6 +91,33 @@ export class PluginTerminalProviderRegistry {
|
||||
});
|
||||
}
|
||||
|
||||
#isUnavailable(): boolean {
|
||||
return this.#disposed || this.#bridgeAvailability === 'unavailable';
|
||||
}
|
||||
|
||||
async #probeRuntimeStatus(generation: number): Promise<boolean> {
|
||||
try {
|
||||
const status = await getSharedPluginRuntimeStatus(this.#statusBridge);
|
||||
if (this.#disposed) return false;
|
||||
if (generation !== this.#providerListGeneration) {
|
||||
return this.#bridgeAvailability !== 'unavailable';
|
||||
}
|
||||
if (!status.available) {
|
||||
this.#bridgeAvailability = 'unavailable';
|
||||
this.#providerListCache.clear();
|
||||
return false;
|
||||
}
|
||||
this.#bridgeAvailability = 'available';
|
||||
return true;
|
||||
} catch {
|
||||
if (!this.#disposed && generation === this.#providerListGeneration) {
|
||||
this.#bridgeAvailability = 'unavailable';
|
||||
this.#providerListCache.clear();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
onDidChangeProviders(listener: () => void): () => void {
|
||||
if (this.#disposed) return () => {};
|
||||
this.#providerListeners.add(listener);
|
||||
@@ -96,6 +135,16 @@ export class PluginTerminalProviderRegistry {
|
||||
const generation = this.#providerListGeneration;
|
||||
const request = (async () => {
|
||||
try {
|
||||
if (
|
||||
this.#bridgeAvailability === 'unknown'
|
||||
&& typeof this.#statusBridge.getPluginRuntimeStatus === 'function'
|
||||
) {
|
||||
const available = await this.#probeRuntimeStatus(generation);
|
||||
if (!available) return Object.freeze([]);
|
||||
}
|
||||
if (this.#isUnavailable()) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
const providers = freezeValue(await this.#bridge.listPluginTerminalProviders(query));
|
||||
if (generation === this.#providerListGeneration) {
|
||||
if (this.#bridgeAvailability !== 'unavailable') this.#bridgeAvailability = 'available';
|
||||
@@ -206,11 +255,21 @@ export class PluginTerminalProviderRegistry {
|
||||
|
||||
async publishSessionEvent(event: NetcattyTerminalSessionEvent): Promise<void> {
|
||||
if (this.#disposed) return;
|
||||
// Short-circuit BEFORE mergeLifecycleSessionSnapshot so disabled plugin
|
||||
// hosts never run structuredClone/Object.freeze or retain session snapshots.
|
||||
if (this.#bridgeAvailability === 'unavailable') return;
|
||||
if (
|
||||
this.#bridgeAvailability === 'unknown'
|
||||
&& typeof this.#statusBridge.getPluginRuntimeStatus === 'function'
|
||||
) {
|
||||
const available = await this.#probeRuntimeStatus(this.#providerListGeneration);
|
||||
if (!available) return;
|
||||
}
|
||||
if (this.#isUnavailable()) return;
|
||||
const previous = this.#sessionSnapshots.get(event.session.sessionId);
|
||||
const session = mergeLifecycleSessionSnapshot(previous, event);
|
||||
if (event.type === 'disposed') this.#sessionSnapshots.delete(session.sessionId);
|
||||
else this.#sessionSnapshots.set(session.sessionId, session);
|
||||
if (this.#bridgeAvailability === 'unavailable') return;
|
||||
try {
|
||||
await this.#bridge.publishPluginTerminalSessionEvent(freezeValue({ ...event, session }));
|
||||
this.#bridgeAvailability = 'available';
|
||||
@@ -302,10 +361,13 @@ export function createWindowPluginTerminalProviderRegistry(
|
||||
providePluginTerminal: (request) => bridge.providePluginTerminal!(request),
|
||||
cancelPluginTerminalRequest: (requestId) => bridge.cancelPluginTerminalRequest!(requestId),
|
||||
publishPluginTerminalSessionEvent: (event) => bridge.publishPluginTerminalSessionEvent!(event),
|
||||
getPluginRuntimeStatus: bridge.getPluginRuntimeStatus
|
||||
? () => bridge.getPluginRuntimeStatus!()
|
||||
: undefined,
|
||||
onPluginContributionsChanged: bridge.onPluginContributionsChanged
|
||||
? (callback) => bridge.onPluginContributionsChanged!(callback)
|
||||
: undefined,
|
||||
});
|
||||
}, bridge);
|
||||
}
|
||||
|
||||
let windowRegistry: PluginTerminalProviderRegistry | null | undefined;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
@@ -76,3 +77,4 @@ export class PluginViewSessions {
|
||||
dispose() { for (const session of [...this.sessions.values()]) session.dispose(); }
|
||||
}
|
||||
export const pluginViewSessions = new PluginViewSessions();
|
||||
registerLoadedPluginViewSessions(pluginViewSessions);
|
||||
@@ -0,0 +1,18 @@
|
||||
type CloseablePluginViewSessions = {
|
||||
closeView(viewId: string): void;
|
||||
};
|
||||
|
||||
let loadedSessions: CloseablePluginViewSessions | null = null;
|
||||
|
||||
/**
|
||||
* Registers the live PluginViewSessions singleton once the lazy host-drawn
|
||||
* plugin view bundle loads, so startup lifecycle hooks can close views without
|
||||
* statically importing css-tree / @remote-dom/core.
|
||||
*/
|
||||
export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSessions): void {
|
||||
loadedSessions = sessions;
|
||||
}
|
||||
|
||||
export function closePluginViewSessionIfLoaded(viewId: string): void {
|
||||
loadedSessions?.closeView(viewId);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createPromptHostnameSessionSignalController } from './promptHostnameSessionSignalController.ts';
|
||||
|
||||
type Change = readonly [sessionId: string, hostname: string | null];
|
||||
|
||||
const getSession = (sessionId: string) => (
|
||||
sessionId === 'ssh-1'
|
||||
? { protocol: 'ssh' as const, hostname: 'jump.example.com' }
|
||||
: { protocol: 'local' as const, hostname: 'localhost' }
|
||||
);
|
||||
|
||||
function createHarness() {
|
||||
const changes: Change[] = [];
|
||||
const controller = createPromptHostnameSessionSignalController({
|
||||
getSession,
|
||||
onChange: (sessionId, hostname) => changes.push([sessionId, hostname]),
|
||||
});
|
||||
return { changes, controller };
|
||||
}
|
||||
|
||||
test('prompt host controller ignores the initial jumpserver prompt', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# ');
|
||||
assert.deepEqual(changes, []);
|
||||
});
|
||||
|
||||
test('prompt host controller publishes a nested target and de-duplicates it', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
|
||||
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
|
||||
});
|
||||
|
||||
test('prompt host controller clears the override when returning to the jumpserver', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'exit\r\n[root@jump.example.com ~]# ');
|
||||
assert.deepEqual(changes, [
|
||||
['ssh-1', '10.1.64.1'],
|
||||
['ssh-1', null],
|
||||
]);
|
||||
});
|
||||
|
||||
test('prompt host controller detects an identity split across output chunks', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'ssh target\r\n[root@10.1.');
|
||||
controller.handleTerminalOutput('ssh-1', '64.1 ~]# ');
|
||||
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
|
||||
});
|
||||
|
||||
test('prompt host controller ignores ambiguous, sensitive, and local output', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'Password:\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'copied output\n# ');
|
||||
controller.handleTerminalOutput('local-1', '[root@10.1.64.1 ~]# ');
|
||||
assert.deepEqual(changes, []);
|
||||
});
|
||||
|
||||
test('prompt host controller ignores host-like text embedded in copied output', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'see [root@prod] logs\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', '[root@prod] copied output\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'root@prod output\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', '[root@prod] version = 1.2\n# ');
|
||||
assert.deepEqual(changes, []);
|
||||
});
|
||||
|
||||
test('prompt host controller publishes common zsh, Alpine, and macOS root prompt hosts', () => {
|
||||
for (const [prompt, hostname] of [
|
||||
['alice@target-a ~ % ', 'target-a'],
|
||||
['alice@target-b ~ # ', 'target-b'],
|
||||
['target-c:~# ', 'target-c'],
|
||||
['target-d:~ root# ', 'target-d'],
|
||||
]) {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', prompt);
|
||||
assert.deepEqual(changes, [['ssh-1', hostname]]);
|
||||
}
|
||||
});
|
||||
|
||||
test('prompt host controller clears live target host when JumpServer returns to its menu', () => {
|
||||
for (const menuPrompt of ['Opt> ', '[Host]> ', '\x1b[32mOpt> \x1b[0m']) {
|
||||
const { changes, controller } = createHarness();
|
||||
// Initial menu before jumping emits nothing.
|
||||
controller.handleTerminalOutput('ssh-1', `Welcome to JumpServer\r\n${menuPrompt}`);
|
||||
// Jump into target host (including repeated CR+EL redraws).
|
||||
controller.handleTerminalOutput(
|
||||
'ssh-1',
|
||||
'11\r\nLast login: Mon Nov 23 16:01:46 2026\r\n[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\r\n# \r\x1b[K# ',
|
||||
);
|
||||
// Exiting back to JumpServer menu clears the published target hostname.
|
||||
controller.handleTerminalOutput('ssh-1', `exit\r\nlogout\r\nConnection closed.\r\n${menuPrompt}`);
|
||||
// Repeating menu prompt does not emit duplicate null updates.
|
||||
controller.handleTerminalOutput('ssh-1', `\r\n${menuPrompt}`);
|
||||
// Jumping to a second target publishes the new host.
|
||||
controller.handleTerminalOutput('ssh-1', '12\r\n[root@app-prod-02 ~]# ');
|
||||
|
||||
assert.deepEqual(
|
||||
changes,
|
||||
[
|
||||
['ssh-1', 'k8s-10-1-64-1'],
|
||||
['ssh-1', null],
|
||||
['ssh-1', 'app-prod-02'],
|
||||
],
|
||||
JSON.stringify(menuPrompt),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('prompt host controller forgets closed sessions when pruned', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@app-prod-01 ~]# ');
|
||||
controller.forgetSession('ssh-1');
|
||||
controller.handleTerminalOutput('ssh-1', '[root@app-prod-01 ~]# ');
|
||||
assert.deepEqual(changes, [
|
||||
['ssh-1', 'app-prod-01'],
|
||||
['ssh-1', 'app-prod-01'],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { TerminalSession } from '../../domain/models';
|
||||
import {
|
||||
extractTerminalPromptHostname,
|
||||
isJumpServerMenuPrompt,
|
||||
} from '../../domain/terminalPromptSecurity';
|
||||
|
||||
type PromptHostnameSessionSignalOptions = {
|
||||
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol' | 'hostname'> | undefined;
|
||||
onChange: (sessionId: string, hostname: string | null) => void;
|
||||
maxTailChars?: number;
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_TAIL_CHARS = 8_192;
|
||||
|
||||
function normalizedHostname(hostname: string): string {
|
||||
return hostname.trim().toLocaleLowerCase().replace(/\.$/u, '');
|
||||
}
|
||||
|
||||
export function createPromptHostnameSessionSignalController({
|
||||
getSession,
|
||||
onChange,
|
||||
maxTailChars = DEFAULT_MAX_TAIL_CHARS,
|
||||
}: PromptHostnameSessionSignalOptions) {
|
||||
const tails = new Map<string, string>();
|
||||
const baselines = new Map<string, string>();
|
||||
const published = new Map<string, string>();
|
||||
const tailLimit = Math.max(256, maxTailChars);
|
||||
|
||||
const forgetSession = (sessionId: string): void => {
|
||||
tails.delete(sessionId);
|
||||
baselines.delete(sessionId);
|
||||
published.delete(sessionId);
|
||||
};
|
||||
|
||||
return {
|
||||
forgetSession,
|
||||
pruneSessions(validSessionIds: ReadonlySet<string>): void {
|
||||
for (const sessionId of [...tails.keys(), ...baselines.keys(), ...published.keys()]) {
|
||||
if (!validSessionIds.has(sessionId)) {
|
||||
forgetSession(sessionId);
|
||||
}
|
||||
}
|
||||
},
|
||||
handleTerminalOutput(sessionId: string, chunk: string): void {
|
||||
const session = getSession(sessionId);
|
||||
if (!session) {
|
||||
forgetSession(sessionId);
|
||||
return;
|
||||
}
|
||||
if ((session.protocol ?? 'ssh') !== 'ssh') return;
|
||||
|
||||
const combined = `${tails.get(sessionId) ?? ''}${chunk}`;
|
||||
const tail = combined.slice(-tailLimit);
|
||||
tails.set(sessionId, tail);
|
||||
|
||||
const detected = extractTerminalPromptHostname(tail);
|
||||
if (!detected) {
|
||||
if (isJumpServerMenuPrompt(tail) && published.has(sessionId)) {
|
||||
published.delete(sessionId);
|
||||
onChange(sessionId, null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const detectedKey = normalizedHostname(detected);
|
||||
if (!detectedKey) return;
|
||||
|
||||
let baseline = baselines.get(sessionId);
|
||||
if (baseline === undefined) {
|
||||
baseline = normalizedHostname(session.hostname) || detectedKey;
|
||||
baselines.set(sessionId, baseline);
|
||||
}
|
||||
|
||||
if (detectedKey === baseline) {
|
||||
if (!published.has(sessionId)) return;
|
||||
published.delete(sessionId);
|
||||
onChange(sessionId, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (published.get(sessionId) === detectedKey) return;
|
||||
published.set(sessionId, detectedKey);
|
||||
onChange(sessionId, detected);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,17 +11,6 @@ test("non-workspace tab → closeSingleTab with session id", () => {
|
||||
activeTabId: "s1",
|
||||
workspace: null,
|
||||
sessionForTab: baseSession,
|
||||
focusIsInsideTerminal: true,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "closeSingleTab", sessionId: "s1" });
|
||||
});
|
||||
|
||||
test("non-workspace session tab → closeSingleTab even when focus is outside the terminal", () => {
|
||||
const r = resolveCloseIntent({
|
||||
activeTabId: "s1",
|
||||
workspace: null,
|
||||
sessionForTab: { id: "s1" },
|
||||
focusIsInsideTerminal: false,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "closeSingleTab", sessionId: "s1" });
|
||||
});
|
||||
@@ -31,27 +20,15 @@ test("vault/sftp tab → noop", () => {
|
||||
activeTabId: "vault",
|
||||
workspace: null,
|
||||
sessionForTab: null,
|
||||
focusIsInsideTerminal: false,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "noop" });
|
||||
});
|
||||
|
||||
test("workspace + focus in terminal → closeTerminal (side panel no longer intercepts)", () => {
|
||||
test("workspace tab closes the whole workspace even with a focused session", () => {
|
||||
const r = resolveCloseIntent({
|
||||
activeTabId: "w1",
|
||||
workspace: baseWorkspace,
|
||||
sessionForTab: null,
|
||||
focusIsInsideTerminal: true,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "closeTerminal", sessionId: "s1" });
|
||||
});
|
||||
|
||||
test("workspace + focus NOT in terminal → closeWorkspace", () => {
|
||||
const r = resolveCloseIntent({
|
||||
activeTabId: "w1",
|
||||
workspace: baseWorkspace,
|
||||
sessionForTab: null,
|
||||
focusIsInsideTerminal: false,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "closeWorkspace", workspaceId: "w1" });
|
||||
});
|
||||
@@ -61,7 +38,6 @@ test("workspace with no focused session → closeWorkspace", () => {
|
||||
activeTabId: "w1",
|
||||
workspace: { id: "w1", focusedSessionId: undefined },
|
||||
sessionForTab: null,
|
||||
focusIsInsideTerminal: true,
|
||||
});
|
||||
assert.deepEqual(r, { kind: "closeWorkspace", workspaceId: "w1" });
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
export type CloseIntent =
|
||||
| { kind: 'closeTerminal'; sessionId: string }
|
||||
| { kind: 'closeWorkspace'; workspaceId: string }
|
||||
| { kind: 'closeSingleTab'; sessionId: string }
|
||||
| { kind: 'noop' };
|
||||
@@ -8,11 +7,10 @@ export interface ResolveCloseInput {
|
||||
activeTabId: string | null;
|
||||
workspace: { id: string; focusedSessionId?: string } | null;
|
||||
sessionForTab: { id: string } | null;
|
||||
focusIsInsideTerminal: boolean;
|
||||
}
|
||||
|
||||
export function resolveCloseIntent(input: ResolveCloseInput): CloseIntent {
|
||||
const { activeTabId, workspace, sessionForTab, focusIsInsideTerminal } = input;
|
||||
const { activeTabId, workspace, sessionForTab } = input;
|
||||
|
||||
if (!activeTabId) return { kind: 'noop' };
|
||||
|
||||
@@ -25,10 +23,5 @@ export function resolveCloseIntent(input: ResolveCloseInput): CloseIntent {
|
||||
return { kind: 'noop' };
|
||||
}
|
||||
|
||||
const focusedSessionId = workspace.focusedSessionId;
|
||||
if (focusedSessionId && focusIsInsideTerminal) {
|
||||
return { kind: 'closeTerminal', sessionId: focusedSessionId };
|
||||
}
|
||||
|
||||
return { kind: 'closeWorkspace', workspaceId: workspace.id };
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
import type { Host, SerialConfig, TerminalSession } from "../../domain/models";
|
||||
import {
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_PORT,
|
||||
isRemoteDesktopProtocol,
|
||||
sanitizeRdpConfig,
|
||||
sanitizeVncConfig,
|
||||
type RemoteDesktopProtocol,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { classifyLocalShellType } from "../../lib/localShell";
|
||||
|
||||
export interface LocalTerminalOptions {
|
||||
@@ -121,6 +129,30 @@ export const createHostTerminalSession = (
|
||||
};
|
||||
}
|
||||
|
||||
if (isRemoteDesktopProtocol(host.protocol)) {
|
||||
const protocol = host.protocol;
|
||||
const sanitizedRdp = protocol === "rdp" ? sanitizeRdpConfig(host.rdpConfig) : undefined;
|
||||
const sanitizedVnc = protocol === "vnc" ? sanitizeVncConfig(host.vncConfig) : undefined;
|
||||
const defaultPort = protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT;
|
||||
const resolvedPort =
|
||||
(protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port)
|
||||
?? host.port
|
||||
?? defaultPort;
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel: host.label || host.hostname,
|
||||
hostname: host.hostname,
|
||||
username: host.username ?? "",
|
||||
status: "connecting",
|
||||
protocol,
|
||||
port: resolvedPort,
|
||||
...(sanitizedRdp ? { rdpConfig: sanitizedRdp } : {}),
|
||||
...(sanitizedVnc ? { vncConfig: sanitizedVnc } : {}),
|
||||
...(host.ephemeral ? { ephemeralHost: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
@@ -165,6 +197,39 @@ export const createHostTerminalSession = (
|
||||
};
|
||||
};
|
||||
|
||||
export const createRemoteDesktopSession = (
|
||||
sessionId: string,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { workspaceId?: string },
|
||||
): TerminalSession => {
|
||||
const isCompanion = host.protocol !== protocol;
|
||||
const sanitizedRdp = protocol === "rdp" ? sanitizeRdpConfig(host.rdpConfig) : undefined;
|
||||
const sanitizedVnc = protocol === "vnc" ? sanitizeVncConfig(host.vncConfig) : undefined;
|
||||
const defaultPort = protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT;
|
||||
const resolvedPort = isCompanion
|
||||
? ((protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port) ?? defaultPort)
|
||||
: ((protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port) ?? host.port ?? defaultPort);
|
||||
const baseLabel = host.label || host.hostname;
|
||||
const hostLabel = isCompanion ? `${baseLabel} (${protocol.toUpperCase()})` : baseLabel;
|
||||
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel,
|
||||
hostname: host.hostname,
|
||||
username: (protocol === "rdp" ? sanitizedRdp?.username : sanitizedVnc?.username) ?? host.username ?? "",
|
||||
status: "connecting",
|
||||
protocol,
|
||||
port: resolvedPort,
|
||||
...(sanitizedRdp ? { rdpConfig: sanitizedRdp } : {}),
|
||||
...(sanitizedVnc ? { vncConfig: sanitizedVnc } : {}),
|
||||
...(isCompanion ? { remoteDesktopCompanion: true } : {}),
|
||||
...(host.ephemeral ? { ephemeralHost: true } : {}),
|
||||
...(options?.workspaceId ? { workspaceId: options.workspaceId } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const createWorkspaceHostTerminalSession = (
|
||||
sessionId: string,
|
||||
host: Host,
|
||||
|
||||
@@ -5,15 +5,17 @@ import {
|
||||
retainStableSessionsIgnoringPresentation,
|
||||
terminalPaneSessionsEqual,
|
||||
} from '../../domain/terminalPaneSessionsEqual.ts';
|
||||
import type { TerminalSession } from '../../domain/models.ts';
|
||||
import { topTabsSessionsEqual } from '../../domain/topTabsSessionsEqual.ts';
|
||||
import {
|
||||
applySessionPresentation,
|
||||
publishSessionCodingCliProvider,
|
||||
publishSessionDynamicTitle,
|
||||
publishSessionPromptHost,
|
||||
sessionPresentationStore,
|
||||
} from './sessionPresentationStore.ts';
|
||||
|
||||
const session = (overrides: Record<string, unknown> = {}) => ({
|
||||
const session = (overrides: Partial<TerminalSession> = {}): TerminalSession => ({
|
||||
id: 's1',
|
||||
hostId: 'h1',
|
||||
hostLabel: 'host',
|
||||
@@ -126,3 +128,16 @@ test('session snapshot distinguishes missing fields from null tombstones', () =>
|
||||
assert.notEqual(bothTombstoned, '');
|
||||
sessionPresentationStore.clearSession('snap-1');
|
||||
});
|
||||
|
||||
test('prompt hostnames overlay as presentation without replacing configured hostname', () => {
|
||||
sessionPresentationStore.clearSession('prompt-host');
|
||||
publishSessionPromptHost('prompt-host', '10.1.64.1');
|
||||
const merged = applySessionPresentation(session({
|
||||
id: 'prompt-host',
|
||||
hostLabel: 'jumpserver',
|
||||
hostname: 'jumpserver.example.com',
|
||||
}));
|
||||
assert.equal(merged.promptHostname, '10.1.64.1');
|
||||
assert.equal(merged.hostname, 'jumpserver.example.com');
|
||||
sessionPresentationStore.clearSession('prompt-host');
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import type { CodingCliProviderId } from '../../domain/codingCliProviders';
|
||||
|
||||
export type SessionPresentation = {
|
||||
dynamicTitle?: string | null;
|
||||
promptHostname?: string | null;
|
||||
codingCliProviderId?: CodingCliProviderId | null;
|
||||
};
|
||||
|
||||
@@ -41,7 +42,7 @@ class SessionPresentationStore {
|
||||
getSessionSnapshot = (sessionId: string): string => {
|
||||
const presentation = this.bySession.get(sessionId);
|
||||
if (!presentation) return '';
|
||||
return `${encodePresentationField(presentation.dynamicTitle)}\0${encodePresentationField(presentation.codingCliProviderId)}`;
|
||||
return `${encodePresentationField(presentation.dynamicTitle)}\0${encodePresentationField(presentation.promptHostname)}\0${encodePresentationField(presentation.codingCliProviderId)}`;
|
||||
};
|
||||
|
||||
subscribe = (listener: Listener): (() => void) => {
|
||||
@@ -59,6 +60,7 @@ class SessionPresentationStore {
|
||||
// title/provider and the store had no prior entry.
|
||||
if (
|
||||
prev.dynamicTitle === next.dynamicTitle
|
||||
&& prev.promptHostname === next.promptHostname
|
||||
&& prev.codingCliProviderId === next.codingCliProviderId
|
||||
) {
|
||||
return;
|
||||
@@ -102,9 +104,14 @@ export function publishSessionCodingCliProvider(
|
||||
sessionPresentationStore.setPresentation(sessionId, { codingCliProviderId: providerId });
|
||||
}
|
||||
|
||||
export function publishSessionPromptHost(sessionId: string, hostname: string | null): void {
|
||||
sessionPresentationStore.setPresentation(sessionId, { promptHostname: hostname });
|
||||
}
|
||||
|
||||
type SessionWithPresentation = {
|
||||
id: string;
|
||||
dynamicTitle?: string;
|
||||
promptHostname?: string;
|
||||
codingCliProviderId?: CodingCliProviderId;
|
||||
};
|
||||
|
||||
@@ -119,11 +126,15 @@ export function applySessionPresentation<T extends SessionWithPresentation>(sess
|
||||
const nextTitle = presentation.dynamicTitle === undefined
|
||||
? session.dynamicTitle
|
||||
: (presentation.dynamicTitle ?? undefined);
|
||||
const nextPromptHost = presentation.promptHostname === undefined
|
||||
? session.promptHostname
|
||||
: (presentation.promptHostname ?? undefined);
|
||||
const nextProvider = presentation.codingCliProviderId === undefined
|
||||
? session.codingCliProviderId
|
||||
: (presentation.codingCliProviderId ?? undefined);
|
||||
if (
|
||||
nextTitle === session.dynamicTitle
|
||||
&& nextPromptHost === session.promptHostname
|
||||
&& nextProvider === session.codingCliProviderId
|
||||
) {
|
||||
return session;
|
||||
@@ -131,6 +142,7 @@ export function applySessionPresentation<T extends SessionWithPresentation>(sess
|
||||
return {
|
||||
...session,
|
||||
dynamicTitle: nextTitle,
|
||||
promptHostname: nextPromptHost,
|
||||
codingCliProviderId: nextProvider,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ test('session actions register and unregister', () => {
|
||||
createLocalTerminal: noop,
|
||||
createSerialSession: noop,
|
||||
connectToHost: noop,
|
||||
connectToHostRemoteDesktop: noop,
|
||||
updateSessionStatus: noop,
|
||||
updateSessionFontSize: noop,
|
||||
clearSessionFontSizeOverride: noop,
|
||||
@@ -113,6 +114,7 @@ test('session actions register and unregister', () => {
|
||||
updateSessionRestoreCwd: noop,
|
||||
getSessionRestoreCwd: noop,
|
||||
updateSessionDynamicTitle: noop,
|
||||
updateSessionPromptHost: noop,
|
||||
updateSessionCodingCliProvider: noop,
|
||||
});
|
||||
getSessionSnapshotActions()?.setActiveTabId('vault');
|
||||
|
||||
@@ -51,6 +51,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'createLocalTerminal'
|
||||
| 'createSerialSession'
|
||||
| 'connectToHost'
|
||||
| 'connectToHostRemoteDesktop'
|
||||
| 'updateSessionStatus'
|
||||
| 'updateSessionFontSize'
|
||||
| 'clearSessionFontSizeOverride'
|
||||
@@ -84,6 +85,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'updateSessionRestoreCwd'
|
||||
| 'getSessionRestoreCwd'
|
||||
| 'updateSessionDynamicTitle'
|
||||
| 'updateSessionPromptHost'
|
||||
| 'updateSessionCodingCliProvider'
|
||||
>;
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
closeSessionsState,
|
||||
closeSessionWorkspaceLayoutState,
|
||||
detachSessionFromWorkspaceState,
|
||||
isPreferredTabAvailableAfterClose,
|
||||
resolveActiveTabAfterCloseSession,
|
||||
resolveActiveTabAfterCloseWorkspace,
|
||||
} from "./sessionWorkspaceDetach";
|
||||
|
||||
const session = (id: string, workspaceId = "ws-1"): TerminalSession => ({
|
||||
@@ -308,3 +310,188 @@ test("closing a subset of standalone sessions keeps tabs outside the batch", ()
|
||||
assert.deepEqual(result.sessions.map((candidate) => candidate.id), ["s1"]);
|
||||
assert.equal(result.activeTabId, undefined);
|
||||
});
|
||||
|
||||
test("issue #4249 scenario 1: closing terminal tabs right-to-left focuses B -> A -> vault", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
const step1 = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["c"],
|
||||
currentActiveTabId: "c",
|
||||
preferredTabId: "b",
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(step1.activeTabId, "b");
|
||||
|
||||
const step2 = closeSessionsState({
|
||||
sessions: step1.sessions,
|
||||
workspaces: step1.workspaces,
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: step1.activeTabId ?? null,
|
||||
preferredTabId: "b",
|
||||
tabOrder: step1.tabOrder,
|
||||
});
|
||||
assert.equal(step2.activeTabId, "a");
|
||||
|
||||
const step3 = closeSessionsState({
|
||||
sessions: step2.sessions,
|
||||
workspaces: step2.workspaces,
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: step2.activeTabId ?? null,
|
||||
preferredTabId: "b",
|
||||
tabOrder: step2.tabOrder,
|
||||
});
|
||||
assert.equal(step3.activeTabId, "vault");
|
||||
});
|
||||
|
||||
test("issue #4249 scenario 2: after visiting vault or sftp, closing C -> B -> A stays on adjacent terminals until the last tab closes", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
for (const rootView of ["vault", "sftp"] as const) {
|
||||
const step1 = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["c"],
|
||||
currentActiveTabId: "c",
|
||||
preferredTabId: rootView,
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(step1.activeTabId, "b", `closing C after ${rootView} should focus B`);
|
||||
|
||||
const step2 = closeSessionsState({
|
||||
sessions: step1.sessions,
|
||||
workspaces: step1.workspaces,
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: step1.activeTabId ?? null,
|
||||
preferredTabId: rootView,
|
||||
tabOrder: step1.tabOrder,
|
||||
});
|
||||
assert.equal(step2.activeTabId, "a", `closing B after ${rootView} should focus A`);
|
||||
|
||||
const step3 = closeSessionsState({
|
||||
sessions: step2.sessions,
|
||||
workspaces: step2.workspaces,
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: step2.activeTabId ?? null,
|
||||
preferredTabId: rootView,
|
||||
tabOrder: step2.tabOrder,
|
||||
});
|
||||
assert.equal(step3.activeTabId, rootView, `closing last tab A should fall back to ${rootView}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("closing a terminal tab follows visual tabOrder instead of raw session/workspace arrays", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
// Raw arrays have [s1, s2] and [ws-1], while visual tab order is [ws-1, s1, s2].
|
||||
const result = closeSessionsState({
|
||||
sessions: [session("ws-pane", "ws-1"), standaloneSession("s1"), standaloneSession("s2")],
|
||||
workspaces: [workspace(["ws-pane"])],
|
||||
sessionIds: ["s2"],
|
||||
currentActiveTabId: "s2",
|
||||
preferredTabId: "vault",
|
||||
tabOrder: ["ws-1", "s1", "s2"],
|
||||
});
|
||||
|
||||
// Must focus adjacent terminal s1, not jump over s1 to ws-1 or vault.
|
||||
assert.equal(result.activeTabId, "s1");
|
||||
});
|
||||
|
||||
test("closing a middle or leftmost terminal tab picks left neighbor first, then right neighbor", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
const closeMiddle = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: "b",
|
||||
preferredTabId: "sftp",
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(closeMiddle.activeTabId, "a");
|
||||
|
||||
const closeLeftmost = closeSessionsState({
|
||||
sessions: closeMiddle.sessions,
|
||||
workspaces: [],
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: "a",
|
||||
preferredTabId: "sftp",
|
||||
tabOrder: closeMiddle.tabOrder,
|
||||
});
|
||||
assert.equal(closeLeftmost.activeTabId, "c");
|
||||
});
|
||||
|
||||
test("resolveActiveTabAfterCloseWorkspace focuses adjacent terminal/workspace before falling back to root view", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const ws1 = workspace(["p1"], { id: "ws-1" });
|
||||
|
||||
assert.equal(
|
||||
resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: "ws-1",
|
||||
closedWorkspaceId: "ws-1",
|
||||
previousWorkspaces: [ws1],
|
||||
remainingWorkspaces: [],
|
||||
remainingSessions: [standaloneSession("s1"), standaloneSession("s2")],
|
||||
tabOrder: ["s1", "ws-1", "s2"],
|
||||
preferredTabId: "sftp",
|
||||
}),
|
||||
"s1",
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: "ws-1",
|
||||
closedWorkspaceId: "ws-1",
|
||||
previousWorkspaces: [ws1],
|
||||
remainingWorkspaces: [],
|
||||
remainingSessions: [],
|
||||
tabOrder: ["ws-1"],
|
||||
preferredTabId: "sftp",
|
||||
}),
|
||||
"sftp",
|
||||
);
|
||||
});
|
||||
|
||||
test("isPreferredTabAvailableAfterClose does not treat vault or sftp as surviving terminal tabs", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const layoutResult = closeSessionWorkspaceLayoutState([], undefined, "c");
|
||||
const remainingSessions = [standaloneSession("a"), standaloneSession("b")];
|
||||
|
||||
assert.equal(
|
||||
isPreferredTabAvailableAfterClose({
|
||||
preferredTabId: "vault",
|
||||
closedSessionId: "c",
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isPreferredTabAvailableAfterClose({
|
||||
preferredTabId: "sftp",
|
||||
closedSessionId: "c",
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { TerminalSession, Workspace } from "../../domain/models";
|
||||
import type { AIChatRecencyEntry } from "../../domain/aiSessionRecency";
|
||||
import { resolveMostRecentlyActiveMemberTerminalId } from "../../domain/aiSessionRecency";
|
||||
import {
|
||||
buildOrderedTerminalTabIds,
|
||||
resolveNextActiveTabAfterTerminalClose,
|
||||
} from "../../domain/tabCloseFocus";
|
||||
import { collectSessionIds, createEmptyWorkspaceRoot, pruneWorkspaceNode } from "../../domain/workspace";
|
||||
|
||||
export type DetachSessionFromWorkspaceStateResult = {
|
||||
@@ -128,7 +132,6 @@ export function isPreferredTabAvailableAfterClose(
|
||||
} {
|
||||
const { preferredTabId, closedSessionId, layoutResult, remainingSessions } = input;
|
||||
if (!preferredTabId || preferredTabId === closedSessionId) return false;
|
||||
if (preferredTabId === "vault" || preferredTabId === "sftp") return true;
|
||||
if (layoutResult.workspaces.some((workspace) => workspace.id === preferredTabId)) return true;
|
||||
return remainingSessions.some((session) => (
|
||||
session.id === preferredTabId
|
||||
@@ -143,6 +146,8 @@ export function resolveActiveTabAfterCloseSession({
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
preferredTabId,
|
||||
orderedTabIdsBeforeClose,
|
||||
tabOrder,
|
||||
}: {
|
||||
currentActiveTabId: string | null;
|
||||
closedSessionId: string;
|
||||
@@ -150,30 +155,61 @@ export function resolveActiveTabAfterCloseSession({
|
||||
layoutResult: CloseSessionWorkspaceLayoutResult;
|
||||
remainingSessions: readonly TerminalSession[];
|
||||
preferredTabId?: string | null;
|
||||
orderedTabIdsBeforeClose?: readonly string[];
|
||||
tabOrder?: readonly string[];
|
||||
}): string | null {
|
||||
const fallbackWorkspace = layoutResult.workspaces[layoutResult.workspaces.length - 1];
|
||||
const fallbackSolo = remainingSessions.filter((session) => !session.workspaceId && !session.hiddenFromTabs).slice(-1)[0];
|
||||
const preferredInput = {
|
||||
preferredTabId,
|
||||
closedSessionId,
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
};
|
||||
const preferredFallback = isPreferredTabAvailableAfterClose(preferredInput)
|
||||
? preferredInput.preferredTabId
|
||||
: undefined;
|
||||
const fallback = preferredFallback
|
||||
?? fallbackWorkspace?.id
|
||||
?? fallbackSolo?.id
|
||||
?? "vault";
|
||||
const survivingTabIds = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: layoutResult.workspaces,
|
||||
tabOrder,
|
||||
});
|
||||
|
||||
// Workspaces survive member loss (#4098 phase 2), so only a closed session
|
||||
// tab that was active needs a replacement.
|
||||
if (currentActiveTabId === closedSessionId) {
|
||||
return fallback;
|
||||
}
|
||||
return resolveNextActiveTabAfterTerminalClose({
|
||||
currentActiveTabId,
|
||||
closedTabId: closedSessionId,
|
||||
orderedTabIdsBeforeClose,
|
||||
survivingTabIds,
|
||||
preferredTabId,
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
export function resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId,
|
||||
closedWorkspaceId,
|
||||
previousWorkspaces,
|
||||
remainingWorkspaces,
|
||||
remainingSessions,
|
||||
tabOrder,
|
||||
preferredTabId,
|
||||
}: {
|
||||
currentActiveTabId: string | null;
|
||||
closedWorkspaceId: string;
|
||||
previousWorkspaces: readonly Workspace[];
|
||||
remainingWorkspaces: readonly Workspace[];
|
||||
remainingSessions: readonly TerminalSession[];
|
||||
tabOrder?: readonly string[];
|
||||
preferredTabId?: string | null;
|
||||
}): string | null {
|
||||
const orderedTabIdsBeforeClose = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: previousWorkspaces,
|
||||
tabOrder,
|
||||
});
|
||||
const survivingTabIds = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: remainingWorkspaces,
|
||||
tabOrder,
|
||||
});
|
||||
|
||||
return resolveNextActiveTabAfterTerminalClose({
|
||||
currentActiveTabId,
|
||||
closedTabId: closedWorkspaceId,
|
||||
orderedTabIdsBeforeClose,
|
||||
survivingTabIds,
|
||||
preferredTabId,
|
||||
});
|
||||
}
|
||||
|
||||
export function closeSessionsState({
|
||||
@@ -203,6 +239,11 @@ export function closeSessionsState({
|
||||
const targetSession = nextSessions.find((session) => session.id === sessionId);
|
||||
if (!targetSession) continue;
|
||||
|
||||
const orderedTabIdsBeforeClose = buildOrderedTerminalTabIds({
|
||||
sessions: nextSessions,
|
||||
workspaces: nextWorkspaces,
|
||||
tabOrder: nextTabOrder,
|
||||
});
|
||||
const workspaceId = targetSession.workspaceId;
|
||||
const layoutResult = closeSessionWorkspaceLayoutState(
|
||||
nextWorkspaces,
|
||||
@@ -220,7 +261,10 @@ export function closeSessionsState({
|
||||
layoutResult,
|
||||
remainingSessions: nextSessions,
|
||||
preferredTabId,
|
||||
orderedTabIdsBeforeClose,
|
||||
tabOrder: nextTabOrder,
|
||||
});
|
||||
nextTabOrder = nextTabOrder.filter((id) => id !== sessionId);
|
||||
if (activeTabAfterClose) {
|
||||
nextActiveTabId = activeTabAfterClose;
|
||||
resolvedActiveTabId = activeTabAfterClose;
|
||||
|
||||
@@ -72,6 +72,11 @@ import {
|
||||
import { isTerminalSidePanelAutoOpenTab, type TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import { isStartupLanding, type StartupLanding } from '../../domain/startupLanding';
|
||||
import type { AppearanceSyncEvent } from './appearanceSync';
|
||||
import {
|
||||
isJumpServerRdpLaunchMode,
|
||||
STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
type JumpServerRdpLaunchMode,
|
||||
} from './settingsStorageSync';
|
||||
|
||||
interface UseSettingsIpcSyncParams {
|
||||
enabled?: boolean;
|
||||
@@ -94,6 +99,7 @@ interface UseSettingsIpcSyncParams {
|
||||
setSshDebugLogsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setSshDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJmsDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJumpServerRdpLaunchModeState: Dispatch<SetStateAction<JumpServerRdpLaunchMode>>;
|
||||
setExplorerContextMenuEnabledState: (enabled: boolean) => void;
|
||||
setHotkeyScheme: Dispatch<SetStateAction<HotkeyScheme>>;
|
||||
applyIncomingCustomKeyBindings: (incoming: { bindings: CustomKeyBindings; version: number; origin: string }) => void;
|
||||
@@ -144,6 +150,7 @@ export function useSettingsIpcSync({
|
||||
setSshDebugLogsEnabled,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setHotkeyScheme,
|
||||
applyIncomingCustomKeyBindings,
|
||||
@@ -261,6 +268,9 @@ export function useSettingsIpcSync({
|
||||
if (key === STORAGE_KEY_JMS_DEEP_LINK_ENABLED && typeof value === 'boolean') {
|
||||
setJmsDeepLinkEnabledState(value);
|
||||
}
|
||||
if (key === STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE && isJumpServerRdpLaunchMode(value)) {
|
||||
setJumpServerRdpLaunchModeState((prev) => (prev === value ? prev : value));
|
||||
}
|
||||
if (key === STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED && typeof value === 'boolean') {
|
||||
setExplorerContextMenuEnabledState(value);
|
||||
}
|
||||
@@ -387,6 +397,7 @@ export function useSettingsIpcSync({
|
||||
setSessionLogsTimestampsEnabled,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setSshDebugLogsEnabled,
|
||||
setSftpAutoOpenSidebar,
|
||||
|
||||
@@ -55,6 +55,11 @@ import {
|
||||
STORAGE_KEY_WINDOW_OPACITY,
|
||||
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
|
||||
STORAGE_KEY_APP_ICON_VARIANT,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { resolveAppIconVariant, type AppIconVariant } from '../../domain/appIconVariant';
|
||||
import { resolveAppearanceStorageEvent } from './appearanceSync';
|
||||
@@ -66,6 +71,42 @@ import { isTerminalSidePanelAutoOpenTab, type TerminalSidePanelAutoOpenTab } fro
|
||||
import { isHostClickBehavior, type HostClickBehavior } from '../../domain/hostClickBehavior';
|
||||
import { isStartupLanding, type StartupLanding } from '../../domain/startupLanding';
|
||||
|
||||
export type JumpServerRdpLaunchMode = 'builtin' | 'system';
|
||||
|
||||
export const STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE = 'netcatty_jumpserver_rdp_launch_mode_v1';
|
||||
|
||||
export const DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE: JumpServerRdpLaunchMode = 'builtin';
|
||||
|
||||
export const isJumpServerRdpLaunchMode = (value: unknown): value is JumpServerRdpLaunchMode => (
|
||||
value === 'builtin' || value === 'system'
|
||||
);
|
||||
|
||||
export type RemoteDesktopRecordingFps = 5 | 10 | 15;
|
||||
|
||||
export const DEFAULT_REMOTE_DESKTOP_AUTO_RECORD = false;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_FPS: RemoteDesktopRecordingFps = 10;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO = true;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB = 1024;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS = 30;
|
||||
|
||||
export const normalizeRemoteDesktopRecordingFps = (value: unknown): RemoteDesktopRecordingFps => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (num === 5 || num === 10 || num === 15) return num;
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_FPS;
|
||||
};
|
||||
|
||||
export const normalizeRemoteDesktopRecordingMaxMb = (value: unknown): number => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (Number.isFinite(num) && num >= 64 && num <= 102400) return Math.round(num);
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB;
|
||||
};
|
||||
|
||||
export const normalizeRemoteDesktopRecordingRetentionDays = (value: unknown): number => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (Number.isFinite(num) && num >= 0 && num <= 3650) return Math.round(num);
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS;
|
||||
};
|
||||
|
||||
interface UseSettingsStorageSyncParams {
|
||||
enabled?: boolean;
|
||||
theme: 'dark' | 'light' | 'system';
|
||||
@@ -110,9 +151,15 @@ interface UseSettingsStorageSyncParams {
|
||||
sessionLogsDir: string;
|
||||
sessionLogsFormat: SessionLogFormat;
|
||||
sessionLogsTimestampsEnabled: boolean;
|
||||
remoteDesktopAutoRecord: boolean;
|
||||
remoteDesktopRecordingFps: RemoteDesktopRecordingFps;
|
||||
remoteDesktopRecordingIncludeAudio: boolean;
|
||||
remoteDesktopRecordingMaxMb: number;
|
||||
remoteDesktopRecordingRetentionDays: number;
|
||||
sshDebugLogsEnabled: boolean;
|
||||
sshDeepLinkEnabled: boolean;
|
||||
jmsDeepLinkEnabled: boolean;
|
||||
jumpServerRdpLaunchMode: JumpServerRdpLaunchMode;
|
||||
explorerContextMenuEnabled: boolean;
|
||||
globalHotkeyEnabled: boolean;
|
||||
autoUpdateEnabled: boolean;
|
||||
@@ -162,9 +209,15 @@ interface UseSettingsStorageSyncParams {
|
||||
setSessionLogsDir: Dispatch<SetStateAction<string>>;
|
||||
setSessionLogsFormat: Dispatch<SetStateAction<SessionLogFormat>>;
|
||||
setSessionLogsTimestampsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopAutoRecordState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopRecordingFpsState: Dispatch<SetStateAction<RemoteDesktopRecordingFps>>;
|
||||
setRemoteDesktopRecordingIncludeAudioState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopRecordingMaxMbState: Dispatch<SetStateAction<number>>;
|
||||
setRemoteDesktopRecordingRetentionDaysState: Dispatch<SetStateAction<number>>;
|
||||
setSshDebugLogsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setSshDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJmsDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJumpServerRdpLaunchModeState: Dispatch<SetStateAction<JumpServerRdpLaunchMode>>;
|
||||
setExplorerContextMenuEnabledState: (enabled: boolean) => void;
|
||||
setGlobalHotkeyEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setWindowOpacity: (raw: unknown) => void;
|
||||
@@ -186,7 +239,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode, applyIncomingCustomAccent,
|
||||
setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage,
|
||||
@@ -195,7 +250,9 @@ export function useSettingsStorageSync({
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
|
||||
setGlobalHotkeyEnabled, setWindowOpacity, setWindowBackgroundBlur, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
|
||||
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
|
||||
applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings,
|
||||
@@ -210,7 +267,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
});
|
||||
settingsSnapshotRef.current = {
|
||||
@@ -220,7 +279,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
};
|
||||
|
||||
@@ -367,6 +428,36 @@ export function useSettingsStorageSync({
|
||||
setSessionLogsTimestampsEnabled(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.remoteDesktopAutoRecord) {
|
||||
setRemoteDesktopAutoRecordState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingFps(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingFps) {
|
||||
setRemoteDesktopRecordingFpsState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.remoteDesktopRecordingIncludeAudio) {
|
||||
setRemoteDesktopRecordingIncludeAudioState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingMaxMb(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingMaxMb) {
|
||||
setRemoteDesktopRecordingMaxMbState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingRetentionDays(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingRetentionDays) {
|
||||
setRemoteDesktopRecordingRetentionDaysState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_SSH_DEBUG_LOGS_ENABLED && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.sshDebugLogsEnabled) {
|
||||
@@ -385,6 +476,11 @@ export function useSettingsStorageSync({
|
||||
setJmsDeepLinkEnabledState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE && e.newValue !== null) {
|
||||
if (isJumpServerRdpLaunchMode(e.newValue) && e.newValue !== s.jumpServerRdpLaunchMode) {
|
||||
setJumpServerRdpLaunchModeState(e.newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.explorerContextMenuEnabled) {
|
||||
@@ -583,8 +679,14 @@ export function useSettingsStorageSync({
|
||||
setSessionLogsEnabled,
|
||||
setSessionLogsFormat,
|
||||
setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState,
|
||||
setRemoteDesktopRecordingFpsState,
|
||||
setRemoteDesktopRecordingIncludeAudioState,
|
||||
setRemoteDesktopRecordingMaxMbState,
|
||||
setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setSshDebugLogsEnabled,
|
||||
setSftpAutoOpenSidebar,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
buildSftpDownloadDialogDirectoryOptions,
|
||||
type SftpDownloadDialogDirectoryOptions,
|
||||
} from "../../../domain/sftpDownloadLocation";
|
||||
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
|
||||
/**
|
||||
* Read the device-local default download folder at call time so every SFTP
|
||||
* surface (main view, terminal side panel, other windows) sees the latest
|
||||
* value without threading it through props.
|
||||
*/
|
||||
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
|
||||
let stored: string | null = null;
|
||||
try {
|
||||
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
|
||||
} catch {
|
||||
// Storage unavailable (non-browser host); fall back to system Downloads.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored);
|
||||
};
|
||||
@@ -0,0 +1,260 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
|
||||
import { runPackedDownload } from "./packedDownload";
|
||||
import { serializeSftpTransferCenter, deserializeSftpTransferCenter } from "../../../domain/sftpTransferCenter";
|
||||
import { findActivePathConflict } from "../../../domain/sftpTransferConflicts";
|
||||
import { globalSftpTransferScheduler } from "./globalTransferScheduler";
|
||||
|
||||
const request = {
|
||||
fileName: "2 selected", remoteDirectory: "/srv", names: ["compose", "README.md"],
|
||||
localDirectory: "/downloads", sftpId: "pinned-sftp", connectionId: "browse", sourceHostId: "host", sourceHostLabel: "Host",
|
||||
};
|
||||
|
||||
test("one selection retains the captured connection and owns only its selected destination paths", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => null);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
const leases: string[] = [];
|
||||
let id = "";
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
retainSftpTransferSession: async (session: string, lease: string, options: { cancelOnOwnerGone: boolean }) => {
|
||||
assert.deepEqual(options, { cancelOnOwnerGone: true });
|
||||
leases.push(session + lease);
|
||||
return { success: true };
|
||||
},
|
||||
releaseSftpTransferSession: async (session: string, lease: string) => {
|
||||
assert.equal(leases.pop(), session + lease);
|
||||
},
|
||||
downloadPackedSftp: async (options: { transferId: string; sftpId: string; remoteDirectory: string; names: string[]; localDirectory: string },
|
||||
progress: (p: { phase: "extracting"; bytes: number }) => void) => {
|
||||
id = options.transferId;
|
||||
assert.equal(options.sftpId, request.sftpId);
|
||||
assert.equal(options.remoteDirectory, "/srv");
|
||||
assert.equal(options.localDirectory, "/downloads");
|
||||
assert.deepEqual(options.names, request.names);
|
||||
progress({ phase: "extracting", bytes: 203 });
|
||||
const rows = sftpTransferCenterStore.getOwnerTasks("fixture");
|
||||
assert.equal(rows.length, 1);
|
||||
const recovered = deserializeSftpTransferCenter(serializeSftpTransferCenter(rows)).tasks[0];
|
||||
assert.equal(recovered.status, "cancelled", "after restart never resume a packed group as a conventional walk of its parent");
|
||||
assert.equal(recovered.resumable, false);
|
||||
assert.equal(rows[0].phase, "extracting");
|
||||
assert.equal(rows[0].transferredBytes, 203);
|
||||
for (const path of ["/downloads/compose", "/downloads/compose/config/.env", "/downloads/README.md"]) {
|
||||
assert.equal(findActivePathConflict(rows, { id: "other", targetConnectionId: "local", targetPath: path })?.id, id);
|
||||
}
|
||||
assert.equal(findActivePathConflict(rows, { id: "other", targetConnectionId: "local", targetPath: "/downloads/another" }), undefined);
|
||||
return { status: "completed" };
|
||||
},
|
||||
}));
|
||||
try {
|
||||
assert.equal(await runPackedDownload("fixture", request), "completed");
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "completed");
|
||||
assert.equal(leases.length, 0);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
|
||||
test("unavailable server and local collision release the path reservation, disabled switch bypasses the SSH request", async (t) => {
|
||||
let enabled = true;
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => enabled);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
let reason = "unsupported", calls = 0;
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
downloadPackedSftp: async () => { calls++; return { status: "fallback", reason }; },
|
||||
}));
|
||||
assert.equal(await runPackedDownload("fallback", request), "unsupported");
|
||||
reason = "conflict";
|
||||
assert.equal(await runPackedDownload("fallback", request), "conflict");
|
||||
enabled = false;
|
||||
assert.equal(await runPackedDownload("fallback", request), "regular");
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(sftpTransferCenterStore.getOwnerTasks("fallback").length, 0);
|
||||
});
|
||||
|
||||
test("cancelling the transfer-center row aborts the packed operation without starting fallback", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
let signalStarted!: (id: string) => void;
|
||||
const started = new Promise<string>((resolve) => { signalStarted = resolve; });
|
||||
let signalStopped!: (result: { status: "cancelled" }) => void;
|
||||
const done = new Promise<{ status: "cancelled" }>((resolve) => { signalStopped = resolve; });
|
||||
let aborted = "", released = false;
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
retainSftpTransferSession: async () => ({ success: true }),
|
||||
releaseSftpTransferSession: async () => { released = true; },
|
||||
downloadPackedSftp: async (options: { transferId: string }) => {
|
||||
signalStarted(options.transferId);
|
||||
return done;
|
||||
},
|
||||
cancelTransfer: async (id: string) => { aborted = id; signalStopped({ status: "cancelled" }); },
|
||||
}));
|
||||
const running = runPackedDownload("cancel-test", request);
|
||||
const id = await started;
|
||||
try {
|
||||
await sftpTransferCenterStore.cancel(id);
|
||||
assert.equal(await running, "cancelled");
|
||||
assert.equal(aborted, id);
|
||||
assert.equal(released, true);
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "cancelled");
|
||||
} finally {
|
||||
signalStopped({ status: "cancelled" });
|
||||
sftpTransferCenterStore.dismiss(id);
|
||||
}
|
||||
});
|
||||
|
||||
test("I/O and archive validation failures keep a failed row instead of falling back over the destination", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
let id = "";
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
downloadPackedSftp: async (options: { transferId: string }) => {
|
||||
id = options.transferId;
|
||||
throw new Error("Unsafe archive entry");
|
||||
},
|
||||
}));
|
||||
try {
|
||||
await assert.rejects(runPackedDownload("error", request), /Unsafe archive entry/);
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "failed");
|
||||
} finally {
|
||||
if (id) sftpTransferCenterStore.dismiss(id);
|
||||
}
|
||||
});
|
||||
|
||||
test("register the selected roots globally before retaining or starting a packed download", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
const order: string[] = [];
|
||||
let id = "";
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
registerPackedDownload: async (metadata: Record<string, unknown>) => {
|
||||
id = String(metadata.transferId);
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.controlKind, "packed-download");
|
||||
assert.equal(metadata.sourceConnectionId, request.connectionId);
|
||||
assert.equal(metadata.sourcePath, "/srv");
|
||||
assert.deepEqual(metadata.packedTargetPaths, ["/downloads/compose", "/downloads/README.md"]);
|
||||
order.push("register");
|
||||
return { success: true };
|
||||
},
|
||||
retainSftpTransferSession: async () => { order.push("retain"); return { success: true }; },
|
||||
downloadPackedSftp: async () => { order.push("download"); return { status: "completed" }; },
|
||||
finishPackedDownload: async (transferId: string) => { assert.equal(transferId, id); order.push("finish"); },
|
||||
releaseSftpTransferSession: async () => { order.push("release"); },
|
||||
}));
|
||||
try {
|
||||
assert.equal(await runPackedDownload("global-order", request), "completed");
|
||||
assert.deepEqual(order, ["register", "retain", "download", "finish", "release"]);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
|
||||
test("cancellation from another window during registration never starts or retains the queued download", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
let id = "", finished = false;
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
registerPackedDownload: async (metadata: { transferId: string }) => {
|
||||
id = metadata.transferId;
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "cancelled", transferId: id, controlKind: "packed-download", endedAt: Date.now(),
|
||||
});
|
||||
// Registration may already have returned success in main when a second
|
||||
// window cancels it; the broadcast can arrive before this IPC resolves.
|
||||
return { success: true };
|
||||
},
|
||||
retainSftpTransferSession: async () => { assert.fail("cancelled work must not acquire a connection lease"); },
|
||||
downloadPackedSftp: async () => { assert.fail("cancelled work must not start"); },
|
||||
finishPackedDownload: async (transferId: string, result: { status: string }) => {
|
||||
assert.equal(transferId, id);
|
||||
assert.equal(result.status, "cancelled");
|
||||
finished = true;
|
||||
},
|
||||
}));
|
||||
try {
|
||||
assert.equal(await runPackedDownload("global-cancel", request), "cancelled");
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "cancelled");
|
||||
assert.equal(finished, true);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
|
||||
test("failed startup and ordinary-download fallback settle the global row", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(localStorageAdapter, "readNumber", () => 1);
|
||||
let id = "", failLease = true;
|
||||
const outcomes: { status: string; error?: string }[] = [];
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
registerPackedDownload: async (metadata: { transferId: string }) => {
|
||||
id = metadata.transferId;
|
||||
return { success: true };
|
||||
},
|
||||
retainSftpTransferSession: async () => ({ success: !failLease, reason: "Connection closed" }),
|
||||
releaseSftpTransferSession: async () => {},
|
||||
downloadPackedSftp: async () => ({ status: "fallback", reason: "unsupported" }),
|
||||
finishPackedDownload: async (_id: string, result: { status: string; error?: string }) => { outcomes.push(result); },
|
||||
}));
|
||||
try {
|
||||
await assert.rejects(runPackedDownload("global-startup", request), /Connection closed/);
|
||||
assert.equal(outcomes[0].status, "failed");
|
||||
assert.equal(outcomes[0].error, "Connection closed");
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "failed");
|
||||
sftpTransferCenterStore.dismiss(id);
|
||||
failLease = false;
|
||||
assert.equal(await runPackedDownload("global-startup", request), "unsupported");
|
||||
assert.equal(outcomes[1].status, "dismissed");
|
||||
assert.equal(sftpTransferCenterStore.getTask(id), undefined);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
|
||||
test("worker failure while registering a queued job remains a failure and never starts it", async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
let id = "", finished = false;
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
registerPackedDownload: async (metadata: { transferId: string }) => {
|
||||
id = metadata.transferId;
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "failed", transferId: id, controlKind: "packed-download", error: "Transfer worker stopped",
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
retainSftpTransferSession: async () => assert.fail("must not retain after worker failure"),
|
||||
downloadPackedSftp: async () => assert.fail("must not start after worker failure"),
|
||||
finishPackedDownload: async (_id: string, result: { status: string; error: string }) => {
|
||||
assert.equal(result.status, "failed");
|
||||
assert.equal(result.error, "Transfer worker stopped");
|
||||
finished = true;
|
||||
},
|
||||
}));
|
||||
try {
|
||||
await assert.rejects(runPackedDownload("global-worker-failure", request), /Transfer worker stopped/);
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, "failed");
|
||||
assert.equal(finished, true);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
|
||||
for (const terminal of ["cancelled", "failed"] as const) {
|
||||
test(`${terminal} during connection retention releases the lease without joining the admission queue`, async (t) => {
|
||||
t.mock.method(localStorageAdapter, "readBoolean", () => true);
|
||||
t.mock.method(globalSftpTransferScheduler, "run", async () => assert.fail("settled work must not queue behind another download"));
|
||||
let id = "", released = false;
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
registerPackedDownload: async (metadata: { transferId: string }) => { id = metadata.transferId; return { success: true }; },
|
||||
retainSftpTransferSession: async () => {
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: terminal, transferId: id, controlKind: "packed-download",
|
||||
...(terminal === "failed" ? { error: "Worker exited while retaining" } : {}),
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
releaseSftpTransferSession: async () => { released = true; },
|
||||
downloadPackedSftp: async () => assert.fail("settled work must not start"),
|
||||
finishPackedDownload: async () => {},
|
||||
}));
|
||||
try {
|
||||
const running = runPackedDownload("global-lease-terminal", request);
|
||||
if (terminal === "failed") await assert.rejects(running, /Worker exited while retaining/);
|
||||
else assert.equal(await running, "cancelled");
|
||||
assert.equal(sftpTransferCenterStore.getTask(id)?.status, terminal);
|
||||
assert.equal(released, true);
|
||||
} finally { if (id) sftpTransferCenterStore.dismiss(id); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { findActivePathConflict, pathConflictMessage } from "../../../domain/sftpTransferConflicts";
|
||||
import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY, STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD } from "../../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
|
||||
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
|
||||
import { createDirectDownloadTransferTask } from "./downloadTransferTask";
|
||||
import { unwrapSftpIpcError } from "./errors";
|
||||
import { globalSftpTransferScheduler, getSftpTransferResourceKeys } from "./globalTransferScheduler";
|
||||
import { isTransferCancelledFlag } from "./transferCancelLatch";
|
||||
import { transferRuntime } from "./transferRuntime";
|
||||
import type { PackedDownloadRequest, PackedDownloadStatus } from "./useSftpTransfers.types";
|
||||
import { joinPath, joinTransferTargetPath } from "./utils";
|
||||
|
||||
export async function runPackedDownload(ownerId: string, request: PackedDownloadRequest): Promise<PackedDownloadStatus> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.downloadPackedSftp || localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD) === false) {
|
||||
return "regular";
|
||||
}
|
||||
if (!request.remoteDirectory.startsWith("/")) return "unsupported";
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
const targetPaths = request.names.map((name) => joinTransferTargetPath(request.localDirectory, name));
|
||||
const task = createDirectDownloadTransferTask({
|
||||
id, fileName: request.fileName,
|
||||
sourcePath: request.names.length === 1 ? joinPath(request.remoteDirectory, request.names[0]) : request.remoteDirectory,
|
||||
targetPath: targetPaths.length === 1 ? targetPaths[0] : request.localDirectory,
|
||||
sourceConnectionId: request.connectionId, sourceHostId: request.sourceHostId,
|
||||
sourceHostLabel: request.sourceHostLabel, isDirectory: true, totalBytes: 0,
|
||||
});
|
||||
const active = sftpTransferCenterStore.getSnapshot().tasks;
|
||||
for (const targetPath of targetPaths) {
|
||||
const conflict = findActivePathConflict(active, { ...task, targetPath });
|
||||
if (conflict) throw new Error(pathConflictMessage(conflict));
|
||||
}
|
||||
|
||||
// Reserve all selected roots synchronously, before waiting for a slot or a channel.
|
||||
transferRuntime.enqueue([{ ...task, ownerId, packedTargetPaths: targetPaths,
|
||||
controlKind: "packed-download", progressMode: "bytes", resumable: false, retryable: false,
|
||||
}]);
|
||||
const packed = bridge.downloadPackedSftp;
|
||||
let outcome: PackedDownloadStatus = "cancelled";
|
||||
let received = 0;
|
||||
const sharedFailure = () => {
|
||||
const current = sftpTransferCenterStore.getTask(id);
|
||||
return current?.status === "failed" ? current.error || "Packed download failed" : undefined;
|
||||
};
|
||||
await transferRuntime.runWalk(id, async () => {
|
||||
let retained = false;
|
||||
let registrationStarted = false;
|
||||
let finalStatus: "cancelled" | "failed" | "dismissed" = "cancelled";
|
||||
let finalError: string | undefined;
|
||||
try {
|
||||
// Register before waiting for admission so every window can see and
|
||||
// cancel queued work. Main owns the shared lifecycle and routes controls
|
||||
// back to this renderer's captured connection.
|
||||
if (bridge.registerPackedDownload) {
|
||||
registrationStarted = true;
|
||||
const registered = await bridge.registerPackedDownload({
|
||||
transferId: id, fileName: task.fileName,
|
||||
sourcePath: task.sourcePath, targetPath: task.targetPath,
|
||||
sourceConnectionId: request.connectionId, sourceHostId: request.sourceHostId,
|
||||
sourceHostLabel: request.sourceHostLabel, packedTargetPaths: targetPaths,
|
||||
});
|
||||
const registrationError = sharedFailure();
|
||||
if (registrationError) throw new Error(registrationError);
|
||||
if (!registered.success || isTransferCancelledFlag(id)) {
|
||||
transferRuntime.patchTask(id, { status: "cancelled", endTime: Date.now() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Use a separate exec channel on the exact browse connection (including terminal
|
||||
// host/user overrides). A transfer lease keeps it alive if the pane is closed.
|
||||
if (bridge.retainSftpTransferSession) {
|
||||
const lease = await bridge.retainSftpTransferSession(request.sftpId, id, { cancelOnOwnerGone: true });
|
||||
if (!lease.success) throw new Error(lease.reason || "SFTP session is no longer available");
|
||||
retained = true;
|
||||
}
|
||||
const leaseError = sharedFailure();
|
||||
if (leaseError) throw new Error(leaseError);
|
||||
if (isTransferCancelledFlag(id)) {
|
||||
transferRuntime.patchTask(id, { status: "cancelled", endTime: Date.now() });
|
||||
return;
|
||||
}
|
||||
const result = await globalSftpTransferScheduler.run(ownerId, id,
|
||||
getSftpTransferResourceKeys({ sourceHostId: request.sourceHostId, sourceSftpId: request.sftpId }),
|
||||
() => localStorageAdapter.readNumber(STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY),
|
||||
async () => {
|
||||
if (isTransferCancelledFlag(id)) return { status: "cancelled" as const };
|
||||
transferRuntime.patchTask(id, { status: "transferring", phase: "transferring" });
|
||||
return packed({
|
||||
sftpId: request.sftpId, transferId: id, remoteDirectory: request.remoteDirectory,
|
||||
names: request.names, localDirectory: request.localDirectory, encoding: request.sourceEncoding,
|
||||
}, ({ phase, bytes }) => {
|
||||
if (isTransferCancelledFlag(id)) return;
|
||||
received = Math.max(received, bytes);
|
||||
transferRuntime.patchTask(id, {
|
||||
phase: phase === "extracting" ? "extracting" : "transferring",
|
||||
transferredBytes: received,
|
||||
});
|
||||
});
|
||||
});
|
||||
const streamError = sharedFailure();
|
||||
if (streamError) throw new Error(streamError);
|
||||
if (result.status === "completed") {
|
||||
outcome = "completed";
|
||||
transferRuntime.patchTask(id, { status: "completed", totalBytes: received, transferredBytes: received, endTime: Date.now() });
|
||||
} else if (result.status === "cancelled" || isTransferCancelledFlag(id)) {
|
||||
transferRuntime.patchTask(id, { status: "cancelled", endTime: Date.now() });
|
||||
} else {
|
||||
outcome = result.reason === "conflict" ? "conflict" : "unsupported";
|
||||
finalStatus = "dismissed";
|
||||
sftpTransferCenterStore.dismiss(id);
|
||||
}
|
||||
} catch (error) {
|
||||
// Worker failure also stops the renderer's admission queue. Preserve the
|
||||
// shared failure instead of labelling that queue interruption Cancelled.
|
||||
const sharedError = sharedFailure();
|
||||
if (!sharedError && isTransferCancelledFlag(id)) {
|
||||
transferRuntime.patchTask(id, { status: "cancelled", endTime: Date.now() });
|
||||
} else {
|
||||
const message = sharedError ?? unwrapSftpIpcError(error);
|
||||
finalStatus = "failed";
|
||||
finalError = message;
|
||||
transferRuntime.patchTask(id, { status: "failed", error: message, endTime: Date.now() });
|
||||
throw new Error(message);
|
||||
}
|
||||
} finally {
|
||||
// Main already publishes the result of a started stream. This also
|
||||
// settles failures/cancellation before a stream could start, and removes
|
||||
// a fallback row from all windows without changing a completed result.
|
||||
if (registrationStarted) {
|
||||
await bridge.finishPackedDownload?.(id, { status: finalStatus, error: finalError }).catch(() => {});
|
||||
}
|
||||
if (retained) await bridge.releaseSftpTransferSession?.(request.sftpId, id).catch(() => {});
|
||||
}
|
||||
});
|
||||
return outcome;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { MouseEvent as ReactMouseEvent } from "react";
|
||||
import { JSDOM } from "jsdom";
|
||||
import type { TransferTask } from "../../../types";
|
||||
|
||||
function setupDom() {
|
||||
const dom = new JSDOM("<!doctype html><html><body><div id=\"root\"></div></body></html>", {
|
||||
pretendToBeVisual: true,
|
||||
url: "http://localhost",
|
||||
});
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
"window",
|
||||
"document",
|
||||
"navigator",
|
||||
"HTMLElement",
|
||||
"Element",
|
||||
"Node",
|
||||
"CustomEvent",
|
||||
"Event",
|
||||
"MouseEvent",
|
||||
"StorageEvent",
|
||||
"DOMException",
|
||||
]) {
|
||||
install(key, key === "window" ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install("localStorage", dom.window.localStorage);
|
||||
install("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const makeTask = (id: string, overrides: Partial<TransferTask> = {}): TransferTask => ({
|
||||
id,
|
||||
fileName: `${id}.bin`,
|
||||
sourcePath: `/src/${id}.bin`,
|
||||
targetPath: `/dst/${id}.bin`,
|
||||
sourceConnectionId: "local",
|
||||
targetConnectionId: "remote-1",
|
||||
direction: "upload",
|
||||
status: "transferring",
|
||||
totalBytes: 1000,
|
||||
transferredBytes: 100,
|
||||
speed: 50,
|
||||
startTime: 1000,
|
||||
isDirectory: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("useSftpPaneSorting cleans up document drag listeners and pending rAF if unmounted mid-drag", async () => {
|
||||
const env = setupDom();
|
||||
const pendingRafs = new Map<number, FrameRequestCallback>();
|
||||
let nextRafId = 1;
|
||||
const cancelledRafIds: number[] = [];
|
||||
const origRaf = globalThis.requestAnimationFrame;
|
||||
const origCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
|
||||
const id = nextRafId++;
|
||||
pendingRafs.set(id, cb);
|
||||
return id;
|
||||
}) as typeof requestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = ((id: number) => {
|
||||
cancelledRafIds.push(id);
|
||||
pendingRafs.delete(id);
|
||||
}) as typeof cancelAnimationFrame;
|
||||
|
||||
let docMoveAdds = 0;
|
||||
let docMoveRemoves = 0;
|
||||
let docUpAdds = 0;
|
||||
let docUpRemoves = 0;
|
||||
const origDocAdd = document.addEventListener.bind(document);
|
||||
const origDocRemove = document.removeEventListener.bind(document);
|
||||
document.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
|
||||
if (type === "mousemove") docMoveAdds += 1;
|
||||
if (type === "mouseup") docUpAdds += 1;
|
||||
return origDocAdd(type, listener, options);
|
||||
}) as typeof document.addEventListener;
|
||||
document.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
|
||||
if (type === "mousemove") docMoveRemoves += 1;
|
||||
if (type === "mouseup") docUpRemoves += 1;
|
||||
return origDocRemove(type, listener, options);
|
||||
}) as typeof document.removeEventListener;
|
||||
|
||||
const { act } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useSftpPaneSorting } = await import("./useSftpPaneSorting");
|
||||
|
||||
let latestResult!: ReturnType<typeof useSftpPaneSorting>;
|
||||
function Harness() {
|
||||
latestResult = useSftpPaneSorting();
|
||||
return <div data-name-width={String(latestResult.columnWidths.name)} />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById("root")!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
|
||||
// 1. Normal drag updates width and cleans up listeners on mouseup.
|
||||
await act(async () => {
|
||||
latestResult.handleResizeStart("name", {
|
||||
preventDefault() {},
|
||||
stopPropagation() {},
|
||||
clientX: 100,
|
||||
} as unknown as ReactMouseEvent);
|
||||
});
|
||||
assert.equal(docMoveAdds, 1);
|
||||
assert.equal(docUpAdds, 1);
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 180 }));
|
||||
});
|
||||
assert.equal(pendingRafs.size, 1);
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mouseup"));
|
||||
});
|
||||
assert.equal(docMoveRemoves, 1);
|
||||
assert.equal(docUpRemoves, 1);
|
||||
assert.equal(pendingRafs.size, 0);
|
||||
assert.equal(latestResult.columnWidths.name, 60);
|
||||
|
||||
// 2. Unmounting mid-drag removes both document listeners and cancels pending rAF.
|
||||
await act(async () => {
|
||||
latestResult.handleResizeStart("name", {
|
||||
preventDefault() {},
|
||||
stopPropagation() {},
|
||||
clientX: 100,
|
||||
} as unknown as ReactMouseEvent);
|
||||
});
|
||||
assert.equal(docMoveAdds, 2);
|
||||
assert.equal(docUpAdds, 2);
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 200 }));
|
||||
});
|
||||
assert.equal(pendingRafs.size, 1);
|
||||
const queuedRafId = [...pendingRafs.keys()][0];
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
assert.equal(docMoveRemoves, 2);
|
||||
assert.equal(docUpRemoves, 2);
|
||||
assert.equal(pendingRafs.size, 0);
|
||||
assert.ok(cancelledRafIds.includes(queuedRafId));
|
||||
} finally {
|
||||
document.addEventListener = origDocAdd;
|
||||
document.removeEventListener = origDocRemove;
|
||||
globalThis.requestAnimationFrame = origRaf;
|
||||
globalThis.cancelAnimationFrame = origCancelRaf;
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("applyTransferProgressToRows returns same array for unknown taskId and single-slot copies matching rows while honoring pause latch", async () => {
|
||||
const { applyTransferProgressToRows } = await import("./useSftpTransfers");
|
||||
|
||||
const row1 = makeTask("task-1", { transferredBytes: 100, speed: 50 });
|
||||
const row2 = makeTask("task-2", { transferredBytes: 200, speed: 80 });
|
||||
const row3 = makeTask("task-3", { status: "paused", transferredBytes: 300, speed: 0 });
|
||||
const rows = [row1, row2, row3];
|
||||
|
||||
// Unknown taskId -> exact same array reference, zero cloning.
|
||||
const unchanged = applyTransferProgressToRows(rows, "missing-task", { transferredBytes: 999 }, () => false);
|
||||
assert.equal(unchanged, rows);
|
||||
|
||||
// Matching taskId -> shallow single-slot copy preserving untouched row references.
|
||||
const updated = applyTransferProgressToRows(rows, "task-2", { transferredBytes: 450, speed: 120 }, () => false);
|
||||
assert.notEqual(updated, rows);
|
||||
assert.equal(updated[0], row1);
|
||||
assert.equal(updated[2], row3);
|
||||
assert.notEqual(updated[1], row2);
|
||||
assert.equal(updated[1].transferredBytes, 450);
|
||||
assert.equal(updated[1].speed, 120);
|
||||
|
||||
// Stale "transferring" progress tick must not reopen a paused or latched row.
|
||||
const stillPaused = applyTransferProgressToRows(
|
||||
rows,
|
||||
"task-3",
|
||||
{ status: "transferring", transferredBytes: 320, speed: 90 },
|
||||
() => false,
|
||||
);
|
||||
assert.equal(stillPaused[2].status, "paused");
|
||||
assert.equal(stillPaused[2].speed, 0);
|
||||
assert.equal(stillPaused[2].transferredBytes, 320);
|
||||
|
||||
const latchedRow = applyTransferProgressToRows(
|
||||
rows,
|
||||
"task-1",
|
||||
{ status: "transferring", transferredBytes: 150, speed: 75 },
|
||||
(rootId, rowId) => rootId === "task-1" && rowId === "task-1",
|
||||
);
|
||||
assert.equal(latchedRow[0].status, "transferring");
|
||||
assert.equal(latchedRow[0].speed, 0);
|
||||
});
|
||||
@@ -19,6 +19,7 @@ const TERMINAL_STATUSES = new Set<TransferTask["status"]>(["completed", "failed"
|
||||
export interface CooperativeTransferHistoryRestoreResult {
|
||||
valid: boolean;
|
||||
tasks: TransferTask[];
|
||||
restoredPackedTaskIds: string[];
|
||||
}
|
||||
|
||||
function monotonicNow(): number {
|
||||
@@ -65,16 +66,19 @@ export async function restoreSftpTransferHistoryCooperatively(
|
||||
try {
|
||||
parsed = JSON.parse(raw) as { version?: unknown; tasks?: unknown };
|
||||
} catch {
|
||||
return { valid: false, tasks: [] };
|
||||
return { valid: false, tasks: [], restoredPackedTaskIds: [] };
|
||||
}
|
||||
if (parsed.version !== SFTP_TRANSFER_CENTER_VERSION || !Array.isArray(parsed.tasks)) {
|
||||
return { valid: false, tasks: [] };
|
||||
return { valid: false, tasks: [], restoredPackedTaskIds: [] };
|
||||
}
|
||||
|
||||
const maybeYield = createRestoreYieldController();
|
||||
const restored: TransferTask[] = [];
|
||||
const restoredPackedTaskIds: string[] = [];
|
||||
for (let index = 0; index < parsed.tasks.length; index += 1) {
|
||||
const task = sanitizeSftpTransferTask(parsed.tasks[index]);
|
||||
const task = sanitizeSftpTransferTask(parsed.tasks[index], {
|
||||
onRestoredPackedTask: (id) => restoredPackedTaskIds.push(id),
|
||||
});
|
||||
if (task) restored.push(task);
|
||||
await maybeYield(index);
|
||||
}
|
||||
@@ -201,5 +205,6 @@ export async function restoreSftpTransferHistoryCooperatively(
|
||||
return {
|
||||
valid: true,
|
||||
tasks: pruneSftpTransferHistory(compacted, now),
|
||||
restoredPackedTaskIds,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Host, KnownHost, SftpConnection, SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models";
|
||||
import { createNavHistory, type SftpNavHistory } from "../../../domain/sftpNavHistory";
|
||||
|
||||
export interface SftpPane {
|
||||
id: string;
|
||||
@@ -13,6 +14,7 @@ export interface SftpPane {
|
||||
filenameEncoding: SftpFilenameEncoding;
|
||||
showHiddenFiles: boolean;
|
||||
transferMutationToken: number;
|
||||
navHistory?: SftpNavHistory;
|
||||
}
|
||||
|
||||
export interface SftpHostKeyInfo {
|
||||
@@ -57,6 +59,7 @@ export const createEmptyPane = (
|
||||
filenameEncoding: "auto",
|
||||
showHiddenFiles,
|
||||
transferMutationToken: 0,
|
||||
navHistory: createNavHistory(),
|
||||
});
|
||||
|
||||
// File watch event types
|
||||
|
||||
@@ -9,7 +9,8 @@ import { useSftpDirectoryListing } from "./useSftpDirectoryListing";
|
||||
import { useSftpHostCredentials } from "./useSftpHostCredentials";
|
||||
import { buildCacheKey, getSharedRemoteHostCache, setSharedRemoteHostCache } from "./sharedRemoteHostCache";
|
||||
import { resolveRemoteSftpStartState } from "./sftpConnectStartPath";
|
||||
import { normalizeSftpPaneNavigationPath } from "./utils";
|
||||
import { isSameSftpPath, normalizeSftpPaneNavigationPath } from "./utils";
|
||||
import { createNavHistory, resolveSftpConnectNavHistory } from "../../../domain/sftpNavHistory";
|
||||
import {
|
||||
setDirectoryCacheEntry,
|
||||
type DirectoryListingCache,
|
||||
@@ -967,6 +968,12 @@ export const useSftpConnections = ({
|
||||
error: null,
|
||||
connectionLogs: [],
|
||||
filenameEncoding, // Reset encoding for new connection
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
|
||||
try {
|
||||
@@ -1039,6 +1046,7 @@ export const useSftpConnections = ({
|
||||
connectionLogs: [],
|
||||
files: isReconnectAttempt ? prev.files : (sharedHostCache?.files ?? []),
|
||||
filenameEncoding, // Reset encoding for new connection
|
||||
navHistory: sameEndpointReconnect ? prev.navHistory : createNavHistory(),
|
||||
}));
|
||||
|
||||
// Subscribe to SFTP connection progress events for auth logging
|
||||
@@ -1280,6 +1288,12 @@ export const useSftpConnections = ({
|
||||
loading: false,
|
||||
reconnecting: false,
|
||||
connectionLogs: [], // Clear after successful connect to avoid replay during navigation
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
} catch (err) {
|
||||
await settleFailedSftpConnectIfCurrent({
|
||||
|
||||
@@ -1,28 +1,6 @@
|
||||
import { useCallback } from "react";
|
||||
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings } from "../../../domain/models";
|
||||
import { isEncryptedCredentialPlaceholder, sanitizeCredentialValue } from "../../../domain/credentials";
|
||||
import { resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshAuth";
|
||||
import { resolveHostKeepalive } from "../../../domain/host";
|
||||
import { connectionTotpFields } from "../../../domain/totpConfig";
|
||||
import { resolveHostSshConnectionTimeouts } from "../../../domain/sshConnectionTimeouts";
|
||||
import {
|
||||
findIncompleteProxyIdentityId,
|
||||
findMissingProxyIdentityId,
|
||||
formatIncompleteProxyIdentityMessage,
|
||||
formatMissingProxyIdentityMessage,
|
||||
hasUnreadableProxyCredential,
|
||||
hasUsableProxyConfig,
|
||||
resolveProxyConfigAuth,
|
||||
} from "../../../domain/proxyProfiles";
|
||||
|
||||
// Fallback used when no global TerminalSettings are wired through (older
|
||||
// call sites or tests). Matches DEFAULT_TERMINAL_SETTINGS so behavior is
|
||||
// identical whether or not the caller passes settings.
|
||||
const FALLBACK_TERMINAL_SETTINGS = {
|
||||
verifyHostKeys: true,
|
||||
keepaliveInterval: 30,
|
||||
keepaliveCountMax: 10,
|
||||
};
|
||||
import { buildSshConnectionCredentials } from "../../../domain/sshConnectionCredentials";
|
||||
|
||||
interface UseSftpHostCredentialsParams {
|
||||
hosts: Host[];
|
||||
@@ -50,183 +28,19 @@ export const buildSftpHostCredentials = ({
|
||||
*/
|
||||
jumpHostsOverride?: Host[];
|
||||
}): NetcattySSHOptions => {
|
||||
const globalTerminalSettings = { ...FALLBACK_TERMINAL_SETTINGS, ...(terminalSettings ?? {}) };
|
||||
if (host.proxyProfileId && !host.proxyConfig) {
|
||||
throw new Error(`Saved proxy for host "${host.label || host.hostname}" is missing. Open host settings and select a valid proxy.`);
|
||||
}
|
||||
if (findMissingProxyIdentityId(host.proxyConfig, identities)) {
|
||||
throw new Error(formatMissingProxyIdentityMessage(host.label || host.hostname));
|
||||
}
|
||||
if (findIncompleteProxyIdentityId(host.proxyConfig, identities)) {
|
||||
throw new Error(formatIncompleteProxyIdentityMessage(host.label || host.hostname));
|
||||
}
|
||||
|
||||
const resolved = resolveHostAuth({ host, keys, identities });
|
||||
const key = resolved.key || null;
|
||||
|
||||
const proxyConfig = host.proxyConfig
|
||||
? resolveProxyConfigAuth(host.proxyConfig, identities)
|
||||
: undefined;
|
||||
let jumpHosts: NetcattyJumpHost[] | undefined;
|
||||
const resolveChainHost = (hostId: string): Host => {
|
||||
const jumpHost = hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!jumpHost) {
|
||||
throw new Error(`Jump host "${hostId}" is missing. Open host settings and repair the jump host chain.`);
|
||||
}
|
||||
return jumpHost;
|
||||
};
|
||||
// A non-empty pinned chain snapshot wins over live hostChain resolution.
|
||||
const chainHosts: Host[] | null = jumpHostsOverride && jumpHostsOverride.length > 0
|
||||
? jumpHostsOverride
|
||||
: host.hostChain?.hostIds && host.hostChain.hostIds.length > 0
|
||||
? host.hostChain.hostIds.map(resolveChainHost)
|
||||
: null;
|
||||
if (chainHosts) {
|
||||
jumpHosts = chainHosts.map((jumpHost, index) => {
|
||||
if (jumpHost.proxyProfileId && !jumpHost.proxyConfig) {
|
||||
throw new Error(`Saved proxy for jump host "${jumpHost.label || jumpHost.hostname}" is missing. Open host settings and select a valid proxy.`);
|
||||
}
|
||||
if (findMissingProxyIdentityId(jumpHost.proxyConfig, identities)) {
|
||||
throw new Error(formatMissingProxyIdentityMessage(jumpHost.label || jumpHost.hostname));
|
||||
}
|
||||
if (findIncompleteProxyIdentityId(jumpHost.proxyConfig, identities)) {
|
||||
throw new Error(formatIncompleteProxyIdentityMessage(jumpHost.label || jumpHost.hostname));
|
||||
}
|
||||
const jumpAuth = resolveHostAuth({
|
||||
host: jumpHost,
|
||||
keys,
|
||||
identities,
|
||||
});
|
||||
const jumpKey = jumpAuth.key;
|
||||
const jumpPassword = sanitizeCredentialValue(jumpAuth.password);
|
||||
const jumpKeyAuth = resolveBridgeKeyAuth({
|
||||
key: jumpKey,
|
||||
fallbackIdentityFilePaths: jumpAuth.authMethod === "password" || jumpAuth.keyId
|
||||
? undefined
|
||||
: jumpHost.identityFilePaths,
|
||||
passphrase: jumpAuth.passphrase,
|
||||
});
|
||||
const jumpAgentAuth = resolveBridgeSshAgentAuth(jumpHost, jumpKey, jumpAuth.authMethod);
|
||||
const hasJumpKeyMaterial = Boolean(
|
||||
jumpAgentAuth.useSshAgent || jumpKeyAuth.privateKey || jumpKeyAuth.identityFilePaths?.length,
|
||||
);
|
||||
const hasConfiguredJumpProxyEndpoint =
|
||||
index === 0 &&
|
||||
hasUsableProxyConfig(jumpHost.proxyConfig);
|
||||
if (
|
||||
hasConfiguredJumpProxyEndpoint &&
|
||||
hasUnreadableProxyCredential(jumpHost.proxyConfig, identities)
|
||||
) {
|
||||
throw new Error(`Proxy credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter the proxy password.`);
|
||||
}
|
||||
const hasUnreadableJumpCredential =
|
||||
isEncryptedCredentialPlaceholder(jumpAuth.password) ||
|
||||
isEncryptedCredentialPlaceholder(jumpKey?.privateKey) ||
|
||||
isEncryptedCredentialPlaceholder(jumpAuth.passphrase);
|
||||
if (
|
||||
(jumpAuth.authMethod === "password" && isEncryptedCredentialPlaceholder(jumpAuth.password) && !jumpPassword) ||
|
||||
(jumpAuth.authMethod !== "password" && jumpAuth.authMethod !== "auto" && hasUnreadableJumpCredential && !jumpPassword && !hasJumpKeyMaterial)
|
||||
) {
|
||||
throw new Error(`Saved credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter them.`);
|
||||
}
|
||||
const hopKeepalive = resolveHostKeepalive(jumpHost, globalTerminalSettings);
|
||||
const hopConnectionTimeouts = resolveHostSshConnectionTimeouts(jumpHost);
|
||||
return {
|
||||
hostname: jumpHost.hostname,
|
||||
hostId: jumpHost.id,
|
||||
port: jumpHost.port || 22,
|
||||
username: jumpAuth.username || "root",
|
||||
authMethod: jumpAuth.authMethod,
|
||||
requiresMfa: !!jumpHost.requiresMfa,
|
||||
password: jumpPassword,
|
||||
...connectionTotpFields(jumpHost),
|
||||
privateKey: jumpKeyAuth.privateKey,
|
||||
certificate: jumpKey?.certificate,
|
||||
passphrase: jumpKeyAuth.passphrase,
|
||||
publicKey: jumpKey?.publicKey,
|
||||
keyId: jumpAuth.keyId,
|
||||
keySource: jumpKey?.source,
|
||||
label: jumpHost.label,
|
||||
proxy: hasUsableProxyConfig(jumpHost.proxyConfig)
|
||||
? resolveProxyConfigAuth(jumpHost.proxyConfig, identities)
|
||||
: undefined,
|
||||
identityFilePaths: jumpKeyAuth.identityFilePaths,
|
||||
...jumpAgentAuth,
|
||||
keepaliveInterval: hopKeepalive.interval,
|
||||
keepaliveCountMax: hopKeepalive.countMax,
|
||||
sshTcpConnectTimeoutMs: hopConnectionTimeouts.tcpConnectTimeoutSeconds * 1000,
|
||||
sshAuthReadyTimeoutMs: hopConnectionTimeouts.authReadyTimeoutSeconds * 1000,
|
||||
verifyHostKeys: globalTerminalSettings.verifyHostKeys,
|
||||
legacyAlgorithms: jumpHost.legacyAlgorithms,
|
||||
skipEcdsaHostKey: jumpHost.skipEcdsaHostKey,
|
||||
algorithmOverrides: jumpHost.algorithms,
|
||||
};
|
||||
});
|
||||
}
|
||||
const usesTargetProxyForFirstHop = !!proxyConfig && !jumpHosts?.[0]?.proxy;
|
||||
if (usesTargetProxyForFirstHop && hasUnreadableProxyCredential(host.proxyConfig, identities)) {
|
||||
throw new Error("Proxy credentials cannot be decrypted on this device. Open host settings and re-enter the proxy password.");
|
||||
}
|
||||
|
||||
const keyAuth = resolveBridgeKeyAuth({
|
||||
key,
|
||||
fallbackIdentityFilePaths: resolved.authMethod === "password" || resolved.keyId
|
||||
? undefined
|
||||
: host.identityFilePaths,
|
||||
passphrase: resolved.passphrase,
|
||||
const sshCredentials = buildSshConnectionCredentials({
|
||||
host,
|
||||
hosts,
|
||||
keys,
|
||||
identities,
|
||||
knownHosts,
|
||||
terminalSettings,
|
||||
jumpHostsOverride,
|
||||
});
|
||||
const targetAgentAuth = resolveBridgeSshAgentAuth(host, key, resolved.authMethod);
|
||||
const password = sanitizeCredentialValue(resolved.password);
|
||||
const hasKeyMaterial = Boolean(
|
||||
targetAgentAuth.useSshAgent || keyAuth.privateKey || keyAuth.identityFilePaths?.length,
|
||||
);
|
||||
const hasUnreadableCredential =
|
||||
isEncryptedCredentialPlaceholder(resolved.password) ||
|
||||
isEncryptedCredentialPlaceholder(key?.privateKey) ||
|
||||
isEncryptedCredentialPlaceholder(resolved.passphrase);
|
||||
if (
|
||||
(resolved.authMethod === "password" && isEncryptedCredentialPlaceholder(resolved.password) && !password) ||
|
||||
(resolved.authMethod !== "password" && resolved.authMethod !== "auto" && hasUnreadableCredential && !password && !hasKeyMaterial)
|
||||
) {
|
||||
throw new Error("Saved credentials cannot be decrypted on this device. Open host settings and re-enter them.");
|
||||
}
|
||||
|
||||
const targetKeepalive = resolveHostKeepalive(host, globalTerminalSettings);
|
||||
const targetConnectionTimeouts = resolveHostSshConnectionTimeouts(host);
|
||||
return {
|
||||
hostname: host.hostname,
|
||||
hostId: host.id,
|
||||
username: resolved.username,
|
||||
authMethod: resolved.authMethod,
|
||||
requiresMfa: !!host.requiresMfa,
|
||||
port: host.port || 22,
|
||||
password,
|
||||
...connectionTotpFields(host),
|
||||
privateKey: keyAuth.privateKey,
|
||||
certificate: key?.certificate,
|
||||
passphrase: keyAuth.passphrase,
|
||||
publicKey: key?.publicKey,
|
||||
keyId: resolved.keyId,
|
||||
keySource: key?.source,
|
||||
proxy: proxyConfig,
|
||||
jumpHosts: jumpHosts && jumpHosts.length > 0 ? jumpHosts : undefined,
|
||||
...sshCredentials,
|
||||
sudo: host.sftpSudo,
|
||||
fileProtocol: host.sftpFileProtocol || "auto",
|
||||
identityFilePaths: keyAuth.identityFilePaths,
|
||||
...targetAgentAuth,
|
||||
keepaliveInterval: targetKeepalive.interval,
|
||||
keepaliveCountMax: targetKeepalive.countMax,
|
||||
sshTcpConnectTimeoutMs: targetConnectionTimeouts.tcpConnectTimeoutSeconds * 1000,
|
||||
sshAuthReadyTimeoutMs: targetConnectionTimeouts.authReadyTimeoutSeconds * 1000,
|
||||
knownHosts,
|
||||
verifyHostKeys: globalTerminalSettings.verifyHostKeys,
|
||||
// Algorithm settings — must reach the SFTP bridge or hosts that need
|
||||
// legacy mode / the ECDSA skip / advanced overrides would still hit
|
||||
// the original negotiation failure when opening their SFTP pane,
|
||||
// even though the terminal session works.
|
||||
legacyAlgorithms: host.legacyAlgorithms,
|
||||
skipEcdsaHostKey: host.skipEcdsaHostKey,
|
||||
algorithmOverrides: host.algorithms,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
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 "../../../domain/models";
|
||||
import {
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
createNavHistory,
|
||||
resolveSftpConnectNavHistory,
|
||||
} from "../../../domain/sftpNavHistory";
|
||||
import type { DirectoryListingCache } from "./directoryListingCache";
|
||||
import type { SftpPane } from "./types";
|
||||
import { useSftpPaneActions } from "./useSftpPaneActions";
|
||||
|
||||
function createConnectedPane(id: string, connectionId: string, initialPath: string, isLocal = false): SftpPane {
|
||||
return {
|
||||
id,
|
||||
connection: {
|
||||
id: connectionId,
|
||||
hostId: isLocal ? "local" : "host-1",
|
||||
hostLabel: isLocal ? "Local" : "Server",
|
||||
isLocal,
|
||||
status: "connected",
|
||||
currentPath: initialPath,
|
||||
homeDir: "/home/alice",
|
||||
},
|
||||
files: [],
|
||||
loading: false,
|
||||
reconnecting: false,
|
||||
error: null,
|
||||
connectionLogs: [],
|
||||
selectedFiles: new Set(),
|
||||
filter: "",
|
||||
filenameEncoding: "auto",
|
||||
showHiddenFiles: false,
|
||||
transferMutationToken: 0,
|
||||
navHistory: createNavHistory(initialPath),
|
||||
};
|
||||
}
|
||||
|
||||
function mountHarness(options?: {
|
||||
leftInitialPath?: string;
|
||||
rightInitialPath?: string;
|
||||
failingPaths?: Set<string>;
|
||||
dirCacheTtlMs?: number;
|
||||
listDir?: (dirPath: string) => Promise<SftpFileEntry[]>;
|
||||
}) {
|
||||
const previousActFlag = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const leftPane = createConnectedPane("tab-left", "conn-left", options?.leftInitialPath ?? "/home/alice", false);
|
||||
const rightPane = createConnectedPane("tab-right", "conn-right", options?.rightInitialPath ?? "/tmp", true);
|
||||
|
||||
const leftTabsRef = { current: { tabs: [leftPane], activeTabId: leftPane.id as string | null } };
|
||||
const rightTabsRef = { current: { tabs: [rightPane], activeTabId: rightPane.id as string | null } };
|
||||
const navSeqRef = { current: { left: 0, right: 0 } };
|
||||
const dirCacheRef = { current: new Map() as DirectoryListingCache };
|
||||
const sftpSessionsRef = { current: new Map<string, string>([["conn-left", "sftp-1"]]) };
|
||||
const lastConnectedHostRef = { current: { left: null, right: null } };
|
||||
const connectionCacheKeyMapRef = { current: new Map<string, string>() };
|
||||
const failingPaths = options?.failingPaths ?? new Set<string>();
|
||||
const listedPaths: string[] = [];
|
||||
|
||||
const getSideTabs = (side: "left" | "right") => (side === "left" ? leftTabsRef : rightTabsRef);
|
||||
const getActivePane = (side: "left" | "right"): SftpPane | null => {
|
||||
const ref = getSideTabs(side).current;
|
||||
return ref.tabs.find((tab) => tab.id === ref.activeTabId) ?? null;
|
||||
};
|
||||
const updateTab = (side: "left" | "right", tabId: string, updater: (pane: SftpPane) => SftpPane) => {
|
||||
const ref = getSideTabs(side);
|
||||
ref.current = {
|
||||
...ref.current,
|
||||
tabs: ref.current.tabs.map((tab) => (tab.id === tabId ? updater(tab) : tab)),
|
||||
};
|
||||
};
|
||||
const updateActiveTab = (side: "left" | "right", updater: (pane: SftpPane) => SftpPane) => {
|
||||
const activeTabId = getSideTabs(side).current.activeTabId;
|
||||
if (!activeTabId) return;
|
||||
updateTab(side, activeTabId, updater);
|
||||
};
|
||||
|
||||
const listDir = async (dirPath: string): Promise<SftpFileEntry[]> => {
|
||||
listedPaths.push(dirPath);
|
||||
if (options?.listDir) {
|
||||
return options.listDir(dirPath);
|
||||
}
|
||||
if (failingPaths.has(dirPath)) {
|
||||
throw new Error(`Permission denied: ${dirPath}`);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
let actions: ReturnType<typeof useSftpPaneActions> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
function Probe() {
|
||||
actions = useSftpPaneActions({
|
||||
hosts: [],
|
||||
getActivePane,
|
||||
updateTab,
|
||||
updateActiveTab,
|
||||
leftTabsRef,
|
||||
rightTabsRef,
|
||||
navSeqRef,
|
||||
dirCacheRef,
|
||||
sftpSessionsRef,
|
||||
lastConnectedHostRef,
|
||||
connectionCacheKeyMapRef,
|
||||
makeCacheKey: (connectionId, dirPath, encoding) => `${connectionId}::${encoding || "auto"}::${dirPath}`,
|
||||
clearCacheForConnection: (connectionId) => {
|
||||
for (const key of dirCacheRef.current.keys()) {
|
||||
if (key.startsWith(`${connectionId}::`)) dirCacheRef.current.delete(key);
|
||||
}
|
||||
},
|
||||
listLocalFiles: listDir,
|
||||
listRemoteFiles: (_sftpId, dirPath) => listDir(dirPath),
|
||||
handleSessionError: () => {},
|
||||
releaseConnection: async () => {},
|
||||
isSessionError: () => false,
|
||||
clearSelectionsExcept: () => {},
|
||||
dirCacheTtlMs: options?.dirCacheTtlMs ?? 10_000,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
get actions() {
|
||||
assert.ok(actions);
|
||||
return actions;
|
||||
},
|
||||
getPane: (side: "left" | "right") => {
|
||||
const pane = getActivePane(side);
|
||||
assert.ok(pane);
|
||||
return pane;
|
||||
},
|
||||
failingPaths,
|
||||
listedPaths,
|
||||
dirCacheRef,
|
||||
updateTab,
|
||||
render: async () => {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
},
|
||||
unmount: async () => {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
renderer = undefined;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousActFlag;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("useSftpPaneActions records navigations, traverses back/forward without duplicates, and truncates on branch", async () => {
|
||||
const harness = mountHarness();
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
// Navigating to the same current path is a no-op in history
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// navigateUp pushes parent directory onto history
|
||||
await harness.actions.navigateUp("left");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 3);
|
||||
|
||||
// Back moves pointer without pushing duplicates or clearing forward entries
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Refresh preserves forward stack
|
||||
await harness.actions.refresh("left");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Forward steps ahead without duplicating
|
||||
assert.equal(await harness.actions.navigateForward("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// New navigation from mid-stack truncates forward entries
|
||||
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/etc"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 3);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
|
||||
// Right pane history stays independent
|
||||
assert.deepEqual(harness.getPane("right").navHistory?.entries, ["/tmp"]);
|
||||
assert.equal(harness.getPane("right").navHistory?.index, 0);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSftpPaneActions preserves history pointer and forward stack when navigation fails", async () => {
|
||||
const failingPaths = new Set<string>(["/forbidden"]);
|
||||
// Disable cache hits so back/forward also exercises async failure rollback
|
||||
const harness = mountHarness({ failingPaths, dirCacheTtlMs: 0 });
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Failed normal navigation must NOT truncate forward entry (/var/log) or push /forbidden
|
||||
assert.equal(await harness.actions.navigateTo("left", "/forbidden"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Failed Back navigation must NOT decrement pointer
|
||||
harness.failingPaths.add("/home/alice");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Failed Forward navigation must NOT increment pointer
|
||||
harness.failingPaths.add("/var/log");
|
||||
assert.equal(await harness.actions.navigateForward("left"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Once /var/log is readable again, Forward still works cleanly
|
||||
harness.failingPaths.delete("/var/log");
|
||||
assert.equal(await harness.actions.navigateForward("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("host switch resets navigation history so previous host paths cannot be navigated via Back", async () => {
|
||||
const harness = mountHarness();
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Simulate switching connection on the same tab (sameEndpointReconnect = false)
|
||||
harness.updateTab("left", "tab-left", (prev) => ({
|
||||
...prev,
|
||||
connection: prev.connection
|
||||
? { ...prev.connection, id: "conn-host-2", hostId: "host-2", currentPath: "/srv/app" }
|
||||
: null,
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect: false,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath: "/srv/app",
|
||||
}),
|
||||
}));
|
||||
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/srv/app"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(await harness.actions.navigateBack("left"), "aborted");
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
function createDeferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
test("mid-flight refresh inherits pending push navigation and clears cleanly on settle or failure", async () => {
|
||||
const pendingLoads: Array<{ path: string; deferred: ReturnType<typeof createDeferred<SftpFileEntry[]>> }> = [];
|
||||
const harness = mountHarness({
|
||||
dirCacheTtlMs: 0,
|
||||
listDir: (dirPath) => {
|
||||
if (dirPath === "/slow" || dirPath === "/slow-fail") {
|
||||
const deferred = createDeferred<SftpFileEntry[]>();
|
||||
pendingLoads.push({ path: dirPath, deferred });
|
||||
return deferred.promise;
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
// Start slow navigation to /slow, then refresh mid-flight before /slow settles.
|
||||
const slowNavPromise = harness.actions.navigateTo("left", "/slow");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/slow");
|
||||
assert.equal(harness.getPane("left").loading, true);
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice"]);
|
||||
|
||||
const refreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
// Original slow navigation finishes first (superseded), then refresh settles.
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await slowNavPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await refreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/slow");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Back returns to /home/alice cleanly.
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
|
||||
// If a mid-flight refresh fails, currentPath reverts and history/forward stack stay intact.
|
||||
pendingLoads.length = 0;
|
||||
const failNavPromise = harness.actions.navigateTo("left", "/slow-fail");
|
||||
const failRefreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await failNavPromise, "superseded");
|
||||
pendingLoads[1].deferred.reject(new Error("I/O error"));
|
||||
await failRefreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("mid-flight refresh during Forward or Back advances history index consistently", async () => {
|
||||
const pendingLoads: Array<{ path: string; deferred: ReturnType<typeof createDeferred<SftpFileEntry[]>> }> = [];
|
||||
let interceptTarget: string | null = null;
|
||||
const harness = mountHarness({
|
||||
dirCacheTtlMs: 0,
|
||||
listDir: (dirPath) => {
|
||||
if (interceptTarget && dirPath === interceptTarget) {
|
||||
const deferred = createDeferred<SftpFileEntry[]>();
|
||||
pendingLoads.push({ path: dirPath, deferred });
|
||||
return deferred.promise;
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
// Build history: [/home/alice, /var, /var/log], then step Back to /var (index 1).
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Start Forward -> /var/log, then trigger Refresh before it finishes.
|
||||
interceptTarget = "/var/log";
|
||||
const forwardPromise = harness.actions.navigateForward("left");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
const refreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await forwardPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await refreshPromise;
|
||||
|
||||
// Displayed directory and history index must stay synchronized at /var/log (index 2).
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// Next Back must go to /var (NOT skip /var and jump to /home/alice).
|
||||
interceptTarget = "/var";
|
||||
pendingLoads.length = 0;
|
||||
const backPromise = harness.actions.navigateBack("left");
|
||||
const backRefreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await backPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await backRefreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), true);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
@@ -24,6 +24,15 @@ import {
|
||||
setDirectoryCacheEntry,
|
||||
type DirectoryListingCache,
|
||||
} from "./directoryListingCache";
|
||||
import {
|
||||
applySftpNavHistoryTransition,
|
||||
createNavHistory,
|
||||
goBack,
|
||||
goForward,
|
||||
resolveSftpEffectiveNavHistoryMode,
|
||||
type PendingSftpNavHistoryTransition,
|
||||
type SftpNavHistoryTransitionMode,
|
||||
} from "../../../domain/sftpNavHistory";
|
||||
|
||||
/** Shared empty set for navigation resets — never mutate this. */
|
||||
const EMPTY_SET = new Set<string>();
|
||||
@@ -58,10 +67,14 @@ export type SftpNavigateOptions = {
|
||||
shouldApply?: () => boolean;
|
||||
/** Restore the previous listing without showing a pane error. */
|
||||
quiet?: boolean;
|
||||
/** Controls how a successful navigation updates per-pane history. Defaults to "push". */
|
||||
historyMode?: SftpNavHistoryTransitionMode;
|
||||
};
|
||||
|
||||
interface UseSftpPaneActionsResult {
|
||||
navigateTo: (side: "left" | "right", path: string, options?: SftpNavigateOptions) => Promise<SftpNavigateResult>;
|
||||
navigateBack: (side: "left" | "right") => Promise<SftpNavigateResult>;
|
||||
navigateForward: (side: "left" | "right") => Promise<SftpNavigateResult>;
|
||||
refresh: (side: "left" | "right", options?: { tabId?: string }) => Promise<void>;
|
||||
navigateUp: (side: "left" | "right") => Promise<void>;
|
||||
openEntry: (side: "left" | "right", entry: SftpFileEntry) => Promise<void>;
|
||||
@@ -151,6 +164,12 @@ export const useSftpPaneActions = ({
|
||||
new Map<string, { connectionId: string; path: string; files: SftpFileEntry[]; selectedFiles: Set<string>; filter: string }>(),
|
||||
);
|
||||
|
||||
// Track the in-flight navigation history transition per tab so a mid-flight
|
||||
// refresh (historyMode: "none") targeting the same unconfirmed destination
|
||||
// inherits the pending transition instead of leaving currentPath and
|
||||
// navHistory out of sync.
|
||||
const pendingNavHistoryRef = useRef(new Map<string, PendingSftpNavHistoryTransition>());
|
||||
|
||||
const navigateTo = useCallback(
|
||||
async (
|
||||
side: "left" | "right",
|
||||
@@ -183,6 +202,14 @@ export const useSftpPaneActions = ({
|
||||
);
|
||||
|
||||
const connectionId = pane.connection.id;
|
||||
const requestedHistoryMode: SftpNavHistoryTransitionMode = options?.historyMode ?? "push";
|
||||
const historyMode = resolveSftpEffectiveNavHistoryMode({
|
||||
requestedMode: requestedHistoryMode,
|
||||
pending: pendingNavHistoryRef.current.get(targetTabId),
|
||||
connectionId,
|
||||
targetPath: normalizedPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
});
|
||||
const requestId = ++navSeqRef.current[side];
|
||||
const cacheKey = makeCacheKey(connectionId, normalizedPath, pane.filenameEncoding);
|
||||
const clearFilterForPathChange = shouldClearSftpFilterForPathChange(pane.connection.currentPath, normalizedPath);
|
||||
@@ -197,6 +224,7 @@ export const useSftpPaneActions = ({
|
||||
cached.files
|
||||
) {
|
||||
tabNavSeqRef.current.set(targetTabId, requestId);
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
lastConfirmedRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
@@ -214,6 +242,13 @@ export const useSftpPaneActions = ({
|
||||
error: null,
|
||||
selectedFiles: EMPTY_SET,
|
||||
filter: clearFilterForPathChange ? "" : prev.filter,
|
||||
navHistory: applySftpNavHistoryTransition({
|
||||
history: prev.navHistory,
|
||||
currentPath: prev.connection?.currentPath,
|
||||
targetPath: normalizedPath,
|
||||
mode: historyMode,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
if (!pane.connection.isLocal) {
|
||||
// Use hostId as the shared cache key — this is safe because the
|
||||
@@ -252,6 +287,11 @@ export const useSftpPaneActions = ({
|
||||
const previousFilter = confirmed.filter;
|
||||
const previousError = pane.error;
|
||||
const isTargetRequestCurrent = () => tabNavSeqRef.current.get(targetTabId) === requestId;
|
||||
const clearPendingNavHistoryIfCurrent = () => {
|
||||
if (isTargetRequestCurrent()) {
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
}
|
||||
};
|
||||
const getTargetPane = () => {
|
||||
const currentSideTabs = side === "left" ? leftTabsRef.current : rightTabsRef.current;
|
||||
return currentSideTabs.tabs.find((t) => t.id === targetTabId) ?? null;
|
||||
@@ -262,6 +302,7 @@ export const useSftpPaneActions = ({
|
||||
);
|
||||
const restoreConfirmedStateIfCurrent = () => {
|
||||
if (!isTargetRequestCurrent()) return;
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
updateTab(side, targetTabId, (prev) => {
|
||||
if (prev.connection?.id !== connectionId || !isTargetRequestCurrent()) return prev;
|
||||
return {
|
||||
@@ -276,6 +317,15 @@ export const useSftpPaneActions = ({
|
||||
});
|
||||
};
|
||||
tabNavSeqRef.current.set(targetTabId, requestId);
|
||||
if (historyMode !== "none") {
|
||||
pendingNavHistoryRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
mode: historyMode,
|
||||
});
|
||||
} else {
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
}
|
||||
// Keep existing files visible during loading — the loading overlay
|
||||
// (pointer-events-none) prevents interaction. This avoids blanking a tab
|
||||
// that gets superseded by another tab navigating on the same side.
|
||||
@@ -305,6 +355,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
clearCacheForConnection(pane.connection.id);
|
||||
// For background tabs (explicit tabId), update that tab directly
|
||||
// instead of handleSessionError which targets the active tab.
|
||||
@@ -331,6 +382,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
await releaseConnection(pane.connection.id);
|
||||
if (options?.tabId) {
|
||||
updateTab(side, targetTabId, (prev) => ({
|
||||
@@ -368,6 +420,8 @@ export const useSftpPaneActions = ({
|
||||
timestamp: Date.now(),
|
||||
}, { ttlMs: dirCacheTtlMs });
|
||||
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
|
||||
lastConfirmedRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
@@ -385,6 +439,13 @@ export const useSftpPaneActions = ({
|
||||
loading: false,
|
||||
selectedFiles: EMPTY_SET,
|
||||
filter: clearFilterForPathChange ? "" : prev.filter,
|
||||
navHistory: applySftpNavHistoryTransition({
|
||||
history: prev.navHistory,
|
||||
currentPath: previousPath,
|
||||
targetPath: normalizedPath,
|
||||
mode: historyMode,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
if (!pane.connection.isLocal) {
|
||||
setSharedRemoteHostCache(getActivePaneCacheKey(side, pane.connection.hostId, pane.connection.id), {
|
||||
@@ -407,6 +468,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
let navigationFailed = false;
|
||||
updateTab(side, targetTabId, (prev) => {
|
||||
if (prev.connection?.id !== connectionId) {
|
||||
@@ -480,7 +542,11 @@ export const useSftpPaneActions = ({
|
||||
}
|
||||
return;
|
||||
}
|
||||
await navigateTo(side, pane.connection.currentPath, { force: true, tabId: options?.tabId });
|
||||
await navigateTo(side, pane.connection.currentPath, {
|
||||
force: true,
|
||||
tabId: options?.tabId,
|
||||
historyMode: "none",
|
||||
});
|
||||
} else if (!pane?.connection && pane?.error) {
|
||||
// For background tabs, don't trigger reconnection (it operates on
|
||||
// the active tab). Just leave the error state for the user to see
|
||||
@@ -504,6 +570,30 @@ export const useSftpPaneActions = ({
|
||||
[getActivePane, leftTabsRef, rightTabsRef, navigateTo, updateActiveTab, lastConnectedHostRef, sftpSessionsRef],
|
||||
);
|
||||
|
||||
const navigateBack = useCallback(
|
||||
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
|
||||
const pane = getActivePane(side);
|
||||
if (!pane?.connection) return "aborted";
|
||||
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
|
||||
const step = goBack(history);
|
||||
if (!step.path) return "aborted";
|
||||
return navigateTo(side, step.path, { historyMode: "back" });
|
||||
},
|
||||
[getActivePane, navigateTo],
|
||||
);
|
||||
|
||||
const navigateForward = useCallback(
|
||||
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
|
||||
const pane = getActivePane(side);
|
||||
if (!pane?.connection) return "aborted";
|
||||
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
|
||||
const step = goForward(history);
|
||||
if (!step.path) return "aborted";
|
||||
return navigateTo(side, step.path, { historyMode: "forward" });
|
||||
},
|
||||
[getActivePane, navigateTo],
|
||||
);
|
||||
|
||||
const navigateUp = useCallback(
|
||||
async (side: "left" | "right") => {
|
||||
const pane = getActivePane(side);
|
||||
@@ -1060,6 +1150,8 @@ export const useSftpPaneActions = ({
|
||||
|
||||
return {
|
||||
navigateTo,
|
||||
navigateBack,
|
||||
navigateForward,
|
||||
refresh,
|
||||
navigateUp,
|
||||
openEntry,
|
||||
|
||||
@@ -98,6 +98,7 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
|
||||
const rafIdRef = useRef<number | null>(null);
|
||||
const lastClientXRef = useRef(0);
|
||||
const activeDragCleanupRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const applyColumnWidth = useCallback(() => {
|
||||
if (!resizingRef.current) return;
|
||||
@@ -121,6 +122,20 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const cleanupActiveResize = useCallback(() => {
|
||||
if (rafIdRef.current !== null) {
|
||||
cancelAnimationFrame(rafIdRef.current);
|
||||
rafIdRef.current = null;
|
||||
}
|
||||
resizingRef.current = null;
|
||||
activeDragCleanupRef.current?.();
|
||||
activeDragCleanupRef.current = null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => {
|
||||
cleanupActiveResize();
|
||||
}, [cleanupActiveResize]);
|
||||
|
||||
const handleResizeMove = useCallback((e: MouseEvent) => {
|
||||
if (!resizingRef.current) return;
|
||||
lastClientXRef.current = e.clientX;
|
||||
@@ -132,13 +147,15 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
}, [applyColumnWidth]);
|
||||
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current);
|
||||
if (rafIdRef.current !== null) {
|
||||
cancelAnimationFrame(rafIdRef.current);
|
||||
rafIdRef.current = null;
|
||||
}
|
||||
applyColumnWidth();
|
||||
rafIdRef.current = null;
|
||||
resizingRef.current = null;
|
||||
document.removeEventListener("mousemove", handleResizeMove);
|
||||
document.removeEventListener("mouseup", handleResizeEnd);
|
||||
}, [applyColumnWidth, handleResizeMove]);
|
||||
activeDragCleanupRef.current?.();
|
||||
activeDragCleanupRef.current = null;
|
||||
}, [applyColumnWidth]);
|
||||
|
||||
const handleResizeStart = (
|
||||
field: keyof ColumnWidths,
|
||||
@@ -146,6 +163,7 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
cleanupActiveResize();
|
||||
lastClientXRef.current = e.clientX;
|
||||
resizingRef.current = {
|
||||
field,
|
||||
@@ -154,6 +172,10 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
};
|
||||
document.addEventListener("mousemove", handleResizeMove);
|
||||
document.addEventListener("mouseup", handleResizeEnd);
|
||||
activeDragCleanupRef.current = () => {
|
||||
document.removeEventListener("mousemove", handleResizeMove);
|
||||
document.removeEventListener("mouseup", handleResizeEnd);
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from "./transferPauseLatch";
|
||||
import { bumpTransferControlEpoch } from "./transferControlEpoch";
|
||||
import { transferRuntime } from "./transferRuntime";
|
||||
import { runPackedDownload } from "./packedDownload";
|
||||
import {
|
||||
clearTransferCancelled,
|
||||
clearTransferCancelledTree,
|
||||
@@ -331,6 +332,28 @@ function notifyPathConflict(
|
||||
notify.warning(message, t("sftp.transfers.pathConflict.title"));
|
||||
}
|
||||
|
||||
export function applyTransferProgressToRows(
|
||||
rows: TransferTask[],
|
||||
taskId: string,
|
||||
updates: Partial<TransferTask>,
|
||||
isLatched: (rootId: string, rowId: string) => boolean = isTransferOrRootPauseLatched,
|
||||
): TransferTask[] {
|
||||
const index = rows.findIndex((row) => row.id === taskId);
|
||||
if (index === -1) return rows;
|
||||
const row = rows[index];
|
||||
const merged = { ...row, ...updates };
|
||||
const latched = isLatched(row.parentTaskId ?? row.id, row.id);
|
||||
const nextRow = (
|
||||
(latched || row.status === "paused" || row.status === "pausing")
|
||||
&& (updates.status === "transferring" || updates.status === "pending" || updates.status === "queued")
|
||||
)
|
||||
? { ...merged, status: row.status, speed: 0 }
|
||||
: merged;
|
||||
const next = rows.slice();
|
||||
next[index] = nextRow;
|
||||
return next;
|
||||
}
|
||||
|
||||
export const useSftpTransfers = ({
|
||||
ownerId,
|
||||
canPrepareAdoption,
|
||||
@@ -510,18 +533,7 @@ export const useSftpTransfers = ({
|
||||
pendingProgressByIdRef.current.set(taskId, { ...prevPending, ...updates });
|
||||
// Keep ref hot for cancel/pause checks without waiting for paint.
|
||||
// A byte tick that still says "transferring" must not reopen a latched pause.
|
||||
transfersRef.current = transfersRef.current.map((row) => {
|
||||
if (row.id !== taskId) return row;
|
||||
const merged = { ...row, ...updates };
|
||||
const latched = isTransferOrRootPauseLatched(row.parentTaskId ?? row.id, row.id);
|
||||
if (
|
||||
(latched || row.status === "paused" || row.status === "pausing")
|
||||
&& (updates.status === "transferring" || updates.status === "pending" || updates.status === "queued")
|
||||
) {
|
||||
return { ...merged, status: row.status, speed: 0 };
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
transfersRef.current = applyTransferProgressToRows(transfersRef.current, taskId, updates);
|
||||
scheduleProgressFlush();
|
||||
}, [scheduleProgressFlush]);
|
||||
useEffect(() => () => {
|
||||
@@ -655,6 +667,7 @@ export const useSftpTransfers = ({
|
||||
}, [getActivePane, getTabByConnectionId]);
|
||||
|
||||
const cleanupTaskArtifacts = useCallback(async (task: TransferTask) => {
|
||||
if (task.controlKind === "packed-download") return; // Backend owns its private staging directory.
|
||||
const endpoints = resolveTaskEndpoints(task);
|
||||
const targetPane = endpoints?.targetPane;
|
||||
const targetSftpId = targetPane?.connection && !targetPane.connection.isLocal
|
||||
@@ -2268,6 +2281,11 @@ export const useSftpTransfers = ({
|
||||
&& ["pending", "queued", "transferring", "pausing"].includes(t.status),
|
||||
).length, [transfers]);
|
||||
|
||||
const tryPackedDownload = useCallback<UseSftpTransfersResult["tryPackedDownload"]>(
|
||||
(request) => runPackedDownload(ownerId, request),
|
||||
[ownerId],
|
||||
);
|
||||
|
||||
const downloadToLocal = useCallback(
|
||||
async (params: {
|
||||
fileName: string;
|
||||
@@ -2634,6 +2652,7 @@ export const useSftpTransfers = ({
|
||||
activeTransfersCount,
|
||||
startTransfer,
|
||||
downloadToLocal,
|
||||
tryPackedDownload,
|
||||
cancelTransfer: transferRuntime.cancel,
|
||||
// Single process-level control surface (TransferRuntime).
|
||||
pauseTransfer: async (transferId: string) => {
|
||||
|
||||
@@ -3,6 +3,20 @@ import type { Host, FileConflict, FileConflictAction, SftpFileEntry, SftpFilenam
|
||||
import type { SftpPane } from "./types";
|
||||
import type { AcquireTransferSessionFn } from "./transferDirectoryOps";
|
||||
|
||||
export interface PackedDownloadRequest {
|
||||
fileName: string;
|
||||
remoteDirectory: string;
|
||||
names: string[];
|
||||
localDirectory: string;
|
||||
sftpId: string;
|
||||
connectionId: string;
|
||||
sourceHostId: string;
|
||||
sourceHostLabel: string;
|
||||
sourceEncoding?: SftpFilenameEncoding;
|
||||
}
|
||||
|
||||
export type PackedDownloadStatus = "completed" | "regular" | "unsupported" | "conflict" | "cancelled";
|
||||
|
||||
export interface UseSftpTransfersParams {
|
||||
ownerId: string;
|
||||
canPrepareAdoption?: boolean;
|
||||
@@ -53,6 +67,7 @@ export interface UseSftpTransfersResult {
|
||||
onTransferComplete?: (result: TransferResult) => void | Promise<void>;
|
||||
},
|
||||
) => Promise<TransferResult[]>;
|
||||
tryPackedDownload: (request: PackedDownloadRequest) => Promise<PackedDownloadStatus>;
|
||||
downloadToLocal: (params: {
|
||||
fileName: string;
|
||||
sourcePath: string;
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { createRequire } from "node:module";
|
||||
import type { TransferTask } from "../../domain/models";
|
||||
import { findActivePathConflict } from "../../domain/sftpTransferConflicts";
|
||||
import { deserializeSftpTransferCenter, serializeSftpTransferCenter } from "../../domain/sftpTransferCenter";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import { createSftpTransferCenterStore } from "./sftpTransferCenterStore";
|
||||
import { createTransferRuntime } from "./sftp/transferRuntime";
|
||||
import { isTransferPauseLatched } from "./sftp/transferPauseLatch";
|
||||
import { isTransferCancelledFlag } from "./sftp/transferCancelLatch";
|
||||
import { globalSftpTransferScheduler } from "./sftp/globalTransferScheduler";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { createPackedDownloadLifecycle } = require("../../electron/bridges/sftpBridge/packedDownloadLifecycle.cjs");
|
||||
|
||||
const makePackedTask = (id: string, status: TransferTask["status"] = "transferring"): TransferTask => ({
|
||||
id, fileName: "2 selected", sourcePath: "/srv", targetPath: "/downloads",
|
||||
sourceConnectionId: "captured-session", targetConnectionId: "local", sourceHostId: "host",
|
||||
packedTargetPaths: ["/downloads/compose", "/downloads/README.md"],
|
||||
direction: "download", status, totalBytes: 0, transferredBytes: 0, speed: 0,
|
||||
startTime: 1, isDirectory: true, controlKind: "packed-download", resumable: false, retryable: false,
|
||||
});
|
||||
|
||||
test("pause then packed completion then resume cannot replay the common parent", async () => {
|
||||
const store = createSftpTransferCenterStore();
|
||||
const runtime = createTransferRuntime(store);
|
||||
const task = makePackedTask("packed-completion-race");
|
||||
let finish!: () => void;
|
||||
const completed = new Promise<void>((resolve) => { finish = resolve; });
|
||||
let dedicatedCalls = 0;
|
||||
store.setDedicatedResumeHandler(async () => { dedicatedCalls++; return { success: true }; });
|
||||
runtime.enqueue([task]);
|
||||
const running = runtime.runWalk(task.id, async () => {
|
||||
await completed;
|
||||
runtime.patchTask(task.id, { status: "completed", transferredBytes: 128, totalBytes: 128, endTime: Date.now() });
|
||||
});
|
||||
try {
|
||||
await store.pause(task.id);
|
||||
assert.equal(store.getTask(task.id)?.status, "transferring");
|
||||
assert.equal(isTransferPauseLatched(task.id), false);
|
||||
finish();
|
||||
await running;
|
||||
assert.equal(runtime.isWalkInFlight(task.id), false);
|
||||
await store.resume(task.id);
|
||||
await store.retry(task.id);
|
||||
assert.equal(store.getTask(task.id)?.status, "completed");
|
||||
assert.equal(store.getTask(task.id)?.transferredBytes, 128);
|
||||
assert.equal(dedicatedCalls, 0, "the display-only /srv parent must never be resumed recursively");
|
||||
assert.equal(store.isResuming(task.id), false);
|
||||
} finally {
|
||||
finish();
|
||||
await running;
|
||||
store.dismiss(task.id);
|
||||
}
|
||||
});
|
||||
|
||||
for (const status of ["queued", "transferring", "paused", "interrupted", "attention", "failed", "cancelled"] as const) {
|
||||
test(`programmatic controls cannot pause/resume/retry a ${status} packed task`, async (t) => {
|
||||
const store = createSftpTransferCenterStore();
|
||||
const task = { ...makePackedTask(`packed-${status}`, status), resumable: true, retryable: true };
|
||||
store.upsertTasks([task]);
|
||||
store.setDedicatedResumeHandler(async () => { assert.fail("dedicated replay is not supported"); });
|
||||
store.registerOwner("packed-owner", {
|
||||
pause: async () => { assert.fail("owner pause is not supported"); },
|
||||
resume: async () => { assert.fail("owner resume is not supported"); },
|
||||
retry: async () => { assert.fail("owner retry is not supported"); },
|
||||
cancel: async () => {}, prioritize: async () => {}, dismiss: () => {},
|
||||
});
|
||||
store.patchTask(task.id, { ownerId: "packed-owner" });
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
clearPendingTransferCancel: async () => { assert.fail("controls must not mutate backend cancellation"); },
|
||||
cleanupTransferArtifacts: async () => { assert.fail("generic retry must not clean a packed destination"); },
|
||||
}));
|
||||
await store.pause(task.id);
|
||||
await store.resume(task.id);
|
||||
await store.retry(task.id);
|
||||
assert.equal(store.getTask(task.id)?.status, status);
|
||||
assert.equal(isTransferPauseLatched(task.id), false);
|
||||
assert.equal(store.isResuming(task.id), false);
|
||||
});
|
||||
}
|
||||
|
||||
const queuedEvent = (id: string) => ({
|
||||
type: "queued" as const, transferId: id, controlKind: "packed-download" as const,
|
||||
fileName: "2 selected", direction: "download" as const, isDirectory: true,
|
||||
sourcePath: "/srv", targetPath: "/downloads", sourceConnectionId: "captured-session",
|
||||
sourceHostId: "host", sourceHostLabel: "Server", origin: "manual" as const,
|
||||
packedTargetPaths: ["/downloads/compose", "/downloads/README.md"],
|
||||
});
|
||||
|
||||
test("other windows preserve packed selection metadata, progress and terminal state", async () => {
|
||||
const store = createSftpTransferCenterStore();
|
||||
const event = queuedEvent("packed-other-window");
|
||||
store.ingestBackgroundEvent(event);
|
||||
const queued = store.getTask(event.transferId)!;
|
||||
assert.equal(queued.ownerId, "background-transfer");
|
||||
assert.equal(queued.sourceConnectionId, "captured-session");
|
||||
assert.equal(queued.sourceHostLabel, "Server");
|
||||
assert.equal(queued.origin, "manual");
|
||||
assert.equal(queued.progressMode, "bytes");
|
||||
assert.equal(queued.resumable, false);
|
||||
assert.equal(queued.retryable, false);
|
||||
assert.deepEqual(queued.packedTargetPaths, event.packedTargetPaths);
|
||||
assert.equal(findActivePathConflict([queued], { id: "other", targetConnectionId: "local", targetPath: "/downloads/compose/config" })?.id, queued.id);
|
||||
assert.equal(findActivePathConflict([queued], { id: "other", targetConnectionId: "local", targetPath: "/downloads/unselected" }), undefined);
|
||||
store.ingestBackgroundEvent({ ...event, type: "started" });
|
||||
store.ingestBackgroundEvent({ ...event, type: "progress", phase: "extracting", transferred: 256 });
|
||||
assert.equal(store.getTask(queued.id)?.phase, "extracting");
|
||||
assert.equal(store.getTask(queued.id)?.transferredBytes, 256);
|
||||
await store.pause(queued.id);
|
||||
assert.equal(store.getTask(queued.id)?.status, "transferring");
|
||||
store.ingestBackgroundEvent({ ...event, type: "completed", transferred: 256, totalBytes: 256 });
|
||||
assert.equal(store.getTask(queued.id)?.status, "completed");
|
||||
assert.equal(store.getTask(queued.id)?.phase, undefined);
|
||||
});
|
||||
|
||||
test("packed event echo preserves the local owner and fallback dismisses all reservations", () => {
|
||||
const store = createSftpTransferCenterStore();
|
||||
const task = { ...makePackedTask("packed-local-echo", "queued"), ownerId: "original-panel" };
|
||||
store.upsertTasks([task]);
|
||||
store.ingestBackgroundEvent(queuedEvent(task.id));
|
||||
assert.equal(store.getTask(task.id)?.ownerId, "original-panel");
|
||||
store.ingestBackgroundEvent({ type: "dismissed", transferId: task.id });
|
||||
assert.equal(store.getTask(task.id), undefined);
|
||||
});
|
||||
|
||||
for (const terminal of ["cancelled", "failed"] as const) {
|
||||
test(`a globally ${terminal} queued packed job cannot start`, async () => {
|
||||
const store = createSftpTransferCenterStore();
|
||||
const runtime = createTransferRuntime(store);
|
||||
const task = makePackedTask(`packed-queued-${terminal}`, "queued");
|
||||
const resource = `packed-queued-${terminal}-resource`;
|
||||
let unblock!: () => void;
|
||||
let started!: () => void;
|
||||
const blockerStarted = new Promise<void>((resolve) => { started = resolve; });
|
||||
const blocker = globalSftpTransferScheduler.run("blocker", "packed-blocker", [resource], () => 1, async () => {
|
||||
started();
|
||||
await new Promise<void>((resolve) => { unblock = resolve; });
|
||||
});
|
||||
await blockerStarted;
|
||||
runtime.enqueue([task]);
|
||||
let backendCalls = 0;
|
||||
const running = runtime.runWalk(task.id, async () => {
|
||||
await assert.rejects(globalSftpTransferScheduler.run("owner", task.id, [resource], () => 1, async () => {
|
||||
backendCalls++;
|
||||
}), /Transfer cancelled/);
|
||||
assert.equal(isTransferCancelledFlag(task.id), true, "owner keeps cancellation until its walk settles");
|
||||
});
|
||||
try {
|
||||
store.ingestBackgroundEvent({ type: terminal, transferId: task.id, controlKind: "packed-download", error: terminal === "failed" ? "Worker exited" : undefined });
|
||||
await running;
|
||||
assert.equal(store.getTask(task.id)?.status, terminal);
|
||||
if (terminal === "failed") assert.equal(store.getTask(task.id)?.error, "Worker exited");
|
||||
assert.equal(backendCalls, 0);
|
||||
assert.equal(isTransferCancelledFlag(task.id), false, "settled walks release their cancellation flag");
|
||||
} finally {
|
||||
unblock();
|
||||
await blocker;
|
||||
await running;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("a mirrored transfer-center Cancel reaches the original window's packed stream", async (t) => {
|
||||
const ownerStore = createSftpTransferCenterStore();
|
||||
const otherWindowStore = createSftpTransferCenterStore();
|
||||
const runtime = createTransferRuntime(ownerStore);
|
||||
const task = { ...makePackedTask("packed-mirror-cancel", "queued"), ownerId: "detached-pane" };
|
||||
const sender = Object.assign(new EventEmitter(), { id: 41, isDestroyed: () => false, send() {} });
|
||||
const ownerEvent = { sender };
|
||||
let started!: () => void;
|
||||
const streamStarted = new Promise<void>((resolve) => { started = resolve; });
|
||||
let finish!: (value: { status: "cancelled" }) => void;
|
||||
const stream = new Promise<{ status: "cancelled" }>((resolve) => { finish = resolve; });
|
||||
const routedTo: number[] = [];
|
||||
const lifecycle = createPackedDownloadLifecycle({
|
||||
broadcast(event: Parameters<typeof ownerStore.ingestBackgroundEvent>[0]) {
|
||||
ownerStore.ingestBackgroundEvent(event);
|
||||
otherWindowStore.ingestBackgroundEvent(event);
|
||||
},
|
||||
async cancel(event: { sender: { id: number } }, id: string) {
|
||||
assert.equal(id, task.id);
|
||||
routedTo.push(event.sender.id);
|
||||
finish({ status: "cancelled" });
|
||||
return { success: true };
|
||||
},
|
||||
});
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
cancelTransfer: (id: string) => lifecycle.cancel(id),
|
||||
cleanupTransferArtifacts: async () => { assert.fail("packed cancellation must not run generic destination cleanup"); },
|
||||
}));
|
||||
runtime.enqueue([task]);
|
||||
lifecycle.register(ownerEvent, { ...queuedEvent(task.id) });
|
||||
const running = runtime.runWalk(task.id, async () => {
|
||||
const result = await lifecycle.run(ownerEvent, {
|
||||
transferId: task.id, names: ["compose", "README.md"], remoteDirectory: "/srv", localDirectory: "/downloads",
|
||||
}, async () => { started(); return stream; });
|
||||
assert.equal(result.status, "cancelled");
|
||||
});
|
||||
try {
|
||||
await streamStarted;
|
||||
assert.equal(otherWindowStore.getTask(task.id)?.ownerId, "background-transfer");
|
||||
await otherWindowStore.cancel(task.id);
|
||||
await running;
|
||||
assert.deepEqual(routedTo, [41], "main routes the mirrored cancel to the captured owner");
|
||||
assert.equal(ownerStore.getTask(task.id)?.status, "cancelled");
|
||||
assert.equal(otherWindowStore.getTask(task.id)?.status, "cancelled");
|
||||
assert.equal(lifecycle.has(task.id), false);
|
||||
assert.equal(sender.listenerCount("destroyed"), 0);
|
||||
} finally {
|
||||
finish({ status: "cancelled" });
|
||||
await running;
|
||||
}
|
||||
});
|
||||
|
||||
test("serialization preserves live packed state so a reloaded window tracks progress, cancels, and completes", async (t) => {
|
||||
let persisted = "";
|
||||
const ownerStore = createSftpTransferCenterStore({
|
||||
read: () => persisted || null,
|
||||
write: (value) => { persisted = value; },
|
||||
});
|
||||
const now = Date.now();
|
||||
const liveTask: TransferTask = {
|
||||
...makePackedTask("packed-live-reload", "transferring"),
|
||||
startTime: now - 1000,
|
||||
ownerId: "detached-pane",
|
||||
phase: "transferring",
|
||||
transferredBytes: 64,
|
||||
};
|
||||
const alreadyCancelled: TransferTask = {
|
||||
...makePackedTask("packed-user-cancelled", "cancelled"),
|
||||
startTime: now - 2000,
|
||||
ownerId: "detached-pane",
|
||||
endTime: now - 500,
|
||||
};
|
||||
ownerStore.upsertTasks([liveTask, alreadyCancelled]);
|
||||
// Verify the serialized snapshot preserves live status, phase, and packedTargetPaths.
|
||||
const serialized = serializeSftpTransferCenter(ownerStore.getSnapshot().tasks);
|
||||
const parsed = JSON.parse(serialized) as { tasks: TransferTask[] };
|
||||
const serializedLive = parsed.tasks.find((row) => row.id === liveTask.id);
|
||||
assert.equal(serializedLive?.status, "transferring");
|
||||
assert.equal(serializedLive?.phase, "transferring");
|
||||
assert.deepEqual(serializedLive?.packedTargetPaths, liveTask.packedTargetPaths);
|
||||
|
||||
// Process restart (no live events) still restores unfinished packed tasks as cancelled.
|
||||
const afterRestart = deserializeSftpTransferCenter(serialized);
|
||||
assert.equal(afterRestart.tasks.find((row) => row.id === liveTask.id)?.status, "cancelled");
|
||||
assert.deepEqual(afterRestart.tasks.find((row) => row.id === liveTask.id)?.packedTargetPaths, liveTask.packedTargetPaths);
|
||||
|
||||
// A new/reloaded non-owner window hydrates from the serialized snapshot while
|
||||
// the owner transfer is still running, then receives live global events and cancels.
|
||||
const reloadedWindow = createSftpTransferCenterStore({
|
||||
read: () => serialized,
|
||||
write: () => {},
|
||||
});
|
||||
assert.equal(reloadedWindow.getTask(liveTask.id)?.status, "cancelled");
|
||||
reloadedWindow.ingestBackgroundEvent({
|
||||
...queuedEvent(liveTask.id),
|
||||
type: "progress",
|
||||
phase: "extracting",
|
||||
transferred: 256,
|
||||
});
|
||||
const revived = reloadedWindow.getTask(liveTask.id)!;
|
||||
assert.equal(revived.status, "transferring");
|
||||
assert.equal(revived.phase, "extracting");
|
||||
assert.equal(revived.transferredBytes, 256);
|
||||
assert.equal(revived.ownerId, "background-transfer");
|
||||
assert.deepEqual(revived.packedTargetPaths, liveTask.packedTargetPaths);
|
||||
assert.equal(
|
||||
findActivePathConflict(reloadedWindow.getSnapshot().tasks, {
|
||||
id: "other", targetConnectionId: "local", targetPath: "/downloads/compose/sub",
|
||||
})?.id,
|
||||
liveTask.id,
|
||||
);
|
||||
|
||||
// A genuinely cancelled packed task must never be revived by late events.
|
||||
reloadedWindow.ingestBackgroundEvent({
|
||||
...queuedEvent(alreadyCancelled.id),
|
||||
type: "progress",
|
||||
phase: "transferring",
|
||||
transferred: 128,
|
||||
});
|
||||
assert.equal(reloadedWindow.getTask(alreadyCancelled.id)?.status, "cancelled");
|
||||
|
||||
// Reloaded window can cancel the revived running transfer.
|
||||
const cancelCalls: string[] = [];
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
cancelTransfer: async (id: string) => { cancelCalls.push(id); return { success: true }; },
|
||||
}));
|
||||
await reloadedWindow.cancel(liveTask.id);
|
||||
assert.deepEqual(cancelCalls, [liveTask.id]);
|
||||
|
||||
// Also verify direct completion without an intermediate progress event revives to completed.
|
||||
const completingWindow = createSftpTransferCenterStore({
|
||||
read: () => serialized,
|
||||
write: () => {},
|
||||
});
|
||||
completingWindow.ingestBackgroundEvent({
|
||||
...queuedEvent(liveTask.id),
|
||||
type: "completed",
|
||||
transferred: 512,
|
||||
totalBytes: 512,
|
||||
});
|
||||
assert.equal(completingWindow.getTask(liveTask.id)?.status, "completed");
|
||||
assert.equal(completingWindow.getTask(liveTask.id)?.transferredBytes, 512);
|
||||
});
|
||||
@@ -143,12 +143,17 @@ export interface SftpTransferCenterStore {
|
||||
markReconnectRequired(taskId: string, error?: string): void;
|
||||
reportResumePreparationFailure(taskId: string, error: string): void;
|
||||
ingestBackgroundEvent(event: {
|
||||
type: "queued" | "started" | "progress" | "pausing" | "paused" | "resumed" | "cancelled" | "completed" | "failed";
|
||||
type: "queued" | "started" | "progress" | "pausing" | "paused" | "resumed" | "cancelled" | "completed" | "failed" | "dismissed";
|
||||
transferId: string;
|
||||
direction?: TransferTask["direction"];
|
||||
fileName?: string;
|
||||
sourcePath?: string;
|
||||
targetPath?: string;
|
||||
packedTargetPaths?: string[];
|
||||
sourceConnectionId?: string;
|
||||
sourceHostLabel?: string;
|
||||
origin?: TransferTask["origin"];
|
||||
retryable?: boolean;
|
||||
startedAt?: number;
|
||||
endedAt?: number;
|
||||
error?: string;
|
||||
@@ -452,9 +457,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
typeof persistedRaw === "string"
|
||||
&& persistedRaw.length >= ASYNC_TRANSFER_HISTORY_RESTORE_THRESHOLD_BYTES
|
||||
);
|
||||
// Track unfinished packed downloads that were only marked cancelled on
|
||||
// hydration in case the app restarted. If a live global event arrives in the
|
||||
// same process (new/reloaded non-owner window), that row can revive cleanly.
|
||||
const restoredUnfinishedPackedIds = new Set<string>();
|
||||
const restored = shouldRestoreCooperatively
|
||||
? { tasks: [] }
|
||||
: deserializeSftpTransferCenter(persistedRaw);
|
||||
: deserializeSftpTransferCenter(persistedRaw, {
|
||||
onRestoredPackedTask: (id) => { restoredUnfinishedPackedIds.add(id); },
|
||||
});
|
||||
let tasks = pruneSftpTransferHistory(restored.tasks);
|
||||
let restoreMigrationPending = shouldRestoreCooperatively;
|
||||
let replayingRestoreEvents = false;
|
||||
@@ -1421,7 +1432,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
try { await netcattyBridge.get()?.clearPendingTransferCancel?.(id); } catch { /* best-effort */ }
|
||||
}));
|
||||
}
|
||||
} else if (tasks.find((candidate) => candidate.id === taskId)?.status === "cancelled") {
|
||||
} else if (task.controlKind !== "packed-download" && tasks.find((candidate) => candidate.id === taskId)?.status === "cancelled") {
|
||||
try {
|
||||
await netcattyBridge.get()?.cleanupTransferArtifacts?.({
|
||||
transferId: taskId,
|
||||
@@ -1883,11 +1894,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
&& ["paused", "interrupted", "attention", "pending", "queued"].includes(task.status);
|
||||
},
|
||||
pause(taskId) {
|
||||
// Packed selections have no resumable walk. Never latch them paused:
|
||||
// their common source directory is display metadata, not a replay source.
|
||||
if (tasks.find((task) => task.id === taskId)?.controlKind === "packed-download") return Promise.resolve();
|
||||
if (cancelInvocations.has(taskId) || isTransferOrRootCancelled(taskId)) return Promise.resolve();
|
||||
clearResumeRequest(taskId);
|
||||
return invoke(taskId, "pause");
|
||||
},
|
||||
async resume(taskId) {
|
||||
if (tasks.find((task) => task.id === taskId)?.controlKind === "packed-download") return;
|
||||
// A cancelled scheduler job cannot be soft-resumed. Wait for the cancel
|
||||
// outcome and fresh re-walk rather than unlatching the old walk.
|
||||
const cancelling = cancelInvocations.get(taskId);
|
||||
@@ -2070,6 +2085,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
async retry(taskId) {
|
||||
const ownerId = findOwner(taskId);
|
||||
const task = tasks.find((candidate) => candidate.id === taskId);
|
||||
if (task?.controlKind === "packed-download") return;
|
||||
// The background-agent controller can only reopen an SFTP channel on the
|
||||
// original terminal session. Failed rows survive an app restart but that
|
||||
// session id does not, so Retry must take the same fresh dedicated path
|
||||
@@ -2196,6 +2212,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
const removing = tasks.filter((candidate) => (
|
||||
candidate.id === taskId || candidate.parentTaskId === taskId
|
||||
));
|
||||
for (const removed of removing) restoredUnfinishedPackedIds.delete(removed.id);
|
||||
settleFinishedTransferControlState(removing, removing);
|
||||
tasks = tasks.filter((task) => task.id !== taskId && task.parentTaskId !== taskId);
|
||||
emit(true);
|
||||
@@ -2212,6 +2229,7 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
&& (status === undefined || task.status === status)
|
||||
&& !(task.parentTaskId && unfinishedParents.has(task.parentTaskId)),
|
||||
);
|
||||
for (const removed of removing) restoredUnfinishedPackedIds.delete(removed.id);
|
||||
const removingIds = new Set(removing.map((task) => task.id));
|
||||
settleFinishedTransferControlState(removing, removing);
|
||||
tasks = tasks.filter((task) => !removingIds.has(task.id) && !removingIds.has(task.parentTaskId ?? ""));
|
||||
@@ -2242,6 +2260,23 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
}
|
||||
let existingIndex = tasks.findIndex((task) => task.id === event.transferId);
|
||||
let existing = tasks[existingIndex];
|
||||
if (event.type === "dismissed") {
|
||||
// Unsupported packed attempts release their reservations in every
|
||||
// window before the originating renderer starts ordinary downloads.
|
||||
restoredUnfinishedPackedIds.delete(event.transferId);
|
||||
if (existing?.controlKind === "packed-download") {
|
||||
tasks = tasks.filter((task) => task.id !== event.transferId);
|
||||
emit(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ((event.type === "cancelled" || event.type === "failed") && existing?.controlKind === "packed-download"
|
||||
&& !TERMINAL_OWNER_STATUSES.has(existing.status)) {
|
||||
// Another window can cancel, or the worker can fail, while the owner
|
||||
// waits for a lease or concurrency slot. Stop its local queue too.
|
||||
markTransferCancelledTree(event.transferId);
|
||||
globalSftpTransferScheduler.cancel(event.transferId);
|
||||
}
|
||||
const beforeEvent = existing;
|
||||
let parentControlsChanged = false;
|
||||
const eventParent = event.parentTaskId
|
||||
@@ -2289,7 +2324,16 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
&& (event.type === "completed" || event.type === "failed" || event.type === "cancelled")
|
||||
)
|
||||
|| (event.sourceFingerprint !== undefined && event.sourceFingerprint !== existing?.sourceFingerprint);
|
||||
const isRestoredProvisionalPacked = Boolean(
|
||||
existing
|
||||
&& existing.controlKind === "packed-download"
|
||||
&& restoredUnfinishedPackedIds.has(existing.id),
|
||||
);
|
||||
if (isRestoredProvisionalPacked && existing) {
|
||||
restoredUnfinishedPackedIds.delete(existing.id);
|
||||
}
|
||||
const terminal = existing
|
||||
&& !isRestoredProvisionalPacked
|
||||
&& (existing.status === "cancelled" || existing.status === "completed" || existing.status === "failed");
|
||||
// Never resurrect a finished/cancelled agent row with late queued/progress.
|
||||
if (terminal && event.type !== "cancelled") {
|
||||
@@ -2365,7 +2409,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
tasks.push({
|
||||
id: event.transferId,
|
||||
ownerId: eventParent?.ownerId
|
||||
?? (event.controlKind === "compressed-upload" ? "background-transfer" : "background-agent"),
|
||||
?? (event.controlKind === "compressed-upload" || event.controlKind === "packed-download"
|
||||
? "background-transfer" : "background-agent"),
|
||||
fileName: event.fileName ?? (
|
||||
targetPath.split(/[\\/]/).pop()
|
||||
|| sourcePath.split(/[\\/]/).pop()
|
||||
@@ -2373,9 +2418,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
),
|
||||
sourcePath,
|
||||
targetPath,
|
||||
sourceConnectionId: event.direction === "upload" ? "local" : (event.sessionId ?? "agent"),
|
||||
packedTargetPaths: event.packedTargetPaths ? [...event.packedTargetPaths] : undefined,
|
||||
sourceConnectionId: event.sourceConnectionId
|
||||
?? (event.direction === "upload" ? "local" : (event.sessionId ?? "agent")),
|
||||
targetConnectionId: event.direction === "download" ? "local" : (event.sessionId ?? "agent"),
|
||||
sourceHostId: event.sourceHostId,
|
||||
sourceHostLabel: event.sourceHostLabel,
|
||||
targetHostId: event.targetHostId,
|
||||
parentTaskId: event.parentTaskId,
|
||||
directoryEntryIndex: event.directoryEntryIndex,
|
||||
@@ -2387,9 +2435,11 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
speed: event.speed ?? 0,
|
||||
startTime: event.startedAt ?? Date.now(),
|
||||
isDirectory: event.isDirectory ?? false,
|
||||
origin: "agent",
|
||||
origin: event.origin ?? (event.controlKind === "packed-download" ? "manual" : "agent"),
|
||||
background: !event.parentTaskId,
|
||||
resumable: event.resumable ?? true,
|
||||
resumable: event.controlKind === "packed-download" ? false : event.resumable ?? true,
|
||||
retryable: event.controlKind === "packed-download" ? false : event.retryable,
|
||||
progressMode: event.controlKind === "packed-download" ? "bytes" : undefined,
|
||||
pauseUnavailableReason: event.pauseUnavailableReason,
|
||||
controlKind: event.controlKind,
|
||||
phase: event.phase,
|
||||
@@ -2405,12 +2455,20 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
: event.lifecycleEpoch !== undefined && incomingEpoch >= currentEpoch;
|
||||
return {
|
||||
...task,
|
||||
ownerId: isRestoredProvisionalPacked && !controllers.has(task.ownerId ?? "")
|
||||
? "background-transfer"
|
||||
: task.ownerId,
|
||||
status: acceptsLifecycle
|
||||
? (event.type === "queued" ? "queued" : "transferring")
|
||||
: task.status,
|
||||
error: acceptsLifecycle ? undefined : task.error,
|
||||
endTime: acceptsLifecycle ? undefined : task.endTime,
|
||||
fileName: event.fileName ?? task.fileName,
|
||||
sourceConnectionId: event.sourceConnectionId ?? task.sourceConnectionId,
|
||||
sourceHostId: event.sourceHostId ?? task.sourceHostId,
|
||||
sourceHostLabel: event.sourceHostLabel ?? task.sourceHostLabel,
|
||||
origin: event.origin ?? task.origin,
|
||||
packedTargetPaths: event.packedTargetPaths ? [...event.packedTargetPaths] : task.packedTargetPaths,
|
||||
totalBytes: event.totalBytes ?? task.totalBytes,
|
||||
isDirectory: event.isDirectory ?? task.isDirectory,
|
||||
controlKind: event.controlKind ?? task.controlKind,
|
||||
@@ -2419,7 +2477,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
directoryEntryIdentity: event.directoryEntryIdentity ?? task.directoryEntryIdentity,
|
||||
background: event.parentTaskId ? false : task.background,
|
||||
phase: event.phase ?? task.phase,
|
||||
resumable: event.resumable ?? task.resumable,
|
||||
resumable: (event.controlKind ?? task.controlKind) === "packed-download" ? false : event.resumable ?? task.resumable,
|
||||
retryable: (event.controlKind ?? task.controlKind) === "packed-download" ? false : event.retryable ?? task.retryable,
|
||||
progressMode: (event.controlKind ?? task.controlKind) === "packed-download" ? "bytes" : task.progressMode,
|
||||
pauseUnavailableReason: event.pauseUnavailableReason ?? task.pauseUnavailableReason,
|
||||
lifecycleEpoch: acceptsLifecycle && event.lifecycleEpoch !== undefined
|
||||
? event.lifecycleEpoch
|
||||
@@ -2513,6 +2573,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
const keepPaused = nextStatus === "paused" || nextStatus === "pausing";
|
||||
return {
|
||||
...task,
|
||||
ownerId: isRestoredProvisionalPacked && !controllers.has(task.ownerId ?? "")
|
||||
? "background-transfer"
|
||||
: task.ownerId,
|
||||
status: nextStatus,
|
||||
transferredBytes: keepPaused ? task.transferredBytes : nextTransferred,
|
||||
totalBytes: event.totalBytes === undefined
|
||||
@@ -2526,8 +2589,11 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
downloadCheckpointBytes: event.downloadCheckpointBytes ?? task.downloadCheckpointBytes,
|
||||
uploadCheckpointBytes: event.uploadCheckpointBytes ?? task.uploadCheckpointBytes,
|
||||
sourceFingerprint: event.sourceFingerprint ?? task.sourceFingerprint,
|
||||
packedTargetPaths: event.packedTargetPaths ? [...event.packedTargetPaths] : task.packedTargetPaths,
|
||||
phase: event.phase ?? task.phase,
|
||||
resumable: event.resumable ?? task.resumable,
|
||||
resumable: (event.controlKind ?? task.controlKind) === "packed-download" ? false : event.resumable ?? task.resumable,
|
||||
retryable: (event.controlKind ?? task.controlKind) === "packed-download" ? false : task.retryable,
|
||||
progressMode: (event.controlKind ?? task.controlKind) === "packed-download" ? "bytes" : task.progressMode,
|
||||
pauseUnavailableReason: event.pauseUnavailableReason ?? task.pauseUnavailableReason,
|
||||
error: keepPaused ? task.error : undefined,
|
||||
endTime: undefined,
|
||||
@@ -2647,6 +2713,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
// Keep the live row for an ID collision, then run the canonical bounded
|
||||
// prune once more over the now-small merged result.
|
||||
const liveIds = new Set(tasks.map((task) => task.id));
|
||||
for (const id of migrated.restoredPackedTaskIds) {
|
||||
if (!liveIds.has(id)) restoredUnfinishedPackedIds.add(id);
|
||||
}
|
||||
tasks = pruneSftpTransferHistory([
|
||||
...migrated.tasks.filter((task) => !liveIds.has(task.id)),
|
||||
...tasks,
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
import React, { useCallback, useRef, useSyncExternalStore } from 'react';
|
||||
import React, { memo, useCallback, useRef, useSyncExternalStore } from 'react';
|
||||
import { act, create } from 'react-test-renderer';
|
||||
import ts from 'typescript';
|
||||
import { resolveSystemSidebarSession } from '../../domain/systemManager/resolveSystemSession';
|
||||
@@ -25,10 +25,10 @@ const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boole
|
||||
test('workspace browser follows focus without replacing the earlier terminal context', async () => {
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const browserSlot = ast.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlot');
|
||||
const browserSlot = ast.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlotInner');
|
||||
assert.ok(browserSlot);
|
||||
const slotCode = ts.transpile(browserSlot.getText(ast), { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React });
|
||||
const Slot = vm.runInNewContext(`${slotCode}; SidePanelBrowserSlot`, {
|
||||
const Slot = vm.runInNewContext(`${slotCode}; SidePanelBrowserSlotInner`, {
|
||||
React, useRef, useSidePanelLiveSnapshotForTab: useSnapshot, resolveSystemSidebarSession, collectSessionIds,
|
||||
sidePanelHiddenPanelClassName: (hidden: boolean) => hidden ? 'hidden' : 'visible',
|
||||
HostBrowserSidePanel: (props: object) => React.createElement('div', { ...props, 'data-browser-context': true }),
|
||||
@@ -133,3 +133,74 @@ test('new panels wait for their own snapshot and workspace panes accept focus ch
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('SidePanelBrowserSlot is memoized and skips re-renders when props are unchanged', async () => {
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
assert.match(
|
||||
source,
|
||||
/export const SidePanelBrowserSlot = memo\(SidePanelBrowserSlotInner\);/,
|
||||
'SidePanelBrowserSlot must be wrapped in React.memo like sibling side-panel slots',
|
||||
);
|
||||
const browserSlot = ast.statements.find(
|
||||
(node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlotInner',
|
||||
);
|
||||
assert.ok(browserSlot);
|
||||
const slotCode = ts.transpile(browserSlot.getText(ast), {
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.React,
|
||||
});
|
||||
let renderCount = 0;
|
||||
const MemoSlot = vm.runInNewContext(
|
||||
`${slotCode}; memo(function TrackedBrowserSlot(props) { onRender(); return SidePanelBrowserSlotInner(props); })`,
|
||||
{
|
||||
React,
|
||||
memo,
|
||||
onRender: () => { renderCount += 1; },
|
||||
useRef,
|
||||
useSidePanelLiveSnapshotForTab: useSnapshot,
|
||||
resolveSystemSidebarSession,
|
||||
collectSessionIds,
|
||||
sidePanelHiddenPanelClassName: (hidden: boolean) => (hidden ? 'hidden' : 'visible'),
|
||||
HostBrowserSidePanel: (props: object) => React.createElement('div', { ...props, 'data-browser-context': true }),
|
||||
},
|
||||
) as React.ComponentType<{ tabId: string; ctx: object; isVisible: boolean }>;
|
||||
|
||||
const sessionA = { id: 'session-a', hostId: 'host-a', protocol: 'ssh' };
|
||||
const ctx = {
|
||||
sessions: [sessionA],
|
||||
workspaceById: new Map(),
|
||||
sessionHostsMap: new Map([['session-a', { id: 'host-a', hostname: 'a', protocol: 'ssh' }]]),
|
||||
sftpAuthHostBySessionId: new Map(),
|
||||
effectiveHosts: [],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
terminalSettings: {},
|
||||
t: (key: string) => key,
|
||||
};
|
||||
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: false }));
|
||||
});
|
||||
assert.equal(renderCount, 1);
|
||||
|
||||
// Re-rendering the parent with identical tabId/ctx/isVisible must be skipped by memo.
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: false }));
|
||||
});
|
||||
assert.equal(renderCount, 1);
|
||||
|
||||
// Visibility changes must still re-render the slot.
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: true }));
|
||||
});
|
||||
assert.equal(renderCount, 2);
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
sidePanelLiveStore.update(SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT);
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
TERMINAL_AUTO_RECONNECT_DELAY_MS,
|
||||
getTerminalAutoReconnectDelayMs,
|
||||
canAttemptTerminalAutoReconnect,
|
||||
isTerminalAutoReconnectEnabled,
|
||||
shouldAutoReconnectAfterExit,
|
||||
@@ -18,6 +19,17 @@ test("terminal auto reconnect uses a five second retry delay", () => {
|
||||
assert.equal(TERMINAL_AUTO_RECONNECT_DELAY_MS, 5000);
|
||||
});
|
||||
|
||||
test("configured reconnect intervals apply to the timer in milliseconds", () => {
|
||||
assert.equal(getTerminalAutoReconnectDelayMs(undefined), 5000);
|
||||
assert.equal(getTerminalAutoReconnectDelayMs({}), 5000);
|
||||
for (const seconds of [5, 30, 300, 3600]) {
|
||||
assert.equal(getTerminalAutoReconnectDelayMs({ sshAutoReconnectInterval: seconds }), seconds * 1000);
|
||||
}
|
||||
assert.equal(getTerminalAutoReconnectDelayMs({ sshAutoReconnectInterval: 0 }), 5000);
|
||||
assert.equal(getTerminalAutoReconnectDelayMs({ sshAutoReconnectInterval: Infinity }), 5000);
|
||||
assert.equal(getTerminalAutoReconnectDelayMs({ sshAutoReconnectInterval: 7200 }), 3600000);
|
||||
});
|
||||
|
||||
test("terminal auto reconnect is disabled unless the setting is explicitly true", () => {
|
||||
assert.equal(isTerminalAutoReconnectEnabled(undefined), false);
|
||||
assert.equal(isTerminalAutoReconnectEnabled({ sshAutoReconnectEnabled: true }), true);
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import type { TerminalSettings } from "../../domain/models";
|
||||
import type { Host, TerminalSettings } from "../../domain/models";
|
||||
import { normalizeSshAutoReconnectInterval } from "../../domain/models/terminal";
|
||||
import type { TerminalSessionExitEvent } from "./resolveTerminalSessionExitIntent";
|
||||
|
||||
export const TERMINAL_AUTO_RECONNECT_DELAY_MS = 5000;
|
||||
|
||||
export function getTerminalAutoReconnectDelayMs(
|
||||
settings?: Partial<Pick<TerminalSettings, "sshAutoReconnectInterval">> | null,
|
||||
): number {
|
||||
return normalizeSshAutoReconnectInterval(settings?.sshAutoReconnectInterval) * 1000;
|
||||
}
|
||||
|
||||
type AutoReconnectHost = {
|
||||
protocol?: "ssh" | "telnet" | "local" | "serial" | "mosh" | "et";
|
||||
protocol?: Host["protocol"];
|
||||
hostname?: string;
|
||||
moshEnabled?: boolean;
|
||||
etEnabled?: boolean;
|
||||
|
||||
@@ -3,6 +3,7 @@ import test from 'node:test';
|
||||
import { createTerminalDirectoryController } from './terminalDirectoryController';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
|
||||
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
|
||||
|
||||
function setup(overrides: Partial<TerminalDirectoryIO> = {}) {
|
||||
let cwd = '/old'; let ready = true; let current = true;
|
||||
@@ -18,6 +19,45 @@ function setup(overrides: Partial<TerminalDirectoryIO> = {}) {
|
||||
return { controller, writes, published, busy: () => { ready = false; }, stale: () => { current = false; } };
|
||||
}
|
||||
|
||||
test('capabilities prohibit writes even when a cwd can be displayed', async () => {
|
||||
let writes = 0;
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId: 'read-only', isCurrent: () => true, isReady: () => true, publish() {},
|
||||
capabilities: { ...COMPLETE_DIRECTORY_CAPABILITIES, changeDirectory: false },
|
||||
io: { cwd: async () => '/base', list: async () => ({ entries: [], home: null }),
|
||||
realpath: async value => value, write() { writes++; } },
|
||||
});
|
||||
assert.equal(await controller.refresh(), '/base');
|
||||
await assert.rejects(controller.change('/next', new AbortController().signal, () => {}), { code: 'unavailable' });
|
||||
assert.equal(writes, 0);
|
||||
controller.dispose();
|
||||
});
|
||||
|
||||
test('Win32 adapters confirm actual native cwd and reject stale revisions or foreign namespace reports', async t => {
|
||||
const id = 'win32-controller';
|
||||
const writes: string[] = [];
|
||||
let cwd = 'C:\\base';
|
||||
terminalCwdStore.setCwd(id, cwd, 'backend-strict');
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId: id, target: { authority: 'local:windows-generation', pathFlavor: 'win32' },
|
||||
buildChangeCommand: path => directoryChangeCommand(path, 'powershell', 'win32'),
|
||||
isCurrent: () => true, isReady: () => true,
|
||||
io: { cwd: async () => cwd, list: async () => ({ entries: [], home: null }),
|
||||
realpath: async value => value, write(data) { writes.push(data); cwd = "D:\\O'Brien"; } },
|
||||
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
|
||||
});
|
||||
t.after(() => controller.dispose());
|
||||
const revision = terminalCwdStore.getSessionRevision(id);
|
||||
terminalCwdStore.setCwd(id, 'C:\\other', 'backend-strict');
|
||||
terminalCwdStore.setCwd(id, 'C:\\base', 'backend-strict');
|
||||
await assert.rejects(controller.change("D:\\O'Brien", new AbortController().signal, () => {}, 'C:\\base', revision), { code: 'unavailable' });
|
||||
await assert.rejects(controller.change('/foreign-posix', new AbortController().signal, () => {}), { code: 'unsupportedPath' });
|
||||
assert.deepEqual(writes, []);
|
||||
await controller.change("D:\\O'Brien", new AbortController().signal, () => {}, 'C:\\base');
|
||||
assert.deepEqual(writes, ["Microsoft.PowerShell.Management\\Set-Location -LiteralPath 'D:\\O''Brien'\r"]);
|
||||
assert.equal(terminalCwdStore.getCwd(id), "D:\\O'Brien");
|
||||
});
|
||||
|
||||
test('navigation writes one quoted cd and waits for actual cwd before confirming', async () => {
|
||||
const ctx = setup(); const accepted: string[] = [];
|
||||
await ctx.controller.change('/next', new AbortController().signal, () => accepted.push('accepted'));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DirectoryPickerError, isDirectoryPath } from '../../domain/directoryPicker';
|
||||
import { resolveInteractiveTerminalCdIntent } from '../../domain/sessionRestore';
|
||||
import { DirectoryPickerError, directoryChangeCommand, isDirectoryPath, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
|
||||
import { sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
|
||||
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
|
||||
@@ -13,12 +13,20 @@ export function createTerminalDirectoryController(options: {
|
||||
isReady: () => boolean;
|
||||
publish: (cwd: string) => void;
|
||||
confirmationMs?: number;
|
||||
target?: DirectoryTarget;
|
||||
capabilities?: DirectoryCapabilities;
|
||||
buildChangeCommand?: (path: string) => string | null;
|
||||
}) {
|
||||
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
|
||||
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
|
||||
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
|
||||
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
|
||||
let disposed = false;
|
||||
let changing = false;
|
||||
let confirmed = false;
|
||||
let refreshing: Promise<string> | null = null;
|
||||
let refreshAgain = false;
|
||||
let cwdError: DirectoryPickerError | null = null;
|
||||
const lifetime = new AbortController();
|
||||
const current = () => !disposed && options.isCurrent();
|
||||
function check(signal?: AbortSignal) {
|
||||
@@ -46,9 +54,10 @@ export function createTerminalDirectoryController(options: {
|
||||
}
|
||||
async function refresh(submittedRevision?: number): Promise<string> {
|
||||
check();
|
||||
if (!capabilities.readCwd) throw new DirectoryPickerError('unavailable');
|
||||
const activeShellCwd = () => {
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
return cwd && terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
&& (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision)
|
||||
? cwd : null;
|
||||
};
|
||||
@@ -57,7 +66,7 @@ export function createTerminalDirectoryController(options: {
|
||||
// events and picker remounts. Only a cd submission may probe past its own
|
||||
// pre-write report while waiting for fresh confirmation.
|
||||
const reported = activeShellCwd();
|
||||
if (reported) { confirmed = true; return reported; }
|
||||
if (reported) { confirmed = true; cwdError = null; return reported; }
|
||||
if (refreshing) {
|
||||
// Output may settle while a pre-cd query is still in flight. Keep one
|
||||
// follow-up query so that its older result cannot be the last update.
|
||||
@@ -65,11 +74,23 @@ export function createTerminalDirectoryController(options: {
|
||||
return refreshing;
|
||||
}
|
||||
const pending = (async () => {
|
||||
const cwd = await bounded(options.io.cwd());
|
||||
let cwd: string;
|
||||
try {
|
||||
cwd = await bounded(options.io.cwd());
|
||||
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
|
||||
} catch (error) {
|
||||
if (current() && target.pathFlavor === 'win32') {
|
||||
confirmed = false;
|
||||
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
|
||||
options.publish('');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
check();
|
||||
const reported = activeShellCwd();
|
||||
const live = terminalCwdStore.getCwd(options.sessionId);
|
||||
confirmed = true;
|
||||
cwdError = null;
|
||||
if (reported) return reported;
|
||||
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd);
|
||||
return cwd;
|
||||
@@ -83,27 +104,32 @@ export function createTerminalDirectoryController(options: {
|
||||
}
|
||||
}
|
||||
}
|
||||
async function change(path: string, signal: AbortSignal, accepted: () => void, expectedCwd?: string) {
|
||||
async function change(path: string, signal: AbortSignal, accepted: () => void, expectedCwd?: string, expectedRevision?: number) {
|
||||
ready();
|
||||
check(signal);
|
||||
if (!capabilities.changeDirectory || !capabilities.confirmChange) throw new DirectoryPickerError('unavailable');
|
||||
if (changing) throw new DirectoryPickerError('busy');
|
||||
const intent = isDirectoryPath(path) ? resolveInteractiveTerminalCdIntent(path) : null;
|
||||
if (!intent) throw new DirectoryPickerError('unsupportedPath');
|
||||
const command = valid(path) ? (options.buildChangeCommand ?? (value => directoryChangeCommand(value, 'posix', target.pathFlavor)))(path) : null;
|
||||
if (!command) throw new DirectoryPickerError('unsupportedPath');
|
||||
changing = true;
|
||||
let confirmationFinished = false;
|
||||
try {
|
||||
const canonical = await bounded(options.io.realpath(path, signal), signal);
|
||||
if (options.io.validateChange) await bounded(options.io.validateChange(expectedCwd), signal);
|
||||
check(signal);
|
||||
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
|
||||
ready(); // The shell can become busy while resolving a remote symlink.
|
||||
if (expectedCwd && terminalCwdStore.getCwd(options.sessionId) !== expectedCwd) throw new DirectoryPickerError('unavailable');
|
||||
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
|
||||
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
|
||||
options.io.write(intent.command + '\r');
|
||||
options.io.write(command + '\r');
|
||||
accepted();
|
||||
const deadline = Date.now() + (options.confirmationMs ?? 8000);
|
||||
const hasFreshOsc7 = () => {
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
return terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
|
||||
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
|
||||
&& terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
&& (cwd === path || cwd === canonical);
|
||||
&& (same(cwd, path) || same(cwd, canonical));
|
||||
};
|
||||
const pause = () => new Promise<void>(resolve => {
|
||||
const done = () => { clearTimeout(timer); lifetime.signal.removeEventListener('abort', done); resolve(); };
|
||||
@@ -118,7 +144,7 @@ export function createTerminalDirectoryController(options: {
|
||||
try {
|
||||
const cwd = await refresh(submittedRevision);
|
||||
check(signal);
|
||||
if (cwd === path || cwd === canonical || await bounded(options.io.realpath(cwd, signal), signal) === canonical) return;
|
||||
if (same(cwd, path) || same(cwd, canonical) || same(await bounded(options.io.realpath(cwd, signal), signal), canonical)) return;
|
||||
} catch (error) {
|
||||
if (!current() || signal.aborted) throw error;
|
||||
}
|
||||
@@ -143,15 +169,20 @@ export function createTerminalDirectoryController(options: {
|
||||
} finally { confirmationFinished = true; changing = false; }
|
||||
}
|
||||
return {
|
||||
target,
|
||||
capabilities,
|
||||
getCwdError: () => cwdError?.code ?? null,
|
||||
refresh: () => refresh(),
|
||||
hasConfirmedCwd: () => confirmed,
|
||||
async home() {
|
||||
check();
|
||||
const result = await bounded(options.io.home?.() ?? Promise.resolve(null));
|
||||
check(); return result;
|
||||
check(); return valid(result) ? result : null;
|
||||
},
|
||||
async list(path: string, signal: AbortSignal) {
|
||||
check(signal);
|
||||
if (!capabilities.listDirectories) throw new DirectoryPickerError('unavailable');
|
||||
if (!valid(path)) throw new DirectoryPickerError('unsupportedPath');
|
||||
const result = await bounded(options.io.list(path, signal), signal);
|
||||
check(signal);
|
||||
return result;
|
||||
|
||||
@@ -44,3 +44,35 @@ test('host tree restored layout width is clamped', () => {
|
||||
assert.equal(clampTerminalHostTreeWidth(0), 176);
|
||||
assert.equal(TERMINAL_HOST_TREE_DEFAULT_WIDTH, 220);
|
||||
});
|
||||
|
||||
test('host tree layout width tracks animated transition flag and deduplicates identical updates', () => {
|
||||
terminalHostTreeStore.setLayoutWidth(0, false);
|
||||
let notifications = 0;
|
||||
const unsubscribe = terminalHostTreeStore.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
try {
|
||||
terminalHostTreeStore.setLayoutWidth(220, true);
|
||||
assert.equal(terminalHostTreeStore.getLayoutWidth(), 220);
|
||||
assert.equal(terminalHostTreeStore.getLayoutTransitionAnimated(), true);
|
||||
assert.equal(notifications, 1);
|
||||
|
||||
// Repeating same (width, animated) is a no-op.
|
||||
terminalHostTreeStore.setLayoutWidth(220, true);
|
||||
assert.equal(notifications, 1);
|
||||
|
||||
// Clearing animated flag notifies once while keeping layoutWidth intact.
|
||||
terminalHostTreeStore.setLayoutTransitionAnimated(false);
|
||||
assert.equal(terminalHostTreeStore.getLayoutWidth(), 220);
|
||||
assert.equal(terminalHostTreeStore.getLayoutTransitionAnimated(), false);
|
||||
assert.equal(notifications, 2);
|
||||
|
||||
// Repeating clear is a no-op.
|
||||
terminalHostTreeStore.setLayoutTransitionAnimated(false);
|
||||
assert.equal(notifications, 2);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
terminalHostTreeStore.setLayoutWidth(0, false);
|
||||
}
|
||||
});
|
||||
@@ -26,14 +26,18 @@ function readIsOpen(): boolean {
|
||||
|
||||
class TerminalHostTreeStore {
|
||||
private isOpen = readIsOpen();
|
||||
/** Live sidebar width (0 when collapsed) for top-tab alignment. */
|
||||
/** Target sidebar width (0 when collapsed or hidden behind root pages) for top-tab and surface alignment. */
|
||||
private layoutWidth = 0;
|
||||
/** Whether layout consumers should animate transitions to `layoutWidth` (false for instant snaps and drag resize). */
|
||||
private layoutTransitionAnimated = false;
|
||||
private listeners = new Set<Listener>();
|
||||
|
||||
getIsOpen = () => this.isOpen;
|
||||
|
||||
getLayoutWidth = () => this.layoutWidth;
|
||||
|
||||
getLayoutTransitionAnimated = () => this.layoutTransitionAnimated;
|
||||
|
||||
setIsOpen = (open: boolean) => {
|
||||
if (this.isOpen === open) return;
|
||||
this.isOpen = open;
|
||||
@@ -44,10 +48,17 @@ class TerminalHostTreeStore {
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
setLayoutWidth = (width: number) => {
|
||||
setLayoutWidth = (width: number, animated = false) => {
|
||||
const next = Math.max(0, Math.round(width));
|
||||
if (this.layoutWidth === next) return;
|
||||
if (this.layoutWidth === next && this.layoutTransitionAnimated === animated) return;
|
||||
this.layoutWidth = next;
|
||||
this.layoutTransitionAnimated = animated;
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
setLayoutTransitionAnimated = (animated: boolean) => {
|
||||
if (this.layoutTransitionAnimated === animated) return;
|
||||
this.layoutTransitionAnimated = animated;
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
@@ -82,3 +93,11 @@ export const useTerminalHostTreeLayoutWidth = () => {
|
||||
terminalHostTreeStore.getLayoutWidth,
|
||||
);
|
||||
};
|
||||
|
||||
export const useTerminalHostTreeLayoutTransitionAnimated = (): boolean => {
|
||||
return useSyncExternalStore(
|
||||
terminalHostTreeStore.subscribe,
|
||||
terminalHostTreeStore.getLayoutTransitionAnimated,
|
||||
terminalHostTreeStore.getLayoutTransitionAnimated,
|
||||
);
|
||||
};
|
||||
@@ -116,6 +116,7 @@ export interface SendToCattyContext {
|
||||
commandBlocklist?: string[];
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
terminalSessions: TerminalSessionInfo[];
|
||||
webSearchConfig?: WebSearchConfig | null;
|
||||
getExecutorContext?: () => ExecutorContext;
|
||||
|
||||
@@ -3,14 +3,28 @@ import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
|
||||
import { STORAGE_KEY_AI_COMMAND_BLOCKLIST } from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAISettingsState } from './useAISettingsState.ts';
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
||||
STORAGE_KEY_AI_PERMISSION_MODE,
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_SESSION_MESSAGE_CAP,
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import type { ProviderConfig } from '../../infrastructure/ai/types.ts';
|
||||
import { useAISettingsState, useSharedAISettingsState } from './useAISettingsState.ts';
|
||||
|
||||
test('command blocklist storage events refresh the mounted AI settings state', async () => {
|
||||
function setupStorageHarness() {
|
||||
const store = new Map<string, string>();
|
||||
const writes: Array<[string, string]> = [];
|
||||
const fakeStorage = {
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => store.set(key, String(value)),
|
||||
setItem: (key: string, value: string) => {
|
||||
writes.push([key, String(value)]);
|
||||
store.set(key, String(value));
|
||||
},
|
||||
removeItem: (key: string) => store.delete(key),
|
||||
};
|
||||
const fakeWindow = new EventTarget() as EventTarget & { netcatty?: unknown };
|
||||
@@ -26,6 +40,28 @@ test('command blocklist storage events refresh the mounted AI settings state', a
|
||||
Object.defineProperty(globalThis, 'localStorage', { value: fakeStorage, configurable: true });
|
||||
Object.defineProperty(globalThis, 'window', { value: fakeWindow, configurable: true });
|
||||
|
||||
return {
|
||||
store,
|
||||
writes,
|
||||
fakeStorage,
|
||||
fakeWindow,
|
||||
dispatchStorage: (key: string) => {
|
||||
const event = new Event('storage');
|
||||
Object.defineProperty(event, 'key', { value: key });
|
||||
fakeWindow.dispatchEvent(event);
|
||||
},
|
||||
cleanup: () => {
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
if (previousLocalStorage) Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
|
||||
else delete globals.localStorage;
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else delete globals.window;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('command blocklist storage events refresh the mounted AI settings state', async () => {
|
||||
const env = setupStorageHarness();
|
||||
let currentBlocklist: string[] = [];
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
const Probe = () => {
|
||||
@@ -37,21 +73,159 @@ test('command blocklist storage events refresh the mounted AI settings state', a
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
fakeStorage.setItem(STORAGE_KEY_AI_COMMAND_BLOCKLIST, JSON.stringify(['company-blocked-command']));
|
||||
const event = new Event('storage');
|
||||
Object.defineProperty(event, 'key', { value: STORAGE_KEY_AI_COMMAND_BLOCKLIST });
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_COMMAND_BLOCKLIST, JSON.stringify(['company-blocked-command']));
|
||||
await act(async () => {
|
||||
fakeWindow.dispatchEvent(event);
|
||||
env.dispatchStorage(STORAGE_KEY_AI_COMMAND_BLOCKLIST);
|
||||
});
|
||||
assert.deepEqual(currentBlocklist, ['company-blocked-command']);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
if (previousLocalStorage) Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
|
||||
else delete globals.localStorage;
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else delete globals.window;
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useSharedAISettingsState preserves invalid-permission-mode ignore option vs useAISettingsState fallback', async () => {
|
||||
const env = setupStorageHarness();
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PERMISSION_MODE, 'auto');
|
||||
|
||||
let sharedMode = '';
|
||||
let settingsPageMode = '';
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const Probe = () => {
|
||||
sharedMode = useSharedAISettingsState({ ignoreInvalidPermissionModeOnStorage: true }).globalPermissionMode;
|
||||
settingsPageMode = useAISettingsState().globalPermissionMode;
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
assert.equal(sharedMode, 'auto');
|
||||
assert.equal(settingsPageMode, 'auto');
|
||||
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PERMISSION_MODE, 'bogus-mode');
|
||||
await act(async () => {
|
||||
env.dispatchStorage(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
});
|
||||
|
||||
assert.equal(sharedMode, 'auto');
|
||||
assert.equal(settingsPageMode, 'confirm');
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useSharedAISettingsState onRemoveProvider replaces localStorage map cleanup and updateProvider skips no-op writes', async () => {
|
||||
const env = setupStorageHarness();
|
||||
const provider: ProviderConfig = {
|
||||
id: 'prov-1',
|
||||
providerId: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'secret',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o',
|
||||
modelContextWindows: { 'gpt-4o': 128000 },
|
||||
};
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify([provider]));
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, 'prov-1');
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify({ catty: 'prov-1' }));
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify({ catty: 'gpt-4o' }));
|
||||
env.writes.length = 0;
|
||||
|
||||
const removedIds: string[] = [];
|
||||
let api: ReturnType<typeof useSharedAISettingsState> | null = null;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const Probe = () => {
|
||||
const onRemoveProvider = React.useCallback((id: string) => {
|
||||
removedIds.push(id);
|
||||
}, []);
|
||||
api = useSharedAISettingsState({ onRemoveProvider });
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
api!.updateProvider('prov-1', {
|
||||
name: 'OpenAI',
|
||||
modelContextWindows: { 'gpt-4o': 128000 },
|
||||
});
|
||||
});
|
||||
assert.equal(
|
||||
env.writes.filter(([key]) => key === STORAGE_KEY_AI_PROVIDERS).length,
|
||||
0,
|
||||
'no-op provider patch should not rewrite localStorage',
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
api!.removeProvider('prov-1');
|
||||
});
|
||||
assert.deepEqual(removedIds, ['prov-1']);
|
||||
assert.equal(api!.activeProviderId, '');
|
||||
assert.equal(
|
||||
env.writes.filter(([key]) => key === STORAGE_KEY_AI_AGENT_PROVIDER_MAP || key === STORAGE_KEY_AI_AGENT_MODEL_MAP).length,
|
||||
0,
|
||||
'custom onRemoveProvider must replace default localStorage agent-map cleanup',
|
||||
);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('SettingsPage-only storage keys do not trigger re-renders in useSharedAISettingsState', async () => {
|
||||
const env = setupStorageHarness();
|
||||
let sharedRenders = 0;
|
||||
let settingsCap = 0;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const SharedProbe = () => {
|
||||
sharedRenders += 1;
|
||||
useSharedAISettingsState({ ignoreInvalidPermissionModeOnStorage: true });
|
||||
return null;
|
||||
};
|
||||
const SettingsProbe = () => {
|
||||
settingsCap = useAISettingsState().aiSessionMessageCap;
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
React.createElement(React.Fragment, null,
|
||||
React.createElement(SharedProbe),
|
||||
React.createElement(SettingsProbe),
|
||||
),
|
||||
);
|
||||
});
|
||||
const rendersAfterMount = sharedRenders;
|
||||
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, '500');
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION, 'false');
|
||||
await act(async () => {
|
||||
env.dispatchStorage(STORAGE_KEY_AI_SESSION_MESSAGE_CAP);
|
||||
env.dispatchStorage(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION);
|
||||
});
|
||||
|
||||
assert.equal(settingsCap, 500);
|
||||
assert.equal(sharedRenders, rendersAfterMount);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_SESSION_MESSAGE_CAP,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
@@ -39,6 +40,10 @@ import {
|
||||
DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
normalizeAiSessionMessageCap,
|
||||
} from '../../domain/aiSessionMessageCap';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -59,7 +64,44 @@ function readToolIntegrationMode(): AIToolIntegrationMode {
|
||||
: 'mcp';
|
||||
}
|
||||
|
||||
export function useAISettingsState() {
|
||||
function providerPatchIsNoop(
|
||||
current: ProviderConfig,
|
||||
updates: Partial<ProviderConfig>,
|
||||
): boolean {
|
||||
for (const key of Object.keys(updates) as Array<keyof ProviderConfig>) {
|
||||
const nextValue = updates[key];
|
||||
const prevValue = current[key];
|
||||
if (nextValue === prevValue) continue;
|
||||
if (key === 'modelContextWindows') {
|
||||
const prevWindows = (prevValue ?? {}) as Record<string, number>;
|
||||
const nextWindows = (nextValue ?? {}) as Record<string, number>;
|
||||
const nextKeys = Object.keys(nextWindows);
|
||||
if (nextKeys.length !== Object.keys(prevWindows).length) return false;
|
||||
if (nextKeys.some((modelId) => prevWindows[modelId] !== nextWindows[modelId])) return false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface SharedAISettingsStateOptions {
|
||||
/**
|
||||
* When true, cross-window `storage` events with unrecognized permission mode
|
||||
* strings are ignored instead of falling back to `'confirm'`.
|
||||
*/
|
||||
ignoreInvalidPermissionModeOnStorage?: boolean;
|
||||
/**
|
||||
* Optional replacement for removing provider references from agent maps when
|
||||
* the caller already owns in-memory React state for those maps.
|
||||
*/
|
||||
onRemoveProvider?: (id: string) => void;
|
||||
}
|
||||
|
||||
export function useSharedAISettingsState(options?: SharedAISettingsStateOptions) {
|
||||
const ignoreInvalidPermissionModeOnStorage = options?.ignoreInvalidPermissionModeOnStorage ?? false;
|
||||
const onRemoveProvider = options?.onRemoveProvider;
|
||||
|
||||
const [providers, setProvidersRaw] = useState<ProviderConfig[]>(() =>
|
||||
localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS) ?? []
|
||||
);
|
||||
@@ -92,10 +134,10 @@ export function useAISettingsState() {
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
const [aiSessionMessageCap, setAiSessionMessageCapRaw] = useState<number>(() =>
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
const [toolOutputMaxChars, setToolOutputMaxCharsRaw] = useState<number>(() =>
|
||||
normalizeAiToolOutputMaxChars(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
)
|
||||
);
|
||||
const [webSearchConfig, setWebSearchConfigRaw] = useState<WebSearchConfig | null>(() =>
|
||||
@@ -104,14 +146,11 @@ export function useAISettingsState() {
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const [showTerminalSelectionAIAction, setShowTerminalSelectionAIAction] = useStoredBoolean(
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw((prev) => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
if (next === prev) return prev;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_PROVIDERS, next);
|
||||
return next;
|
||||
});
|
||||
@@ -122,9 +161,15 @@ export function useAISettingsState() {
|
||||
}, [setProviders]);
|
||||
|
||||
const updateProvider = useCallback((id: string, updates: Partial<ProviderConfig>) => {
|
||||
setProviders((prev) => prev.map((provider) => (
|
||||
provider.id === id ? { ...provider, ...updates } : provider
|
||||
)));
|
||||
setProviders((prev) => {
|
||||
const index = prev.findIndex((provider) => provider.id === id);
|
||||
if (index < 0) return prev;
|
||||
const current = prev[index];
|
||||
if (providerPatchIsNoop(current, updates)) return prev;
|
||||
const next = prev.slice();
|
||||
next[index] = { ...current, ...updates };
|
||||
return next;
|
||||
});
|
||||
}, [setProviders]);
|
||||
|
||||
const removeProvider = useCallback((id: string) => {
|
||||
@@ -135,6 +180,11 @@ export function useAISettingsState() {
|
||||
return '';
|
||||
});
|
||||
|
||||
if (onRemoveProvider) {
|
||||
onRemoveProvider(id);
|
||||
return;
|
||||
}
|
||||
|
||||
const agentProviderMap =
|
||||
localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_PROVIDER_MAP) ?? {};
|
||||
const agentModelMap =
|
||||
@@ -146,7 +196,7 @@ export function useAISettingsState() {
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
}
|
||||
}, [setProviders]);
|
||||
}, [onRemoveProvider, setProviders]);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
@@ -208,10 +258,10 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
setAiSessionMessageCapRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, normalizedValue);
|
||||
const setToolOutputMaxChars = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiToolOutputMaxChars(value);
|
||||
setToolOutputMaxCharsRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS, normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setWebSearchConfig = useCallback((config: WebSearchConfig | null) => {
|
||||
@@ -249,14 +299,26 @@ export function useAISettingsState() {
|
||||
case STORAGE_KEY_AI_ACTIVE_MODEL:
|
||||
setActiveModelIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE:
|
||||
setGlobalPermissionModeRaw(readPermissionMode());
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(readPermissionMode());
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE: {
|
||||
if (ignoreInvalidPermissionModeOnStorage) {
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (mode === 'observer' || mode === 'confirm' || mode === 'auto') {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
} else {
|
||||
const mode = readPermissionMode();
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
break;
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE:
|
||||
setToolIntegrationModeRaw(readToolIntegrationMode());
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(readToolIntegrationMode());
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE: {
|
||||
const mode = readToolIntegrationMode();
|
||||
setToolIntegrationModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_EXTERNAL_AGENTS: {
|
||||
const agents = localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS);
|
||||
if (agents != null && !Array.isArray(agents)) break;
|
||||
@@ -294,14 +356,13 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
case STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS: {
|
||||
const limit = localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
if (!Number.isFinite(limit)) break;
|
||||
setToolOutputMaxCharsRaw(normalizeAiToolOutputMaxChars(limit));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_WEB_SEARCH:
|
||||
setWebSearchConfigRaw(localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null);
|
||||
break;
|
||||
@@ -325,7 +386,7 @@ export function useAISettingsState() {
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
};
|
||||
}, []);
|
||||
}, [ignoreInvalidPermissionModeOnStorage]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = getAIBridge();
|
||||
@@ -365,14 +426,12 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
}), [
|
||||
providers,
|
||||
setProviders,
|
||||
@@ -400,12 +459,72 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
]);
|
||||
}
|
||||
|
||||
export function useAISettingsState() {
|
||||
const shared = useSharedAISettingsState();
|
||||
const [aiSessionMessageCap, setAiSessionMessageCapRaw] = useState<number>(() =>
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
)
|
||||
);
|
||||
const [showTerminalSelectionAIAction, setShowTerminalSelectionAIAction] = useStoredBoolean(
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
setAiSessionMessageCapRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, normalizedValue);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const syncMessageCap = (key: string | null) => {
|
||||
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
|
||||
try {
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
|
||||
const handleLocalStateChanged = (event: Event) => {
|
||||
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
window.addEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return useMemo(() => ({
|
||||
...shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
}), [
|
||||
shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
]);
|
||||
|
||||
+59
-363
@@ -1,18 +1,7 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_ACTIVE_MODEL,
|
||||
STORAGE_KEY_AI_PERMISSION_MODE,
|
||||
STORAGE_KEY_AI_TOOL_INTEGRATION_MODE,
|
||||
STORAGE_KEY_AI_HOST_PERMISSIONS,
|
||||
STORAGE_KEY_AI_EXTERNAL_AGENTS,
|
||||
STORAGE_KEY_AI_DEFAULT_AGENT,
|
||||
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS_OVERFLOW,
|
||||
STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW,
|
||||
@@ -20,30 +9,15 @@ import {
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AGENT_THINKING_MAP,
|
||||
STORAGE_KEY_AI_WEB_SEARCH,
|
||||
STORAGE_KEY_AI_QUICK_MESSAGES,
|
||||
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
|
||||
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
|
||||
import type {
|
||||
AIDraft,
|
||||
AISessionContextCompaction,
|
||||
AISession,
|
||||
AIPermissionMode,
|
||||
AIToolIntegrationMode,
|
||||
ProviderConfig,
|
||||
HostAIPermission,
|
||||
ExternalAgentConfig,
|
||||
ChatMessage,
|
||||
AISessionScope,
|
||||
WebSearchConfig,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS,
|
||||
normalizeCommandTimeoutSeconds,
|
||||
normalizeResponseIdleTimeoutSeconds,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
activateDraftView,
|
||||
@@ -114,10 +88,7 @@ import {
|
||||
readLiveSessionsArray,
|
||||
} from './aiSessionsBackup';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import {
|
||||
persistCommandBlocklistSetting,
|
||||
readCommandBlocklistSetting,
|
||||
} from './commandBlocklistSettings';
|
||||
import { useSharedAISettingsState } from './useAISettingsState';
|
||||
import {
|
||||
handoffDissolvedWorkspaceAIScope,
|
||||
retargetWorkspaceActiveChatAfterMemberLoss,
|
||||
@@ -128,79 +99,11 @@ import {
|
||||
type UndoLastTurnRestoredDraft,
|
||||
} from '../../domain/aiUndoLastTurn';
|
||||
|
||||
|
||||
function providerPatchIsNoop(
|
||||
current: ProviderConfig,
|
||||
updates: Partial<ProviderConfig>,
|
||||
): boolean {
|
||||
for (const key of Object.keys(updates) as Array<keyof ProviderConfig>) {
|
||||
const nextValue = updates[key];
|
||||
const prevValue = current[key];
|
||||
if (nextValue === prevValue) continue;
|
||||
if (key === 'modelContextWindows') {
|
||||
const prevWindows = (prevValue ?? {}) as Record<string, number>;
|
||||
const nextWindows = (nextValue ?? {}) as Record<string, number>;
|
||||
const nextKeys = Object.keys(nextWindows);
|
||||
if (nextKeys.length !== Object.keys(prevWindows).length) return false;
|
||||
if (nextKeys.some((modelId) => prevWindows[modelId] !== nextWindows[modelId])) return false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function useAIState() {
|
||||
// ── Provider Config ──
|
||||
const [providers, setProvidersRaw] = useState<ProviderConfig[]>(() =>
|
||||
localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS) ?? []
|
||||
);
|
||||
const [activeProviderId, setActiveProviderIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER) ?? ''
|
||||
);
|
||||
const [activeModelId, setActiveModelIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? ''
|
||||
);
|
||||
|
||||
// ── Permission Model ──
|
||||
const [globalPermissionMode, setGlobalPermissionModeRaw] = useState<AIPermissionMode>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
|
||||
return 'confirm';
|
||||
});
|
||||
const [toolIntegrationMode, setToolIntegrationModeRaw] = useState<AIToolIntegrationMode>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE);
|
||||
return stored === 'skills' ? 'skills' : 'mcp';
|
||||
});
|
||||
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
|
||||
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
|
||||
);
|
||||
|
||||
// ── External Agents ──
|
||||
const [externalAgents, setExternalAgentsRaw] = useState<ExternalAgentConfig[]>(() =>
|
||||
localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS) ?? []
|
||||
);
|
||||
const [defaultAgentId, setDefaultAgentIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT) ?? 'catty'
|
||||
);
|
||||
|
||||
// ── Safety Settings ──
|
||||
const [commandBlocklist, setCommandBlocklistRaw] = useState<string[]>(readCommandBlocklistSetting);
|
||||
const [commandTimeout, setCommandTimeoutRaw] = useState<number>(() =>
|
||||
normalizeCommandTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
);
|
||||
const [responseIdleTimeout, setResponseIdleTimeoutRaw] = useState<number>(() =>
|
||||
normalizeResponseIdleTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT)
|
||||
?? DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS,
|
||||
)
|
||||
);
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
|
||||
// ── Sessions ──
|
||||
// Memory-only initial state: the primary store is IndexedDB and loads
|
||||
// asynchronously in the boot effect below (issue #4123). The legacy
|
||||
@@ -450,15 +353,59 @@ export function useAIState() {
|
||||
localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_THINKING_MAP) ?? {}
|
||||
);
|
||||
|
||||
// ── Web Search Config ──
|
||||
const [webSearchConfig, setWebSearchConfigRaw] = useState<WebSearchConfig | null>(() =>
|
||||
localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null
|
||||
);
|
||||
const handleRemoveProviderReferences = useCallback((id: string) => {
|
||||
const cleanup = removeProviderReferences(
|
||||
id,
|
||||
agentProviderMapRef.current,
|
||||
agentModelMapRef.current,
|
||||
);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
setAgentProviderMapRaw(cleanup.agentProviderMap);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
setAgentModelMapRaw(cleanup.agentModelMap);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ── Quick Messages (slash prompts) ──
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const {
|
||||
providers,
|
||||
setProviders,
|
||||
addProvider,
|
||||
updateProvider,
|
||||
removeProvider,
|
||||
activeProviderId,
|
||||
setActiveProviderId,
|
||||
activeModelId,
|
||||
setActiveModelId,
|
||||
activeProvider,
|
||||
globalPermissionMode,
|
||||
setGlobalPermissionMode,
|
||||
toolIntegrationMode,
|
||||
setToolIntegrationMode,
|
||||
externalAgents,
|
||||
setExternalAgents,
|
||||
defaultAgentId,
|
||||
setDefaultAgentId,
|
||||
commandBlocklist,
|
||||
setCommandBlocklist,
|
||||
commandTimeout,
|
||||
setCommandTimeout,
|
||||
responseIdleTimeout,
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
} = useSharedAISettingsState({
|
||||
ignoreInvalidPermissionModeOnStorage: true,
|
||||
onRemoveProvider: handleRemoveProviderReferences,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
@@ -589,53 +536,6 @@ export function useAIState() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setWebSearchConfig = useCallback((config: WebSearchConfig | null) => {
|
||||
setWebSearchConfigRaw(config);
|
||||
if (config) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_WEB_SEARCH, config);
|
||||
} else {
|
||||
localStorageAdapter.remove(STORAGE_KEY_AI_WEB_SEARCH);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setQuickMessages = useCallback((value: AIQuickMessage[] | ((prev: AIQuickMessage[]) => AIQuickMessage[])) => {
|
||||
setQuickMessagesRaw((prev) => {
|
||||
const nextRaw = typeof value === 'function' ? value(prev) : value;
|
||||
const next = sanitizeQuickMessages(nextRaw);
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_QUICK_MESSAGES, next);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_QUICK_MESSAGES);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ── Persist helpers ──
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
if (next === prev) return prev;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_PROVIDERS, next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, id);
|
||||
}, []);
|
||||
|
||||
const setActiveModelId = useCallback((id: string) => {
|
||||
setActiveModelIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_MODEL, id);
|
||||
}, []);
|
||||
|
||||
const setGlobalPermissionMode = useCallback((mode: AIPermissionMode) => {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_PERMISSION_MODE, mode);
|
||||
// Sync to MCP Server bridge (observer mode blocks write operations)
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetPermissionMode?.(mode);
|
||||
}, []);
|
||||
|
||||
const setHostPermissions = useCallback((value: HostAIPermission[] | ((prev: HostAIPermission[]) => HostAIPermission[])) => {
|
||||
setHostPermissionsRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
@@ -644,145 +544,14 @@ export function useAIState() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setToolIntegrationMode = useCallback((mode: AIToolIntegrationMode) => {
|
||||
setToolIntegrationModeRaw(mode);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE, mode);
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
}, []);
|
||||
|
||||
const setExternalAgents = useCallback((value: ExternalAgentConfig[] | ((prev: ExternalAgentConfig[]) => ExternalAgentConfig[])) => {
|
||||
setExternalAgentsRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_EXTERNAL_AGENTS, next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setDefaultAgentId = useCallback((id: string) => {
|
||||
setDefaultAgentIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_DEFAULT_AGENT, id);
|
||||
}, []);
|
||||
|
||||
const setCommandBlocklist = useCallback((value: string[]) => {
|
||||
setCommandBlocklistRaw(value);
|
||||
persistCommandBlocklistSetting(value);
|
||||
// Sync to MCP Server bridge so SDK agents also respect the blocklist
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetCommandBlocklist?.(value);
|
||||
}, []);
|
||||
|
||||
const setCommandTimeout = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeCommandTimeoutSeconds(value);
|
||||
setCommandTimeoutRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT, normalizedValue);
|
||||
// Sync to MCP Server bridge
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetCommandTimeout?.(normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setResponseIdleTimeout = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeResponseIdleTimeoutSeconds(value);
|
||||
setResponseIdleTimeoutRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT, normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setMaxIterations = useCallback((value: number) => {
|
||||
setMaxIterationsRaw(value);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, value);
|
||||
// Sync to MCP Server bridge (used by SDK agent path)
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
// ── Cross-window sync via storage events ──
|
||||
// When the settings window updates localStorage, the main window picks up changes.
|
||||
// Shared AI settings sync is handled by useSharedAISettingsState; this
|
||||
// listener handles session/agent/host-permission keys owned by useAIState.
|
||||
useEffect(() => {
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
try {
|
||||
const key = e.key;
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_PROVIDERS: {
|
||||
const parsed = localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS);
|
||||
if (parsed != null && !Array.isArray(parsed)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_PROVIDERS is not an array, skipping');
|
||||
break;
|
||||
}
|
||||
setProvidersRaw(parsed ?? []);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_ACTIVE_PROVIDER:
|
||||
setActiveProviderIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_ACTIVE_MODEL:
|
||||
setActiveModelIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE: {
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (mode === 'observer' || mode === 'confirm' || mode === 'auto') {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE:
|
||||
{
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE) === 'skills'
|
||||
? 'skills'
|
||||
: 'mcp';
|
||||
setToolIntegrationModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
}
|
||||
break;
|
||||
case STORAGE_KEY_AI_EXTERNAL_AGENTS: {
|
||||
const agents = localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS);
|
||||
if (agents != null && !Array.isArray(agents)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_EXTERNAL_AGENTS is not an array, skipping');
|
||||
break;
|
||||
}
|
||||
setExternalAgentsRaw(agents ?? []);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_DEFAULT_AGENT:
|
||||
setDefaultAgentIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT) ?? 'catty');
|
||||
break;
|
||||
case STORAGE_KEY_AI_COMMAND_BLOCKLIST: {
|
||||
const blocklist = readCommandBlocklistSetting();
|
||||
setCommandBlocklistRaw(blocklist);
|
||||
getAIBridge()?.aiMcpSetCommandBlocklist?.(blocklist);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_COMMAND_TIMEOUT: {
|
||||
const timeout = localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS;
|
||||
if (!Number.isFinite(timeout)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_COMMAND_TIMEOUT is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
const normalizedTimeout = normalizeCommandTimeoutSeconds(timeout);
|
||||
setCommandTimeoutRaw(normalizedTimeout);
|
||||
getAIBridge()?.aiMcpSetCommandTimeout?.(normalizedTimeout);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT: {
|
||||
const timeout = localStorageAdapter.readNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT)
|
||||
?? DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS;
|
||||
if (!Number.isFinite(timeout)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_RESPONSE_IDLE_TIMEOUT is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
setResponseIdleTimeoutRaw(normalizeResponseIdleTimeoutSeconds(timeout));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_MAX_ITERATIONS: {
|
||||
const iters = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20;
|
||||
if (!Number.isFinite(iters)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_MAX_ITERATIONS is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
setMaxIterationsRaw(iters);
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_HOST_PERMISSIONS: {
|
||||
const perms = localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS);
|
||||
if (perms != null && !Array.isArray(perms)) {
|
||||
@@ -817,14 +586,6 @@ export function useAIState() {
|
||||
setActiveSessionIdMapRaw(nextActiveSessionIdMap);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_WEB_SEARCH:
|
||||
setWebSearchConfigRaw(localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null);
|
||||
break;
|
||||
case STORAGE_KEY_AI_QUICK_MESSAGES: {
|
||||
const messages = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES);
|
||||
setQuickMessagesRaw(sanitizeQuickMessages(messages));
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAIState] Cross-window sync: failed to process storage event for key', e.key, err);
|
||||
@@ -896,30 +657,6 @@ export function useAIState() {
|
||||
})();
|
||||
}), []);
|
||||
|
||||
// ── Sync initial safety settings to MCP Server on mount ──
|
||||
useEffect(() => {
|
||||
const bridge = getAIBridge();
|
||||
const initialBlocklist = readCommandBlocklistSetting();
|
||||
bridge?.aiMcpSetCommandBlocklist?.(initialBlocklist);
|
||||
const initialTimeout = normalizeCommandTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
);
|
||||
bridge?.aiMcpSetCommandTimeout?.(initialTimeout);
|
||||
const initialMaxIter = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20;
|
||||
bridge?.aiMcpSetMaxIterations?.(initialMaxIter);
|
||||
const storedPermMode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
const initialPermMode: AIPermissionMode =
|
||||
storedPermMode === 'observer' || storedPermMode === 'confirm' || storedPermMode === 'auto'
|
||||
? storedPermMode
|
||||
: 'confirm';
|
||||
bridge?.aiMcpSetPermissionMode?.(initialPermMode);
|
||||
const initialToolMode: AIToolIntegrationMode =
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE) === 'skills'
|
||||
? 'skills'
|
||||
: 'mcp';
|
||||
bridge?.aiMcpSetToolIntegrationMode?.(initialToolMode);
|
||||
}, []);
|
||||
|
||||
// ── Session CRUD ──
|
||||
const persistSessions = useCallback((next: AISession[], deletedSessionIds?: readonly string[]) => {
|
||||
writeSessionsForStorage(next, { deletedSessionIds });
|
||||
@@ -1664,51 +1401,6 @@ export function useAIState() {
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
// ── Provider CRUD helpers ──
|
||||
const addProvider = useCallback((provider: ProviderConfig) => {
|
||||
setProviders(prev => [...prev, provider]);
|
||||
}, [setProviders]);
|
||||
|
||||
const updateProvider = useCallback((id: string, updates: Partial<ProviderConfig>) => {
|
||||
setProviders((prev) => {
|
||||
const index = prev.findIndex((provider) => provider.id === id);
|
||||
if (index < 0) return prev;
|
||||
const current = prev[index];
|
||||
if (providerPatchIsNoop(current, updates)) return prev;
|
||||
const next = prev.slice();
|
||||
next[index] = { ...current, ...updates };
|
||||
return next;
|
||||
});
|
||||
}, [setProviders]);
|
||||
|
||||
const removeProvider = useCallback((id: string) => {
|
||||
setProviders(prev => prev.filter(p => p.id !== id));
|
||||
setActiveProviderIdRaw(prevId => {
|
||||
if (prevId === id) {
|
||||
const next = '';
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, next);
|
||||
return next;
|
||||
}
|
||||
return prevId;
|
||||
});
|
||||
const cleanup = removeProviderReferences(
|
||||
id,
|
||||
agentProviderMapRef.current,
|
||||
agentModelMapRef.current,
|
||||
);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
setAgentProviderMapRaw(cleanup.agentProviderMap);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
setAgentModelMapRaw(cleanup.agentModelMap);
|
||||
}
|
||||
}, [setProviders]);
|
||||
|
||||
// ── Computed ──
|
||||
const activeProvider = providers.find(p => p.id === activeProviderId) ?? null;
|
||||
|
||||
// Stream/message updates publish here so AIConfig Context consumers do not
|
||||
// re-render on every token. AIChatPanelsHost reads aiSessionsStore instead.
|
||||
useLayoutEffect(() => {
|
||||
@@ -1749,6 +1441,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
@@ -1816,6 +1510,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
|
||||
@@ -317,3 +317,320 @@ test("edited theme previews cannot grow the chrome CSS cache without bound", ()
|
||||
assert.equal(stats.size, CHROME_THEME_CSS_CACHE_MAX_ENTRIES);
|
||||
assert.equal(stats.keys.at(-1), latestFingerprint);
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme skips style rewrite and IPCs on same-fingerprint clone switches", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSnapshot = getSettingsChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const baseTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "dark");
|
||||
const otherTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "light");
|
||||
assert.ok(baseTheme);
|
||||
assert.ok(otherTheme);
|
||||
const applyAppTheme = () => {};
|
||||
|
||||
function Harness({ activeTheme }: { activeTheme: typeof baseTheme }) {
|
||||
useActiveChromeTheme({ activeTheme: activeTheme!, applyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { activeTheme: baseTheme }));
|
||||
});
|
||||
|
||||
const styleEl = document.getElementById("netcatty-active-chrome-theme") as HTMLStyleElement | null;
|
||||
assert.ok(styleEl, "initial mount should inject the chrome style tag");
|
||||
assert.equal(themeCalls.length, 1);
|
||||
assert.equal(backgroundCalls.length, 1);
|
||||
|
||||
// Track any writes to styleEl.textContent after initial mount.
|
||||
const textContentDescriptor = Object.getOwnPropertyDescriptor(
|
||||
dom.window.Node.prototype,
|
||||
"textContent",
|
||||
);
|
||||
assert.ok(textContentDescriptor?.get && textContentDescriptor?.set);
|
||||
let styleWrites = 0;
|
||||
Object.defineProperty(styleEl, "textContent", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return textContentDescriptor.get!.call(this);
|
||||
},
|
||||
set(value: string | null) {
|
||||
styleWrites += 1;
|
||||
textContentDescriptor.set!.call(this, value);
|
||||
},
|
||||
});
|
||||
|
||||
// Switch to a structurally equal clone with a new object reference but identical fingerprint.
|
||||
const clonedTheme = { ...baseTheme, colors: { ...baseTheme.colors } };
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { activeTheme: clonedTheme }));
|
||||
});
|
||||
|
||||
assert.equal(styleWrites, 0, "same-fingerprint clone must not rewrite <style>");
|
||||
assert.equal(themeCalls.length, 1, "same-fingerprint clone must not invoke setTheme IPC");
|
||||
assert.equal(backgroundCalls.length, 1, "same-fingerprint clone must not invoke setBackgroundColor IPC");
|
||||
|
||||
// Switching to a genuinely different theme must still update <style> and IPCs.
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { activeTheme: otherTheme }));
|
||||
});
|
||||
|
||||
assert.equal(styleWrites, 1, "different theme fingerprint must update <style>");
|
||||
assert.equal(themeCalls.length, 2, "different theme fingerprint must invoke setTheme IPC");
|
||||
assert.equal(backgroundCalls.length, 2, "different theme fingerprint must invoke setBackgroundColor IPC");
|
||||
assert.equal(backgroundCalls.at(-1), otherTheme.colors.background);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme refreshes surfaces when theme mode, pluginThemeRevision, or applyAppTheme changes", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
const { pluginThemeRegistry } = await import("../../infrastructure/config/pluginThemeRegistry");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSnapshot = getSettingsChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const theme = TERMINAL_THEMES.find((candidate) => candidate.type === "dark");
|
||||
assert.ok(theme);
|
||||
const initialApplyAppTheme = () => {};
|
||||
|
||||
function Harness({ applyAppTheme }: { applyAppTheme: () => void }) {
|
||||
useActiveChromeTheme({ activeTheme: theme!, applyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { applyAppTheme: initialApplyAppTheme }));
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark"]);
|
||||
assert.equal(backgroundCalls.length, 1);
|
||||
|
||||
// 1. Switching theme 'dark' -> 'system' while resolvedTheme stays 'dark' must still refresh surfaces.
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "system", resolvedTheme: "dark" });
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark", "system"]);
|
||||
assert.equal(backgroundCalls.length, 2);
|
||||
|
||||
// And switching 'system' -> 'dark' while resolvedTheme stays 'dark' must also refresh surfaces.
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark", "system", "dark"]);
|
||||
assert.equal(backgroundCalls.length, 3);
|
||||
|
||||
// 2. Bumping pluginThemeRevision must still refresh surfaces.
|
||||
document.documentElement.className = "light";
|
||||
await act(async () => {
|
||||
pluginThemeRegistry.setCatalog({ ...pluginThemeRegistry.getCatalog() });
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("dark"), true);
|
||||
assert.equal(themeCalls.length, 4);
|
||||
assert.equal(backgroundCalls.length, 4);
|
||||
|
||||
// 3. Changing applyAppTheme identity must still refresh surfaces.
|
||||
document.documentElement.className = "light";
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { applyAppTheme: () => {} }));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("dark"), true);
|
||||
assert.equal(themeCalls.length, 5);
|
||||
assert.equal(backgroundCalls.length, 5);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme restores terminal surfaces when UI palette or accent changes with a stable applyAppTheme wrapper", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
const { getAppearanceChromeSnapshot, publishAppearanceChromeSnapshot } = await import("./appearanceChromeStore");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSettingsSnapshot = getSettingsChromeSnapshot();
|
||||
const originalAppearanceSnapshot = getAppearanceChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const lightTerminalTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "light");
|
||||
assert.ok(lightTerminalTheme);
|
||||
// ChromeHost passes a permanently stable applyAppTheme callback wrapper.
|
||||
const stableApplyAppTheme = () => {};
|
||||
|
||||
function Harness({ activeTheme }: { activeTheme: typeof lightTerminalTheme }) {
|
||||
useActiveChromeTheme({ activeTheme: activeTheme!, applyAppTheme: stableApplyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "default",
|
||||
lightUiThemeId: "default",
|
||||
});
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "custom",
|
||||
customAccent: "210 90% 50%",
|
||||
});
|
||||
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { activeTheme: lightTerminalTheme }));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 1. Dark UI palette changes while light terminal stays active (with a cloned
|
||||
// theme object of identical fingerprint). Simulate applyThemeTokens resetting
|
||||
// root class and native window background to dark app palette first.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "midnight",
|
||||
lightUiThemeId: "default",
|
||||
});
|
||||
renderer!.render(createElement(Harness, {
|
||||
activeTheme: { ...lightTerminalTheme, colors: { ...lightTerminalTheme.colors } },
|
||||
}));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 2. Light UI palette changes.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "midnight",
|
||||
lightUiThemeId: "paper",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 3. Accent mode / custom accent changes while light terminal stays active.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "custom",
|
||||
customAccent: "340 80% 55%",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "theme",
|
||||
customAccent: "340 80% 55%",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSettingsSnapshot);
|
||||
publishAppearanceChromeSnapshot(originalAppearanceSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { pluginThemeRegistry } from '../../infrastructure/config/pluginThemeRegistry';
|
||||
import { useAppearanceChromeStore } from './appearanceChromeStore';
|
||||
import { usePluginThemeRevision } from './usePluginThemeRuntime';
|
||||
import { getSettingsChromeSnapshot, useSettingsChromeStore } from './settingsChromeStore';
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
@@ -10,46 +11,12 @@ import {
|
||||
import { runThemeTransition } from "./themeTransition";
|
||||
import { TERMINAL_THEMES } from "../../infrastructure/config/terminalThemes";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import { resolveReadableForegroundForHsl } from "../../domain/colorContrast";
|
||||
|
||||
function hexToHsl(hex: string): string {
|
||||
const r = parseInt(hex.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(hex.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(hex.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightness(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextLightness = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(nextLightness * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturation(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextSaturation = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(nextSaturation * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from "../../domain/colorContrast";
|
||||
|
||||
const CSS_VARS = [
|
||||
"background",
|
||||
@@ -74,15 +41,15 @@ const CSS_VARS = [
|
||||
] as const;
|
||||
|
||||
function buildChromeCss(theme: TerminalTheme): string {
|
||||
const bg = hexToHsl(theme.colors.background);
|
||||
const fg = hexToHsl(theme.colors.foreground);
|
||||
const cursor = hexToHsl(theme.colors.cursor);
|
||||
const bg = hexToHslToken(theme.colors.background);
|
||||
const fg = hexToHslToken(theme.colors.foreground);
|
||||
const cursor = hexToHslToken(theme.colors.cursor);
|
||||
const isDark = theme.type === "dark";
|
||||
const card = adjustLightness(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightness(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightness(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturation(adjustLightness(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightness(bg, isDark ? 12 : -10);
|
||||
const card = adjustLightnessToken(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightnessToken(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightnessToken(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturationToken(adjustLightnessToken(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightnessToken(bg, isDark ? 12 : -10);
|
||||
const primaryFg = resolveReadableForegroundForHsl(cursor);
|
||||
|
||||
const values = [
|
||||
@@ -278,17 +245,60 @@ export function useActiveChromeTheme({
|
||||
applyAppTheme: () => void;
|
||||
}) {
|
||||
const pluginThemeRevision = usePluginThemeRevision();
|
||||
const { resolvedTheme } = useSettingsChromeStore();
|
||||
const { theme, resolvedTheme, lightUiThemeId, darkUiThemeId } = useSettingsChromeStore();
|
||||
const { accentMode, customAccent } = useAppearanceChromeStore();
|
||||
const effectiveTheme = pluginThemeRegistry.isActive(resolvedTheme) ? null : activeTheme;
|
||||
const applyAppThemeRef = useRef(applyAppTheme);
|
||||
applyAppThemeRef.current = applyAppTheme;
|
||||
const prevSurfaceTriggersRef = useRef({
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
pluginThemeRevision,
|
||||
applyAppTheme,
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// Settings may have just applied the OS theme over a fixed terminal theme.
|
||||
// Reassert its visual surfaces even when the terminal fingerprint is stable;
|
||||
// tab-switch callers retain the default fingerprint fast path.
|
||||
syncActiveChromeTheme(effectiveTheme, applyAppTheme, { refreshSurfaces: true });
|
||||
}, [effectiveTheme, applyAppTheme, pluginThemeRevision, resolvedTheme]);
|
||||
const prev = prevSurfaceTriggersRef.current;
|
||||
const refreshSurfaces =
|
||||
prev.theme !== theme ||
|
||||
prev.resolvedTheme !== resolvedTheme ||
|
||||
prev.lightUiThemeId !== lightUiThemeId ||
|
||||
prev.darkUiThemeId !== darkUiThemeId ||
|
||||
prev.accentMode !== accentMode ||
|
||||
prev.customAccent !== customAccent ||
|
||||
prev.pluginThemeRevision !== pluginThemeRevision ||
|
||||
prev.applyAppTheme !== applyAppTheme;
|
||||
prevSurfaceTriggersRef.current = {
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
pluginThemeRevision,
|
||||
applyAppTheme,
|
||||
};
|
||||
|
||||
// Settings or plugin themes may have just applied the app theme over a fixed
|
||||
// terminal theme. Reassert its visual surfaces only when one of those
|
||||
// surface-refresh triggers changed; same-theme tab switches retain the
|
||||
// default fingerprint fast path.
|
||||
syncActiveChromeTheme(effectiveTheme, applyAppTheme, { refreshSurfaces });
|
||||
}, [
|
||||
effectiveTheme,
|
||||
applyAppTheme,
|
||||
pluginThemeRevision,
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -2,8 +2,8 @@ import { useCallback } from 'react';
|
||||
import { STORAGE_KEY_COMPOSE_BAR_HEIGHT } from '../../infrastructure/config/storageKeys';
|
||||
import { useStoredNumber } from './useStoredNumber';
|
||||
|
||||
export const COMPOSE_BAR_HEIGHT_DEFAULT = 144;
|
||||
export const COMPOSE_BAR_HEIGHT_MIN = 104;
|
||||
export const COMPOSE_BAR_HEIGHT_DEFAULT = 120;
|
||||
export const COMPOSE_BAR_HEIGHT_MIN = 72;
|
||||
export const COMPOSE_BAR_HEIGHT_MAX = 360;
|
||||
|
||||
const HEIGHT_CLAMP = { min: COMPOSE_BAR_HEIGHT_MIN, max: COMPOSE_BAR_HEIGHT_MAX };
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act } from 'react-test-renderer';
|
||||
import { STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS } from '../../infrastructure/config/storageKeys';
|
||||
import { useComposeBarPinnedSnippets } from './useComposeBarPinnedSnippets';
|
||||
|
||||
function setupDom(t: test.TestContext) {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const globals = ['window', 'document', 'localStorage', 'CustomEvent', 'Event', 'StorageEvent'] as const;
|
||||
const originals = globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
for (const name of globals) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
|
||||
}
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
const rootElement = dom.window.document.querySelector('#root')!;
|
||||
const root = createRoot(rootElement);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [name, descriptor] of originals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
});
|
||||
return { dom, root };
|
||||
}
|
||||
|
||||
test('useComposeBarPinnedSnippets persists reordered pins, ignores unknown IDs, and syncs sibling instances', async (t) => {
|
||||
const { dom, root } = setupDom(t);
|
||||
dom.window.localStorage.setItem(
|
||||
STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS,
|
||||
JSON.stringify(['s1', 's2', 's3']),
|
||||
);
|
||||
|
||||
type HookResult = ReturnType<typeof useComposeBarPinnedSnippets>;
|
||||
let firstHook!: HookResult;
|
||||
let secondHook!: HookResult;
|
||||
|
||||
function Harness({ snippetIdKey }: { snippetIdKey: string }) {
|
||||
firstHook = useComposeBarPinnedSnippets(snippetIdKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
function SiblingHarness({ snippetIdKey }: { snippetIdKey: string }) {
|
||||
secondHook = useComposeBarPinnedSnippets(snippetIdKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<>
|
||||
<Harness snippetIdKey={'s1\0s2\0s3'} />
|
||||
<SiblingHarness snippetIdKey={'s1\0s2\0s3'} />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s1', 's2', 's3']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s1', 's2', 's3']);
|
||||
|
||||
await act(async () => {
|
||||
firstHook.reorder('s3', 's1', 'before');
|
||||
});
|
||||
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['s3', 's1', 's2'],
|
||||
);
|
||||
|
||||
// Unknown/deleted drag IDs are ignored without corrupting persisted order.
|
||||
await act(async () => {
|
||||
firstHook.reorder('deleted-snippet', 's1', 'before');
|
||||
firstHook.reorder('s2', 'missing-target', 'after');
|
||||
});
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
|
||||
// Deleting a snippet prunes it while keeping the customized order of remaining pins.
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<>
|
||||
<Harness snippetIdKey={'s3\0s2'} />
|
||||
<SiblingHarness snippetIdKey={'s3\0s2'} />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's2']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s3', 's2']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['s3', 's2'],
|
||||
);
|
||||
});
|
||||
|
||||
test('useComposeBarPinnedSnippets still seeds defaults on first run when vault snippets are present', async (t) => {
|
||||
const { dom, root } = setupDom(t);
|
||||
type HookResult = ReturnType<typeof useComposeBarPinnedSnippets>;
|
||||
let hook!: HookResult;
|
||||
|
||||
function Harness() {
|
||||
hook = useComposeBarPinnedSnippets('a\0b', ['a', 'b']);
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
|
||||
assert.deepEqual(hook.pinnedIds, ['a', 'b']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['a', 'b'],
|
||||
);
|
||||
});
|
||||
Loaded 100 of 758 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user