mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 20:00:51 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470628b1a3 | ||
|
|
ef99e0daf7 | ||
|
|
18a9000278 | ||
|
|
ed9da31034 | ||
|
|
3d302e2456 | ||
|
|
5e4195bf7f | ||
|
|
9c292460e3 | ||
|
|
8b3832feef | ||
|
|
83d0d5f949 | ||
|
|
0a4ff8875f | ||
|
|
8433302959 | ||
|
|
51cb14955c | ||
|
|
1d5cef09ec | ||
|
|
17d53152ec | ||
|
|
cf7f998689 | ||
|
|
db3a9e88e2 | ||
|
|
65435c06f5 | ||
|
|
3096f86889 | ||
|
|
94f8bd9bc7 | ||
|
|
5cd42cb518 | ||
|
|
f05ea0c9b7 | ||
|
|
9ccb62ea07 | ||
|
|
d0fffac598 | ||
|
|
106e39a797 | ||
|
|
3bf4c9df1a |
No files matched your search
@@ -1220,6 +1220,23 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
|
||||
}
|
||||
}
|
||||
|
||||
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
|
||||
const { addConnectionLog, systemInfoRef } = getCtx();
|
||||
const { username, hostname } = systemInfoRef.current;
|
||||
addConnectionLog({
|
||||
sessionId: session.id,
|
||||
hostId: session.hostId,
|
||||
hostLabel: session.hostLabel,
|
||||
hostname: session.hostname,
|
||||
username: session.username,
|
||||
protocol: session.protocol || 'ssh',
|
||||
startTime: Date.now(),
|
||||
localUsername: username,
|
||||
localHostname: hostname,
|
||||
saved: false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, sessionId: string, data: string) {
|
||||
const { IS_DEV, connectionLogs, selectConnectionLogForTerminalDataCapture, sessions, updateConnectionLog } = getCtx();
|
||||
{
|
||||
|
||||
@@ -104,7 +104,7 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
|
||||
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
|
||||
import { createOpenTerminalQueue } from './openTerminalQueue';
|
||||
import { useAppStartupEffects } from './useAppStartupEffects';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
|
||||
type OpenSessionInNewWindowPayload = {
|
||||
title?: string;
|
||||
@@ -1895,8 +1895,18 @@ export function AppSideEffects() {
|
||||
setActiveTabId('vault');
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const restoredSessionLogsStartedRef = useRef(new Set<string>());
|
||||
// A restored tab retains its session ID, but its previous ConnectionLog is closed.
|
||||
// Start the new incarnation's log before updateSessionStatus clears restoreState.
|
||||
// Wrap updateSessionStatus to track lastConnectedAt on successful connection
|
||||
const handleSessionStatusChange = useCallback((sessionId: string, status: TerminalSession['status']) => {
|
||||
const session = sessionByIdRef.current.get(sessionId);
|
||||
if (session?.restoreState === 'restored-disconnected'
|
||||
&& (status === 'connecting' || status === 'connected')
|
||||
&& !restoredSessionLogsStartedRef.current.has(sessionId)) {
|
||||
restoredSessionLogsStartedRef.current.add(sessionId);
|
||||
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog, systemInfoRef }), session);
|
||||
}
|
||||
updateSessionStatus(sessionId, status);
|
||||
if (status === 'connected') {
|
||||
const session = sessionByIdRef.current.get(sessionId);
|
||||
@@ -1904,7 +1914,7 @@ export function AppSideEffects() {
|
||||
updateHostLastConnected(session.hostId);
|
||||
}
|
||||
}
|
||||
}, [updateSessionStatus, updateHostLastConnected]);
|
||||
}, [addConnectionLog, updateSessionStatus, updateHostLastConnected]);
|
||||
|
||||
const handleUpdateHostFromTerminal = useCallback((host: TerminalHostUpdate) => {
|
||||
// Functional update + identity-preserving updateHosts: only the patched
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
|
||||
import { useSessionState } from '../state/useSessionState';
|
||||
import { captureClosingTerminalSessions, useTerminalSessionCloseCapture } from '../state/terminalSessionCloseCapture';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
|
||||
import { TerminalConnectionProgress } from '../../components/terminal/TerminalConnectionProgress';
|
||||
import { I18nProvider } from '../i18n/I18nProvider';
|
||||
import { handleTerminalDataCaptureImpl } from './AppHandlers';
|
||||
|
||||
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
test('explicit close persists never-connected logs; runtime remounts leave them open', async (t) => {
|
||||
const dom = new JSDOM('', { url: 'http://localhost' });
|
||||
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
|
||||
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
Object.defineProperties(globalThis, {
|
||||
window: { value: dom.window, configurable: true },
|
||||
localStorage: { value: dom.window.localStorage, configurable: true },
|
||||
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
|
||||
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
|
||||
});
|
||||
installBrowserLockFixture();
|
||||
const { useVaultState } = await import('../state/useVaultState');
|
||||
try {
|
||||
for (const scenario of [
|
||||
{ name: 'tab X before connected, empty buffer', status: 'connecting', data: '' },
|
||||
{ name: 'failed-dialog close, empty buffer', status: 'disconnected', data: '' },
|
||||
{ name: 'failed-dialog close preserves buffered diagnostics', status: 'disconnected', data: 'SSH diagnostic\r\n' },
|
||||
{ name: 'batch close before connected', status: 'connecting', data: '', closeMode: 'batch' },
|
||||
{ name: 'workspace close before connected', status: 'connecting', data: '', closeMode: 'workspace' },
|
||||
] as const) {
|
||||
await t.test(scenario.name, async () => {
|
||||
let vault!: ReturnType<typeof useVaultState>;
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
let root: ReactTestRenderer | undefined;
|
||||
let sessionId!: string;
|
||||
let logId!: string;
|
||||
const captures: Promise<void>[] = [];
|
||||
const capturedData: string[] = [];
|
||||
function TerminalProbe() {
|
||||
const hasConnectedRef = useRef(false);
|
||||
const terminalDataCapturedRef = useRef(false);
|
||||
const buffer = useRef(createConnectionLogBuffer(10000));
|
||||
useEffect(() => {
|
||||
buffer.current.append(scenario.data);
|
||||
return () => { buffer.current.reset(); };
|
||||
}, []);
|
||||
useTerminalSessionCloseCapture({
|
||||
sessionId, enabled: true, hasConnectedRef, terminalDataCapturedRef,
|
||||
finalizeTerminalLogData: () => buffer.current.toString(),
|
||||
onTerminalDataCapture: (id, data, options) => {
|
||||
assert.equal(options.finalized, true);
|
||||
assert.ok(state.sessions.some((session) => session.id === id), 'capture starts before removal');
|
||||
terminalDataCapturedRef.current = true;
|
||||
capturedData.push(data);
|
||||
const pending = handleTerminalDataCaptureImpl(() => ({
|
||||
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: state.sessions,
|
||||
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
|
||||
}), id, data);
|
||||
captures.push(pending);
|
||||
return pending;
|
||||
},
|
||||
});
|
||||
return scenario.status === 'disconnected' ? React.createElement(
|
||||
I18nProvider, { locale: 'en' }, React.createElement(TerminalConnectionProgress, {
|
||||
status: 'disconnected', error: 'Connection refused', timeLeft: 0,
|
||||
isCancelling: false, showLogs: false, progressLogs: [],
|
||||
onCancelConnect: () => {}, onCloseSession: () => state.closeSession(sessionId),
|
||||
}),
|
||||
) : null;
|
||||
}
|
||||
function Probe({ showTerminal = true }) {
|
||||
vault = useVaultState();
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return showTerminal && state.sessions.some((session) => session.id === sessionId)
|
||||
? React.createElement(TerminalProbe) : null;
|
||||
}
|
||||
const mount = async () => {
|
||||
await act(async () => { root = create(React.createElement(Probe)); });
|
||||
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
|
||||
await act(async () => { await tick(); });
|
||||
}
|
||||
assert.equal(vault.isInitialized, true);
|
||||
};
|
||||
try {
|
||||
await mount();
|
||||
await act(async () => { sessionId = state.createLocalTerminal(); });
|
||||
await act(async () => {
|
||||
state.updateSessionStatus(sessionId, scenario.status);
|
||||
const session = state.sessions.find((candidate) => candidate.id === sessionId)!;
|
||||
logId = vault.addConnectionLog({
|
||||
sessionId, hostId: session.hostId, hostLabel: session.hostLabel,
|
||||
hostname: session.hostname, username: session.username,
|
||||
protocol: session.protocol, startTime: Date.now(),
|
||||
localUsername: 'local-user', localHostname: 'local-host', saved: false,
|
||||
});
|
||||
await vault.updateConnectionLog(logId, {});
|
||||
});
|
||||
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
|
||||
let otherId!: string;
|
||||
await act(async () => { otherId = state.createLocalTerminal(); });
|
||||
await act(async () => { state.createWorkspaceFromSessions(sessionId, otherId, 'right'); });
|
||||
}
|
||||
// Recycle the renderer while retaining the session, as with a pane
|
||||
// remount. Neither disposal nor the replacement runtime may end its log.
|
||||
await act(async () => { root!.update(React.createElement(Probe, { showTerminal: false })); });
|
||||
await act(async () => { root!.update(React.createElement(Probe)); });
|
||||
assert.equal(captures.length, 0);
|
||||
assert.equal(vault.connectionLogs.find((log) => log.id === logId)?.endTime, undefined);
|
||||
|
||||
// Both UI actions converge here. This exercises the actual state
|
||||
// removal, owning-terminal hook, capture handler and vault persistence.
|
||||
await act(async () => {
|
||||
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
|
||||
state.closeWorkspace(state.workspaces[0].id);
|
||||
} else if ('closeMode' in scenario && scenario.closeMode === 'batch') {
|
||||
state.closeSessions([sessionId]);
|
||||
} else if (scenario.status === 'disconnected') {
|
||||
// Click the actual Close button rendered inside the failed dialog.
|
||||
root!.root.findByType('button').props.onClick();
|
||||
} else {
|
||||
state.closeSession(sessionId);
|
||||
}
|
||||
await Promise.all(captures);
|
||||
});
|
||||
assert.equal(state.sessions.some((session) => session.id === sessionId), false);
|
||||
assert.deepEqual(capturedData, [scenario.data]);
|
||||
await act(async () => { state.closeSession(sessionId); });
|
||||
assert.equal(captures.length, 1, 'removed runtimes must unregister their capture');
|
||||
await act(async () => { root!.unmount(); });
|
||||
root = undefined;
|
||||
await mount();
|
||||
const persisted = vault.connectionLogs.find((log) => log.id === logId)!;
|
||||
assert.ok(persisted.endTime, 'a durable endTime must exist even without terminal output');
|
||||
assert.equal(persisted.terminalData || '', scenario.data);
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
dom.window.close();
|
||||
for (const key of globals) {
|
||||
const descriptor = previous.get(key);
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('close capture skips non-owning, already connected and already captured runtimes', async (t) => {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
|
||||
try {
|
||||
for (const scenario of [
|
||||
{ name: 'attached popup / inactive restored placeholder', enabled: false, connected: false, captured: false },
|
||||
{ name: 'connected terminal uses existing drain path', enabled: true, connected: true, captured: false },
|
||||
{ name: 'quit already captured the log', enabled: true, connected: false, captured: true },
|
||||
]) {
|
||||
await t.test(scenario.name, async () => {
|
||||
let calls = 0;
|
||||
let root!: ReactTestRenderer;
|
||||
function Probe() {
|
||||
useTerminalSessionCloseCapture({
|
||||
sessionId: 'guarded', enabled: scenario.enabled,
|
||||
hasConnectedRef: useRef(scenario.connected),
|
||||
terminalDataCapturedRef: useRef(scenario.captured),
|
||||
finalizeTerminalLogData: () => { calls++; return ''; },
|
||||
onTerminalDataCapture: () => { calls++; },
|
||||
});
|
||||
return null;
|
||||
}
|
||||
await act(async () => { root = create(React.createElement(Probe)); });
|
||||
try {
|
||||
await act(async () => { captureClosingTerminalSessions(['guarded']); });
|
||||
assert.equal(calls, 0);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (previous) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previous);
|
||||
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('both UI close paths reach session removal and Terminal registers the owning capture', () => {
|
||||
const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
const app = read('./AppView.tsx');
|
||||
assert.match(app, /onCloseSession=\{closeSession\}/);
|
||||
assert.match(read('../../components/top-tabs/TopTabItems.tsx'), /onClick=\{\(e\) => onCloseSession\(session\.id, e\)\}/);
|
||||
const terminal = read('../../components/Terminal.tsx');
|
||||
assert.match(terminal, /useTerminalSessionCloseCapture\(\{\s*sessionId,\s*enabled: !attachExistingSession && restoreState !== "restored-disconnected",\s*hasConnectedRef,\s*terminalDataCapturedRef,\s*finalizeTerminalLogData,\s*onTerminalDataCapture: handleTerminalDataCaptureOnce,/);
|
||||
const handler = terminal.slice(terminal.indexOf('const handleCloseDisconnectedSession ='), terminal.indexOf('const handleHostKeyClose ='));
|
||||
assert.match(handler, /onCloseSession\?\.\(sessionId\)/);
|
||||
assert.match(read('../../components/TerminalLayer.tsx'), /onCloseSession\(sessionId\)/);
|
||||
assert.match(read('../../components/terminal/TerminalView.tsx'), /onCloseSession: handleCloseDisconnectedSession/);
|
||||
assert.match(read('../../components/terminal/TerminalConnectionProgress.tsx'), /onClick=\{onCloseSession\}/);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
|
||||
import { withVaultImportLock } from '../state/vaultManagedImportLock';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import type { TerminalSession } from '../../domain/models';
|
||||
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
|
||||
import { handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl } from './AppHandlers';
|
||||
import { createPreloadApi } from '../../electron/preload/api.cjs';
|
||||
import { finalizeSessionLogs } from '../../electron/bridges/sessionLogShutdown.cjs';
|
||||
|
||||
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
test('quit persists replay before acknowledgment; restored reconnect keeps the old log and starts a new one', async () => {
|
||||
const dom = new JSDOM('', { url: 'http://localhost' });
|
||||
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
|
||||
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
Object.defineProperties(globalThis, {
|
||||
window: { value: dom.window, configurable: true },
|
||||
localStorage: { value: dom.window.localStorage, configurable: true },
|
||||
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
|
||||
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
|
||||
});
|
||||
installBrowserLockFixture();
|
||||
const { useVaultState } = await import('../state/useVaultState');
|
||||
let vault!: ReturnType<typeof useVaultState>;
|
||||
let root: ReactTestRenderer | undefined;
|
||||
const Probe = () => { vault = useVaultState(); return null; };
|
||||
const mount = async () => {
|
||||
await act(async () => { root = create(React.createElement(Probe)); });
|
||||
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
|
||||
await act(async () => { await tick(); });
|
||||
}
|
||||
assert.equal(vault.isInitialized, true);
|
||||
};
|
||||
const session: TerminalSession = {
|
||||
id: 'restorable-tab', hostId: 'host', hostLabel: 'Host', hostname: 'host.test',
|
||||
username: 'user', protocol: 'ssh', status: 'connected',
|
||||
};
|
||||
const systemInfoRef = { current: { username: 'local-user', hostname: 'local-host' } };
|
||||
const capture = (data: string) => handleTerminalDataCaptureImpl(() => ({
|
||||
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: [session],
|
||||
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
|
||||
}), session.id, data);
|
||||
try {
|
||||
await mount();
|
||||
let oldId!: string;
|
||||
await act(async () => {
|
||||
oldId = vault.addConnectionLog({
|
||||
sessionId: session.id, hostId: session.hostId, hostLabel: session.hostLabel,
|
||||
hostname: session.hostname, username: session.username, protocol: 'ssh', startTime: 1,
|
||||
localUsername: 'local-user', localHostname: 'local-host', saved: false,
|
||||
});
|
||||
// Wait for the initial catalog write before blocking the capture write.
|
||||
await vault.updateConnectionLog(oldId, {});
|
||||
});
|
||||
const buffer = createConnectionLogBuffer(10000);
|
||||
buffer.append('output before quitting\r\n');
|
||||
const ipcMain = new EventEmitter();
|
||||
const ipcRenderer = new EventEmitter() as EventEmitter & { send: (channel: string, payload: unknown) => void };
|
||||
const webContents = { send: (channel: string, payload: unknown) => ipcRenderer.emit(channel, {}, payload) };
|
||||
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
|
||||
const api = createPreloadApi({ ipcRenderer });
|
||||
const off = api.onFinalizeSessionLogs(() => capture(buffer.toString()));
|
||||
let release!: () => void;
|
||||
const blockedWrite = withVaultImportLock('connection-logs', () => new Promise<void>((resolve) => { release = resolve; }));
|
||||
await tick();
|
||||
let acknowledged = false;
|
||||
await act(async () => {
|
||||
const quit = finalizeSessionLogs(webContents, { ipcMain }).then((success: boolean) => {
|
||||
acknowledged = true;
|
||||
assert.equal(success, true);
|
||||
});
|
||||
await tick();
|
||||
assert.equal(acknowledged, false, 'main must wait for the persistence queue');
|
||||
release();
|
||||
await blockedWrite;
|
||||
await quit;
|
||||
});
|
||||
off();
|
||||
// Remounting reads durable storage. Node has no IndexedDB, so this also
|
||||
// exercises the existing localStorage replay fallback.
|
||||
await act(async () => { root?.unmount(); });
|
||||
await mount();
|
||||
const oldLog = vault.connectionLogs.find((log) => log.id === oldId)!;
|
||||
assert.ok(oldLog.endTime);
|
||||
assert.equal(oldLog.terminalData, 'output before quitting\r\n');
|
||||
await act(async () => {
|
||||
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog: vault.addConnectionLog, systemInfoRef }), {
|
||||
...session, status: 'disconnected', restoreState: 'restored-disconnected',
|
||||
});
|
||||
});
|
||||
const newLog = vault.connectionLogs.find((log) => log.id !== oldId)!;
|
||||
assert.equal(newLog.sessionId, session.id);
|
||||
assert.equal(newLog.endTime, undefined);
|
||||
assert.equal(newLog.terminalData, undefined);
|
||||
await act(async () => { await capture('output after reconnect\r\n'); });
|
||||
await act(async () => { root?.unmount(); });
|
||||
await mount();
|
||||
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.terminalData, oldLog.terminalData);
|
||||
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.endTime, oldLog.endTime);
|
||||
assert.equal(vault.connectionLogs.find((log) => log.id === newLog.id)?.terminalData, 'output after reconnect\r\n');
|
||||
assert.ok(vault.connectionLogs.find((log) => log.id === newLog.id)?.endTime);
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
dom.window.close();
|
||||
for (const key of globals) {
|
||||
const descriptor = previous.get(key);
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('terminal quit listener drains output and awaits capture without tearing down tabs', () => {
|
||||
const source = readFileSync(new URL('../../components/Terminal.tsx', import.meta.url), 'utf8');
|
||||
const start = source.indexOf('onFinalizeSessionLogs?.(async () => {');
|
||||
assert.ok(start > 0);
|
||||
const listener = source.slice(start, source.indexOf('const attachHomeWebContentsIdRef', start));
|
||||
assert.match(listener, /await flushPendingTerminalWritesBeforeHibernate\(term\)/);
|
||||
assert.match(listener, /await handleTerminalDataCaptureOnce\(sessionId, finalizeTerminalLogData\(\), \{ finalized: true \}\)/);
|
||||
assert.doesNotMatch(listener, /closeSession|teardown/);
|
||||
const effects = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8');
|
||||
const handler = effects.slice(effects.indexOf('const handleSessionStatusChange ='), effects.indexOf('const handleUpdateHostFromTerminal ='));
|
||||
assert.ok(handler.indexOf('startRestoredSessionConnectionLogImpl(') < handler.indexOf('updateSessionStatus(sessionId, status)'));
|
||||
assert.match(handler, /restoredSessionLogsStartedRef\.current\.has\(sessionId\)/);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { enAiMessages } from './en/ai';
|
||||
import { esAiMessages } from './es/ai';
|
||||
import { ruAiMessages } from './ru/ai';
|
||||
import { zhCNAiMessages } from './zh-CN/ai';
|
||||
import { zhTWAiMessages } from './zh-TW/ai';
|
||||
|
||||
for (const [locale, messages] of Object.entries({
|
||||
en: enAiMessages, es: esAiMessages, ru: ruAiMessages,
|
||||
'zh-CN': zhCNAiMessages, 'zh-TW': zhTWAiMessages,
|
||||
})) {
|
||||
test(`${locale} translates the Catty iteration limit notice and Continue action`, () => {
|
||||
assert.ok(messages['ai.chat.iterationLimitReached']);
|
||||
assert.match(messages['ai.chat.iterationLimitReached'], /\{limit\}/);
|
||||
assert.ok(messages['ai.chat.continue']);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
|
||||
@@ -12,16 +12,23 @@ import zhTW from "./zh-TW.ts";
|
||||
// so the remaining debt stays visible instead of silently rendering in English
|
||||
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
|
||||
// Move a locale out of this list once it covers every `en` key.
|
||||
const LOCALES_PENDING_PARITY = ["ru", "zh-CN", "zh-TW"] as const;
|
||||
const LOCALES_PENDING_PARITY = ["ru"] as const;
|
||||
|
||||
const hasKey = (messages: Record<string, string>, key: string) =>
|
||||
Object.hasOwn(messages, key);
|
||||
|
||||
const interpolationTokens = (value: string) =>
|
||||
[...value.matchAll(/\{\{\s*\w+\s*\}\}|\{\s*\w+\s*\}/g)]
|
||||
[...value.matchAll(/\{\{\s*[^}]+\s*\}\}|\{\s*\w+\s*\}/g)]
|
||||
.map((match) => match[0].replace(/[{}]/g, "").trim())
|
||||
.sort();
|
||||
|
||||
test("interpolationTokens reads the :default placeholder form", () => {
|
||||
assert.deepEqual(interpolationTokens("{{name}} or {{name:default}}"), [
|
||||
"name",
|
||||
"name:default",
|
||||
]);
|
||||
});
|
||||
|
||||
test("es defines every message key that en defines", () => {
|
||||
const missing = Object.keys(en).filter((key) => !hasKey(es, key));
|
||||
|
||||
@@ -42,22 +49,31 @@ test("es defines no message keys that en does not define", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("es keeps the same interpolation placeholders as en", () => {
|
||||
const mismatched: string[] = [];
|
||||
test("every translated locale keeps the same interpolation placeholders as en", () => {
|
||||
const locales = [
|
||||
{ name: "es", messages: es },
|
||||
{ name: "ru", messages: ru },
|
||||
{ name: "zh-CN", messages: zhCN },
|
||||
{ name: "zh-TW", messages: zhTW },
|
||||
];
|
||||
|
||||
for (const key of Object.keys(es)) {
|
||||
if (!hasKey(en, key)) continue;
|
||||
for (const locale of locales) {
|
||||
const mismatched: string[] = [];
|
||||
|
||||
const expected = interpolationTokens(en[key] ?? "").join(",");
|
||||
const actual = interpolationTokens(es[key] ?? "").join(",");
|
||||
if (expected !== actual) mismatched.push(key);
|
||||
for (const key of Object.keys(locale.messages)) {
|
||||
if (!hasKey(en, key)) continue;
|
||||
|
||||
const expected = interpolationTokens(en[key] ?? "").join(",");
|
||||
const actual = interpolationTokens(locale.messages[key] ?? "").join(",");
|
||||
if (expected !== actual) mismatched.push(key);
|
||||
}
|
||||
|
||||
assert.deepEqual(
|
||||
mismatched,
|
||||
[],
|
||||
`${locale.name} changes interpolation placeholders for ${mismatched.length} keys`,
|
||||
);
|
||||
}
|
||||
|
||||
assert.deepEqual(
|
||||
mismatched,
|
||||
[],
|
||||
`es changes interpolation placeholders for ${mismatched.length} keys`,
|
||||
);
|
||||
});
|
||||
|
||||
test("every default shortcut has a label in en and es", () => {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
|
||||
@@ -121,9 +121,11 @@ export const zhCNCoreMessages: Messages = {
|
||||
'confirm.closeBusyTerminal.messageWithMore': '进程 "{command}" 及其他 {count} 个正在运行的进程将被终止。',
|
||||
'confirm.closeBusyTerminal.cancel': '取消',
|
||||
'confirm.closeBusyTerminal.close': '关闭',
|
||||
'dialog.createWorkspace.title': '创建工作区',
|
||||
'dialog.renameWorkspace.title': '重命名工作区',
|
||||
'dialog.renameSession.title': '重命名会话',
|
||||
'field.name': '名称',
|
||||
'field.selectHosts': '选择主机',
|
||||
'placeholder.workspaceName': '工作区名称',
|
||||
'placeholder.sessionName': '会话名称',
|
||||
'placeholder.searchHosts': '搜索主机或标签...',
|
||||
|
||||
@@ -969,7 +969,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'snippets.variables.placeholderDefault': '默认:{value}',
|
||||
'snippets.variables.required': '请填写此变量',
|
||||
'snippets.variables.run': '运行',
|
||||
'snippets.field.variablesHelp': '在脚本中使用 {{名称}} 或 {{名称:默认值}} 定义变量。',
|
||||
'snippets.field.variablesHelp': '在脚本中使用 {{name}} 或 {{name:default}} 作为占位符。',
|
||||
'snippets.field.variablesDetected': '变量',
|
||||
'snippets.field.variableDefault': '默认 {value}',
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
@@ -39,6 +41,15 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.providers.noApiKey': '未設定 API Key',
|
||||
'ai.providers.configure': '設定',
|
||||
'ai.providers.remove': '移除',
|
||||
'ai.providers.headers': '自訂 HTTP 請求標頭',
|
||||
'ai.providers.headers.help': '為此服務新增選用請求標頭。內容會隱藏顯示,並在儲存時加密。',
|
||||
'ai.providers.headers.name': '請求標頭名稱',
|
||||
'ai.providers.headers.value': '請求標頭內容',
|
||||
'ai.providers.headers.add': '新增請求標頭',
|
||||
'ai.providers.headers.remove': '刪除請求標頭',
|
||||
'ai.providers.headers.invalid': '請填寫有效且不重複的請求標頭。Content-Length 和 Transfer-Encoding 由應用程式自動設定。',
|
||||
'ai.providers.headers.loadError': '無法解鎖已儲存的請求標頭。請取消編輯,解鎖系統鑰匙圈後重試。',
|
||||
'ai.providers.headers.saveError': '無法安全儲存。請確認系統鑰匙圈可用後重試。',
|
||||
'ai.providers.name': '顯示名稱',
|
||||
'ai.providers.name.placeholder': '例如 我的供應商',
|
||||
'ai.providers.style': '協定風格',
|
||||
@@ -385,8 +396,8 @@ export const zhTWAiMessages: Messages = {
|
||||
"ai.privacy.cidrs.description": "每行一個 IPv4 或 IPv6 CIDR。留空則僅使用內建規則。",
|
||||
"ai.privacy.patterns": "自訂正規表示式",
|
||||
"ai.privacy.patterns.description": "每行一個相容 RE2 的模式,不含 / 分隔符號或旗標。不支援或不安全的模式會遭拒絕。",
|
||||
"ai.privacy.connectionScope": "預留位置在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
|
||||
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用預留位置。",
|
||||
"ai.privacy.connectionScope": "佔位符在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
|
||||
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用佔位符。",
|
||||
"ai.privacy.apply": "套用",
|
||||
"ai.privacy.applying": "正在套用...",
|
||||
"ai.privacy.applied": "AI 隱私設定已套用。請建立新的受管對話並重新連接外部 MCP 用戶端。",
|
||||
@@ -657,7 +668,7 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap.unit': '則訊息',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主程序處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發程序,然後重試。',
|
||||
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
|
||||
|
||||
// AI Web Search
|
||||
'ai.webSearch.title': '網路搜尋',
|
||||
|
||||
@@ -6,7 +6,7 @@ export const zhTWCoreMessages: Messages = {
|
||||
"settings.plugins.github.repository": "GitHub 儲存庫",
|
||||
"settings.plugins.github.formats": "支援 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。",
|
||||
"settings.plugins.github.busy": "正在下載、驗證或安裝套件…",
|
||||
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置腳本,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
|
||||
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置指令碼,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
|
||||
"settings.plugins.github.accept": "已審查並信任此儲存庫,且已查看宣告的權限。",
|
||||
"settings.plugins.github.confirm": "安裝並保持停用",
|
||||
"settings.plugins.github.download": "下載並審查",
|
||||
@@ -117,8 +117,8 @@ export const zhTWCoreMessages: Messages = {
|
||||
'confirm.deleteIdentity': '刪除身分 "{name}"?',
|
||||
'confirm.removeProvider': '移除供應商 "{name}"?',
|
||||
'confirm.closeBusyTerminal.title': '確認關閉',
|
||||
'confirm.closeBusyTerminal.message': '程序 "{command}" 仍在執行,關閉後會被終止。',
|
||||
'confirm.closeBusyTerminal.messageWithMore': '程序 "{command}" 及其他 {count} 個正在執行的程序將被終止。',
|
||||
'confirm.closeBusyTerminal.message': '行程 "{command}" 仍在執行,關閉後會被終止。',
|
||||
'confirm.closeBusyTerminal.messageWithMore': '行程 "{command}" 及其他 {count} 個正在執行的行程將被終止。',
|
||||
'confirm.closeBusyTerminal.cancel': '取消',
|
||||
'confirm.closeBusyTerminal.close': '關閉',
|
||||
'dialog.createWorkspace.title': '建立工作區',
|
||||
@@ -296,7 +296,7 @@ export const zhTWCoreMessages: Messages = {
|
||||
|
||||
// Settings > System > Crash Logs
|
||||
'settings.system.crashLogs.title': '崩潰日誌',
|
||||
'settings.system.crashLogs.description': '檢視主程序錯誤日誌,協助診斷異常行為。',
|
||||
'settings.system.crashLogs.description': '檢視主行程錯誤日誌,協助診斷異常行為。',
|
||||
'settings.system.crashLogs.noLogs': '未找到崩潰日誌。',
|
||||
'settings.system.crashLogs.entries': '{count} 條記錄',
|
||||
'settings.system.crashLogs.clear': '清除所有日誌',
|
||||
@@ -1245,16 +1245,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'settings.tab.plugins': '外掛程式',
|
||||
"settings.plugins.author.official": "官方維護",
|
||||
"settings.plugins.author.officialMeaning": "由 Netcatty 專案維護。這不是安全認證。",
|
||||
"settings.plugins.manager.installed": "已安裝插件",
|
||||
"settings.plugins.manager.import": "導入 .ncpkg",
|
||||
"settings.plugins.manager.preview": "導入的插件保持停用,請檢查後再啟用。",
|
||||
"settings.plugins.manager.empty": "導入本地插件包以開始使用。",
|
||||
"settings.plugins.manager.installed": "已安裝外掛",
|
||||
"settings.plugins.manager.import": "匯入 .ncpkg",
|
||||
"settings.plugins.manager.preview": "匯入的外掛保持停用,請檢查後再啟用。",
|
||||
"settings.plugins.manager.empty": "匯入本地外掛包以開始使用。",
|
||||
"settings.plugins.manager.enabled": "已啟用",
|
||||
"settings.plugins.manager.disabled": "已停用",
|
||||
"settings.plugins.manager.enable": "啟用",
|
||||
"settings.plugins.manager.disable": "停用",
|
||||
"settings.plugins.manager.remove": "卸載",
|
||||
"settings.plugins.manager.removeNote": "卸載會移除插件代碼和本地 KV 數據,保留用戶設置、秘密存儲和同步 sidecar。",
|
||||
"settings.plugins.manager.remove": "解除安裝",
|
||||
"settings.plugins.manager.removeNote": "解除安裝會移除外掛代碼和本地 KV 資料,保留使用者設定、秘密儲存和同步 sidecar。",
|
||||
"settings.plugins.permissions.statusUnknown": "狀態不明",
|
||||
"plugins.sidebar.extensions": "擴充功能頁面",
|
||||
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
|
||||
@@ -1315,44 +1315,44 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"settings.plugins.themes.invalid": "部分主題配色未通過驗證或無法使用。",
|
||||
"settings.plugins.themes.failed": "無法套用主題。",
|
||||
"settings.plugins.manager.dataTheme": "主題套件:已驗證配色,不啟動程式執行環境。",
|
||||
"settings.plugins.manager.browser": "瀏覽器運行時:特權訪問通過宿主權限代理。",
|
||||
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 文件系統和網絡能力,代理權限無法限制這些訪問。僅供開發預覽。",
|
||||
"settings.plugins.manager.data": "本地 KV 僅保留在此設備。只有明確標記為同步的非秘密設置進入加密雲 sidecar。插件包和權限授權不參與同步。",
|
||||
"settings.plugins.manager.browser": "瀏覽器運行時:特權存取通過宿主權限代理。",
|
||||
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 檔案系統和網路能力,代理權限無法限制這些存取。僅供開發預覽。",
|
||||
"settings.plugins.manager.data": "本地 KV 僅保留在此裝置。只有明確標記為同步的非秘密設置進入加密雲 sidecar。外掛包和權限授權不參與同步。",
|
||||
"settings.plugins.manager.unbounded": "未宣告更細的資源範圍,仍受應用程式驗證和所選權限模式約束。",
|
||||
"settings.plugins.openView": "開啟",
|
||||
"settings.plugins.openManager": "開啟插件管理",
|
||||
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
|
||||
"settings.plugins.sources.clearPrivate": "同时清除本来源的私有数据、授权和秘密,以便显式换源重装。此操作不可撤销。",
|
||||
"settings.plugins.openManager": "開啟外掛管理",
|
||||
"settings.plugins.sources.conflict": "此 ID 已從其他來源安裝。請先解除安裝並明確清理舊來源資料,再換源重新安裝。原來源:",
|
||||
"settings.plugins.sources.clearPrivate": "同時清除本來源的私有資料、授權和秘密,以便明確換源重新安裝。此操作無法復原。",
|
||||
"settings.plugins.sources.short.official": "官方",
|
||||
"settings.plugins.sources.short.thirdparty": "第三方",
|
||||
"settings.plugins.sources.short.local": "本機",
|
||||
"settings.plugins.sources.official": "官方市场",
|
||||
"settings.plugins.sources.thirdparty": "第三方市场",
|
||||
"settings.plugins.sources.manage": "管理来源",
|
||||
"settings.plugins.sources.select": "选择来源",
|
||||
"settings.plugins.sources.empty": "选择或添加第三方来源。",
|
||||
"settings.plugins.sources.add": "添加来源",
|
||||
"settings.plugins.sources.remove": "移除来源",
|
||||
"settings.plugins.sources.name": "来源名称",
|
||||
"settings.plugins.sources.address": "HTTPS 来源地址",
|
||||
"settings.plugins.sources.risk": "第三方来源不代表 Netcatty 维护或认可。安装前请核对真实域名、插件权限与作者。",
|
||||
"settings.plugins.sources.accept": "我信任此域名提供插件目录和软件包。此操作不会授予插件权限。",
|
||||
"settings.plugins.sources.removeNote": "保留已安装插件及数据,停止此来源更新,不会自动切换到其他来源。",
|
||||
"settings.plugins.sources.disablePlugins": "同时停用来自该来源的插件",
|
||||
"settings.plugins.sources.installConfirm": "确认第三方安装",
|
||||
"settings.plugins.sources.source": "来源",
|
||||
"settings.plugins.sources.local": "本地导入",
|
||||
"settings.plugins.sources.all": "全部来源",
|
||||
"settings.plugins.title": "插件",
|
||||
"settings.plugins.configuration": "插件設定",
|
||||
"settings.plugins.description": "管理已安裝插件,瀏覽精選目錄。",
|
||||
"settings.plugins.sources.official": "官方市集",
|
||||
"settings.plugins.sources.thirdparty": "第三方市集",
|
||||
"settings.plugins.sources.manage": "管理來源",
|
||||
"settings.plugins.sources.select": "選擇來源",
|
||||
"settings.plugins.sources.empty": "選擇或新增第三方來源。",
|
||||
"settings.plugins.sources.add": "新增來源",
|
||||
"settings.plugins.sources.remove": "移除來源",
|
||||
"settings.plugins.sources.name": "來源名稱",
|
||||
"settings.plugins.sources.address": "HTTPS 來源位址",
|
||||
"settings.plugins.sources.risk": "第三方來源不代表 Netcatty 維護或認可。安裝前請核對真實網域、外掛權限與作者。",
|
||||
"settings.plugins.sources.accept": "我信任此網域提供外掛目錄和套件。此操作不會授予外掛權限。",
|
||||
"settings.plugins.sources.removeNote": "保留已安裝外掛及資料,停止此來源更新,不會自動切換到其他來源。",
|
||||
"settings.plugins.sources.disablePlugins": "同時停用來自該來源的外掛",
|
||||
"settings.plugins.sources.installConfirm": "確認第三方安裝",
|
||||
"settings.plugins.sources.source": "來源",
|
||||
"settings.plugins.sources.local": "本機匯入",
|
||||
"settings.plugins.sources.all": "全部來源",
|
||||
"settings.plugins.title": "外掛",
|
||||
"settings.plugins.configuration": "外掛設定",
|
||||
"settings.plugins.description": "管理已安裝外掛,瀏覽精選目錄。",
|
||||
'settings.plugins.loading': '正在載入外掛程式設定…',
|
||||
"settings.plugins.market.results": "{count} 個插件",
|
||||
"settings.plugins.market.results": "{count} 個外掛",
|
||||
"settings.plugins.manager.lastError": "上次記錄的錯誤",
|
||||
"settings.plugins.sources.offline": "來源暫不可用。如已快取此來源通過驗證的目錄,僅可繼續瀏覽;重新整理成功前無法安裝。",
|
||||
"settings.plugins.sources.note": "此目錄由所選第三方提供,不屬於 Netcatty 精選目錄。安裝前請核對來源網域和權限,更新需手動確認。",
|
||||
"settings.plugins.sources.sourceOnly": "此提供方僅提供原始碼項目,沒有可下載外掛套件;請查看作者的建置和匯入說明。",
|
||||
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市場安裝。",
|
||||
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市集安裝。",
|
||||
"settings.plugins.manager.details": "查看詳情",
|
||||
"settings.plugins.manager.noDescription": "作者尚未提供功能簡介。",
|
||||
"settings.plugins.status": "{count} 項提醒",
|
||||
@@ -1362,22 +1362,22 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"settings.plugins.market.readmeInfo": "README 來源說明",
|
||||
"settings.plugins.market.installed": "已安裝",
|
||||
"settings.plugins.market.sourceBadge": "原始碼範例",
|
||||
"settings.plugins.market.title": "插件市場",
|
||||
"settings.plugins.market.note": "精選開源插件。審核不代表安全認證,更新由你手動確認。",
|
||||
"settings.plugins.market.back": "所有插件",
|
||||
"settings.plugins.market.title": "外掛市集",
|
||||
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
|
||||
"settings.plugins.market.back": "所有外掛",
|
||||
"settings.plugins.market.install": "安裝此版本(保持停用)",
|
||||
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
|
||||
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並導入 .ncpkg;尚未發佈可下載發行包。",
|
||||
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠程圖片不加載。內容由插件作者提供。",
|
||||
"settings.plugins.manager.noVault": "系統密鑰存儲不可用。秘密和憑據操作被阻止;瀏覽市場和不使用秘密的插件仍可使用。",
|
||||
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
|
||||
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
|
||||
"settings.plugins.manager.noVault": "系統金鑰儲存不可用。秘密和憑據操作被阻止;瀏覽市集和不使用秘密的外掛仍可使用。",
|
||||
"settings.plugins.manager.sensitive": "敏感存取:此能力可能涉及私密資料,可在權限設定中調整其模式。",
|
||||
"settings.plugins.manager.dual": "默認使用瀏覽器運行時,但包中還包含擁有完整設備權限的 Node 入口;僅限開發者模式。",
|
||||
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器插件模式;請逐項檢查聲明權限。",
|
||||
"settings.plugins.manager.dual": "預設使用瀏覽器運行時,但包中還包含擁有完整裝置權限的 Node 入口;僅限開發者模式。",
|
||||
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器外掛模式;請逐項檢查聲明權限。",
|
||||
"settings.plugins.market.retry": "重試",
|
||||
"settings.plugins.market.empty": "目錄暫無插件,仍可導入本地瀏覽器插件。",
|
||||
"settings.plugins.market.empty": "目錄暫無外掛,仍可匯入本地瀏覽器外掛。",
|
||||
"settings.plugins.market.emptyReadme": "README 內容為空。",
|
||||
"settings.plugins.market.search": "搜索名稱、作者或描述",
|
||||
"settings.plugins.market.noResults": "沒有匹配插件,請嘗試其他關鍵詞。",
|
||||
"settings.plugins.market.noResults": "沒有匹配外掛,請嘗試其他關鍵詞。",
|
||||
"settings.plugins.market.manifest": "兼容性與權限",
|
||||
'settings.plugins.empty': '目前沒有已啟用外掛程式提供設定。',
|
||||
'settings.plugins.scopeContext': '請在對應的 {scope} 情境中開啟此設定。',
|
||||
|
||||
@@ -4,10 +4,10 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'terminal.layer.system': '系統',
|
||||
|
||||
'systemManager.noSession': '沒有使用中的終端工作階段。',
|
||||
'systemManager.notConnected': '請先連線到主機以管理程序與服務。',
|
||||
'systemManager.notConnected': '請先連線到主機以管理行程與服務。',
|
||||
'systemManager.empty': '暫無資料。',
|
||||
'systemManager.tabs.overview': '概覽',
|
||||
'systemManager.tabs.processes': '程序',
|
||||
'systemManager.tabs.processes': '行程',
|
||||
'systemManager.tabs.ports': '連接埠',
|
||||
'systemManager.tabs.services': '服務',
|
||||
'systemManager.tabs.tmux': 'tmux',
|
||||
@@ -17,7 +17,7 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.popup.loading': '正在開啟終端…',
|
||||
'systemManager.popup.startupFailed': '啟動指令未順利完成。請確認目標仍可使用後再試一次。',
|
||||
|
||||
'systemManager.errors.loadProcesses': '載入程序列表失敗',
|
||||
'systemManager.errors.loadProcesses': '載入行程列表失敗',
|
||||
'systemManager.errors.loadTmux': '載入 tmux 工作階段失敗',
|
||||
'systemManager.errors.loadTmuxWindows': '載入 tmux 視窗失敗',
|
||||
'systemManager.errors.loadTmuxPanes': '載入 tmux 窗格失敗',
|
||||
@@ -58,13 +58,13 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.overview.cpuCores': 'CPU 核心',
|
||||
'systemManager.overview.disks': '磁碟',
|
||||
'systemManager.overview.interfaces': '網路介面',
|
||||
'systemManager.overview.topProcesses': '記憶體佔用最高程序',
|
||||
'systemManager.overview.topProcesses': '記憶體佔用最高行程',
|
||||
'systemManager.overview.noData': '暫無資料',
|
||||
'systemManager.overview.noDisks': '暫無磁碟資料',
|
||||
'systemManager.overview.noInterfaces': '暫無網路卡資料',
|
||||
'systemManager.overview.noTopProcesses': '暫無程序資料',
|
||||
'systemManager.overview.noTopProcesses': '暫無行程資料',
|
||||
|
||||
'systemManager.processes.search': '搜尋程序…',
|
||||
'systemManager.processes.search': '搜尋行程…',
|
||||
'systemManager.processes.command': '指令',
|
||||
'systemManager.processes.user': '使用者',
|
||||
'systemManager.processes.term': '終止',
|
||||
@@ -75,18 +75,18 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.processes.renice': '調整優先順序',
|
||||
'systemManager.processes.renicePrompt': 'Nice 值 (-20 到 19)',
|
||||
'systemManager.processes.reniceInvalid': 'Nice 值必須在 -20 到 19 之間',
|
||||
'systemManager.processes.confirmKill': '向程序 {{pid}} 傳送 SIGKILL?',
|
||||
'systemManager.processes.confirmSignal': '向程序 {{pid}} 傳送 SIG{{signal}}?',
|
||||
'systemManager.processes.confirmKill': '向行程 {{pid}} 傳送 SIGKILL?',
|
||||
'systemManager.processes.confirmSignal': '向行程 {{pid}} 傳送 SIG{{signal}}?',
|
||||
'systemManager.processes.filter.all': '全部',
|
||||
'systemManager.processes.filter.running': '執行中',
|
||||
'systemManager.processes.ppid': '父程序 PID',
|
||||
'systemManager.processes.ppid': '父行程 PID',
|
||||
'systemManager.processes.rss': '實體記憶體',
|
||||
'systemManager.processes.vsz': '虛擬記憶體',
|
||||
'systemManager.processes.elapsed': '執行時長',
|
||||
'systemManager.processes.stat': '狀態',
|
||||
'systemManager.processes.meta': '{{count}} 個程序',
|
||||
'systemManager.processes.loading': '正在載入程序…',
|
||||
'systemManager.processes.loadingMore': '正在載入更多程序…',
|
||||
'systemManager.processes.meta': '{{count}} 個行程',
|
||||
'systemManager.processes.loading': '正在載入行程…',
|
||||
'systemManager.processes.loadingMore': '正在載入更多行程…',
|
||||
'systemManager.processes.state.running': '執行中',
|
||||
'systemManager.processes.state.sleeping': '睡眠',
|
||||
'systemManager.processes.state.stopped': '已暫停',
|
||||
@@ -236,9 +236,9 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.ports.search': '搜尋連接埠…',
|
||||
'systemManager.ports.meta': '{{count}} 個監聽',
|
||||
'systemManager.ports.filter.all': '全部',
|
||||
'systemManager.ports.unknownProcess': '未知程序',
|
||||
'systemManager.ports.terminate': '結束程序',
|
||||
'systemManager.ports.confirmTerminate': '向佔用該連接埠的程序 {{pid}} 傳送 SIGTERM?',
|
||||
'systemManager.ports.unknownProcess': '未知行程',
|
||||
'systemManager.ports.terminate': '結束行程',
|
||||
'systemManager.ports.confirmTerminate': '向佔用該連接埠的行程 {{pid}} 傳送 SIGTERM?',
|
||||
|
||||
'systemManager.services.unavailable': '此主機未偵測到 systemctl。',
|
||||
'systemManager.services.loading': '正在載入 systemd 服務…',
|
||||
@@ -261,10 +261,10 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.gpu.unavailable': '此主機未偵測到 NVIDIA GPU 或昇騰 NPU 工具。',
|
||||
'systemManager.gpu.loading': '正在載入加速卡狀態…',
|
||||
'systemManager.gpu.empty': '已偵測到加速卡工具,但未回傳裝置資訊。',
|
||||
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個程序',
|
||||
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個行程',
|
||||
'systemManager.gpu.devices': '裝置',
|
||||
'systemManager.gpu.processes': '計算程序',
|
||||
'systemManager.gpu.noProcesses': '目前沒有計算程序。',
|
||||
'systemManager.gpu.processes': '計算行程',
|
||||
'systemManager.gpu.noProcesses': '目前沒有計算行程。',
|
||||
'systemManager.gpu.vendor.nvidia': 'NVIDIA',
|
||||
'systemManager.gpu.vendor.ascend': '昇騰',
|
||||
'systemManager.gpu.util': '使用率',
|
||||
|
||||
@@ -510,8 +510,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.terminal.serverStats.refreshInterval.desc': '伺服器狀態重新整理的頻率。',
|
||||
'settings.terminal.serverStats.seconds': '秒',
|
||||
'settings.terminal.section.systemManager': '系統管理',
|
||||
'settings.terminal.systemManager.processRefreshInterval': '程序列表重新整理間隔',
|
||||
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中程序列表的重新整理頻率。',
|
||||
'settings.terminal.systemManager.processRefreshInterval': '行程列表重新整理間隔',
|
||||
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中行程列表的重新整理頻率。',
|
||||
'settings.terminal.systemManager.tmuxRefreshInterval': 'tmux 工作階段重新整理間隔',
|
||||
'settings.terminal.systemManager.tmuxRefreshInterval.desc': 'tmux 工作階段列表的重新整理頻率。',
|
||||
'settings.terminal.systemManager.dockerListRefreshInterval': '容器列表重新整理間隔',
|
||||
@@ -969,7 +969,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'snippets.variables.placeholderDefault': '預設:{value}',
|
||||
'snippets.variables.required': '請填寫此變數',
|
||||
'snippets.variables.run': '執行',
|
||||
'snippets.field.variablesHelp': '在指令碼中使用 {{名稱}} 或 {{名稱:預設值}} 定義變數。',
|
||||
'snippets.field.variablesHelp': '在指令碼中使用 {{name}} 或 {{name:default}} 作為佔位符。',
|
||||
'snippets.field.variablesDetected': '變數',
|
||||
'snippets.field.variableDefault': '預設 {value}',
|
||||
|
||||
|
||||
@@ -580,7 +580,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'terminal.serverStats.swapUsed': '已用交換',
|
||||
'terminal.serverStats.swapFree': '空閒交換',
|
||||
'terminal.serverStats.swapTotal': '總計',
|
||||
'terminal.serverStats.topProcesses': '記憶體佔用前十程序',
|
||||
'terminal.serverStats.topProcesses': '記憶體佔用前十行程',
|
||||
'terminal.serverStats.disk': '磁碟使用',
|
||||
'terminal.serverStats.diskDetails': '已掛載磁碟',
|
||||
'terminal.serverStats.network': '網路速度',
|
||||
|
||||
@@ -6,6 +6,7 @@ import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { PREFLIGHT_STAT_CONCURRENCY, PREFLIGHT_STAT_MAX_FILES, useSftpTransfers } from "./useSftpTransfers";
|
||||
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
|
||||
import type { SftpPane } from "./types";
|
||||
import { buildCacheKey } from "./sharedRemoteHostCache";
|
||||
|
||||
for (const direction of ["download", "upload"] as const) {
|
||||
test(`failed ${direction} connection replaces Waiting with the actual error (#3698)`, async () => {
|
||||
@@ -999,3 +1000,86 @@ test("no-conflict local copy awaits discovery so a late stat cannot overwrite th
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
for (const scenario of ["folder-cp", "folder-fallback", "file-cp", "different-key", "missing-key", "non-utf8"] as const) {
|
||||
test(`fresh remote copy selects a consistent strategy: ${scenario} (#4207)`, async () => {
|
||||
const isDirectory = scenario.startsWith("folder");
|
||||
const source = makePane("left");
|
||||
const target = makePane("left");
|
||||
target.connection = { ...target.connection!, id: "target-conn", currentPath: "/usr/tmp" };
|
||||
if (scenario === "non-utf8") target.filenameEncoding = "gb18030";
|
||||
const key = buildCacheKey("host-1", "debian", 22, "ssh", false, "user", "sftp");
|
||||
const keys = new Map([["remote-conn", key], ["target-conn", key]]);
|
||||
if (scenario === "different-key") keys.set("target-conn", buildCacheKey("host-2", "debian", 22, "ssh", false, "user", "sftp"));
|
||||
if (scenario === "missing-key") keys.delete("target-conn");
|
||||
const ownerId = `same-host-${scenario}-4207`;
|
||||
const streams: Array<{ resumable: boolean; sameHost?: boolean; parentTaskId?: string }> = [];
|
||||
const copies: unknown[][] = [];
|
||||
let listings = 0;
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
const restore = installGlobals({
|
||||
statSftp: async (id: string) => id === "sftp-source"
|
||||
? { type: "file", size: 3626, lastModified: 1758000001000 }
|
||||
: null,
|
||||
mkdirSftp: async () => undefined,
|
||||
sameHostCopyDirectory: async (...args: unknown[]) => {
|
||||
copies.push(args);
|
||||
assert.equal(sftpTransferCenterStore.getTask(args[4] as string)?.resumable, false);
|
||||
return { success: scenario !== "folder-fallback" };
|
||||
},
|
||||
startStreamTransfer: async (options: { transferId: string; resumable: boolean; sameHost?: boolean; parentTaskId?: string }) => {
|
||||
streams.push(options);
|
||||
assert.equal(sftpTransferCenterStore.getTask(options.transferId)?.resumable, options.resumable);
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed", transferId: options.transferId,
|
||||
transferred: 3626, totalBytes: 3626, lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
});
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId,
|
||||
getActivePane: (side) => side === "left" ? source : target,
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-source"], ["target-conn", "sftp-target"]]) },
|
||||
connectionCacheKeyMapRef: { current: keys },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => { listings++; return source.files; },
|
||||
});
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
const results = await ops!.startTransfer(
|
||||
[{ name: isDirectory ? "bt_mine" : "aops_dns_view_demo.sh", isDirectory }], "left", "right",
|
||||
);
|
||||
assert.equal(results[0]?.status, "completed");
|
||||
});
|
||||
const eligible = ["folder-cp", "folder-fallback", "file-cp"].includes(scenario);
|
||||
const rows = sftpTransferCenterStore.getOwnerTasks(ownerId);
|
||||
assert.ok(rows.length > 0);
|
||||
assert.ok(rows.every(row => row.resumable === !eligible));
|
||||
assert.equal(copies.length, isDirectory ? 1 : 0);
|
||||
if (isDirectory) assert.deepEqual(copies[0]?.slice(0, 4), ["sftp-source", "/opt/bt_mine", "/usr/tmp/bt_mine", "auto"]);
|
||||
assert.equal(listings, scenario === "folder-fallback" ? 1 : 0);
|
||||
assert.equal(streams.length, scenario === "folder-cp" ? 0 : 1);
|
||||
if (streams.length) {
|
||||
assert.equal(streams[0].resumable, !eligible);
|
||||
assert.equal(streams[0].sameHost, !["different-key", "missing-key"].includes(scenario) || undefined);
|
||||
if (isDirectory) assert.ok(streams[0].parentTaskId);
|
||||
}
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
for (const row of sftpTransferCenterStore.getOwnerTasks(ownerId)) sftpTransferCenterStore.dismiss(row.id);
|
||||
restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1348,6 +1348,17 @@ export const useSftpTransfers = ({
|
||||
const sourceConnectionId = options?.sourceConnectionId ?? sourcePane.connection.id;
|
||||
const batchId = crypto.randomUUID();
|
||||
const usesLegacyScp = sourcePane.connection.fileProtocol === "scp" || targetPane.connection.fileProtocol === "scp";
|
||||
const sourceCacheKey = connectionCacheKeyMapRef.current.get(sourcePane.connection.id);
|
||||
const targetCacheKey = connectionCacheKeyMapRef.current.get(targetPane.connection.id);
|
||||
const encodingSafeForExec = [sourcePane.filenameEncoding, targetPane.filenameEncoding]
|
||||
.every((encoding) => !encoding || encoding === "utf-8" || encoding === "auto");
|
||||
// Select the existing non-resumable cp route only for newly created copies.
|
||||
// Resume/recovery keeps its saved strategy and checkpoints. If cp fails,
|
||||
// recursive/download+upload fallback also remains non-resumable.
|
||||
const useSameHostCopy = !usesLegacyScp
|
||||
&& !sourcePane.connection.isLocal && !targetPane.connection.isLocal
|
||||
&& !!sourceCacheKey && sourceCacheKey === targetCacheKey
|
||||
&& encodingSafeForExec;
|
||||
|
||||
const newTasks: TransferTask[] = [];
|
||||
const skippedResults: TransferResult[] = [];
|
||||
@@ -1582,8 +1593,10 @@ export const useSftpTransfers = ({
|
||||
sourceLastModified,
|
||||
preflightStatSkipped: preflightSkippedNames.has(file.name),
|
||||
origin: "manual",
|
||||
resumable: !usesLegacyScp,
|
||||
pauseUnavailableReason: usesLegacyScp ? "This server uses legacy SCP; cancel and retry from the beginning instead" : undefined,
|
||||
resumable: !usesLegacyScp && !useSameHostCopy,
|
||||
pauseUnavailableReason: usesLegacyScp
|
||||
? "This server uses legacy SCP; cancel and retry from the beginning instead"
|
||||
: useSameHostCopy ? "Same-host copies cannot be paused; cancel and retry from the beginning instead" : undefined,
|
||||
phase: file.isDirectory ? "scanning" : "transferring",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useEffect, type RefObject } from 'react';
|
||||
import { logger } from '../../lib/logger';
|
||||
|
||||
const closeCaptures = new Map<string, Set<() => void>>();
|
||||
|
||||
/** Notify owning terminals before explicit session removal, never on runtime cleanup. */
|
||||
export function captureClosingTerminalSessions(sessionIds: readonly string[]): void {
|
||||
for (const sessionId of new Set(sessionIds)) {
|
||||
for (const capture of closeCaptures.get(sessionId) ?? []) capture();
|
||||
}
|
||||
}
|
||||
|
||||
export function useTerminalSessionCloseCapture({
|
||||
sessionId,
|
||||
enabled,
|
||||
hasConnectedRef,
|
||||
terminalDataCapturedRef,
|
||||
finalizeTerminalLogData,
|
||||
onTerminalDataCapture,
|
||||
}: {
|
||||
sessionId: string;
|
||||
enabled: boolean;
|
||||
hasConnectedRef: RefObject<boolean>;
|
||||
terminalDataCapturedRef: RefObject<boolean>;
|
||||
finalizeTerminalLogData: () => string;
|
||||
onTerminalDataCapture: (
|
||||
sessionId: string,
|
||||
data: string,
|
||||
options: { finalized: true },
|
||||
) => void | Promise<void>;
|
||||
}): void {
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const capture = () => {
|
||||
// Connected terminals retain their existing drain/serialize close path.
|
||||
if (hasConnectedRef.current || terminalDataCapturedRef.current) return;
|
||||
try {
|
||||
// A never-connected runtime is disposed synchronously on unmount.
|
||||
// Finish its log now, even if empty, so persistence can set endTime.
|
||||
void Promise.resolve(onTerminalDataCapture(
|
||||
sessionId, finalizeTerminalLogData(), { finalized: true },
|
||||
)).catch((err: unknown) => {
|
||||
logger.warn('Failed to capture terminal log on session close', err);
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn('Failed to capture terminal log on session close', err);
|
||||
}
|
||||
};
|
||||
const captures = closeCaptures.get(sessionId) ?? new Set<() => void>();
|
||||
closeCaptures.set(sessionId, captures);
|
||||
captures.add(capture);
|
||||
return () => {
|
||||
captures.delete(capture);
|
||||
if (!captures.size) closeCaptures.delete(sessionId);
|
||||
};
|
||||
}, [sessionId, enabled, hasConnectedRef, terminalDataCapturedRef, finalizeTerminalLogData, onTerminalDataCapture]);
|
||||
}
|
||||
@@ -75,6 +75,7 @@ import {
|
||||
getSessionConnectionLabel,
|
||||
} from '../../domain/sessionTabTitle';
|
||||
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
|
||||
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
|
||||
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
|
||||
import { useVaultSnapshotField } from './vaultSnapshotStore';
|
||||
|
||||
@@ -603,6 +604,7 @@ export const useSessionState = ({
|
||||
const closedIds = sessionsRef.current
|
||||
.filter(session => session.workspaceId === workspaceId)
|
||||
.map(session => session.id);
|
||||
captureClosingTerminalSessions(closedIds);
|
||||
cleanupClosedTerminalSessions(closedIds);
|
||||
for (const sessionId of closedIds) {
|
||||
sessionPresentationStore.clearSession(sessionId);
|
||||
@@ -626,6 +628,7 @@ export const useSessionState = ({
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const closeSessions = useCallback((sessionIds: string[]) => {
|
||||
captureClosingTerminalSessions(sessionIds);
|
||||
cleanupClosedTerminalSessions(sessionIds);
|
||||
for (const sessionId of sessionIds) {
|
||||
sessionPresentationStore.clearSession(sessionId);
|
||||
|
||||
@@ -55,7 +55,7 @@ interface AIChatPanelContentProps {
|
||||
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
|
||||
inputValue: string;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: () => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
onRenameSession?: (sessionId: string, title: string) => void;
|
||||
@@ -211,6 +211,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
parked = false,
|
||||
sending = false,
|
||||
}) => {
|
||||
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
|
||||
const mentionHosts = React.useMemo(
|
||||
() => terminalSessions.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
@@ -345,6 +346,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<ChatMessageList
|
||||
messages={messages}
|
||||
isStreaming={isStreaming}
|
||||
onContinue={handleContinue}
|
||||
activeSessionId={activeSessionId}
|
||||
activeCompaction={activeCompaction}
|
||||
contextCompaction={activeSession?.contextCompaction}
|
||||
|
||||
@@ -1610,14 +1610,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
|
||||
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
const handleSend = useCallback(async (textOverride?: string) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
const currentSessionView = activeSessionRef.current;
|
||||
if (!validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = draft?.text.trim() ?? '';
|
||||
if (textOverride === undefined && !validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = (textOverride ?? draft?.text ?? '').trim();
|
||||
const sendScopeKey = scopeKey;
|
||||
const attachments = (draft?.attachments ?? []).map((file) => ({
|
||||
const attachments = (textOverride === undefined ? draft?.attachments ?? [] : []).map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
filename: file.filename,
|
||||
@@ -1645,12 +1645,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
|
||||
if (sendAgentId !== 'catty' && !agentConfig) return;
|
||||
|
||||
const selectedSkillSlugs = draft?.selectedUserSkillSlugs ?? [];
|
||||
const selectedSkillSlugs = textOverride === undefined ? draft?.selectedUserSkillSlugs ?? [] : [];
|
||||
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
|
||||
const modelAttachments = attachments.filter((attachment) => !isInlineTextAttachment(attachment));
|
||||
const isDraftMode = currentPanelView.mode === 'draft';
|
||||
|
||||
flushDraftText();
|
||||
if (textOverride === undefined) flushDraftText();
|
||||
const submittedText = draft?.text ?? '';
|
||||
const keepPendingAfterSend = () => {
|
||||
const pending = pendingComposerTextRef.current;
|
||||
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(createdSession.id);
|
||||
setActiveSessionId(createdSession.id);
|
||||
sessionSendGateKey = sessionId;
|
||||
@@ -1770,7 +1770,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1785,7 +1785,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1798,7 +1798,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
...(selectedSkillSlugs.length > 0 ? { selectedUserSkillSlugs: selectedSkillSlugs } : {}),
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
setStreamingForScope(sessionId, true);
|
||||
|
||||
@@ -409,6 +409,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
const nestedDelayMs = (request.aiSubTab || request.syncSubTab) ? 80 : 40;
|
||||
const focusHandle = window.setTimeout(() => {
|
||||
void focusSettingsAnchor(request.anchorId, {
|
||||
fallbackAnchorId: request.fallbackAnchorId,
|
||||
attempts: 48,
|
||||
delayMs: 50,
|
||||
}).finally(() => {
|
||||
|
||||
@@ -82,6 +82,7 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean";
|
||||
import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString";
|
||||
import { performSessionLogAction, type SessionLogAction } from "../application/state/sessionLogActions";
|
||||
import { useSessionLogBackend } from "../application/state/useSessionLogBackend";
|
||||
import { useTerminalSessionCloseCapture } from "../application/state/terminalSessionCloseCapture";
|
||||
import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore";
|
||||
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
|
||||
import {
|
||||
@@ -1676,6 +1677,28 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
return captureHandler(capturedSessionId, capturedData);
|
||||
}, [finalizeTerminalLogData]);
|
||||
|
||||
useTerminalSessionCloseCapture({
|
||||
sessionId,
|
||||
enabled: !attachExistingSession && restoreState !== "restored-disconnected",
|
||||
hasConnectedRef,
|
||||
terminalDataCapturedRef,
|
||||
finalizeTerminalLogData,
|
||||
onTerminalDataCapture: handleTerminalDataCaptureOnce,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Attached popups do not own the ConnectionLog; the home terminal captures it.
|
||||
if (attachExistingSession) return;
|
||||
return netcattyBridge.get()?.onFinalizeSessionLogs?.(async () => {
|
||||
if (terminalDataCapturedRef.current || (restoreState === "restored-disconnected" && statusRef.current === "disconnected")) return;
|
||||
const term = termRef.current;
|
||||
if (term && !await flushPendingTerminalWritesBeforeHibernate(term)) {
|
||||
throw new Error("Terminal output did not drain before quit capture");
|
||||
}
|
||||
await handleTerminalDataCaptureOnce(sessionId, finalizeTerminalLogData(), { finalized: true });
|
||||
});
|
||||
}, [attachExistingSession, restoreState, sessionId, finalizeTerminalLogData, handleTerminalDataCaptureOnce]);
|
||||
|
||||
const attachHomeWebContentsIdRef = useRef<number | null | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
|
||||
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
|
||||
@@ -644,3 +645,64 @@ test('fork is offered only for safe completed replies and hidden while streaming
|
||||
assert.equal((render(false).match(/Fork from here/g) ?? []).length, 1);
|
||||
assert.equal((render(true).match(/Fork from here/g) ?? []).length, 0);
|
||||
});
|
||||
|
||||
test('ChatMessageList renders a non-error iteration limit notice with a Continue action', () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ id: 'poll', role: 'tool', content: '', timestamp: 1,
|
||||
toolResults: [{ toolCallId: 'poll-1', content: '{"jobId":"job-1","status":"running"}' }] },
|
||||
{ id: 'limit', role: 'assistant', content: '', timestamp: 2, iterationLimit: 20 },
|
||||
];
|
||||
const render = (isStreaming: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList messages={messages} isStreaming={isStreaming} onContinue={() => {}} />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
const markup = render(false);
|
||||
assert.match(markup, /Tool-loop limit \(20 iterations\) reached/);
|
||||
assert.match(markup, /<button[^>]*>Continue<\/button>/);
|
||||
assert.doesNotMatch(markup, /bg-destructive/);
|
||||
assert.match(render(true), /<button[^>]*disabled=""[^>]*>Continue<\/button>/);
|
||||
|
||||
const source = readFileSync(new URL('./ChatMessageList.tsx', import.meta.url), 'utf8');
|
||||
const panel = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
const sidePanel = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /onClick=\{onContinue\}/);
|
||||
assert.match(panel, /onContinue=\{handleContinue\}/);
|
||||
assert.match(panel, /handleContinue = React.useCallback\(\(\) => handleSend\(t\('ai.chat.continue'\)\)/);
|
||||
assert.match(sidePanel, /const handleSend = useCallback\(async \(textOverride\?: string\)/);
|
||||
assert.match(sidePanel, /const trimmed = \(textOverride \?\? draft\?\.text \?\? ''\)\.trim\(\)/);
|
||||
});
|
||||
|
||||
test('iteration limit Continue button invokes the provided send callback', async t => {
|
||||
const previousWindow = globalThis.window;
|
||||
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
|
||||
globalThis.window = { setTimeout, clearTimeout } as unknown as Window & typeof globalThis;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
t.after(() => {
|
||||
globalThis.window = previousWindow;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
let continued = 0;
|
||||
let renderer: ReactTestRenderer;
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList
|
||||
messages={[{ id: 'limit', role: 'assistant', content: '', timestamp: 1, iterationLimit: 20 }]}
|
||||
onContinue={() => { continued += 1; }}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
const button = renderer!.root.findAllByType('button').find(node => node.children.includes('Continue'));
|
||||
assert.ok(button);
|
||||
assert.equal(button.props.disabled, false);
|
||||
await act(async () => { button.props.onClick(); });
|
||||
assert.equal(continued, 1);
|
||||
await act(async () => { renderer!.unmount(); });
|
||||
});
|
||||
@@ -90,6 +90,7 @@ import ChatJumpNav from './ChatJumpNav';
|
||||
interface ChatMessageListProps {
|
||||
messages: ChatMessage[];
|
||||
isStreaming?: boolean;
|
||||
onContinue?: () => void;
|
||||
/** Active chat session ID — used to filter standalone MCP approval blocks */
|
||||
activeSessionId?: string | null;
|
||||
activeCompaction?: ActiveCompactionUi | null;
|
||||
@@ -185,6 +186,7 @@ export function pruneResolvedApprovals(
|
||||
const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
messages,
|
||||
isStreaming,
|
||||
onContinue,
|
||||
activeSessionId,
|
||||
activeCompaction = null,
|
||||
contextCompaction,
|
||||
@@ -813,6 +815,18 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message.iterationLimit != null && (
|
||||
<div role="status" className="rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<p>{t('ai.chat.iterationLimitReached', { limit: message.iterationLimit })}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onContinue}
|
||||
disabled={!!isStreaming || !onContinue}
|
||||
className="mt-2 rounded-md border border-border px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>{t('ai.chat.continue')}</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error info */}
|
||||
{message.errorInfo && (
|
||||
<div className="flex items-start gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-sm">
|
||||
@@ -1079,6 +1093,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
|
||||
function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps): boolean {
|
||||
if (prev.isStreaming !== next.isStreaming) return false;
|
||||
if (prev.onContinue !== next.onContinue) return false;
|
||||
if (prev.activeSessionId !== next.activeSessionId) return false;
|
||||
if (prev.notes !== next.notes) return false;
|
||||
if (prev.hosts !== next.hosts) return false;
|
||||
@@ -1107,6 +1122,7 @@ function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps
|
||||
p.statusText !== n.statusText ||
|
||||
p.executionStatus !== n.executionStatus ||
|
||||
p.errorInfo !== n.errorInfo ||
|
||||
p.iterationLimit !== n.iterationLimit ||
|
||||
p.toolCalls !== n.toolCalls ||
|
||||
p.toolResults !== n.toolResults ||
|
||||
p.agentActivities !== n.agentActivities ||
|
||||
|
||||
@@ -459,6 +459,17 @@ test("note markdown toolbar remains usable in narrow panes", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("MDX link dialog overlay stays inside the retained notes editor container", () => {
|
||||
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
|
||||
|
||||
// Default MDXEditor popup target is document.body. Keep the overlay in the
|
||||
// editor container so section `hidden` and vault visibility:hidden hide it (#4257).
|
||||
assert.match(source, /const \[overlayContainer, setOverlayContainer\] = useState<HTMLElement \| null>\(null\);/);
|
||||
assert.match(source, /setOverlayContainer\(\(current\) => \(current === node \? current : node\)\);/);
|
||||
assert.match(source, /ref=\{setEditorContainer\}/);
|
||||
assert.match(source, /overlayContainer=\{overlayContainer \?\? undefined\}/);
|
||||
});
|
||||
|
||||
test("preview mode opens links directly without showing the edit hover action", () => {
|
||||
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
|
||||
|
||||
|
||||
@@ -946,6 +946,14 @@ export const InlineMarkdownEditor = React.memo(
|
||||
});
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
// MDXEditor portals .mdxeditor-popup-container to document.body unless
|
||||
// overlayContainer is set. Notes stays mounted and is only CSS-hidden, so a
|
||||
// body portal would leave the link preview toolbar over other pages (#4257).
|
||||
const [overlayContainer, setOverlayContainer] = useState<HTMLElement | null>(null);
|
||||
const setEditorContainer = useCallback((node: HTMLDivElement | null) => {
|
||||
containerRef.current = node;
|
||||
setOverlayContainer((current) => (current === node ? current : node));
|
||||
}, []);
|
||||
|
||||
const getSelectedText = useCallback((): string => {
|
||||
const container = containerRef.current;
|
||||
@@ -2063,7 +2071,7 @@ export const InlineMarkdownEditor = React.memo(
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
ref={setEditorContainer}
|
||||
className="relative flex h-full flex-col"
|
||||
style={{
|
||||
["--note-font-family" as string]: noteFontFamily || undefined,
|
||||
@@ -2223,6 +2231,7 @@ export const InlineMarkdownEditor = React.memo(
|
||||
<MDXEditor
|
||||
key={editorMode}
|
||||
ref={editorRef}
|
||||
overlayContainer={overlayContainer ?? undefined}
|
||||
markdown={
|
||||
mdxRetry !== null && value === mdxRetry.staleValue
|
||||
? normalizeNotePublicAssetPaths(mdxRetry.markdown)
|
||||
|
||||
@@ -93,6 +93,7 @@ export function SettingsSearchControl({
|
||||
aiSubTab: hit.entry.aiSubTab,
|
||||
syncSubTab: hit.entry.syncSubTab,
|
||||
anchorId: hit.entry.id,
|
||||
fallbackAnchorId: hit.entry.fallbackAnchorId,
|
||||
});
|
||||
collapseSearch(false);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,102 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { settingsAnchorDomId } from "../../domain/settingsSearchCatalog.ts";
|
||||
import { focusSettingsAnchor } from "./settingsFocus.ts";
|
||||
|
||||
function setupFocusDom(t: TestContext) {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const anchors = new Map<string, HTMLElement>();
|
||||
const focused: string[] = [];
|
||||
const scrolled: string[] = [];
|
||||
const globals = {
|
||||
document: {
|
||||
getElementById: (id: string) => anchors.get(id) ?? null,
|
||||
querySelectorAll: () => [],
|
||||
documentElement: {},
|
||||
body: {},
|
||||
},
|
||||
window: { setTimeout, clearTimeout },
|
||||
CSS: { escape: (value: string) => value },
|
||||
requestAnimationFrame: (callback: FrameRequestCallback) => { callback(0); return 0; },
|
||||
};
|
||||
for (const [key, value] of Object.entries(globals)) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
t.after(() => {
|
||||
if (previous) Object.defineProperty(globalThis, key, previous);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
});
|
||||
}
|
||||
const mount = (id: string, visible = true) => {
|
||||
const classes = new Set<string>();
|
||||
const el = {
|
||||
closest: () => null,
|
||||
checkVisibility: () => visible,
|
||||
classList: { add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name) },
|
||||
matches: () => true,
|
||||
hasAttribute: () => true,
|
||||
focus: () => focused.push(id),
|
||||
scrollIntoView: () => scrolled.push(id),
|
||||
} as unknown as HTMLElement;
|
||||
anchors.set(settingsAnchorDomId(id), el);
|
||||
return classes;
|
||||
};
|
||||
return { mount, focused, scrolled };
|
||||
}
|
||||
|
||||
test("missing search target focuses and highlights its visible parent after a short mount window", async (t) => {
|
||||
const { mount, focused, scrolled } = setupFocusDom(t);
|
||||
const parentClasses = mount("parent");
|
||||
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent", attempts: 48, delayMs: 50 });
|
||||
|
||||
for (let retry = 0; retry < 3; retry += 1) t.mock.timers.tick(50);
|
||||
t.mock.timers.tick(49);
|
||||
assert.deepEqual(focused, []);
|
||||
t.mock.timers.tick(1);
|
||||
assert.equal(await result, true);
|
||||
assert.deepEqual(focused, ["parent"]);
|
||||
assert.deepEqual(scrolled, ["parent"]);
|
||||
assert.ok(parentClasses.has("settings-search-highlight"));
|
||||
});
|
||||
|
||||
test("search focus prefers a visible primary over its fallback", async (t) => {
|
||||
const { mount, focused } = setupFocusDom(t);
|
||||
const childClasses = mount("child");
|
||||
const parentClasses = mount("parent");
|
||||
|
||||
assert.equal(await focusSettingsAnchor("child", { fallbackAnchorId: "parent" }), true);
|
||||
assert.deepEqual(focused, ["child"]);
|
||||
assert.ok(childClasses.has("settings-search-highlight"));
|
||||
assert.equal(parentClasses.has("settings-search-highlight"), false);
|
||||
});
|
||||
|
||||
test("search focus waits for a lazy primary before using a visible fallback", async (t) => {
|
||||
const { mount, focused } = setupFocusDom(t);
|
||||
mount("parent");
|
||||
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
|
||||
t.mock.timers.tick(50);
|
||||
t.mock.timers.tick(50);
|
||||
mount("child");
|
||||
t.mock.timers.tick(50);
|
||||
|
||||
assert.equal(await result, true);
|
||||
assert.deepEqual(focused, ["child"]);
|
||||
});
|
||||
|
||||
test("search focus skips a hidden primary and waits for a visible fallback", async (t) => {
|
||||
const { mount, focused } = setupFocusDom(t);
|
||||
mount("child", false);
|
||||
mount("parent", false);
|
||||
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
|
||||
for (let retry = 0; retry < 4; retry += 1) t.mock.timers.tick(50);
|
||||
assert.deepEqual(focused, []);
|
||||
mount("parent");
|
||||
t.mock.timers.tick(50);
|
||||
|
||||
assert.equal(await result, true);
|
||||
assert.deepEqual(focused, ["parent"]);
|
||||
});
|
||||
|
||||
test("system setting hints sit below their cards with a shared top gap", () => {
|
||||
const uiSource = readFileSync(new URL("./settings-ui.tsx", import.meta.url), "utf8");
|
||||
|
||||
@@ -4,12 +4,15 @@ const HIGHLIGHT_CLASS = "settings-search-highlight";
|
||||
const HIGHLIGHT_MS = 1600;
|
||||
/** Keep focused anchors slightly below the top of the settings content pane. */
|
||||
const SCROLL_TOP_PADDING_PX = 24;
|
||||
/** Allow 200ms at the default retry delay for lazy tab / sub-tab mounts. */
|
||||
const FALLBACK_AFTER_ATTEMPTS = 5;
|
||||
|
||||
export type SettingsFocusTarget = {
|
||||
tab: string;
|
||||
aiSubTab?: string;
|
||||
syncSubTab?: string;
|
||||
anchorId: string;
|
||||
fallbackAnchorId?: string;
|
||||
};
|
||||
|
||||
let focusGeneration = 0;
|
||||
@@ -30,6 +33,18 @@ function isAnchorVisible(el: HTMLElement): boolean {
|
||||
return el.getClientRects().length > 0;
|
||||
}
|
||||
|
||||
function findVisibleAnchor(anchorId: string): HTMLElement | undefined {
|
||||
const candidates = [
|
||||
document.getElementById(settingsAnchorDomId(anchorId)),
|
||||
...Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
|
||||
),
|
||||
),
|
||||
].filter((node): node is HTMLElement => Boolean(node));
|
||||
return candidates.find((node) => isAnchorVisible(node));
|
||||
}
|
||||
|
||||
function focusAnchorElement(el: HTMLElement): void {
|
||||
const focusable = el.matches("button, a, input, select, textarea, [tabindex]")
|
||||
? el
|
||||
@@ -103,15 +118,16 @@ export function scrollSettingsAnchorIntoView(
|
||||
/**
|
||||
* Scroll the settings content pane to a catalog anchor and briefly highlight it.
|
||||
* Retries to cover lazy tab mounts / nested sub-tab switches.
|
||||
* After a short mount window, use a visible parent fallback for gated rows.
|
||||
*/
|
||||
export function focusSettingsAnchor(
|
||||
anchorId: string,
|
||||
options?: { attempts?: number; delayMs?: number },
|
||||
options?: { attempts?: number; delayMs?: number; fallbackAnchorId?: string },
|
||||
): Promise<boolean> {
|
||||
const attempts = options?.attempts ?? 40;
|
||||
const delayMs = options?.delayMs ?? 50;
|
||||
const generation = ++focusGeneration;
|
||||
let remaining = attempts;
|
||||
let attempt = 0;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const finish = (ok: boolean) => {
|
||||
@@ -125,20 +141,13 @@ export function focusSettingsAnchor(
|
||||
return;
|
||||
}
|
||||
|
||||
const domId = settingsAnchorDomId(anchorId);
|
||||
const candidates = [
|
||||
document.getElementById(domId),
|
||||
...Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
|
||||
),
|
||||
),
|
||||
].filter((node): node is HTMLElement => Boolean(node));
|
||||
|
||||
const el = candidates.find((node) => isAnchorVisible(node));
|
||||
attempt += 1;
|
||||
let el = findVisibleAnchor(anchorId);
|
||||
if (!el && options?.fallbackAnchorId && attempt >= Math.min(FALLBACK_AFTER_ATTEMPTS, attempts)) {
|
||||
el = findVisibleAnchor(options.fallbackAnchorId);
|
||||
}
|
||||
if (!el) {
|
||||
remaining -= 1;
|
||||
if (remaining > 0) {
|
||||
if (attempt < attempts) {
|
||||
window.setTimeout(tryFocus, delayMs);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -258,6 +258,7 @@ export const AppLockSettingsSection: React.FC<AppLockSettingsSectionProps> = ({
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-app-lock-timeout"
|
||||
label={t('settings.appLock.timeout')}
|
||||
description={t('settings.appLock.timeoutDesc')}
|
||||
>
|
||||
|
||||
@@ -66,9 +66,15 @@ test('local logging controls default off, disclose verbose risk, and call host-o
|
||||
assert.match(document.querySelector('[role=alert]')!.textContent!, /synthetic preferences write failed/);
|
||||
await act(async () => button('Close').click());
|
||||
assert.equal(document.querySelector('[role=dialog]'), null);
|
||||
assert.equal(document.activeElement, configure);
|
||||
// Radix restores focus in a setTimeout(0) after the dialog unmounts.
|
||||
// act() can finish before that timer, so drain it before checking focus.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
// Comparing DOM objects directly makes Node inspect the entire JSDOM graph
|
||||
// on failure, which can stall the test process while formatting the diff.
|
||||
assert.ok(document.activeElement === configure, `expected focus on Configure, got ${document.activeElement?.tagName}`);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
|
||||
@@ -9,6 +9,13 @@ test("SFTP settings imports the shared Toggle used by its option rows", () => {
|
||||
assert.match(source, /Toggle,\s*\n\s*Select,/);
|
||||
});
|
||||
|
||||
test("folder compression row exposes its settings search anchor", () => {
|
||||
assert.match(
|
||||
source,
|
||||
/<SettingRow\s+anchorId="sftp-compressed-upload"\s+label=\{t\('settings\.sftp\.compressedUpload\.enable'\)\}/,
|
||||
);
|
||||
});
|
||||
|
||||
function functionBody(functionName: string): string {
|
||||
const start = source.indexOf(`const ${functionName} = useCallback`);
|
||||
assert.notEqual(start, -1, `${functionName} should exist`);
|
||||
|
||||
@@ -180,6 +180,7 @@ export default function SettingsFileAssociationsTab() {
|
||||
<SectionHeader title={t('settings.sftp.compressedUpload')} />
|
||||
<SettingCard>
|
||||
<SettingRow
|
||||
anchorId="sftp-compressed-upload"
|
||||
label={t('settings.sftp.compressedUpload.enable')}
|
||||
description={t('settings.sftp.compressedUpload.enableDesc')}
|
||||
>
|
||||
@@ -231,12 +232,14 @@ export default function SettingsFileAssociationsTab() {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="sftp-skip-unchanged"
|
||||
label={t('settings.sftp.skipUnchanged.enable')}
|
||||
description={t('settings.sftp.skipUnchanged.enableDesc')}
|
||||
>
|
||||
<Toggle checked={sftpSkipUnchanged} onChange={setSftpSkipUnchanged} />
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="sftp-transport-idle-ttl"
|
||||
label={t('settings.ssh.transportIdleTtl')}
|
||||
description={t('settings.ssh.transportIdleTtl.desc')}
|
||||
>
|
||||
|
||||
@@ -693,6 +693,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
{httpNetworkProxy.mode === "custom" && (
|
||||
<>
|
||||
<SettingRow
|
||||
anchorId="system-network-proxy-url"
|
||||
label={t("settings.system.networkProxy.url")}
|
||||
description={t("settings.system.networkProxy.url.desc")}
|
||||
>
|
||||
@@ -710,6 +711,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="system-network-proxy-bypass"
|
||||
label={t("settings.system.networkProxy.bypass")}
|
||||
description={t("settings.system.networkProxy.bypass.desc")}
|
||||
>
|
||||
@@ -1088,7 +1090,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
</SettingRow>
|
||||
|
||||
{/* Directory Selection */}
|
||||
<div className="space-y-2">
|
||||
<SettingsAnchor anchorId="system-session-logs-directory" className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{t("settings.sessionLogs.directory")}</span>
|
||||
</div>
|
||||
@@ -1125,10 +1127,11 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.sessionLogs.directoryHint")}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsAnchor>
|
||||
|
||||
{/* Format Selection */}
|
||||
<SettingRow
|
||||
anchorId="system-session-logs-format"
|
||||
label={t("settings.sessionLogs.format")}
|
||||
description={t("settings.sessionLogs.formatDesc")}
|
||||
>
|
||||
@@ -1141,6 +1144,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-session-logs-timestamps"
|
||||
label={t("settings.sessionLogs.timestamps")}
|
||||
description={t("settings.sessionLogs.timestampsDesc")}
|
||||
>
|
||||
|
||||
@@ -814,6 +814,7 @@ function SettingsTerminalTab(props: {
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-side-panel-auto-open-pane"
|
||||
label={t("settings.terminal.sidePanel.autoOpenPane")}
|
||||
description={t("settings.terminal.sidePanel.autoOpenPane.desc")}
|
||||
>
|
||||
@@ -841,6 +842,7 @@ function SettingsTerminalTab(props: {
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-local-shell-side-panel-auto-open-pane"
|
||||
label={t("settings.terminal.localShellSidePanel.autoOpenPane")}
|
||||
description={t("settings.terminal.localShellSidePanel.autoOpenPane.desc")}
|
||||
>
|
||||
@@ -945,6 +947,7 @@ function SettingsTerminalTab(props: {
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-local-shell-start-dir"
|
||||
label={t("settings.terminal.localShell.startDir")}
|
||||
description={t("settings.terminal.localShell.startDir.desc")}
|
||||
>
|
||||
@@ -1048,6 +1051,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-keepalive-count-max"
|
||||
label={t("settings.terminal.connection.keepaliveCountMax")}
|
||||
description={t("settings.terminal.connection.keepaliveCountMax.desc")}
|
||||
>
|
||||
@@ -1082,6 +1086,7 @@ function SettingsTerminalTab(props: {
|
||||
<SectionHeader title={t("settings.terminal.section.serverStats")} />
|
||||
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
|
||||
<SettingRow
|
||||
anchorId="terminal-host-info-bar-show"
|
||||
label={t("settings.terminal.hostInfoBar.show")}
|
||||
description={t("settings.terminal.hostInfoBar.show.desc")}
|
||||
>
|
||||
@@ -1092,6 +1097,7 @@ function SettingsTerminalTab(props: {
|
||||
</SettingRow>
|
||||
{terminalSettings.showHostInfoBar && (
|
||||
<SettingRow
|
||||
anchorId="terminal-host-info-bar-title-mode"
|
||||
label={t("settings.terminal.hostInfoBar.titleMode")}
|
||||
description={t("settings.terminal.hostInfoBar.titleMode.desc")}
|
||||
>
|
||||
@@ -1119,6 +1125,7 @@ function SettingsTerminalTab(props: {
|
||||
|
||||
{terminalSettings.showServerStats && (
|
||||
<SettingRow
|
||||
anchorId="terminal-server-stats-refresh-interval"
|
||||
label={t("settings.terminal.serverStats.refreshInterval")}
|
||||
description={t("settings.terminal.serverStats.refreshInterval.desc")}
|
||||
>
|
||||
@@ -1145,6 +1152,7 @@ function SettingsTerminalTab(props: {
|
||||
<SectionHeader title={t("settings.terminal.section.systemManager")} />
|
||||
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
|
||||
<SettingRow
|
||||
anchorId="terminal-system-manager-process-refresh-interval"
|
||||
label={t("settings.terminal.systemManager.processRefreshInterval")}
|
||||
description={t("settings.terminal.systemManager.processRefreshInterval.desc")}
|
||||
>
|
||||
@@ -1166,6 +1174,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-system-manager-tmux-refresh-interval"
|
||||
label={t("settings.terminal.systemManager.tmuxRefreshInterval")}
|
||||
description={t("settings.terminal.systemManager.tmuxRefreshInterval.desc")}
|
||||
>
|
||||
@@ -1187,6 +1196,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-system-manager-docker-list-refresh-interval"
|
||||
label={t("settings.terminal.systemManager.dockerListRefreshInterval")}
|
||||
description={t("settings.terminal.systemManager.dockerListRefreshInterval.desc")}
|
||||
>
|
||||
@@ -1208,6 +1218,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-system-manager-docker-stats-refresh-interval"
|
||||
label={t("settings.terminal.systemManager.dockerStatsRefreshInterval")}
|
||||
description={t("settings.terminal.systemManager.dockerStatsRefreshInterval.desc")}
|
||||
>
|
||||
@@ -1249,6 +1260,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-hidden-tabs"
|
||||
label={t("settings.terminal.rendering.hibernateHiddenTabs")}
|
||||
description={t("settings.terminal.rendering.hibernateHiddenTabs.desc")}
|
||||
>
|
||||
@@ -1260,6 +1272,7 @@ function SettingsTerminalTab(props: {
|
||||
{terminalSettings.hibernateHiddenTabs && (
|
||||
<>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-hidden-tabs-delay"
|
||||
label={t("settings.terminal.rendering.hibernateHiddenTabsDelay")}
|
||||
description={t("settings.terminal.rendering.hibernateHiddenTabsDelay.desc")}
|
||||
>
|
||||
@@ -1281,6 +1294,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-skip-alt-screen"
|
||||
label={t("settings.terminal.rendering.hibernateSkipAltScreen")}
|
||||
description={t("settings.terminal.rendering.hibernateSkipAltScreen.desc")}
|
||||
>
|
||||
@@ -1290,6 +1304,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-keep-renderer-count"
|
||||
label={t("settings.terminal.rendering.hibernateKeepRendererCount")}
|
||||
description={t("settings.terminal.rendering.hibernateKeepRendererCount.desc")}
|
||||
>
|
||||
@@ -1308,6 +1323,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-replay-chunk-bytes"
|
||||
label={t("settings.terminal.rendering.hibernateReplayChunkBytes")}
|
||||
description={t("settings.terminal.rendering.hibernateReplayChunkBytes.desc")}
|
||||
>
|
||||
@@ -1327,6 +1343,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-hibernate-prefer-wasm-serialize"
|
||||
label={t("settings.terminal.rendering.hibernatePreferWasmSerialize")}
|
||||
description={t("settings.terminal.rendering.hibernatePreferWasmSerialize.desc")}
|
||||
>
|
||||
@@ -1354,6 +1371,7 @@ function SettingsTerminalTab(props: {
|
||||
{terminalSettings.inlineImagesEnabled && (
|
||||
<>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-kitty"
|
||||
label={t("settings.terminal.inlineImages.kitty")}
|
||||
description={t("settings.terminal.inlineImages.kitty.desc")}
|
||||
>
|
||||
@@ -1363,6 +1381,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-sixel"
|
||||
label={t("settings.terminal.inlineImages.sixel")}
|
||||
description={t("settings.terminal.inlineImages.sixel.desc")}
|
||||
>
|
||||
@@ -1372,6 +1391,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-iip"
|
||||
label={t("settings.terminal.inlineImages.iip")}
|
||||
description={t("settings.terminal.inlineImages.iip.desc")}
|
||||
>
|
||||
@@ -1381,6 +1401,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-storage-limit"
|
||||
label={t("settings.terminal.inlineImages.storageLimit")}
|
||||
description={t("settings.terminal.inlineImages.storageLimit.desc")}
|
||||
>
|
||||
@@ -1406,6 +1427,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-max-megapixels"
|
||||
label={t("settings.terminal.inlineImages.maxMegapixels")}
|
||||
description={t("settings.terminal.inlineImages.maxMegapixels.desc")}
|
||||
>
|
||||
@@ -1431,6 +1453,7 @@ function SettingsTerminalTab(props: {
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-inline-images-sequence-limit"
|
||||
label={t("settings.terminal.inlineImages.sequenceLimit")}
|
||||
description={t("settings.terminal.inlineImages.sequenceLimit.desc")}
|
||||
>
|
||||
@@ -1496,6 +1519,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-autocomplete-ghost-text"
|
||||
label={t("settings.terminal.autocomplete.ghostText")}
|
||||
description={t("settings.terminal.autocomplete.ghostText.desc")}
|
||||
>
|
||||
@@ -1506,6 +1530,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-autocomplete-popup-menu"
|
||||
label={t("settings.terminal.autocomplete.popupMenu")}
|
||||
description={t("settings.terminal.autocomplete.popupMenu.desc")}
|
||||
>
|
||||
@@ -1516,6 +1541,7 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-autocomplete-history-scope"
|
||||
label={t("settings.terminal.autocomplete.historyScope")}
|
||||
description={t("settings.terminal.autocomplete.historyScope.desc")}
|
||||
>
|
||||
|
||||
@@ -101,6 +101,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-right-click-long-press-menu"
|
||||
label={t("settings.terminal.behavior.rightClick.longPressMenu")}
|
||||
description={t("settings.terminal.behavior.rightClick.longPressMenu.desc")}
|
||||
>
|
||||
@@ -111,6 +112,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-right-click-fullscreen-menu"
|
||||
label={t("settings.terminal.behavior.rightClick.fullscreenMenu")}
|
||||
description={t("settings.terminal.behavior.rightClick.fullscreenMenu.desc")}
|
||||
>
|
||||
@@ -228,6 +230,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-shift-enter-newline-text"
|
||||
label={t("settings.terminal.behavior.shiftEnterNewlineText")}
|
||||
description={t("settings.terminal.behavior.shiftEnterNewlineText.desc")}
|
||||
>
|
||||
@@ -260,6 +263,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-preserve-selection-on-input"
|
||||
label={t("settings.terminal.behavior.preserveSelectionOnInput")}
|
||||
description={t("settings.terminal.behavior.preserveSelectionOnInput.desc")}
|
||||
>
|
||||
@@ -267,6 +271,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-force-prompt-new-line"
|
||||
label={t("settings.terminal.behavior.forcePromptNewLine")}
|
||||
description={t("settings.terminal.behavior.forcePromptNewLine.desc")}
|
||||
>
|
||||
@@ -341,6 +346,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-scroll-on-input"
|
||||
label={t("settings.terminal.behavior.scrollOnInput")}
|
||||
description={t("settings.terminal.behavior.scrollOnInput.desc")}
|
||||
>
|
||||
@@ -348,6 +354,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-scroll-on-output"
|
||||
label={t("settings.terminal.behavior.scrollOnOutput")}
|
||||
description={t("settings.terminal.behavior.scrollOnOutput.desc")}
|
||||
>
|
||||
@@ -355,6 +362,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-scroll-on-key-press"
|
||||
label={t("settings.terminal.behavior.scrollOnKeyPress")}
|
||||
description={t("settings.terminal.behavior.scrollOnKeyPress.desc")}
|
||||
>
|
||||
@@ -362,6 +370,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-scroll-on-paste"
|
||||
label={t("settings.terminal.behavior.scrollOnPaste")}
|
||||
description={t("settings.terminal.behavior.scrollOnPaste.desc")}
|
||||
>
|
||||
@@ -369,6 +378,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-smooth-scrolling"
|
||||
label={t("settings.terminal.behavior.smoothScrolling")}
|
||||
description={t("settings.terminal.behavior.smoothScrolling.desc")}
|
||||
>
|
||||
@@ -392,6 +402,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-link-modifier"
|
||||
label={t("settings.terminal.behavior.linkModifier")}
|
||||
description={t("settings.terminal.behavior.linkModifier.desc")}
|
||||
>
|
||||
|
||||
@@ -756,7 +756,7 @@ export const ExternalMcpCard: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<SettingsAnchor anchorId="ai-external-mcp-approval-alert">
|
||||
<SettingRow className="flex-col items-start md:flex-row md:items-center" label={t("ai.toolSettings.behavior")} description={t(mode === "persistent" ? "ai.externalMcp.mode.persistent" : "ai.externalMcp.mode.temporary")}>
|
||||
<SettingRow anchorId="ai-external-mcp-behavior" className="flex-col items-start md:flex-row md:items-center" label={t("ai.toolSettings.behavior")} description={t(mode === "persistent" ? "ai.externalMcp.mode.persistent" : "ai.externalMcp.mode.temporary")}>
|
||||
<ToolSettingsDialog title={t("ai.toolSettings.behavior")} triggerLabel={t("ai.toolSettings.configureBehavior")} immediate open={behaviorOpen} onOpenChange={setBehaviorOpen}>
|
||||
<SettingCard divided className="border-0 bg-transparent p-0">
|
||||
<SettingRow
|
||||
@@ -879,7 +879,7 @@ export const ExternalMcpCard: React.FC = () => {
|
||||
/>
|
||||
|
||||
<SettingCard>
|
||||
<SettingRow className="flex-col items-start md:flex-row md:items-center" label={t("ai.externalMcp.clientConfiguration")} description={t("ai.externalMcp.clientConfiguration.description")}>
|
||||
<SettingRow anchorId="ai-external-mcp-client-configuration" className="flex-col items-start md:flex-row md:items-center" label={t("ai.externalMcp.clientConfiguration")} description={t("ai.externalMcp.clientConfiguration.description")}>
|
||||
<ToolSettingsDialog title={t("ai.externalMcp.clientConfiguration")} triggerLabel={t("ai.toolSettings.configureClients")}>
|
||||
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
|
||||
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
|
||||
if (!result.ok) {
|
||||
if (discoveryKeyRef.current !== requestKey) return;
|
||||
|
||||
@@ -136,6 +136,7 @@ export const SafetySettings: React.FC<{
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="ai-safety-max-iterations"
|
||||
label={t('ai.safety.maxIterations')}
|
||||
description={t('ai.safety.maxIterations.description')}
|
||||
>
|
||||
|
||||
@@ -144,6 +144,7 @@ export const WebSearchSettings: React.FC<{
|
||||
{/* API Key (hidden for SearXNG) */}
|
||||
{preset.requiresApiKey && (
|
||||
<SettingRow
|
||||
anchorId="ai-web-search-api-key"
|
||||
label={t("ai.webSearch.apiKey")}
|
||||
description={t("ai.webSearch.apiKey.description")}
|
||||
>
|
||||
@@ -170,6 +171,7 @@ export const WebSearchSettings: React.FC<{
|
||||
|
||||
{/* API Host */}
|
||||
<SettingRow
|
||||
anchorId="ai-web-search-api-host"
|
||||
label={t("ai.webSearch.apiHost")}
|
||||
description={
|
||||
config.providerId === "searxng"
|
||||
@@ -188,6 +190,7 @@ export const WebSearchSettings: React.FC<{
|
||||
|
||||
{/* Max Results */}
|
||||
<SettingRow
|
||||
anchorId="ai-web-search-max-results"
|
||||
label={t("ai.webSearch.maxResults")}
|
||||
description={t("ai.webSearch.maxResults.description")}
|
||||
>
|
||||
|
||||
@@ -75,6 +75,9 @@ test('list hook preserves local copy/move routing, remote HTML drag, selection a
|
||||
await act(async () => root.render(React.createElement(Harness, { local: false })));
|
||||
await act(async () => right.handlePaneDrop(event()));
|
||||
assert.equal(actions.at(-1)?.kind, 'copy');
|
||||
actions.length = 0;
|
||||
await act(async () => left.handleEntryDrop(entries[2], event()));
|
||||
assert.deepEqual(actions, [{ kind: 'move', args: [['/files/b.txt'], '/files/folder'] }], 'same-pane remote drag stays a move');
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
clearLocalFileDrag();
|
||||
|
||||
@@ -2,9 +2,11 @@ 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, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { TerminalComposeBar } from './TerminalComposeBar';
|
||||
import { TerminalContextMenu } from './TerminalContextMenu';
|
||||
import { TooltipProvider } from '../ui/tooltip';
|
||||
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from '../../application/state/composeBarHistoryStore';
|
||||
import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
|
||||
@@ -303,3 +305,54 @@ test('compose send target toggle shows all vs active without looking like broadc
|
||||
assert.equal(stillPulsing.length, 0);
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
|
||||
|
||||
test('compose right-click never pastes into the terminal behind it', async (t) => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { url: 'http://localhost' });
|
||||
const globals = ['window', 'document', 'localStorage', 'Element', 'HTMLElement', 'Node'] 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] });
|
||||
}
|
||||
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);
|
||||
}
|
||||
});
|
||||
let pasteCount = 0;
|
||||
const render = (broadcast: boolean) => (
|
||||
<I18nProvider locale="en"><TooltipProvider>
|
||||
<TerminalContextMenu sessionId="right-click-test" status="connected" rightClickBehavior="paste" onPaste={() => { pasteCount++; }}>
|
||||
<div>
|
||||
<div data-terminal-cell />
|
||||
<TerminalComposeBar sessionId="right-click-test" isBroadcastEnabled={broadcast} onSend={() => true} onClose={() => {}} />
|
||||
</div>
|
||||
</TerminalContextMenu>
|
||||
</TooltipProvider></I18nProvider>
|
||||
);
|
||||
const rightClick = async (target: string) => {
|
||||
const element = rootElement.querySelector(target);
|
||||
assert.ok(element, target);
|
||||
await act(async () => {
|
||||
element.dispatchEvent(new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 }));
|
||||
});
|
||||
};
|
||||
|
||||
await act(async () => root.render(render(false)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 0, 'the solo composer must not paste into the PTY');
|
||||
await rightClick('[data-terminal-cell]');
|
||||
assert.equal(pasteCount, 1, 'ordinary terminal right-click paste still works');
|
||||
|
||||
await act(async () => root.render(render(true)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 1, 'broadcast compose opens only its own menu');
|
||||
assert.ok(rootElement.querySelector('[data-compose-broadcast-menu]'));
|
||||
await rightClick('[data-compose-broadcast-menu]');
|
||||
assert.equal(pasteCount, 1, 'right-click on the compose menu must not paste into the PTY');
|
||||
});
|
||||
@@ -360,9 +360,11 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const sendToAll = composeSendToAll ?? Boolean(isBroadcastEnabled);
|
||||
const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => {
|
||||
// A solo composer is inside the terminal's context-menu trigger, but this
|
||||
// gesture must never run a terminal action (such as paste into the PTY).
|
||||
event.stopPropagation();
|
||||
if (!isBroadcastEnabled && !sendToAll) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setBroadcastMenuAnchor({
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
|
||||
@@ -2601,6 +2601,18 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
}
|
||||
}
|
||||
|
||||
// Claim Shift+Insert as clipboard paste before Kitty/Win32 or xterm can
|
||||
// encode it as an Insert key, while preserving user shortcut precedence.
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void ctx.terminalContextActionsRef?.current?.onPaste?.();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
|
||||
// full-width "," arrives on insertText. Returning false (without
|
||||
// preventDefault) stops xterm/Kitty from sending the half-width key so the
|
||||
@@ -2776,15 +2788,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
};
|
||||
return true;
|
||||
}
|
||||
// xterm leaves Shift+Insert to the browser's native paste handler. Fan out
|
||||
// the clipboard data from onData instead of encoding an Insert key for
|
||||
// peers or treating the paste as that key's pending legacy data (#4142).
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!shouldDeferKittyKeyEvent(normalizedKittyEvent)) {
|
||||
const identity = kittyKeyIdentity(e);
|
||||
if (
|
||||
|
||||
@@ -65,3 +65,24 @@ test('disabled or mouse-owned gestures retain the full original event sequence',
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
|
||||
test('right-click in the compose bar is never captured or replayed as terminal paste', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const dom = new JSDOM('<div id="root"><div data-section="terminal-compose-bar"><textarea></textarea></div></div>');
|
||||
const root = dom.window.document.querySelector<HTMLElement>('#root')!;
|
||||
const compose = root.querySelector('textarea')!;
|
||||
const dispose = installRightClickLongPress(root, () => true);
|
||||
const seen: EventTarget[] = [];
|
||||
root.addEventListener('contextmenu', (event) => seen.push(event.target!));
|
||||
const fire = (type: string) => compose.dispatchEvent(new dom.window.MouseEvent(type, {
|
||||
bubbles: true, cancelable: true, button: 2, buttons: type === 'mouseup' ? 0 : 2,
|
||||
}));
|
||||
fire('mousedown');
|
||||
fire('contextmenu');
|
||||
t.mock.timers.tick(RIGHT_CLICK_LONG_PRESS_MS);
|
||||
fire('mouseup');
|
||||
assert.deepEqual(seen, [compose], 'only the original composer event should be delivered');
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
@@ -37,7 +37,7 @@ export function installRightClickLongPress(
|
||||
suppressContextMenu = false;
|
||||
if (event.button !== 2 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey
|
||||
|| !canStart()
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview]')) return;
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview], [data-section="terminal-compose-bar"]')) return;
|
||||
press = event;
|
||||
suppressContextMenu = true;
|
||||
timer = setTimeout(() => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { buildSync } from "esbuild";
|
||||
import { JSDOM } from "jsdom";
|
||||
import ts from "typescript";
|
||||
|
||||
test("native Shift+Insert broadcasts clipboard bytes once without an Insert key", async () => {
|
||||
test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keyboard modes", async () => {
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const layer = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8");
|
||||
const start = layer.indexOf(" const handleBroadcastInput = useCallback(");
|
||||
@@ -21,6 +21,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
contents: `
|
||||
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
|
||||
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
|
||||
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
|
||||
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
|
||||
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
|
||||
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
|
||||
export * from "./components/terminal/runtime/terminalPacedBroadcast";
|
||||
@@ -50,7 +52,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
`);
|
||||
dom.window.eval(bundle);
|
||||
const results = await dom.window.eval(`(async () => {
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, resolveTerminalBroadcastTargetIds,
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
|
||||
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
|
||||
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
|
||||
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
|
||||
const ref = current => ({current});
|
||||
@@ -60,71 +63,123 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
const canUseDirectSessionWriteFallback = () => true;
|
||||
const isTerminalSensitiveInputActive = () => false;
|
||||
const wires = new Map();
|
||||
const pasteCalls = new Map();
|
||||
const terminalBackend = {
|
||||
writeToSession:(id,data)=>wires.get(id).push(data), resizeSession(){}, openExternalAvailable:false,
|
||||
};
|
||||
${dispatcher}
|
||||
const make = (id, kittyKeyboardProtocolEnabled) => {
|
||||
const make = (id, kittyKeyboardProtocolEnabled, options = {}) => {
|
||||
const container = document.createElement('div'); document.body.appendChild(container);
|
||||
wires.set(id, []);
|
||||
pasteCalls.set(id, 0);
|
||||
const terminalContextActionsRef = ref({});
|
||||
const host = {id,label:id,hostname:'localhost',protocol:'ssh',sshInputCompatibility:false};
|
||||
return createXTermRuntime({
|
||||
const runtime = createXTermRuntime({
|
||||
container, host, getHost:()=>host, sessionId:id, sessionRef:ref(id), statusRef:ref('connected'),
|
||||
fontFamilyId:'jetbrains-mono',resolvedFontFamily:'monospace',fontSize:14,
|
||||
terminalTheme:{colors:{background:'#111111',foreground:'#eeeeee',cursor:'#ffffff',selection:'#444444'}},
|
||||
terminalSettingsRef:ref({...DEFAULT_TERMINAL_SETTINGS,rendererType:'dom',fontLigatures:false,cursorBlink:false}),
|
||||
terminalBackend,hotkeySchemeRef:ref('disabled'),keyBindingsRef:ref([]),onHotkeyActionRef:ref(undefined),
|
||||
terminalBackend,hotkeySchemeRef:ref('pc'),
|
||||
keyBindingsRef:ref(options.bindings ?? DEFAULT_KEY_BINDINGS),onHotkeyActionRef:ref(undefined),
|
||||
terminalContextActionsRef, snippetsRef:ref(options.snippets ?? []),
|
||||
onSnippetShortkeyRef:ref(options.onSnippet),
|
||||
isBroadcastEnabledRef:ref(true),onBroadcastInputRef:ref(handleBroadcastInput),
|
||||
commandBufferRef:ref(''),requestSearchFocus(){},kittyKeyboardProtocolEnabled,
|
||||
commandBufferRef:ref(''),requestSearchFocus:options.onSearch ?? (()=>{}),kittyKeyboardProtocolEnabled,
|
||||
});
|
||||
terminalContextActionsRef.current.onPaste = async () => {
|
||||
pasteCalls.set(id, pasteCalls.get(id) + 1);
|
||||
if (options.delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
pasteTextIntoTerminal(runtime.term, 'clipboard', {scrollOnPaste:false});
|
||||
};
|
||||
return runtime;
|
||||
};
|
||||
const results = [];
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', false), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
const beforePaste = [...wires.get('peer')];
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
// Supply the native clipboard event which Chromium emits for this chord.
|
||||
const paste = new Event('paste', {bubbles:true,cancelable:true});
|
||||
Object.defineProperty(paste,'clipboardData',{value:{getData:()=> 'clipboard'}});
|
||||
source.term.textarea.dispatchEvent(paste);
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({bracketed,delayed,peerKitty,beforePaste,
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty) {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
const modes = [
|
||||
{name:'legacy',kitty:false,setup:''},
|
||||
{name:'native-kitty',kitty:false,setup:'\\x1b[>1u'},
|
||||
{name:'native-kitty-all-keys',kitty:false,setup:'\\x1b[>8u'},
|
||||
{name:'netcatty-kitty',kitty:true,setup:'\\x1b[>1u'},
|
||||
{name:'win32',kitty:false,setup:'\\x1b[?9001h'},
|
||||
];
|
||||
for (const mode of modes) {
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', mode.kitty, {delayed}), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (mode.setup) await new Promise(resolve=>source.term.write(mode.setup,resolve));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({plainInsert:true,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
results.push({mode:mode.name,bracketed,delayed,peerKitty,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty && mode.name !== 'win32') {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
}));
|
||||
results.push({plainInsert:true,mode:mode.name,pasteCalls:pasteCalls.get('source'),
|
||||
source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
const pasteShortcut = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(pasteShortcut);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
}));
|
||||
results.push({configuredPaste:true,mode:mode.name,bracketed,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:pasteShortcut.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const shortcut of ['binding','snippet']) {
|
||||
let searchCalls = 0, snippetCalls = 0;
|
||||
const source = make('source', true, shortcut === 'binding'
|
||||
? {onSearch:()=>searchCalls++,bindings:DEFAULT_KEY_BINDINGS.map(binding=>binding.action === 'searchTerminal'
|
||||
? {...binding,pc:'Shift + Insert'} : binding)}
|
||||
: {snippets:[{id:'snippet',shortkey:'Shift + Insert'}],onSnippet:()=>snippetCalls++});
|
||||
try {
|
||||
await new Promise(resolve=>source.term.write('\\x1b[>1u',resolve));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({shortcut,pasteCalls:pasteCalls.get('source'),snippetCalls,searchCalls,
|
||||
source:[...wires.get('source')]});
|
||||
} finally { source.dispose(); }
|
||||
}
|
||||
return JSON.stringify(results);
|
||||
})()`);
|
||||
for (const result of JSON.parse(results)) {
|
||||
if (result.plainInsert) {
|
||||
assert.equal(result.pasteCalls, 1);
|
||||
assert.deepEqual(result.source, ["\x1b[2~"]);
|
||||
assert.deepEqual(result.peer, ["\x1b[2~"]);
|
||||
continue;
|
||||
}
|
||||
if (result.shortcut) {
|
||||
assert.equal(result.pasteCalls, 0, result.shortcut);
|
||||
assert.equal(result.snippetCalls, result.shortcut === 'snippet' ? 1 : 0);
|
||||
assert.equal(result.searchCalls, result.shortcut === 'binding' ? 1 : 0);
|
||||
assert.deepEqual(result.source, []);
|
||||
continue;
|
||||
}
|
||||
const label = JSON.stringify(result);
|
||||
assert.deepEqual(result.beforePaste, [], label);
|
||||
assert.equal(result.prevented, false, "native paste must remain enabled: " + label);
|
||||
assert.equal(result.pasteCalls, result.configuredPaste ? 2 : 1, label);
|
||||
assert.equal(result.prevented, true, label);
|
||||
const expected = result.bracketed ? "\x1b[200~clipboard\x1b[201~" : "clipboard";
|
||||
assert.deepEqual(result.source, [expected], label);
|
||||
assert.deepEqual(result.peer, [expected], label);
|
||||
|
||||
@@ -89,6 +89,15 @@ test("a visible pane past the cap releases the least recently seen hidden pane",
|
||||
assert.equal(budget.getActiveCount(), 3);
|
||||
});
|
||||
|
||||
test("new visible panes are refused when visible holders fill the cap", () => {
|
||||
const { budget } = setup(2);
|
||||
const members = ["a", "b", "c", "d"].map((name) => new FakeMember(name));
|
||||
assert.deepEqual(members.map((member) => budget.tryAcquire(member)), [true, true, false, false]);
|
||||
assert.equal(budget.tryAcquire(members[0]), true, "an existing holder keeps its slot");
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
assert.deepEqual(members.map((member) => member.releases), [0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test("recently hidden panes are released only once they stay hidden long enough", () => {
|
||||
const { clock, budget } = setup(2);
|
||||
const [a, b] = ["a", "b"].map((name) => new FakeMember(name));
|
||||
@@ -101,6 +110,8 @@ test("recently hidden panes are released only once they stay hidden long enough"
|
||||
budget.tryAcquire(new FakeMember("shown"));
|
||||
assert.equal(a.releases, 0, "a quick tab flip must not lose the renderer");
|
||||
assert.equal(budget.getActiveCount(), 3);
|
||||
assert.equal(budget.tryAcquire(new FakeMember("overflow")), false);
|
||||
assert.equal(budget.getActiveCount(), 3, "one hidden holder allows only one extra context");
|
||||
|
||||
clock.advance(2_999);
|
||||
assert.equal(a.releases, 0);
|
||||
@@ -110,26 +121,33 @@ test("recently hidden panes are released only once they stay hidden long enough"
|
||||
assert.equal(clock.pendingTimers, 0);
|
||||
});
|
||||
|
||||
test("a pane hidden after the budget went over is released once eligible", () => {
|
||||
test("a pane hidden after a grace overshoot is released once eligible", () => {
|
||||
const { clock, budget } = setup(2);
|
||||
const [a, b, c] = ["a", "b", "c"].map((name) => new FakeMember(name));
|
||||
budget.tryAcquire(a);
|
||||
budget.tryAcquire(b);
|
||||
budget.tryAcquire(c);
|
||||
assert.equal(budget.getActiveCount(), 3, "three visible panes all keep WebGL");
|
||||
assert.equal(budget.tryAcquire(c), false);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
assert.equal(clock.pendingTimers, 0);
|
||||
|
||||
a.hiddenSince = clock.now();
|
||||
budget.noteHidden(a);
|
||||
assert.equal(budget.tryAcquire(c), true);
|
||||
assert.equal(budget.getActiveCount(), 3, "recently hidden holders allow a grace overshoot");
|
||||
a.hiddenSince = null;
|
||||
b.hiddenSince = clock.now();
|
||||
budget.noteHidden(b);
|
||||
clock.advance(3_000);
|
||||
|
||||
assert.equal(b.releases, 1);
|
||||
assert.equal(a.releases, 0, "a holder shown again keeps its renderer");
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
});
|
||||
|
||||
test("a hidden pane cannot take a context once the budget is full", () => {
|
||||
const { budget } = setup(2);
|
||||
budget.tryAcquire(new FakeMember("a"));
|
||||
const { clock, budget } = setup(2);
|
||||
const a = new FakeMember("a");
|
||||
budget.tryAcquire(a);
|
||||
budget.tryAcquire(new FakeMember("b"));
|
||||
|
||||
const hidden = new FakeMember("hidden");
|
||||
@@ -138,7 +156,13 @@ test("a hidden pane cannot take a context once the budget is full", () => {
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
|
||||
hidden.hiddenSince = null;
|
||||
assert.equal(budget.tryAcquire(hidden), true, "it gets one as soon as it is shown");
|
||||
assert.equal(budget.tryAcquire(hidden), false, "visible holders still fill the cap");
|
||||
a.hiddenSince = clock.now();
|
||||
budget.noteHidden(a);
|
||||
clock.advance(3_000);
|
||||
assert.equal(budget.tryAcquire(hidden), true, "a shown pane can replace an eligible hidden holder");
|
||||
assert.equal(a.releases, 1);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
});
|
||||
|
||||
test("released and forgotten panes free their slot", () => {
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
*
|
||||
* The budget stays below the browser limit by releasing the renderers of panes
|
||||
* that have been hidden for a while, least recently seen first. Visible panes
|
||||
* are never released and always get a context. A released pane builds a new
|
||||
* renderer when it is shown again. Below the cap nothing changes.
|
||||
* are never released, but new ones stay on DOM when visible holders fill the
|
||||
* cap. Recently hidden holders may temporarily exceed the cap during tab flips.
|
||||
* A released pane can rebuild when shown if the budget permits.
|
||||
*/
|
||||
|
||||
export const MAX_ACTIVE_WEBGL_CONTEXTS = 12;
|
||||
@@ -31,8 +32,8 @@ export interface WebglContextBudgetMember {
|
||||
|
||||
export interface WebglContextBudget {
|
||||
/**
|
||||
* Reserve a context for a member about to create its renderer. Visible
|
||||
* members always get one; hidden members only while the budget has room.
|
||||
* Reserve a context if the budget has room. Visible members may replace
|
||||
* hidden holders, allowing a temporary overshoot until their grace expires.
|
||||
*/
|
||||
tryAcquire(member: WebglContextBudgetMember): boolean;
|
||||
/** Give the slot back once the member's renderer is gone. Idempotent. */
|
||||
@@ -102,7 +103,11 @@ export function createWebglContextBudget(
|
||||
return {
|
||||
tryAcquire(member) {
|
||||
if (active.has(member)) return true;
|
||||
if (member.getHiddenSince() !== null && active.size >= maxActive) return false;
|
||||
if (active.size >= maxActive) {
|
||||
if (member.getHiddenSince() !== null) return false;
|
||||
const visibleCount = [...active].filter((holder) => holder.getHiddenSince() === null).length;
|
||||
if (visibleCount >= maxActive) return false;
|
||||
}
|
||||
active.add(member);
|
||||
releaseOverflow();
|
||||
return true;
|
||||
|
||||
@@ -186,20 +186,93 @@ test("panes past the budget give up WebGL after staying hidden, and get it back
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
});
|
||||
|
||||
test("simultaneous visible ensures stay within the context budget", () => {
|
||||
const { budget, createPane } = setup();
|
||||
const panes = Array.from({ length: 13 }, () => createPane());
|
||||
for (const pane of panes) pane.controller.ensure();
|
||||
|
||||
assert.deepEqual(panes.map((pane) => pane.loaded), [...Array(12).fill(true), false]);
|
||||
assert.equal(panes[12].addons.length, 0);
|
||||
assert.equal(budget.getActiveCount(), 12);
|
||||
});
|
||||
|
||||
test("visible context loss recovers at the cap, including with a refused visible pane", () => {
|
||||
for (const withOverflow of [false, true]) {
|
||||
const { clock, budget, createPane } = setup(2);
|
||||
const panes = [createPane(), createPane()];
|
||||
for (const pane of panes) pane.controller.ensure();
|
||||
const overflow = withOverflow ? createPane() : null;
|
||||
overflow?.controller.ensure();
|
||||
assert.equal(overflow?.addons.length ?? 0, 0);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
|
||||
panes[0].addons[0].loseContext();
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
clock.advance(49);
|
||||
assert.equal(panes[0].loaded, false);
|
||||
clock.advance(1);
|
||||
assert.equal(panes[0].loaded, true);
|
||||
assert.equal(panes[0].addons.length, 2);
|
||||
assert.equal(panes[1].addons.length, 1);
|
||||
overflow?.controller.ensure();
|
||||
assert.equal(overflow?.addons.length ?? 0, 0);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
assert.equal(clock.pendingTimers, 0);
|
||||
assert.ok(panes.every((pane) => !pane.warnings.some((warning) => warning.includes("staying on DOM renderer"))));
|
||||
}
|
||||
});
|
||||
|
||||
test("visible loss stays on DOM if another visible pane takes the freed slot before recovery", () => {
|
||||
const { clock, budget, createPane } = setup(2);
|
||||
const panes = [createPane(), createPane(), createPane()];
|
||||
for (const pane of panes) pane.controller.ensure();
|
||||
assert.equal(panes[2].loaded, false);
|
||||
|
||||
panes[0].addons[0].loseContext();
|
||||
panes[2].controller.ensure();
|
||||
assert.equal(panes[2].loaded, true);
|
||||
clock.advance(50);
|
||||
|
||||
assert.equal(panes[0].loaded, false);
|
||||
assert.deepEqual(panes.map((pane) => pane.addons.length), [1, 1, 1]);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
assert.equal(clock.pendingTimers, 0);
|
||||
assert.ok(panes.every((pane) => !pane.warnings.some((warning) => warning.includes("staying on DOM renderer"))));
|
||||
});
|
||||
|
||||
test("a hidden pane mounted past the budget keeps the DOM renderer until shown", () => {
|
||||
const { budget, createPane } = setup(1);
|
||||
createPane().controller.ensure();
|
||||
const { clock, budget, createPane } = setup(1);
|
||||
const occupant = createPane();
|
||||
occupant.controller.ensure();
|
||||
|
||||
const hidden = createPane(false);
|
||||
hidden.controller.ensure();
|
||||
assert.equal(hidden.addons.length, 0);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
|
||||
occupant.setVisible(false);
|
||||
clock.advance(3_000);
|
||||
hidden.reveal();
|
||||
assert.equal(hidden.loaded, true);
|
||||
assert.equal(occupant.loaded, false);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
});
|
||||
|
||||
test("a pane on screen is never refused or released, even if a sync was missed", () => {
|
||||
test("revealing a hidden pane is refused while visible holders fill the budget", () => {
|
||||
const { budget, createPane } = setup(1);
|
||||
const occupant = createPane();
|
||||
occupant.controller.ensure();
|
||||
const hidden = createPane(false);
|
||||
hidden.controller.ensure();
|
||||
hidden.reveal();
|
||||
|
||||
assert.equal(hidden.loaded, false);
|
||||
assert.equal(hidden.addons.length, 0);
|
||||
assert.equal(occupant.loaded, true);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
});
|
||||
|
||||
test("a holder on screen is never released, even if a sync was missed", () => {
|
||||
const { clock, budget, createPane } = setup(1);
|
||||
const visible = createPane();
|
||||
visible.controller.ensure();
|
||||
@@ -210,12 +283,37 @@ test("a pane on screen is never refused or released, even if a sync was missed",
|
||||
createPane().controller.ensure();
|
||||
clock.advance(10_000);
|
||||
assert.equal(visible.loaded, true);
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
|
||||
const late = createPane(false);
|
||||
late.setVisibleWithoutSync(true);
|
||||
late.controller.ensure();
|
||||
assert.equal(late.loaded, true);
|
||||
assert.equal(late.loaded, false);
|
||||
assert.equal(late.addons.length, 0);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
});
|
||||
|
||||
test("grace overflow never releases a holder shown again without a visibility sync", () => {
|
||||
const { clock, budget, createPane } = setup(1);
|
||||
const holder = createPane();
|
||||
holder.controller.ensure();
|
||||
holder.setVisible(false);
|
||||
const front = createPane();
|
||||
front.controller.ensure();
|
||||
assert.equal(budget.getActiveCount(), 2);
|
||||
|
||||
holder.setVisibleWithoutSync(true);
|
||||
clock.advance(3_000);
|
||||
assert.equal(holder.loaded, true);
|
||||
assert.equal(front.loaded, true);
|
||||
assert.equal(holder.addons[0].disposeCalls, 0);
|
||||
|
||||
front.addons[0].loseContext();
|
||||
clock.advance(50);
|
||||
assert.equal(front.loaded, false, "recovery cannot exceed a cap already filled by visible holders");
|
||||
assert.equal(front.addons.length, 1);
|
||||
assert.equal(budget.getActiveCount(), 1);
|
||||
assert.equal(clock.pendingTimers, 0);
|
||||
});
|
||||
|
||||
test("suspend, dispose and failed loads return the budget slot", () => {
|
||||
|
||||
@@ -65,7 +65,7 @@ export function createWebglRendererController<TAddon extends WebglRendererAddon>
|
||||
|
||||
// isVisible() is the source of truth; hiddenSince only remembers when the
|
||||
// pane was last seen. Re-reading it at every decision keeps a pane that is
|
||||
// on screen from being refused or released even if a sync was missed.
|
||||
// on screen from being released even if a sync was missed.
|
||||
const readVisibility = () => {
|
||||
if (!options.isVisible) return;
|
||||
if (options.isVisible()) hiddenSince = null;
|
||||
@@ -94,7 +94,7 @@ export function createWebglRendererController<TAddon extends WebglRendererAddon>
|
||||
|
||||
const ensure = () => {
|
||||
if (loaded || circuitBroken || disposed || !options.enabled) return;
|
||||
// A hidden pane past the budget keeps the DOM renderer until it is shown.
|
||||
// Panes past the budget keep the DOM renderer until a slot is available.
|
||||
if (budget && !budget.tryAcquire(budgetMember)) return;
|
||||
let nextAddon: TAddon | null = null;
|
||||
try {
|
||||
|
||||
@@ -938,9 +938,9 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A boot that never reached "connected" has nothing worth capturing, and
|
||||
// the teardown below awaits terminal drain plus serialization before it
|
||||
// closes anything. Cancel the pending backend boot after giving an immediate
|
||||
// Never-connected logs are captured at explicit session close, including
|
||||
// empty buffers. Runtime cleanup alone must not end an open log.
|
||||
// Cancel the pending backend boot after giving an immediate
|
||||
// remount a chance to replace this generation, instead of letting it
|
||||
// finish against a pane that is already gone. Attached popups never own
|
||||
// the backend session (skip closeSession) but still sync-dispose xterm.
|
||||
|
||||
@@ -374,3 +374,14 @@ test('side panel close button stays visible at every panel width', () => {
|
||||
assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/);
|
||||
assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/);
|
||||
});
|
||||
|
||||
test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => {
|
||||
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
|
||||
const overlay = source.slice(
|
||||
source.indexOf('data-section="pane-magnification-overlay"'),
|
||||
source.indexOf('data-section="pane-magnification-content"'),
|
||||
);
|
||||
assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/);
|
||||
assert.match(overlay, /borderColor: sidePanelTheme\.accent,/);
|
||||
assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
|
||||
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
|
||||
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
|
||||
|
||||
const MemoizedSidePanelMountedContent = memo(
|
||||
SidePanelMountedContent,
|
||||
@@ -1545,6 +1545,9 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
|
||||
style={{
|
||||
borderColor: sidePanelTheme.accent,
|
||||
borderWidth: resolveMagnifiedChromeBorderWidth(
|
||||
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
|
||||
),
|
||||
backgroundColor: sidePanelTheme.termBg,
|
||||
color: sidePanelTheme.termFg,
|
||||
}}
|
||||
|
||||
@@ -52,6 +52,7 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
|
||||
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import type { SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
import {
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolvePaneMagnificationStyle,
|
||||
type PaneMagnificationController,
|
||||
type PaneMagnificationTarget,
|
||||
@@ -1439,10 +1440,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
observer.observe(surface);
|
||||
return () => observer.disconnect();
|
||||
}, [isMagnified]);
|
||||
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
|
||||
const style: React.CSSProperties = resolvePaneMagnificationStyle(
|
||||
layoutStyle,
|
||||
isMagnified && !!magnifiedSurfaceBounds,
|
||||
magnifiedSurfaceBounds,
|
||||
magnifiedDevicePixelRatio,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -1605,6 +1608,9 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
style={{
|
||||
...style,
|
||||
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: isMagnified && magnifiedSurfaceBounds
|
||||
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
|
||||
: undefined,
|
||||
}}
|
||||
tabIndex={-1}
|
||||
onClick={handlePaneClick}
|
||||
|
||||
@@ -15,6 +15,14 @@ test("magnified terminal panes use the resolved terminal accent for border chrom
|
||||
|
||||
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl /);
|
||||
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
|
||||
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
|
||||
});
|
||||
|
||||
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*\)/);
|
||||
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
|
||||
});
|
||||
|
||||
test("terminal keyboard focus updates the pane selected for magnification", () => {
|
||||
|
||||
@@ -33,17 +33,17 @@
|
||||
<text x="85" y="85.0" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
|
||||
<text x="43" y="271.5" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
|
||||
<text x="90.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
|
||||
<text x="214.5" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="347.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="481.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="616.5" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="749.7" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="211.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="342.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="472.4" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="604.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="735.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="50%" y="525" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
|
||||
<line x1="90" y1="80" x2="90" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<line x1="90" y1="463" x2="765" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
|
||||
<circle cx="765.0" cy="119.4" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7176</text>
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
|
||||
<circle cx="765.0" cy="108.4" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7406</text>
|
||||
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#fff" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 38 KiB |
@@ -33,17 +33,17 @@
|
||||
<text x="85" y="85.0" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
|
||||
<text x="43" y="271.5" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
|
||||
<text x="90.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
|
||||
<text x="214.5" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="347.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="481.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="616.5" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="749.7" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="211.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="342.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="472.4" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="604.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="735.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="50%" y="525" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
|
||||
<line x1="90" y1="80" x2="90" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<line x1="90" y1="463" x2="765" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
|
||||
<circle cx="765.0" cy="119.4" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7176</text>
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
|
||||
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
|
||||
<circle cx="765.0" cy="108.4" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7406</text>
|
||||
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#000" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 38 KiB |
@@ -1,6 +1,11 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { describeHostKey } = require("../electron/bridges/hostKeyVerifier.cjs");
|
||||
const { mintHostCertificates, legacyCertificate, sshString, sshKeygenSkip } = require("../electron/bridges/fixtures/hostCertificates.test.fixture.cjs");
|
||||
|
||||
import type { KnownHost } from "./models";
|
||||
import {
|
||||
@@ -139,6 +144,55 @@ test("fingerprintFromPublicKey returns empty string on missing input", () => {
|
||||
|
||||
// --- Migration --------------------------------------------------------------
|
||||
|
||||
for (const options of [
|
||||
{ type: "ed25519" },
|
||||
{ type: "rsa", bits: 2048 },
|
||||
...[256, 384, 521].map((bits) => ({ type: "ecdsa", bits })),
|
||||
{ type: "ed25519", sk: true },
|
||||
{ type: "ecdsa", bits: 256, sk: true },
|
||||
]) {
|
||||
test(`renderer certificate fingerprint and migration agree with verifier: ${JSON.stringify(options)}`, { skip: sshKeygenSkip }, (t) => {
|
||||
const { first, renewed, different } = mintHostCertificates(t, options);
|
||||
const expected = describeHostKey(first.blob).fingerprint;
|
||||
assert.equal(fingerprintFromPublicKey(first.line), expected);
|
||||
assert.equal(expected, first.publicKeyFingerprint);
|
||||
assert.equal(fingerprintFromPublicKey(renewed.line), expected);
|
||||
assert.notEqual(fingerprintFromPublicKey(different.line), expected);
|
||||
assert.equal(fingerprintFromPublicKey(first.plain.line), expected);
|
||||
|
||||
const legacy = knownHost({
|
||||
keyType: first.keyType,
|
||||
publicKey: first.line,
|
||||
fingerprint: crypto.createHash("sha256").update(first.blob).digest("base64").replace(/=+$/g, ""),
|
||||
});
|
||||
const migrated = normalizeKnownHost(legacy);
|
||||
assert.equal(migrated.fingerprint, expected);
|
||||
assert.equal(migrated.keyType, first.keyType);
|
||||
assert.equal(migrated.publicKey, first.line);
|
||||
assert.equal(normalizeKnownHost(migrated), migrated, "migration is idempotent");
|
||||
assert.equal(normalizeKnownHost({ ...legacy, fingerprint: undefined }).fingerprint, expected);
|
||||
assert.equal(normalizeKnownHost({ ...legacy, keyType: "" }).keyType, first.keyType);
|
||||
const unrelated = { ...legacy, fingerprint: "unrelated-explicit-fingerprint" };
|
||||
assert.equal(normalizeKnownHost(unrelated), unrelated);
|
||||
const opaque = { ...legacy, publicKey: `SHA256:${legacy.fingerprint}` };
|
||||
assert.equal(normalizeKnownHost(opaque), opaque);
|
||||
const fingerprintOnly = { ...legacy, publicKey: undefined };
|
||||
assert.equal(normalizeKnownHost(fingerprintOnly), fingerprintOnly);
|
||||
});
|
||||
}
|
||||
|
||||
test("renderer fingerprints v00 certificates and falls back for unparseable certificates", () => {
|
||||
const cert = legacyCertificate("ssh-rsa", ["exponent", "modulus"]);
|
||||
assert.equal(fingerprintFromPublicKey(cert.line), describeHostKey(cert.plain).fingerprint);
|
||||
const malformed = Buffer.concat([
|
||||
sshString("ssh-ed25519-cert-v01@openssh.com"), sshString("nonce"), sshString(Buffer.alloc(32)),
|
||||
]);
|
||||
const line = `ssh-ed25519-cert-v01@openssh.com ${malformed.toString("base64")}`;
|
||||
const fullHash = crypto.createHash("sha256").update(malformed).digest("base64").replace(/=+$/g, "");
|
||||
assert.equal(fingerprintFromPublicKey(line), fullHash);
|
||||
assert.equal(fingerprintFromPublicKey(line), describeHostKey(malformed).fingerprint);
|
||||
});
|
||||
|
||||
test("normalizeKnownHost backfills fingerprint when only publicKey is stored", () => {
|
||||
const rawKey = makeRawPublicKey("ssh-ed25519");
|
||||
const base64Body = rawKey.toString("base64");
|
||||
|
||||
+15
-6
@@ -1,4 +1,5 @@
|
||||
import type { KnownHost } from "./models";
|
||||
import { extractCertificatePublicKey } from "@/domain/sshPublicKey.shared.cjs";
|
||||
|
||||
const normalizeHost = (value: string) => value.trim().toLowerCase();
|
||||
|
||||
@@ -132,7 +133,7 @@ export const fingerprintFromPublicKey = (publicKey: string | undefined | null):
|
||||
const parts = trimmed.split(/\s+/);
|
||||
if (parts.length >= 2 && SSH_KEY_TYPE_PREFIX.test(parts[0])) {
|
||||
const bytes = base64Decode(parts[1]);
|
||||
if (bytes) return stripPadding(base64Encode(sha256Bytes(bytes)));
|
||||
if (bytes) return stripPadding(base64Encode(sha256Bytes(extractCertificatePublicKey(bytes) || bytes)));
|
||||
}
|
||||
|
||||
return stripPadding(trimmed);
|
||||
@@ -145,9 +146,9 @@ const extractKeyTypeFromPublicKey = (publicKey: string | undefined | null): stri
|
||||
};
|
||||
|
||||
/**
|
||||
* Backfill missing `fingerprint` / `keyType` on a stored record so the host
|
||||
* verifier can match it without falling back to the brittle re-derivation
|
||||
* path. Returns the same reference when nothing changes so callers can skip
|
||||
* Backfill missing `fingerprint` / `keyType` and migrate full-certificate
|
||||
* fingerprints to the underlying key when the certificate body is available.
|
||||
* Returns the same reference when nothing changes so callers can skip
|
||||
* persistence writes and React re-renders.
|
||||
*/
|
||||
export const normalizeKnownHost = (knownHost: KnownHost): KnownHost => {
|
||||
@@ -156,9 +157,17 @@ export const normalizeKnownHost = (knownHost: KnownHost): KnownHost => {
|
||||
&& knownHost.keyType.length > 0
|
||||
&& knownHost.keyType !== "unknown";
|
||||
|
||||
if (hasFingerprint && hasKeyType) return knownHost;
|
||||
const parts = knownHost.publicKey?.trim().split(/\s+/) ?? [];
|
||||
const certBytes = /-cert-v0[01]@openssh\.com$/.test(parts[0]) && parts[1]
|
||||
? base64Decode(parts[1]) : null;
|
||||
const legacyCertFingerprint = certBytes && extractCertificatePublicKey(certBytes)
|
||||
? stripPadding(base64Encode(sha256Bytes(certBytes))) : "";
|
||||
const migrateCertificate = legacyCertFingerprint
|
||||
&& stripPadding((knownHost.fingerprint ?? "").replace(/^SHA256:/i, "")) === legacyCertFingerprint;
|
||||
|
||||
const derivedFingerprint = hasFingerprint
|
||||
if (hasFingerprint && hasKeyType && !migrateCertificate) return knownHost;
|
||||
|
||||
const derivedFingerprint = hasFingerprint && !migrateCertificate
|
||||
? knownHost.fingerprint!
|
||||
: fingerprintFromPublicKey(knownHost.publicKey);
|
||||
const derivedKeyType = hasKeyType
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
isPaneMagnificationSelectionValid,
|
||||
resolvePaneMagnificationCandidate,
|
||||
resolvePaneMagnificationStyle,
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolveTwoPaneMagnificationStyle,
|
||||
snapCssRectToDevicePixels,
|
||||
type PaneMagnificationController,
|
||||
} from './paneMagnification.ts';
|
||||
|
||||
@@ -90,6 +92,53 @@ test('magnification overlays the original layout without changing its rect', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
|
||||
});
|
||||
|
||||
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
|
||||
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
|
||||
// Integer CSS pixels at 1x stay unchanged (existing contract).
|
||||
assert.deepEqual(resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120,
|
||||
top: 80,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 1), {
|
||||
position: 'fixed',
|
||||
left: '132px',
|
||||
top: '92px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
// 120.4+12=132.4 at 2x -> 264.8 rounds to 265 -> 132.5
|
||||
// right: 120.4+1400-12=1508.4 at 2x -> 3016.8 rounds to 3017 -> 1508.5
|
||||
const snapped = resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120.4,
|
||||
top: 80.4,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 2);
|
||||
assert.deepEqual(snapped, {
|
||||
position: 'fixed',
|
||||
left: '132.5px',
|
||||
top: '92.5px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
const rect = snapCssRectToDevicePixels(10.2, 20.2, 110.2, 80.2, 2);
|
||||
assert.deepEqual(rect, { left: 10, top: 20, width: 100, height: 60 });
|
||||
});
|
||||
|
||||
test('two-pane magnification keeps the dormant pane geometry unchanged', () => {
|
||||
assert.deepEqual(resolveTwoPaneMagnificationStyle('left', true, true), {
|
||||
left: '12px', top: '12px', width: 'calc(100% - 24px)', height: 'calc(100% - 24px)', zIndex: 50,
|
||||
|
||||
@@ -92,19 +92,52 @@ export function getPaneMagnificationShortcutLabel(
|
||||
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
|
||||
}
|
||||
|
||||
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
|
||||
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
|
||||
}
|
||||
|
||||
export function snapCssRectToDevicePixels(
|
||||
left: number,
|
||||
top: number,
|
||||
right: number,
|
||||
bottom: number,
|
||||
devicePixelRatio = 1,
|
||||
): { left: number; top: number; width: number; height: number } {
|
||||
const dpr = devicePixelRatio > 0 ? devicePixelRatio : 1;
|
||||
const snap = (value: number) => Math.round(value * dpr) / dpr;
|
||||
const snappedLeft = snap(left);
|
||||
const snappedTop = snap(top);
|
||||
const snappedRight = snap(right);
|
||||
const snappedBottom = snap(bottom);
|
||||
return {
|
||||
left: snappedLeft,
|
||||
top: snappedTop,
|
||||
width: Math.max(0, snappedRight - snappedLeft),
|
||||
height: Math.max(0, snappedBottom - snappedTop),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePaneMagnificationStyle(
|
||||
original: React.CSSProperties,
|
||||
magnified: boolean,
|
||||
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
|
||||
devicePixelRatio = 1,
|
||||
): React.CSSProperties {
|
||||
if (!magnified) return original;
|
||||
if (surfaceBounds) {
|
||||
const snapped = snapCssRectToDevicePixels(
|
||||
surfaceBounds.left + 12,
|
||||
surfaceBounds.top + 12,
|
||||
surfaceBounds.left + surfaceBounds.width - 12,
|
||||
surfaceBounds.top + surfaceBounds.height - 12,
|
||||
devicePixelRatio,
|
||||
);
|
||||
return {
|
||||
position: 'fixed',
|
||||
left: `${surfaceBounds.left + 12}px`,
|
||||
top: `${surfaceBounds.top + 12}px`,
|
||||
width: `${Math.max(0, surfaceBounds.width - 24)}px`,
|
||||
height: `${Math.max(0, surfaceBounds.height - 24)}px`,
|
||||
left: `${snapped.left}px`,
|
||||
top: `${snapped.top}px`,
|
||||
width: `${snapped.width}px`,
|
||||
height: `${snapped.height}px`,
|
||||
zIndex: 50,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,6 +64,41 @@ test("settings search catalog has unique ids", () => {
|
||||
assert.equal(new Set(ids).size, ids.length);
|
||||
});
|
||||
|
||||
test("newly indexed gated settings retain visible parent destinations in search", () => {
|
||||
const fallbacks = {
|
||||
"terminal-hibernate-hidden-tabs-delay": "terminal-hibernate-hidden-tabs",
|
||||
"terminal-hibernate-skip-alt-screen": "terminal-hibernate-hidden-tabs",
|
||||
"terminal-hibernate-keep-renderer-count": "terminal-hibernate-hidden-tabs",
|
||||
"terminal-hibernate-replay-chunk-bytes": "terminal-hibernate-hidden-tabs",
|
||||
"terminal-hibernate-prefer-wasm-serialize": "terminal-hibernate-hidden-tabs",
|
||||
"terminal-inline-images-kitty": "terminal-inline-images-enabled",
|
||||
"terminal-inline-images-sixel": "terminal-inline-images-enabled",
|
||||
"terminal-inline-images-iip": "terminal-inline-images-enabled",
|
||||
"terminal-inline-images-storage-limit": "terminal-inline-images-enabled",
|
||||
"terminal-inline-images-max-megapixels": "terminal-inline-images-enabled",
|
||||
"terminal-inline-images-sequence-limit": "terminal-inline-images-enabled",
|
||||
"terminal-host-info-bar-title-mode": "terminal-host-info-bar-show",
|
||||
"terminal-server-stats-refresh-interval": "terminal-server-stats-show",
|
||||
"ai-web-search-api-key": "ai-web-search-provider",
|
||||
"system-network-proxy-url": "system-network-proxy-mode",
|
||||
"system-network-proxy-bypass": "system-network-proxy-mode",
|
||||
"system-app-lock-timeout": "system-app-lock",
|
||||
};
|
||||
const hits = filterSettingsSearchCatalog("", (key) => en[key] ?? key, { limit: 500 });
|
||||
for (const [id, fallbackId] of Object.entries(fallbacks)) {
|
||||
const entry = hits.find((hit) => hit.entry.id === id)?.entry;
|
||||
assert.ok(entry, id);
|
||||
assert.equal(entry.fallbackAnchorId, fallbackId, id);
|
||||
const parent = SETTINGS_SEARCH_CATALOG.find((candidate) => candidate.id === fallbackId);
|
||||
assert.ok(parent, fallbackId);
|
||||
assert.equal(parent.tab, entry.tab, id);
|
||||
assert.equal(parent.aiSubTab, entry.aiSubTab, id);
|
||||
assert.equal(parent.fallbackAnchorId, undefined, fallbackId);
|
||||
}
|
||||
// The local start-directory row is always mounted in this UI.
|
||||
assert.equal(hits.find((hit) => hit.entry.id === "terminal-local-shell-start-dir")?.entry.fallbackAnchorId, undefined);
|
||||
});
|
||||
|
||||
test("filterSettingsSearchCatalog matches English labels", () => {
|
||||
const hits = filterSettingsSearchCatalog("copy on select", tEn);
|
||||
assert.ok(hits.some((hit) => hit.entry.id === "terminal-copy-on-select"));
|
||||
@@ -125,6 +160,107 @@ test("settings search finds App Lock from the zh-CN locale", () => {
|
||||
assert.ok(hits.some((hit) => hit.entry.id === "system-app-lock"));
|
||||
});
|
||||
|
||||
test("settings search finds folder compression from the real locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [t, queries] of [
|
||||
[tZhReal, ["压缩", "普通传输"]],
|
||||
[tEnReal, ["compress", "tar"]],
|
||||
] as const) {
|
||||
for (const query of queries) {
|
||||
const hits = filterSettingsSearchCatalog(query, t);
|
||||
assert.ok(hits.some((hit) => hit.entry.id === "sftp-compressed-upload"), query);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds skip unchanged files from the real locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [t, queries] of [
|
||||
[tZhReal, ["跳过未改文件", "修改时间"]],
|
||||
[tEnReal, ["skip unchanged", "rsync"]],
|
||||
] as const) {
|
||||
for (const query of queries) {
|
||||
const hits = filterSettingsSearchCatalog(query, t);
|
||||
assert.ok(hits.some((hit) => hit.entry.id === "sftp-skip-unchanged"), query);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds SSH connection keep-alive from the real locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [t, queries] of [
|
||||
[tZhReal, ["保活时间", "重新认证"]],
|
||||
[tEnReal, ["keep-alive", "re-authentication"]],
|
||||
] as const) {
|
||||
for (const query of queries) {
|
||||
const hits = filterSettingsSearchCatalog(query, t);
|
||||
assert.ok(hits.some((hit) => hit.entry.id === "sftp-transport-idle-ttl"), query);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds note typography from the real locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [id, zhQuery, enQuery] of [
|
||||
["appearance-vault-notes-font", "代码字体", "code font"],
|
||||
["appearance-vault-notes-font-size", "笔记字号", "note font size"],
|
||||
["appearance-vault-notes-code-font-size", "代码字号", "code font size"],
|
||||
] as const) {
|
||||
for (const [t, query] of [[tZhReal, zhQuery], [tEnReal, enQuery]] as const) {
|
||||
const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === id);
|
||||
assert.ok(hit, `${query} should find ${id}`);
|
||||
assert.equal(hit.entry.tab, "appearance");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds session log options from the real locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [id, t, queries] of [
|
||||
["system-session-logs-directory", tZhReal, ["保存目录"]],
|
||||
["system-session-logs-directory", tEnReal, ["save directory"]],
|
||||
["system-session-logs-format", tZhReal, ["日志格式"]],
|
||||
["system-session-logs-format", tEnReal, ["log format"]],
|
||||
["system-session-logs-timestamps", tZhReal, ["时间戳"]],
|
||||
["system-session-logs-timestamps", tEnReal, ["timestamp", "Add timestamps"]],
|
||||
] as const) {
|
||||
for (const query of queries) {
|
||||
const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === id);
|
||||
assert.ok(hit, `${query} should find ${id}`);
|
||||
assert.equal(hit.entry.tab, "system");
|
||||
assert.equal(hit.entry.sectionKey, "settings.sessionLogs.title");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("later-added settings retain their tab and sub-tab destinations", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [id, tab, subTab, labelKey] of [
|
||||
["terminal-font-ligatures", "terminal", undefined, "settings.terminal.font.ligatures"],
|
||||
["terminal-local-shell-side-panel-auto-open", "terminal", undefined, "settings.terminal.localShellSidePanel.autoOpen"],
|
||||
["terminal-system-manager-process-refresh-interval", "terminal", undefined, "settings.terminal.systemManager.processRefreshInterval"],
|
||||
["ai-chat-history-message-cap", "ai", "tools", "ai.chatHistory.messageCap"],
|
||||
["ai-web-search-max-results", "ai", "search", "ai.webSearch.maxResults"],
|
||||
["ai-safety-max-iterations", "ai", "safety", "ai.safety.maxIterations"],
|
||||
["sync-ai-sessions", "sync", "status", "cloudSync.aiSessions.title"],
|
||||
["system-network-proxy-url", "system", undefined, "settings.system.networkProxy.url"],
|
||||
] as const) {
|
||||
for (const t of [tZhReal, tEnReal]) {
|
||||
assert.notEqual(t(labelKey), labelKey);
|
||||
const hit = filterSettingsSearchCatalog(t(labelKey), t).find((hit) => hit.entry.id === id);
|
||||
assert.ok(hit, `${t(labelKey)} should find ${id}`);
|
||||
assert.equal(hit.entry.tab, tab);
|
||||
assert.equal(hit.entry.aiSubTab ?? hit.entry.syncSubTab, subTab);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds temporary network device mode", () => {
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
const tZhTW = (key: string) => zhTW[key] ?? key;
|
||||
|
||||
@@ -24,7 +24,7 @@ function collectSourceFiles(root: string): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
test("every settings search catalog id is wired as an anchor in components", () => {
|
||||
test("every settings search catalog id and fallback is wired as an anchor in components", () => {
|
||||
const roots = [
|
||||
join(process.cwd(), "components"),
|
||||
];
|
||||
@@ -32,7 +32,7 @@ test("every settings search catalog id is wired as an anchor in components", ()
|
||||
const haystack = sources.map((file) => readFileSync(file, "utf8")).join("\n");
|
||||
|
||||
const missing = SETTINGS_SEARCH_CATALOG
|
||||
.map((entry) => entry.id)
|
||||
.flatMap((entry) => [entry.id, ...(entry.fallbackAnchorId ? [entry.fallbackAnchorId] : [])])
|
||||
.filter((id) => {
|
||||
const asProp = `anchorId="${id}"`;
|
||||
const asPropSingle = `anchorId='${id}'`;
|
||||
|
||||
@@ -36,6 +36,11 @@ export type SettingsPlatform = "mac" | "win" | "linux";
|
||||
export type SettingsSearchEntry = {
|
||||
/** Stable id; also used as `data-settings-anchor` on the target element. */
|
||||
id: string;
|
||||
/**
|
||||
* Already-mounted parent to highlight when a prerequisite setting is off and
|
||||
* this entry's own anchor is not in the DOM.
|
||||
*/
|
||||
fallbackAnchorId?: string;
|
||||
tab: SettingsTabId;
|
||||
/** Nested AI settings tab when `tab === "ai"`. */
|
||||
aiSubTab?: AISettingsSubTabId;
|
||||
@@ -214,6 +219,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.vault.autoImportSystemKnownHostsDesc",
|
||||
sectionKey: "settings.vault.title",
|
||||
},
|
||||
{
|
||||
id: "appearance-vault-notes-font",
|
||||
tab: "appearance",
|
||||
labelKey: "settings.vault.notesFont",
|
||||
descriptionKey: "settings.vault.notesFontDesc",
|
||||
sectionKey: "settings.vault.title",
|
||||
},
|
||||
{
|
||||
id: "appearance-vault-notes-font-size",
|
||||
tab: "appearance",
|
||||
labelKey: "settings.vault.notesFontSize",
|
||||
descriptionKey: "settings.vault.notesFontSizeDesc",
|
||||
sectionKey: "settings.vault.title",
|
||||
},
|
||||
{
|
||||
id: "appearance-vault-notes-code-font-size",
|
||||
tab: "appearance",
|
||||
labelKey: "settings.vault.notesCodeFontSize",
|
||||
descriptionKey: "settings.vault.notesCodeFontSizeDesc",
|
||||
sectionKey: "settings.vault.title",
|
||||
},
|
||||
{
|
||||
id: "appearance-custom-css",
|
||||
tab: "appearance",
|
||||
@@ -273,6 +299,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.font.smoothing.desc",
|
||||
sectionKey: "settings.terminal.section.font",
|
||||
},
|
||||
{
|
||||
id: "terminal-font-ligatures",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.font.ligatures",
|
||||
descriptionKey: "settings.terminal.font.ligatures.desc",
|
||||
sectionKey: "settings.terminal.section.font",
|
||||
},
|
||||
{
|
||||
id: "terminal-font-line-padding",
|
||||
tab: "terminal",
|
||||
@@ -366,6 +399,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.behavior.rightClick.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-right-click-long-press-menu",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.rightClick.longPressMenu",
|
||||
descriptionKey: "settings.terminal.behavior.rightClick.longPressMenu.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-right-click-fullscreen-menu",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.rightClick.fullscreenMenu",
|
||||
descriptionKey: "settings.terminal.behavior.rightClick.fullscreenMenu.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-copy-on-select",
|
||||
tab: "terminal",
|
||||
@@ -415,6 +462,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.behavior.confirmMultilinePaste.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-confirm-multiline-paste-min-lines",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.confirmMultilinePasteMinLines",
|
||||
descriptionKey: "settings.terminal.behavior.confirmMultilinePasteMinLines.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-shift-enter-newline",
|
||||
tab: "terminal",
|
||||
@@ -422,6 +476,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.behavior.shiftEnterNewline.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-shift-enter-newline-text",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.shiftEnterNewlineText",
|
||||
descriptionKey: "settings.terminal.behavior.shiftEnterNewlineText.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-shift-enter-force-text",
|
||||
tab: "terminal",
|
||||
@@ -443,6 +504,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.behavior.clearWipesScrollback.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-preserve-selection-on-input",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.preserveSelectionOnInput",
|
||||
descriptionKey: "settings.terminal.behavior.preserveSelectionOnInput.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-force-prompt-new-line",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.forcePromptNewLine",
|
||||
descriptionKey: "settings.terminal.behavior.forcePromptNewLine.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-tab-double-click",
|
||||
tab: "terminal",
|
||||
@@ -472,6 +547,55 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.behavior.osc52Clipboard.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-scroll-on-input",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.scrollOnInput",
|
||||
descriptionKey: "settings.terminal.behavior.scrollOnInput.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-scroll-on-output",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.scrollOnOutput",
|
||||
descriptionKey: "settings.terminal.behavior.scrollOnOutput.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-scroll-on-key-press",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.scrollOnKeyPress",
|
||||
descriptionKey: "settings.terminal.behavior.scrollOnKeyPress.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-scroll-on-paste",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.scrollOnPaste",
|
||||
descriptionKey: "settings.terminal.behavior.scrollOnPaste.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-smooth-scrolling",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.smoothScrolling",
|
||||
descriptionKey: "settings.terminal.behavior.smoothScrolling.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-link-browser",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.linkBrowser",
|
||||
descriptionKey: "settings.terminal.behavior.linkBrowser.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-link-modifier",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.behavior.linkModifier",
|
||||
descriptionKey: "settings.terminal.behavior.linkModifier.desc",
|
||||
sectionKey: "settings.terminal.section.behavior",
|
||||
},
|
||||
{
|
||||
id: "terminal-scrollback-rows",
|
||||
tab: "terminal",
|
||||
@@ -493,6 +617,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.sidePanel.autoOpen.desc",
|
||||
sectionKey: "settings.terminal.section.sidePanel",
|
||||
},
|
||||
{
|
||||
id: "terminal-side-panel-auto-open-pane",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.sidePanel.autoOpenPane",
|
||||
descriptionKey: "settings.terminal.sidePanel.autoOpenPane.desc",
|
||||
sectionKey: "settings.terminal.section.sidePanel",
|
||||
},
|
||||
{
|
||||
id: "terminal-local-shell-side-panel-auto-open",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.localShellSidePanel.autoOpen",
|
||||
descriptionKey: "settings.terminal.localShellSidePanel.autoOpen.desc",
|
||||
sectionKey: "settings.terminal.section.localShellSidePanel",
|
||||
},
|
||||
{
|
||||
id: "terminal-local-shell-side-panel-auto-open-pane",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.localShellSidePanel.autoOpenPane",
|
||||
descriptionKey: "settings.terminal.localShellSidePanel.autoOpenPane.desc",
|
||||
sectionKey: "settings.terminal.section.localShellSidePanel",
|
||||
},
|
||||
{
|
||||
id: "terminal-keyword-highlight",
|
||||
tab: "terminal",
|
||||
@@ -507,6 +652,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.localShell.shell.desc",
|
||||
sectionKey: "settings.terminal.section.localShell",
|
||||
},
|
||||
{
|
||||
id: "terminal-local-shell-start-dir",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.localShell.startDir",
|
||||
descriptionKey: "settings.terminal.localShell.startDir.desc",
|
||||
sectionKey: "settings.terminal.section.localShell",
|
||||
},
|
||||
{
|
||||
id: "terminal-default-proxy",
|
||||
tab: "terminal",
|
||||
@@ -552,6 +704,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.connection.keepaliveInterval.desc",
|
||||
sectionKey: "settings.terminal.section.connection",
|
||||
},
|
||||
{
|
||||
id: "terminal-keepalive-count-max",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.connection.keepaliveCountMax",
|
||||
descriptionKey: "settings.terminal.connection.keepaliveCountMax.desc",
|
||||
sectionKey: "settings.terminal.section.connection",
|
||||
},
|
||||
{
|
||||
id: "terminal-x11-display",
|
||||
tab: "terminal",
|
||||
@@ -560,6 +719,21 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "settings.terminal.section.connection",
|
||||
keywords: ["x11", "display"],
|
||||
},
|
||||
{
|
||||
id: "terminal-host-info-bar-show",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.hostInfoBar.show",
|
||||
descriptionKey: "settings.terminal.hostInfoBar.show.desc",
|
||||
sectionKey: "settings.terminal.section.serverStats",
|
||||
},
|
||||
{
|
||||
id: "terminal-host-info-bar-title-mode",
|
||||
fallbackAnchorId: "terminal-host-info-bar-show",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.hostInfoBar.titleMode",
|
||||
descriptionKey: "settings.terminal.hostInfoBar.titleMode.desc",
|
||||
sectionKey: "settings.terminal.section.serverStats",
|
||||
},
|
||||
{
|
||||
id: "terminal-server-stats-show",
|
||||
tab: "terminal",
|
||||
@@ -567,6 +741,42 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.serverStats.show.desc",
|
||||
sectionKey: "settings.terminal.section.serverStats",
|
||||
},
|
||||
{
|
||||
id: "terminal-server-stats-refresh-interval",
|
||||
fallbackAnchorId: "terminal-server-stats-show",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.serverStats.refreshInterval",
|
||||
descriptionKey: "settings.terminal.serverStats.refreshInterval.desc",
|
||||
sectionKey: "settings.terminal.section.serverStats",
|
||||
},
|
||||
{
|
||||
id: "terminal-system-manager-process-refresh-interval",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.systemManager.processRefreshInterval",
|
||||
descriptionKey: "settings.terminal.systemManager.processRefreshInterval.desc",
|
||||
sectionKey: "settings.terminal.section.systemManager",
|
||||
},
|
||||
{
|
||||
id: "terminal-system-manager-tmux-refresh-interval",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.systemManager.tmuxRefreshInterval",
|
||||
descriptionKey: "settings.terminal.systemManager.tmuxRefreshInterval.desc",
|
||||
sectionKey: "settings.terminal.section.systemManager",
|
||||
},
|
||||
{
|
||||
id: "terminal-system-manager-docker-list-refresh-interval",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.systemManager.dockerListRefreshInterval",
|
||||
descriptionKey: "settings.terminal.systemManager.dockerListRefreshInterval.desc",
|
||||
sectionKey: "settings.terminal.section.systemManager",
|
||||
},
|
||||
{
|
||||
id: "terminal-system-manager-docker-stats-refresh-interval",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.systemManager.dockerStatsRefreshInterval",
|
||||
descriptionKey: "settings.terminal.systemManager.dockerStatsRefreshInterval.desc",
|
||||
sectionKey: "settings.terminal.section.systemManager",
|
||||
},
|
||||
{
|
||||
id: "terminal-renderer",
|
||||
tab: "terminal",
|
||||
@@ -575,6 +785,53 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
keywords: ["webgl", "canvas"],
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernateHiddenTabs",
|
||||
descriptionKey: "settings.terminal.rendering.hibernateHiddenTabs.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-hidden-tabs-delay",
|
||||
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernateHiddenTabsDelay",
|
||||
descriptionKey: "settings.terminal.rendering.hibernateHiddenTabsDelay.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-skip-alt-screen",
|
||||
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernateSkipAltScreen",
|
||||
descriptionKey: "settings.terminal.rendering.hibernateSkipAltScreen.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-keep-renderer-count",
|
||||
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernateKeepRendererCount",
|
||||
descriptionKey: "settings.terminal.rendering.hibernateKeepRendererCount.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-replay-chunk-bytes",
|
||||
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernateReplayChunkBytes",
|
||||
descriptionKey: "settings.terminal.rendering.hibernateReplayChunkBytes.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-hibernate-prefer-wasm-serialize",
|
||||
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.rendering.hibernatePreferWasmSerialize",
|
||||
descriptionKey: "settings.terminal.rendering.hibernatePreferWasmSerialize.desc",
|
||||
sectionKey: "settings.terminal.section.rendering",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
@@ -583,6 +840,54 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
keywords: ["sixel", "kitty", "iip"],
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-kitty",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.kitty",
|
||||
descriptionKey: "settings.terminal.inlineImages.kitty.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-sixel",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.sixel",
|
||||
descriptionKey: "settings.terminal.inlineImages.sixel.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-iip",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.iip",
|
||||
descriptionKey: "settings.terminal.inlineImages.iip.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-storage-limit",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.storageLimit",
|
||||
descriptionKey: "settings.terminal.inlineImages.storageLimit.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-max-megapixels",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.maxMegapixels",
|
||||
descriptionKey: "settings.terminal.inlineImages.maxMegapixels.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-inline-images-sequence-limit",
|
||||
fallbackAnchorId: "terminal-inline-images-enabled",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.inlineImages.sequenceLimit",
|
||||
descriptionKey: "settings.terminal.inlineImages.sequenceLimit.desc",
|
||||
sectionKey: "settings.terminal.section.inlineImages",
|
||||
},
|
||||
{
|
||||
id: "terminal-workspace-focus-style",
|
||||
tab: "terminal",
|
||||
@@ -598,6 +903,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
keywords: ["completion", "补全"],
|
||||
},
|
||||
{
|
||||
id: "terminal-autocomplete-ghost-text",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.autocomplete.ghostText",
|
||||
descriptionKey: "settings.terminal.autocomplete.ghostText.desc",
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
},
|
||||
{
|
||||
id: "terminal-autocomplete-popup-menu",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.autocomplete.popupMenu",
|
||||
descriptionKey: "settings.terminal.autocomplete.popupMenu.desc",
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
},
|
||||
{
|
||||
id: "terminal-autocomplete-history-scope",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.autocomplete.historyScope",
|
||||
descriptionKey: "settings.terminal.autocomplete.historyScope.desc",
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
},
|
||||
{
|
||||
id: "terminal-password-prompt-assist",
|
||||
tab: "terminal",
|
||||
@@ -671,6 +997,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.sftp.autoSync.enableDesc",
|
||||
sectionKey: "settings.sftp.autoSync",
|
||||
},
|
||||
{
|
||||
id: "sftp-compressed-upload",
|
||||
tab: "file-associations",
|
||||
labelKey: "settings.sftp.compressedUpload.enable",
|
||||
descriptionKey: "settings.sftp.compressedUpload.enableDesc",
|
||||
sectionKey: "settings.sftp.compressedUpload",
|
||||
},
|
||||
{
|
||||
id: "sftp-follow-terminal-cwd",
|
||||
tab: "file-associations",
|
||||
@@ -691,6 +1024,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
labelKey: "settings.sftp.transferConcurrency",
|
||||
descriptionKey: "settings.sftp.transferConcurrency.desc",
|
||||
},
|
||||
{
|
||||
id: "sftp-skip-unchanged",
|
||||
tab: "file-associations",
|
||||
labelKey: "settings.sftp.skipUnchanged.enable",
|
||||
descriptionKey: "settings.sftp.skipUnchanged.enableDesc",
|
||||
sectionKey: "settings.sftp.transferConcurrency",
|
||||
},
|
||||
{
|
||||
id: "sftp-transport-idle-ttl",
|
||||
tab: "file-associations",
|
||||
labelKey: "settings.ssh.transportIdleTtl",
|
||||
descriptionKey: "settings.ssh.transportIdleTtl.desc",
|
||||
sectionKey: "settings.sftp.transferConcurrency",
|
||||
},
|
||||
{
|
||||
id: "sftp-default-opener",
|
||||
tab: "file-associations",
|
||||
@@ -758,6 +1105,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
labelKey: "ai.defaultAgent",
|
||||
descriptionKey: "ai.defaultAgent.description",
|
||||
},
|
||||
{
|
||||
id: "ai-privacy",
|
||||
tab: "ai",
|
||||
aiSubTab: "tools",
|
||||
labelKey: "ai.privacy.title",
|
||||
descriptionKey: "ai.privacy.description",
|
||||
},
|
||||
{
|
||||
id: "ai-chat-shortcuts-selection",
|
||||
tab: "ai",
|
||||
@@ -798,6 +1152,29 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "ai.externalMcp.title",
|
||||
keywords: ["notification", "approval", "dock"],
|
||||
},
|
||||
{
|
||||
id: "ai-chat-history-message-cap",
|
||||
tab: "ai",
|
||||
aiSubTab: "tools",
|
||||
labelKey: "ai.chatHistory.messageCap",
|
||||
descriptionKey: "ai.chatHistory.messageCap.description",
|
||||
sectionKey: "ai.chatHistory.title",
|
||||
},
|
||||
{
|
||||
id: "ai-external-mcp-behavior",
|
||||
tab: "ai",
|
||||
aiSubTab: "tools",
|
||||
labelKey: "ai.toolSettings.behavior",
|
||||
sectionKey: "ai.externalMcp.title",
|
||||
},
|
||||
{
|
||||
id: "ai-external-mcp-client-configuration",
|
||||
tab: "ai",
|
||||
aiSubTab: "tools",
|
||||
labelKey: "ai.externalMcp.clientConfiguration",
|
||||
descriptionKey: "ai.externalMcp.clientConfiguration.description",
|
||||
sectionKey: "ai.externalMcp.title",
|
||||
},
|
||||
{
|
||||
id: "ai-user-skills",
|
||||
tab: "ai",
|
||||
@@ -829,6 +1206,31 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "ai.webSearch.provider.description",
|
||||
sectionKey: "ai.webSearch.title",
|
||||
},
|
||||
{
|
||||
id: "ai-web-search-api-key",
|
||||
fallbackAnchorId: "ai-web-search-provider",
|
||||
tab: "ai",
|
||||
aiSubTab: "search",
|
||||
labelKey: "ai.webSearch.apiKey",
|
||||
descriptionKey: "ai.webSearch.apiKey.description",
|
||||
sectionKey: "ai.webSearch.title",
|
||||
},
|
||||
{
|
||||
id: "ai-web-search-api-host",
|
||||
tab: "ai",
|
||||
aiSubTab: "search",
|
||||
labelKey: "ai.webSearch.apiHost",
|
||||
descriptionKey: "ai.webSearch.apiHost.description",
|
||||
sectionKey: "ai.webSearch.title",
|
||||
},
|
||||
{
|
||||
id: "ai-web-search-max-results",
|
||||
tab: "ai",
|
||||
aiSubTab: "search",
|
||||
labelKey: "ai.webSearch.maxResults",
|
||||
descriptionKey: "ai.webSearch.maxResults.description",
|
||||
sectionKey: "ai.webSearch.title",
|
||||
},
|
||||
{
|
||||
id: "ai-safety-permission-mode",
|
||||
tab: "ai",
|
||||
@@ -855,6 +1257,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "ai.safety.title",
|
||||
keywords: ["response", "request", "idle", "timeout", "响应", "请求", "超时"],
|
||||
},
|
||||
{
|
||||
id: "ai-safety-max-iterations",
|
||||
tab: "ai",
|
||||
aiSubTab: "safety",
|
||||
labelKey: "ai.safety.maxIterations",
|
||||
descriptionKey: "ai.safety.maxIterations.description",
|
||||
sectionKey: "ai.safety.title",
|
||||
},
|
||||
{
|
||||
id: "ai-safety-blocklist",
|
||||
tab: "ai",
|
||||
@@ -894,6 +1304,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
labelKey: "cloudSync.strategy.title",
|
||||
descriptionKey: "cloudSync.strategy.desc",
|
||||
},
|
||||
{
|
||||
id: "sync-ai-sessions",
|
||||
tab: "sync",
|
||||
syncSubTab: "status",
|
||||
labelKey: "cloudSync.aiSessions.title",
|
||||
descriptionKey: "cloudSync.aiSessions.desc",
|
||||
},
|
||||
{
|
||||
id: "sync-local-backups",
|
||||
tab: "sync",
|
||||
@@ -941,6 +1358,22 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
sectionKey: "settings.system.networkProxy.title",
|
||||
keywords: ["proxy", "http", "代理"],
|
||||
},
|
||||
{
|
||||
id: "system-network-proxy-url",
|
||||
fallbackAnchorId: "system-network-proxy-mode",
|
||||
tab: "system",
|
||||
labelKey: "settings.system.networkProxy.url",
|
||||
descriptionKey: "settings.system.networkProxy.url.desc",
|
||||
sectionKey: "settings.system.networkProxy.title",
|
||||
},
|
||||
{
|
||||
id: "system-network-proxy-bypass",
|
||||
fallbackAnchorId: "system-network-proxy-mode",
|
||||
tab: "system",
|
||||
labelKey: "settings.system.networkProxy.bypass",
|
||||
descriptionKey: "settings.system.networkProxy.bypass.desc",
|
||||
sectionKey: "settings.system.networkProxy.title",
|
||||
},
|
||||
{
|
||||
id: "system-app-lock",
|
||||
tab: "system",
|
||||
@@ -948,6 +1381,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.appLock.description",
|
||||
keywords: ["app lock", "applock", "lock", "应用锁", "锁屏", "idle", "timeout", "无操作"],
|
||||
},
|
||||
{
|
||||
id: "system-app-lock-timeout",
|
||||
fallbackAnchorId: "system-app-lock",
|
||||
tab: "system",
|
||||
labelKey: "settings.appLock.timeout",
|
||||
descriptionKey: "settings.appLock.timeoutDesc",
|
||||
sectionKey: "settings.appLock.title",
|
||||
},
|
||||
{
|
||||
id: "system-credentials",
|
||||
tab: "system",
|
||||
@@ -996,6 +1437,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.sessionLogs.enableAutoSaveDesc",
|
||||
sectionKey: "settings.sessionLogs.title",
|
||||
},
|
||||
{
|
||||
id: "system-session-logs-directory",
|
||||
tab: "system",
|
||||
labelKey: "settings.sessionLogs.directory",
|
||||
descriptionKey: "settings.sessionLogs.directoryHint",
|
||||
sectionKey: "settings.sessionLogs.title",
|
||||
},
|
||||
{
|
||||
id: "system-session-logs-format",
|
||||
tab: "system",
|
||||
labelKey: "settings.sessionLogs.format",
|
||||
descriptionKey: "settings.sessionLogs.formatDesc",
|
||||
sectionKey: "settings.sessionLogs.title",
|
||||
},
|
||||
{
|
||||
id: "system-session-logs-timestamps",
|
||||
tab: "system",
|
||||
labelKey: "settings.sessionLogs.timestamps",
|
||||
descriptionKey: "settings.sessionLogs.timestampsDesc",
|
||||
sectionKey: "settings.sessionLogs.title",
|
||||
},
|
||||
{
|
||||
id: "system-ssh-deep-link",
|
||||
tab: "system",
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"use strict";
|
||||
|
||||
// Extract only the public-key wire blob for fingerprinting, never CA trust or
|
||||
// certificate validation. ssh2's getPublicSSH() preserves the full certificate,
|
||||
// and its internal base-type helper is not exported. Keep this byte-only helper
|
||||
// shared by Electron and the renderer so migration uses exactly the same bytes.
|
||||
// Layouts: OpenSSH PROTOCOL.certkeys (v00/v01) and PROTOCOL.u2f (SK).
|
||||
function extractCertificatePublicKey(blob) {
|
||||
let offset = 0;
|
||||
const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
|
||||
const skip = (length) => {
|
||||
if (offset + length > blob.length) throw new Error("Truncated SSH key");
|
||||
offset += length;
|
||||
};
|
||||
const readString = () => {
|
||||
skip(4);
|
||||
const length = view.getUint32(offset - 4, false);
|
||||
const start = offset;
|
||||
skip(length);
|
||||
return blob.subarray(start, offset);
|
||||
};
|
||||
const ascii = (bytes) => String.fromCharCode(...bytes);
|
||||
|
||||
try {
|
||||
const typeBytes = readString();
|
||||
if (typeBytes.length > 128) return null;
|
||||
const match = ascii(typeBytes).match(/^(.*)-cert-v0([01])@openssh\.com$/);
|
||||
if (!match) return null;
|
||||
let baseType = match[1];
|
||||
const v01 = match[2] === "1";
|
||||
if (/^rsa-sha2-(256|512)$/.test(baseType)) baseType = "ssh-rsa";
|
||||
if (baseType === "sk-ssh-ed25519" || baseType === "sk-ecdsa-sha2-nistp256") {
|
||||
baseType += "@openssh.com";
|
||||
}
|
||||
let fields;
|
||||
switch (baseType) {
|
||||
case "ssh-rsa": fields = 2; break;
|
||||
case "ssh-dss": fields = 4; break;
|
||||
case "ssh-ed25519": fields = 1; break;
|
||||
case "sk-ssh-ed25519@openssh.com": fields = 2; break;
|
||||
case "sk-ecdsa-sha2-nistp256@openssh.com": fields = 3; break;
|
||||
case "ecdsa-sha2-nistp256":
|
||||
case "ecdsa-sha2-nistp384":
|
||||
case "ecdsa-sha2-nistp521": fields = 2; break;
|
||||
default: return null;
|
||||
}
|
||||
|
||||
// v00 put its nonce after the constraints, not before the key material.
|
||||
if (v01) readString();
|
||||
const keyStart = offset;
|
||||
for (let i = 0; i < fields; i += 1) {
|
||||
const field = readString();
|
||||
const isApplication = baseType.startsWith("sk-") && i === fields - 1;
|
||||
if (!field.length && !isApplication) return null;
|
||||
if (i === 0 && baseType.includes("ed25519") && field.length !== 32) return null;
|
||||
if (i === 0 && baseType.includes("ecdsa")) {
|
||||
const curve = baseType.replace(/^sk-/, "").replace(/@openssh\.com$/, "").replace(/^ecdsa-sha2-/, "");
|
||||
if (field.length > 8 || ascii(field) !== curve) return null;
|
||||
}
|
||||
}
|
||||
const keyEnd = offset;
|
||||
// Check the outer envelope too; truncated/unsupported certificates retain
|
||||
// their full-blob fingerprint rather than gaining an inner-key match.
|
||||
if (v01) skip(8); // serial
|
||||
skip(4); // host/user type
|
||||
readString(); // key ID
|
||||
readString(); // principals
|
||||
skip(16); // validity
|
||||
readString(); // critical options (v00 constraints)
|
||||
readString(); // extensions (v00 nonce)
|
||||
readString(); // reserved
|
||||
if (!readString().length || !readString().length || offset !== blob.length) return null;
|
||||
|
||||
const result = new Uint8Array(4 + baseType.length + keyEnd - keyStart);
|
||||
new DataView(result.buffer).setUint32(0, baseType.length, false);
|
||||
for (let i = 0; i < baseType.length; i += 1) result[4 + i] = baseType.charCodeAt(i);
|
||||
result.set(blob.subarray(keyStart, keyEnd), 4 + baseType.length);
|
||||
return result;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
exports.extractCertificatePublicKey = extractCertificatePublicKey;
|
||||
@@ -84,6 +84,7 @@ module.exports = {
|
||||
// is excluded below, so the shared TOTP runtime must be listed.
|
||||
'domain/totp.shared.cjs',
|
||||
'domain/totpPrompt.shared.cjs',
|
||||
'domain/sshPublicKey.shared.cjs',
|
||||
'lib/**/*.cjs',
|
||||
'lib/**/*.json',
|
||||
'skills/**/*',
|
||||
|
||||
@@ -27,6 +27,7 @@ const {
|
||||
stripAnsi,
|
||||
} = require("./ptyExecHelpers.cjs");
|
||||
const { extractTrailingIdlePrompt } = require("./shellUtils.cjs");
|
||||
const { READINESS_UNKNOWN, SHELL_READINESS_UNKNOWN_MESSAGE } = require("./shellReadinessState.cjs");
|
||||
const { getSessionSnapshot } = require("../terminalInterruptDiagnostics.cjs");
|
||||
const { createJobStartupDiag } = require("./jobStartupDiagnostics.cjs");
|
||||
|
||||
@@ -70,6 +71,7 @@ function startPtyJob(ptyStream, command, options) {
|
||||
sessionId = null,
|
||||
diagnosticsSession = null,
|
||||
getReadyPrompt,
|
||||
classifyReadiness,
|
||||
beforeInput,
|
||||
promptWaitTimeoutMs = 30000,
|
||||
typedInput = false,
|
||||
@@ -85,6 +87,30 @@ function startPtyJob(ptyStream, command, options) {
|
||||
let readinessFailureCode = null;
|
||||
let waitingForInputGuard = typeof beforeInput === "function";
|
||||
|
||||
// #4195: an empty prompt at the bounded wait deadline is resolved into a
|
||||
// PROVEN-busy hard block (unchanged) or an honest, actionable `unknown`.
|
||||
// A missing/ambiguous classifier always fails closed to busy, so #4110's
|
||||
// false-ready guards and legacy callers without classifyReadiness keep the
|
||||
// exact SHELL_NOT_READY behavior. `unknown` NEVER sends the queued command.
|
||||
function resolveUnreadyOutcome() {
|
||||
if (typeof classifyReadiness !== "function") return "busy";
|
||||
try {
|
||||
return classifyReadiness() === "unknown" ? "unknown" : "busy";
|
||||
} catch {
|
||||
return "busy";
|
||||
}
|
||||
}
|
||||
|
||||
function finishUnready(busyMessage) {
|
||||
if (resolveUnreadyOutcome() === "unknown") {
|
||||
readinessFailureCode = READINESS_UNKNOWN;
|
||||
finish("", -1, SHELL_READINESS_UNKNOWN_MESSAGE);
|
||||
} else {
|
||||
readinessFailureCode = "SHELL_NOT_READY";
|
||||
finish("", -1, busyMessage);
|
||||
}
|
||||
}
|
||||
|
||||
const marker = `__NCMCP_${Date.now().toString(36)}_${crypto.randomBytes(16).toString('hex')}__`;
|
||||
let resolvedShellKind = resolveEffectiveShellKind(shellKind, expectedPrompt, {
|
||||
loginShellHint,
|
||||
@@ -203,10 +229,12 @@ function startPtyJob(ptyStream, command, options) {
|
||||
wallTimeoutId = setTimeout(() => {
|
||||
if (finished) return;
|
||||
if (waitingForPrompt || waitingForInputGuard) {
|
||||
readinessFailureCode = waitingForPrompt ? "SHELL_NOT_READY" : "EXECUTION_NOT_AUTHORIZED";
|
||||
finish("", -1, waitingForPrompt
|
||||
? "Shell prompt is not ready; no command was sent"
|
||||
: "Execution authorization timed out; no command was sent");
|
||||
if (waitingForPrompt) {
|
||||
finishUnready("Shell prompt is not ready; no command was sent");
|
||||
} else {
|
||||
readinessFailureCode = "EXECUTION_NOT_AUTHORIZED";
|
||||
finish("", -1, "Execution authorization timed out; no command was sent");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pendingEnd) {
|
||||
@@ -1017,8 +1045,10 @@ function startPtyJob(ptyStream, command, options) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
readinessFailureCode = "SHELL_NOT_READY";
|
||||
finish("", -1, "Shell prompt is not ready (startup, busy program, pending input, or unrecognized prompt); no command was sent");
|
||||
// Same bounded 30s budget, unchanged. Only the *verdict* differs:
|
||||
// proven-busy stays a hard block; an unrecognized prompt on a live
|
||||
// shell becomes an honest, non-terminal, actionable `unknown`.
|
||||
finishUnready("Shell prompt is not ready (startup, busy program, pending input, or unrecognized prompt); no command was sent");
|
||||
return;
|
||||
}
|
||||
readinessTimer = setTimeout(checkReady, Math.min(50, deadline - Date.now()));
|
||||
@@ -1062,6 +1092,7 @@ function startPtyJob(ptyStream, command, options) {
|
||||
* @param {AbortSignal} [options.abortSignal] - AbortSignal to cancel execution
|
||||
* @param {string} [options.expectedPrompt] - Last observed idle prompt for exact fallback matching
|
||||
* @param {() => string} [options.getReadyPrompt] - Read current prompt; wait without writing until non-empty
|
||||
* @param {() => "busy"|"unknown"} [options.classifyReadiness] - At the bounded wait deadline, classify an empty prompt as PROVEN busy (hard SHELL_NOT_READY) or an honest actionable `unknown` (SHELL_READINESS_UNKNOWN). Absent/ambiguous ⇒ busy (fail closed). Never sends the command for `unknown`.
|
||||
* @param {function} [options.beforeInput] - Revalidate authorization before the first PTY byte (may return a promise)
|
||||
* @param {number} [options.promptWaitTimeoutMs=30000] - Bounded pre-input wait (maximum 30 seconds)
|
||||
* @param {boolean} [options.typedInput=false] - Emit synthetic command echo before execution
|
||||
|
||||
@@ -281,6 +281,26 @@ test('wall deadline during authorization reports authorization failure rather th
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
test('idle Enter-PSSession remoting prompt allows the command to be sent', async () => {
|
||||
const pty = new TestPty();
|
||||
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
|
||||
const prompt = '[192.168.1.10]: PS C:\\Users\\Administrator\\Documents> ';
|
||||
trackSessionIdlePrompt(session, `PowerShell 7\r\n${prompt}`);
|
||||
assert.equal(readyPrompt(session), prompt);
|
||||
|
||||
const result = await startPtyJob(pty, 'Write-Output ok', {
|
||||
shellKind: 'powershell',
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
promptWaitTimeoutMs: 200,
|
||||
timeoutMs: 1000,
|
||||
typedInput: true,
|
||||
}).resultPromise;
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.stdout, 'OK');
|
||||
assert.equal(pty.writes.length, 1);
|
||||
assert.match(pty.writes[0], /\$__NCMCP_/);
|
||||
});
|
||||
|
||||
test('idle PowerShell whose raw tail was CSI-erased still receives the command', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
|
||||
const pty = new TestPty();
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { startPtyJob } = require("./ptyExec.cjs");
|
||||
const {
|
||||
trackSessionIdlePrompt,
|
||||
getFreshIdlePrompt,
|
||||
getVisibleIdlePrompt,
|
||||
} = require("./shellUtils.cjs");
|
||||
const {
|
||||
READINESS_UNKNOWN,
|
||||
SHELL_READINESS_UNKNOWN_MESSAGE,
|
||||
classifyShellReadiness,
|
||||
} = require("./shellReadinessState.cjs");
|
||||
const {
|
||||
formatTerminalExecuteMcpResponse,
|
||||
} = require("../../capabilities/codegen/mcpToolRegistry.cjs");
|
||||
const { MODEL_DESCRIPTION_HINTS } = require("../../capabilities/schemas/toolInputs.cjs");
|
||||
|
||||
function readyPrompt(session) {
|
||||
return getFreshIdlePrompt(session) || getVisibleIdlePrompt(session);
|
||||
}
|
||||
|
||||
function makeSession(extra = {}) {
|
||||
return { _promptTrackTail: "", lastIdlePrompt: "", ...extra };
|
||||
}
|
||||
|
||||
// Records every byte written to the PTY; echoes a completion marker so a
|
||||
// genuinely-executed command resolves ok:true (same seam as
|
||||
// ptyExec.readiness.test.cjs).
|
||||
class TestPty extends EventEmitter {
|
||||
writes = [];
|
||||
write(data) {
|
||||
this.writes.push(String(data));
|
||||
const marker = String(data).match(/(__NCMCP_[a-z0-9]+_[0-9a-f]+__)/i)?.[1];
|
||||
if (marker) queueMicrotask(() => this.emit("data", `${marker}_S\nOK\n${marker}_E:0\n`));
|
||||
}
|
||||
}
|
||||
|
||||
const UNKNOWN_PROMPT = "Last login: Mon\r\nstarship-custom-prompt─❯ ";
|
||||
const SHORT_BUDGET = { promptWaitTimeoutMs: 30, timeoutMs: 2000 };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// classifier unit: PROVEN busy stays hard, whitelist miss on a live shell is
|
||||
// an honest unknown. These are the #4110 false-ready guards we must not weaken.
|
||||
// ---------------------------------------------------------------------------
|
||||
test("classifyShellReadiness: proven-busy OSC 133 / pending-input / task / transport stay busy", () => {
|
||||
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: false })), "busy"); // C/D
|
||||
assert.equal(classifyShellReadiness(makeSession({ _osc133PromptRedrawPending: true })), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession({ _osc133PromptContinued: true })), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: true, _osc133PromptLine: 3 })), "busy"); // B cursor deviation
|
||||
assert.equal(classifyShellReadiness(makeSession({ waitingForInput: true })), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession({ busy: true })), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession({ status: "disconnected" })), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession(), { taskInFlight: true }), "busy");
|
||||
assert.equal(classifyShellReadiness(makeSession(), { transportAlive: false }), "busy");
|
||||
assert.equal(classifyShellReadiness(null), "busy"); // fail closed
|
||||
});
|
||||
|
||||
test("classifyShellReadiness: unrecognized prompt on a live shell is unknown (not ready, not busy)", () => {
|
||||
const session = makeSession();
|
||||
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
|
||||
assert.equal(readyPrompt(session), ""); // genuine whitelist miss
|
||||
assert.equal(classifyShellReadiness(session), "unknown");
|
||||
// A-only marker with no C/D and no B confirmation is still unknown (no busy evidence).
|
||||
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: true, _osc133PromptLine: null })), "unknown");
|
||||
});
|
||||
|
||||
test("classifyShellReadiness: credential prompts remain hard busy (#4195)", () => {
|
||||
for (const line of ["Password:", "[sudo] password for alice: ", "Enter passphrase for key '/root/.ssh/id_rsa': ", "PIN: ", "Sorry, try again."]) {
|
||||
const session = makeSession({ _promptTrackTail: line });
|
||||
assert.equal(readyPrompt(session), "", line);
|
||||
assert.equal(classifyShellReadiness(session), "busy", line);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// gating trichotomy end-to-end — EVERY case asserts PTY bytes written.
|
||||
// ---------------------------------------------------------------------------
|
||||
test("ready (whitelist match) → command sent, unchanged", async () => {
|
||||
const pty = new TestPty();
|
||||
const prompt = "user@host:~$ ";
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => prompt,
|
||||
classifyReadiness: () => "unknown", // never consulted when a prompt is recognized
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(pty.writes.length, 1);
|
||||
});
|
||||
|
||||
test("ready (OSC 133 A with empty input) → command sent, unchanged (#4110)", async () => {
|
||||
const pty = new TestPty();
|
||||
const session = makeSession();
|
||||
trackSessionIdlePrompt(session, "\x1b]133;A\x07\x1b[38;5;39m~/src\x1b[0m \x1b[38;5;213m❯\x1b[0m ");
|
||||
assert.equal(readyPrompt(session), "~/src ❯ ");
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(pty.writes.length, 1);
|
||||
});
|
||||
|
||||
test("PROVEN busy (OSC 133 C/D) → hard SHELL_NOT_READY, ZERO bytes written (#4110 guard)", async () => {
|
||||
const pty = new TestPty();
|
||||
const session = makeSession();
|
||||
trackSessionIdlePrompt(session, "\x1b]133;A\x07PS C:\\Users\\alice> ");
|
||||
assert.equal(readyPrompt(session), "PS C:\\Users\\alice> ");
|
||||
trackSessionIdlePrompt(session, "\x1b]133;C\x07build running...\r\nPS C:\\Users\\alice> ");
|
||||
assert.equal(readyPrompt(session), "");
|
||||
assert.equal(classifyShellReadiness(session), "busy");
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "powershell",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, "SHELL_NOT_READY");
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
test("PROVEN busy (pending-input / our task / disconnected) → hard block, ZERO bytes written", async () => {
|
||||
for (const extra of [
|
||||
{ _osc133PromptContinued: true },
|
||||
{ _osc133PromptRedrawPending: true },
|
||||
{ waitingForInput: true },
|
||||
{ busy: true },
|
||||
{ status: "disconnected" },
|
||||
]) {
|
||||
const pty = new TestPty();
|
||||
const session = makeSession(extra);
|
||||
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
|
||||
assert.equal(readyPrompt(session), "");
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, "SHELL_NOT_READY", JSON.stringify(extra));
|
||||
assert.deepEqual(pty.writes, [], JSON.stringify(extra));
|
||||
}
|
||||
});
|
||||
|
||||
test("unknown (unrecognized prompt, live shell, no busy evidence): command NOT sent, actionable NON-fatal result", async () => {
|
||||
const pty = new TestPty();
|
||||
const session = makeSession();
|
||||
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
|
||||
assert.equal(readyPrompt(session), "");
|
||||
assert.equal(classifyShellReadiness(session), "unknown");
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, READINESS_UNKNOWN);
|
||||
assert.equal(result.ok, false); // NOT a lie of success
|
||||
assert.equal(result.error, SHELL_READINESS_UNKNOWN_MESSAGE);
|
||||
assert.match(result.error, /connection is alive/i);
|
||||
assert.match(result.error, /could not be recognized/i);
|
||||
assert.match(result.error, /NOT sent/i);
|
||||
assert.match(result.error, /read-only/i);
|
||||
assert.match(result.error, /get_environment|terminal_read_context/);
|
||||
assert.deepEqual(pty.writes, []); // no blind typing
|
||||
});
|
||||
|
||||
test("unknown keeps the same bounded wait (no early send, no early verdict)", async () => {
|
||||
const pty = new TestPty();
|
||||
let prompt = "";
|
||||
const job = startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => prompt,
|
||||
classifyReadiness: () => "unknown",
|
||||
promptWaitTimeoutMs: 80,
|
||||
timeoutMs: 2000,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
assert.deepEqual(pty.writes, []); // still waiting at the bounded budget
|
||||
const result = await job.resultPromise;
|
||||
assert.equal(result.code, READINESS_UNKNOWN);
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
test("unknown is recoverable: a recognized prompt (user pressed Enter) lets the next exec succeed", async () => {
|
||||
const pty = new TestPty();
|
||||
let prompt = "";
|
||||
const first = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => prompt,
|
||||
classifyReadiness: () => "unknown",
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(first.code, READINESS_UNKNOWN);
|
||||
assert.deepEqual(pty.writes, []); // first exec never bricked the session
|
||||
|
||||
prompt = "user@host:~$ ";
|
||||
const second = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => prompt,
|
||||
classifyReadiness: () => "unknown",
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(second.ok, true);
|
||||
assert.equal(pty.writes.length, 1);
|
||||
});
|
||||
|
||||
test("Password: remains hard not-ready, ZERO bytes written (#4195 correct behavior)", async () => {
|
||||
const pty = new TestPty();
|
||||
const session = makeSession();
|
||||
trackSessionIdlePrompt(session, "Password:");
|
||||
assert.equal(readyPrompt(session), "");
|
||||
assert.equal(classifyShellReadiness(session), "busy");
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, "SHELL_NOT_READY");
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
test("legacy callers without classifyReadiness keep the exact hard SHELL_NOT_READY block", async () => {
|
||||
const pty = new TestPty();
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
getReadyPrompt: () => "",
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, "SHELL_NOT_READY");
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
test("a throwing / ambiguous classifier fails closed to busy (never a false ready)", async () => {
|
||||
const pty = new TestPty();
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
getReadyPrompt: () => "",
|
||||
classifyReadiness: () => { throw new Error("inspection blew up"); },
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.code, "SHELL_NOT_READY");
|
||||
assert.deepEqual(pty.writes, []);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// agent-visible surfaces: MCP tool result + tool description.
|
||||
// ---------------------------------------------------------------------------
|
||||
test("MCP terminal_execute surfaces unknown as a NON-fatal, actionable result (not isError)", () => {
|
||||
const unknownResult = {
|
||||
ok: false,
|
||||
error: SHELL_READINESS_UNKNOWN_MESSAGE,
|
||||
code: READINESS_UNKNOWN,
|
||||
exitCode: -1,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
};
|
||||
const formatted = formatTerminalExecuteMcpResponse(unknownResult);
|
||||
assert.notEqual(formatted.isError, true); // THE fix: agent does not see a terminal error
|
||||
assert.match(formatted.content[0].text, /read-only/i);
|
||||
assert.match(formatted.content[0].text, /NOT sent/i);
|
||||
assert.match(formatted.content[0].text, /get_environment|terminal_read_context/);
|
||||
// Control: a proven-busy verdict is still a hard error.
|
||||
const busy = formatTerminalExecuteMcpResponse({ ...unknownResult, code: "SHELL_NOT_READY", error: "Shell prompt is not ready; no command was sent" });
|
||||
assert.equal(busy.isError, true);
|
||||
});
|
||||
|
||||
test("terminal_execute tool description documents the unknown outcome and the read-only/confirm path", () => {
|
||||
const description = MODEL_DESCRIPTION_HINTS["terminal.execute"] || "";
|
||||
assert.match(description, /SHELL_READINESS_UNKNOWN/);
|
||||
assert.match(description, /NOT sent/);
|
||||
assert.match(description, /read-only/);
|
||||
assert.match(description, /get_environment|terminal_read_context/);
|
||||
assert.match(description, /ask the user to confirm/);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* First-class shell readiness classification for the pre-input gate in
|
||||
* startPtyJob. This composes #4110's OSC 133 marker authority and #4195's
|
||||
* asymmetric-harm thesis: a whitelist miss on a live shell must be an
|
||||
* actionable `unknown`, never a terminal SHELL_NOT_READY — but anything
|
||||
* PROVEN busy (or a credential prompt waiting for the user's secret) must
|
||||
* stay a hard block. It mirrors #3935's honesty rule: `unknown` is NOT a lie
|
||||
* of success and is never claimed as ready.
|
||||
*
|
||||
* This module only READS session state. It never writes to a PTY, never
|
||||
* injects OSC markers, and never widens tool scope. It lives outside
|
||||
* shellUtils.cjs (the prompt whitelist) on purpose so the gating consumer
|
||||
* evolves independently of positive-signal additions such as #4197.
|
||||
*/
|
||||
const { stripAnsi } = require("./shellUtils.cjs");
|
||||
|
||||
/** Distinct, non-terminal code emitted when the gate cannot prove busy. */
|
||||
const READINESS_UNKNOWN = "SHELL_READINESS_UNKNOWN";
|
||||
|
||||
/**
|
||||
* Honest, actionable result text. Surfaced verbatim as the exec result
|
||||
* `error` and as the MCP/Catty tool-result text. It must never claim ready.
|
||||
* (a) connection alive + no busy signal, (b) prompt unrecognized,
|
||||
* (c) command NOT sent / no blind typing, (d) the viable read-only path.
|
||||
*/
|
||||
const SHELL_READINESS_UNKNOWN_MESSAGE = [
|
||||
"Shell readiness unknown (SHELL_READINESS_UNKNOWN): the terminal connection is",
|
||||
"alive and no busy, pending-input, or credential-prompt signal was observed, but",
|
||||
"the prompt could not be recognized (custom theme, colored/starship/root prompt,",
|
||||
"or continuation). The command was NOT sent — never blind-type into a possible",
|
||||
"password prompt, editor, or half-typed command. This is a recoverable,",
|
||||
"non-terminal state, not a failed command. Read-only next steps: call",
|
||||
"get_environment or terminal_read_context to inspect the visible buffer, re-check",
|
||||
"readiness after the user presses Enter or a recognized prompt appears, reuse",
|
||||
"another idle session, or ask the user to confirm the prompt before retrying.",
|
||||
"Retrying once the prompt is recognized is safe.",
|
||||
].join(" ");
|
||||
|
||||
// Known credential/passphrase prompts. #4195: `Password:` (and friends) are
|
||||
// PROVEN "waiting for secret input" states and MUST remain hard not-ready.
|
||||
// This is a conservative block-list (hardening only): a miss falls through to
|
||||
// `unknown`, which still never types.
|
||||
const BLOCKING_INPUT_PATTERNS = [
|
||||
/^(?:\[sudo\]\s*|enter\s+|please\s+enter\s+)?(?:password|passphrase|pin)(?:\s+for\s+[^:]+)?\s*:?\s*$/i,
|
||||
/^sorry,\s*try\s+again\.?\s*$/i,
|
||||
];
|
||||
|
||||
function lastVisibleLine(session) {
|
||||
const tail = typeof session?._promptTrackTail === "string" ? session._promptTrackTail : "";
|
||||
if (!tail) return "";
|
||||
const lines = stripAnsi(tail).split(/[\r\n]/);
|
||||
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
||||
const line = lines[i].trim();
|
||||
if (line) return line;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a session whose getReadyPrompt() just returned empty (i.e. no
|
||||
* whitelist match and no OSC 133 A-with-empty-input ready signal).
|
||||
*
|
||||
* Returns:
|
||||
* "busy" — PROVEN busy → keep the hard SHELL_NOT_READY block unchanged.
|
||||
* "unknown" — connection alive, no proven-busy evidence, prompt not
|
||||
* recognized → actionable, non-terminal outcome.
|
||||
*
|
||||
* Anything ambiguous (missing session, thrown helper, unknown context) fails
|
||||
* CLOSED to "busy", so #4110's false-ready guards are never weakened.
|
||||
*/
|
||||
function classifyShellReadiness(session, context = {}) {
|
||||
if (!session) return "busy";
|
||||
const { taskInFlight = false, transportAlive = true } = context || {};
|
||||
// Our own tracked task in flight / a dead transport are proven busy and are
|
||||
// also hard-blocked at the exec call sites (reserveSessionExecution,
|
||||
// writability check) and by the PTY close/error handlers.
|
||||
if (taskInFlight || !transportAlive) return "busy";
|
||||
// #4110: an OSC 133 C/D marker establishes a running command/output
|
||||
// lifecycle. shellUtils.cjs:321 sets osc133Ready=false; getFreshIdlePrompt
|
||||
// (:377) and getVisibleIdlePrompt (:406) both return "" for that state.
|
||||
if (session.osc133Ready === false) return "busy";
|
||||
// #4110 pending-input guards (shellUtils.cjs:265-275): redraw latch,
|
||||
// continuation/PS2, and B-marker cursor deviation. An empty prompt while
|
||||
// osc133Ready===true with a B-marked line means matchesOsc133EmptyPrompt
|
||||
// rejected it → the user typed into the prompt line.
|
||||
if (session._osc133PromptRedrawPending) return "busy";
|
||||
if (session._osc133PromptContinued) return "busy";
|
||||
if (session.osc133Ready === true && session._osc133PromptLine != null) return "busy";
|
||||
// Explicit busy / waiting-for-input session state (#3935 recovery model:
|
||||
// sessionRecoveryService.cjs:55-56, 101-102).
|
||||
if (session.waitingForInput === true || session.busy === true) return "busy";
|
||||
if (session.status === "disconnected" || session.status === "stopped") return "busy";
|
||||
// Credential prompt waiting for the user's secret (#4195).
|
||||
const line = lastVisibleLine(session);
|
||||
if (line && BLOCKING_INPUT_PATTERNS.some((pattern) => pattern.test(line))) return "busy";
|
||||
// Connection alive, no proven-busy evidence, prompt not recognized.
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
READINESS_UNKNOWN,
|
||||
SHELL_READINESS_UNKNOWN_MESSAGE,
|
||||
classifyShellReadiness,
|
||||
};
|
||||
@@ -50,11 +50,12 @@ function formatSyntheticEcho(command) {
|
||||
}
|
||||
|
||||
// Default PowerShell prompt (e.g. `PS C:\Users\alice>`, `PS>`,
|
||||
// `PS /home/alice>`). Anchored so command output that merely starts with
|
||||
// `PS` (e.g. `PSO>`) doesn't match. The `\S` after `\s+` rejects literal
|
||||
// `PS /home/alice>`), with optional Enter-PSSession / remoting `[host]: `
|
||||
// and debug `[DBG]: ` prefixes. Anchored so command output that merely
|
||||
// starts with `PS` (e.g. `PSO>`) doesn't match. The `\S` after `\s+` rejects literal
|
||||
// `"PS >"` (which the default prompt never emits) so a script that prints
|
||||
// such a line can't trick prompt-driven shell-kind selection.
|
||||
const POWERSHELL_PROMPT_PATTERN = /^PS(?:\s+\S.*)?>$/;
|
||||
const POWERSHELL_PROMPT_PATTERN = /^(?:\[[^\]\r\n]+\]: )*PS(?:\s+\S.*)?>$/;
|
||||
|
||||
// Default cmd.exe prompt (e.g. `C:\>`, `C:\Users\alice>`, `D:\data>`).
|
||||
// Drive letter + optional path + `>`. Rejects `C: >` (space before `>`) and
|
||||
@@ -69,6 +70,10 @@ const CMD_PROMPT_PATTERN = /^[A-Za-z]:(?:\\[^<>"|]*)?>$/;
|
||||
// the final `]` before `$`/`#` is the delimiter.
|
||||
const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s\]:]+(?:\s+[^\n\r]+)?\])[#$]$/;
|
||||
|
||||
// Bracket PS1 without @host, with bash `\t` time: `[\u \t \w]$` -> `[root 12:04:23 ~]$` (#4276).
|
||||
// Require HH:MM:SS so loose `[word]$` output cannot count as idle.
|
||||
const BRACKET_TIME_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+\d{2}:\d{2}:\d{2}(?:\s+[^\n\r\]]+)?\][#$]$/;
|
||||
|
||||
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
|
||||
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
|
||||
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
|
||||
@@ -136,6 +141,7 @@ function isDefaultPosixPromptLine(line) {
|
||||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
return (
|
||||
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
|
||||
@@ -112,6 +112,46 @@ test("isDefaultPowerShellPromptLine matches default shapes and rejects look-alik
|
||||
assert.equal(isDefaultPowerShellPromptLine(null), false);
|
||||
});
|
||||
|
||||
test("PowerShell prompt helpers recognize remoting and debug prefixes", () => {
|
||||
for (const prompt of [
|
||||
"[192.168.1.10]: PS C:\\Users\\Administrator\\Documents>",
|
||||
"[SERVER01]: PS C:\\>",
|
||||
"[host.example.com]: PS C:\\Windows\\System32>",
|
||||
"[fe80::1]: PS C:\\>",
|
||||
"[DBG]: PS C:\\Users\\alice>",
|
||||
"[SERVER01]: [DBG]: PS C:\\>",
|
||||
]) {
|
||||
assert.equal(isDefaultPowerShellPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("PowerShell prompt helpers reject malformed remoting prefixes and look-alikes", () => {
|
||||
for (const line of [
|
||||
"[host] PS C:\\>",
|
||||
"prefix [host]: PS C:\\>",
|
||||
"[]: PS C:\\>",
|
||||
"[ho]st]: PS C:\\>",
|
||||
"[ho\rst]: PS C:\\>",
|
||||
"[ho\nst]: PS C:\\>",
|
||||
"[host]:PS C:\\>",
|
||||
"[host]: PS >",
|
||||
"PS >",
|
||||
"PSO>",
|
||||
"ZIPS>",
|
||||
"",
|
||||
null,
|
||||
]) {
|
||||
assert.equal(isDefaultPowerShellPromptLine(line), false, String(line));
|
||||
assert.equal(extractTrailingIdlePrompt(line), "", String(line));
|
||||
}
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt preserves trailing space on a remoting prompt", () => {
|
||||
const prompt = "[192.168.1.10]: PS C:\\Users\\Administrator\\Documents> ";
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt);
|
||||
});
|
||||
|
||||
test("extracts a trailing cmd.exe idle prompt", () => {
|
||||
// Windows OpenSSH default shell is cmd.exe; without capturing `C:\...>`
|
||||
// AI exec cannot select the cmd wrapper when shellKind is still unset.
|
||||
@@ -152,6 +192,30 @@ test("isDefaultPosixPromptLine matches classic user@host prompts", () => {
|
||||
assert.equal(isDefaultPosixPromptLine(""), false);
|
||||
});
|
||||
|
||||
test("recognizes bracketed time prompts without a hostname and preserves trailing space", () => {
|
||||
for (const prompt of [
|
||||
"[root 12:04:23 ~]$",
|
||||
"[root 12:04:23 ~]$ ",
|
||||
"[alice 00:00:00 /var/log]# ",
|
||||
"[alice-admin 23:59:59 ~/src]$ ",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("bracketed time prompt recognition rejects pending input and prompts without time", () => {
|
||||
for (const line of [
|
||||
"[root 12:04:23 ~]$ hostname",
|
||||
"[root 12:04:23 ~]$ echo $",
|
||||
"[root ~]$",
|
||||
"[word]$",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(line), false, line);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
|
||||
}
|
||||
});
|
||||
|
||||
test("recognizes space-separated Bash idle prompts and preserves trailing whitespace", () => {
|
||||
for (const prompt of [
|
||||
"root@VM-Q7L4M8P2 ~ $",
|
||||
@@ -448,6 +512,13 @@ test("extracts a trailing RHEL-family bracketed idle prompt", () => {
|
||||
assert.equal(extractTrailingIdlePrompt("welcome\r\nroot@host ~#"), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed time prompt", () => {
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt("welcome\r\n[\x1b[1;34mroot \x1b[1;36m12:04:23 \x1b[1;32m~\x1b[0m]$ "),
|
||||
"[root 12:04:23 ~]$ ",
|
||||
);
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes a two-line user@host then bare $/# PS1", () => {
|
||||
// export PS1="\u@\h: \w\n$ " paints the host line, then a lone "$ ".
|
||||
// The cached prompt must keep both lines so a lone "$" cannot satisfy endsWith.
|
||||
@@ -1193,6 +1264,14 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oracle/RHEL bracke
|
||||
assert.equal(getFreshIdlePrompt(bracketedPath), "[user@host My [Project]]$ ");
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed time prompt", () => {
|
||||
const session = {};
|
||||
const prompt = "[root 12:04:23 ~]$ ";
|
||||
assert.equal(trackSessionIdlePrompt(session, `Last login...\r\n${prompt}`), prompt);
|
||||
assert.equal(session.lastIdlePrompt, prompt);
|
||||
assert.equal(getFreshIdlePrompt(session), prompt);
|
||||
});
|
||||
|
||||
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
|
||||
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
|
||||
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// (based in electron/bridges/). Requiring here keeps the path unambiguous.
|
||||
const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs");
|
||||
const { formatSyntheticEcho, getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
|
||||
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
|
||||
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
|
||||
const { remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
|
||||
const defaultAiPrivacyService = require("../../shared/aiPrivacyService.cjs");
|
||||
@@ -227,6 +228,7 @@ function registerCattyExecHandlers(ctx) {
|
||||
expectedPrompt: getFreshIdlePrompt(session),
|
||||
getReadyPrompt: typeof session._promptTrackTail === "string"
|
||||
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
typedInput: true,
|
||||
echoCommand: (rawCommand) => {
|
||||
const contents = electronModule?.webContents?.fromId?.(session.webContentsId);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
let sshKeygenSkip = false;
|
||||
try {
|
||||
execFileSync("ssh-keygen", ["-h"], { stdio: "ignore" });
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") sshKeygenSkip = "ssh-keygen is not installed";
|
||||
}
|
||||
|
||||
const sshString = (value) => {
|
||||
const body = Buffer.from(value);
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32BE(body.length);
|
||||
return Buffer.concat([length, body]);
|
||||
};
|
||||
|
||||
// Real local certificates, with no server/network or security-key device.
|
||||
function mintHostCertificates(t, { type = "ed25519", bits, sk = false, user = false } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(__dirname, ".hostcert-"));
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
const keygen = (...args) => execFileSync("ssh-keygen", ["-q", ...args], { stdio: "pipe" });
|
||||
const ca = path.join(dir, "ca");
|
||||
keygen("-t", "ed25519", "-N", "", "-f", ca);
|
||||
const readKey = (file) => {
|
||||
const line = fs.readFileSync(file, "utf8").trim();
|
||||
const [keyType, body] = line.split(/\s+/);
|
||||
return { line, keyType, blob: Buffer.from(body, "base64") };
|
||||
};
|
||||
const mint = (name, validity, serial) => {
|
||||
const host = path.join(dir, name);
|
||||
if (!fs.existsSync(host)) {
|
||||
keygen("-t", type, ...(bits ? ["-b", String(bits)] : []), "-N", "", "-f", host);
|
||||
if (sk) {
|
||||
const plain = readKey(`${host}.pub`);
|
||||
const keyMaterial = plain.blob.subarray(4 + plain.keyType.length);
|
||||
const skType = `sk-${plain.keyType}@openssh.com`;
|
||||
const blob = Buffer.concat([sshString(skType), keyMaterial, sshString("ssh:netcatty-test")]);
|
||||
fs.writeFileSync(`${host}.pub`, `${skType} ${blob.toString("base64")}\n`);
|
||||
}
|
||||
}
|
||||
keygen("-s", ca, "-I", "netcatty-hostcert", ...(user ? [] : ["-h"]),
|
||||
"-n", "127.0.0.1", "-V", validity, "-z", String(serial), `${host}.pub`);
|
||||
const cert = readKey(`${host}-cert.pub`);
|
||||
const listing = execFileSync("ssh-keygen", ["-L", "-f", `${host}-cert.pub`], { encoding: "utf8" });
|
||||
const publicKeyFingerprint = listing.match(/Public key: .* SHA256:(\S+)/)?.[1];
|
||||
if (!publicKeyFingerprint) throw new Error("Missing ssh-keygen certificate fingerprint");
|
||||
return { ...cert, publicKeyFingerprint, plain: readKey(`${host}.pub`) };
|
||||
};
|
||||
return {
|
||||
first: mint("host", "20250101:20260101", 1),
|
||||
renewed: mint("host", "20260101:20270101", 2),
|
||||
different: mint("other", "20260101:20270101", 3),
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy v00 is no longer emitted by ssh-keygen. This follows the original
|
||||
// PROTOCOL.certkeys layout: key material first, nonce after constraints.
|
||||
function legacyCertificate(keyType, keyFields) {
|
||||
const blob = Buffer.concat([
|
||||
sshString(`${keyType}-cert-v00@openssh.com`),
|
||||
...keyFields.map(sshString),
|
||||
Buffer.from([0, 0, 0, 2]),
|
||||
sshString("legacy"), sshString(""), Buffer.alloc(16),
|
||||
sshString(""), sshString("nonce"), sshString(""),
|
||||
sshString("signing key"), sshString("signature"),
|
||||
]);
|
||||
return {
|
||||
blob,
|
||||
plain: Buffer.concat([sshString(keyType), ...keyFields.map(sshString)]),
|
||||
line: `${keyType}-cert-v00@openssh.com ${blob.toString("base64")}`,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { mintHostCertificates, legacyCertificate, sshString, sshKeygenSkip };
|
||||
@@ -1,6 +1,7 @@
|
||||
const crypto = require("node:crypto");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { utils: sshUtils } = require("ssh2");
|
||||
const { extractCertificatePublicKey } = require("../../domain/sshPublicKey.shared.cjs");
|
||||
|
||||
const REQUEST_TTL_MS = 2 * 60 * 1000;
|
||||
const hostKeyRequests = new Map();
|
||||
@@ -65,8 +66,9 @@ const fingerprintFromPublicKey = (publicKey) => {
|
||||
const parts = trimmed.split(/\s+/);
|
||||
if (parts.length >= 2 && /^ssh-|^ecdsa-|^sk-/.test(parts[0])) {
|
||||
try {
|
||||
const blob = Buffer.from(parts[1], "base64");
|
||||
return crypto.createHash("sha256")
|
||||
.update(Buffer.from(parts[1], "base64"))
|
||||
.update(extractCertificatePublicKey(blob) || blob)
|
||||
.digest("base64")
|
||||
.replace(/=+$/g, "");
|
||||
} catch {
|
||||
@@ -77,7 +79,16 @@ const fingerprintFromPublicKey = (publicKey) => {
|
||||
};
|
||||
|
||||
const getKnownHostFingerprint = (knownHost) => {
|
||||
return normalizeFingerprint(knownHost?.fingerprint)
|
||||
const stored = normalizeFingerprint(knownHost?.fingerprint);
|
||||
const parts = knownHost?.publicKey?.trim().split(/\s+/) || [];
|
||||
if (parts.length >= 2 && /-cert-v0[01]@openssh\.com$/.test(parts[0])) {
|
||||
const blob = Buffer.from(parts[1], "base64");
|
||||
// Only replace an explicit fingerprint if it is the legacy full-cert hash.
|
||||
// Fingerprint-only records cannot be migrated without the certificate body.
|
||||
const legacy = crypto.createHash("sha256").update(blob).digest("base64").replace(/=+$/g, "");
|
||||
if (!stored || stored === legacy) return fingerprintFromPublicKey(knownHost.publicKey);
|
||||
}
|
||||
return stored
|
||||
|| fingerprintFromPublicKey(knownHost?.publicKey);
|
||||
};
|
||||
|
||||
@@ -134,7 +145,7 @@ const classifyHostKey = ({ knownHosts = [], hostname, port = 22, keyType, finger
|
||||
const describeHostKey = (rawKey) => {
|
||||
const key = Buffer.isBuffer(rawKey) ? rawKey : Buffer.from(rawKey || "");
|
||||
const fingerprint = crypto.createHash("sha256")
|
||||
.update(key)
|
||||
.update(extractCertificatePublicKey(key) || key)
|
||||
.digest("base64")
|
||||
.replace(/=+$/g, "");
|
||||
let keyType = "unknown";
|
||||
@@ -149,7 +160,9 @@ const describeHostKey = (rawKey) => {
|
||||
try {
|
||||
const parsed = sshUtils.parseKey(key);
|
||||
const parsedKey = Array.isArray(parsed) ? parsed[0] : parsed;
|
||||
if (parsedKey && !(parsedKey instanceof Error)) {
|
||||
// Keep the presented certificate identity, even if a parser returns its
|
||||
// base algorithm or underlying public key as metadata.
|
||||
if (parsedKey && !(parsedKey instanceof Error) && !/-cert-v0[01]@openssh\.com$/.test(keyType)) {
|
||||
keyType = parsedKey.type || keyType;
|
||||
const publicSsh = parsedKey.getPublicSSH?.();
|
||||
if (publicSsh) publicKey = publicSsh.toString("utf8");
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const crypto = require("node:crypto");
|
||||
const { mintHostCertificates, legacyCertificate, sshString, sshKeygenSkip } = require("./fixtures/hostCertificates.test.fixture.cjs");
|
||||
|
||||
const {
|
||||
classifyHostKey,
|
||||
createHostVerifier,
|
||||
describeHostKey,
|
||||
getKnownHostFingerprint,
|
||||
handleResponse,
|
||||
normalizeFingerprint,
|
||||
} = require("./hostKeyVerifier.cjs");
|
||||
@@ -17,6 +19,84 @@ const makeRawPublicKey = (keyType, body = "trusted imported host key") => {
|
||||
return Buffer.concat([length, type, Buffer.from(body)]);
|
||||
};
|
||||
|
||||
const hashKey = (blob) => crypto.createHash("sha256").update(blob).digest("base64").replace(/=+$/g, "");
|
||||
|
||||
test("host certificate renewals trust the inner key, including legacy saved fingerprints", { skip: sshKeygenSkip }, (t) => {
|
||||
const { first, renewed, different } = mintHostCertificates(t);
|
||||
const original = describeHostKey(first.blob);
|
||||
const live = describeHostKey(renewed.blob);
|
||||
const changed = describeHostKey(different.blob);
|
||||
assert.notDeepEqual(first.blob, renewed.blob);
|
||||
assert.equal(original.fingerprint, first.publicKeyFingerprint);
|
||||
assert.equal(live.fingerprint, original.fingerprint);
|
||||
assert.notEqual(changed.fingerprint, live.fingerprint);
|
||||
assert.equal(original.keyType, "ssh-ed25519-cert-v01@openssh.com");
|
||||
assert.equal(original.publicKey, `${first.keyType} ${first.blob.toString("base64")}`);
|
||||
assert.equal(describeHostKey(first.plain.blob).fingerprint, hashKey(first.plain.blob));
|
||||
|
||||
const stored = { id: "kh-cert", hostname: "cert.local", port: 2222, ...original };
|
||||
const classify = (key, record = stored) => classifyHostKey({
|
||||
knownHosts: [record], hostname: "cert.local", port: 2222, ...key,
|
||||
});
|
||||
assert.equal(classify(live).status, "trusted");
|
||||
assert.equal(classify(changed).status, "changed");
|
||||
assert.equal(classify(changed, { ...stored, keyType: "ssh-rsa" }).status, "unknown");
|
||||
|
||||
const legacy = { ...stored, fingerprint: hashKey(first.blob) };
|
||||
assert.notEqual(legacy.fingerprint, live.fingerprint);
|
||||
assert.equal(getKnownHostFingerprint(legacy), live.fingerprint);
|
||||
assert.equal(classify(live, legacy).status, "trusted");
|
||||
assert.equal(classify(changed, legacy).status, "changed");
|
||||
assert.equal(classify(live, { ...legacy, publicKey: undefined }).status, "changed");
|
||||
assert.equal(classify(live, { ...legacy, publicKey: `SHA256:${legacy.fingerprint}` }).status, "changed");
|
||||
assert.equal(classify(live, { ...legacy, fingerprint: "unrelated-explicit-fingerprint" }).status, "changed");
|
||||
assert.equal(classify(live, { ...legacy, fingerprint: undefined }).status, "trusted");
|
||||
|
||||
// Renewal is trusted on reconnect, but changing the raw certificate during
|
||||
// an established connection must still be rejected synchronously on rekey.
|
||||
const verifier = createHostVerifier({ hostname: stored.hostname, port: stored.port, knownHosts: [legacy] });
|
||||
const results = [];
|
||||
verifier(first.blob, (accepted) => results.push(accepted));
|
||||
verifier(Buffer.from(first.blob), (accepted) => results.push(accepted));
|
||||
verifier(renewed.blob, (accepted) => results.push(accepted));
|
||||
assert.deepEqual(results, [true, true, false]);
|
||||
});
|
||||
|
||||
for (const options of [
|
||||
{ type: "rsa", bits: 2048 },
|
||||
...[256, 384, 521].map((bits) => ({ type: "ecdsa", bits })),
|
||||
{ type: "ed25519", sk: true },
|
||||
{ type: "ecdsa", bits: 256, sk: true },
|
||||
{ type: "ed25519", user: true },
|
||||
]) {
|
||||
test(`certificate fingerprint matches ssh-keygen for ${JSON.stringify(options)}`, { skip: sshKeygenSkip }, (t) => {
|
||||
const { first, renewed, different } = mintHostCertificates(t, options);
|
||||
assert.equal(describeHostKey(first.blob).fingerprint, first.publicKeyFingerprint);
|
||||
assert.equal(describeHostKey(first.blob).fingerprint, hashKey(first.plain.blob));
|
||||
assert.equal(describeHostKey(renewed.blob).fingerprint, first.publicKeyFingerprint);
|
||||
assert.notEqual(describeHostKey(different.blob).fingerprint, first.publicKeyFingerprint);
|
||||
});
|
||||
}
|
||||
|
||||
test("v00 certificates extract the key before the nonce", () => {
|
||||
for (const [type, fields] of [["ssh-rsa", ["exponent", "modulus"]], ["ssh-dss", ["p", "q", "g", "y"]]]) {
|
||||
const cert = legacyCertificate(type, fields);
|
||||
assert.equal(describeHostKey(cert.blob).fingerprint, hashKey(cert.plain));
|
||||
assert.equal(describeHostKey(cert.blob).keyType, `${type}-cert-v00@openssh.com`);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed and unsupported certificates keep their full-blob fingerprint", () => {
|
||||
const truncated = Buffer.concat([
|
||||
sshString("ssh-ed25519-cert-v01@openssh.com"), sshString("nonce"), sshString(Buffer.alloc(32)),
|
||||
]);
|
||||
const badLength = Buffer.concat([sshString("ssh-ed25519-cert-v01@openssh.com"), Buffer.from([255, 255, 255, 255])]);
|
||||
const unsupported = Buffer.concat([sshString("unknown-cert-v01@openssh.com"), sshString("nonce")]);
|
||||
for (const blob of [truncated, badLength, unsupported]) {
|
||||
assert.equal(describeHostKey(blob).fingerprint, hashKey(blob));
|
||||
}
|
||||
});
|
||||
|
||||
test("classifyHostKey prompts for unknown hosts", () => {
|
||||
const result = classifyHostKey({
|
||||
knownHosts: [],
|
||||
|
||||
@@ -384,7 +384,9 @@ test("MCP background readiness timeout survives job polling without PTY writes",
|
||||
const polled = api.handleJobPoll({ jobId: started.jobId, chatSessionId: "readiness-chat" });
|
||||
assert.equal(polled.status, "failed");
|
||||
assert.equal(polled.completed, true);
|
||||
assert.equal(polled.code, "SHELL_NOT_READY");
|
||||
// #4195: a live shell whose prompt was never recognized is an actionable
|
||||
// unknown, not a terminal SHELL_NOT_READY. The command is still never sent.
|
||||
assert.equal(polled.code, "SHELL_READINESS_UNKNOWN");
|
||||
assert.equal(ctx.activeSessionExecutions.size, 0);
|
||||
assert.deepEqual(pty.writes, []);
|
||||
ctx.getFreshIdlePrompt = () => "user@host:~$ ";
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// where bare `require` resolves to ctx.require (based in electron/bridges/).
|
||||
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
|
||||
const { getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
|
||||
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
|
||||
const { emitJobDiag } = require("../ai/jobStartupDiagnostics.cjs");
|
||||
const {
|
||||
ensureSessionShellKind,
|
||||
@@ -161,6 +162,7 @@ function createExecHandlerApi(ctx) {
|
||||
expectedPrompt: getFreshIdlePrompt(session),
|
||||
getReadyPrompt: typeof session._promptTrackTail === "string"
|
||||
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
typedInput: true,
|
||||
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
|
||||
chatSessionId,
|
||||
@@ -343,6 +345,7 @@ function createExecHandlerApi(ctx) {
|
||||
expectedPrompt: getFreshIdlePrompt(session),
|
||||
getReadyPrompt: typeof session._promptTrackTail === "string"
|
||||
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
typedInput: true,
|
||||
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
|
||||
maxBufferedChars: MAX_BACKGROUND_JOB_OUTPUT_CHARS,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
const { randomUUID } = require("node:crypto");
|
||||
|
||||
// Keep the renderer alive until its ConnectionLog replay writes have committed.
|
||||
function finalizeSessionLogs(webContents, { ipcMain, timeoutMs = 5000 } = {}) {
|
||||
if (!webContents || webContents.isDestroyed?.() || webContents.isCrashed?.()
|
||||
|| typeof webContents.send !== "function"
|
||||
|| typeof ipcMain?.on !== "function"
|
||||
|| typeof ipcMain?.removeListener !== "function") {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const requestId = randomUUID();
|
||||
const finish = (success) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
ipcMain.removeListener("app:session-logs-finalized", onResult);
|
||||
} catch {
|
||||
// IPC teardown must not prevent the window from closing.
|
||||
}
|
||||
if (!success) console.warn("[SessionLogs] Renderer did not finalize logs before close");
|
||||
resolve(success);
|
||||
};
|
||||
const onResult = (event, payload) => {
|
||||
if (event.sender === webContents && payload?.requestId === requestId) {
|
||||
finish(payload.success === true);
|
||||
}
|
||||
};
|
||||
const timer = setTimeout(() => finish(false), timeoutMs);
|
||||
try {
|
||||
ipcMain.on("app:session-logs-finalized", onResult);
|
||||
webContents.send("app:finalize-session-logs", { requestId });
|
||||
} catch {
|
||||
finish(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { finalizeSessionLogs };
|
||||
@@ -0,0 +1,193 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { finalizeSessionLogs } = require("./sessionLogShutdown.cjs");
|
||||
const { createPreloadApi } = require("../preload/api.cjs");
|
||||
const { handleBeforeQuit } = require("../main/appLockLifecycle.cjs");
|
||||
const { readFileSync } = require("node:fs");
|
||||
const vm = require("node:vm");
|
||||
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
function renderer(ipcMain = new EventEmitter()) {
|
||||
const ipcRenderer = new EventEmitter();
|
||||
const webContents = { send: (channel, payload) => ipcRenderer.emit(channel, {}, payload) };
|
||||
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
|
||||
const api = createPreloadApi({ ipcRenderer });
|
||||
return { api, ipcMain, ipcRenderer, webContents };
|
||||
}
|
||||
|
||||
test("finalization waits for every terminal replay commit, including a hidden renderer", async () => {
|
||||
const h = renderer();
|
||||
const commits = [];
|
||||
const off = h.api.onFinalizeSessionLogs(() => { throw new Error("unmounted terminal"); });
|
||||
off();
|
||||
for (let i = 0; i < 2; i++) {
|
||||
h.api.onFinalizeSessionLogs(() => new Promise((resolve) => commits.push(resolve)));
|
||||
}
|
||||
let done = false;
|
||||
const pending = finalizeSessionLogs(h.webContents, h).then((result) => { done = true; return result; });
|
||||
await tick();
|
||||
assert.equal(done, false);
|
||||
commits[0](); await tick();
|
||||
assert.equal(done, false);
|
||||
commits[1]();
|
||||
assert.equal(await pending, true);
|
||||
assert.equal(h.ipcMain.listenerCount("app:session-logs-finalized"), 0);
|
||||
});
|
||||
|
||||
test("empty renderers acknowledge immediately; failed captures acknowledge failure", async () => {
|
||||
const h = renderer();
|
||||
assert.equal(await finalizeSessionLogs(h.webContents, h), true);
|
||||
h.api.onFinalizeSessionLogs(() => { throw new Error("capture failed"); });
|
||||
assert.equal(await finalizeSessionLogs(h.webContents, h), false);
|
||||
});
|
||||
|
||||
test("overlapping window close and app quit share the pending replay commit", async () => {
|
||||
const h = renderer();
|
||||
let finish;
|
||||
let captures = 0;
|
||||
h.api.onFinalizeSessionLogs(() => {
|
||||
captures++;
|
||||
return new Promise((resolve) => { finish = resolve; });
|
||||
});
|
||||
const first = finalizeSessionLogs(h.webContents, h);
|
||||
let secondDone = false;
|
||||
const second = finalizeSessionLogs(h.webContents, h).then((result) => { secondDone = true; return result; });
|
||||
await tick();
|
||||
assert.equal(captures, 1);
|
||||
assert.equal(secondDone, false);
|
||||
finish();
|
||||
assert.equal(await first, true);
|
||||
assert.equal(await second, true);
|
||||
});
|
||||
|
||||
test("only the queried renderer and current request can acknowledge finalization", async () => {
|
||||
const ipcMain = new EventEmitter();
|
||||
let request;
|
||||
const webContents = { send: (_channel, payload) => { request = payload; } };
|
||||
let done = false;
|
||||
const pending = finalizeSessionLogs(webContents, { ipcMain }).then((result) => { done = true; return result; });
|
||||
ipcMain.emit("app:session-logs-finalized", { sender: {} }, { ...request, success: true });
|
||||
ipcMain.emit("app:session-logs-finalized", { sender: webContents }, { requestId: "old", success: true });
|
||||
await tick();
|
||||
assert.equal(done, false);
|
||||
ipcMain.emit("app:session-logs-finalized", { sender: webContents }, { ...request, success: true });
|
||||
assert.equal(await pending, true);
|
||||
});
|
||||
|
||||
test("unresponsive and destroyed renderers do not strand quit or leak listeners", async () => {
|
||||
const ipcMain = new EventEmitter();
|
||||
assert.equal(await finalizeSessionLogs({ send() {} }, { ipcMain, timeoutMs: 1 }), false);
|
||||
assert.equal(await finalizeSessionLogs({ send() { throw new Error("destroyed"); } }, { ipcMain }), false);
|
||||
assert.equal(await finalizeSessionLogs({ isDestroyed: () => true }, { ipcMain }), false);
|
||||
assert.equal(ipcMain.listenerCount("app:session-logs-finalized"), 0);
|
||||
});
|
||||
|
||||
test("unavailable finalize IPC returns immediately without scheduling timers or sending", async (t) => {
|
||||
const timer = t.mock.method(globalThis, "setTimeout");
|
||||
const ipcMain = new EventEmitter();
|
||||
const send = t.mock.fn();
|
||||
const on = t.mock.method(ipcMain, "on");
|
||||
for (const unavailableIpc of [undefined, null, {}, { on() {} }, { removeListener() {} }, { on: true, removeListener() {} }, { on() {}, removeListener: true }]) {
|
||||
assert.equal(await finalizeSessionLogs({ send }, { ipcMain: unavailableIpc }), false);
|
||||
}
|
||||
for (const webContents of [undefined, null, {}, { send: true }]) {
|
||||
assert.equal(await finalizeSessionLogs(webContents, { ipcMain }), false);
|
||||
}
|
||||
assert.equal(timer.mock.callCount(), 0);
|
||||
assert.equal(on.mock.callCount(), 0);
|
||||
assert.equal(send.mock.callCount(), 0);
|
||||
});
|
||||
|
||||
for (const failure of ["registration", "send", "cleanup"]) {
|
||||
test(`finalize IPC ${failure} errors do not reject or leave a pending timeout`, async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const warn = t.mock.method(console, "warn", () => {});
|
||||
const ipcMain = new EventEmitter();
|
||||
const webContents = { send() { throw new Error("send failed"); } };
|
||||
if (failure === "registration") {
|
||||
ipcMain.on = (channel, listener) => {
|
||||
EventEmitter.prototype.on.call(ipcMain, channel, listener);
|
||||
throw new Error("registration failed");
|
||||
};
|
||||
} else if (failure === "cleanup") {
|
||||
ipcMain.removeListener = (channel, listener) => {
|
||||
EventEmitter.prototype.removeListener.call(ipcMain, channel, listener);
|
||||
throw new Error("cleanup failed");
|
||||
};
|
||||
}
|
||||
let result;
|
||||
const pending = finalizeSessionLogs(webContents, { ipcMain }).then((success) => { result = success; });
|
||||
await tick();
|
||||
assert.equal(result, false, "failed setup must finish before the timeout");
|
||||
await pending;
|
||||
assert.equal(ipcMain.listenerCount("app:session-logs-finalized"), 0);
|
||||
assert.equal(warn.mock.callCount(), 1);
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(warn.mock.callCount(), 1, "the cleared timeout must not run after finalization");
|
||||
});
|
||||
}
|
||||
|
||||
test("tray quit finalizes only after the dirty guard accepts and waits before quitting", async () => {
|
||||
const h = renderer();
|
||||
let finishCapture;
|
||||
let captures = 0;
|
||||
let quits = 0;
|
||||
h.api.onFinalizeSessionLogs(() => {
|
||||
captures++;
|
||||
return new Promise((resolve) => { finishCapture = resolve; });
|
||||
});
|
||||
let shutdown;
|
||||
const options = {
|
||||
event: { preventDefault() {} }, mainWindows: [{ webContents: h.webContents }],
|
||||
queryDirtyEditors: async () => true,
|
||||
commitQuit: () => { shutdown = finalizeSessionLogs(h.webContents, h).then(() => { quits++; }); },
|
||||
dialog: { showMessageBoxSync() {} },
|
||||
};
|
||||
await handleBeforeQuit(options);
|
||||
assert.equal(captures, 0);
|
||||
await handleBeforeQuit({ ...options, queryDirtyEditors: async () => false });
|
||||
await tick();
|
||||
assert.equal(captures, 1);
|
||||
assert.equal(quits, 0);
|
||||
finishCapture(); await shutdown;
|
||||
assert.equal(quits, 1);
|
||||
});
|
||||
|
||||
test("production quit commit awaits renderer logs and file streams before plugins and process exit", async () => {
|
||||
const source = readFileSync(require.resolve("../main.cjs"), "utf8");
|
||||
const start = source.indexOf(" const commitQuit = () => {");
|
||||
const end = source.indexOf('\n app.on("before-quit"', start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const calls = [];
|
||||
let finishCapture;
|
||||
let finishStreams;
|
||||
const hiddenWindow = { webContents: {} };
|
||||
const context = {
|
||||
console,
|
||||
getWindowManager: () => ({ setIsQuitting: () => calls.push("quitting"), getAppContentWindows: () => [hiddenWindow] }),
|
||||
electronModule: { ipcMain: {} },
|
||||
finalizeSessionLogs: (wc) => {
|
||||
assert.equal(wc, hiddenWindow.webContents);
|
||||
calls.push("capture");
|
||||
return new Promise((resolve) => { finishCapture = resolve; });
|
||||
},
|
||||
sessionLogStreamManager: { cleanupAll: () => {
|
||||
calls.push("streams");
|
||||
return new Promise((resolve) => { finishStreams = resolve; });
|
||||
} },
|
||||
appLockController: { setLocked: () => calls.push("lock") },
|
||||
runPluginShutdown: async () => { calls.push("plugins"); return { timedOut: false }; },
|
||||
app: { quit: () => calls.push("quit") },
|
||||
quitGuardChannelBusy: false, quitConfirmed: false,
|
||||
};
|
||||
vm.runInNewContext(`${source.slice(start, end)}; commitQuit();`, context);
|
||||
assert.deepEqual(calls, ["lock", "quitting", "capture"]);
|
||||
assert.equal(context.quitGuardChannelBusy, true);
|
||||
finishCapture(); await tick();
|
||||
assert.deepEqual(calls, ["lock", "quitting", "capture", "streams"]);
|
||||
assert.equal(context.quitConfirmed, false);
|
||||
finishStreams(); await tick();
|
||||
assert.deepEqual(calls, ["lock", "quitting", "capture", "streams", "plugins", "quit"]);
|
||||
assert.equal(context.quitConfirmed, true);
|
||||
});
|
||||
@@ -16,10 +16,29 @@ const {
|
||||
startStream,
|
||||
startStreamToFile,
|
||||
stopStream,
|
||||
cleanupAll,
|
||||
} = require("./sessionLogStreamManager.cjs");
|
||||
|
||||
const TEMP_ROOT = path.join(__dirname, ".tmp-session-log-stream-tests");
|
||||
|
||||
test("quit cleanup finishes all pending file captures before resolving", async () => {
|
||||
const directory = path.join(TEMP_ROOT, `quit-${Date.now()}`);
|
||||
try {
|
||||
for (const sessionId of ["quit-one", "quit-two"]) {
|
||||
startStreamToFile(sessionId, { filePath: path.join(directory, `${sessionId}.log`), format: "raw" });
|
||||
appendData(sessionId, `output before quit: ${sessionId}\r\n`);
|
||||
}
|
||||
await cleanupAll();
|
||||
for (const sessionId of ["quit-one", "quit-two"]) {
|
||||
assert.equal(hasStream(sessionId), false);
|
||||
assert.equal(fs.readFileSync(path.join(directory, `${sessionId}.log`), "utf8"), `output before quit: ${sessionId}\r\n`);
|
||||
}
|
||||
} finally {
|
||||
await cleanupAll();
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("txt stream live snapshots include pending ED2 cleared screens", async () => {
|
||||
const directory = path.join(TEMP_ROOT, `stream-${Date.now()}-${Math.random().toString(16).slice(2)}`);
|
||||
const sessionId = `session-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
|
||||
@@ -1913,6 +1913,16 @@ function createSessionBackedSftpClient(sessionId, sshClient, options = {}) {
|
||||
const attrs = await statAsync(sftp, remotePath);
|
||||
return statResultFromAttrs(attrs);
|
||||
},
|
||||
async lstat(remotePath) {
|
||||
const sftp = await requireSftpChannel(client);
|
||||
// Copy preflights must inspect link nodes, never their followed targets.
|
||||
// lstatAsync falls back to STAT when LSTAT is absent, so reject first.
|
||||
if (typeof sftp.lstat !== "function") {
|
||||
throw Object.assign(new Error("Remote server does not support LSTAT"), { code: "ENOTSUP" });
|
||||
}
|
||||
const attrs = await lstatAsync(sftp, remotePath);
|
||||
return statResultFromAttrs(attrs);
|
||||
},
|
||||
async realPath(remotePath) {
|
||||
const sftp = await requireSftpChannel(client);
|
||||
return await realpathAsync(sftp, remotePath);
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { Readable, PassThrough } = require("node:stream");
|
||||
const sftpBridge = require("./sftpBridge.cjs");
|
||||
const transferBridge = require("./transferBridge.cjs");
|
||||
|
||||
const missing = () => Object.assign(new Error("ENOENT"), { code: 2 });
|
||||
|
||||
async function openSessionClient(t, { sourceIsLink = false, targetExists = false } = {}) {
|
||||
const commands = [];
|
||||
const channel = new EventEmitter();
|
||||
channel.readdir = (_path, callback) => callback(null, []);
|
||||
channel.mkdir = (_path, callback) => callback(null);
|
||||
channel.unlink = (_path, callback) => callback(null);
|
||||
channel.stat = (remotePath, callback) => {
|
||||
if (String(remotePath) === "/target/file" && !targetExists) return callback(missing());
|
||||
callback(null, { size: 66, mode: 0o100640, mtime: 1 });
|
||||
};
|
||||
channel.lstat = (remotePath, callback) => {
|
||||
if (String(remotePath) === "/target" && !targetExists) return callback(missing());
|
||||
callback(null, { size: 66, mode: sourceIsLink ? 0o120777 : 0o100640, mtime: 1 });
|
||||
};
|
||||
channel.createReadStream = () => Readable.from([Buffer.alloc(66)]);
|
||||
const connection = {
|
||||
sftp(callback) { callback(null, channel); },
|
||||
exec(command, callback) {
|
||||
commands.push(command);
|
||||
const stream = new PassThrough();
|
||||
stream.stderr = new PassThrough();
|
||||
callback(null, stream);
|
||||
setImmediate(() => stream.emit("close", 0));
|
||||
},
|
||||
};
|
||||
const clients = new Map();
|
||||
sftpBridge.init({
|
||||
electronModule: { webContents: { fromId: () => null } },
|
||||
sessions: new Map([["copy-session", { conn: connection }]]),
|
||||
sftpClients: clients,
|
||||
});
|
||||
transferBridge.init({ sftpClients: clients });
|
||||
const { sftpId } = await sftpBridge.openSftpForSession(null, {
|
||||
sessionId: "copy-session", fileProtocol: "sftp",
|
||||
});
|
||||
t.after(() => sftpBridge.closeSftp(null, { sftpId }));
|
||||
return { client: clients.get(sftpId), channel, commands, sftpId };
|
||||
}
|
||||
|
||||
test("same-host file copy executes cp using the actual session-backed client (#4207)", async (t) => {
|
||||
const { commands, sftpId } = await openSessionClient(t);
|
||||
const result = await transferBridge.startTransfer({ sender: { send() {} } }, {
|
||||
transferId: "session-backed-file-copy",
|
||||
sourcePath: "/source/file", targetPath: "/target/file",
|
||||
sourceType: "sftp", targetType: "sftp",
|
||||
sourceSftpId: sftpId, targetSftpId: sftpId,
|
||||
sourceEncoding: "utf-8", targetEncoding: "utf-8",
|
||||
totalBytes: 66, sameHost: true, resumable: false,
|
||||
});
|
||||
assert.deepEqual(commands, ["cp -a '/source/file' '/target/file'"]);
|
||||
assert.equal(result.error, undefined);
|
||||
});
|
||||
|
||||
for (const sourceIsLink of [false, true]) {
|
||||
test(`session-backed LSTAT preserves link classification (${sourceIsLink})`, async (t) => {
|
||||
const { client } = await openSessionClient(t, { sourceIsLink });
|
||||
assert.equal((await client.lstat("/source/file")).isSymbolicLink, sourceIsLink);
|
||||
assert.equal((await client.stat("/source/file")).isSymbolicLink, false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const unsupported of ["missing-method", "server-error"]) {
|
||||
test(`session-backed LSTAT never follows STAT on ${unsupported}`, async (t) => {
|
||||
const { client, channel } = await openSessionClient(t);
|
||||
let statCalls = 0;
|
||||
channel.stat = () => { statCalls++; throw new Error("must not follow symlinks"); };
|
||||
if (unsupported === "missing-method") delete channel.lstat;
|
||||
else channel.lstat = (_path, callback) => callback(Object.assign(new Error("unsupported"), { code: 8 }));
|
||||
await assert.rejects(() => client.lstat("/source/file"), error =>
|
||||
error.code === (unsupported === "missing-method" ? "ENOTSUP" : 8));
|
||||
assert.equal(statCalls, 0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const targetExists of [false, true]) {
|
||||
test(`session-backed directory cp preserves the destination merge guard (${targetExists})`, async (t) => {
|
||||
const { commands, sftpId } = await openSessionClient(t, { targetExists });
|
||||
const result = await transferBridge.sameHostCopyDirectory({ sender: { send() {} } }, {
|
||||
transferId: `session-backed-directory-copy-${targetExists}`,
|
||||
sftpId, sourcePath: "/source", targetPath: "/target", encoding: "utf-8",
|
||||
});
|
||||
assert.equal(result.success, !targetExists);
|
||||
assert.deepEqual(commands, targetExists ? [] : ["cp -ra '/source/.' '/target/'"]);
|
||||
});
|
||||
}
|
||||
@@ -41,6 +41,8 @@
|
||||
* leaves the Mosh stats bar empty (graceful degradation), never weakens
|
||||
* security.
|
||||
*/
|
||||
const { extractCertificatePublicKey } = require("../../../domain/sshPublicKey.shared.cjs");
|
||||
|
||||
function createSystemKnownHostsApi(ctx) {
|
||||
const { fs, path, os, crypto, log } = ctx;
|
||||
|
||||
@@ -64,7 +66,7 @@ function createSystemKnownHostsApi(ctx) {
|
||||
}
|
||||
if (blob.length === 0) return "";
|
||||
return stripFingerprintPadding(
|
||||
crypto.createHash("sha256").update(blob).digest("base64"),
|
||||
crypto.createHash("sha256").update(extractCertificatePublicKey(blob) || blob).digest("base64"),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -176,7 +178,7 @@ function createSystemKnownHostsApi(ctx) {
|
||||
|
||||
// Parse one known_hosts line into { revoked, certAuthority, hostField,
|
||||
// keyType, fingerprint } or null when it is a comment / blank / malformed.
|
||||
// The fingerprint is the SHA-256 of the line's key blob.
|
||||
// Certificates pin their underlying key, just like the live verifier.
|
||||
const parseKnownHostsLine = (rawLine) => {
|
||||
const line = String(rawLine || "").trim();
|
||||
if (!line || line.startsWith("#")) return null;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const crypto = require("node:crypto");
|
||||
const { mintHostCertificates, sshKeygenSkip } = require("../fixtures/hostCertificates.test.fixture.cjs");
|
||||
const { describeHostKey } = require("../hostKeyVerifier.cjs");
|
||||
const path = require("node:path");
|
||||
const os = require("node:os");
|
||||
|
||||
@@ -59,6 +61,22 @@ function hashedHostField(token, salt = crypto.randomBytes(20)) {
|
||||
|
||||
const HOME_KH = path.join(os.homedir(), ".ssh", "known_hosts");
|
||||
|
||||
test("system certificate entries pin the inner key across renewals without CA trust", { skip: sshKeygenSkip }, (t) => {
|
||||
const { first, renewed, different } = mintHostCertificates(t);
|
||||
const { api } = makeApi({ [HOME_KH]: `example.com ${first.line}\n` });
|
||||
const liveFingerprint = describeHostKey(renewed.blob).fingerprint;
|
||||
assert.equal(api.parseKnownHostsLine(`example.com ${first.line}`).fingerprint, liveFingerprint);
|
||||
assert.equal(api.isHostKeyTrustedBySystem({ hostname: "example.com", fingerprint: liveFingerprint }), true);
|
||||
assert.equal(api.isHostKeyTrustedBySystem({
|
||||
hostname: "example.com", fingerprint: describeHostKey(different.blob).fingerprint,
|
||||
}), false);
|
||||
|
||||
const revoked = makeApi({ [HOME_KH]: `example.com ${first.line}\n@revoked example.com ${renewed.line}\n` });
|
||||
assert.equal(revoked.api.isHostKeyTrustedBySystem({ hostname: "example.com", fingerprint: liveFingerprint }), false);
|
||||
const ca = makeApi({ [HOME_KH]: `@cert-authority example.com ${first.line}\n` });
|
||||
assert.equal(ca.api.isHostKeyTrustedBySystem({ hostname: "example.com", fingerprint: liveFingerprint }), false);
|
||||
});
|
||||
|
||||
test("system known_hosts paths include the OpenSSH defaults for the platform", () => {
|
||||
const { api } = makeApi();
|
||||
const paths = api.getSystemKnownHostsPaths();
|
||||
|
||||
@@ -959,6 +959,9 @@ async function buildLocalSessionEnv(
|
||||
) {
|
||||
const { buildTerminalProcessEnv } = require("./httpNetworkProxyBridge.cjs");
|
||||
const env = { ...buildTerminalProcessEnv(baseEnv), ...(payload?.env || {}) };
|
||||
// AppImage's ARGV0 makes zsh rename external commands, including ssh. Xorg
|
||||
// then mistakes ssh's X11 connection for a local client and sends unusable fds.
|
||||
delete env.ARGV0;
|
||||
if (platform !== "win32") return env;
|
||||
|
||||
const { getPathEnvKey, resolveWindowsLivePath } = require("./ai/shellUtils.cjs");
|
||||
|
||||
@@ -37,6 +37,15 @@ const STALE_PATH =
|
||||
const LIVE_PATH =
|
||||
"C:\\Users\\me\\.herdr\\packages\\standalone\\releases\\0.9.1-x86_64-pc-windows-msvc;C:\\Windows\\System32";
|
||||
|
||||
test("buildLocalSessionEnv strips AppImage ARGV0 without changing the base env", async () => {
|
||||
const baseEnv = { PATH: "/usr/bin:/bin", ARGV0: "/opt/Netcatty.AppImage" };
|
||||
const env = await bridge.buildLocalSessionEnv({}, { baseEnv, platform: "linux" });
|
||||
|
||||
assert.equal(Object.hasOwn(env, "ARGV0"), false);
|
||||
assert.equal(env.PATH, baseEnv.PATH);
|
||||
assert.equal(baseEnv.ARGV0, "/opt/Netcatty.AppImage");
|
||||
});
|
||||
|
||||
test("buildLocalSessionEnv keeps the captured PATH untouched off Windows", async () => {
|
||||
const env = await bridge.buildLocalSessionEnv(
|
||||
{ env: { NETCATTY_MARKER: "1" } },
|
||||
|
||||
@@ -7174,6 +7174,13 @@ async function startTransferNow(event, payload, onProgress) {
|
||||
const singleChannelCopy = srcClient.__netcattySingleChannelSsh || sshClient?.__netcattySingleChannelSsh;
|
||||
if (sshClient && typeof sshClient.exec === 'function' && !singleChannelCopy) {
|
||||
try {
|
||||
// cp -a preserves link nodes; the SFTP fallback follows target bytes.
|
||||
// A failed lstat also falls through to that existing route.
|
||||
const sourceAttrs = await runCancelablePreflight(() => srcClient.lstat(
|
||||
encodePathForSession(sourceSftpId, sourcePath, resolvedSourceEnc),
|
||||
));
|
||||
if (sourceAttrs.isSymbolicLink) throw new Error("Source is a symbolic link");
|
||||
|
||||
const dir = path.dirname(targetPath).replace(/\\/g, '/');
|
||||
try {
|
||||
await runTransferAbortableOperation(transfer, (signal) => ensureRemoteDirForSession(
|
||||
@@ -7186,6 +7193,18 @@ async function startTransferNow(event, payload, onProgress) {
|
||||
if (transfer.cancelled || transfer.signal?.aborted) throw new Error("Transfer cancelled");
|
||||
}
|
||||
|
||||
const targetClient = sftpClients.get(targetSftpId);
|
||||
let existingRemoteMode = null;
|
||||
try {
|
||||
const attrs = await runCancelablePreflight(() => targetClient.stat(
|
||||
encodePathForSession(targetSftpId, targetPath, resolvedTargetEnc),
|
||||
));
|
||||
if (Number.isFinite(attrs?.mode)) existingRemoteMode = attrs.mode & 0o7777;
|
||||
} catch {
|
||||
// Missing destinations or failed stats need no permission restore.
|
||||
if (transfer.cancelled || transfer.signal?.aborted) throw new Error("Transfer cancelled");
|
||||
}
|
||||
|
||||
const escapedSource = sourcePath.replace(/'/g, "'\\''");
|
||||
const escapedTarget = targetPath.replace(/'/g, "'\\''");
|
||||
const command = `cp -a '${escapedSource}' '${escapedTarget}'`;
|
||||
@@ -7194,6 +7213,13 @@ async function startTransferNow(event, payload, onProgress) {
|
||||
if (result.code === 0) {
|
||||
sendProgress(fileSize, fileSize);
|
||||
sameHostDone = true;
|
||||
await restoreRemoteUploadModeBestEffort(
|
||||
targetClient,
|
||||
targetSftpId,
|
||||
targetPath,
|
||||
resolvedTargetEnc,
|
||||
existingRemoteMode,
|
||||
);
|
||||
} else if (result.code === 127) {
|
||||
// Exit 127 = command not found — cache to skip future attempts
|
||||
cpUnavailableSet.add(srcClient);
|
||||
@@ -8204,11 +8230,28 @@ async function sameHostCopyDirectory(event, payload) {
|
||||
}
|
||||
if (cpUnavailableSet.has(client)) return { success: false };
|
||||
|
||||
const resolvedEncoding = resolveEncodingForRequest(sftpId, encoding);
|
||||
if (resolvedEncoding && resolvedEncoding !== 'utf-8') {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const sshClient = client.client;
|
||||
if (!sshClient || typeof sshClient.exec !== 'function') {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
// Merges must use recursive SFTP transfers to preserve destination child modes.
|
||||
// Only a clearly missing target is safe for the remote cp optimization.
|
||||
try {
|
||||
await runTransferCancelablePreflight(transfer, () => client.lstat(
|
||||
encodePathForSession(sftpId, targetPath, resolvedEncoding),
|
||||
));
|
||||
return { success: false };
|
||||
} catch (error) {
|
||||
if (transfer.cancelled) throw new Error("Transfer cancelled");
|
||||
if (!isMissingRemoteStageError(error)) return { success: false };
|
||||
}
|
||||
|
||||
if (transfer.cancelled) throw new Error("Transfer cancelled");
|
||||
const lifecyclePayload = {
|
||||
...payload,
|
||||
@@ -8233,8 +8276,7 @@ async function sameHostCopyDirectory(event, payload) {
|
||||
if (transfer.cancelled) throw new Error("Transfer cancelled");
|
||||
}
|
||||
|
||||
// Use "source/." to copy directory *contents* into target, preserving merge
|
||||
// semantics consistent with the recursive per-file transfer path.
|
||||
// Use "source/." to copy directory *contents* into the newly created target.
|
||||
// Without "/.", `cp -ra source target` would create target/source/ when target exists.
|
||||
const escapedSource = sourcePath.replace(/'/g, "'\\''");
|
||||
const escapedTarget = targetPath.replace(/'/g, "'\\''");
|
||||
|
||||
@@ -106,6 +106,7 @@ test("same-host cp capability cache follows the live SFTP client, not a recycled
|
||||
bridge.init({ sftpClients });
|
||||
|
||||
const makeClient = (exitCode, calls) => ({
|
||||
async lstat() { throw Object.assign(new Error("ENOENT"), { code: 2 }); },
|
||||
client: {
|
||||
exec(_command, callback) {
|
||||
calls.count += 1;
|
||||
|
||||
@@ -1294,7 +1294,9 @@ test("server-to-server resume cancellation settles while source identity verific
|
||||
t.after(async () => fs.promises.rm(tempPath, { force: true }));
|
||||
let markPrefixStarted;
|
||||
const prefixStarted = new Promise((resolve) => { markPrefixStarted = resolve; });
|
||||
let execCalls = 0;
|
||||
const sourceClient = {
|
||||
client: { exec() { execCalls += 1; throw new Error("checkpointed copies must not exec cp"); } },
|
||||
sftp: createFastSftp({
|
||||
createReadStream() {
|
||||
markPrefixStarted();
|
||||
@@ -1317,7 +1319,7 @@ test("server-to-server resume cancellation settles while source identity verific
|
||||
targetSftpId: "target",
|
||||
totalBytes: 8,
|
||||
resumable: true,
|
||||
sameHost: false,
|
||||
sameHost: true,
|
||||
resumeStage: "download",
|
||||
checkpointBytes: 4,
|
||||
downloadCheckpointBytes: 4,
|
||||
@@ -1332,6 +1334,7 @@ test("server-to-server resume cancellation settles while source identity verific
|
||||
]);
|
||||
|
||||
assert.match(result.error || "", /cancel/i);
|
||||
assert.equal(execCalls, 0, "same-host resume must verify its saved prefix instead of running cp");
|
||||
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:cancelled"), true);
|
||||
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
|
||||
});
|
||||
@@ -13243,6 +13246,119 @@ test("same-host directory copy rejected by a committed close leaves no lease or
|
||||
assert.equal(sftpTransferSessionLeaseStore.getLeaseCount(sftpId), 0);
|
||||
});
|
||||
|
||||
test("same-host directory copy skips cp when auto encoding resolves to non-UTF-8", async (t) => {
|
||||
const {
|
||||
sftpTransferSessionLeaseStore,
|
||||
} = require("./sftpTransferSessionLease.cjs");
|
||||
sftpTransferSessionLeaseStore.resetForTests();
|
||||
t.after(() => sftpTransferSessionLeaseStore.resetForTests());
|
||||
|
||||
const sftpId = "same-host-directory-auto-gb18030";
|
||||
// Seed the session's resolved encoding before the copy requests auto.
|
||||
sftpBridge.resolveEncodingForRequest(sftpId, "gb18030");
|
||||
let execCalls = 0;
|
||||
transferBridge.init({
|
||||
sftpClients: new Map([[sftpId, {
|
||||
client: {
|
||||
exec(_command, callback) {
|
||||
execCalls += 1;
|
||||
const stream = new EventEmitter();
|
||||
stream.stderr = new EventEmitter();
|
||||
callback(null, stream);
|
||||
setImmediate(() => stream.emit("close", 0));
|
||||
},
|
||||
},
|
||||
}]]),
|
||||
});
|
||||
const sender = createSender();
|
||||
|
||||
const result = await transferBridge.sameHostCopyDirectory(
|
||||
{ sender },
|
||||
{
|
||||
transferId: "same-host-directory-auto-gb18030-copy",
|
||||
sftpId,
|
||||
sourcePath: "/source",
|
||||
targetPath: "/\u76ee\u6807",
|
||||
encoding: "auto",
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(execCalls, 0);
|
||||
assert.equal(result.success, false);
|
||||
assert.deepEqual(sender.sent, []);
|
||||
assert.equal(transferBridge._getActiveTransferCountForTests(), 0);
|
||||
assert.equal(sftpTransferSessionLeaseStore.getLeaseCount(sftpId), 0);
|
||||
});
|
||||
|
||||
for (const targetState of ["existing", "missing", "stat-error"]) {
|
||||
test(`same-host directory copy ${targetState} target uses cp only for a fresh destination`, async (t) => {
|
||||
const { sftpTransferSessionLeaseStore } = require("./sftpTransferSessionLease.cjs");
|
||||
sftpTransferSessionLeaseStore.resetForTests();
|
||||
t.after(() => sftpTransferSessionLeaseStore.resetForTests());
|
||||
const sftpId = `same-host-directory-${targetState}`;
|
||||
const commands = [];
|
||||
const mkdirs = [];
|
||||
let targetExists = targetState === "existing";
|
||||
const client = {
|
||||
async lstat(remotePath) {
|
||||
assert.equal(String(remotePath), "/target");
|
||||
assert.deepEqual(mkdirs, [], "check the destination before ensuring it");
|
||||
if (targetState === "stat-error") {
|
||||
throw Object.assign(new Error("Permission denied"), { code: 3 });
|
||||
}
|
||||
if (!targetExists) throw Object.assign(new Error("ENOENT"), { code: 2 });
|
||||
return { isDirectory: true };
|
||||
},
|
||||
sftp: createFastSftp({
|
||||
stat(_remotePath, callback) {
|
||||
if (!targetExists) {
|
||||
callback(Object.assign(new Error("ENOENT"), { code: 2 }));
|
||||
return;
|
||||
}
|
||||
callback(null, { isDirectory: () => true });
|
||||
},
|
||||
mkdir(remotePath, callback) {
|
||||
mkdirs.push(String(remotePath));
|
||||
targetExists = true;
|
||||
callback(null);
|
||||
},
|
||||
}),
|
||||
client: {
|
||||
exec(command, callback) {
|
||||
commands.push(command);
|
||||
assert.equal(targetExists, true, "create the fresh destination before cp");
|
||||
const stream = new PassThrough();
|
||||
stream.stderr = new PassThrough();
|
||||
callback(null, stream);
|
||||
setImmediate(() => stream.emit("close", 0));
|
||||
},
|
||||
},
|
||||
};
|
||||
const sftpClients = new Map([[sftpId, client]]);
|
||||
transferBridge.init({ sftpClients });
|
||||
sftpBridge.init({ sftpClients });
|
||||
const sender = createSender();
|
||||
const result = await transferBridge.sameHostCopyDirectory({ sender }, {
|
||||
transferId: `${sftpId}-copy`, sftpId,
|
||||
sourcePath: "/source", targetPath: "/target", encoding: "utf-8",
|
||||
});
|
||||
|
||||
if (targetState === "missing") {
|
||||
assert.deepEqual(result, { success: true });
|
||||
assert.deepEqual(commands, ["cp -ra '/source/.' '/target/'"]);
|
||||
assert.deepEqual(mkdirs, ["/target"]);
|
||||
assert.equal(sender.sent.some(entry => entry.channel === "netcatty:transfer:complete"), true);
|
||||
} else {
|
||||
assert.deepEqual(result, { success: false });
|
||||
assert.deepEqual(commands, []);
|
||||
assert.deepEqual(mkdirs, []);
|
||||
assert.deepEqual(sender.sent, []);
|
||||
}
|
||||
assert.equal(transferBridge._getActiveTransferCountForTests(), 0);
|
||||
assert.equal(sftpTransferSessionLeaseStore.getLeaseCount(sftpId), 0);
|
||||
});
|
||||
}
|
||||
|
||||
test("same-host directory copy cancellation aborts cp and releases its lease", async (t) => {
|
||||
const {
|
||||
sftpTransferSessionLeaseStore,
|
||||
@@ -13259,6 +13375,7 @@ test("same-host directory copy cancellation aborts cp and releases its lease", a
|
||||
stream.end = () => {};
|
||||
stream.destroy = () => {};
|
||||
const client = {
|
||||
async lstat() { throw Object.assign(new Error("ENOENT"), { code: 2 }); },
|
||||
client: {
|
||||
exec(_command, callback) {
|
||||
callback(null, stream);
|
||||
@@ -13342,6 +13459,7 @@ test("same-host file cp cancellation releases the shared session lease", async (
|
||||
stream.end = () => {};
|
||||
stream.destroy = () => {};
|
||||
const client = {
|
||||
lstat: async () => ({ isSymbolicLink: false }),
|
||||
client: {
|
||||
exec(_command, callback) {
|
||||
callback(null, stream);
|
||||
@@ -15139,3 +15257,209 @@ test("pending channel-open skips the fastPut reopen and uses the shared channel"
|
||||
assert.ok(sharedWrites >= 1);
|
||||
assert.deepEqual(remoteFiles.get(targetPath), payload);
|
||||
});
|
||||
|
||||
test("same-host file cp restores existing destination mode", async () => {
|
||||
const commands = [];
|
||||
const chmods = [];
|
||||
let targetMode = 0o100600;
|
||||
let downloads = 0;
|
||||
let uploads = 0;
|
||||
const sourceSftp = createFastSftp({
|
||||
open() { downloads++; throw new Error("unexpected download"); },
|
||||
});
|
||||
const sourceClient = {
|
||||
sftp: sourceSftp,
|
||||
lstat: async () => ({ isSymbolicLink: false }),
|
||||
stat: async () => ({ size: 64, mode: 0o100644 }),
|
||||
client: {
|
||||
sftp: (callback) => callback(null, sourceSftp),
|
||||
exec(command, callback) {
|
||||
commands.push(command);
|
||||
targetMode = 0o100644;
|
||||
const stream = new PassThrough();
|
||||
stream.stderr = new PassThrough();
|
||||
callback(null, stream);
|
||||
setImmediate(() => stream.emit("close", 0));
|
||||
},
|
||||
},
|
||||
};
|
||||
const targetClient = {
|
||||
sftp: createFastSftp({
|
||||
open() { uploads++; throw new Error("unexpected upload"); },
|
||||
}),
|
||||
stat: async () => ({ size: 64, mode: targetMode }),
|
||||
chmod: async (remotePath, mode) => {
|
||||
chmods.push([String(remotePath), mode]);
|
||||
targetMode = mode;
|
||||
},
|
||||
};
|
||||
transferBridge.init({ sftpClients: new Map([["source", sourceClient], ["target", targetClient]]) });
|
||||
const result = await transferBridge.startTransfer({ sender: createSender() }, {
|
||||
transferId: `same-host-cp-mode-${crypto.randomUUID()}`,
|
||||
sourcePath: "/source/payload.bin", targetPath: "/target/payload.bin",
|
||||
sourceType: "sftp", targetType: "sftp",
|
||||
sourceSftpId: "source", targetSftpId: "target",
|
||||
sourceEncoding: "utf-8", targetEncoding: "utf-8",
|
||||
totalBytes: 64,
|
||||
sameHost: true, resumable: false,
|
||||
});
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.deepEqual(commands, ["cp -a '/source/payload.bin' '/target/payload.bin'"]);
|
||||
assert.deepEqual(chmods, [["/target/payload.bin", 0o600]]);
|
||||
assert.equal(targetMode, 0o600);
|
||||
assert.equal(downloads, 0);
|
||||
assert.equal(uploads, 0);
|
||||
});
|
||||
|
||||
for (const sourceState of ["symlink", "lstat-error"]) {
|
||||
test(`same-host file cp skips a source ${sourceState} and downloads/uploads target bytes`, async (t) => {
|
||||
const transferId = `same-host-cp-fallback-${crypto.randomUUID()}`;
|
||||
const sourcePath = "/opt/app/config";
|
||||
const targetPath = "/tmp/app/config";
|
||||
const payload = Buffer.from("contents of ../shared/config");
|
||||
const commands = [];
|
||||
let reads = 0;
|
||||
let remote = Buffer.alloc(0);
|
||||
let promoted = false;
|
||||
const { sftp: sourceSftp } = createPipelinedDownloadSftp(payload);
|
||||
const originalRead = sourceSftp.read;
|
||||
sourceSftp.read = (...args) => { reads++; originalRead(...args); };
|
||||
const sourceClient = {
|
||||
sftp: sourceSftp,
|
||||
async lstat(remotePath) {
|
||||
assert.equal(String(remotePath), sourcePath);
|
||||
if (sourceState === "lstat-error") throw new Error("lstat unsupported");
|
||||
return { isSymbolicLink: true, size: "../shared/config".length };
|
||||
},
|
||||
stat: async () => ({ size: payload.length }),
|
||||
client: {
|
||||
sftp: (callback) => callback(null, sourceSftp),
|
||||
exec(command, callback) {
|
||||
commands.push(command);
|
||||
callback(new Error("unexpected exec"));
|
||||
},
|
||||
},
|
||||
};
|
||||
const targetSftp = createFastSftp({
|
||||
open(_path, _flags, callback) { callback(null, Buffer.from("target-handle")); },
|
||||
write(_handle, buffer, offset, length, position, callback) {
|
||||
if (remote.length < position + length) {
|
||||
remote = Buffer.concat([remote, Buffer.alloc(position + length - remote.length)]);
|
||||
}
|
||||
buffer.copy(remote, position, offset, offset + length);
|
||||
callback(null);
|
||||
},
|
||||
close(_handle, callback) { callback(null); },
|
||||
});
|
||||
const targetClient = {
|
||||
sftp: targetSftp,
|
||||
client: { sftp: (callback) => callback(null, targetSftp) },
|
||||
async stat(remotePath) {
|
||||
if (String(remotePath) === targetPath && remote.length === 0) {
|
||||
throw Object.assign(new Error("ENOENT"), { code: 2 });
|
||||
}
|
||||
return { size: remote.length };
|
||||
},
|
||||
rename: async () => { promoted = true; },
|
||||
delete: async () => {},
|
||||
};
|
||||
transferBridge.init({ sftpClients: new Map([["source", sourceClient], ["target", targetClient]]) });
|
||||
const localStage = tempDirBridge.getTransferTempFilePath(transferId, "config");
|
||||
t.after(async () => fs.promises.rm(localStage, { force: true }));
|
||||
const result = await transferBridge.startTransfer({ sender: createSender() }, {
|
||||
transferId, sourcePath, targetPath,
|
||||
sourceType: "sftp", targetType: "sftp",
|
||||
sourceSftpId: "source", targetSftpId: "target",
|
||||
sourceEncoding: "utf-8", targetEncoding: "utf-8",
|
||||
totalBytes: payload.length, sameHost: true, resumable: false,
|
||||
});
|
||||
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.deepEqual(commands, [], "source symlinks and lstat failures must bypass cp -a");
|
||||
assert.ok(reads > 0, "fallback must download the followed source contents");
|
||||
assert.deepEqual(remote, payload, "fallback must upload target bytes rather than the link node");
|
||||
assert.equal(promoted, true);
|
||||
});
|
||||
}
|
||||
|
||||
for (const cpResult of [0, 127, 1, "exec-error"]) {
|
||||
test(`fresh same-host file cp result ${cpResult} preserves copy/fallback behavior (#4207)`, async (t) => {
|
||||
const transferId = `same-host-cp-${crypto.randomUUID()}`;
|
||||
const payload = Buffer.from("same-host ordinary SFTP copy");
|
||||
const commands = [];
|
||||
const chmods = [];
|
||||
let reads = 0;
|
||||
let remote = Buffer.alloc(0);
|
||||
let promoted = false;
|
||||
const { sftp: sourceSftp } = createPipelinedDownloadSftp(payload);
|
||||
const originalRead = sourceSftp.read;
|
||||
sourceSftp.read = (...args) => { reads++; originalRead(...args); };
|
||||
const sourceClient = {
|
||||
sftp: sourceSftp,
|
||||
lstat: async () => ({ isSymbolicLink: false }),
|
||||
stat: async () => ({ size: payload.length }),
|
||||
client: {
|
||||
sftp: (callback) => callback(null, sourceSftp),
|
||||
exec(command, callback) {
|
||||
commands.push(command);
|
||||
if (cpResult === "exec-error") { callback(new Error("exec denied")); return; }
|
||||
const stream = new PassThrough();
|
||||
stream.stderr = new PassThrough();
|
||||
callback(null, stream);
|
||||
setImmediate(() => stream.emit("close", cpResult));
|
||||
},
|
||||
},
|
||||
};
|
||||
const targetSftp = createFastSftp({
|
||||
open(_path, _flags, callback) { callback(null, Buffer.from("target-handle")); },
|
||||
write(_handle, buffer, offset, length, position, callback) {
|
||||
if (remote.length < position + length) {
|
||||
remote = Buffer.concat([remote, Buffer.alloc(position + length - remote.length)]);
|
||||
}
|
||||
buffer.copy(remote, position, offset, offset + length);
|
||||
callback(null);
|
||||
},
|
||||
close(_handle, callback) { callback(null); },
|
||||
});
|
||||
const targetClient = {
|
||||
sftp: targetSftp,
|
||||
client: { sftp: (callback) => callback(null, targetSftp) },
|
||||
stat: async (remotePath) => {
|
||||
if (String(remotePath) === "/target/payload.bin" && remote.length === 0) {
|
||||
throw Object.assign(new Error("ENOENT"), { code: 2 });
|
||||
}
|
||||
return { size: remote.length };
|
||||
},
|
||||
chmod: async (...args) => { chmods.push(args); },
|
||||
rename: async () => { promoted = true; },
|
||||
delete: async () => {},
|
||||
};
|
||||
transferBridge.init({ sftpClients: new Map([["source", sourceClient], ["target", targetClient]]) });
|
||||
const localStage = tempDirBridge.getTransferTempFilePath(transferId, "payload.bin");
|
||||
t.after(async () => fs.promises.rm(localStage, { force: true }));
|
||||
const sender = createSender();
|
||||
const result = await transferBridge.startTransfer({ sender }, {
|
||||
transferId,
|
||||
sourcePath: "/source/payload.bin",
|
||||
targetPath: "/target/payload.bin",
|
||||
sourceType: "sftp", targetType: "sftp",
|
||||
sourceSftpId: "source", targetSftpId: "target",
|
||||
sourceEncoding: "utf-8", targetEncoding: "utf-8",
|
||||
totalBytes: payload.length,
|
||||
sameHost: true, resumable: false,
|
||||
});
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.deepEqual(commands, ["cp -a '/source/payload.bin' '/target/payload.bin'"]);
|
||||
assert.equal(sender.sent.some(entry => entry.channel === "netcatty:transfer:complete"), true);
|
||||
if (cpResult === 0) {
|
||||
assert.deepEqual(chmods, [], "fresh cp must not restore destination permissions");
|
||||
assert.equal(reads, 0, "successful cp must not download the source");
|
||||
assert.equal(remote.length, 0, "successful cp must not upload through SFTP");
|
||||
assert.equal(fs.existsSync(localStage), false);
|
||||
} else {
|
||||
assert.ok(reads > 0, "cp failure must fall back to SFTP download");
|
||||
assert.deepEqual(remote, payload, "fallback must upload the downloaded contents");
|
||||
assert.equal(promoted, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ const {
|
||||
} = require("./windowsWindowChrome.cjs");
|
||||
const { attachDisplayRecovery } = require("./displayRecovery.cjs");
|
||||
const perfTrace = require("../../perfTrace.cjs");
|
||||
const { finalizeSessionLogs } = require("../sessionLogShutdown.cjs");
|
||||
|
||||
const TERMINAL_KEYBOARD_FOCUS = Symbol("netcattyTerminalKeyboardFocus");
|
||||
|
||||
@@ -534,11 +535,12 @@ function createMainWindowApi(ctx) {
|
||||
: false;
|
||||
})();
|
||||
Promise.resolve(dirtyEditorQuery)
|
||||
.then((hasDirty) => {
|
||||
.then(async (hasDirty) => {
|
||||
if (hasDirty) {
|
||||
thisWindowCloseRequested = false;
|
||||
return;
|
||||
}
|
||||
await finalizeSessionLogs(win.webContents, { ipcMain: electronModule.ipcMain });
|
||||
dirtyEditorCloseConfirmed = true;
|
||||
try {
|
||||
win.close();
|
||||
|
||||
@@ -10,10 +10,18 @@ for (const peer of [true, false]) {
|
||||
let ownsTabs = true;
|
||||
let ownerChecks = 0;
|
||||
let dirtyChecks = 0;
|
||||
const ipcMain = new EventEmitter();
|
||||
let finishLogCapture;
|
||||
let logCaptures = 0;
|
||||
let closeToTray = false;
|
||||
class Window extends EventEmitter {
|
||||
constructor() {
|
||||
super(); this.destroyed = false;
|
||||
this.webContents = Object.assign(new EventEmitter(), { id: 71, isDestroyed: () => this.destroyed, setWindowOpenHandler() {}, openDevTools() {}, send() {} });
|
||||
this.webContents = Object.assign(new EventEmitter(), { id: 71, isDestroyed: () => this.destroyed, setWindowOpenHandler() {}, openDevTools() {}, send: (channel, payload) => {
|
||||
if (channel !== "app:finalize-session-logs") return;
|
||||
logCaptures++;
|
||||
finishLogCapture = () => ipcMain.emit("app:session-logs-finalized", { sender: this.webContents }, { requestId: payload.requestId, success: true });
|
||||
} });
|
||||
}
|
||||
close() { const event = { prevented: false, preventDefault() { this.prevented = true; } }; this.emit("close", event); if (!event.prevented) { this.destroyed = true; this.emit("closed"); } }
|
||||
isDestroyed() { return this.destroyed; }
|
||||
@@ -30,7 +38,11 @@ for (const peer of [true, false]) {
|
||||
V8_CACHE_OPTIONS: "code", THEME_COLORS: { light: {} },
|
||||
unhealthyWebContentsIds: new Set(), rendererReadySeenByWebContentsId: new Set(),
|
||||
__dirname, URL, require, console, setTimeout, clearTimeout,
|
||||
getGlobalShortcutBridge: () => ({ handleWindowClose: () => false }),
|
||||
getGlobalShortcutBridge: () => ({ handleWindowClose: (event) => {
|
||||
if (!closeToTray) return false;
|
||||
event.preventDefault();
|
||||
return true;
|
||||
} }),
|
||||
getMainWindowCount: () => 1,
|
||||
debugLog() {}, resolveFrontendBackgroundColor() { return null; }, loadWindowState() { return null; },
|
||||
getDevRendererBaseUrl: (url) => url, getWindowBoundsState() { return null; },
|
||||
@@ -43,10 +55,18 @@ for (const peer of [true, false]) {
|
||||
closeEditorTabsForSource: () => { ownerChecks++; return new Promise((resolve) => { finish = resolve; }); },
|
||||
queryDirtyEditors: async () => { dirtyChecks++; return false; },
|
||||
});
|
||||
const win = await api.createWindow({ BrowserWindow: Window, nativeTheme: {}, app: {}, screen: {}, shell: {}, ipcMain: {} }, {
|
||||
const win = await api.createWindow({ BrowserWindow: Window, nativeTheme: {}, app: {}, screen: {}, shell: {}, ipcMain }, {
|
||||
preload: "/tmp/preload.cjs", devServerUrl: "http://localhost:5173", isDev: true, isMac: true,
|
||||
electronDir: __dirname, route: peer ? "session-window" : undefined, registerAsMainWindow: !peer,
|
||||
});
|
||||
if (!peer) {
|
||||
closeToTray = true;
|
||||
win.close(); await tick();
|
||||
assert.equal(win.destroyed, false);
|
||||
assert.equal(logCaptures, 0, "hiding to tray must keep the session log live");
|
||||
assert.equal(ownerChecks, 0);
|
||||
closeToTray = false;
|
||||
}
|
||||
win.close(); win.close();
|
||||
assert.equal(ownerChecks, 1, "repeat close must share the ownership check");
|
||||
assert.equal(dirtyChecks, 0, "the short dirty query must not race a detached Save/Cancel prompt");
|
||||
@@ -54,10 +74,14 @@ for (const peer of [true, false]) {
|
||||
finish({ success: true, cancelled: true }); await tick();
|
||||
assert.equal(win.destroyed, false, "Cancel keeps the source save/dock renderer alive");
|
||||
assert.equal(dirtyChecks, 0);
|
||||
assert.equal(logCaptures, 0, "Cancel must leave the live log ongoing");
|
||||
win.close();
|
||||
ownsTabs = false;
|
||||
finish({ success: true, cancelled: false }); await tick();
|
||||
assert.equal(dirtyChecks, 1);
|
||||
assert.equal(logCaptures, 1);
|
||||
assert.equal(win.destroyed, false, "renderer must survive until replay persistence acknowledges completion");
|
||||
finishLogCapture(); await tick();
|
||||
assert.equal(win.destroyed, true, "close proceeds only after all owned editors settled");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
const { Transform } = require("node:stream");
|
||||
|
||||
const DEFAULT_HIDDEN_EXTENSIONS = Object.freeze(["DRI3", "MIT-SHM"]);
|
||||
const EMPTY = Buffer.alloc(0);
|
||||
|
||||
function readUInt16(buffer, offset, littleEndian) {
|
||||
return littleEndian ? buffer.readUInt16LE(offset) : buffer.readUInt16BE(offset);
|
||||
}
|
||||
|
||||
function readUInt32(buffer, offset, littleEndian) {
|
||||
return littleEndian ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset);
|
||||
}
|
||||
|
||||
function pad4(length) {
|
||||
return Math.ceil(length / 4) * 4;
|
||||
}
|
||||
|
||||
// Retain only the header we need; large request/reply bodies stream through.
|
||||
function collectHeader(state, length, chunk, offset) {
|
||||
const count = Math.min(Math.max(0, length - state.header.length), chunk.length - offset);
|
||||
if (count > 0) {
|
||||
state.header = Buffer.concat([state.header, chunk.subarray(offset, offset + count)]);
|
||||
}
|
||||
return offset + count;
|
||||
}
|
||||
|
||||
class RequestTracker extends Transform {
|
||||
constructor(shared) {
|
||||
super();
|
||||
this.shared = shared;
|
||||
this.setup = true;
|
||||
this.header = EMPTY;
|
||||
this.remaining = 0;
|
||||
this.sequence = 0;
|
||||
}
|
||||
|
||||
_transform(chunk, _encoding, callback) {
|
||||
const shared = this.shared;
|
||||
let offset = 0;
|
||||
while (offset < chunk.length && shared.enabled) {
|
||||
if (this.remaining > 0) {
|
||||
const count = Math.min(this.remaining, chunk.length - offset);
|
||||
offset += count;
|
||||
this.remaining -= count;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.setup) {
|
||||
offset = collectHeader(this, 1, chunk, offset);
|
||||
if (this.header[0] !== 0x6c && this.header[0] !== 0x42) {
|
||||
shared.enabled = false;
|
||||
break;
|
||||
}
|
||||
shared.littleEndian = this.header[0] === 0x6c;
|
||||
offset = collectHeader(this, 12, chunk, offset);
|
||||
if (this.header.length < 12) break;
|
||||
this.remaining = pad4(readUInt16(this.header, 6, shared.littleEndian))
|
||||
+ pad4(readUInt16(this.header, 8, shared.littleEndian));
|
||||
this.header = EMPTY;
|
||||
this.setup = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
offset = collectHeader(this, 4, chunk, offset);
|
||||
if (this.header.length < 4) break;
|
||||
let words = readUInt16(this.header, 2, shared.littleEndian);
|
||||
const headerLength = words === 0 ? 8 : 4;
|
||||
if (headerLength === 8) {
|
||||
offset = collectHeader(this, 8, chunk, offset);
|
||||
if (this.header.length < 8) break;
|
||||
words = readUInt32(this.header, 4, shared.littleEndian);
|
||||
}
|
||||
const total = words * 4;
|
||||
if (total < headerLength) {
|
||||
shared.enabled = false;
|
||||
break;
|
||||
}
|
||||
|
||||
let name;
|
||||
const nameOffset = headerLength + 4;
|
||||
if (this.header[0] === 98 && total >= nameOffset) { // QueryExtension
|
||||
offset = collectHeader(this, nameOffset, chunk, offset);
|
||||
if (this.header.length < nameOffset) break;
|
||||
const nameLength = readUInt16(this.header, headerLength, shared.littleEndian);
|
||||
if (nameLength <= shared.maxNameLength && nameOffset + pad4(nameLength) <= total) {
|
||||
offset = collectHeader(this, nameOffset + nameLength, chunk, offset);
|
||||
if (this.header.length < nameOffset + nameLength) break;
|
||||
name = this.header.toString("latin1", nameOffset, nameOffset + nameLength);
|
||||
}
|
||||
}
|
||||
|
||||
this.sequence = (this.sequence + 1) & 0xffff;
|
||||
// Do not let an unanswered query affect an unrelated request after wrap.
|
||||
shared.pending.delete(this.sequence);
|
||||
if (shared.hidden.has(name)) shared.pending.set(this.sequence, name);
|
||||
this.remaining = total - this.header.length;
|
||||
this.header = EMPTY;
|
||||
}
|
||||
callback(null, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
class ReplyFilter extends Transform {
|
||||
constructor(shared) {
|
||||
super();
|
||||
this.shared = shared;
|
||||
this.setup = true;
|
||||
this.header = EMPTY;
|
||||
this.remaining = 0;
|
||||
}
|
||||
|
||||
_transform(chunk, _encoding, callback) {
|
||||
const shared = this.shared;
|
||||
let offset = 0;
|
||||
while (offset < chunk.length) {
|
||||
if (!shared.enabled) {
|
||||
this.push(this.header);
|
||||
this.header = EMPTY;
|
||||
this.push(chunk.subarray(offset));
|
||||
break;
|
||||
}
|
||||
if (this.remaining > 0) {
|
||||
const count = Math.min(this.remaining, chunk.length - offset);
|
||||
this.push(chunk.subarray(offset, offset + count));
|
||||
offset += count;
|
||||
this.remaining -= count;
|
||||
continue;
|
||||
}
|
||||
|
||||
offset = collectHeader(this, this.setup ? 8 : 4, chunk, offset);
|
||||
if (this.header.length < (this.setup ? 8 : 4)) break;
|
||||
if (this.setup) {
|
||||
this.remaining = readUInt16(this.header, 6, shared.littleEndian) * 4;
|
||||
this.setup = false;
|
||||
} else {
|
||||
const type = this.header[0];
|
||||
let total = 32; // Errors and ordinary events are fixed size.
|
||||
if (type === 1 || (type & 0x7f) === 35) { // Reply or GenericEvent
|
||||
offset = collectHeader(this, 8, chunk, offset);
|
||||
if (this.header.length < 8) break;
|
||||
total += readUInt32(this.header, 4, shared.littleEndian) * 4;
|
||||
}
|
||||
if (type === 0 || type === 1) {
|
||||
const sequence = readUInt16(this.header, 2, shared.littleEndian);
|
||||
const name = shared.pending.get(sequence);
|
||||
if (name !== undefined) {
|
||||
if (type === 1) {
|
||||
offset = collectHeader(this, 9, chunk, offset);
|
||||
if (this.header.length < 9) break;
|
||||
if (this.header[8] !== 0) {
|
||||
this.header[8] = 0; // QueryExtension.present = False
|
||||
if (!shared.warned) {
|
||||
shared.warned = true;
|
||||
shared.logger.warn?.(`[X11] hiding ${name}: forwarding cannot carry file descriptors`);
|
||||
}
|
||||
}
|
||||
}
|
||||
shared.pending.delete(sequence);
|
||||
}
|
||||
}
|
||||
this.remaining = total - this.header.length;
|
||||
}
|
||||
this.push(this.header);
|
||||
this.header = EMPTY;
|
||||
}
|
||||
callback();
|
||||
}
|
||||
|
||||
_flush(callback) {
|
||||
callback(null, this.header);
|
||||
}
|
||||
}
|
||||
|
||||
// SCM_RIGHTS descriptors cannot travel over an SSH byte stream. Hide extensions
|
||||
// that require them so clients select a supported rendering path instead.
|
||||
function createX11FdGuard(options = {}) {
|
||||
const hidden = new Set(options.hiddenExtensions ?? DEFAULT_HIDDEN_EXTENSIONS);
|
||||
const shared = {
|
||||
enabled: hidden.size > 0,
|
||||
hidden,
|
||||
maxNameLength: Math.max(0, ...Array.from(hidden, (name) => name.length)),
|
||||
littleEndian: true,
|
||||
pending: new Map(),
|
||||
warned: false,
|
||||
logger: options.logger || console,
|
||||
};
|
||||
return { toServer: new RequestTracker(shared), toClient: new ReplyFilter(shared) };
|
||||
}
|
||||
|
||||
module.exports = { createX11FdGuard, DEFAULT_HIDDEN_EXTENSIONS };
|
||||
@@ -0,0 +1,204 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { once } = require("node:events");
|
||||
const { createX11FdGuard, DEFAULT_HIDDEN_EXTENSIONS } = require("./x11FdGuard.cjs");
|
||||
|
||||
function writeUInt16(buffer, value, offset, endian) {
|
||||
buffer[endian === "l" ? "writeUInt16LE" : "writeUInt16BE"](value, offset);
|
||||
}
|
||||
|
||||
function writeUInt32(buffer, value, offset, endian) {
|
||||
buffer[endian === "l" ? "writeUInt32LE" : "writeUInt32BE"](value, offset);
|
||||
}
|
||||
|
||||
function setupRequest(endian = "l") {
|
||||
const packet = Buffer.alloc(24, 0xab);
|
||||
packet[0] = endian.charCodeAt(0);
|
||||
writeUInt16(packet, 11, 2, endian);
|
||||
writeUInt16(packet, 3, 6, endian);
|
||||
writeUInt16(packet, 5, 8, endian);
|
||||
return packet;
|
||||
}
|
||||
|
||||
function setupReply(endian = "l", status = 1) {
|
||||
const packet = Buffer.alloc(20, 0xcd);
|
||||
packet[0] = status;
|
||||
writeUInt16(packet, 11, 2, endian);
|
||||
writeUInt16(packet, 3, 6, endian);
|
||||
return packet;
|
||||
}
|
||||
|
||||
function request(name, { endian = "l", big = false, opcode = 98 } = {}) {
|
||||
const nameBytes = Buffer.from(name, "latin1");
|
||||
const prefix = big ? 12 : 8;
|
||||
const packet = Buffer.alloc(prefix + Math.ceil(nameBytes.length / 4) * 4);
|
||||
packet[0] = opcode;
|
||||
writeUInt16(packet, big ? 0 : packet.length / 4, 2, endian);
|
||||
if (big) writeUInt32(packet, packet.length / 4, 4, endian);
|
||||
writeUInt16(packet, nameBytes.length, big ? 8 : 4, endian);
|
||||
nameBytes.copy(packet, prefix);
|
||||
return packet;
|
||||
}
|
||||
|
||||
function reply(sequence, { endian = "l", type = 1, present = 1, extra = 0 } = {}) {
|
||||
const packet = Buffer.alloc(32 + extra, 0xef);
|
||||
packet[0] = type;
|
||||
writeUInt16(packet, sequence, 2, endian);
|
||||
writeUInt32(packet, extra / 4, 4, endian);
|
||||
packet[8] = present;
|
||||
return packet;
|
||||
}
|
||||
|
||||
function withoutPresent(packet) {
|
||||
const copy = Buffer.from(packet);
|
||||
copy[8] = 0;
|
||||
return copy;
|
||||
}
|
||||
|
||||
function chunks(buffer, size) {
|
||||
if (!size) return [buffer];
|
||||
const result = [];
|
||||
for (let offset = 0; offset < buffer.length; offset += size) {
|
||||
result.push(buffer.subarray(offset, offset + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function exchange(uplink, downlink, { chunkSize, ...options } = {}) {
|
||||
const warnings = [];
|
||||
const guard = createX11FdGuard({ logger: { warn: (message) => warnings.push(message) }, ...options });
|
||||
const sent = [];
|
||||
const received = [];
|
||||
guard.toServer.on("data", (chunk) => sent.push(chunk));
|
||||
guard.toClient.on("data", (chunk) => received.push(chunk));
|
||||
const ended = Promise.all([once(guard.toServer, "end"), once(guard.toClient, "end")]);
|
||||
for (const chunk of chunks(uplink, chunkSize)) guard.toServer.write(chunk);
|
||||
for (const chunk of chunks(downlink, chunkSize)) guard.toClient.write(chunk);
|
||||
guard.toServer.end();
|
||||
guard.toClient.end();
|
||||
await ended;
|
||||
assert.deepEqual(Buffer.concat(sent), uplink, "uplink must stay byte-identical");
|
||||
return { received: Buffer.concat(received), warnings };
|
||||
}
|
||||
|
||||
for (const endian of ["l", "B"]) {
|
||||
for (const chunkSize of [undefined, 1]) {
|
||||
test(`default guard hides only DRI3 and MIT-SHM (${endian}, chunks ${chunkSize || "coalesced"})`, async () => {
|
||||
assert.deepEqual(DEFAULT_HIDDEN_EXTENSIONS, ["DRI3", "MIT-SHM"]);
|
||||
const names = ["DRI3", "GLX", "MIT-SHM", "RENDER", "dri3", "DRI3-extra", ""];
|
||||
const replies = names.map((_, index) => reply(index + 1, { endian }));
|
||||
const uplink = Buffer.concat([setupRequest(endian), ...names.map((name) => request(name, { endian }))]);
|
||||
const downlink = Buffer.concat([setupReply(endian), ...replies]);
|
||||
const expected = Buffer.concat([setupReply(endian), ...replies.map((packet, index) => (
|
||||
index === 0 || index === 2 ? withoutPresent(packet) : packet
|
||||
))]);
|
||||
const result = await exchange(uplink, downlink, { chunkSize });
|
||||
assert.deepEqual(result.received, expected);
|
||||
assert.equal(result.warnings.length, 1);
|
||||
assert.match(result.warnings[0], /^\[X11\] hiding DRI3/);
|
||||
assert.deepEqual(downlink, Buffer.concat([setupReply(endian), ...replies]), "input buffers must stay unchanged");
|
||||
});
|
||||
}
|
||||
|
||||
test(`BIG-REQUESTS use the extended header offsets (${endian})`, async () => {
|
||||
const queries = [
|
||||
request("DRI3", { endian, big: true }),
|
||||
request("MIT-SHM", { endian, big: true }),
|
||||
request("GLX", { endian, big: true }),
|
||||
request("DRI3", { endian }),
|
||||
];
|
||||
const replies = queries.map((_, index) => reply(index + 1, { endian }));
|
||||
const result = await exchange(
|
||||
Buffer.concat([setupRequest(endian), ...queries]),
|
||||
Buffer.concat([setupReply(endian), ...replies]),
|
||||
{ chunkSize: 1 },
|
||||
);
|
||||
assert.deepEqual(result.received, Buffer.concat([
|
||||
setupReply(endian), withoutPresent(replies[0]), withoutPresent(replies[1]), replies[2], withoutPresent(replies[3]),
|
||||
]));
|
||||
});
|
||||
}
|
||||
|
||||
test("an empty hide list is byte-identical and a custom list replaces the defaults", async () => {
|
||||
const uplink = Buffer.concat([setupRequest(), request("DRI3"), request("MIT-SHM"), request("GLX")]);
|
||||
const replies = [reply(1), reply(2), reply(3)];
|
||||
const downlink = Buffer.concat([setupReply(), ...replies]);
|
||||
const disabled = await exchange(uplink, downlink, { hiddenExtensions: [], chunkSize: 1 });
|
||||
assert.deepEqual(disabled.received, downlink);
|
||||
assert.deepEqual(disabled.warnings, []);
|
||||
const custom = await exchange(uplink, downlink, { hiddenExtensions: ["GLX"], chunkSize: 1 });
|
||||
assert.deepEqual(custom.received, Buffer.concat([setupReply(), replies[0], replies[1], withoutPresent(replies[2])]));
|
||||
assert.equal(custom.warnings.length, 1);
|
||||
assert.match(custom.warnings[0], /hiding GLX/);
|
||||
});
|
||||
|
||||
test("errors, unrelated replies, ordinary events and variable GenericEvents preserve sequence isolation", async () => {
|
||||
const uplink = Buffer.concat([setupRequest(), request("DRI3"), request("GLX"), request("MIT-SHM")]);
|
||||
const error = reply(1, { type: 0 });
|
||||
const afterError = reply(1);
|
||||
const unrelated = reply(2, { extra: 64 });
|
||||
const event = reply(3, { type: 12 });
|
||||
const generic = reply(3, { type: 35, extra: 48 });
|
||||
const sentGeneric = reply(3, { type: 0x80 | 35, extra: 12 });
|
||||
const hidden = reply(3);
|
||||
const repeated = reply(3);
|
||||
const prefix = [setupReply(), error, afterError, unrelated, event, generic, sentGeneric];
|
||||
const result = await exchange(uplink, Buffer.concat([...prefix, hidden, repeated]), { chunkSize: 1 });
|
||||
assert.deepEqual(result.received, Buffer.concat([...prefix, withoutPresent(hidden), repeated]));
|
||||
assert.equal(result.warnings.length, 1);
|
||||
assert.match(result.warnings[0], /hiding MIT-SHM/);
|
||||
});
|
||||
|
||||
test("absent extensions and failed queries do not log", async () => {
|
||||
const uplink = Buffer.concat([setupRequest(), request("DRI3"), request("MIT-SHM")]);
|
||||
const downlink = Buffer.concat([setupReply(), reply(1, { present: 0 }), reply(2, { type: 0 })]);
|
||||
const result = await exchange(uplink, downlink, { chunkSize: 1 });
|
||||
assert.deepEqual(result.received, downlink);
|
||||
assert.deepEqual(result.warnings, []);
|
||||
});
|
||||
|
||||
test("request bodies are skipped without mistaking embedded queries for requests", async () => {
|
||||
const body = Buffer.alloc(128 * 1024);
|
||||
request("DRI3").copy(body, 0);
|
||||
const large = Buffer.alloc(8 + body.length);
|
||||
large[0] = 18; // ChangeProperty, using BIG-REQUESTS framing
|
||||
large.writeUInt32LE(large.length / 4, 4);
|
||||
body.copy(large, 8);
|
||||
const uplink = Buffer.concat([setupRequest(), large, request("MIT-SHM")]);
|
||||
const visible = reply(1, { extra: 128 * 1024 });
|
||||
const hidden = reply(2);
|
||||
const result = await exchange(uplink, Buffer.concat([setupReply(), visible, hidden]), { chunkSize: 17 });
|
||||
assert.deepEqual(result.received, Buffer.concat([setupReply(), visible, withoutPresent(hidden)]));
|
||||
});
|
||||
|
||||
test("sequence wrap hides new queries and clears stale entries on reused sequences", async () => {
|
||||
const noOp = Buffer.from([127, 0, 1, 0]);
|
||||
const queries = [request("DRI3"), Buffer.concat(Array(65534).fill(noOp)), request("MIT-SHM"), noOp, request("DRI3")];
|
||||
const stale = reply(1);
|
||||
const wrapped = reply(0);
|
||||
const hidden = reply(2);
|
||||
const result = await exchange(
|
||||
Buffer.concat([setupRequest(), ...queries]),
|
||||
Buffer.concat([setupReply(), wrapped, stale, hidden]),
|
||||
{ chunkSize: 13 },
|
||||
);
|
||||
assert.deepEqual(result.received, Buffer.concat([setupReply(), withoutPresent(wrapped), stale, withoutPresent(hidden)]));
|
||||
});
|
||||
|
||||
test("setup failures and truncated headers flush unchanged", async () => {
|
||||
for (const status of [0, 2]) {
|
||||
const downlink = setupReply("B", status);
|
||||
const result = await exchange(setupRequest("B"), downlink, { chunkSize: 1 });
|
||||
assert.deepEqual(result.received, downlink);
|
||||
}
|
||||
const shortSetup = await exchange(setupRequest(), setupReply().subarray(0, 5), { chunkSize: 1 });
|
||||
assert.deepEqual(shortSetup.received, setupReply().subarray(0, 5));
|
||||
const partial = Buffer.concat([setupReply(), reply(1).subarray(0, 7)]);
|
||||
const result = await exchange(Buffer.concat([setupRequest(), request("DRI3")]), partial, { chunkSize: 1 });
|
||||
assert.deepEqual(result.received, partial);
|
||||
});
|
||||
|
||||
test("non-X11 payloads pass through unchanged", async () => {
|
||||
const result = await exchange(Buffer.from("remote"), Buffer.from("local"), { chunkSize: 1 });
|
||||
assert.equal(result.received.toString(), "local");
|
||||
});
|
||||
@@ -2,6 +2,7 @@ const net = require("node:net");
|
||||
const fs = require("node:fs");
|
||||
const { Transform } = require("node:stream");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const { createX11FdGuard } = require("./x11FdGuard.cjs");
|
||||
|
||||
const X11_PORT_BASE = 6000;
|
||||
const MIT_MAGIC_COOKIE_PROTOCOL = "MIT-MAGIC-COOKIE-1";
|
||||
@@ -253,11 +254,16 @@ function attachX11Forwarding(conn, options = {}) {
|
||||
const target = resolveX11DisplaySpec(display, { platform });
|
||||
const localSocket = createSocket();
|
||||
let acceptedChannel = null;
|
||||
let guard = null;
|
||||
let settled = false;
|
||||
|
||||
const cleanup = () => {
|
||||
if (acceptedChannel) destroyStream(acceptedChannel);
|
||||
destroyStream(localSocket);
|
||||
if (guard) {
|
||||
destroyStream(guard.toServer);
|
||||
destroyStream(guard.toClient);
|
||||
}
|
||||
};
|
||||
|
||||
localSocket.once("connect", () => {
|
||||
@@ -275,15 +281,19 @@ function attachX11Forwarding(conn, options = {}) {
|
||||
localSocket.on("error", () => cleanup());
|
||||
acceptedChannel.on("close", () => destroyStream(localSocket));
|
||||
localSocket.on("close", () => destroyStream(acceptedChannel));
|
||||
guard = createX11FdGuard({ hiddenExtensions: options.hiddenExtensions, logger });
|
||||
guard.toServer.on("error", cleanup);
|
||||
guard.toClient.on("error", cleanup);
|
||||
const realCookie = resolveLocalAuthCookie();
|
||||
if (realCookie && fakeCookie) {
|
||||
acceptedChannel
|
||||
.pipe(createX11AuthTransform({ fakeCookie, realCookie }))
|
||||
.pipe(localSocket)
|
||||
.pipe(acceptedChannel);
|
||||
.pipe(guard.toServer)
|
||||
.pipe(localSocket);
|
||||
} else {
|
||||
acceptedChannel.pipe(localSocket).pipe(acceptedChannel);
|
||||
acceptedChannel.pipe(guard.toServer).pipe(localSocket);
|
||||
}
|
||||
localSocket.pipe(guard.toClient).pipe(acceptedChannel);
|
||||
});
|
||||
|
||||
localSocket.once("error", (err) => {
|
||||
|
||||
@@ -181,6 +181,7 @@ test("attachX11Forwarding pipes accepted X11 channels to the local display socke
|
||||
attachX11Forwarding(conn, {
|
||||
display: ":0",
|
||||
createSocket: () => localSocket,
|
||||
readLocalAuthCookie: () => null,
|
||||
sendMessage: (message) => messages.push(message),
|
||||
platform: "linux",
|
||||
});
|
||||
@@ -203,6 +204,79 @@ test("attachX11Forwarding pipes accepted X11 channels to the local display socke
|
||||
assert.deepEqual(messages, []);
|
||||
});
|
||||
|
||||
for (const rewriteCookie of [false, true]) {
|
||||
test(`attachX11Forwarding hides fd extensions with cookie rewriting ${rewriteCookie ? "enabled" : "disabled"}`, async (t) => {
|
||||
const conn = new EventEmitter();
|
||||
const capturedLocal = [];
|
||||
const capturedRemote = [];
|
||||
const warnings = [];
|
||||
const makeDuplex = (captured) => new Duplex({
|
||||
read() {},
|
||||
write(chunk, _encoding, callback) {
|
||||
captured.push(Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const localSocket = makeDuplex(capturedLocal);
|
||||
const acceptedChannel = makeDuplex(capturedRemote);
|
||||
t.after(() => {
|
||||
localSocket.destroy();
|
||||
acceptedChannel.destroy();
|
||||
});
|
||||
localSocket.connect = () => {
|
||||
queueMicrotask(() => localSocket.emit("connect"));
|
||||
return localSocket;
|
||||
};
|
||||
const fakeCookie = "11111111111111111111111111111111";
|
||||
const realCookie = "22222222222222222222222222222222";
|
||||
attachX11Forwarding(conn, {
|
||||
display: ":0",
|
||||
platform: "linux",
|
||||
createSocket: () => localSocket,
|
||||
fakeCookie: rewriteCookie ? fakeCookie : undefined,
|
||||
readLocalAuthCookie: () => rewriteCookie ? Buffer.from(realCookie, "hex") : null,
|
||||
logger: { warn: (message) => warnings.push(message) },
|
||||
});
|
||||
conn.emit("x11", {}, () => acceptedChannel, () => assert.fail("unexpected reject"));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
const setup = buildX11SetupPacket({ cookie: fakeCookie });
|
||||
const queries = ["DRI3", "MIT-SHM", "GLX"].map((name) => {
|
||||
const packet = Buffer.alloc(8 + Math.ceil(name.length / 4) * 4);
|
||||
packet[0] = 98;
|
||||
packet.writeUInt16LE(packet.length / 4, 2);
|
||||
packet.writeUInt16LE(name.length, 4);
|
||||
packet.write(name, 8, "ascii");
|
||||
return packet;
|
||||
});
|
||||
// Fragment the auth packet, coalescing its tail with the first requests.
|
||||
acceptedChannel.push(setup.subarray(0, 7));
|
||||
acceptedChannel.push(Buffer.concat([setup.subarray(7), ...queries]));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(Buffer.concat(capturedLocal), Buffer.concat([
|
||||
buildX11SetupPacket({ cookie: rewriteCookie ? realCookie : fakeCookie }), ...queries,
|
||||
]));
|
||||
|
||||
const setupReply = Buffer.from([1, 0, 11, 0, 0, 0, 0, 0]);
|
||||
const replies = queries.map((_, index) => {
|
||||
const packet = Buffer.alloc(32);
|
||||
packet[0] = 1;
|
||||
packet.writeUInt16LE(index + 1, 2);
|
||||
packet[8] = 1;
|
||||
return packet;
|
||||
});
|
||||
const response = Buffer.concat([setupReply, ...replies]);
|
||||
for (const byte of response) localSocket.push(Buffer.from([byte]));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const expected = Buffer.from(response);
|
||||
expected[8 + 8] = 0;
|
||||
expected[8 + 32 + 8] = 0;
|
||||
assert.deepEqual(Buffer.concat(capturedRemote), expected);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /^\[X11\] hiding DRI3/);
|
||||
});
|
||||
}
|
||||
|
||||
test("attachX11Forwarding rejects the remote channel and explains local display failures", async () => {
|
||||
const conn = new EventEmitter();
|
||||
const localSocket = new EventEmitter();
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user