mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-06 14:30:13 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb01c4ef58 | ||
|
|
6fcd6a3ec3 | ||
|
|
de6d1a28ba | ||
|
|
b2ed83ae51 | ||
|
|
f91b2cd04e | ||
|
|
1d10d1679e | ||
|
|
8d2058267a | ||
|
|
8020eaa427 | ||
|
|
3298a70f32 | ||
|
|
e7202f392a | ||
|
|
9423a1d1cd | ||
|
|
50ca182e1e | ||
|
|
04a63c653a | ||
|
|
e2f499b0f9 | ||
|
|
5805d15746 | ||
|
|
bd8476fb34 | ||
|
|
c74daf0102 | ||
|
|
f1425c8d5a | ||
|
|
fc55e9ac17 | ||
|
|
025ce741c2 | ||
|
|
323ff0b16a | ||
|
|
6ece7e8222 | ||
|
|
e3894eb850 | ||
|
|
38c7376515 | ||
|
|
1b8228b23d | ||
|
|
b2c518a6f1 | ||
|
|
ea36f46d1d | ||
|
|
6d0d39e678 | ||
|
|
08089323a9 | ||
|
|
91db655a1a | ||
|
|
d51cd2714d |
No files matched your search
@@ -70,3 +70,26 @@ jobs:
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
windows-broadcast-ssh:
|
||||
name: windows-broadcast-ssh
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Exercise two SSH password prompts in the desktop app
|
||||
run: node scripts/terminal-broadcast-ssh.live.cjs
|
||||
@@ -3,7 +3,7 @@ import type React from 'react';
|
||||
import type { Host, HostProtocol, TerminalSession } from '../../types';
|
||||
import type { PassphraseRequest } from '../../components/PassphraseModal';
|
||||
import type { TerminalPopupPayload } from '../../domain/systemManager/types';
|
||||
import { getEffectiveHostDistro, classifyDistroId, shouldProbeSessionCwd } from '../../domain/host';
|
||||
import { getEffectiveHostDistro, classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from '../../domain/host';
|
||||
import { getAvailablePaneMagnificationController } from '../../domain/paneMagnification';
|
||||
import { sanitizeHostIconFields } from '../../domain/hostIcon';
|
||||
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
|
||||
@@ -535,7 +535,11 @@ async function captureCtxInheritedCwd(getCtx: AppContextGetter, sessionId: strin
|
||||
if (!liveCwd && isConnectedSsh && !isNetworkDevice) {
|
||||
try {
|
||||
const info = await bridge?.getSessionRemoteInfo?.(sessionId);
|
||||
allowSshProbe = shouldProbeSessionCwd({ isNetworkDevice: false, remoteSshVersion: info?.remoteSshVersion });
|
||||
allowSshProbe = shouldProbeSessionCwd({
|
||||
isNetworkDevice: false,
|
||||
remoteSshVersion: info?.remoteSshVersion,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(host),
|
||||
});
|
||||
} catch {
|
||||
allowSshProbe = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8");
|
||||
|
||||
test("deep-link tab names are applied to terminal sessions", () => {
|
||||
assert.match(source, /type DeepLinkPayload = \{[\s\S]*tabName\?: string/);
|
||||
assert.match(source, /const handleConnectToHostWithTabName = useCallback/);
|
||||
assert.match(source, /renameSessionInline\(sessionId, tabName\)/);
|
||||
assert.match(source, /handleConnectToHostWithTabName\(ephemeralHost, tabName\)/);
|
||||
assert.match(
|
||||
source,
|
||||
/handleConnectToHostWithTabName\(buildSshDeepLinkConnectionHost\(originalHost\), tabName\)/,
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/handleConnectToHostWithTabName\(buildTelnetDeepLinkConnectionHost\(matchedEffectiveHost\), tabName\)/,
|
||||
);
|
||||
assert.match(source, /label: tabName/);
|
||||
});
|
||||
@@ -98,6 +98,11 @@ type OpenSessionInNewWindowPayload = {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
};
|
||||
|
||||
type DeepLinkPayload = {
|
||||
url?: string;
|
||||
tabName?: string;
|
||||
};
|
||||
|
||||
const IS_DEV = import.meta.env.DEV;
|
||||
const HOTKEY_DEBUG =
|
||||
IS_DEV && localStorageAdapter.readString(STORAGE_KEY_DEBUG_HOTKEYS) === '1';
|
||||
@@ -260,6 +265,7 @@ export function AppSideEffects() {
|
||||
copyWorkspace,
|
||||
createSessionFromCloneSource,
|
||||
getSessionRestoreCwd,
|
||||
renameSessionInline,
|
||||
} = sessionState;
|
||||
|
||||
// Presentation-field thrash stays off Host bags (Hosts use retainStable);
|
||||
@@ -1398,6 +1404,14 @@ export function AppSideEffects() {
|
||||
}), host, hidden);
|
||||
}, [addConnectionLog, connectToHost, resolveEffectiveHost, identities, keys]);
|
||||
|
||||
const handleConnectToHostWithTabName = useCallback((host: Host, tabName?: string) => {
|
||||
const sessionId = handleConnectToHost(host);
|
||||
if (sessionId && tabName) {
|
||||
renameSessionInline(sessionId, tabName);
|
||||
}
|
||||
return sessionId;
|
||||
}, [handleConnectToHost, renameSessionInline]);
|
||||
|
||||
const openHostForVaultAgent = useCallback((host: Host, isExternalMcpCall: boolean) => {
|
||||
// Silent sessions only apply to actual external MCP clients (chatSessionId
|
||||
// equals the reserved external-MCP scope). The in-app Catty AI chat's
|
||||
@@ -1465,15 +1479,16 @@ export function AppSideEffects() {
|
||||
// deep links until unlock so saved-credential connects cannot start behind
|
||||
// the lock screen.
|
||||
const pendingDeepLinksWhileLockedRef = useRef<Array<
|
||||
| { kind: 'ssh'; payload: { url?: string } }
|
||||
| { kind: 'telnet'; payload: { url?: string } }
|
||||
| { kind: 'ssh'; payload: DeepLinkPayload }
|
||||
| { kind: 'telnet'; payload: DeepLinkPayload }
|
||||
| { kind: 'jms'; payload: { url?: string } }
|
||||
| { kind: 'open-terminal-path'; payload: { path?: string } }
|
||||
>>([]);
|
||||
|
||||
const _processSshDeepLink = useEffectEvent((payload: { url?: string }) => {
|
||||
const _processSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
|
||||
startupLaunchIntentReceivedRef.current = true;
|
||||
const rawUrl = payload?.url || '';
|
||||
const tabName = payload?.tabName?.trim();
|
||||
const target = parseSshDeepLink(rawUrl);
|
||||
if (!target) {
|
||||
toast.warning(t('deepLink.ssh.invalid'));
|
||||
@@ -1502,25 +1517,26 @@ export function AppSideEffects() {
|
||||
? buildSshDeepLinkEphemeralHostFromSaved(matchedEffectiveHost, target, draftOptions)
|
||||
: buildSshDeepLinkEphemeralHost(target, draftOptions);
|
||||
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
|
||||
handleConnectToHost(ephemeralHost);
|
||||
handleConnectToHostWithTabName(ephemeralHost, tabName);
|
||||
return;
|
||||
}
|
||||
|
||||
if (matchedEffectiveHost) {
|
||||
const originalHost = hosts.find((host) => host.id === matchedEffectiveHost.id) ?? matchedEffectiveHost;
|
||||
handleConnectToHost(buildSshDeepLinkConnectionHost(originalHost));
|
||||
handleConnectToHostWithTabName(buildSshDeepLinkConnectionHost(originalHost), tabName);
|
||||
return;
|
||||
}
|
||||
|
||||
setDeepLinkHostDraft(buildSshDeepLinkHostDraft(target, {
|
||||
const hostDraft = buildSshDeepLinkHostDraft(target, {
|
||||
id: crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
}));
|
||||
});
|
||||
setDeepLinkHostDraft(tabName ? { ...hostDraft, label: tabName } : hostDraft);
|
||||
setNavigateToSection('hosts');
|
||||
setActiveTabId('vault');
|
||||
});
|
||||
|
||||
const _handleSshDeepLink = useEffectEvent((payload: { url?: string }) => {
|
||||
const _handleSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
|
||||
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
|
||||
pendingDeepLinksWhileLockedRef.current.push({ kind: 'ssh', payload: payload || {} });
|
||||
return;
|
||||
@@ -1537,9 +1553,10 @@ export function AppSideEffects() {
|
||||
});
|
||||
}, [isPeerSessionWindow]);
|
||||
|
||||
const _processTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
|
||||
const _processTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
|
||||
startupLaunchIntentReceivedRef.current = true;
|
||||
const rawUrl = payload?.url || '';
|
||||
const tabName = payload?.tabName?.trim();
|
||||
const target = parseTelnetDeepLink(rawUrl);
|
||||
if (!target) {
|
||||
toast.warning(t('deepLink.telnet.invalid'));
|
||||
@@ -1560,10 +1577,10 @@ export function AppSideEffects() {
|
||||
now: Date.now(),
|
||||
});
|
||||
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
|
||||
handleConnectToHost(ephemeralHost);
|
||||
handleConnectToHostWithTabName(ephemeralHost, tabName);
|
||||
return;
|
||||
}
|
||||
handleConnectToHost(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost));
|
||||
handleConnectToHostWithTabName(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost), tabName);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1572,10 +1589,10 @@ export function AppSideEffects() {
|
||||
now: Date.now(),
|
||||
});
|
||||
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
|
||||
handleConnectToHost(ephemeralHost);
|
||||
handleConnectToHostWithTabName(ephemeralHost, tabName);
|
||||
});
|
||||
|
||||
const _handleTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
|
||||
const _handleTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
|
||||
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
|
||||
pendingDeepLinksWhileLockedRef.current.push({ kind: 'telnet', payload: payload || {} });
|
||||
return;
|
||||
|
||||
@@ -288,6 +288,18 @@ export const enAiMessages: Messages = {
|
||||
'ai.opencode.check': 'Check',
|
||||
'ai.opencode.resetPath': 'Reset',
|
||||
|
||||
// AI MiMo Code (Xiaomi MiMo Code CLI — OpenCode fork)
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': "Xiaomi's MiMo Code CLI, an OpenCode fork. Install it and configure providers in its own config, then select it as an external coding agent.",
|
||||
'ai.mimo.detecting': 'Detecting...',
|
||||
'ai.mimo.detected': 'Detected',
|
||||
'ai.mimo.notFound': 'Not found',
|
||||
'ai.mimo.path': 'Path:',
|
||||
'ai.mimo.notFoundHint': 'Could not find mimo in PATH. Install it or specify the executable path below.',
|
||||
'ai.mimo.customPathPlaceholder': 'e.g. /usr/local/bin/mimo',
|
||||
'ai.mimo.check': 'Check',
|
||||
'ai.mimo.resetPath': 'Reset',
|
||||
|
||||
// AI Grok Build (in-app managed agent — distinct from External MCP client install)
|
||||
'ai.grok.title': 'Grok Build',
|
||||
'ai.grok.description': "xAI's Grok Build coding agent CLI. Install the Grok CLI, sign in with `grok login` or set XAI_API_KEY, then select it as an external agent.",
|
||||
@@ -324,6 +336,13 @@ export const enAiMessages: Messages = {
|
||||
|
||||
// External MCP (productized catalog MCP for Codex / Claude Code / Cursor)
|
||||
'ai.externalMcp.title': 'External MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': 'Always',
|
||||
'ai.externalMcp.allowCommandOnHostHint': 'Always allow this action on this server.',
|
||||
'ai.externalMcp.allowAll': 'Allow all actions',
|
||||
'ai.externalMcp.allowSession': 'This connection',
|
||||
'ai.externalMcp.allowSessionHint': 'Allow all actions from this client until it disconnects.',
|
||||
'ai.externalMcp.allowHost': 'This server',
|
||||
'ai.externalMcp.allowHostHint': 'Always allow actions on this server.',
|
||||
'ai.externalMcp.description': 'Expose Netcatty as an MCP server for external clients such as Codex, Claude Code, Cursor, and Grok. Uses the same catalog tools as in-app agents (terminal, SFTP, Vault, port forwarding). Keep Netcatty running while clients are connected.',
|
||||
'ai.externalMcp.sessionsExposed': 'Sessions in scope: {count}',
|
||||
'ai.externalMcp.mode': 'Availability mode',
|
||||
@@ -602,6 +621,10 @@ export const enAiMessages: Messages = {
|
||||
'terminal.layer.movePanelLeft': 'Move panel to left',
|
||||
'terminal.layer.movePanelRight': 'Move panel to right',
|
||||
'terminal.layer.movePanelBottom': 'Move panel to bottom',
|
||||
'terminal.layer.choosePanelPosition': 'Change position',
|
||||
'terminal.layer.dockLeft': 'Left',
|
||||
'terminal.layer.dockRight': 'Right',
|
||||
'terminal.layer.dockBottom': 'Bottom',
|
||||
'terminal.layer.closePanel': 'Close panel',
|
||||
'terminal.layer.closePane': 'Close split',
|
||||
'terminal.layer.saveLayoutAsDefault': 'Save layout as default',
|
||||
|
||||
@@ -312,8 +312,11 @@ export const enCoreMessages: Messages = {
|
||||
'settings.globalHotkey.toggleWindowDesc': 'Press a key combination to set a global shortcut for showing/hiding the window.',
|
||||
'settings.globalHotkey.notSet': 'Not set',
|
||||
'settings.globalHotkey.reset': 'Reset to default',
|
||||
'settings.globalHotkey.closeToTray': 'Close to System Tray',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'When enabled, closing the window will minimize to the system tray instead of quitting.',
|
||||
'settings.globalHotkey.closeToTray': 'Keep Running When Window Closes',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'When enabled, closing the window hides it while the app keeps running. Tray icon visibility is set separately.',
|
||||
'settings.globalHotkey.showTrayIcon': 'Show System Tray Icon',
|
||||
'settings.globalHotkey.showTrayIconDesc': 'When disabled, the tray icon is hidden but the app keeps running in the background.',
|
||||
'settings.globalHotkey.showTrayIconHiddenHint': 'Tray icon hidden. Launch the app again or use the global toggle hotkey to bring the window back, then re-enable this setting to restore the icon.',
|
||||
'settings.globalHotkey.enabled': 'Enable Global Hotkey',
|
||||
'settings.globalHotkey.enabledDesc': 'Register system-wide keyboard shortcuts. When disabled, all global hotkeys are unregistered.',
|
||||
'settings.globalHotkey.hint': 'Global hotkey works system-wide to quickly show or hide the window (Quake-style terminal).',
|
||||
@@ -538,7 +541,7 @@ Highlight the focused split pane:
|
||||
'settings.appearance.windowOpacity': 'Window Opacity',
|
||||
'settings.appearance.windowOpacity.desc': 'Adjust the transparency of the entire application window. Lower values also fade terminal text. Some Linux desktop environments may not support this.',
|
||||
'settings.appearance.appIcon': 'App Icon',
|
||||
'settings.appearance.appIcon.desc': 'Choose a dock/taskbar icon style to make Netcatty easier to spot when switching apps. Applies at runtime; the installed app bundle icon is unchanged.',
|
||||
'settings.appearance.appIcon.desc': 'Choose a dock/taskbar icon style to make Netcatty easier to spot when switching apps. On Windows, the notification area icon uses the same style. Applies at runtime; the installed app bundle icon is unchanged.',
|
||||
'settings.appearance.appIcon.original': 'Original',
|
||||
'settings.appearance.appIcon.bright': 'Bright',
|
||||
'settings.appearance.appIcon.dark': 'Dark',
|
||||
@@ -614,6 +617,8 @@ Highlight the focused split pane:
|
||||
'settings.terminal.font.weightBold.desc': 'Weight for bold text (100-900)',
|
||||
'settings.terminal.font.smoothing': 'Font smoothing',
|
||||
'settings.terminal.font.smoothing.desc': 'Use native macOS font anti-aliasing',
|
||||
'settings.terminal.font.ligatures': 'Font ligatures',
|
||||
'settings.terminal.font.ligatures.desc': 'Render ligatures such as != when the terminal font includes them',
|
||||
'settings.terminal.font.linePadding': 'Line padding',
|
||||
'settings.terminal.font.linePadding.desc': 'Additional space between lines (0-10)',
|
||||
'settings.terminal.font.emulationType': 'Terminal emulation type',
|
||||
@@ -621,6 +626,8 @@ Highlight the focused split pane:
|
||||
'settings.terminal.cursor.style.block': 'Block',
|
||||
'settings.terminal.cursor.style.bar': 'Bar',
|
||||
'settings.terminal.cursor.style.underline': 'Underline',
|
||||
'settings.terminal.cursor.barWidth': 'Bar cursor width',
|
||||
'settings.terminal.cursor.barWidth.desc': 'Width of bar cursors used by applications such as vi (1-4 px)',
|
||||
'settings.terminal.cursor.blink': 'Cursor blink',
|
||||
'settings.terminal.cursor.highlightLine': 'Highlight current line',
|
||||
'settings.terminal.cursor.highlightLine.desc':
|
||||
@@ -705,7 +712,10 @@ Highlight the focused split pane:
|
||||
'Send configured text instead of normal Enter when pressing Shift+Enter in the terminal.',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText': 'Text to send',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText.desc':
|
||||
'Use \\n for newline, \\t for tab, and \\\\ for backslash.',
|
||||
'Use \\n for newline, \\t for tab, \\e for Escape, and \\\\ for backslash.',
|
||||
'settings.terminal.behavior.shiftEnterForceText': 'Send text in Win32 input mode',
|
||||
'settings.terminal.behavior.shiftEnterForceText.desc':
|
||||
'Also send the text above when a local Windows ConPTY session negotiates Win32 input mode. Needed for Node/Bun CLIs (Claude Code, CodeBuddy) that cannot read modifier keys from console input records.',
|
||||
'settings.terminal.behavior.clearWipesScrollback': '`clear` wipes scrollback',
|
||||
'settings.terminal.behavior.clearWipesScrollback.desc':
|
||||
'Make `clear` also wipe the scrollback buffer (POSIX default). Disable to keep history visible after `clear`.',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const enScriptsMessages = {
|
||||
'scripts.actions.runParallel': 'Run on all tabs (parallel)',
|
||||
'scripts.actions.runSequential': 'Run on all tabs (sequential)',
|
||||
'scripts.actions.runOnAllTabs': 'Run on all tabs',
|
||||
'scripts.actions.copyCommand': 'Copy command',
|
||||
'scripts.actions.copyCommand.copied': 'Command copied',
|
||||
'scripts.actions.copyCommand.failed': 'Could not copy command',
|
||||
'scripts.actions.skippedConnectingSessions': '{count} tab(s) still connecting and were skipped',
|
||||
'scripts.actions.skippedSensitiveSessions': '{count} tab(s) skipped (password/sensitive input)',
|
||||
'scripts.actions.noRunnableHosts': 'No connectable hosts match this script\'s targets',
|
||||
|
||||
@@ -31,6 +31,7 @@ export const enSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadPorts': 'Failed to load listening ports',
|
||||
'systemManager.errors.loadServices': 'Failed to load systemd services',
|
||||
'systemManager.errors.sshChannelUnavailable': 'The server refused to open a new execution channel. Try again later, or reconnect this host.',
|
||||
'systemManager.unsupportedRemote': 'This host does not allow extra SSH exec channels, so System Manager is unavailable. Opening this panel will no longer disconnect the terminal.',
|
||||
|
||||
'systemManager.overview.empty': 'No system overview data yet.',
|
||||
'systemManager.overview.loading': 'Loading system overview…',
|
||||
|
||||
@@ -61,6 +61,7 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.composeBar.send': 'Send',
|
||||
'terminal.composeBar.close': 'Close compose bar',
|
||||
'terminal.composeBar.broadcasting': 'Broadcasting to all sessions',
|
||||
'terminal.composeBar.broadcastAllowPassword': 'Broadcast without password protection',
|
||||
'terminal.composeBar.resize': 'Resize compose bar height',
|
||||
'terminal.composeBar.manageSnippets': 'Manage quick snippets',
|
||||
'terminal.composeBar.searchSnippets': 'Search snippets...',
|
||||
@@ -134,6 +135,7 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.search.noResults': 'No results',
|
||||
'terminal.search.prevMatch': 'Previous match (Shift+Enter)',
|
||||
'terminal.search.nextMatch': 'Next match (Enter)',
|
||||
'terminal.menu.cut': 'Cut',
|
||||
'terminal.menu.copy': 'Copy',
|
||||
'terminal.menu.paste': 'Paste',
|
||||
'terminal.menu.uploadClipboardImage': 'Upload clipboard image',
|
||||
|
||||
@@ -279,6 +279,18 @@ export const esAiMessages: Messages = {
|
||||
'ai.opencode.check': 'Verificar',
|
||||
'ai.opencode.resetPath': 'Restablecer',
|
||||
|
||||
// AI MiMo Code (CLI de Xiaomi MiMo Code — fork de OpenCode)
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': 'CLI de MiMo Code de Xiaomi, un fork de OpenCode. Instálalo y configura los proveedores en su propia configuración, luego selecciónalo como agente de codificación externo.',
|
||||
'ai.mimo.detecting': 'Detectando...',
|
||||
'ai.mimo.detected': 'Detectado',
|
||||
'ai.mimo.notFound': 'No encontrado',
|
||||
'ai.mimo.path': 'Ruta:',
|
||||
'ai.mimo.notFoundHint': 'No se pudo encontrar mimo en el PATH. Instálalo o especifica la ruta del ejecutable a continuación.',
|
||||
'ai.mimo.customPathPlaceholder': 'p. ej. /usr/local/bin/mimo',
|
||||
'ai.mimo.check': 'Verificar',
|
||||
'ai.mimo.resetPath': 'Restablecer',
|
||||
|
||||
// AI Grok Build (in-app managed agent — distinct from External MCP client install)
|
||||
'ai.grok.title': 'Grok Build',
|
||||
'ai.grok.description': "La CLI de agente de codificación Grok Build de xAI. Instala la CLI de Grok, inicia sesión con `grok login` o define XAI_API_KEY, y luego selecciónala como agente externo.",
|
||||
@@ -315,6 +327,13 @@ export const esAiMessages: Messages = {
|
||||
|
||||
// External MCP (productized catalog MCP for Codex / Claude Code / Cursor)
|
||||
'ai.externalMcp.title': 'MCP externo',
|
||||
'ai.externalMcp.allowCommandOnHost': 'Siempre',
|
||||
'ai.externalMcp.allowCommandOnHostHint': 'Permitir siempre esta acción en este servidor.',
|
||||
'ai.externalMcp.allowAll': 'Permitir todas las acciones',
|
||||
'ai.externalMcp.allowSession': 'Esta conexión',
|
||||
'ai.externalMcp.allowSessionHint': 'Permitir todas las acciones de este cliente hasta que se desconecte.',
|
||||
'ai.externalMcp.allowHost': 'Este servidor',
|
||||
'ai.externalMcp.allowHostHint': 'Permitir siempre acciones en este servidor.',
|
||||
'ai.externalMcp.description': 'Expón Netcatty como un servidor MCP para clientes externos como Codex, Claude Code, Cursor y Grok. Usa las mismas herramientas del catálogo que los agentes de la aplicación (terminal, SFTP, Vault, reenvío de puertos). Mantén Netcatty en ejecución mientras los clientes estén conectados.',
|
||||
'ai.externalMcp.sessionsExposed': 'Sesiones en alcance: {count}',
|
||||
'ai.externalMcp.mode': 'Modo de disponibilidad',
|
||||
@@ -593,6 +612,10 @@ export const esAiMessages: Messages = {
|
||||
'terminal.layer.movePanelLeft': 'Mover panel a la izquierda',
|
||||
'terminal.layer.movePanelRight': 'Mover panel a la derecha',
|
||||
'terminal.layer.movePanelBottom': 'Mover panel a la parte inferior',
|
||||
'terminal.layer.choosePanelPosition': 'Cambiar posición',
|
||||
'terminal.layer.dockLeft': 'Izquierda',
|
||||
'terminal.layer.dockRight': 'Derecha',
|
||||
'terminal.layer.dockBottom': 'Abajo',
|
||||
'terminal.layer.closePanel': 'Cerrar panel',
|
||||
'terminal.layer.closePane': 'Cerrar división',
|
||||
'terminal.layer.resizeSplit': 'Redimensionar división',
|
||||
|
||||
@@ -227,8 +227,11 @@ export const esCoreMessages: Messages = {
|
||||
'settings.globalHotkey.toggleWindowDesc': 'Presiona una combinación de teclas para definir un atajo global que muestre u oculte la ventana.',
|
||||
'settings.globalHotkey.notSet': 'No configurada',
|
||||
'settings.globalHotkey.reset': 'Restablecer al valor predeterminado',
|
||||
'settings.globalHotkey.closeToTray': 'Cerrar a la bandeja del sistema',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'Cuando está activado, cerrar la ventana la minimiza a la bandeja del sistema en lugar de salir.',
|
||||
'settings.globalHotkey.closeToTray': 'Seguir en segundo plano al cerrar la ventana',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'Al cerrar la ventana, se oculta y la aplicación sigue activa. La visibilidad del icono de la bandeja se configura aparte.',
|
||||
'settings.globalHotkey.showTrayIcon': 'Mostrar icono de la bandeja del sistema',
|
||||
'settings.globalHotkey.showTrayIconDesc': 'Cuando está desactivado, el icono de la bandeja se oculta, pero la aplicación sigue ejecutándose en segundo plano.',
|
||||
'settings.globalHotkey.showTrayIconHiddenHint': 'Icono de la bandeja oculto. Vuelve a iniciar la aplicación o usa el atajo global para recuperar la ventana y vuelve a activar este ajuste para restaurar el icono.',
|
||||
'settings.globalHotkey.enabled': 'Activar tecla de acceso global',
|
||||
'settings.globalHotkey.enabledDesc': 'Registra atajos de teclado a nivel de todo el sistema. Cuando está desactivado, todas las teclas de acceso global se desregistran.',
|
||||
'settings.globalHotkey.hint': 'La tecla de acceso global funciona en todo el sistema para mostrar u ocultar la ventana rápidamente (terminal estilo Quake).',
|
||||
@@ -453,7 +456,7 @@ Resalta el panel dividido enfocado:
|
||||
'settings.appearance.windowOpacity': 'Opacidad de la ventana',
|
||||
'settings.appearance.windowOpacity.desc': 'Ajusta la transparencia de toda la ventana de la aplicación. Los valores más bajos también atenúan el texto de la terminal. Algunos entornos de escritorio de Linux pueden no admitir esto.',
|
||||
'settings.appearance.appIcon': 'Ícono de la aplicación',
|
||||
'settings.appearance.appIcon.desc': 'Elige un estilo de ícono para el dock o la barra de tareas que haga más fácil distinguir Netcatty al cambiar de aplicación. Se aplica en tiempo de ejecución; el ícono del paquete instalado no cambia.',
|
||||
'settings.appearance.appIcon.desc': 'Elige un estilo de ícono para el dock o la barra de tareas que haga más fácil distinguir Netcatty al cambiar de aplicación. En Windows, el icono del área de notificación usa el mismo estilo. Se aplica en tiempo de ejecución; el ícono del paquete instalado no cambia.',
|
||||
'settings.appearance.appIcon.original': 'Original',
|
||||
'settings.appearance.appIcon.bright': 'Brillante',
|
||||
'settings.appearance.appIcon.dark': 'Oscuro',
|
||||
@@ -529,6 +532,8 @@ Resalta el panel dividido enfocado:
|
||||
'settings.terminal.font.weightBold.desc': 'Peso del texto en negrita (100-900)',
|
||||
'settings.terminal.font.smoothing': 'Suavizado de fuente',
|
||||
'settings.terminal.font.smoothing.desc': 'Usar el anti-aliasing nativo de fuentes de macOS',
|
||||
'settings.terminal.font.ligatures': 'Ligaduras de fuente',
|
||||
'settings.terminal.font.ligatures.desc': 'Mostrar ligaduras como != cuando la fuente del terminal las incluye',
|
||||
'settings.terminal.font.linePadding': 'Espaciado de líneas',
|
||||
'settings.terminal.font.linePadding.desc': 'Espacio adicional entre líneas (0-10)',
|
||||
'settings.terminal.font.emulationType': 'Tipo de emulación de terminal',
|
||||
@@ -536,6 +541,8 @@ Resalta el panel dividido enfocado:
|
||||
'settings.terminal.cursor.style.block': 'Bloque',
|
||||
'settings.terminal.cursor.style.bar': 'Barra',
|
||||
'settings.terminal.cursor.style.underline': 'Subrayado',
|
||||
'settings.terminal.cursor.barWidth': 'Ancho del cursor de barra',
|
||||
'settings.terminal.cursor.barWidth.desc': 'Ancho de los cursores de barra utilizados por aplicaciones como vi (1-4 px)',
|
||||
'settings.terminal.cursor.blink': 'Parpadeo del cursor',
|
||||
'settings.terminal.cursor.highlightLine': 'Resaltar línea actual',
|
||||
'settings.terminal.cursor.highlightLine.desc':
|
||||
@@ -620,7 +627,10 @@ Resalta el panel dividido enfocado:
|
||||
'Envía el texto configurado en lugar del Enter normal al presionar Shift+Enter en la terminal.',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText': 'Texto a enviar',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText.desc':
|
||||
'Usa \\n para nueva línea, \\t para tabulación y \\\\ para barra invertida.',
|
||||
'Usa \\n para nueva línea, \\t para tabulación, \\e para Escape y \\\\ para barra invertida.',
|
||||
'settings.terminal.behavior.shiftEnterForceText': 'Enviar texto también en modo de entrada Win32',
|
||||
'settings.terminal.behavior.shiftEnterForceText.desc':
|
||||
'Envía también el texto anterior cuando una sesión ConPTY local de Windows negocia el modo de entrada Win32. Necesario para CLI escritas en Node/Bun (Claude Code, CodeBuddy) que no pueden leer modificadores desde los registros de entrada de la consola.',
|
||||
'settings.terminal.behavior.clearWipesScrollback': '`clear` borra el historial de desplazamiento',
|
||||
'settings.terminal.behavior.clearWipesScrollback.desc':
|
||||
'Haz que `clear` también borre el buffer del historial de desplazamiento (predeterminado de POSIX). Desactívalo para mantener visible el historial después de `clear`.',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const esScriptsMessages = {
|
||||
'scripts.actions.runParallel': 'Ejecutar en todas las pestañas (en paralelo)',
|
||||
'scripts.actions.runSequential': 'Ejecutar en todas las pestañas (en secuencia)',
|
||||
'scripts.actions.runOnAllTabs': 'Ejecutar en todas las pestañas',
|
||||
'scripts.actions.copyCommand': 'Copiar comando',
|
||||
'scripts.actions.copyCommand.copied': 'Comando copiado',
|
||||
'scripts.actions.copyCommand.failed': 'No se pudo copiar el comando',
|
||||
'scripts.actions.skippedConnectingSessions': '{count} pestaña(s) aún conectándose y fueron omitidas',
|
||||
'scripts.actions.skippedSensitiveSessions': '{count} pestaña(s) omitidas (entrada de contraseña/datos sensibles)',
|
||||
'scripts.actions.noRunnableHosts': 'Ningún host conectable coincide con los destinos de este script',
|
||||
|
||||
@@ -31,6 +31,7 @@ export const esSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadPorts': 'No se pudieron cargar los puertos en escucha',
|
||||
'systemManager.errors.loadServices': 'No se pudieron cargar los servicios de systemd',
|
||||
'systemManager.errors.sshChannelUnavailable': 'El servidor se negó a abrir un nuevo canal de ejecución. Inténtalo de nuevo más tarde o vuelve a conectar este host.',
|
||||
'systemManager.unsupportedRemote': 'Este host no permite canales SSH de ejecución adicionales, por lo que el administrador del sistema no está disponible. Abrir este panel ya no desconectará la terminal.',
|
||||
|
||||
'systemManager.overview.empty': 'Aún no hay datos de resumen del sistema.',
|
||||
'systemManager.overview.loading': 'Cargando resumen del sistema…',
|
||||
|
||||
@@ -61,6 +61,7 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.composeBar.send': 'Enviar',
|
||||
'terminal.composeBar.close': 'Cerrar barra de redacción',
|
||||
'terminal.composeBar.broadcasting': 'Difundiendo a todas las sesiones',
|
||||
'terminal.composeBar.broadcastAllowPassword': 'Difundir sin protección de contraseña',
|
||||
'terminal.composeBar.resize': 'Cambiar la altura de la barra de redacción',
|
||||
'terminal.composeBar.manageSnippets': 'Administrar snippets rápidos',
|
||||
'terminal.composeBar.searchSnippets': 'Buscar snippets...',
|
||||
@@ -134,6 +135,7 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.search.noResults': 'Sin resultados',
|
||||
'terminal.search.prevMatch': 'Coincidencia anterior (Shift+Enter)',
|
||||
'terminal.search.nextMatch': 'Coincidencia siguiente (Enter)',
|
||||
'terminal.menu.cut': 'Cortar',
|
||||
'terminal.menu.copy': 'Copiar',
|
||||
'terminal.menu.paste': 'Pegar',
|
||||
'terminal.menu.uploadClipboardImage': 'Subir imagen del portapapeles',
|
||||
|
||||
@@ -283,6 +283,13 @@ export const ruAiMessages: Messages = {
|
||||
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
|
||||
|
||||
'ai.externalMcp.title': 'Внешний MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': 'Всегда',
|
||||
'ai.externalMcp.allowCommandOnHostHint': 'Всегда разрешать это действие на этом сервере.',
|
||||
'ai.externalMcp.allowAll': 'Разрешить все действия',
|
||||
'ai.externalMcp.allowSession': 'Это подключение',
|
||||
'ai.externalMcp.allowSessionHint': 'Разрешать все действия клиента до отключения.',
|
||||
'ai.externalMcp.allowHost': 'Этот сервер',
|
||||
'ai.externalMcp.allowHostHint': 'Всегда разрешать действия на этом сервере.',
|
||||
'ai.externalMcp.description': 'Откройте Netcatty как MCP-сервер для Codex, Claude Code, Cursor и Grok. Набор инструментов тот же, что у встроенных агентов. Держите Netcatty запущенным, пока клиенты подключены.',
|
||||
'ai.externalMcp.sessionsExposed': 'Сессий в области: {count}',
|
||||
'ai.externalMcp.mode': 'Режим доступности',
|
||||
@@ -561,6 +568,10 @@ export const ruAiMessages: Messages = {
|
||||
'terminal.layer.movePanelLeft': 'Переместить панель влево',
|
||||
'terminal.layer.movePanelRight': 'Переместить панель вправо',
|
||||
'terminal.layer.movePanelBottom': 'Переместить панель вниз',
|
||||
'terminal.layer.choosePanelPosition': 'Изменить положение',
|
||||
'terminal.layer.dockLeft': 'Слева',
|
||||
'terminal.layer.dockRight': 'Справа',
|
||||
'terminal.layer.dockBottom': 'Снизу',
|
||||
'terminal.layer.closePanel': 'Закрыть панель',
|
||||
'terminal.layer.closePane': 'Закрыть область',
|
||||
'terminal.layer.resizeSplit': 'Изменить размер области',
|
||||
|
||||
@@ -296,8 +296,11 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.globalHotkey.toggleWindowDesc': 'Нажмите сочетание клавиш, чтобы задать глобальную горячую клавишу для показа или скрытия окна.',
|
||||
'settings.globalHotkey.notSet': 'Не задано',
|
||||
'settings.globalHotkey.reset': 'Сбросить по умолчанию',
|
||||
'settings.globalHotkey.closeToTray': 'Сворачивать в системный трей',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'Если включено, при закрытии окно будет сворачиваться в системный трей вместо выхода из приложения.',
|
||||
'settings.globalHotkey.closeToTray': 'Оставлять приложение в фоне при закрытии окна',
|
||||
'settings.globalHotkey.closeToTrayDesc': 'При закрытии окно скрывается, а приложение продолжает работать. Отображение значка в трее настраивается отдельно.',
|
||||
'settings.globalHotkey.showTrayIcon': 'Показывать значок в системном трее',
|
||||
'settings.globalHotkey.showTrayIconDesc': 'Если отключено, значок в трее скрыт, но приложение продолжает работать в фоне.',
|
||||
'settings.globalHotkey.showTrayIconHiddenHint': 'Значок в трее скрыт. Запустите приложение снова или используйте глобальную горячую клавишу, чтобы вернуть окно, затем снова включите этот параметр, чтобы восстановить значок.',
|
||||
'settings.globalHotkey.enabled': 'Включить глобальную горячую клавишу',
|
||||
'settings.globalHotkey.enabledDesc': 'Регистрировать системные сочетания клавиш. Когда отключено, все глобальные горячие клавиши снимаются с регистрации.',
|
||||
'settings.globalHotkey.hint': 'Глобальная горячая клавиша работает на уровне всей системы и позволяет быстро показывать или скрывать окно (терминал в стиле Quake).',
|
||||
@@ -507,7 +510,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.appearance.windowOpacity': 'Прозрачность окна',
|
||||
'settings.appearance.windowOpacity.desc': 'Настройте прозрачность всего окна приложения. При низких значениях текст терминала тоже бледнеет. В некоторых средах Linux это может не поддерживаться.',
|
||||
'settings.appearance.appIcon': 'Значок приложения',
|
||||
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. Применяется во время работы; значок установленного пакета не меняется.',
|
||||
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. В Windows значок области уведомлений использует тот же стиль. Применяется во время работы; значок установленного пакета не меняется.',
|
||||
'settings.appearance.appIcon.original': 'Оригинал',
|
||||
'settings.appearance.appIcon.bright': 'Яркий',
|
||||
'settings.appearance.appIcon.dark': 'Тёмный',
|
||||
@@ -582,6 +585,8 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.font.weightBold.desc': 'Толщина жирного текста (100-900)',
|
||||
'settings.terminal.font.smoothing': 'Сглаживание шрифта',
|
||||
'settings.terminal.font.smoothing.desc': 'Использовать родное сглаживание шрифтов macOS',
|
||||
'settings.terminal.font.ligatures': 'Лигатуры шрифта',
|
||||
'settings.terminal.font.ligatures.desc': 'Показывать лигатуры вроде !=, если шрифт терминала их содержит',
|
||||
'settings.terminal.font.linePadding': 'Межстрочный отступ',
|
||||
'settings.terminal.font.linePadding.desc': 'Дополнительное пространство между строками (0-10)',
|
||||
'settings.terminal.font.emulationType': 'Тип эмуляции терминала',
|
||||
@@ -589,6 +594,8 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.cursor.style.block': 'Блок',
|
||||
'settings.terminal.cursor.style.bar': 'Полоса',
|
||||
'settings.terminal.cursor.style.underline': 'Подчёркивание',
|
||||
'settings.terminal.cursor.barWidth': 'Толщина курсора-полосы',
|
||||
'settings.terminal.cursor.barWidth.desc': 'Ширина курсоров-полос, используемых приложениями вроде vi (1-4 пикс.)',
|
||||
'settings.terminal.cursor.blink': 'Мигание курсора',
|
||||
'settings.terminal.cursor.highlightLine': 'Подсветка текущей строки',
|
||||
'settings.terminal.cursor.highlightLine.desc':
|
||||
@@ -656,7 +663,10 @@ export const ruCoreMessages: Messages = {
|
||||
'Отправлять настроенный текст вместо обычного Enter при нажатии Shift+Enter в терминале.',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText': 'Отправляемый текст',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText.desc':
|
||||
'Используйте \\n для перевода строки, \\t для табуляции и \\\\ для обратной косой черты.',
|
||||
'Используйте \\n для перевода строки, \\t для табуляции, \\e для Escape и \\\\ для обратной косой черты.',
|
||||
'settings.terminal.behavior.shiftEnterForceText': 'Отправлять текст и в режиме ввода Win32',
|
||||
'settings.terminal.behavior.shiftEnterForceText.desc':
|
||||
'Отправлять указанный выше текст даже когда локальная сессия Windows ConPTY согласует режим ввода Win32. Нужно для CLI на Node/Bun (Claude Code, CodeBuddy), которые не читают модификаторы из записей ввода консоли.',
|
||||
'settings.terminal.behavior.clearWipesScrollback': '`clear` очищает буфер прокрутки',
|
||||
'settings.terminal.behavior.clearWipesScrollback.desc':
|
||||
'Команда `clear` также будет очищать буфер прокрутки (поведение POSIX по умолчанию). Отключите, чтобы история оставалась видимой после `clear`.',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const ruScriptsMessages = {
|
||||
'scripts.actions.runParallel': 'Запустить на всех вкладках (параллельно)',
|
||||
'scripts.actions.runSequential': 'Запустить на всех вкладках (последовательно)',
|
||||
'scripts.actions.runOnAllTabs': 'Запустить на всех вкладках',
|
||||
'scripts.actions.copyCommand': 'Копировать команду',
|
||||
'scripts.actions.copyCommand.copied': 'Команда скопирована',
|
||||
'scripts.actions.copyCommand.failed': 'Не удалось скопировать команду',
|
||||
'scripts.actions.skippedConnectingSessions': 'Пропущено вкладок, которые ещё подключаются: {count}',
|
||||
'scripts.actions.skippedSensitiveSessions': 'Пропущено вкладок с паролем/чувствительным вводом: {count}',
|
||||
'scripts.actions.noRunnableHosts': 'Нет доступных для подключения хостов, соответствующих целям этого скрипта',
|
||||
|
||||
@@ -31,6 +31,7 @@ export const ruSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
|
||||
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
|
||||
'systemManager.errors.sshChannelUnavailable': 'Сервер отказался открыть новый канал выполнения. Повторите попытку позже или переподключите этот хост.',
|
||||
'systemManager.unsupportedRemote': 'Этот хост не разрешает дополнительные SSH exec-каналы, поэтому системная панель недоступна. Открытие панели больше не разрывает терминал.',
|
||||
|
||||
'systemManager.overview.empty': 'Данных обзора пока нет.',
|
||||
'systemManager.overview.loading': 'Загрузка обзора системы…',
|
||||
|
||||
@@ -82,6 +82,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.composeBar.send': 'Отправить',
|
||||
'terminal.composeBar.close': 'Закрыть строку ввода',
|
||||
'terminal.composeBar.broadcasting': 'Трансляция во все сессии',
|
||||
'terminal.composeBar.broadcastAllowPassword': 'Транслировать без защиты пароля',
|
||||
'terminal.composeBar.resize': 'Изменить высоту строки ввода',
|
||||
'terminal.composeBar.manageSnippets': 'Управление быстрыми сниппетами',
|
||||
'terminal.composeBar.searchSnippets': 'Поиск сниппетов...',
|
||||
@@ -155,6 +156,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.search.noResults': 'Ничего не найдено',
|
||||
'terminal.search.prevMatch': 'Предыдущее совпадение (Shift+Enter)',
|
||||
'terminal.search.nextMatch': 'Следующее совпадение (Enter)',
|
||||
'terminal.menu.cut': 'Вырезать',
|
||||
'terminal.menu.copy': 'Копировать',
|
||||
'terminal.menu.paste': 'Вставить',
|
||||
'terminal.menu.uploadClipboardImage': 'Загрузить изображение из буфера',
|
||||
|
||||
@@ -7,9 +7,11 @@ import { HOST_ICON_COLORS, HOST_ICON_IDS } from "../../../domain/hostIcon.ts";
|
||||
import zhCN from "./zh-CN.ts";
|
||||
import ru from "./ru.ts";
|
||||
import es from "./es.ts";
|
||||
import zhTW from "./zh-TW.ts";
|
||||
|
||||
const LOCALIZED_SETTINGS_LOCALES = [
|
||||
{ name: "zh-CN", messages: zhCN },
|
||||
{ name: "zh-TW", messages: zhTW },
|
||||
{ name: "ru", messages: ru },
|
||||
{ name: "es", messages: es },
|
||||
];
|
||||
@@ -83,6 +85,21 @@ test("localized settings include OSC desktop notification labels", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("localized settings include bar cursor width labels", () => {
|
||||
const keys = [
|
||||
"settings.terminal.cursor.barWidth",
|
||||
"settings.terminal.cursor.barWidth.desc",
|
||||
];
|
||||
|
||||
for (const locale of [
|
||||
{ name: "en", messages: en },
|
||||
...LOCALIZED_SETTINGS_LOCALES,
|
||||
]) {
|
||||
const missing = keys.filter((key) => !locale.messages[key]);
|
||||
assert.deepEqual(missing, [], `${locale.name} is missing bar cursor width labels`);
|
||||
}
|
||||
});
|
||||
|
||||
test("localized settings include terminal font weight option labels", () => {
|
||||
const keys = [
|
||||
"settings.terminal.font.weight.thin",
|
||||
|
||||
@@ -288,6 +288,18 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.opencode.check': '检查',
|
||||
'ai.opencode.resetPath': '重置',
|
||||
|
||||
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安装后在它自己的配置里配置 provider 和密钥,检测到后即可作为外部编程 Agent 使用。',
|
||||
'ai.mimo.detecting': '检测中...',
|
||||
'ai.mimo.detected': '已检测到',
|
||||
'ai.mimo.notFound': '未找到',
|
||||
'ai.mimo.path': '路径:',
|
||||
'ai.mimo.notFoundHint': '在 PATH 中未找到 mimo。请安装或在下方指定可执行文件路径。',
|
||||
'ai.mimo.customPathPlaceholder': '例如 /usr/local/bin/mimo',
|
||||
'ai.mimo.check': '检查',
|
||||
'ai.mimo.resetPath': '重置',
|
||||
|
||||
// AI Grok Build(应用内托管 Agent,与 External MCP「添加到 Grok」不同)
|
||||
'ai.grok.title': 'Grok Build',
|
||||
'ai.grok.description': 'xAI 的 Grok Build 编程 Agent CLI。安装 Grok CLI,使用 `grok login` 登录或设置 XAI_API_KEY 后,即可作为外部 Agent 选择。',
|
||||
@@ -324,6 +336,13 @@ export const zhCNAiMessages: Messages = {
|
||||
|
||||
// External MCP
|
||||
'ai.externalMcp.title': '对外 MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': '始终',
|
||||
'ai.externalMcp.allowCommandOnHostHint': '始终允许在此服务器执行同类操作。',
|
||||
'ai.externalMcp.allowAll': '允许所有操作',
|
||||
'ai.externalMcp.allowSession': '此次连接',
|
||||
'ai.externalMcp.allowSessionHint': '在客户端断开前,允许此次连接的所有操作。',
|
||||
'ai.externalMcp.allowHost': '此服务器',
|
||||
'ai.externalMcp.allowHostHint': '始终允许操作此服务器。',
|
||||
'ai.externalMcp.description': '把 Netcatty 作为 MCP 服务器暴露给 Codex、Claude Code、Cursor、Grok 等外部客户端。工具面与应用内 Agent 相同(终端、SFTP、Vault、端口转发)。客户端连接期间请保持 Netcatty 运行。',
|
||||
'ai.externalMcp.sessionsExposed': '作用域内会话:{count}',
|
||||
'ai.externalMcp.mode': '可用模式',
|
||||
@@ -602,6 +621,10 @@ export const zhCNAiMessages: Messages = {
|
||||
'terminal.layer.movePanelLeft': '面板移至左侧',
|
||||
'terminal.layer.movePanelRight': '面板移至右侧',
|
||||
'terminal.layer.movePanelBottom': '面板移至底部',
|
||||
'terminal.layer.choosePanelPosition': '改变位置',
|
||||
'terminal.layer.dockLeft': '左侧',
|
||||
'terminal.layer.dockRight': '右侧',
|
||||
'terminal.layer.dockBottom': '底部',
|
||||
'terminal.layer.closePanel': '关闭面板',
|
||||
'terminal.layer.closePane': '关闭分屏',
|
||||
'terminal.layer.saveLayoutAsDefault': '将布局保存为默认',
|
||||
|
||||
@@ -316,8 +316,11 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.globalHotkey.toggleWindowDesc': '按下组合键以设置显示/隐藏窗口的全局快捷键。',
|
||||
'settings.globalHotkey.notSet': '未设置',
|
||||
'settings.globalHotkey.reset': '恢复默认',
|
||||
'settings.globalHotkey.closeToTray': '关闭时最小化到托盘',
|
||||
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口将最小化到系统托盘而不是退出程序。',
|
||||
'settings.globalHotkey.closeToTray': '关闭窗口后在后台运行',
|
||||
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口会隐藏窗口,应用继续在后台运行。托盘图标可单独开关。',
|
||||
'settings.globalHotkey.showTrayIcon': '显示系统托盘图标',
|
||||
'settings.globalHotkey.showTrayIconDesc': '关闭后,托盘图标将被隐藏,但应用仍会在后台正常运行。',
|
||||
'settings.globalHotkey.showTrayIconHiddenHint': '托盘图标已隐藏。再次启动应用或使用全局显示/隐藏快捷键即可找回窗口,然后重新打开此设置即可恢复图标。',
|
||||
'settings.globalHotkey.enabled': '启用全局快捷键',
|
||||
'settings.globalHotkey.enabledDesc': '注册系统级键盘快捷键。禁用后将取消所有全局快捷键注册。',
|
||||
'settings.globalHotkey.hint': '全局快捷键在系统范围内工作,可快速显示或隐藏窗口(下拉式终端风格)。',
|
||||
@@ -542,7 +545,7 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.appearance.windowOpacity': '窗口透明度',
|
||||
'settings.appearance.windowOpacity.desc': '调节整个应用窗口的透明度,方便叠在其他内容上方。较低时终端文字也会变淡;部分 Linux 桌面环境可能不支持。',
|
||||
'settings.appearance.appIcon': '应用图标',
|
||||
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。运行时生效,安装包内的图标不会改变。',
|
||||
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。Windows 通知区域图标会使用同一套风格。运行时生效,安装包内的图标不会改变。',
|
||||
'settings.appearance.appIcon.original': '原始',
|
||||
'settings.appearance.appIcon.bright': '明亮',
|
||||
'settings.appearance.appIcon.dark': '深色',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const zhCNScriptsMessages = {
|
||||
'scripts.actions.runParallel': '在所有标签页并行运行',
|
||||
'scripts.actions.runSequential': '在所有标签页顺序运行',
|
||||
'scripts.actions.runOnAllTabs': '在所有标签页运行',
|
||||
'scripts.actions.copyCommand': '复制命令',
|
||||
'scripts.actions.copyCommand.copied': '命令已复制',
|
||||
'scripts.actions.copyCommand.failed': '复制命令失败',
|
||||
'scripts.actions.skippedConnectingSessions': '有 {count} 个标签仍在连接中,已跳过',
|
||||
'scripts.actions.skippedSensitiveSessions': '有 {count} 个标签处于密码/敏感输入,已跳过',
|
||||
'scripts.actions.noRunnableHosts': '没有与脚本目标匹配的可连接主机',
|
||||
|
||||
@@ -31,6 +31,7 @@ export const zhCnSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadPorts': '加载监听端口失败',
|
||||
'systemManager.errors.loadServices': '加载 systemd 服务失败',
|
||||
'systemManager.errors.sshChannelUnavailable': '服务器拒绝打开新的执行通道。请稍后重试,或重新连接当前主机。',
|
||||
'systemManager.unsupportedRemote': '该主机不允许额外的 SSH 执行通道,系统面板不可用。打开此面板不会再断开当前终端。',
|
||||
|
||||
'systemManager.overview.empty': '暂无系统概览数据。',
|
||||
'systemManager.overview.loading': '正在加载系统概览…',
|
||||
|
||||
@@ -278,6 +278,8 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.terminal.font.weightBold.desc': '粗体文本字重 (100-900)',
|
||||
'settings.terminal.font.smoothing': '字体平滑',
|
||||
'settings.terminal.font.smoothing.desc': '使用 macOS 原生字体抗锯齿',
|
||||
'settings.terminal.font.ligatures': '字体连字',
|
||||
'settings.terminal.font.ligatures.desc': '支持连字的字体把 != 这类字符显示成一个符号',
|
||||
'settings.terminal.font.linePadding': '行间距',
|
||||
'settings.terminal.font.linePadding.desc': '行之间的额外间距 (0-10)',
|
||||
'settings.terminal.font.emulationType': '终端仿真类型',
|
||||
@@ -285,6 +287,8 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.terminal.cursor.style.block': '块',
|
||||
'settings.terminal.cursor.style.bar': '竖线',
|
||||
'settings.terminal.cursor.style.underline': '下划线',
|
||||
'settings.terminal.cursor.barWidth': '竖线光标粗细',
|
||||
'settings.terminal.cursor.barWidth.desc': 'vi 等应用使用竖线光标时的宽度(1-4 像素)',
|
||||
'settings.terminal.cursor.blink': '光标闪烁',
|
||||
'settings.terminal.cursor.highlightLine': '高亮当前行',
|
||||
'settings.terminal.cursor.highlightLine.desc': '为光标所在行加上淡色背景,方便定位当前输入位置',
|
||||
@@ -344,7 +348,10 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'在终端中按 Shift+Enter 时发送配置的文本,而不是普通回车。',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText': '发送内容',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText.desc':
|
||||
'使用 \\n 表示换行,\\t 表示 Tab,\\\\ 表示反斜杠。',
|
||||
'使用 \\n 表示换行,\\t 表示 Tab,\\e 表示 ESC,\\\\ 表示反斜杠。',
|
||||
'settings.terminal.behavior.shiftEnterForceText': '在 Win32 输入模式下也发送文本',
|
||||
'settings.terminal.behavior.shiftEnterForceText.desc':
|
||||
'本机 Windows ConPTY 会话协商 Win32 输入模式时,仍然发送上面的文本。Node/Bun 写的 CLI(Claude Code、CodeBuddy)读不到控制台输入记录里的修饰键,需要这个开关才能区分 Shift+Enter。',
|
||||
'settings.terminal.behavior.clearWipesScrollback': '`clear` 同时清空回滚历史',
|
||||
'settings.terminal.behavior.clearWipesScrollback.desc':
|
||||
'`clear` 命令同时清空回滚历史(POSIX 默认行为)。关闭则保留历史。',
|
||||
|
||||
@@ -466,6 +466,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'terminal.composeBar.send': '发送',
|
||||
'terminal.composeBar.close': '关闭撰写栏',
|
||||
'terminal.composeBar.broadcasting': '正在广播到所有会话',
|
||||
'terminal.composeBar.broadcastAllowPassword': '广播时不对密码进行保护',
|
||||
'terminal.composeBar.resize': '拖拽调整撰写栏高度',
|
||||
'terminal.composeBar.manageSnippets': '管理快捷代码片段',
|
||||
'terminal.composeBar.searchSnippets': '搜索代码片段...',
|
||||
@@ -537,6 +538,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'terminal.search.noResults': '无结果',
|
||||
'terminal.search.prevMatch': '上一个匹配 (Shift+Enter)',
|
||||
'terminal.search.nextMatch': '下一个匹配 (Enter)',
|
||||
'terminal.menu.cut': '剪切',
|
||||
'terminal.menu.copy': '复制',
|
||||
'terminal.menu.paste': '粘贴',
|
||||
'terminal.menu.addSelectionToAI': '添加到对话',
|
||||
|
||||
@@ -279,6 +279,18 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.opencode.check': '檢查',
|
||||
'ai.opencode.resetPath': '重設',
|
||||
|
||||
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安裝後在它自己的設定裡設定 provider 和金鑰,偵測到後即可作為外部程式設計 Agent 使用。',
|
||||
'ai.mimo.detecting': '偵測中...',
|
||||
'ai.mimo.detected': '已偵測到',
|
||||
'ai.mimo.notFound': '未找到',
|
||||
'ai.mimo.path': '路徑:',
|
||||
'ai.mimo.notFoundHint': '在 PATH 中未找到 mimo。請安裝或在下方指定執行檔路徑。',
|
||||
'ai.mimo.customPathPlaceholder': '例如 /usr/local/bin/mimo',
|
||||
'ai.mimo.check': '檢查',
|
||||
'ai.mimo.resetPath': '重設',
|
||||
|
||||
// AI Grok Build(應用內託管 Agent,與 External MCP「新增到 Grok」不同)
|
||||
'ai.grok.title': 'Grok Build',
|
||||
'ai.grok.description': 'xAI 的 Grok Build 程式設計 Agent CLI。安裝 Grok CLI,使用 `grok login` 登入或設定 XAI_API_KEY 後,即可作為外部 Agent 選擇。',
|
||||
@@ -314,6 +326,13 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.toolAccess.skills.unavailable': '暫時無法取得 Skill 檔案路徑',
|
||||
|
||||
'ai.externalMcp.title': '對外 MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': '始終',
|
||||
'ai.externalMcp.allowCommandOnHostHint': '始終允許在此伺服器執行同類操作。',
|
||||
'ai.externalMcp.allowAll': '允許所有操作',
|
||||
'ai.externalMcp.allowSession': '此次連線',
|
||||
'ai.externalMcp.allowSessionHint': '在用戶端中斷前,允許此次連線的所有操作。',
|
||||
'ai.externalMcp.allowHost': '此伺服器',
|
||||
'ai.externalMcp.allowHostHint': '始終允許操作此伺服器。',
|
||||
'ai.externalMcp.description': '將 Netcatty 作為 MCP 伺服器暴露給 Codex、Claude Code、Cursor、Grok 等外部用戶端。工具面與應用內 Agent 相同。用戶端連線期間請保持 Netcatty 執行。',
|
||||
'ai.externalMcp.sessionsExposed': '作用域內工作階段:{count}',
|
||||
'ai.externalMcp.mode': '可用模式',
|
||||
@@ -592,6 +611,10 @@ export const zhTWAiMessages: Messages = {
|
||||
'terminal.layer.movePanelLeft': '面板移至左側',
|
||||
'terminal.layer.movePanelRight': '面板移至右側',
|
||||
'terminal.layer.movePanelBottom': '面板移至底部',
|
||||
'terminal.layer.choosePanelPosition': '變更位置',
|
||||
'terminal.layer.dockLeft': '左側',
|
||||
'terminal.layer.dockRight': '右側',
|
||||
'terminal.layer.dockBottom': '底部',
|
||||
'terminal.layer.closePanel': '關閉面板',
|
||||
'terminal.layer.closePane': '關閉分割',
|
||||
'terminal.layer.saveLayoutAsDefault': '將佈局儲存為預設',
|
||||
|
||||
@@ -318,8 +318,11 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.globalHotkey.toggleWindowDesc': '按下組合鍵以設定顯示/隱藏視窗的全域快速鍵。',
|
||||
'settings.globalHotkey.notSet': '未設定',
|
||||
'settings.globalHotkey.reset': '恢復預設',
|
||||
'settings.globalHotkey.closeToTray': '關閉時最小化到系統匣',
|
||||
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗將最小化到系統匣而不是結束程式。',
|
||||
'settings.globalHotkey.closeToTray': '關閉視窗後在背景執行',
|
||||
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗會隱藏視窗,應用程式繼續在背景執行。系統匣圖示可另外開關。',
|
||||
'settings.globalHotkey.showTrayIcon': '顯示系統匣圖示',
|
||||
'settings.globalHotkey.showTrayIconDesc': '關閉後,系統匣圖示將被隱藏,但應用程式仍會在背景正常執行。',
|
||||
'settings.globalHotkey.showTrayIconHiddenHint': '系統匣圖示已隱藏。再次啟動應用程式或使用全域顯示/隱藏快捷鍵即可找回視窗,然後重新開啟此設定即可恢復圖示。',
|
||||
'settings.globalHotkey.enabled': '啟用全域快速鍵',
|
||||
'settings.globalHotkey.enabledDesc': '註冊系統級鍵盤快速鍵。停用後將取消所有全域快速鍵註冊。',
|
||||
'settings.globalHotkey.hint': '全域快速鍵在系統範圍內工作,可快速顯示或隱藏視窗(下拉式終端風格)。',
|
||||
@@ -544,7 +547,7 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.appearance.windowOpacity': '視窗透明度',
|
||||
'settings.appearance.windowOpacity.desc': '調節整個應用程式視窗的透明度,方便疊在其他內容上方。較低時終端文字也會變淡;部分 Linux 桌面環境可能不支援。',
|
||||
'settings.appearance.appIcon': '應用程式圖示',
|
||||
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。執行時生效,安裝檔內的圖示不會改變。',
|
||||
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。Windows 通知區域圖示會使用同一套風格。執行時生效,安裝檔內的圖示不會改變。',
|
||||
'settings.appearance.appIcon.original': '原始',
|
||||
'settings.appearance.appIcon.bright': '明亮',
|
||||
'settings.appearance.appIcon.dark': '深色',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const zhTWScriptsMessages = {
|
||||
'scripts.actions.runParallel': '在所有分頁並行執行',
|
||||
'scripts.actions.runSequential': '在所有分頁依序執行',
|
||||
'scripts.actions.runOnAllTabs': '在所有分頁執行',
|
||||
'scripts.actions.copyCommand': '複製指令',
|
||||
'scripts.actions.copyCommand.copied': '指令已複製',
|
||||
'scripts.actions.copyCommand.failed': '複製指令失敗',
|
||||
'scripts.actions.skippedConnectingSessions': '有 {count} 個分頁仍在連線中,已跳過',
|
||||
'scripts.actions.skippedSensitiveSessions': '有 {count} 個分頁處於密碼/敏感輸入,已跳過',
|
||||
'scripts.actions.noRunnableHosts': '沒有與指令碼目標相符的可連線主機',
|
||||
|
||||
@@ -31,6 +31,7 @@ export const zhTwSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadPorts': '載入監聽連接埠失敗',
|
||||
'systemManager.errors.loadServices': '載入 systemd 服務失敗',
|
||||
'systemManager.errors.sshChannelUnavailable': '伺服器拒絕開啟新的執行通道。請稍後重試,或重新連線目前主機。',
|
||||
'systemManager.unsupportedRemote': '此主機不允許額外的 SSH 執行通道,系統面板無法使用。開啟此面板不會再中斷目前終端。',
|
||||
|
||||
'systemManager.overview.empty': '暫無系統概覽資料。',
|
||||
'systemManager.overview.loading': '正在載入系統概覽…',
|
||||
|
||||
@@ -278,6 +278,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.terminal.font.weightBold.desc': '粗體文字字重 (100-900)',
|
||||
'settings.terminal.font.smoothing': '字型平滑',
|
||||
'settings.terminal.font.smoothing.desc': '使用 macOS 原生字型抗鋸齒',
|
||||
'settings.terminal.font.ligatures': '字型連字',
|
||||
'settings.terminal.font.ligatures.desc': '支援連字的字型把 != 這類字元顯示成一個符號',
|
||||
'settings.terminal.font.linePadding': '行間距',
|
||||
'settings.terminal.font.linePadding.desc': '行之間的額外間距 (0-10)',
|
||||
'settings.terminal.font.emulationType': '終端模擬型別',
|
||||
@@ -285,6 +287,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.terminal.cursor.style.block': '塊',
|
||||
'settings.terminal.cursor.style.bar': '豎線',
|
||||
'settings.terminal.cursor.style.underline': '下劃線',
|
||||
'settings.terminal.cursor.barWidth': '豎線游標粗細',
|
||||
'settings.terminal.cursor.barWidth.desc': 'vi 等應用程式使用豎線游標時的寬度(1-4 像素)',
|
||||
'settings.terminal.cursor.blink': '游標閃爍',
|
||||
'settings.terminal.cursor.highlightLine': '高亮目前行',
|
||||
'settings.terminal.cursor.highlightLine.desc': '為游標所在行加上淡色背景,方便定位目前輸入位置',
|
||||
@@ -344,7 +348,10 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'在終端中按 Shift+Enter 時傳送設定的文字,而不是一般 Enter。',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText': '傳送內容',
|
||||
'settings.terminal.behavior.shiftEnterNewlineText.desc':
|
||||
'使用 \\n 表示換行,\\t 表示 Tab,\\\\ 表示反斜線。',
|
||||
'使用 \\n 表示換行,\\t 表示 Tab,\\e 表示 ESC,\\\\ 表示反斜線。',
|
||||
'settings.terminal.behavior.shiftEnterForceText': '在 Win32 輸入模式下也傳送文字',
|
||||
'settings.terminal.behavior.shiftEnterForceText.desc':
|
||||
'本機 Windows ConPTY 工作階段協商 Win32 輸入模式時,仍然傳送上面的文字。Node/Bun 寫的 CLI(Claude Code、CodeBuddy)讀不到主控台輸入記錄中的修飾鍵,需要這個開關才能區分 Shift+Enter。',
|
||||
'settings.terminal.behavior.clearWipesScrollback': '`clear` 同時清空捲動緩衝',
|
||||
'settings.terminal.behavior.clearWipesScrollback.desc':
|
||||
'`clear` 指令同時清空捲動緩衝(POSIX 預設行為)。關閉則保留歷史。',
|
||||
|
||||
@@ -466,6 +466,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'terminal.composeBar.send': '傳送',
|
||||
'terminal.composeBar.close': '關閉撰寫欄',
|
||||
'terminal.composeBar.broadcasting': '正在廣播到所有工作階段',
|
||||
'terminal.composeBar.broadcastAllowPassword': '廣播時不對密碼進行保護',
|
||||
'terminal.composeBar.resize': '拖曳調整撰寫欄高度',
|
||||
'terminal.composeBar.manageSnippets': '管理快捷程式碼片段',
|
||||
'terminal.composeBar.searchSnippets': '搜尋程式碼片段...',
|
||||
@@ -537,6 +538,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'terminal.search.noResults': '無結果',
|
||||
'terminal.search.prevMatch': '上一個相符 (Shift+Enter)',
|
||||
'terminal.search.nextMatch': '下一個相符 (Enter)',
|
||||
'terminal.menu.cut': '剪下',
|
||||
'terminal.menu.copy': '複製',
|
||||
'terminal.menu.paste': '貼上',
|
||||
'terminal.menu.addSelectionToAI': '新增到對話',
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
formatSessionClosedExitMessage,
|
||||
resolveTerminalSessionExitIntent,
|
||||
shouldCloseTerminalPopupOnExit,
|
||||
shouldRevealTerminalPopupOnExit,
|
||||
@@ -120,3 +121,32 @@ test("attached terminal popups keep their existing auto-close behavior by defaul
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("exit messages show the reported code for a real remote exit", () => {
|
||||
assert.equal(
|
||||
formatSessionClosedExitMessage({ reason: "exited", exitCode: 0 }),
|
||||
"\r\n[session closed (code 0)]",
|
||||
);
|
||||
assert.equal(
|
||||
formatSessionClosedExitMessage({ reason: "exited", exitCode: 127 }),
|
||||
"\r\n[session closed (code 127)]",
|
||||
);
|
||||
});
|
||||
|
||||
test("a channel closed without exit-status or exit-signal must not render as code 0", () => {
|
||||
assert.equal(
|
||||
formatSessionClosedExitMessage({
|
||||
reason: "closed",
|
||||
remoteClosedWithoutExitStatus: true,
|
||||
}),
|
||||
"\r\n[session closed by remote (no exit status)]",
|
||||
);
|
||||
});
|
||||
|
||||
test("exit messages without a reported code stay plain instead of showing a sentinel", () => {
|
||||
assert.equal(
|
||||
formatSessionClosedExitMessage({ reason: "closed" }),
|
||||
"\r\n[session closed]",
|
||||
);
|
||||
assert.equal(formatSessionClosedExitMessage({}), "\r\n[session closed]");
|
||||
});
|
||||
@@ -5,9 +5,20 @@ export type TerminalSessionExitEvent = {
|
||||
signal?: number;
|
||||
error?: string;
|
||||
reason?: "exited" | "error" | "timeout" | "closed";
|
||||
// True when the remote closed the channel without sending exit-status or
|
||||
// exit-signal (#3591): no numeric exit code exists, and the renderer shows
|
||||
// a distinct message instead of a misleading "code 0".
|
||||
remoteClosedWithoutExitStatus?: boolean;
|
||||
diagnostics?: ReadonlyArray<ProviderValidationIssue>;
|
||||
};
|
||||
|
||||
export function formatSessionClosedExitMessage(evt: TerminalSessionExitEvent): string {
|
||||
if (evt?.remoteClosedWithoutExitStatus) {
|
||||
return "\r\n[session closed by remote (no exit status)]";
|
||||
}
|
||||
return `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`;
|
||||
}
|
||||
|
||||
export type TerminalSessionExitIntent =
|
||||
| { kind: "closeSession" }
|
||||
| { kind: "markDisconnected" };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
runAutomationScript,
|
||||
runConnectScriptsSequential,
|
||||
selectScriptOverlayRun,
|
||||
setScriptRuns,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
} from './scriptAutomationCoordinator.ts';
|
||||
import type { ScriptRun } from '@/types/global/netcatty-bridge-script.d.ts';
|
||||
import type { Snippet } from '@/domain/models';
|
||||
import { STORAGE_KEY_AI_PERMISSION_MODE } from '@/infrastructure/config/storageKeys.ts';
|
||||
import { netcattyBridge } from '@/infrastructure/services/netcattyBridge.ts';
|
||||
|
||||
test('waitForScriptRun resolves when run is already completed on subscribe', async () => {
|
||||
@@ -246,3 +248,127 @@ test('runConnectScriptsSequential does not treat a script error named Aborted as
|
||||
Reflect.deleteProperty(globalThis, 'localStorage');
|
||||
}
|
||||
});
|
||||
|
||||
function installPermissionMode(mode: string) {
|
||||
const storage = new Map<string, string>([[STORAGE_KEY_AI_PERMISSION_MODE, mode]]);
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => { storage.set(key, String(value)); },
|
||||
removeItem: (key: string) => { storage.delete(key); },
|
||||
clear: () => { storage.clear(); },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const writeScript: Snippet = {
|
||||
id: 'write-script',
|
||||
label: 'Write',
|
||||
command: "await nct.screen.sendLine('echo hi');",
|
||||
kind: 'script',
|
||||
};
|
||||
|
||||
test('runAutomationScript executes a user write script while AI permission mode is observer', async () => {
|
||||
const originalGet = netcattyBridge.get;
|
||||
installPermissionMode('observer');
|
||||
let seenMode: string | undefined;
|
||||
netcattyBridge.get = () => ({
|
||||
scriptRun: async (params) => {
|
||||
seenMode = params.permissionMode;
|
||||
return { runId: 'user-run', runIds: ['user-run'] };
|
||||
},
|
||||
}) as ReturnType<typeof netcattyBridge.get>;
|
||||
|
||||
try {
|
||||
const result = await runAutomationScript({
|
||||
snippet: writeScript,
|
||||
sessionId: 'sess-user',
|
||||
initiatedBy: 'user',
|
||||
});
|
||||
assert.equal(result.runId, 'user-run');
|
||||
assert.equal(seenMode, 'auto');
|
||||
} finally {
|
||||
netcattyBridge.get = originalGet;
|
||||
Reflect.deleteProperty(globalThis, 'localStorage');
|
||||
}
|
||||
});
|
||||
|
||||
test('runAutomationScript blocks automatic write scripts in observer mode', async () => {
|
||||
const originalGet = netcattyBridge.get;
|
||||
installPermissionMode('observer');
|
||||
let called = false;
|
||||
netcattyBridge.get = () => ({
|
||||
scriptRun: async () => {
|
||||
called = true;
|
||||
return { runId: 'automatic-run', runIds: ['automatic-run'] };
|
||||
},
|
||||
}) as ReturnType<typeof netcattyBridge.get>;
|
||||
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => runAutomationScript({ snippet: writeScript, sessionId: 'sess-automatic' }),
|
||||
/Observer mode blocks scripts that write to the terminal/,
|
||||
);
|
||||
assert.equal(called, false);
|
||||
} finally {
|
||||
netcattyBridge.get = originalGet;
|
||||
Reflect.deleteProperty(globalThis, 'localStorage');
|
||||
}
|
||||
});
|
||||
|
||||
test('runAutomationScript blocks an AI write script in observer mode', async () => {
|
||||
const originalGet = netcattyBridge.get;
|
||||
installPermissionMode('observer');
|
||||
let called = false;
|
||||
netcattyBridge.get = () => ({
|
||||
scriptRun: async () => {
|
||||
called = true;
|
||||
return { runId: 'ai-run', runIds: ['ai-run'] };
|
||||
},
|
||||
}) as ReturnType<typeof netcattyBridge.get>;
|
||||
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => runAutomationScript({
|
||||
snippet: writeScript,
|
||||
sessionId: 'sess-ai',
|
||||
initiatedBy: 'ai',
|
||||
}),
|
||||
/Observer mode blocks scripts that write to the terminal/,
|
||||
);
|
||||
assert.equal(called, false);
|
||||
} finally {
|
||||
netcattyBridge.get = originalGet;
|
||||
Reflect.deleteProperty(globalThis, 'localStorage');
|
||||
}
|
||||
});
|
||||
|
||||
test('runAutomationScript keeps observer on an AI read-only script so later writes stay blocked', async () => {
|
||||
const originalGet = netcattyBridge.get;
|
||||
installPermissionMode('observer');
|
||||
let seenMode: string | undefined;
|
||||
netcattyBridge.get = () => ({
|
||||
scriptRun: async (params) => {
|
||||
seenMode = params.permissionMode;
|
||||
return { runId: 'ai-read', runIds: ['ai-read'] };
|
||||
},
|
||||
}) as ReturnType<typeof netcattyBridge.get>;
|
||||
|
||||
try {
|
||||
await runAutomationScript({
|
||||
snippet: {
|
||||
id: 'read-script',
|
||||
label: 'Read',
|
||||
command: "await nct.screen.waitForPrompt(1000);",
|
||||
kind: 'script',
|
||||
},
|
||||
sessionId: 'sess-ai-read',
|
||||
initiatedBy: 'ai',
|
||||
});
|
||||
assert.equal(seenMode, 'observer');
|
||||
} finally {
|
||||
netcattyBridge.get = originalGet;
|
||||
Reflect.deleteProperty(globalThis, 'localStorage');
|
||||
}
|
||||
});
|
||||
@@ -95,8 +95,10 @@ export async function runAutomationScript(params: {
|
||||
hostname?: string;
|
||||
username?: string;
|
||||
};
|
||||
/** Only a direct user action bypasses Observer; AI and automatic runs honor it. */
|
||||
initiatedBy?: 'user' | 'ai';
|
||||
}): Promise<{ runId: string; runIds: string[] }> {
|
||||
const permissionMode = readPermissionMode();
|
||||
const permissionMode = params.initiatedBy === 'user' ? 'auto' : readPermissionMode();
|
||||
if (permissionMode === 'observer' && scriptContainsWriteOperations(params.snippet.command)) {
|
||||
throw new Error('Observer mode blocks scripts that write to the terminal.');
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isMissingStatError } from "./errors";
|
||||
import { isMissingStatError, unwrapSftpIpcError } from "./errors";
|
||||
|
||||
test("isMissingStatError accepts only true path absence codes", () => {
|
||||
for (const code of [2, "ENOENT", "NO_SUCH_FILE", "SSH_FX_NO_SUCH_FILE"] as const) {
|
||||
@@ -64,3 +64,15 @@ test("isMissingStatError rejects unsupported LSTAT and other failures", () => {
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
test("unwrapSftpIpcError strips the Electron IPC wrapper", () => {
|
||||
assert.equal(
|
||||
unwrapSftpIpcError(
|
||||
new Error("Error invoking remote method 'netcatty:sftp:delete': Error: Permission denied"),
|
||||
),
|
||||
"Permission denied",
|
||||
);
|
||||
assert.equal(unwrapSftpIpcError(new Error("Permission denied")), "Permission denied");
|
||||
assert.equal(unwrapSftpIpcError("channel closed"), "channel closed");
|
||||
});
|
||||
@@ -18,4 +18,13 @@ export const isSessionError = (err: unknown): boolean => {
|
||||
);
|
||||
};
|
||||
|
||||
const SFTP_IPC_ERROR_PREFIX = /^Error invoking remote method 'netcatty:[^']+':\s*/i;
|
||||
|
||||
/** Drop Electron IPC wrapper so dialogs can show the server error. */
|
||||
export function unwrapSftpIpcError(err: unknown): string {
|
||||
const raw = err instanceof Error ? err.message : String(err ?? "");
|
||||
const unwrapped = raw.replace(SFTP_IPC_ERROR_PREFIX, "").replace(/^Error:\s*/, "").trim();
|
||||
return unwrapped || raw;
|
||||
}
|
||||
|
||||
export { isMissingStatError } from "../../../domain/sftpStatError";
|
||||
@@ -62,6 +62,8 @@ export interface SftpConnectOptions {
|
||||
sourceSessionId?: string;
|
||||
/** Fail instead of opening a new route when the requested terminal transport cannot be reused. */
|
||||
requireSourceSessionReuse?: boolean;
|
||||
/** When false, never attach SFTP to a live terminal SSH transport. */
|
||||
reuseTransport?: boolean;
|
||||
/** Prevent a forced terminal-drop route rebind from sharing an older open. */
|
||||
connectRequestKey?: string;
|
||||
/** Identifies the exact tab and connection created for a route-bound request. */
|
||||
@@ -1074,6 +1076,7 @@ export const useSftpConnections = ({
|
||||
openOptions: {
|
||||
sessionId: sftpSessionId,
|
||||
...credentials,
|
||||
...(options?.reuseTransport === false ? { reuseTransport: false } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -85,6 +85,60 @@ test("first-open follow uses a fresh terminal cwd instead of the cached home pat
|
||||
await act(async () => renderer?.unmount());
|
||||
});
|
||||
|
||||
test("first-open follow stays put when the terminal cwd is still an unresolved ~", async () => {
|
||||
const navigatedPaths: string[] = [];
|
||||
const connection = {
|
||||
id: "conn-1",
|
||||
hostId: "host-1",
|
||||
currentPath: "/root",
|
||||
homeDir: "/root",
|
||||
status: "connected",
|
||||
isLocal: false,
|
||||
};
|
||||
const sftpRef = {
|
||||
current: {
|
||||
leftPane: { connection, loading: false },
|
||||
navigateTo: async (_side: "left", path: string) => {
|
||||
navigatedPaths.push(path);
|
||||
connection.currentPath = path;
|
||||
return "reached" as const;
|
||||
},
|
||||
},
|
||||
};
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
function Probe() {
|
||||
useSftpFollowTerminalCwd({
|
||||
activeSessionId: "session-1",
|
||||
activeTerminalCwd: "~",
|
||||
canFollowTerminalCwd: true,
|
||||
connectionId: connection.id,
|
||||
connectionIsLocal: connection.isLocal,
|
||||
connectionLoading: false,
|
||||
connectionPath: connection.currentPath,
|
||||
connectionStatus: connection.status,
|
||||
effectiveFollowTerminalCwd: true,
|
||||
followTerminalCwdHost: host,
|
||||
hasActiveWork: false,
|
||||
isVisible: true,
|
||||
ownerPanelOpen: true,
|
||||
onGetTerminalCwd: async () => "~",
|
||||
onPendingFollowOverride: () => {},
|
||||
sftpRef,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
});
|
||||
|
||||
assert.deepEqual(navigatedPaths, []);
|
||||
assert.equal(connection.currentPath, "/root");
|
||||
await act(async () => renderer?.unmount());
|
||||
});
|
||||
|
||||
test("first-open follow does not use a stale cached cwd while the fresh probe is pending", async () => {
|
||||
let resolveCwd: ((cwd: string) => void) | null = null;
|
||||
const navigatedPaths: string[] = [];
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
shouldReleaseInitialFollowSyncAttempt,
|
||||
shouldResetInitialFollowTerminalCwdSync,
|
||||
type SftpFollowTerminalCwdBlock,
|
||||
resolveTerminalCwdForSftp,
|
||||
isSftpFollowTargetPath,
|
||||
fallbackFollowPathForUntrackedSession,
|
||||
} from "../../../domain/sftpFollowTerminalCwd";
|
||||
import type { Host } from "../../../types";
|
||||
import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActions";
|
||||
@@ -23,6 +26,7 @@ import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActio
|
||||
type FollowConnection = {
|
||||
id: string;
|
||||
currentPath?: string | null;
|
||||
homeDir?: string | null;
|
||||
status: string;
|
||||
isLocal?: boolean;
|
||||
};
|
||||
@@ -48,6 +52,7 @@ type GetTerminalCwd = (options?: {
|
||||
type InitialFollowConnection = {
|
||||
id: string;
|
||||
currentPath?: string | null;
|
||||
homeDir?: string | null;
|
||||
status: string;
|
||||
isLocal?: boolean;
|
||||
};
|
||||
@@ -85,13 +90,21 @@ const runInitialFollowTerminalCwdSync = async ({
|
||||
return false;
|
||||
}
|
||||
|
||||
const targetPath = resolveTerminalCwdForSftp(cwd, live.homeDir, live.currentPath);
|
||||
if (!isSftpFollowTargetPath(targetPath)) {
|
||||
// Prompt-only shortcuts such as `~` are not a real SFTP path yet. Stay on
|
||||
// the connection's landing directory instead of listing `/~`.
|
||||
setHandled({ connectionId: expectedConnectionId, terminalCwd: cwd });
|
||||
return true;
|
||||
}
|
||||
|
||||
setHandled({
|
||||
connectionId: expectedConnectionId,
|
||||
terminalCwd: staleTerminalCwd && staleTerminalCwd !== cwd ? staleTerminalCwd : cwd,
|
||||
terminalCwd: staleTerminalCwd && staleTerminalCwd !== targetPath ? staleTerminalCwd : targetPath,
|
||||
});
|
||||
if (live.currentPath === cwd) return true;
|
||||
if (live.currentPath === targetPath) return true;
|
||||
|
||||
const navigateResult = await navigate(cwd, isEligible);
|
||||
const navigateResult = await navigate(targetPath, isEligible);
|
||||
if (!isEligible()) return false;
|
||||
const current = getConnection();
|
||||
if (!current || current.id !== expectedConnectionId || current.status !== "connected") {
|
||||
@@ -174,6 +187,7 @@ export function useSftpFollowTerminalCwd({
|
||||
const ownerPanelOpenRef = useRef(ownerPanelOpen);
|
||||
const hasActiveWorkRef = useRef(hasActiveWork);
|
||||
const initialFollowReadyConnectionRef = useRef<string | null>(null);
|
||||
const lastFollowOriginIdRef = useRef<string | null>(null);
|
||||
|
||||
effectiveFollowTerminalCwdRef.current = effectiveFollowTerminalCwd;
|
||||
canFollowTerminalCwdRef.current = canFollowTerminalCwd;
|
||||
@@ -257,10 +271,16 @@ export function useSftpFollowTerminalCwd({
|
||||
});
|
||||
if (!cwd) return;
|
||||
if (!shouldApply()) return;
|
||||
const navigateResult = await sftpRef.current.navigateTo("left", cwd, { shouldApply });
|
||||
const connection = sftpRef.current.leftPane.connection;
|
||||
const targetPath = resolveTerminalCwdForSftp(
|
||||
cwd,
|
||||
connection?.homeDir,
|
||||
connection?.currentPath,
|
||||
);
|
||||
if (!isSftpFollowTargetPath(targetPath)) return;
|
||||
const navigateResult = await sftpRef.current.navigateTo("left", targetPath, { shouldApply });
|
||||
if (navigateResult !== "reached" || !shouldApply()) return;
|
||||
blockedFollowRef.current = null;
|
||||
const connection = sftpRef.current.leftPane.connection;
|
||||
if (connection?.id) {
|
||||
handledFollowRef.current = { connectionId: connection.id, terminalCwd: cwd };
|
||||
}
|
||||
@@ -275,9 +295,23 @@ export function useSftpFollowTerminalCwd({
|
||||
const syncGeneration = followSyncGenerationRef.current;
|
||||
const expectedSessionId = focusedSessionIdRef.current ?? activeSessionIdRef.current ?? null;
|
||||
const expectedConnectionIdAtStart = connectionIdRef.current ?? liveConnectionId;
|
||||
const previousOriginId = lastFollowOriginIdRef.current;
|
||||
const originChanged = Boolean(
|
||||
previousOriginId
|
||||
&& expectedSessionId
|
||||
&& previousOriginId !== expectedSessionId,
|
||||
);
|
||||
if (expectedSessionId) lastFollowOriginIdRef.current = expectedSessionId;
|
||||
const usesLiveTerminalCwd = Boolean(activeTerminalCwd && activeTerminalCwdTrusted);
|
||||
let terminalCwd = usesLiveTerminalCwd ? activeTerminalCwd : null;
|
||||
if (!terminalCwd) {
|
||||
if (!terminalCwd && originChanged) {
|
||||
// Do not reuse an in-flight probe from the pane we just left.
|
||||
terminalCwd = fallbackFollowPathForUntrackedSession({
|
||||
originChanged,
|
||||
homeDir: sftpRef.current.leftPane.connection?.homeDir,
|
||||
currentPath: sftpRef.current.leftPane.connection?.currentPath,
|
||||
});
|
||||
} else if (!terminalCwd) {
|
||||
terminalCwd = await onGetTerminalCwd({
|
||||
preferFreshBackend: true,
|
||||
allowRendererFallback: false,
|
||||
@@ -335,26 +369,36 @@ export function useSftpFollowTerminalCwd({
|
||||
liveTerminalCwd: activeTerminalCwdRef.current,
|
||||
requireLiveTerminalCwd: usesLiveTerminalCwd,
|
||||
});
|
||||
const navigateResult = await sftpRef.current.navigateTo("left", terminalCwd, {
|
||||
if (!connection) return;
|
||||
const targetPath = resolveTerminalCwdForSftp(
|
||||
terminalCwd,
|
||||
connection.homeDir,
|
||||
connection.currentPath,
|
||||
);
|
||||
if (!isSftpFollowTargetPath(targetPath)) return;
|
||||
const navigateResult = await sftpRef.current.navigateTo("left", targetPath, {
|
||||
shouldApply: shouldApplyCurrentFollowSync,
|
||||
quiet: true,
|
||||
});
|
||||
if (!shouldApplyCurrentFollowSync()) return;
|
||||
|
||||
const currentConnection = sftpRef.current.leftPane.connection;
|
||||
if (!currentConnection || currentConnection.id !== connection?.id) return;
|
||||
if (navigateResult === "failed") {
|
||||
blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
|
||||
blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
|
||||
} else if (navigateResult === "superseded") {
|
||||
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
|
||||
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
|
||||
} else if (navigateResult === "reached") {
|
||||
blockedFollowRef.current = null;
|
||||
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
|
||||
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
|
||||
}
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeTerminalCwd,
|
||||
activeTerminalCwdTrusted,
|
||||
canFollowTerminalCwd,
|
||||
effectiveFollowTerminalCwd,
|
||||
focusedSessionId,
|
||||
hasActiveWork,
|
||||
isVisible,
|
||||
onGetTerminalCwd,
|
||||
@@ -380,6 +424,7 @@ export function useSftpFollowTerminalCwd({
|
||||
if (!effectiveFollowTerminalCwd || !canFollowTerminalCwd || !isVisible || hasActiveWork) return;
|
||||
void syncFollowToTerminalCwd();
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeTerminalCwd,
|
||||
activeTerminalCwdTrusted,
|
||||
canFollowTerminalCwd,
|
||||
@@ -387,6 +432,7 @@ export function useSftpFollowTerminalCwd({
|
||||
connectionIsLocal,
|
||||
connectionStatus,
|
||||
effectiveFollowTerminalCwd,
|
||||
focusedSessionId,
|
||||
hasActiveWork,
|
||||
isVisible,
|
||||
syncFollowToTerminalCwd,
|
||||
@@ -533,7 +579,7 @@ export function useSftpFollowTerminalCwd({
|
||||
getConnection: () => sftpRef.current.leftPane.connection,
|
||||
navigate: (cwd, shouldApply) => {
|
||||
navigationStarted = true;
|
||||
return sftpRef.current.navigateTo("left", cwd, { shouldApply });
|
||||
return sftpRef.current.navigateTo("left", cwd, { shouldApply, quiet: true });
|
||||
},
|
||||
setHandled: (value) => { handledFollowRef.current = value; },
|
||||
setBlocked: (value) => { blockedFollowRef.current = value; },
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useCallback, useRef } from "react";
|
||||
import type { Host, SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models";
|
||||
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
|
||||
import { logger } from "../../../lib/logger";
|
||||
import { unwrapSftpIpcError } from "./errors";
|
||||
import { SftpPane } from "./types";
|
||||
import {
|
||||
getFileName,
|
||||
@@ -55,6 +56,8 @@ export type SftpNavigateOptions = {
|
||||
force?: boolean;
|
||||
tabId?: string;
|
||||
shouldApply?: () => boolean;
|
||||
/** Restore the previous listing without showing a pane error. */
|
||||
quiet?: boolean;
|
||||
};
|
||||
|
||||
interface UseSftpPaneActionsResult {
|
||||
@@ -416,8 +419,9 @@ export const useSftpPaneActions = ({
|
||||
files: previousFiles,
|
||||
selectedFiles: previousSelection,
|
||||
filter: getSftpFilterAfterPathChangeError(clearFilterForPathChange, previousFilter, prev.filter),
|
||||
error:
|
||||
err instanceof Error ? err.message : "Failed to list directory",
|
||||
error: options?.quiet
|
||||
? previousError
|
||||
: unwrapSftpIpcError(err) || "Failed to list directory",
|
||||
loading: false,
|
||||
};
|
||||
});
|
||||
@@ -1030,6 +1034,30 @@ export const useSftpPaneActions = ({
|
||||
[getActivePane, refresh, handleSessionError, sftpSessionsRef, isSessionError],
|
||||
);
|
||||
|
||||
const removeListedNames = useCallback((
|
||||
side: "left" | "right",
|
||||
parentPath: string,
|
||||
names: string[],
|
||||
) => {
|
||||
if (names.length === 0) return;
|
||||
const removeSet = new Set(names);
|
||||
updateActiveTab(side, (prev) => {
|
||||
if (!prev.connection || prev.connection.currentPath !== parentPath) return prev;
|
||||
const nextSelection = new Set(prev.selectedFiles);
|
||||
for (const name of names) nextSelection.delete(name);
|
||||
return {
|
||||
...prev,
|
||||
files: prev.files.filter((file) => !removeSet.has(file.name)),
|
||||
selectedFiles: nextSelection,
|
||||
error: null,
|
||||
};
|
||||
});
|
||||
const pane = getActivePane(side);
|
||||
if (pane?.connection && !pane.connection.isLocal) {
|
||||
clearCacheForConnection(pane.connection.id);
|
||||
}
|
||||
}, [clearCacheForConnection, getActivePane, updateActiveTab]);
|
||||
|
||||
return {
|
||||
navigateTo,
|
||||
refresh,
|
||||
@@ -1047,6 +1075,7 @@ export const useSftpPaneActions = ({
|
||||
createFileAtPath,
|
||||
deleteFiles,
|
||||
deleteFilesAtPath,
|
||||
removeListedNames,
|
||||
renameFile,
|
||||
renameFileAtPath,
|
||||
moveEntriesToPath,
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
/** @test issue #3559 — dual-pane transfers must re-stat remote sources before planning */
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { PREFLIGHT_STAT_CONCURRENCY, PREFLIGHT_STAT_MAX_FILES, useSftpTransfers } from "./useSftpTransfers";
|
||||
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
|
||||
import type { SftpPane } from "./types";
|
||||
|
||||
type StartOptions = {
|
||||
transferId: string;
|
||||
sourcePath: string;
|
||||
sourceType: string;
|
||||
targetType: string;
|
||||
totalBytes?: number;
|
||||
sourceSftpId?: string;
|
||||
};
|
||||
|
||||
/** Remote pane whose listing was captured before the file grew to 3626 bytes. */
|
||||
function makePane(side: "left" | "right"): SftpPane {
|
||||
const isLocal = side === "right";
|
||||
return {
|
||||
id: side,
|
||||
connection: {
|
||||
id: isLocal ? "local-conn" : "remote-conn",
|
||||
hostId: isLocal ? undefined : "host-1",
|
||||
hostLabel: isLocal ? "Local" : "SSH host",
|
||||
isLocal,
|
||||
status: "connected",
|
||||
currentPath: isLocal ? "/Users/reporter/Downloads" : "/opt",
|
||||
},
|
||||
files: isLocal
|
||||
? []
|
||||
: [
|
||||
{
|
||||
name: "aops_dns_view_demo.sh",
|
||||
type: "file" as const,
|
||||
size: 3622,
|
||||
sizeFormatted: "3.5 KB",
|
||||
lastModified: 1758000000000,
|
||||
lastModifiedFormatted: "",
|
||||
},
|
||||
],
|
||||
loading: false,
|
||||
reconnecting: false,
|
||||
error: null,
|
||||
connectionLogs: [],
|
||||
selectedFiles: new Set<string>(),
|
||||
filter: "",
|
||||
filenameEncoding: "auto",
|
||||
showHiddenFiles: true,
|
||||
transferMutationToken: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function installGlobals(netty: Record<string, unknown>) {
|
||||
const previousWindow = (globalThis as { window?: unknown }).window;
|
||||
const previousActFlag = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const previousStorage = (globalThis as { localStorage?: unknown }).localStorage;
|
||||
const previousRaf = (globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame;
|
||||
const previousCancelRaf = (globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame;
|
||||
// Progress patches are rAF-coalesced; provide a microtask-ish shim.
|
||||
const raf = (cb: (time: number) => void) => setTimeout(() => cb(Date.now()), 0);
|
||||
(globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame = raf;
|
||||
(globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame = (id: unknown) => clearTimeout(id as number);
|
||||
(globalThis as { window?: unknown }).window = {
|
||||
netcatty: netty,
|
||||
requestAnimationFrame: raf,
|
||||
cancelAnimationFrame: (id: unknown) => clearTimeout(id as number),
|
||||
};
|
||||
(globalThis as { localStorage?: unknown }).localStorage = {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
};
|
||||
return () => {
|
||||
(globalThis as { window?: unknown }).window = previousWindow;
|
||||
(globalThis as { localStorage?: unknown }).localStorage = previousStorage;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousActFlag;
|
||||
(globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame = previousRaf;
|
||||
(globalThis as { cancelAnimationFrame?: unknown }).cancelAnimationFrame = previousCancelRaf;
|
||||
};
|
||||
}
|
||||
|
||||
for (const liveStatAvailable of [true, false]) {
|
||||
test(
|
||||
liveStatAvailable
|
||||
? "dual-pane download plan uses the live source size, not the stale listing (#3559)"
|
||||
: "dual-pane download plan falls back to live size measurement when stat is unavailable (#3559)",
|
||||
async () => {
|
||||
const statCalls: Array<{ sftpId: string; path: string }> = [];
|
||||
const startedOptions: StartOptions[] = [];
|
||||
let resolveTransfer!: (options: StartOptions) => void;
|
||||
const transferStarted = new Promise<StartOptions>((resolve) => { resolveTransfer = resolve; });
|
||||
|
||||
const restore = installGlobals({
|
||||
statSftp: async (sftpId: string, target: string) => {
|
||||
if (!liveStatAvailable) return undefined;
|
||||
statCalls.push({ sftpId, path: target });
|
||||
return {
|
||||
name: "aops_dns_view_demo.sh",
|
||||
type: "file" as const,
|
||||
size: 3626,
|
||||
sizeKnown: true,
|
||||
lastModified: 1758000001000,
|
||||
};
|
||||
},
|
||||
statLocal: async () => null,
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
startedOptions.push(options);
|
||||
resolveTransfer(options);
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed",
|
||||
transferId: options.transferId,
|
||||
transferred: options.totalBytes ?? 0,
|
||||
totalBytes: options.totalBytes ?? 0,
|
||||
lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
const running = ops!.startTransfer(
|
||||
[{ name: "aops_dns_view_demo.sh", isDirectory: false }],
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
const options = await transferStarted;
|
||||
startedOptions.length = 0;
|
||||
startedOptions.push(options);
|
||||
await running;
|
||||
});
|
||||
|
||||
// Every fresh remote plan must come from a live re-stat of the source.
|
||||
if (liveStatAvailable) {
|
||||
assert.equal(statCalls.length, 1);
|
||||
assert.equal(statCalls[0].sftpId, "sftp-remote");
|
||||
assert.equal(statCalls[0].path, "/opt/aops_dns_view_demo.sh");
|
||||
}
|
||||
const planBytes = startedOptions[0]?.totalBytes;
|
||||
if (liveStatAvailable) {
|
||||
assert.equal(planBytes, 3626, "plan must use the live remote size, not the stale listing 3622");
|
||||
} else {
|
||||
// No live stat possible: plan 0 must be omitted so the transfer
|
||||
// bridge measures the live size instead of truncating.
|
||||
assert.equal(planBytes, undefined);
|
||||
}
|
||||
} finally {
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test("stat-less remote source keeps the listing size in the overwrite dialog and leaves the plan unknown", async () => {
|
||||
const started: StartOptions[] = [];
|
||||
const restore = installGlobals({
|
||||
statSftp: async () => ({
|
||||
name: "aops_dns_view_demo.sh",
|
||||
type: "file" as const,
|
||||
size: 0,
|
||||
sizeKnown: false,
|
||||
lastModified: 0,
|
||||
}),
|
||||
statLocal: async () => ({
|
||||
name: "aops_dns_view_demo.sh",
|
||||
type: "file" as const,
|
||||
size: 100,
|
||||
lastModified: 1,
|
||||
}),
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
started.push(options);
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner-statless",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
await ops!.startTransfer(
|
||||
[{ name: "aops_dns_view_demo.sh", isDirectory: false }],
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
});
|
||||
|
||||
assert.equal(started.length, 0, "an unresolved conflict must not start the transfer");
|
||||
assert.equal(ops!.conflicts.length, 1);
|
||||
assert.equal(ops!.conflicts[0].newSize, 3622);
|
||||
assert.equal(ops!.conflicts[0].newModified, 1758000000000);
|
||||
const task = ops!.transfers.find((row) => row.fileName === "aops_dns_view_demo.sh");
|
||||
assert.equal(task?.totalBytes, 0, "listing size must not become the transfer plan");
|
||||
assert.equal(task?.status, "attention");
|
||||
} finally {
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("remote transfer preflight stats stay within the concurrency cap and file bound", async () => {
|
||||
const limit = PREFLIGHT_STAT_CONCURRENCY;
|
||||
const fileCount = limit + 4;
|
||||
let inflight = 0;
|
||||
let maxInflight = 0;
|
||||
let releaseAll = () => {};
|
||||
const gate = new Promise<void>((resolve) => { releaseAll = resolve; });
|
||||
let reachedCap = () => {};
|
||||
const hitCap = new Promise<void>((resolve) => { reachedCap = resolve; });
|
||||
const names = Array.from({ length: fileCount }, (_, index) => `file-${index}.bin`);
|
||||
|
||||
const restore = installGlobals({
|
||||
statSftp: async () => {
|
||||
inflight += 1;
|
||||
maxInflight = Math.max(maxInflight, inflight);
|
||||
if (inflight >= limit) reachedCap();
|
||||
try {
|
||||
await gate;
|
||||
} finally {
|
||||
inflight -= 1;
|
||||
}
|
||||
return {
|
||||
name: "file",
|
||||
type: "file" as const,
|
||||
size: 10,
|
||||
sizeKnown: true,
|
||||
lastModified: 1,
|
||||
};
|
||||
},
|
||||
statLocal: async () => null,
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed",
|
||||
transferId: options.transferId,
|
||||
transferred: options.totalBytes ?? 0,
|
||||
totalBytes: options.totalBytes ?? 0,
|
||||
lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner-concurrency",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
let running: Promise<unknown> = Promise.resolve();
|
||||
await act(async () => {
|
||||
running = ops!.startTransfer(
|
||||
names.map((name) => ({ name, isDirectory: false })),
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
const capTimeout = new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error("preflight did not reach the concurrency cap")), 2000);
|
||||
});
|
||||
await Promise.race([hitCap, capTimeout]);
|
||||
});
|
||||
assert.equal(maxInflight, limit);
|
||||
assert.ok(inflight <= limit);
|
||||
releaseAll();
|
||||
await act(async () => { await running; });
|
||||
assert.equal(maxInflight, limit);
|
||||
} finally {
|
||||
releaseAll();
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("a preflight timeout stops the rest of the batch", async () => {
|
||||
const extra = 4;
|
||||
const names = Array.from(
|
||||
{ length: PREFLIGHT_STAT_CONCURRENCY + extra },
|
||||
(_, index) => `hung-${index}.bin`,
|
||||
);
|
||||
let statCalls = 0;
|
||||
const restore = installGlobals({
|
||||
statSftp: () => {
|
||||
statCalls += 1;
|
||||
return new Promise(() => {});
|
||||
},
|
||||
statLocal: async () => null,
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed",
|
||||
transferId: options.transferId,
|
||||
transferred: options.totalBytes ?? 0,
|
||||
totalBytes: options.totalBytes ?? 0,
|
||||
lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner-timeout",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
await ops!.startTransfer(
|
||||
names.map((name) => ({ name, isDirectory: false })),
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
});
|
||||
// One preflight wave, then stop. Timed-out files are not statted again.
|
||||
assert.equal(statCalls, PREFLIGHT_STAT_CONCURRENCY);
|
||||
} finally {
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("stat-less preflight results are not statted again before transfer", async () => {
|
||||
const names = Array.from(
|
||||
{ length: PREFLIGHT_STAT_CONCURRENCY + 2 },
|
||||
(_, index) => `legacy-${index}.bin`,
|
||||
);
|
||||
let statCalls = 0;
|
||||
let inflight = 0;
|
||||
let maxInflight = 0;
|
||||
const started: StartOptions[] = [];
|
||||
const restore = installGlobals({
|
||||
statSftp: async () => {
|
||||
statCalls += 1;
|
||||
inflight += 1;
|
||||
maxInflight = Math.max(maxInflight, inflight);
|
||||
await Promise.resolve();
|
||||
inflight -= 1;
|
||||
return {
|
||||
name: "legacy",
|
||||
type: "file" as const,
|
||||
size: 0,
|
||||
sizeKnown: false,
|
||||
lastModified: 0,
|
||||
};
|
||||
},
|
||||
statLocal: async () => null,
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
started.push(options);
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed",
|
||||
transferId: options.transferId,
|
||||
transferred: options.totalBytes ?? 0,
|
||||
totalBytes: options.totalBytes ?? 0,
|
||||
lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner-statless-batch",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
await ops!.startTransfer(
|
||||
names.map((name) => ({ name, isDirectory: false })),
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
});
|
||||
assert.equal(statCalls, names.length);
|
||||
assert.ok(maxInflight <= PREFLIGHT_STAT_CONCURRENCY);
|
||||
assert.equal(started.length, names.length);
|
||||
assert.equal(started.filter((options) => options.totalBytes === undefined).length, names.length);
|
||||
} finally {
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("files past the preflight bound stay un-statted after conflict resolution", async () => {
|
||||
const extra = 2;
|
||||
const names = Array.from({ length: PREFLIGHT_STAT_MAX_FILES + extra }, (_, index) => `bulk-${index}.bin`);
|
||||
let statCalls = 0;
|
||||
const started: StartOptions[] = [];
|
||||
const restore = installGlobals({
|
||||
statSftp: async () => {
|
||||
statCalls += 1;
|
||||
return {
|
||||
name: "bulk",
|
||||
type: "file" as const,
|
||||
size: 20,
|
||||
sizeKnown: true,
|
||||
lastModified: 5,
|
||||
};
|
||||
},
|
||||
statLocal: async (target: string) => names.slice(-extra).some((name) => target.endsWith(`/${name}`))
|
||||
? { name: target.split("/").pop() || "", type: "file" as const, size: 1, lastModified: 1 }
|
||||
: null,
|
||||
startStreamTransfer: async (options: StartOptions) => {
|
||||
started.push(options);
|
||||
sftpTransferCenterStore.ingestBackgroundEvent({
|
||||
type: "completed",
|
||||
transferId: options.transferId,
|
||||
transferred: options.totalBytes ?? 0,
|
||||
totalBytes: options.totalBytes ?? 0,
|
||||
lifecycleEpoch: 0,
|
||||
});
|
||||
return {};
|
||||
},
|
||||
pauseTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
|
||||
});
|
||||
|
||||
let ops: ReturnType<typeof useSftpTransfers> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
function Probe() {
|
||||
ops = useSftpTransfers({
|
||||
ownerId: "plan-owner-bound",
|
||||
getActivePane: (side) => (side === "left" ? makePane("left") : makePane("right")),
|
||||
getPaneByConnectionId: () => null,
|
||||
getTabByConnectionId: () => null,
|
||||
updateTab: () => undefined,
|
||||
refresh: async () => undefined,
|
||||
clearCacheForConnection: () => undefined,
|
||||
handleSessionError: () => undefined,
|
||||
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-remote"]]) },
|
||||
connectionCacheKeyMapRef: { current: new Map() },
|
||||
listLocalFiles: async () => [],
|
||||
listRemoteFiles: async () => [],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
await act(async () => {
|
||||
await ops!.startTransfer(
|
||||
names.map((name) => ({ name, isDirectory: false })),
|
||||
"left",
|
||||
"right",
|
||||
);
|
||||
});
|
||||
assert.equal(statCalls, PREFLIGHT_STAT_MAX_FILES);
|
||||
assert.equal(started.length, names.length - extra);
|
||||
assert.equal(ops!.conflicts.length, extra);
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
assert.equal(ops!.conflicts.length, extra, "conflicts must survive panel remount");
|
||||
await act(async () => {
|
||||
await ops!.resolveConflict(ops!.conflicts[0].transferId, "replace", true);
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
});
|
||||
assert.equal(started.length, names.length);
|
||||
assert.equal(statCalls, PREFLIGHT_STAT_MAX_FILES, "conflict resolution must keep the preflight cap");
|
||||
const omitted = started.filter((options) => options.totalBytes === undefined);
|
||||
assert.equal(omitted.length, extra);
|
||||
} finally {
|
||||
renderer?.unmount();
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -63,6 +63,21 @@ import {
|
||||
retryExternalDragDropFileUpload,
|
||||
} from "./externalDragDropRetry";
|
||||
|
||||
// The bridge's statSftp awaits an unbounded SFTP callback, so a half-open
|
||||
// session can leave a stat pending forever. Every stat issued outside the
|
||||
// bridge is bounded with this timeout; on timeout the caller falls back to
|
||||
// stale metadata / a 0 plan instead of one hung stat blocking a batch.
|
||||
const STAT_SFTP_TIMEOUT_MS = 10_000;
|
||||
|
||||
// Preflight re-stats share the browse SFTP session and the renderer IPC
|
||||
// queue. Launching one stat per file for a huge multi-file selection would
|
||||
// flood both before any transfer task reaches the UI, so cap the number of
|
||||
// in-flight preflight stats and skip the re-stat entirely once the selection
|
||||
// grows past a bound (files beyond the cap stay on the safe 0 plan, which
|
||||
// makes the bridge measure the live size anyway).
|
||||
export const PREFLIGHT_STAT_CONCURRENCY = 8;
|
||||
export const PREFLIGHT_STAT_MAX_FILES = 128;
|
||||
|
||||
/** Keep the MutableRefObject mirror in sync with the process-global latch set. */
|
||||
function syncPausedTasksRef(ref: { current: Set<string> }, taskId: string, latched: boolean) {
|
||||
if (latched) ref.current.add(taskId);
|
||||
@@ -207,7 +222,6 @@ export const useSftpTransfers = ({
|
||||
const transfersRef = useRef(transfers);
|
||||
const conflictsRef = useRef(conflicts);
|
||||
conflictsRef.current = conflicts;
|
||||
|
||||
// When the retained panel is re-opened, catch up React state from the ref that
|
||||
// kept receiving progress while the surface was hidden.
|
||||
useEffect(() => {
|
||||
@@ -613,9 +627,30 @@ export const useSftpTransfers = ({
|
||||
|
||||
const sameHost = sameHostEndpoints && !!sourceSftpId && !!targetSftpId;
|
||||
|
||||
const discoverTransferSize = async () => {
|
||||
// Returns the discovered stat so callers that need the size (e.g. the
|
||||
// overwrite conflict dialog) can await this instead of reading stale
|
||||
// metadata from the local task copy.
|
||||
const discoverTransferSize = async (): Promise<{
|
||||
size: number;
|
||||
lastModified?: number;
|
||||
/** False for pane-listing display data. That size must not become the plan. */
|
||||
plan: boolean;
|
||||
} | null> => {
|
||||
// When the endpoint cannot stat the source (legacy SCP returns the
|
||||
// sizeKnown: false placeholder) or the stat fails, the transfer plan
|
||||
// stays unknown (0 bytes, so the bridge measures the live size). The
|
||||
// overwrite dialog still needs display metadata, so fall back to the
|
||||
// retained cached listing entry instead of reporting 0 bytes — but only
|
||||
// for the dialog; the plan itself must never take the listing's
|
||||
// possibly stale size back.
|
||||
const cachedListingStatForDialog = (): { size: number; lastModified?: number; plan: false } | null => {
|
||||
if (getParentPath(task.sourcePath) !== sourcePane.connection?.currentPath) return null;
|
||||
const entry = sourcePane.files.find((candidate) => candidate.name === task.fileName);
|
||||
if (!entry || !(entry.size > 0)) return null;
|
||||
return { size: entry.size, lastModified: entry.lastModified, plan: false };
|
||||
};
|
||||
try {
|
||||
if (task.totalBytes > 0 || !!task.sourceLastModified) return;
|
||||
if (task.totalBytes > 0 || !!task.sourceLastModified) return null;
|
||||
|
||||
if (sourcePane.connection?.isLocal) {
|
||||
const stat = await netcattyBridge.get()?.statLocal?.(task.sourcePath);
|
||||
@@ -628,17 +663,41 @@ export const useSftpTransfers = ({
|
||||
totalBytes: stat.size,
|
||||
});
|
||||
}
|
||||
return { size: stat.size, lastModified: stat.lastModified, plan: true };
|
||||
}
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (sourceSftpId) {
|
||||
const stat = await netcattyBridge.get()?.statSftp?.(
|
||||
sourceSftpId,
|
||||
task.sourcePath,
|
||||
sourceEncoding,
|
||||
);
|
||||
if (stat) {
|
||||
if (task.preflightStatSkipped) {
|
||||
return cachedListingStatForDialog();
|
||||
}
|
||||
// This stat runs deferred (started before the conflict check) and
|
||||
// can be awaited by the conflict path, so it must not hang on a
|
||||
// half-open session. Bound it like the preflight stat and settle
|
||||
// early once the task is cancelled, since a marked task cannot
|
||||
// settle an in-flight SFTP callback itself.
|
||||
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let cancelTimer: ReturnType<typeof setInterval> | undefined;
|
||||
const stat = await Promise.race([
|
||||
Promise.resolve(netcattyBridge.get()?.statSftp?.(
|
||||
sourceSftpId,
|
||||
task.sourcePath,
|
||||
sourceEncoding,
|
||||
)),
|
||||
new Promise<undefined>((resolve) => {
|
||||
timeoutTimer = setTimeout(() => resolve(undefined), STAT_SFTP_TIMEOUT_MS);
|
||||
}),
|
||||
new Promise<undefined>((resolve) => {
|
||||
cancelTimer = setInterval(() => {
|
||||
if (cancelledTasksRef.current.has(task.id)) resolve(undefined);
|
||||
}, 250);
|
||||
}),
|
||||
]).finally(() => {
|
||||
if (timeoutTimer) clearTimeout(timeoutTimer);
|
||||
if (cancelTimer) clearInterval(cancelTimer);
|
||||
});
|
||||
if (stat && stat.sizeKnown !== false) {
|
||||
if (!task.sourceLastModified && stat.lastModified) {
|
||||
task.sourceLastModified = stat.lastModified;
|
||||
}
|
||||
@@ -647,12 +706,18 @@ export const useSftpTransfers = ({
|
||||
totalBytes: stat.size,
|
||||
});
|
||||
}
|
||||
return { size: stat.size, lastModified: stat.lastModified, plan: true };
|
||||
}
|
||||
// Unknown size (e.g. legacy SCP stat): keep the transfer plan
|
||||
// unknown so a 0-byte placeholder never replaces trusted metadata,
|
||||
// but give the conflict dialog the retained cached listing entry.
|
||||
return cachedListingStatForDialog();
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isTransferCancelledError(err)) {
|
||||
logger.debug?.("[SFTP] Deferred transfer size discovery failed", err);
|
||||
}
|
||||
return cachedListingStatForDialog();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -746,16 +811,35 @@ export const useSftpTransfers = ({
|
||||
return null;
|
||||
})();
|
||||
|
||||
// For single files: fire-and-forget size discovery
|
||||
if (!task.isDirectory) {
|
||||
void discoverTransferSize();
|
||||
}
|
||||
// For single files: start size discovery without blocking the conflict
|
||||
// check, but keep the promise so an actual conflict can await fresh
|
||||
// size metadata before the dialog is shown.
|
||||
const sizeDiscoveryPromise = task.isDirectory ? null : discoverTransferSize();
|
||||
|
||||
// Only await conflict check (fast single stat call)
|
||||
const conflict = await conflictCheckPromise;
|
||||
// Cancel/Stop may have won while conflict stats were in flight.
|
||||
if (cancelledTasksRef.current.has(task.id)) return "cancelled";
|
||||
|
||||
// null means the plan size is still unknown. A verified 0-byte stat is 0,
|
||||
// not null, so an empty file does not pick up a stale listing size.
|
||||
let verifiedPlanBytes: number | null = task.totalBytes > 0 ? task.totalBytes : null;
|
||||
if (conflict && sizeDiscoveryPromise) {
|
||||
// The task's totalBytes may still be 0 here because discovery ran
|
||||
// deferred and updateTask never mutates the local task copy. Await
|
||||
// discovery (bounded per-task; the task is already visible/cancellable)
|
||||
// so the overwrite dialog shows the real source size, not 0 (#3559).
|
||||
const discovered = await sizeDiscoveryPromise;
|
||||
// Cancel during this stat must win before an apply-to-all Replace
|
||||
// deletes an existing symlink.
|
||||
if (cancelledTasksRef.current.has(task.id)) return "cancelled";
|
||||
if (discovered && discovered.size >= 0) {
|
||||
conflict.newSize = discovered.size;
|
||||
if (discovered.lastModified) conflict.newModified = discovered.lastModified;
|
||||
if (discovered.plan) verifiedPlanBytes = discovered.size;
|
||||
}
|
||||
}
|
||||
|
||||
if (conflict) {
|
||||
const defaultAction = conflictDefaultsRef.current
|
||||
.get(task.batchId ?? "global")
|
||||
@@ -819,7 +903,9 @@ export const useSftpTransfers = ({
|
||||
setConflicts((prev) => [...prev, conflict]);
|
||||
updateTask({
|
||||
status: "attention",
|
||||
totalBytes: conflict.newSize || task.totalBytes || 0,
|
||||
// Dialog newSize may be the listing fallback (plan: false). Only a
|
||||
// verified stat may become the plan; 0 stays omitted at startStreamTransfer.
|
||||
totalBytes: verifiedPlanBytes ?? 0,
|
||||
conflict,
|
||||
});
|
||||
return "attention";
|
||||
@@ -1094,6 +1180,84 @@ export const useSftpTransfers = ({
|
||||
? new Map(sourcePane.files.map(f => [f.name, f]))
|
||||
: null;
|
||||
|
||||
// Pane listings can be stale when the file changed in a terminal or
|
||||
// another session after the pane was listed (#3559). A stale undersized
|
||||
// size becomes the transfer plan and silently truncates the download, so
|
||||
// remote single files are always re-statted before the plan is built.
|
||||
// When no live stat is possible the plan stays 0, which makes the bridge
|
||||
// measure the live size instead of trusting the stale listing.
|
||||
const freshRemoteMetadata = new Map<string, { size: number; lastModified: number }>();
|
||||
const sourceSftpIdForPlan = sourcePane.connection.isLocal
|
||||
? null
|
||||
: (sftpSessionsRef.current.get(sourceConnectionId) ?? null);
|
||||
const remoteSingleFiles = sourcePane.connection.isLocal
|
||||
? []
|
||||
: sourceFiles.filter((file) => !file.isDirectory);
|
||||
const preflightFiles = remoteSingleFiles.slice(0, PREFLIGHT_STAT_MAX_FILES);
|
||||
// Remote files without a verified live stat are not statted again in
|
||||
// discoverTransferSize. That covers the tail past the cap, a missing
|
||||
// browse session, a timeout that stops the pool, and a stat that
|
||||
// returns no usable size. The plan stays unknown so the bridge measures
|
||||
// the live size; the overwrite dialog still uses the pane listing.
|
||||
const preflightSkippedNames = new Set<string>();
|
||||
if (remoteSingleFiles.length > 0 && sourceSftpIdForPlan) {
|
||||
const sourceEncoding = sourcePane.filenameEncoding || "auto";
|
||||
// The bridge's statSftp awaits an unbounded SFTP callback, so a
|
||||
// half-open session can leave a stat pending forever. Bound each
|
||||
// preflight stat: on timeout the file keeps its 0 plan and the bridge
|
||||
// measures the live size during the transfer instead of one hung stat
|
||||
// blocking the entire selected batch.
|
||||
const PREFLIGHT_STAT_TIMEOUT_MS = STAT_SFTP_TIMEOUT_MS;
|
||||
// These stats share the browse session. Keep a few in flight, and
|
||||
// after the first timeout stop claiming more files so a half-open
|
||||
// session cannot run the whole selection out to 10s each.
|
||||
let preflightStopped = false;
|
||||
const statOneRemoteFile = async (file: { name: string; isDirectory: boolean }) => {
|
||||
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
try {
|
||||
const stat = await Promise.race([
|
||||
Promise.resolve(netcattyBridge.get()?.statSftp?.(
|
||||
sourceSftpIdForPlan,
|
||||
joinPath(sourcePath, file.name),
|
||||
sourceEncoding,
|
||||
)),
|
||||
new Promise<undefined>((resolve) => {
|
||||
timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(undefined);
|
||||
}, PREFLIGHT_STAT_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
if (timedOut) {
|
||||
preflightStopped = true;
|
||||
return;
|
||||
}
|
||||
if (stat && stat.type !== "symlink" && stat.sizeKnown !== false && stat.size >= 0) {
|
||||
freshRemoteMetadata.set(file.name, { size: stat.size, lastModified: stat.lastModified });
|
||||
}
|
||||
} catch (err) {
|
||||
// Fall through to a 0 plan so the bridge measures the live size.
|
||||
logger.debug?.("[SFTP] Transfer plan re-stat failed; falling back to live size", err);
|
||||
} finally {
|
||||
if (timeoutTimer) clearTimeout(timeoutTimer);
|
||||
}
|
||||
};
|
||||
const workers = Math.min(PREFLIGHT_STAT_CONCURRENCY, preflightFiles.length);
|
||||
let preflightCursor = 0;
|
||||
await Promise.allSettled(
|
||||
Array.from({ length: workers }, async () => {
|
||||
while (!preflightStopped && preflightCursor < preflightFiles.length) {
|
||||
const file = preflightFiles[preflightCursor++];
|
||||
await statOneRemoteFile(file);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const file of remoteSingleFiles) {
|
||||
if (!freshRemoteMetadata.has(file.name)) preflightSkippedNames.add(file.name);
|
||||
}
|
||||
|
||||
for (const file of sourceFiles) {
|
||||
const direction: TransferDirection =
|
||||
sourcePane.connection!.isLocal && !targetPane.connection!.isLocal
|
||||
@@ -1102,12 +1266,30 @@ export const useSftpTransfers = ({
|
||||
? "download"
|
||||
: "remote-to-remote";
|
||||
|
||||
// Use cached metadata from the source pane's file list to avoid
|
||||
// redundant stat calls over the network, but only when the transfer
|
||||
// source matches the pane's currently listed directory.
|
||||
// Prefer the fresh re-stat for remote files: a cached listing size can
|
||||
// be stale and undersized, which would silently truncate downloads
|
||||
// (#3559). Remote files without a live stat use plan 0 so the bridge
|
||||
// measures the live size; local sources keep the pane metadata.
|
||||
const fileEntry = fileEntryMap?.get(file.name);
|
||||
const fileSize = file.isDirectory ? 0 : (fileEntry?.size ?? 0);
|
||||
const sourceLastModified = fileEntry?.lastModified ?? 0;
|
||||
const freshMetadata = freshRemoteMetadata.get(file.name);
|
||||
const fileSize = file.isDirectory
|
||||
? 0
|
||||
: freshMetadata
|
||||
? freshMetadata.size
|
||||
: sourcePane.connection!.isLocal
|
||||
? (fileEntry?.size ?? 0)
|
||||
: 0;
|
||||
// Only keep an mtime that is paired with trusted metadata (live re-stat,
|
||||
// local source size, or directory totals). A remote file whose re-stat
|
||||
// failed must stay fully unknown (size 0 AND mtime 0 in the plan):
|
||||
// discoverTransferSize and the conflict check both treat a nonzero
|
||||
// sourceLastModified as proof the size is already known, so a stale
|
||||
// mtime would suppress the deferred source re-stat. The overwrite
|
||||
// dialog still gets the pane listing's cached entry via
|
||||
// discoverTransferSize's cachedListingStatForDialog fallback.
|
||||
const sourceLastModified = !file.isDirectory && !sourcePane.connection!.isLocal && !freshMetadata
|
||||
? 0
|
||||
: (freshMetadata?.lastModified ?? fileEntry?.lastModified ?? 0);
|
||||
|
||||
const nextSourcePath = joinPath(sourcePath, file.name);
|
||||
const nextTargetPath = joinPath(targetPath, file.name);
|
||||
@@ -1167,8 +1349,9 @@ export const useSftpTransfers = ({
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const taskId = crypto.randomUUID();
|
||||
newTasks.push({
|
||||
id: crypto.randomUUID(),
|
||||
id: taskId,
|
||||
batchId,
|
||||
fileName: file.name,
|
||||
originalFileName: file.name,
|
||||
@@ -1189,6 +1372,7 @@ export const useSftpTransfers = ({
|
||||
isDirectory: file.isDirectory,
|
||||
progressMode: file.isDirectory ? "files" : "bytes",
|
||||
sourceLastModified,
|
||||
preflightStatSkipped: preflightSkippedNames.has(file.name),
|
||||
origin: "manual",
|
||||
resumable: !usesLegacyScp,
|
||||
pauseUnavailableReason: usesLegacyScp ? "This server uses legacy SCP; cancel and retry from the beginning instead" : undefined,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, type MutableRefObject } from 'react';
|
||||
import {
|
||||
STORAGE_KEY_AUTO_UPDATE_ENABLED,
|
||||
STORAGE_KEY_CLOSE_TO_TRAY,
|
||||
STORAGE_KEY_SHOW_TRAY_ICON,
|
||||
STORAGE_KEY_AUTO_LAUNCH_ENABLED,
|
||||
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
|
||||
STORAGE_KEY_TOGGLE_WINDOW_HOTKEY,
|
||||
@@ -42,6 +43,7 @@ interface UseSystemSettingsEffectsParams {
|
||||
toggleWindowHotkey: string;
|
||||
globalHotkeyEnabled: boolean;
|
||||
closeToTray: boolean;
|
||||
showTrayIcon: boolean;
|
||||
autoLaunchEnabled: boolean;
|
||||
windowOpacityRecord: WindowOpacityRecord;
|
||||
windowOpacityMutationSourceRef: MutableRefObject<WindowOpacityMutationSource>;
|
||||
@@ -62,6 +64,7 @@ export function useSystemSettingsEffects({
|
||||
toggleWindowHotkey,
|
||||
globalHotkeyEnabled,
|
||||
closeToTray,
|
||||
showTrayIcon,
|
||||
autoLaunchEnabled,
|
||||
windowOpacityRecord,
|
||||
windowOpacityMutationSourceRef,
|
||||
@@ -173,6 +176,24 @@ export function useSystemSettingsEffects({
|
||||
notifySettingsChanged(STORAGE_KEY_CLOSE_TO_TRAY, closeToTray);
|
||||
}, [enabled, closeToTray, notifySettingsChanged, persistMountedRef]);
|
||||
|
||||
// Persist and sync the show-tray-icon setting. Runs after the close-to-tray
|
||||
// effect above (declaration order) so a hidden icon destroys the tray that
|
||||
// close-to-tray's mount-time push may have just created.
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
// Update main process tray visibility (needed on mount)
|
||||
const bridge = netcattyBridge.get();
|
||||
if (bridge?.setShowTrayIcon) {
|
||||
bridge.setShowTrayIcon(showTrayIcon).catch((err) => {
|
||||
console.warn('[SystemTray] Failed to set show-tray-icon:', err);
|
||||
});
|
||||
}
|
||||
localStorageAdapter.writeString(STORAGE_KEY_SHOW_TRAY_ICON, showTrayIcon ? 'true' : 'false');
|
||||
// Skip IPC on initial mount
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_SHOW_TRAY_ICON, showTrayIcon);
|
||||
}, [enabled, showTrayIcon, notifySettingsChanged, persistMountedRef]);
|
||||
|
||||
// Hydrate auto-launch from the main process on mount — the OS login item
|
||||
// is the real source of truth (the user may have toggled it outside the
|
||||
// app), localStorage is only an optimistic cache for first paint.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
type Listener = () => void;
|
||||
|
||||
export type TerminalCwdSource = "osc7" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
|
||||
export type TerminalCwdSource = "osc7" | "inferred" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
|
||||
|
||||
/**
|
||||
* Live terminal CWD map + version token.
|
||||
|
||||
@@ -174,10 +174,13 @@ export function useAgentDiscovery(
|
||||
? { ...(ea.env ?? {}), CLAUDE_CODE_EXECUTABLE: matchPath }
|
||||
: match.command === 'opencode'
|
||||
? { ...(ea.env ?? {}), OPENCODE_BIN: matchPath }
|
||||
: ea.env;
|
||||
: match.command === 'mimo'
|
||||
? { ...(ea.env ?? {}), MIMOCODE_BIN: matchPath }
|
||||
: ea.env;
|
||||
const envChanged =
|
||||
(match.command === 'claude' && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath)
|
||||
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath);
|
||||
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath)
|
||||
|| (match.command === 'mimo' && ea.env?.MIMOCODE_BIN !== matchPath);
|
||||
const versionChanged = Boolean(match.version) && ea.cliVersion !== match.version;
|
||||
if (currentArgs !== newArgs || backendChanged || envChanged || versionChanged) {
|
||||
changed = true;
|
||||
@@ -220,7 +223,9 @@ export function useAgentDiscovery(
|
||||
? { env: { CLAUDE_CODE_EXECUTABLE: agent.binPath || agent.path || '' } }
|
||||
: agent.command === 'opencode'
|
||||
? { env: { OPENCODE_BIN: agent.binPath || agent.path || '' } }
|
||||
: {}),
|
||||
: agent.command === 'mimo'
|
||||
? { env: { MIMOCODE_BIN: agent.binPath || agent.path || '' } }
|
||||
: {}),
|
||||
};
|
||||
},
|
||||
[],
|
||||
|
||||
@@ -10,5 +10,11 @@ export const useClipboardBackend = () => {
|
||||
return typeof text === "string" ? text : "";
|
||||
}, []);
|
||||
|
||||
return { readClipboardText };
|
||||
const writeClipboardText = useCallback(async (text: string): Promise<boolean> => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.writeClipboardText) return false;
|
||||
return await bridge.writeClipboardText(text) === true;
|
||||
}, []);
|
||||
|
||||
return { readClipboardText, writeClipboardText };
|
||||
};
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
getSessionConnectionLabel,
|
||||
} from '../../domain/sessionTabTitle';
|
||||
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
|
||||
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
|
||||
import { useVaultSnapshotField } from './vaultSnapshotStore';
|
||||
|
||||
export function addWorkspaceIfMissing(
|
||||
workspaces: Workspace[],
|
||||
@@ -267,6 +269,20 @@ export const useSessionState = ({
|
||||
}
|
||||
}, [initialRestoreState.activeTabId]);
|
||||
|
||||
// Keep open sessions' connection label in sync with the vault. Sessions
|
||||
// snapshot `hostLabel` at connect time, so renaming a host would otherwise
|
||||
// leave its already-open tabs (and merged-workspace titles derived from
|
||||
// those labels) showing the old name until the session is closed. The
|
||||
// generated-title sync effect below re-runs on this session change and
|
||||
// refreshes synthesized workspace titles too.
|
||||
const vaultHosts = useVaultSnapshotField('hosts');
|
||||
useEffect(() => {
|
||||
if (vaultHosts.length === 0) return;
|
||||
// The helper returns the same array reference when nothing changed, so
|
||||
// React bails out of the state update.
|
||||
setSessions(prev => syncSessionHostLabels(prev, vaultHosts));
|
||||
}, [vaultHosts]);
|
||||
|
||||
// Keep generated merged-workspace titles (e.g. "01/02" after dragging tab
|
||||
// "02" onto "01") synchronized with the workspace's current membership and
|
||||
// each pane's connection label. `autoTitle: false` makes
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import type { Host } from "../../domain/models";
|
||||
import { EMPTY_VAULT_SNAPSHOT, publishVaultSnapshot } from "./vaultSnapshotStore";
|
||||
import { useSessionState } from "./useSessionState.ts";
|
||||
|
||||
type SessionState = ReturnType<typeof useSessionState>;
|
||||
|
||||
const testHost = (overrides: Partial<Host> = {}): Host => ({
|
||||
id: "host-1",
|
||||
label: "web-01",
|
||||
hostname: "10.0.0.1",
|
||||
port: 22,
|
||||
username: "root",
|
||||
os: "linux",
|
||||
tags: [],
|
||||
...overrides,
|
||||
} as Host);
|
||||
|
||||
test("rewriting the host label updates already-open session tabs on that host", async (t) => {
|
||||
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
|
||||
t.after(() => publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT));
|
||||
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
const eventTarget = new EventTarget() as EventTarget & Record<string, unknown>;
|
||||
Object.assign(eventTarget, { setTimeout, clearTimeout });
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: eventTarget,
|
||||
});
|
||||
t.after(() => {
|
||||
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
const actEnvironment = globalThis as typeof globalThis & {
|
||||
IS_REACT_ACT_ENVIRONMENT?: boolean;
|
||||
};
|
||||
const previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
t.after(() => {
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
|
||||
let state: SessionState | null = null;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
const current = (): SessionState => {
|
||||
assert.ok(state);
|
||||
return state;
|
||||
};
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
|
||||
let sessionId = "";
|
||||
await act(async () => {
|
||||
sessionId = current().connectToHost(testHost());
|
||||
});
|
||||
const sessionOf = () => current().sessions.find((s) => s.id === sessionId);
|
||||
assert.ok(sessionOf());
|
||||
assert.equal(sessionOf()?.hostLabel, "web-01");
|
||||
|
||||
// The host is renamed in the vault while the session stays open.
|
||||
await act(async () => {
|
||||
publishVaultSnapshot({
|
||||
...EMPTY_VAULT_SNAPSHOT,
|
||||
hosts: [testHost({ label: "web-01-renamed" })],
|
||||
});
|
||||
});
|
||||
|
||||
assert.equal(sessionOf()?.hostLabel, "web-01-renamed");
|
||||
|
||||
// Renaming the pane afterwards hands the title to the user rename.
|
||||
await act(async () => {
|
||||
current().submitSessionRename(sessionId, "my pane");
|
||||
});
|
||||
const renamed = sessionOf();
|
||||
assert.ok(renamed);
|
||||
assert.equal(renamed!.customName, "my pane");
|
||||
|
||||
// A later vault rename must not clobber the user-authored pane name.
|
||||
await act(async () => {
|
||||
publishVaultSnapshot({
|
||||
...EMPTY_VAULT_SNAPSHOT,
|
||||
hosts: [testHost({ label: "web-01-again" })],
|
||||
});
|
||||
});
|
||||
const after = sessionOf();
|
||||
assert.ok(after);
|
||||
assert.equal(after!.customName, "my pane");
|
||||
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
});
|
||||
@@ -67,6 +67,7 @@ import {
|
||||
STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED,
|
||||
STORAGE_KEY_TOGGLE_WINDOW_HOTKEY,
|
||||
STORAGE_KEY_CLOSE_TO_TRAY,
|
||||
STORAGE_KEY_SHOW_TRAY_ICON,
|
||||
STORAGE_KEY_AUTO_LAUNCH_ENABLED,
|
||||
STORAGE_KEY_HTTP_NETWORK_PROXY,
|
||||
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
|
||||
@@ -550,6 +551,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
if (stored === null) return true;
|
||||
return stored === 'true';
|
||||
});
|
||||
// Preserve the old tray visibility for existing users until they set this
|
||||
// independently. Fresh installs still default to showing the icon.
|
||||
const [showTrayIcon, setShowTrayIcon] = useState<boolean>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_SHOW_TRAY_ICON);
|
||||
if (stored === null) return closeToTray;
|
||||
return stored === 'true';
|
||||
});
|
||||
// Optimistic cache for first paint; useSystemSettingsEffects hydrates this
|
||||
// from app.getLoginItemSettings() (the real source of truth) on mount.
|
||||
const [autoLaunchEnabled, setAutoLaunchEnabled] = useState<boolean>(() => {
|
||||
@@ -1791,6 +1799,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
toggleWindowHotkey,
|
||||
globalHotkeyEnabled,
|
||||
closeToTray,
|
||||
showTrayIcon,
|
||||
autoLaunchEnabled,
|
||||
windowOpacityRecord,
|
||||
windowOpacityMutationSourceRef,
|
||||
@@ -2156,6 +2165,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setToggleWindowHotkey,
|
||||
closeToTray,
|
||||
setCloseToTray,
|
||||
showTrayIcon,
|
||||
setShowTrayIcon,
|
||||
autoLaunchEnabled,
|
||||
setAutoLaunchEnabled,
|
||||
autoLaunchSupported,
|
||||
|
||||
@@ -469,6 +469,7 @@ export const useSftpState = (
|
||||
createFileAtPath,
|
||||
deleteFiles,
|
||||
deleteFilesAtPath,
|
||||
removeListedNames,
|
||||
renameFile,
|
||||
renameFileAtPath,
|
||||
moveEntriesToPath,
|
||||
@@ -781,6 +782,7 @@ export const useSftpState = (
|
||||
createFileAtPath,
|
||||
deleteFiles,
|
||||
deleteFilesAtPath,
|
||||
removeListedNames,
|
||||
renameFile,
|
||||
renameFileAtPath,
|
||||
moveEntriesToPath,
|
||||
@@ -857,6 +859,8 @@ export const useSftpState = (
|
||||
deleteFiles: (...args: Parameters<typeof deleteFiles>) => methodsRef.current.deleteFiles(...args),
|
||||
deleteFilesAtPath: (...args: Parameters<typeof deleteFilesAtPath>) =>
|
||||
methodsRef.current.deleteFilesAtPath(...args),
|
||||
removeListedNames: (...args: Parameters<typeof removeListedNames>) =>
|
||||
methodsRef.current.removeListedNames(...args),
|
||||
renameFile: (...args: Parameters<typeof renameFile>) => methodsRef.current.renameFile(...args),
|
||||
renameFileAtPath: (...args: Parameters<typeof renameFileAtPath>) => methodsRef.current.renameFileAtPath(...args),
|
||||
moveEntriesToPath: (...args: Parameters<typeof moveEntriesToPath>) => methodsRef.current.moveEntriesToPath(...args),
|
||||
|
||||
@@ -15,6 +15,9 @@ function delay(ms: number): Promise<void> {
|
||||
function normalizePollingErrorMessage(error: unknown, t: I18nContextValue['t']): string {
|
||||
const message = error instanceof Error ? error.message : String(error || 'Unknown error');
|
||||
const lower = message.toLowerCase();
|
||||
if (lower.includes('extra exec channels')) {
|
||||
return t('systemManager.unsupportedRemote');
|
||||
}
|
||||
if (lower.includes('channel open failure') || lower.includes('unable to exec')) {
|
||||
return t('systemManager.errors.sshChannelUnavailable');
|
||||
}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const useTerminalBackend = () => {
|
||||
|
||||
const getSessionPwd = useCallback(async (
|
||||
sessionId: string,
|
||||
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean },
|
||||
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean; timeoutMs?: number },
|
||||
) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.getSessionPwd) return { success: false, error: 'getSessionPwd unavailable' };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import {
|
||||
applyAgentNotesUpdate,
|
||||
haveSameVaultAgentSnapshot,
|
||||
resolveVaultAgentEffectiveHost,
|
||||
resolveVaultAgentNotes,
|
||||
@@ -27,6 +28,33 @@ describe('haveSameVaultAgentSnapshot', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyAgentNotesUpdate', () => {
|
||||
it('rolls back an unsaved agent note before a later successful write', () => {
|
||||
const oldNotes = [{ id: 'old', title: 'Old', content: 'old', createdAt: 1, updatedAt: 1 }];
|
||||
const noteA = { id: 'a', title: 'A', content: 'a', createdAt: 2, updatedAt: 2 };
|
||||
const noteB = { id: 'b', title: 'B', content: 'b', createdAt: 3, updatedAt: 3 };
|
||||
let inMemory = oldNotes;
|
||||
let persisted = oldNotes;
|
||||
let failNext = true;
|
||||
const updateNotes = (notes: typeof oldNotes) => {
|
||||
inMemory = notes;
|
||||
if (failNext) {
|
||||
failNext = false;
|
||||
return false;
|
||||
}
|
||||
persisted = notes;
|
||||
return true;
|
||||
};
|
||||
|
||||
assert.equal(applyAgentNotesUpdate([...oldNotes, noteA], oldNotes, updateNotes), false);
|
||||
assert.deepEqual(inMemory, oldNotes);
|
||||
assert.deepEqual(persisted, oldNotes);
|
||||
|
||||
assert.equal(applyAgentNotesUpdate([...inMemory, noteB], inMemory, updateNotes), true);
|
||||
assert.deepEqual(persisted.map((note) => note.id), ['old', 'b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveVaultAgentEffectiveHost', () => {
|
||||
it('uses the latest snapshotted group defaults', () => {
|
||||
const host: Host = {
|
||||
|
||||
@@ -89,6 +89,20 @@ export function resolveVaultAgentNotes(
|
||||
: (getNotesSnapshot().notes as VaultNote[]);
|
||||
}
|
||||
|
||||
export function applyAgentNotesUpdate(
|
||||
notes: VaultNote[],
|
||||
previousNotes: VaultNote[],
|
||||
updateNotes: (notes: VaultNote[]) => boolean | void,
|
||||
): boolean | void {
|
||||
const saved = updateNotes(notes);
|
||||
if (saved === false) {
|
||||
// Editor autosave keeps failed writes in memory so a draft is not lost.
|
||||
// Agent writes must roll that draft back before another approved write.
|
||||
updateNotes(previousNotes);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
export const haveSameVaultAgentSnapshot = (
|
||||
left: VaultAgentSnapshot,
|
||||
right: VaultAgentSnapshot,
|
||||
@@ -145,6 +159,7 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
|
||||
?? ((notes: VaultNote[]) => {
|
||||
console.warn('[useVaultAgentBridge] updateNotes unavailable');
|
||||
void notes;
|
||||
return false;
|
||||
});
|
||||
return handleVaultAgentOp(op, params, {
|
||||
getHosts: () => vaultSnapshotRef.current.hosts,
|
||||
@@ -239,8 +254,10 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
|
||||
updateKeys: current.updateKeys,
|
||||
}),
|
||||
updateNotes: (notes) => {
|
||||
vaultSnapshotRef.current.notes = notes;
|
||||
applyUpdateNotes(notes);
|
||||
const previousNotes = vaultSnapshotRef.current.notes;
|
||||
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
|
||||
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
|
||||
return saved;
|
||||
},
|
||||
updateSnippets: (snippetUpdate) => {
|
||||
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
|
||||
|
||||
@@ -4,7 +4,8 @@ import assert from "node:assert/strict";
|
||||
import type { SyncPayload } from "../domain/sync.ts";
|
||||
import type { KnownHost } from "../domain/models.ts";
|
||||
import type { SyncableVaultData } from "./syncPayload.ts";
|
||||
import { parseTerminalFontSizeRecord } from "./state/terminalFontSizeSync.ts";
|
||||
import { clampTerminalFontSizeValue, parseTerminalFontSizeRecord } from "./state/terminalFontSizeSync.ts";
|
||||
import { parseCustomAccentRecord } from "./state/customAccentSync.ts";
|
||||
import commandBlocklistTable from "../lib/commandBlocklist.json";
|
||||
|
||||
type LocalStorageMock = {
|
||||
@@ -498,6 +499,134 @@ test("applySyncPayload writes a newer terminal font size that old versions can r
|
||||
assert.equal(record.origin, "sync-payload");
|
||||
});
|
||||
|
||||
test("applying identical versioned settings preserves their records, then propagates real changes", async () => {
|
||||
const scenarios: Array<{
|
||||
name: string;
|
||||
storageKey: string;
|
||||
field: keyof NonNullable<SyncPayload["settings"]>;
|
||||
initialValue: string | number | Record<string, unknown>;
|
||||
changedValue: string | number | Record<string, unknown>;
|
||||
}> = [
|
||||
{
|
||||
name: "accent",
|
||||
storageKey: storageKeys.STORAGE_KEY_COLOR,
|
||||
field: "customAccent",
|
||||
initialValue: parseCustomAccentRecord(null).color,
|
||||
changedValue: "0 84% 60%",
|
||||
},
|
||||
{
|
||||
name: "terminal font size",
|
||||
storageKey: storageKeys.STORAGE_KEY_TERM_FONT_SIZE,
|
||||
field: "terminalFontSize",
|
||||
initialValue: parseTerminalFontSizeRecord(null).fontSize,
|
||||
changedValue: 19,
|
||||
},
|
||||
{
|
||||
name: "custom key bindings",
|
||||
storageKey: storageKeys.STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
||||
field: "customKeyBindings",
|
||||
initialValue: {},
|
||||
changedValue: { open: { mac: "Cmd+K" } },
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
localStorage.clear();
|
||||
const writes: string[] = [];
|
||||
const originalSetItem = localStorage.setItem;
|
||||
localStorage.setItem = (key, value) => {
|
||||
writes.push(key);
|
||||
originalSetItem(key, value);
|
||||
};
|
||||
const applySetting = (value: typeof scenario.initialValue) => applySyncPayload({
|
||||
hosts: [], keys: [], identities: [], snippets: [], customGroups: [],
|
||||
settings: { [scenario.field]: value },
|
||||
} as SyncPayload, { importVaultData: () => {} });
|
||||
|
||||
try {
|
||||
await applySetting(scenario.initialValue);
|
||||
const firstRecord = localStorage.getItem(scenario.storageKey);
|
||||
assert.ok(firstRecord, `${scenario.name}: an explicit first value must be saved`);
|
||||
assert.equal(writes.filter((key) => key === scenario.storageKey).length, 1);
|
||||
|
||||
writes.length = 0;
|
||||
await applySetting(scenario.initialValue);
|
||||
assert.equal(localStorage.getItem(scenario.storageKey), firstRecord);
|
||||
assert.equal(writes.filter((key) => key === scenario.storageKey).length, 0,
|
||||
`${scenario.name}: unchanged value must not write or trigger a storage change`);
|
||||
|
||||
writes.length = 0;
|
||||
await applySetting(scenario.changedValue);
|
||||
assert.equal(writes.filter((key) => key === scenario.storageKey).length, 1,
|
||||
`${scenario.name}: a real change must be saved`);
|
||||
assert.notEqual(localStorage.getItem(scenario.storageKey), firstRecord);
|
||||
assert.deepEqual(buildSyncPayload(vault([])).settings?.[scenario.field], scenario.changedValue);
|
||||
} finally {
|
||||
localStorage.setItem = originalSetItem;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("sync replaces malformed setting records and does not repeat normalized writes", async () => {
|
||||
const versionedKeys = [
|
||||
storageKeys.STORAGE_KEY_COLOR,
|
||||
storageKeys.STORAGE_KEY_TERM_FONT_SIZE,
|
||||
storageKeys.STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
||||
];
|
||||
for (const key of versionedKeys) localStorage.setItem(key, "bad");
|
||||
const writes: string[] = [];
|
||||
const originalSetItem = localStorage.setItem;
|
||||
localStorage.setItem = (key, value) => {
|
||||
writes.push(key);
|
||||
originalSetItem(key, value);
|
||||
};
|
||||
const settings = {
|
||||
customAccent: parseCustomAccentRecord(null).color,
|
||||
terminalFontSize: parseTerminalFontSizeRecord(null).fontSize,
|
||||
customKeyBindings: {},
|
||||
};
|
||||
const applySettings = (nextSettings: NonNullable<SyncPayload["settings"]>) => applySyncPayload({
|
||||
hosts: [], keys: [], identities: [], snippets: [], customGroups: [],
|
||||
settings: nextSettings,
|
||||
}, { importVaultData: () => {} });
|
||||
|
||||
try {
|
||||
await applySettings(settings);
|
||||
for (const key of versionedKeys) {
|
||||
assert.notEqual(localStorage.getItem(key), "bad", `${key}: malformed record must be repaired`);
|
||||
assert.equal(writes.filter((written) => written === key).length, 1);
|
||||
}
|
||||
|
||||
writes.length = 0;
|
||||
await applySettings(settings);
|
||||
for (const key of versionedKeys) {
|
||||
assert.equal(writes.filter((written) => written === key).length, 0,
|
||||
`${key}: repaired record must not be written again`);
|
||||
}
|
||||
|
||||
const oversizedFontSize = 100;
|
||||
writes.length = 0;
|
||||
await applySettings({ terminalFontSize: oversizedFontSize });
|
||||
assert.equal(parseTerminalFontSizeRecord(localStorage.getItem(storageKeys.STORAGE_KEY_TERM_FONT_SIZE)).fontSize,
|
||||
clampTerminalFontSizeValue(oversizedFontSize));
|
||||
assert.equal(writes.filter((key) => key === storageKeys.STORAGE_KEY_TERM_FONT_SIZE).length, 1);
|
||||
|
||||
writes.length = 0;
|
||||
await applySettings({ terminalFontSize: oversizedFontSize });
|
||||
assert.equal(writes.filter((key) => key === storageKeys.STORAGE_KEY_TERM_FONT_SIZE).length, 0,
|
||||
"a repeated out-of-range incoming size must not bump the stored version again");
|
||||
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_TERM_FONT_SIZE, "999");
|
||||
writes.length = 0;
|
||||
await applySettings({ terminalFontSize: oversizedFontSize });
|
||||
assert.equal(writes.filter((key) => key === storageKeys.STORAGE_KEY_TERM_FONT_SIZE).length, 1,
|
||||
"an out-of-range legacy record must be replaced with the normalized value");
|
||||
assert.notEqual(localStorage.getItem(storageKeys.STORAGE_KEY_TERM_FONT_SIZE), "999");
|
||||
} finally {
|
||||
localStorage.setItem = originalSetItem;
|
||||
}
|
||||
});
|
||||
|
||||
test("buildSyncPayload excludes externalAgents (device-local OS-bound config)", () => {
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_EXTERNAL_AGENTS, JSON.stringify([
|
||||
{ id: "codex", name: "Codex", command: "/opt/homebrew/bin/codex", enabled: true },
|
||||
@@ -1585,6 +1714,26 @@ test("applySyncPayload restores the terminal host information bar preference", a
|
||||
assert.equal(parsed.scrollback, 5000);
|
||||
});
|
||||
|
||||
test("bar cursor width survives terminal settings sync round-trip", async () => {
|
||||
localStorage.setItem(
|
||||
storageKeys.STORAGE_KEY_TERM_SETTINGS,
|
||||
JSON.stringify({ cursorBarWidth: 3 }),
|
||||
);
|
||||
|
||||
const payload = buildSyncPayload(vault());
|
||||
const termSettings = (payload.settings?.terminalSettings ?? {}) as Record<string, unknown>;
|
||||
assert.equal(termSettings.cursorBarWidth, 3);
|
||||
|
||||
localStorage.setItem(
|
||||
storageKeys.STORAGE_KEY_TERM_SETTINGS,
|
||||
JSON.stringify({ cursorBarWidth: 1 }),
|
||||
);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
|
||||
const restored = JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_TERM_SETTINGS)!);
|
||||
assert.equal(restored.cursorBarWidth, 3);
|
||||
});
|
||||
|
||||
test("buildSyncPayload omits fallbackFont when TERM_SETTINGS does not set it", () => {
|
||||
localStorage.setItem(
|
||||
storageKeys.STORAGE_KEY_TERM_SETTINGS,
|
||||
|
||||
+56
-31
@@ -51,6 +51,7 @@ import {
|
||||
} from './state/commandBlocklistSettings';
|
||||
import { rehydrateGlobalSftpBookmarks } from './state/sftp/globalSftpBookmarks';
|
||||
import {
|
||||
clampTerminalFontSizeValue,
|
||||
nextTerminalFontSizeSyncVersion,
|
||||
parseTerminalFontSizeRecord,
|
||||
serializeTerminalFontSizeRecord,
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
parseCustomAccentRecord,
|
||||
serializeCustomAccentRecord,
|
||||
} from './state/customAccentSync';
|
||||
import { isValidHslToken } from './state/settingsStateDefaults';
|
||||
import {
|
||||
STORAGE_KEY_THEME,
|
||||
STORAGE_KEY_UI_THEME_LIGHT,
|
||||
@@ -257,8 +259,9 @@ const SYNCABLE_TERMINAL_KEYS = [
|
||||
'startupCommandDelayMs',
|
||||
'scrollback', 'drawBoldInBrightColors', 'terminalEmulationType',
|
||||
'fontLigatures', 'fontSmoothing', 'fontWeight', 'fontWeightBold', 'fallbackFont',
|
||||
'linePadding', 'cursorShape', 'cursorBlink', 'highlightCursorLine', 'minimumContrastRatio',
|
||||
'linePadding', 'cursorShape', 'cursorBlink', 'cursorBarWidth', 'highlightCursorLine', 'minimumContrastRatio',
|
||||
'altAsMeta', 'optionArrowWordJump', 'shiftEnterNewlineEnabled', 'shiftEnterNewlineText',
|
||||
'shiftEnterForceText',
|
||||
'kittyKeyboardProtocolEnabled',
|
||||
'scrollOnInput', 'scrollOnOutput', 'scrollOnKeyPress', 'scrollOnPaste',
|
||||
'smoothScrolling',
|
||||
@@ -689,15 +692,25 @@ async function applySyncableSettings(
|
||||
if (settings.darkUiThemeId != null) localStorageAdapter.writeString(STORAGE_KEY_UI_THEME_DARK, settings.darkUiThemeId);
|
||||
if (settings.accentMode != null) localStorageAdapter.writeString(STORAGE_KEY_ACCENT_MODE, settings.accentMode);
|
||||
if (settings.customAccent != null) {
|
||||
const existing = parseCustomAccentRecord(localStorageAdapter.readString(STORAGE_KEY_COLOR));
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_COLOR,
|
||||
serializeCustomAccentRecord({
|
||||
color: parseCustomAccentRecord(settings.customAccent).color,
|
||||
// Bump so peer windows' version gates accept the synced value.
|
||||
version: Math.max(existing.version, 0) + 1,
|
||||
}),
|
||||
const storedColor = localStorageAdapter.readString(STORAGE_KEY_COLOR);
|
||||
const existing = parseCustomAccentRecord(storedColor);
|
||||
const incomingColor = parseCustomAccentRecord(settings.customAccent).color;
|
||||
// A missing or malformed record parses to the fallback color, but still
|
||||
// needs to be replaced by an explicit incoming value.
|
||||
const storedColorIsValid = storedColor !== null && (
|
||||
isValidHslToken(storedColor.trim())
|
||||
|| storedColor === serializeCustomAccentRecord(existing)
|
||||
);
|
||||
if (!storedColorIsValid || incomingColor !== existing.color) {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_COLOR,
|
||||
serializeCustomAccentRecord({
|
||||
color: incomingColor,
|
||||
// Bump so peer windows' version gates accept the synced value.
|
||||
version: Math.max(existing.version, 0) + 1,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (settings.uiFontFamilyId != null) localStorageAdapter.writeString(STORAGE_KEY_UI_FONT_FAMILY, settings.uiFontFamilyId);
|
||||
if (settings.uiLanguage != null) localStorageAdapter.writeString(STORAGE_KEY_UI_LANGUAGE, settings.uiLanguage);
|
||||
@@ -719,18 +732,26 @@ async function applySyncableSettings(
|
||||
if (settings.terminalThemeLight != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_THEME_LIGHT, settings.terminalThemeLight);
|
||||
if (settings.terminalFontFamily != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_FONT_FAMILY, settings.terminalFontFamily);
|
||||
if (settings.terminalFontSize != null) {
|
||||
const existing = parseTerminalFontSizeRecord(
|
||||
localStorageAdapter.readString(STORAGE_KEY_TERM_FONT_SIZE),
|
||||
);
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_TERM_FONT_SIZE,
|
||||
serializeTerminalFontSizeRecord({
|
||||
fontSize: settings.terminalFontSize,
|
||||
// Bump so peer windows' version gates accept the synced value.
|
||||
version: nextTerminalFontSizeSyncVersion(existing.version, existing.version),
|
||||
origin: 'sync-payload',
|
||||
}),
|
||||
const storedFontSize = localStorageAdapter.readString(STORAGE_KEY_TERM_FONT_SIZE);
|
||||
const existing = parseTerminalFontSizeRecord(storedFontSize);
|
||||
const incomingFontSize = clampTerminalFontSizeValue(settings.terminalFontSize);
|
||||
// A missing or malformed record parses to the default font size. A
|
||||
// supported legacy number remains valid without forcing migration.
|
||||
const storedFontSizeIsValid = storedFontSize !== null && (
|
||||
storedFontSize.trim() === String(existing.fontSize)
|
||||
|| storedFontSize === serializeTerminalFontSizeRecord(existing)
|
||||
);
|
||||
if (!storedFontSizeIsValid || incomingFontSize !== existing.fontSize) {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_TERM_FONT_SIZE,
|
||||
serializeTerminalFontSizeRecord({
|
||||
fontSize: incomingFontSize,
|
||||
// Bump so peer windows' version gates accept the synced value.
|
||||
version: nextTerminalFontSizeSyncVersion(existing.version, existing.version),
|
||||
origin: 'sync-payload',
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (settings.terminalSidePanelAutoOpen != null) {
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, settings.terminalSidePanelAutoOpen);
|
||||
@@ -784,17 +805,21 @@ async function applySyncableSettings(
|
||||
|
||||
// Keyboard
|
||||
if (settings.customKeyBindings != null) {
|
||||
const previous = parseCustomKeyBindingsStorageRecord(
|
||||
localStorageAdapter.readString(STORAGE_KEY_CUSTOM_KEY_BINDINGS),
|
||||
);
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
||||
serializeCustomKeyBindingsStorageRecord({
|
||||
version: nextCustomKeyBindingsSyncVersion(previous?.version || 0),
|
||||
origin: CUSTOM_KEY_BINDINGS_SYNC_PAYLOAD_ORIGIN,
|
||||
bindings: settings.customKeyBindings,
|
||||
}),
|
||||
);
|
||||
const storedBindings = localStorageAdapter.readString(STORAGE_KEY_CUSTOM_KEY_BINDINGS);
|
||||
const previous = parseCustomKeyBindingsStorageRecord(storedBindings);
|
||||
// Keep an explicit empty binding set when this device has no record.
|
||||
const incomingBindings = JSON.stringify(settings.customKeyBindings);
|
||||
const existingBindings = JSON.stringify(previous?.bindings ?? []);
|
||||
if (previous === null || incomingBindings !== existingBindings) {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
||||
serializeCustomKeyBindingsStorageRecord({
|
||||
version: nextCustomKeyBindingsSyncVersion(previous?.version || 0),
|
||||
origin: CUSTOM_KEY_BINDINGS_SYNC_PAYLOAD_ORIGIN,
|
||||
bindings: settings.customKeyBindings,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Editor
|
||||
|
||||
@@ -175,6 +175,22 @@ test('Claude model cache keys isolate configuration directories under one home',
|
||||
);
|
||||
});
|
||||
|
||||
test('MiMo model cache reloads after its config directory changes', async () => {
|
||||
const agent = { id: 'discovered_mimo', sdkBackend: 'mimo', command: '/bin/mimo' };
|
||||
const firstKey = buildSdkRuntimeModelCacheKey({ ...agent, env: { MIMOCODE_HOME: '/profiles/a' } });
|
||||
const secondKey = buildSdkRuntimeModelCacheKey({ ...agent, env: { MIMOCODE_HOME: '/profiles/b' } });
|
||||
const cache = createSdkRuntimeModelCache();
|
||||
let loads = 0;
|
||||
const load = async () => ({ currentModelId: String(++loads), models: [] });
|
||||
assert.deepEqual(await cache.refresh(firstKey, load), { currentModelId: '1', models: [] });
|
||||
assert.deepEqual(await cache.refresh(secondKey, load), { currentModelId: '2', models: [] });
|
||||
assert.equal(loads, 2);
|
||||
assert.notEqual(
|
||||
buildSdkRuntimeModelCacheKey({ ...agent, env: { MIMOCODE_CONFIG: '/profiles/a/mimocode.json' } }),
|
||||
buildSdkRuntimeModelCacheKey({ ...agent, env: { MIMOCODE_CONFIG: '/profiles/b/mimocode.json' } }),
|
||||
);
|
||||
});
|
||||
|
||||
test('Claude model cache keys isolate credentials without exposing them', () => {
|
||||
const agent = { id: 'discovered_claude', sdkBackend: 'claude', command: '/bin/claude' };
|
||||
for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN']) {
|
||||
|
||||
@@ -54,6 +54,14 @@ const MODEL_CACHE_ENV_HINTS = [
|
||||
'OPENCODE_CONFIG',
|
||||
'OPENCODE_CONFIG_DIR',
|
||||
'OPENCODE_CONFIG_CONTENT',
|
||||
'MIMOCODE_HOME',
|
||||
'MIMOCODE_BIN',
|
||||
'MIMOCODE_BIN_PATH',
|
||||
'MIMOCODE_CONFIG',
|
||||
'MIMOCODE_CONFIG_DIR',
|
||||
'MIMOCODE_MIMO_ONLY',
|
||||
'XDG_DATA_HOME',
|
||||
'XDG_CACHE_HOME',
|
||||
'CLAUDE_CODE_EXECUTABLE',
|
||||
'CODEBUDDY_CODE_PATH',
|
||||
'CURSOR_API_KEY',
|
||||
@@ -266,7 +274,8 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
|
||||
|| sdkBackend === 'cursor'
|
||||
|| sdkBackend === 'codebuddy'
|
||||
|| sdkBackend === 'opencode'
|
||||
|| sdkBackend === 'grok';
|
||||
|| sdkBackend === 'grok'
|
||||
|| sdkBackend === 'mimo';
|
||||
}
|
||||
|
||||
export function shouldAdoptSdkCurrentModel(
|
||||
|
||||
@@ -53,6 +53,19 @@ test("scripts side panel offers run-on-all-tabs for every snippet, not only auto
|
||||
assert.match(source, /openPackageDialog/);
|
||||
});
|
||||
|
||||
test("scripts side panel snippet context menu offers copy command without running", () => {
|
||||
// Copy must sit between the run actions and Edit, write snippet.command to
|
||||
// the clipboard, and confirm with a toast — it never executes the command.
|
||||
assert.match(source, /onCopyCommand=\{\(\) => handleCopySnippetCommand\(item\.snippet\)\}/);
|
||||
assert.match(source, /onCopyCommand=\{\(\) => handleCopySnippetCommand\(item\.row\.snippet\)\}/);
|
||||
assert.match(source, /scripts\.actions\.copyCommand'/);
|
||||
const menu = source.match(/\{onRunParallel \? \([\s\S]*?<\/ContextMenu>/);
|
||||
assert.ok(menu, "snippet row context menu should exist");
|
||||
assert.match(menu[0], /onCopyCommand[\s\S]*?onClick=\{onEdit\}/);
|
||||
assert.match(menu[0], /<Copy className="[\s\S]*?\{copyCommandLabel\}/);
|
||||
assert.match(source, /handleCopySnippetCommand[\s\S]*?snippet\.command[\s\S]*?toast\.success/);
|
||||
});
|
||||
|
||||
test("scripts side panel exposes create actions as inline toolbar icons", () => {
|
||||
assert.match(source, /snippets\.action\.newSnippet/);
|
||||
assert.match(source, /snippets\.action\.newPackage/);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import {
|
||||
CheckSquare,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Edit2,
|
||||
Expand,
|
||||
FolderPlus,
|
||||
@@ -54,6 +55,7 @@ import { SnippetCommandTooltipContent } from './snippets/SnippetCommandTooltipCo
|
||||
import { TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS } from './terminalLayer/terminalSidePanelChrome';
|
||||
import { isNonPrimaryPointer, primaryOnlyDragHandlers } from './ui/primaryOnlyDrag';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
|
||||
import { toast } from './ui/toast';
|
||||
|
||||
const toolbarIconButtonClass =
|
||||
'h-7 w-7 shrink-0 flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors disabled:opacity-40 disabled:pointer-events-none';
|
||||
@@ -889,6 +891,20 @@ const ScriptsSidePanelInner: React.FC<ScriptsSidePanelProps> = ({
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handleCopySnippetCommand = useCallback((snippet: Snippet) => {
|
||||
if (!snippet.command) return;
|
||||
navigator.clipboard.writeText(snippet.command).then(
|
||||
() => {
|
||||
toast.success(t('scripts.actions.copyCommand.copied'), {
|
||||
title: snippet.label,
|
||||
});
|
||||
},
|
||||
() => {
|
||||
toast.error(t('scripts.actions.copyCommand.failed'));
|
||||
},
|
||||
);
|
||||
}, [t]);
|
||||
|
||||
if (!isVisible) return null;
|
||||
|
||||
const hasAnyContent = snippets.length > 0 || packages.length > 0;
|
||||
@@ -1129,6 +1145,8 @@ const ScriptsSidePanelInner: React.FC<ScriptsSidePanelProps> = ({
|
||||
onClick={() => handleSnippetClick(item.snippet)}
|
||||
onEdit={() => handleEditSnippet(item.snippet)}
|
||||
onDelete={() => handleDeleteSnippet(item.snippet.id)}
|
||||
onCopyCommand={() => handleCopySnippetCommand(item.snippet)}
|
||||
copyCommandLabel={t('scripts.actions.copyCommand')}
|
||||
onRunParallel={onRunScriptOnWorkspace
|
||||
? () => onRunScriptOnWorkspace(item.snippet, 'parallel')
|
||||
: undefined}
|
||||
@@ -1182,6 +1200,8 @@ const ScriptsSidePanelInner: React.FC<ScriptsSidePanelProps> = ({
|
||||
onClick={() => handleSnippetClick(item.row.snippet)}
|
||||
onEdit={() => handleEditSnippet(item.row.snippet)}
|
||||
onDelete={() => handleDeleteSnippet(item.row.snippet.id)}
|
||||
onCopyCommand={() => handleCopySnippetCommand(item.row.snippet)}
|
||||
copyCommandLabel={t('scripts.actions.copyCommand')}
|
||||
onRunParallel={onRunScriptOnWorkspace
|
||||
? () => onRunScriptOnWorkspace(item.row.snippet, 'parallel')
|
||||
: undefined}
|
||||
@@ -1505,6 +1525,8 @@ interface SnippetRowProps {
|
||||
onDelete: () => void;
|
||||
onRunParallel?: () => void;
|
||||
onRunSequential?: () => void;
|
||||
onCopyCommand?: () => void;
|
||||
copyCommandLabel?: string;
|
||||
runParallelLabel?: string;
|
||||
runSequentialLabel?: string;
|
||||
editLabel: string;
|
||||
@@ -1527,6 +1549,8 @@ const SnippetRow = memo<SnippetRowProps>(({
|
||||
onDelete,
|
||||
onRunParallel,
|
||||
onRunSequential,
|
||||
onCopyCommand,
|
||||
copyCommandLabel,
|
||||
runParallelLabel,
|
||||
runSequentialLabel,
|
||||
editLabel,
|
||||
@@ -1604,6 +1628,11 @@ const SnippetRow = memo<SnippetRowProps>(({
|
||||
<Layers className="mr-2 h-4 w-4" /> {runSequentialLabel}
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{onCopyCommand ? (
|
||||
<ContextMenuItem onClick={onCopyCommand}>
|
||||
<Copy className="mr-2 h-4 w-4" /> {copyCommandLabel}
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
<ContextMenuItem onClick={onEdit}>
|
||||
<Edit2 className="mr-2 h-4 w-4" /> {editLabel}
|
||||
</ContextMenuItem>
|
||||
|
||||
@@ -677,6 +677,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setToggleWindowHotkey={settings.setToggleWindowHotkey}
|
||||
closeToTray={settings.closeToTray}
|
||||
setCloseToTray={settings.setCloseToTray}
|
||||
showTrayIcon={settings.showTrayIcon}
|
||||
setShowTrayIcon={settings.setShowTrayIcon}
|
||||
autoLaunchEnabled={settings.autoLaunchEnabled}
|
||||
setAutoLaunchEnabled={settings.setAutoLaunchEnabled}
|
||||
autoLaunchSupported={settings.autoLaunchSupported}
|
||||
|
||||
@@ -76,6 +76,7 @@ import {
|
||||
resolveLocateSftpPathSessionId,
|
||||
} from "../domain/sftpLocatePathInTerminal";
|
||||
import { classifyDistroId } from "../domain/host";
|
||||
import { remoteSoftwareRequiresSingleChannel } from "../domain/singleChannelSshBanner.shared.mjs";
|
||||
import { useTerminalBackend } from "../application/state/useTerminalBackend";
|
||||
import { isTerminalSensitiveInputActive } from "./terminal/runtime/terminalSensitiveInputRegistry";
|
||||
import { isTerminalReadyForCommandInjection } from "./terminal/runtime/terminalCommandInjectionReadyRegistry";
|
||||
@@ -95,6 +96,8 @@ import {
|
||||
shouldCancelSettledPendingSftpRebindWithoutTarget,
|
||||
shouldDeferPendingSftpUploadForOriginFocus,
|
||||
shouldDeferSftpSidePanelAutoConnectForSession,
|
||||
isSplitFocusSftpStillConnected,
|
||||
shouldKeepConnectedSftpOnSplitFocus,
|
||||
shouldRebindSftpSidePanelSourceSession,
|
||||
shouldSkipSftpSidePanelAutoConnect,
|
||||
shouldStartPendingSftpUploadRebind,
|
||||
@@ -570,6 +573,41 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
const lastBrowsedPathByConnectionKeyRef = useRef<Map<string, string>>(new Map());
|
||||
const [interactiveWorkActive, setInteractiveWorkActive] = useState(false);
|
||||
const [sftpUiReady, setSftpUiReady] = useState(false);
|
||||
const terminalBackend = useTerminalBackend();
|
||||
const [sftpBannerDecision, setSftpBannerDecision] = useState<{
|
||||
sessionId: string;
|
||||
singleChannel: boolean;
|
||||
} | null>(null);
|
||||
const activeSessionStatusForBanner = activeSessionId
|
||||
? sessions.find((session) => session.id === activeSessionId)?.status ?? null
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeSessionId || activeSessionStatusForBanner !== "connected") {
|
||||
setSftpBannerDecision(null);
|
||||
return;
|
||||
}
|
||||
const readRemoteInfo = terminalBackend.getSessionRemoteInfo;
|
||||
if (!readRemoteInfo) {
|
||||
setSftpBannerDecision({ sessionId: activeSessionId, singleChannel: false });
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void readRemoteInfo(activeSessionId).then((info) => {
|
||||
if (cancelled) return;
|
||||
setSftpBannerDecision({
|
||||
sessionId: activeSessionId,
|
||||
singleChannel: remoteSoftwareRequiresSingleChannel(info?.remoteSshVersion),
|
||||
});
|
||||
}).catch(() => {
|
||||
if (!cancelled) {
|
||||
setSftpBannerDecision({ sessionId: activeSessionId, singleChannel: false });
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeSessionId, activeSessionStatusForBanner, terminalBackend]);
|
||||
|
||||
useEffect(() => {
|
||||
pruneSftpSidePanelState(
|
||||
@@ -693,6 +731,16 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
previousStatus: lastSourceSessionStatusRef.current,
|
||||
nextStatus: activeSessionStatus ?? (activeSessionId ? "connected" : null),
|
||||
});
|
||||
// The peer banner is known only after the terminal handshake. Wait for it
|
||||
// before choosing a shared terminal channel, so a one-channel bastion
|
||||
// dials its file login directly.
|
||||
if (
|
||||
activeSessionId
|
||||
&& activeSessionStatus === "connected"
|
||||
&& sftpBannerDecision?.sessionId !== activeSessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasBackendSession = (connectionId: string) => !!s.getSftpIdForConnection(connectionId);
|
||||
const activeTab = s.leftTabs.tabs.find((tab) => tab.id === s.leftTabs.activeTabId) ?? null;
|
||||
@@ -708,16 +756,33 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
// Rebind when the focused terminal SSH session changes: saved host keys can
|
||||
// lag live session endpoints (edited host / unsaved user). Still keep the
|
||||
// browsed path sticky via remembered initialPath below.
|
||||
// Single-channel SFTP does not borrow that terminal, so A -> B -> A must
|
||||
// keep the login that is already up for this endpoint.
|
||||
const backendSessionUp = activeConnectionId ? hasBackendSession(activeConnectionId) : false;
|
||||
const endpointAlreadyConnected = shouldSkipSftpSidePanelAutoConnect(
|
||||
connectionKey,
|
||||
connectedKeyRef.current,
|
||||
activeTab,
|
||||
backendSessionUp,
|
||||
activeTabConnectionKey,
|
||||
);
|
||||
const splitEndpointStillUp = isSplitFocusSftpStillConnected(
|
||||
connectionKey,
|
||||
connectedKeyRef.current,
|
||||
activeTab,
|
||||
backendSessionUp,
|
||||
activeTabConnectionKey,
|
||||
);
|
||||
const keepSplitSftp = shouldKeepConnectedSftpOnSplitFocus({
|
||||
sessionChanged,
|
||||
previousSessionId: lastSourceSessionIdRef.current,
|
||||
nextSessionId: activeSessionId,
|
||||
endpointAlreadyConnected: splitEndpointStillUp,
|
||||
});
|
||||
if (
|
||||
!sessionChanged
|
||||
&& !pendingRequiresForcedRebind
|
||||
&& shouldSkipSftpSidePanelAutoConnect(
|
||||
connectionKey,
|
||||
connectedKeyRef.current,
|
||||
activeTab,
|
||||
activeConnectionId ? hasBackendSession(activeConnectionId) : false,
|
||||
activeTabConnectionKey,
|
||||
)
|
||||
!pendingRequiresForcedRebind
|
||||
&& (endpointAlreadyConnected || splitEndpointStillUp)
|
||||
&& (!sessionChanged || keepSplitSftp)
|
||||
) {
|
||||
if (activeSessionId) {
|
||||
lastSourceSessionIdRef.current = activeSessionId;
|
||||
@@ -869,13 +934,20 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
|
||||
connectedKeyRef.current = connectionKey;
|
||||
connectedHostObjRef.current = activeHost;
|
||||
const dedicatedSftpLogin = sftpBannerDecision?.sessionId === activeSessionId
|
||||
&& sftpBannerDecision.singleChannel;
|
||||
const reuseTerminalTransport = !dedicatedSftpLogin && (
|
||||
Boolean(pendingStrictSourceSessionId) || activeSessionStatus === "connected"
|
||||
);
|
||||
const connect = (
|
||||
connectRequestKey?: string,
|
||||
onConnectionCreated?: (target: { tabId: string; connectionId: string }) => void,
|
||||
) => s.connect("left", activeHost, {
|
||||
sourceSessionId: pendingStrictSourceSessionId
|
||||
?? (activeSessionStatus === "connected" ? (activeSessionId ?? undefined) : undefined),
|
||||
requireSourceSessionReuse: Boolean(pendingStrictSourceSessionId),
|
||||
sourceSessionId: reuseTerminalTransport
|
||||
? (pendingStrictSourceSessionId ?? (activeSessionId ?? undefined))
|
||||
: undefined,
|
||||
requireSourceSessionReuse: reuseTerminalTransport && Boolean(pendingStrictSourceSessionId),
|
||||
...(reuseTerminalTransport ? {} : { reuseTransport: false }),
|
||||
...(connectRequestKey ? { connectRequestKey } : undefined),
|
||||
onConnectionCreated,
|
||||
...(initialPath ? { initialPath } : undefined),
|
||||
@@ -907,6 +979,7 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
pendingUploadRebindSettledRequestId,
|
||||
pendingUploadRebindStartedIdRef,
|
||||
sessions,
|
||||
sftpBannerDecision,
|
||||
startPendingUploadRebind,
|
||||
]);
|
||||
|
||||
@@ -1308,6 +1381,10 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
|
||||
sftpDefaultViewMode={sftpDefaultViewMode}
|
||||
activeHost={activeHost}
|
||||
activeSessionId={activeSessionId}
|
||||
bannerRequiresSingleChannel={
|
||||
sftpBannerDecision?.sessionId === activeSessionId
|
||||
&& sftpBannerDecision.singleChannel
|
||||
}
|
||||
focusedSessionId={focusedSessionId}
|
||||
showWorkspaceHostHeader={showWorkspaceHostHeader}
|
||||
renderOverlays={renderOverlays}
|
||||
@@ -1356,6 +1433,7 @@ type SftpSidePanelInteractiveBodyProps = {
|
||||
sftpDefaultViewMode: "list" | "tree";
|
||||
activeHost: Host | null;
|
||||
activeSessionId?: string | null;
|
||||
bannerRequiresSingleChannel?: boolean;
|
||||
focusedSessionId?: string | null;
|
||||
showWorkspaceHostHeader: boolean;
|
||||
renderOverlays: boolean;
|
||||
@@ -1406,6 +1484,7 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
|
||||
sftpDefaultViewMode,
|
||||
activeHost,
|
||||
activeSessionId = null,
|
||||
bannerRequiresSingleChannel = false,
|
||||
focusedSessionId = null,
|
||||
showWorkspaceHostHeader,
|
||||
renderOverlays,
|
||||
@@ -1613,11 +1692,12 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
|
||||
|
||||
const canFollowTerminalCwd = useMemo(() => {
|
||||
if (!onGetTerminalCwd || !followTerminalCwdHost) return false;
|
||||
if (bannerRequiresSingleChannel) return false;
|
||||
const proto = followTerminalCwdHost.protocol;
|
||||
if (proto === "local" || proto === "serial") return false;
|
||||
if (followTerminalCwdHost.id?.startsWith("local-") || followTerminalCwdHost.id?.startsWith("serial-")) return false;
|
||||
return true;
|
||||
}, [followTerminalCwdHost, onGetTerminalCwd]);
|
||||
}, [bannerRequiresSingleChannel, followTerminalCwdHost, onGetTerminalCwd]);
|
||||
|
||||
const hasActiveWork = showTextEditor || !!permissionsState || showFileOpenerDialog
|
||||
|| (sftp.activeFileWatchCountRef?.current ?? 0) > 0
|
||||
|
||||
+93
-22
@@ -1,4 +1,6 @@
|
||||
import { clearTerminalBroadcastUserInput, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast";
|
||||
import { shouldBroadcastDuringSensitivePrompt } from "../domain/terminalBroadcast";
|
||||
import { STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS } from "../infrastructure/config/storageKeys";
|
||||
import { createTerminalReflowReadingPosition } from "./terminal/terminalReflowReadingPosition";
|
||||
import { resolveHostOs } from '../domain/host';
|
||||
import { Terminal as XTerm } from "@xterm/xterm";
|
||||
@@ -38,6 +40,7 @@ import {
|
||||
type TerminalEncodingAttachConnection,
|
||||
} from "../domain/terminalEncodingPreference";
|
||||
import { resolveRestoreCwdIntent, resolveInheritedCwdIntent } from "../domain/sessionRestore";
|
||||
import { formatSessionClosedExitMessage } from "../application/state/resolveTerminalSessionExitIntent";
|
||||
import {
|
||||
buildTerminalContextReadResult,
|
||||
buildTerminalContextSnapshotText,
|
||||
@@ -45,7 +48,7 @@ import {
|
||||
resolveTerminalContextLineWindow,
|
||||
type TerminalContextReader,
|
||||
} from "../domain/terminalContextRead";
|
||||
import { classifyDistroId, shouldProbeSessionCwd } from "../domain/host";
|
||||
import { classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from "../domain/host";
|
||||
import { shouldCollectServerStats } from "../domain/systemManager/systemTarget";
|
||||
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
|
||||
import { CONNECTION_PROGRESS_START } from "./terminal/connectionProgress";
|
||||
@@ -161,7 +164,12 @@ import { registerTerminalSensitiveInputReader } from "./terminal/runtime/termina
|
||||
import { registerTerminalCommandInjectionReadyReader } from "./terminal/runtime/terminalCommandInjectionReadyRegistry";
|
||||
import { isIdleShellReadyForCommandInjection } from "../domain/terminalCommandInjectionReady";
|
||||
import { detectPrompt } from "./terminal/autocomplete/promptDetector";
|
||||
import { applyUserCursorPreference } from "./terminal/runtime/cursorPreference";
|
||||
import {
|
||||
applyUserCursorPreference,
|
||||
applyUserCursorWidthPreference,
|
||||
shouldApplyUserCursorPreference,
|
||||
snapshotUserCursorPreference,
|
||||
} from "./terminal/runtime/cursorPreference";
|
||||
import { terminalAltKeyOptions } from "./terminal/runtime/altKeyOptions";
|
||||
import {
|
||||
createPromptLineBreakState,
|
||||
@@ -196,6 +204,7 @@ import {
|
||||
import {
|
||||
createTerminalCwdTracker,
|
||||
invalidateTerminalCwdAfterCommand,
|
||||
shouldPreserveTerminalCwdAcrossCommand,
|
||||
resolvePreferredTerminalCwd,
|
||||
type TerminalCwdChangeMeta,
|
||||
} from "./terminal/sftpCwd";
|
||||
@@ -830,6 +839,15 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
isBroadcastEnabledRef.current = isBroadcastEnabled;
|
||||
onBroadcastInputRef.current = onBroadcastInput;
|
||||
|
||||
// Opt-in "broadcast without password protection" (#3488): when enabled, the
|
||||
// fail-closed password-prompt heuristic no longer pauses broadcast fan-out.
|
||||
const [broadcastPasswordBypass] = useStoredBoolean(
|
||||
STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS,
|
||||
false,
|
||||
);
|
||||
const broadcastPasswordBypassRef = useRef(broadcastPasswordBypass);
|
||||
broadcastPasswordBypassRef.current = broadcastPasswordBypass;
|
||||
|
||||
// Snippets ref for shortkey support in terminal
|
||||
const snippetsRef = useRef(snippets);
|
||||
snippetsRef.current = snippets;
|
||||
@@ -1060,8 +1078,17 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
}
|
||||
|
||||
// Broadcast to other sessions if broadcast mode is enabled
|
||||
if (!sensitive && isBroadcastEnabledRef.current && onBroadcastInputRef.current) {
|
||||
onBroadcastInputRef.current(text, sessionId);
|
||||
if (
|
||||
shouldBroadcastDuringSensitivePrompt({
|
||||
sensitivePromptActive: sensitive,
|
||||
broadcastPasswordBypass: broadcastPasswordBypassRef.current,
|
||||
})
|
||||
&& isBroadcastEnabledRef.current
|
||||
&& onBroadcastInputRef.current
|
||||
) {
|
||||
// Bypassed password fan-out (#3488): retain the sensitive marker so
|
||||
// peer writes keep skipping input interceptors.
|
||||
onBroadcastInputRef.current(text, sessionId, sensitive ? { sourceSensitive: true } : undefined);
|
||||
}
|
||||
|
||||
// ESC-prefixed writes (Esc+. yank-last-arg) are shell editor commands.
|
||||
@@ -1134,12 +1161,15 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
allowRendererFallback?: boolean;
|
||||
requireActiveShellCwd?: boolean;
|
||||
}): Promise<string | undefined> => {
|
||||
const skipBackendPwd = hostRestrictsExtraSshChannels(host);
|
||||
const cwd = await resolvePreferredTerminalCwd({
|
||||
rendererCwd: terminalCwdTracker.getRendererCwd(),
|
||||
rendererCwdSource: terminalCwdTracker.getRendererCwdSource(),
|
||||
sessionId: sessionRef.current,
|
||||
getSessionPwd: (id, options) => terminalBackend.getSessionPwd(id, options),
|
||||
preferFreshBackend: options?.preferFreshBackend,
|
||||
getSessionPwd: skipBackendPwd
|
||||
? async () => ({ success: false })
|
||||
: (id, pwdOptions) => terminalBackend.getSessionPwd(id, pwdOptions),
|
||||
preferFreshBackend: skipBackendPwd ? false : options?.preferFreshBackend,
|
||||
allowRendererFallback: options?.allowRendererFallback,
|
||||
requireActiveShellCwd: options?.requireActiveShellCwd,
|
||||
});
|
||||
@@ -2037,7 +2067,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
if (evt.error) {
|
||||
setError(evt.error);
|
||||
}
|
||||
const exitMessage = `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`;
|
||||
const exitMessage = formatSessionClosedExitMessage(evt);
|
||||
hibernatePendingBufferRef.current = hibernatePendingCapDisabledRef.current
|
||||
? hibernatePendingBufferRef.current + exitMessage
|
||||
: appendHibernatePendingBuffer(
|
||||
@@ -2375,14 +2405,17 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const cwdAwareOnCommandSubmitted = useCallback((
|
||||
...args: Parameters<NonNullable<typeof onCommandSubmitted>>
|
||||
) => {
|
||||
invalidateTerminalCwdAfterCommand(
|
||||
terminalCwdTracker,
|
||||
sessionId,
|
||||
() => { knownCwdRef.current = undefined; },
|
||||
onTerminalCwdChange,
|
||||
);
|
||||
onCommandSubmitted?.(...args);
|
||||
}, [onCommandSubmitted, onTerminalCwdChange, sessionId, terminalCwdTracker]);
|
||||
if (!shouldPreserveTerminalCwdAcrossCommand(hostRestrictsExtraSshChannels(host))) {
|
||||
invalidateTerminalCwdAfterCommand(
|
||||
terminalCwdTracker,
|
||||
sessionId,
|
||||
() => { knownCwdRef.current = undefined; },
|
||||
onTerminalCwdChange,
|
||||
);
|
||||
}
|
||||
const [command, hostId, hostLabel, submittedSessionId] = args;
|
||||
onCommandSubmitted?.(command, hostId, hostLabel, submittedSessionId);
|
||||
}, [host, onCommandSubmitted, onTerminalCwdChange, sessionId, terminalCwdTracker]);
|
||||
const pluginAwareOnCommandCompleted = useCallback(() => {
|
||||
pluginTerminalLifecycle.onCommandCompleted();
|
||||
void xtermRuntimeRef.current?.pluginProviderHost?.commandCompleted();
|
||||
@@ -3265,15 +3298,26 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
|
||||
const broadcastUserPasteData = useCallback((
|
||||
data: string,
|
||||
options?: { lineDelayMs?: number },
|
||||
options?: { lineDelayMs?: number; sensitive?: boolean },
|
||||
) => {
|
||||
if (
|
||||
!passwordPromptActiveRef.current
|
||||
shouldBroadcastDuringSensitivePrompt({
|
||||
sensitivePromptActive: passwordPromptActiveRef.current,
|
||||
broadcastPasswordBypass: broadcastPasswordBypassRef.current,
|
||||
})
|
||||
&& sessionRef.current
|
||||
&& isBroadcastEnabledRef.current
|
||||
&& onBroadcastInputRef.current
|
||||
) {
|
||||
onBroadcastInputRef.current(data, sessionId, options);
|
||||
// Bypassed password fan-out (#3488): retain the sensitive marker so
|
||||
// peer writes keep skipping input interceptors. A paste confirmed at
|
||||
// a sensitive prompt keeps its pre-dialog snapshot (#3491), so its
|
||||
// carried sensitivity tags the fan-out even when the dialog await
|
||||
// cleared the live prompt ref.
|
||||
const sourceSensitive = passwordPromptActiveRef.current || options?.sensitive === true;
|
||||
onBroadcastInputRef.current(data, sessionId, sourceSensitive
|
||||
? { ...options, sourceSensitive: true }
|
||||
: options);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -3287,6 +3331,10 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
multiLineRunMode?: Snippet["multiLineRunMode"];
|
||||
/** When false, skip term.focus() so multi-tab fan-out does not steal focus. */
|
||||
focus?: boolean;
|
||||
/** Force sensitive classification on the write (bypassed password fan-out, #3488). */
|
||||
sensitive?: boolean;
|
||||
/** Observer for the broadcast recipients that received the payload (#3491). */
|
||||
onBroadcastDelivered?: (sessionIds: readonly string[]) => void;
|
||||
},
|
||||
): Promise<boolean> => {
|
||||
// Hidden-tab hibernation clears termRef. Wake via the *connected* path so
|
||||
@@ -3341,13 +3389,32 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
// without re-wrapping. Without broadcasting at all, accepting a snippet in
|
||||
// broadcast mode would clear peer input (the clear keystrokes already go
|
||||
// through the broadcast-aware path) but never send the command.
|
||||
const sensitive = passwordPromptActiveRef.current;
|
||||
if (!sensitive && options?.broadcast !== false && isBroadcastEnabledRef.current && onBroadcastInputRef.current) {
|
||||
onBroadcastInputRef.current(data, sessionId, {
|
||||
// A bypassed password fan-out (#3488) forces the sensitive marker even
|
||||
// when this target has not itself classified its prompt as sensitive.
|
||||
const sensitive = passwordPromptActiveRef.current || options?.sensitive === true;
|
||||
if (
|
||||
shouldBroadcastDuringSensitivePrompt({
|
||||
sensitivePromptActive: sensitive,
|
||||
broadcastPasswordBypass: broadcastPasswordBypassRef.current,
|
||||
})
|
||||
&& options?.broadcast !== false
|
||||
&& isBroadcastEnabledRef.current
|
||||
&& onBroadcastInputRef.current
|
||||
) {
|
||||
const broadcastDeliveredSessionIds = onBroadcastInputRef.current(data, sessionId, {
|
||||
automated: true,
|
||||
noAutoRun,
|
||||
// Bypassed password fan-out (#3488): retain the sensitive marker so
|
||||
// peer writes keep skipping input interceptors.
|
||||
...(sensitive ? { sourceSensitive: true } : {}),
|
||||
...(lineDelayMs ? { lineDelayMs } : {}),
|
||||
});
|
||||
// #3491: report the sessions that received the fan-out so callers (the
|
||||
// solo compose bar) can detect a payload delivered into a sensitive
|
||||
// peer prompt and keep it out of send history.
|
||||
if (broadcastDeliveredSessionIds) {
|
||||
options?.onBroadcastDelivered?.(broadcastDeliveredSessionIds);
|
||||
}
|
||||
}
|
||||
|
||||
data = prepareProgrammaticSudoInput(data);
|
||||
@@ -3377,6 +3444,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
await runAutomationScript({
|
||||
snippet,
|
||||
sessionId,
|
||||
initiatedBy: 'user',
|
||||
sessionMeta: {
|
||||
connected: true,
|
||||
name: scriptSessionName,
|
||||
@@ -3416,6 +3484,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
isBroadcastEnabledRef,
|
||||
onBroadcastInputRef,
|
||||
passwordPromptActiveRef,
|
||||
broadcastPasswordBypassRef,
|
||||
isLocalConnection,
|
||||
supportsRemoteImagePaste,
|
||||
autoUploadClipboardImageOnPasteRef,
|
||||
@@ -4006,6 +4075,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
terminalBackend,
|
||||
isSensitiveInput: () => passwordPromptActiveRef.current,
|
||||
scrollOnPasteRef,
|
||||
broadcastPasswordBypassRef,
|
||||
onPasteData: broadcastUserPasteData,
|
||||
scrollToBottomAfterProgrammaticInput,
|
||||
containerRef,
|
||||
@@ -4248,6 +4318,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
onOpenExternalError,
|
||||
isBroadcastEnabledRef,
|
||||
onBroadcastInputRef,
|
||||
broadcastPasswordBypassRef,
|
||||
snippetsRef,
|
||||
onSnippetShortkeyRef,
|
||||
sessionId,
|
||||
@@ -4554,7 +4625,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
onWake: wakeFromHibernateRuntime,
|
||||
});
|
||||
|
||||
useTerminalEffects({ CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setTimeLeft, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
useTerminalEffects({ CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setTimeLeft, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -27,6 +27,7 @@ import { detectLocalOs } from '../lib/localShell';
|
||||
import { useStoredString } from '../application/state/useStoredString';
|
||||
import { useStoredNumber } from '../application/state/useStoredNumber';
|
||||
import { useStoredBoolean } from '../application/state/useStoredBoolean';
|
||||
import { STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS } from '../infrastructure/config/storageKeys';
|
||||
import {
|
||||
STORAGE_KEY_SIDE_PANEL_HEIGHT,
|
||||
STORAGE_KEY_SIDE_PANEL_WIDTH,
|
||||
@@ -117,7 +118,7 @@ import {
|
||||
type RendererCwdSource,
|
||||
type TerminalCwdChangeMeta,
|
||||
} from './terminal/sftpCwd';
|
||||
import { classifyDistroId, shouldProbeSessionCwd } from '../domain/host';
|
||||
import { classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from '../domain/host';
|
||||
import {
|
||||
collectSidePanelPanes,
|
||||
sidePanelLayoutHasTool,
|
||||
@@ -741,6 +742,14 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
STORAGE_KEY_TERMINAL_COMPOSE_BAR_OPEN,
|
||||
false,
|
||||
);
|
||||
// Opt-in "broadcast without password protection" (#3488): when enabled, the
|
||||
// fail-closed password-prompt heuristic no longer pauses workspace broadcast.
|
||||
const [broadcastPasswordBypass] = useStoredBoolean(
|
||||
STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS,
|
||||
false,
|
||||
);
|
||||
const broadcastPasswordBypassRef = useRef(broadcastPasswordBypass);
|
||||
broadcastPasswordBypassRef.current = broadcastPasswordBypass;
|
||||
const sessionsRef = useRef(sessions);
|
||||
sessionsRef.current = sessions;
|
||||
const workspacesRef = useRef(workspaces);
|
||||
@@ -1241,10 +1250,13 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
options?: TerminalBroadcastInputOptions,
|
||||
) => {
|
||||
const paced = options?.pacedBroadcast;
|
||||
// Opt-in #3488 bypass: when enabled, sensitive-prompt targets stay in the
|
||||
// fan-out instead of being silently dropped here.
|
||||
const passwordBypass = broadcastPasswordBypassRef.current === true;
|
||||
if (paced && !options?.preparePacedBroadcast) {
|
||||
if (!paced.targets || isTerminalSensitiveInputActive(sourceSessionId)) return [];
|
||||
if (!paced.targets || (!passwordBypass && isTerminalSensitiveInputActive(sourceSessionId))) return [];
|
||||
paced.targets = paced.targets.filter(target => isTerminalBroadcastInputCurrent(target)
|
||||
&& !isTerminalSensitiveInputActive(target.sessionId));
|
||||
&& (passwordBypass || !isTerminalSensitiveInputActive(target.sessionId)));
|
||||
}
|
||||
const targetSessionIds = resolveTerminalBroadcastTargetIds({
|
||||
sessions: sessionsRef.current,
|
||||
@@ -1253,7 +1265,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
directTargetSessionIds: options?.kittyKeyboardTargetSessionIds,
|
||||
}).filter(id => !paced?.targets || paced.targets.some(target => target.sessionId === id));
|
||||
if (options?.preparePacedBroadcast && paced) {
|
||||
paced.targets = targetSessionIds.filter(id => !isTerminalSensitiveInputActive(id)).map(id => {
|
||||
paced.targets = targetSessionIds.filter(id => passwordBypass || !isTerminalSensitiveInputActive(id)).map(id => {
|
||||
markTerminalBroadcastUserInput(id);
|
||||
terminalBackend.interruptSession(id, undefined, { cancelPendingWritesOnly: true });
|
||||
return captureTerminalBroadcastInput(id);
|
||||
@@ -1275,6 +1287,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
beforeUrgentInterrupt: () => {
|
||||
broadcastInterruptPrioritizersRef.current.get(session.id)?.();
|
||||
},
|
||||
// Bypassed password fan-out (#3488): the receiver forces sensitive
|
||||
// writes so its input interceptors stay skipped for the secret.
|
||||
...(options?.sourceSensitive === true ? { sourceSensitive: true } : {}),
|
||||
});
|
||||
deliveredSessionIds.push(session.id);
|
||||
continue;
|
||||
@@ -1297,10 +1312,15 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
terminalBackend.interruptSession(session.id);
|
||||
continue;
|
||||
}
|
||||
if (isTerminalSensitiveInputActive(session.id)) continue;
|
||||
if (!passwordBypass && isTerminalSensitiveInputActive(session.id)) continue;
|
||||
terminalBackend.writeToSession(session.id, data, {
|
||||
automated: options?.automated === true,
|
||||
sensitive: false,
|
||||
// Retain the source-sensitive marker (bypassed password fan-out, #3488)
|
||||
// so peer input interceptors stay skipped for the secret payload. A
|
||||
// target that is itself awaiting a secret keeps its classification:
|
||||
// bypassing the fan-out pause must not downgrade its own sensitive
|
||||
// state (#3491).
|
||||
sensitive: options?.sourceSensitive === true || isTerminalSensitiveInputActive(session.id),
|
||||
...(lineDelayMs ? { lineDelayMs } : {}),
|
||||
});
|
||||
deliveredSessionIds.push(session.id);
|
||||
@@ -1323,6 +1343,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
visibleSftpHost,
|
||||
sessionHost,
|
||||
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
|
||||
})) return;
|
||||
|
||||
const osc7SignalAtCommand = terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0;
|
||||
@@ -1338,13 +1359,14 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
if (cwdProbeGenerationRef.current.get(sessionId) !== probeGeneration) return false;
|
||||
const host = sessionHostsMapRef.current.get(sessionId);
|
||||
if (!host) return false;
|
||||
const detectedDeviceClass = classifyDistroId(host.distro);
|
||||
const isNetworkDevice =
|
||||
host.deviceType === 'network' || detectedDeviceClass === 'network-device';
|
||||
const hostDeviceClass = classifyDistroId(host.distro);
|
||||
const hostIsNetworkDevice =
|
||||
host.deviceType === 'network' || hostDeviceClass === 'network-device';
|
||||
const info = await terminalBackend.getSessionRemoteInfo?.(sessionId);
|
||||
return shouldProbeSessionCwd({
|
||||
isNetworkDevice,
|
||||
isNetworkDevice: hostIsNetworkDevice,
|
||||
remoteSshVersion: info?.remoteSshVersion,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(host),
|
||||
});
|
||||
},
|
||||
onProbedCwd: (cwd) => {
|
||||
@@ -1552,14 +1574,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
requireActiveShellCwd?: boolean;
|
||||
}): Promise<string | null> => {
|
||||
const sessionId = getActiveTerminalSessionId();
|
||||
const host = sessionId ? sessionHostsMapRef.current.get(sessionId) : undefined;
|
||||
const skipBackendPwd = hostRestrictsExtraSshChannels(host);
|
||||
return resolvePreferredTerminalCwd({
|
||||
rendererCwd: sessionId ? terminalRendererCwdBySessionRef.current.get(sessionId) : undefined,
|
||||
rendererCwdSource: sessionId
|
||||
? terminalRendererCwdSourceBySessionRef.current.get(sessionId)
|
||||
: undefined,
|
||||
sessionId,
|
||||
getSessionPwd: (id, options) => terminalBackend.getSessionPwd(id, options),
|
||||
preferFreshBackend: options?.preferFreshBackend,
|
||||
getSessionPwd: skipBackendPwd
|
||||
? async () => ({ success: false })
|
||||
: (id, pwdOptions) => terminalBackend.getSessionPwd(id, pwdOptions),
|
||||
preferFreshBackend: skipBackendPwd ? false : options?.preferFreshBackend,
|
||||
allowRendererFallback: options?.allowRendererFallback,
|
||||
requireActiveShellCwd: options?.requireActiveShellCwd,
|
||||
});
|
||||
@@ -2129,6 +2155,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
await runAutomationScript({
|
||||
snippet,
|
||||
sessionId,
|
||||
initiatedBy: 'user',
|
||||
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -2154,6 +2181,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
await runAutomationScript({
|
||||
snippet,
|
||||
sessionId,
|
||||
initiatedBy: 'user',
|
||||
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -2239,6 +2267,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
await runAutomationScript({
|
||||
snippet,
|
||||
sessionId,
|
||||
initiatedBy: 'user',
|
||||
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -2308,6 +2337,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const runOnSession = (sid: string) => runAutomationScript({
|
||||
snippet,
|
||||
sessionId: sid,
|
||||
initiatedBy: 'user',
|
||||
sessionMeta: buildScriptSessionMeta(sid, sessionsRef.current, hosts),
|
||||
});
|
||||
if (mode === 'sequential') {
|
||||
@@ -2357,29 +2387,55 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const activeWorkspace = activeWorkspaceRef.current;
|
||||
if (!activeWorkspace) return false;
|
||||
let recordHistory = false;
|
||||
// Any recipient at a sensitive prompt turns the fan-out into a secret
|
||||
// delivery: the payload is that peer's password/MFA input and must not be
|
||||
// recallable from compose history, even if the focused session itself is
|
||||
// non-sensitive.
|
||||
let anyRecipientSensitive = false;
|
||||
const pendingSends: Promise<boolean>[] = [];
|
||||
const payload = text + '\r';
|
||||
const broadcastEnabled = isBroadcastEnabled?.(activeWorkspace.id);
|
||||
const focusedSessionId = activeWorkspace.focusedSessionId;
|
||||
const broadcastPasswordBypass = broadcastPasswordBypassRef.current;
|
||||
const focusedSensitive = focusedSessionId
|
||||
? isTerminalSensitiveInputActive(focusedSessionId)
|
||||
: false;
|
||||
|
||||
if (broadcastEnabled && !focusedSensitive) {
|
||||
if (broadcastEnabled && (broadcastPasswordBypass || !focusedSensitive)) {
|
||||
const allSessionIds = sessionsRef.current
|
||||
.filter((session) => session.workspaceId === activeWorkspace.id)
|
||||
.map((session) => session.id);
|
||||
for (const sid of allSessionIds) {
|
||||
if (isTerminalSensitiveInputActive(sid)) continue;
|
||||
const recipientSensitive = isTerminalSensitiveInputActive(sid);
|
||||
if (!broadcastPasswordBypass && recipientSensitive) continue;
|
||||
const executor = snippetExecutorsRef.current.get(sid);
|
||||
if (executor) {
|
||||
pendingSends.push(Promise.resolve(executor(text, false, { broadcast: false })).then(
|
||||
(sent) => sent && !isTerminalSensitiveInputActive(sid),
|
||||
pendingSends.push(Promise.resolve(executor(text, false, {
|
||||
broadcast: false,
|
||||
// Preserve both prompt snapshots across an asynchronous wake: the
|
||||
// peer may clear its prompt classification before the actual write.
|
||||
...(focusedSensitive || recipientSensitive ? { sensitive: true } : {}),
|
||||
})).then(
|
||||
(sent) => {
|
||||
// A lagging peer can reach its password prompt by delivery time;
|
||||
// anything it receives there is its secret input, so mark the
|
||||
// whole fan-out as history-ineligible.
|
||||
if (sent && (recipientSensitive || isTerminalSensitiveInputActive(sid))) anyRecipientSensitive = true;
|
||||
return sent && (broadcastPasswordBypass || !isTerminalSensitiveInputActive(sid));
|
||||
},
|
||||
));
|
||||
} else {
|
||||
const session = sessionsRef.current.find((candidate) => candidate.id === sid);
|
||||
if (!session || !canUseDirectSessionWriteFallback(session)) continue;
|
||||
terminalBackend.writeToSession(sid, payload, { sensitive: false });
|
||||
// Keep the source-sensitive marker when the #3488 bypass let a
|
||||
// password-prompt payload through, so interceptors stay skipped.
|
||||
// A non-sensitive focused pane can still fan into a sensitive peer
|
||||
// (its password/MFA input): mark the peer's write sensitive too,
|
||||
// like the broadcast dispatcher does for its executor writes.
|
||||
terminalBackend.writeToSession(sid, payload, {
|
||||
sensitive: focusedSensitive || recipientSensitive,
|
||||
});
|
||||
if (recipientSensitive) anyRecipientSensitive = true;
|
||||
recordHistory = recordHistory || session.status === 'connected';
|
||||
}
|
||||
}
|
||||
@@ -2407,7 +2463,13 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
}
|
||||
}
|
||||
const results = await Promise.allSettled(pendingSends);
|
||||
return recordHistory || results.some((result) => result.status === 'fulfilled' && result.value);
|
||||
const delivered = recordHistory || results.some((result) => result.status === 'fulfilled' && result.value);
|
||||
// A bypassed send typed at a sensitive prompt (#3488), or delivered into
|
||||
// any recipient's sensitive prompt, was delivered but must not be
|
||||
// recallable from compose history via ArrowUp, so report no history
|
||||
// eligibility for it.
|
||||
if (focusedSensitive || anyRecipientSensitive) return false;
|
||||
return delivered;
|
||||
}, [isBroadcastEnabled, terminalBackend]);
|
||||
|
||||
const sessionLogConfig = useMemo(
|
||||
|
||||
@@ -1188,12 +1188,9 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Keep window controls above the top drag stripe so their full height remains clickable. */}
|
||||
{/* Right controls share the tab row. */}
|
||||
<div
|
||||
className={cn(
|
||||
"flex-shrink-0 flex items-center gap-0.5 app-drag overflow-visible self-end",
|
||||
showWindowControls ? "relative z-20 h-9" : "h-7",
|
||||
)}
|
||||
className="flex-shrink-0 flex items-center gap-0.5 app-drag h-7 overflow-visible self-end"
|
||||
style={dragRegionStyle}
|
||||
data-section="top-tabs-toolbar-actions"
|
||||
>
|
||||
|
||||
@@ -249,7 +249,7 @@ function formatToolResult(result: unknown): string {
|
||||
const obj = JSON.parse(parsed);
|
||||
if (obj && typeof obj === 'object') parsed = obj;
|
||||
} catch {
|
||||
return parsed;
|
||||
return result as string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,6 +272,7 @@ function formatToolResult(result: unknown): string {
|
||||
|
||||
export interface ToolCallProps extends HTMLAttributes<HTMLDivElement> {
|
||||
name: string;
|
||||
approvalTarget?: { label: string; hostname: string };
|
||||
className?: string;
|
||||
args?: Record<string, unknown>;
|
||||
result?: unknown;
|
||||
@@ -292,6 +293,7 @@ export interface ToolCallProps extends HTMLAttributes<HTMLDivElement> {
|
||||
onAlwaysAllow?: () => void;
|
||||
/** Optional source-specific label for the persistent/session approval action. */
|
||||
alwaysAllowLabel?: string;
|
||||
alwaysAllowTitle?: string;
|
||||
}
|
||||
|
||||
async function copyTextToClipboard(text: string): Promise<boolean> {
|
||||
@@ -321,8 +323,8 @@ async function copyTextToClipboard(text: string): Promise<boolean> {
|
||||
}
|
||||
|
||||
export const ToolCall = ({
|
||||
name, args, result, isError, isLoading, isInterrupted,
|
||||
approvalStatus, approvalId, onApprove, onReject, onApproveOnce, onAlwaysAllow, alwaysAllowLabel,
|
||||
name, args, result, isError, isLoading, isInterrupted, approvalTarget,
|
||||
approvalStatus, approvalId, onApprove, onReject, onApproveOnce, onAlwaysAllow, alwaysAllowLabel, alwaysAllowTitle,
|
||||
className, ...props
|
||||
}: ToolCallProps) => {
|
||||
const { t } = useI18n();
|
||||
@@ -520,31 +522,47 @@ export const ToolCall = ({
|
||||
{statusIcon}
|
||||
</button>
|
||||
|
||||
{isPendingApproval && approvalTarget && !showApprovalCommand && (
|
||||
<div className="min-w-0 break-words border-t border-border/20 px-3 py-1.5 text-xs font-medium">
|
||||
{t('ai.chat.targetLabel')}: <span className="break-all">{approvalTarget.label}</span>
|
||||
{approvalTarget.hostname && approvalTarget.hostname !== approvalTarget.label && (
|
||||
<span className="ml-1 break-all text-muted-foreground">({approvalTarget.hostname})</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{expanded && (
|
||||
<div className="border-t border-border/20">
|
||||
{showApprovalCommand && reviewCommand && (
|
||||
<div className="px-3 py-2 space-y-1.5">
|
||||
{executionContext && (
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted-foreground/45">
|
||||
<span className="font-medium uppercase tracking-wider text-muted-foreground/30">
|
||||
{(approvalTarget || executionContext) && (
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground">
|
||||
<span className="font-medium uppercase tracking-wider text-muted-foreground/60">
|
||||
{t('ai.chat.targetLabel')}
|
||||
</span>
|
||||
{executionContext.sessionId && (
|
||||
{approvalTarget ? (
|
||||
<span className="min-w-0 break-all font-medium text-foreground/90">
|
||||
{approvalTarget.label}
|
||||
{approvalTarget.hostname && approvalTarget.hostname !== approvalTarget.label && (
|
||||
<span className="ml-1 font-normal text-muted-foreground">({approvalTarget.hostname})</span>
|
||||
)}
|
||||
</span>
|
||||
) : executionContext?.sessionId && (
|
||||
<span className="font-mono truncate" title={executionContext.sessionId}>
|
||||
{t('ai.chat.approvalSession')}: {executionContext.sessionId}
|
||||
</span>
|
||||
)}
|
||||
{executionContext.shell && (
|
||||
{executionContext?.shell && (
|
||||
<span className="font-mono">
|
||||
{t('ai.chat.approvalShell')}: {executionContext.shell}
|
||||
</span>
|
||||
)}
|
||||
{executionContext.cwd && (
|
||||
{executionContext?.cwd && (
|
||||
<span className="font-mono truncate" title={executionContext.cwd}>
|
||||
{t('ai.chat.approvalCwd')}: {executionContext.cwd}
|
||||
</span>
|
||||
)}
|
||||
{executionContext.reason && (
|
||||
{executionContext?.reason && (
|
||||
<span className="truncate" title={executionContext.reason}>
|
||||
{t('ai.chat.approvalReason')}: {executionContext.reason}
|
||||
</span>
|
||||
@@ -656,6 +674,7 @@ export const ToolCall = ({
|
||||
size="sm"
|
||||
className="h-7 min-w-0 flex-1 gap-1 px-1.5 text-[11px] font-normal border-green-500/35 text-green-300/95 hover:bg-green-500/10 hover:text-green-300 hover:border-green-500/50"
|
||||
onClick={handleAlwaysAllow}
|
||||
title={alwaysAllowTitle}
|
||||
>
|
||||
<Check size={12} className="shrink-0" />
|
||||
<span className="truncate">{alwaysAllowLabel || t('ai.chat.alwaysAllow')}</span>
|
||||
|
||||
@@ -843,6 +843,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
<ToolCall
|
||||
name={req.toolName}
|
||||
args={req.args}
|
||||
approvalTarget={req.target}
|
||||
isLoading={false}
|
||||
isInterrupted={false}
|
||||
approvalStatus={'pending'}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { ToolCall } from '../ai-elements/tool-call';
|
||||
import { Button } from '../ui/button';
|
||||
import {
|
||||
onApprovalCleared,
|
||||
onApprovalRequest,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
} from '../../infrastructure/ai/shared/approvalGate';
|
||||
import {
|
||||
buildGrantsFromApproval,
|
||||
createPermissionGrantId,
|
||||
resolveCapabilityId,
|
||||
} from '../../infrastructure/ai/harness/permissionGrants';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
@@ -61,7 +63,10 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
|
||||
|
||||
const handleAlwaysAllow = useCallback((toolCallId: string, request: ApprovalRequest) => {
|
||||
const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName);
|
||||
const persistGrants = buildGrantsFromApproval(capabilityId, request.args, request.chatSessionId);
|
||||
const persistGrants = buildGrantsFromApproval(capabilityId, request.args, request.chatSessionId)
|
||||
.map((grant) => request.target?.hostId
|
||||
? { ...grant, sessionPattern: `host:${request.target.hostId}` }
|
||||
: grant);
|
||||
resolveApproval(toolCallId, { approved: true, persistGrants });
|
||||
setPendingApprovals((prev) => {
|
||||
const next = new Map(prev);
|
||||
@@ -70,6 +75,35 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleAllowSession = useCallback((toolCallId: string) => {
|
||||
resolveApproval(toolCallId, { approved: true, scope: 'session' });
|
||||
setPendingApprovals((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(toolCallId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleAllowHost = useCallback((toolCallId: string, request: ApprovalRequest) => {
|
||||
const hostId = request.target?.hostId;
|
||||
if (!hostId) return;
|
||||
resolveApproval(toolCallId, {
|
||||
approved: true,
|
||||
persistGrant: {
|
||||
id: createPermissionGrantId(),
|
||||
capabilityId: '*',
|
||||
sessionPattern: `host:${hostId}`,
|
||||
createdAt: Date.now(),
|
||||
note: request.target?.label,
|
||||
},
|
||||
});
|
||||
setPendingApprovals((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(toolCallId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleReject = useCallback((toolCallId: string) => {
|
||||
resolveApproval(toolCallId, false);
|
||||
setPendingApprovals((prev) => {
|
||||
@@ -84,7 +118,7 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-auto fixed bottom-4 right-4 z-[80] flex w-[min(420px,calc(100vw-2rem))] flex-col gap-2"
|
||||
className="pointer-events-auto fixed bottom-4 right-4 z-[80] flex max-h-[calc(100vh-2rem)] w-[min(420px,calc(100vw-2rem))] flex-col gap-2 overflow-y-auto overscroll-contain"
|
||||
data-testid="external-mcp-approvals-host"
|
||||
>
|
||||
<div className="rounded-lg border border-border/60 bg-background/95 p-3 shadow-lg backdrop-blur-sm">
|
||||
@@ -93,18 +127,65 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{entries.map(([id, req]) => (
|
||||
<ToolCall
|
||||
key={id}
|
||||
name={req.toolName}
|
||||
args={req.args}
|
||||
isLoading={false}
|
||||
isInterrupted={false}
|
||||
approvalStatus="pending"
|
||||
approvalId={id}
|
||||
onApproveOnce={() => handleApproveOnce(id)}
|
||||
onAlwaysAllow={() => handleAlwaysAllow(id, req)}
|
||||
onReject={() => handleReject(id)}
|
||||
/>
|
||||
<div key={id} className="space-y-1.5">
|
||||
<ToolCall
|
||||
name={req.toolName}
|
||||
args={req.args}
|
||||
approvalTarget={req.target}
|
||||
isLoading={false}
|
||||
isInterrupted={false}
|
||||
approvalStatus="pending"
|
||||
approvalId={id}
|
||||
onApproveOnce={() => handleApproveOnce(id)}
|
||||
onAlwaysAllow={req.target && !req.target.hostId ? undefined : () => handleAlwaysAllow(id, req)}
|
||||
onReject={() => handleReject(id)}
|
||||
alwaysAllowLabel={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHost') : undefined}
|
||||
alwaysAllowTitle={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHostHint') : undefined}
|
||||
/>
|
||||
{(req.allowSession || req.target?.hostId) && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground/60">
|
||||
{t('ai.externalMcp.allowAll')}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
{req.allowSession && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={`h-7 min-w-0 px-2 text-[11px] ${req.target?.hostId ? '' : 'col-span-2'}`}
|
||||
title={t('ai.externalMcp.allowSessionHint')}
|
||||
onClick={() => handleAllowSession(id)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleReject(id);
|
||||
}}
|
||||
>
|
||||
{t('ai.externalMcp.allowSession')}
|
||||
</Button>
|
||||
)}
|
||||
{req.target?.hostId && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={`h-7 min-w-0 px-2 text-[11px] ${req.allowSession ? '' : 'col-span-2'}`}
|
||||
title={t('ai.externalMcp.allowHostHint')}
|
||||
onClick={() => handleAllowHost(id, req)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleReject(id);
|
||||
}}
|
||||
>
|
||||
{t('ai.externalMcp.allowHost')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -345,6 +345,23 @@ test('buildManagedAgentState stores OPENCODE_BIN for opencode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('buildManagedAgentState stores MIMOCODE_BIN for mimo', () => {
|
||||
const state = buildManagedAgentState(
|
||||
[],
|
||||
'catty',
|
||||
'mimo',
|
||||
{ path: '/opt/homebrew/bin/mimo', version: '1.0.0', available: true },
|
||||
);
|
||||
|
||||
assert.equal(state.agents.length, 1);
|
||||
assert.equal(state.agents[0].id, 'discovered_mimo');
|
||||
assert.equal(state.agents[0].command, '/opt/homebrew/bin/mimo');
|
||||
assert.equal(state.agents[0].sdkBackend, 'mimo');
|
||||
assert.deepEqual(state.agents[0].env, {
|
||||
MIMOCODE_BIN: '/opt/homebrew/bin/mimo',
|
||||
});
|
||||
});
|
||||
|
||||
test('updateCodebuddyManagedEnv creates a disabled managed entry before CLI detection', () => {
|
||||
const state = updateCodebuddyManagedEnv([], 'internal', 'CODEBUDDY_API_KEY=secret');
|
||||
|
||||
|
||||
@@ -50,4 +50,34 @@ test('inferArtifactToolNameFromCliArgs maps Netcatty CLI artifact commands', ()
|
||||
}),
|
||||
'host_get',
|
||||
);
|
||||
assert.equal(
|
||||
inferArtifactToolNameFromCliArgs({
|
||||
command: `/bin/zsh -lc '"/Applications/Netcatty.app/netcatty-tool-cli" notes import --file-name runbook.md --content-stdin --json'`,
|
||||
}),
|
||||
'vault_notes_import',
|
||||
);
|
||||
assert.equal(
|
||||
inferArtifactToolNameFromCliArgs({
|
||||
command: `/bin/zsh -lc '"/Applications/Netcatty.app/netcatty-tool-cli" --json notes list'`,
|
||||
}),
|
||||
'vault_notes_list',
|
||||
);
|
||||
assert.equal(
|
||||
inferArtifactToolNameFromCliArgs({
|
||||
command: 'netcatty-tool-cli notes list --json',
|
||||
}),
|
||||
'vault_notes_list',
|
||||
);
|
||||
assert.equal(
|
||||
inferArtifactToolNameFromCliArgs({
|
||||
command: 'netcatty-tool-cli notes --group "ops team" import --content-stdin --json',
|
||||
}),
|
||||
'vault_notes_import',
|
||||
);
|
||||
assert.equal(
|
||||
inferArtifactToolNameFromCliArgs({
|
||||
command: '& "C:\\Program Files\\Netcatty\\netcatty-tool-cli.cmd" notes import --attachment-index 0 --json',
|
||||
}),
|
||||
'vault_notes_import',
|
||||
);
|
||||
});
|
||||
@@ -6,6 +6,8 @@ const KNOWN_ARTIFACT_TOOL_NAMES = [
|
||||
'vault_notes_update',
|
||||
'vault_notes_get',
|
||||
'vault_notes_list',
|
||||
'vault_notes_delete',
|
||||
'vault_notes_import',
|
||||
'vault_hosts_create',
|
||||
'vault_hosts_import',
|
||||
'vault_hosts_list',
|
||||
@@ -30,8 +32,16 @@ const KNOWN_ARTIFACT_TOOL_NAMES = [
|
||||
'scripts_targets_set',
|
||||
] as const;
|
||||
|
||||
const CLI_FLAGS_WITHOUT_VALUES = new Set(['--json', '--content-stdin', '--documents-stdin']);
|
||||
|
||||
const CLI_ARTIFACT_TOOL_NAMES = new Map<string, string>([
|
||||
['vault host get', 'host_get'],
|
||||
['notes list', 'vault_notes_list'],
|
||||
['notes get', 'vault_notes_get'],
|
||||
['notes create', 'vault_notes_create'],
|
||||
['notes update', 'vault_notes_update'],
|
||||
['notes delete', 'vault_notes_delete'],
|
||||
['notes import', 'vault_notes_import'],
|
||||
]);
|
||||
|
||||
function readCommandString(args: Record<string, unknown> | undefined): string | null {
|
||||
@@ -84,6 +94,26 @@ export function normalizeArtifactToolName(toolName: string | undefined): string
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function collectCliCommandWords(afterCli: string): string[] {
|
||||
const commandWords: string[] = [];
|
||||
const parts = afterCli.match(/(?:[^\s"'\\]|\\.|"(?:\\.|[^"\\])*"|'[^']*')+/g) ?? [];
|
||||
for (let index = 0; index < parts.length; index += 1) {
|
||||
const part = parts[index];
|
||||
if (!part) continue;
|
||||
if (part.startsWith('-')) {
|
||||
// Flags may appear before or between command words. Skip a valued flag's
|
||||
// quoted or unquoted value so note content is never a command word.
|
||||
if (CLI_FLAGS_WITHOUT_VALUES.has(part)) continue;
|
||||
const next = parts[index + 1];
|
||||
if (next && !next.startsWith('-')) index += 1;
|
||||
continue;
|
||||
}
|
||||
commandWords.push(part);
|
||||
if (CLI_ARTIFACT_TOOL_NAMES.has(commandWords.join(' ')) || commandWords.length === 3) break;
|
||||
}
|
||||
return commandWords;
|
||||
}
|
||||
|
||||
export function inferArtifactToolNameFromCliArgs(
|
||||
args: Record<string, unknown> | undefined,
|
||||
): string | undefined {
|
||||
@@ -91,15 +121,11 @@ export function inferArtifactToolNameFromCliArgs(
|
||||
if (!command) return undefined;
|
||||
|
||||
const unwrapped = unwrapShellCommand(command);
|
||||
const cliMatch = unwrapped.match(/(?:^|\s|["'])(?:\S*\/)?netcatty-tool-cli(?:\.(?:cjs|cmd))?(?=["'\s]|$)([\s\S]*)$/);
|
||||
const cliMatch = unwrapped.match(/(?:^|\s|["'])(?:\S*[\\/])?netcatty-tool-cli(?:\.(?:cjs|cmd))?(?=["'\s]|$)([\s\S]*)$/);
|
||||
if (!cliMatch) return undefined;
|
||||
|
||||
const afterCli = stripWrappingQuote(cliMatch[1] ?? '').replace(/^["']?\s*/, '');
|
||||
const commandKey = afterCli
|
||||
.split(/\s+/)
|
||||
.filter((part) => part && !part.startsWith('-'))
|
||||
.slice(0, 3)
|
||||
.join(' ');
|
||||
const commandKey = collectCliCommandWords(afterCli).join(' ');
|
||||
|
||||
return CLI_ARTIFACT_TOOL_NAMES.get(commandKey);
|
||||
}
|
||||
@@ -11,6 +11,13 @@ test('resolveVaultArtifactVisualKind distinguishes note vs host tools', () => {
|
||||
),
|
||||
'noteCreate',
|
||||
);
|
||||
assert.equal(
|
||||
resolveVaultArtifactVisualKind(
|
||||
{ kind: 'vault.note', noteId: 'n1', title: 'Doc' },
|
||||
'vault_notes_import',
|
||||
),
|
||||
'noteImport',
|
||||
);
|
||||
assert.equal(
|
||||
resolveVaultArtifactVisualKind(
|
||||
{ kind: 'vault.host', hostId: 'h1', label: 'Web', hostname: '10.0.0.1' },
|
||||
|
||||
@@ -26,6 +26,7 @@ export type VaultArtifactVisualKind =
|
||||
| 'noteUpdate'
|
||||
| 'noteRead'
|
||||
| 'noteList'
|
||||
| 'noteImport'
|
||||
| 'host'
|
||||
| 'hostCreate'
|
||||
| 'hostImport'
|
||||
@@ -54,6 +55,7 @@ const VISUAL_STYLES: Record<VaultArtifactVisualKind, { wrapper: string; icon: st
|
||||
noteUpdate: { wrapper: 'bg-violet-500/10', icon: 'text-violet-300/90' },
|
||||
noteRead: { wrapper: 'bg-violet-500/10', icon: 'text-violet-300/80' },
|
||||
noteList: { wrapper: 'bg-muted/30', icon: 'text-muted-foreground/70' },
|
||||
noteImport: { wrapper: 'bg-violet-500/12', icon: 'text-violet-400' },
|
||||
host: { wrapper: 'bg-emerald-500/12', icon: 'text-emerald-400' },
|
||||
hostCreate: { wrapper: 'bg-sky-500/12', icon: 'text-sky-400' },
|
||||
hostImport: { wrapper: 'bg-amber-500/12', icon: 'text-amber-400' },
|
||||
@@ -83,6 +85,7 @@ export function resolveVaultArtifactVisualKind(
|
||||
if (artifact.kind === 'error') return 'error';
|
||||
|
||||
if (artifact.kind === 'vault.note') {
|
||||
if (toolName === 'vault_notes_import') return 'noteImport';
|
||||
if (toolName === 'vault_notes_create') return 'noteCreate';
|
||||
if (toolName === 'vault_notes_update') return 'noteUpdate';
|
||||
return 'noteRead';
|
||||
@@ -98,6 +101,7 @@ export function resolveVaultArtifactVisualKind(
|
||||
}
|
||||
|
||||
if (artifact.kind === 'vault.summary') {
|
||||
if (toolName === 'vault_notes_import') return 'noteImport';
|
||||
if (artifact.section === 'notes') return 'noteList';
|
||||
if (artifact.section === 'hosts') return 'hostList';
|
||||
if (artifact.section === 'snippets') return 'snippetList';
|
||||
@@ -139,6 +143,8 @@ function renderVisualIcon(kind: VaultArtifactVisualKind): React.ReactNode {
|
||||
return <FileText size={ARTIFACT_ICON_SIZE} className={className} />;
|
||||
case 'noteList':
|
||||
return <Library size={ARTIFACT_ICON_SIZE} className={className} />;
|
||||
case 'noteImport':
|
||||
return <FolderInput size={ARTIFACT_ICON_SIZE} className={className} />;
|
||||
case 'host':
|
||||
return <Server size={ARTIFACT_ICON_SIZE} className={className} />;
|
||||
case 'hostCreate':
|
||||
|
||||
@@ -16,6 +16,20 @@ test('parseVaultToolArtifact maps note create results', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('parseVaultToolArtifact maps a single note import', () => {
|
||||
const artifact = parseVaultToolArtifact('vault_notes_import', {
|
||||
ok: true,
|
||||
importedCount: 1,
|
||||
notes: [{ id: 'note-2', title: 'Runbook', group: 'ops' }],
|
||||
});
|
||||
assert.deepEqual(artifact, {
|
||||
kind: 'vault.note',
|
||||
noteId: 'note-2',
|
||||
title: 'Runbook',
|
||||
group: 'ops',
|
||||
});
|
||||
});
|
||||
|
||||
test('parseVaultToolArtifact maps single host create to host artifact', () => {
|
||||
const artifact = parseVaultToolArtifact('vault_hosts_create', {
|
||||
ok: true,
|
||||
|
||||
@@ -84,6 +84,7 @@ const VAULT_ARTIFACT_TOOL_NAMES = new Set([
|
||||
'vault_notes_update',
|
||||
'vault_notes_get',
|
||||
'vault_notes_list',
|
||||
'vault_notes_import',
|
||||
'vault_hosts_create',
|
||||
'vault_hosts_import',
|
||||
'vault_hosts_list',
|
||||
@@ -221,6 +222,13 @@ export function parseVaultToolArtifact(
|
||||
const notes = Array.isArray(payload.notes) ? payload.notes : [];
|
||||
return { kind: 'vault.summary', section: 'notes', count: notes.length };
|
||||
}
|
||||
case 'vault_notes_import': {
|
||||
const notes = Array.isArray(payload.notes) ? payload.notes : [];
|
||||
if (notes.length === 1) return parseNoteArtifact(notes[0]);
|
||||
const count = readNumber(payload.importedCount) ?? notes.length;
|
||||
if (count <= 0) return null;
|
||||
return { kind: 'vault.summary', section: 'notes', count };
|
||||
}
|
||||
case 'vault_hosts_create':
|
||||
case 'vault_hosts_import': {
|
||||
const preview = parsePreviewHosts(payload.previewHosts);
|
||||
|
||||
@@ -226,6 +226,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
codebuddy: string;
|
||||
opencode: string;
|
||||
grok: string;
|
||||
mimo: string;
|
||||
} | null>(null);
|
||||
if (!initialManagedPathsRef.current) {
|
||||
initialManagedPathsRef.current = getInitialManagedAgentPaths(externalAgents);
|
||||
@@ -298,6 +299,12 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
const [grokCustomPath, setGrokCustomPath] = useState(() => initialManagedPathsRef.current?.grok ?? "");
|
||||
const [isResolvingGrok, setIsResolvingGrok] = useState(false);
|
||||
|
||||
const [mimoPathInfo, setMimoPathInfo] = useState<AgentPathInfo | null>(
|
||||
() => getSavedManagedAgentPathInfo(externalAgents, "mimo"),
|
||||
);
|
||||
const [mimoCustomPath, setMimoCustomPath] = useState(() => initialManagedPathsRef.current?.mimo ?? "");
|
||||
const [isResolvingMimo, setIsResolvingMimo] = useState(false);
|
||||
|
||||
const codebuddyManagedAgent = useMemo(
|
||||
() => externalAgents.find((a) => a.id === "discovered_codebuddy"),
|
||||
[externalAgents],
|
||||
@@ -348,7 +355,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
codexRequestIdRef.current += 1;
|
||||
for (const key of ["codex", "claude", "copilot", "cursor", "codebuddy", "opencode", "grok"] as ManagedAgentKey[]) {
|
||||
for (const key of ["codex", "claude", "copilot", "cursor", "codebuddy", "opencode", "grok", "mimo"] as ManagedAgentKey[]) {
|
||||
agentPathRequestIds[key] = (agentPathRequestIds[key] ?? 0) + 1;
|
||||
}
|
||||
};
|
||||
@@ -371,7 +378,9 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
? setCodebuddyPathInfo
|
||||
: agentKey === "opencode"
|
||||
? setOpencodePathInfo
|
||||
: setGrokPathInfo;
|
||||
: agentKey === "grok"
|
||||
? setGrokPathInfo
|
||||
: setMimoPathInfo;
|
||||
|
||||
setInfo(result);
|
||||
|
||||
@@ -414,7 +423,9 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
? setIsResolvingCodebuddy
|
||||
: agentKey === "opencode"
|
||||
? setIsResolvingOpencode
|
||||
: setIsResolvingGrok;
|
||||
: agentKey === "grok"
|
||||
? setIsResolvingGrok
|
||||
: setIsResolvingMimo;
|
||||
|
||||
setResolving(true);
|
||||
const requestId = (agentPathRequestIdRef.current[agentKey] ?? 0) + 1;
|
||||
@@ -455,7 +466,9 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
? setCodebuddyPathInfo
|
||||
: agentKey === "opencode"
|
||||
? setOpencodePathInfo
|
||||
: setGrokPathInfo;
|
||||
: agentKey === "grok"
|
||||
? setGrokPathInfo
|
||||
: setMimoPathInfo;
|
||||
setInfo(result);
|
||||
return result;
|
||||
}
|
||||
@@ -494,6 +507,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
{ key: "codebuddy", delayMs: 1280, path: initialPaths?.codebuddy ?? "" },
|
||||
{ key: "opencode", delayMs: 1560, path: initialPaths?.opencode ?? "" },
|
||||
{ key: "grok", delayMs: 1840, path: initialPaths?.grok ?? "" },
|
||||
{ key: "mimo", delayMs: 2120, path: initialPaths?.mimo ?? "" },
|
||||
];
|
||||
const cancelTasks = tasks
|
||||
.filter((task) => !autoResolvedAgentStateRef.current[task.key])
|
||||
@@ -754,7 +768,9 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
? opencodeCustomPath
|
||||
: agentKey === "grok"
|
||||
? grokCustomPath
|
||||
: "";
|
||||
: agentKey === "mimo"
|
||||
? mimoCustomPath
|
||||
: "";
|
||||
const result = await resolveAgentPath(agentKey, customPath, {
|
||||
refreshShellEnv: true,
|
||||
commandSource: customPath.trim() ? "manual" : "auto",
|
||||
@@ -766,7 +782,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
codexPath: result?.path || customPath.trim() || undefined,
|
||||
});
|
||||
}
|
||||
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, resolveAgentPath, refreshCodexIntegration]);
|
||||
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, mimoCustomPath, resolveAgentPath, refreshCodexIntegration]);
|
||||
|
||||
const handleResetCustomPath = useCallback(async (agentKey: ManagedAgentKey) => {
|
||||
if (agentKey === "codex") {
|
||||
@@ -781,6 +797,8 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
setOpencodeCustomPath("");
|
||||
} else if (agentKey === "grok") {
|
||||
setGrokCustomPath("");
|
||||
} else if (agentKey === "mimo") {
|
||||
setMimoCustomPath("");
|
||||
}
|
||||
|
||||
const result = await resolveAgentPath(agentKey, "", {
|
||||
@@ -1207,6 +1225,21 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title={t('ai.mimo.title')}
|
||||
leading={<AgentIconBadge agent={{ id: "mimo", icon: "mimo", name: "MiMo Code" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
|
||||
>
|
||||
<CopilotCliCard
|
||||
pathInfo={mimoPathInfo}
|
||||
isResolvingPath={isResolvingMimo}
|
||||
customPath={mimoCustomPath}
|
||||
onCustomPathChange={setMimoCustomPath}
|
||||
onRecheckPath={() => void handleCheckCustomPath("mimo")}
|
||||
onResetPath={() => void handleResetCustomPath("mimo")}
|
||||
i18nPrefix="ai.mimo"
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
{agentOptions.length > 1 ? (
|
||||
<SettingsSection anchorId="ai-default-agent" title={t('ai.defaultAgent')}>
|
||||
<SettingCard>
|
||||
|
||||
@@ -121,6 +121,8 @@ interface SettingsSystemTabProps {
|
||||
setToggleWindowHotkey: (hotkey: string) => void;
|
||||
closeToTray: boolean;
|
||||
setCloseToTray: (enabled: boolean) => void;
|
||||
showTrayIcon: boolean;
|
||||
setShowTrayIcon: (enabled: boolean) => void;
|
||||
autoLaunchEnabled: boolean;
|
||||
setAutoLaunchEnabled: (enabled: boolean) => void;
|
||||
autoLaunchSupported: boolean;
|
||||
@@ -173,6 +175,8 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
setToggleWindowHotkey,
|
||||
closeToTray,
|
||||
setCloseToTray,
|
||||
showTrayIcon,
|
||||
setShowTrayIcon,
|
||||
autoLaunchEnabled,
|
||||
setAutoLaunchEnabled,
|
||||
autoLaunchSupported,
|
||||
@@ -1313,6 +1317,23 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
onChange={setCloseToTray}
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
{/* Show System Tray Icon */}
|
||||
<SettingRow
|
||||
anchorId="system-show-tray-icon"
|
||||
label={t("settings.globalHotkey.showTrayIcon")}
|
||||
description={t("settings.globalHotkey.showTrayIconDesc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={showTrayIcon}
|
||||
onChange={setShowTrayIcon}
|
||||
/>
|
||||
</SettingRow>
|
||||
{!showTrayIcon && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("settings.globalHotkey.showTrayIconHiddenHint")}
|
||||
</p>
|
||||
)}
|
||||
</SettingCard>
|
||||
|
||||
<SettingHint>
|
||||
|
||||
@@ -10,6 +10,15 @@ test("terminal settings expose cursor line highlight toggle", () => {
|
||||
assert.match(source, /updateTerminalSetting\("highlightCursorLine", v\)/);
|
||||
});
|
||||
|
||||
test("terminal settings expose a bounded bar cursor width control", () => {
|
||||
assert.match(source, /settings\.terminal\.cursor\.barWidth/);
|
||||
assert.match(source, /min=\{1\}/);
|
||||
assert.match(source, /max=\{4\}/);
|
||||
assert.match(source, /value=\{terminalSettings\.cursorBarWidth\}/);
|
||||
assert.match(source, /aria-label=\{t\("settings\.terminal\.cursor\.barWidth"\)\}/);
|
||||
assert.match(source, /updateTerminalSetting\("cursorBarWidth", parseInt\(e\.target\.value\)\)/);
|
||||
});
|
||||
|
||||
test("terminal settings hide terminal theme pickers while following app theme", () => {
|
||||
assert.match(source, /\{!followAppTerminalTheme && \(/);
|
||||
assert.doesNotMatch(source, /settings\.terminal\.theme\.followingTheme/);
|
||||
|
||||
@@ -602,6 +602,17 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-font-ligatures"
|
||||
label={t("settings.terminal.font.ligatures")}
|
||||
description={t("settings.terminal.font.ligatures.desc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={terminalSettings.fontLigatures}
|
||||
onChange={(v) => updateTerminalSetting("fontLigatures", v)}
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-font-line-padding"
|
||||
label={t("settings.terminal.font.linePadding")}
|
||||
@@ -652,6 +663,28 @@ function SettingsTerminalTab(props: {
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-cursor-bar-width"
|
||||
label={t("settings.terminal.cursor.barWidth")}
|
||||
description={t("settings.terminal.cursor.barWidth.desc")}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="range"
|
||||
aria-label={t("settings.terminal.cursor.barWidth")}
|
||||
min={1}
|
||||
max={4}
|
||||
step={1}
|
||||
value={terminalSettings.cursorBarWidth}
|
||||
onChange={(e) => updateTerminalSetting("cursorBarWidth", parseInt(e.target.value))}
|
||||
className="w-24 accent-primary"
|
||||
/>
|
||||
<span className="w-6 text-center text-sm text-muted-foreground">
|
||||
{terminalSettings.cursorBarWidth}px
|
||||
</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow anchorId="terminal-cursor-blink" label={t("settings.terminal.cursor.blink")}>
|
||||
<Toggle
|
||||
checked={terminalSettings.cursorBlink}
|
||||
|
||||
@@ -232,6 +232,17 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-shift-enter-force-text"
|
||||
label={t("settings.terminal.behavior.shiftEnterForceText")}
|
||||
description={t("settings.terminal.behavior.shiftEnterForceText.desc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={terminalSettings.shiftEnterForceText ?? false}
|
||||
onChange={(v) => updateTerminalSetting("shiftEnterForceText", v)}
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="terminal-clear-wipes-scrollback"
|
||||
label={t("settings.terminal.behavior.clearWipesScrollback")}
|
||||
|
||||
@@ -14,7 +14,7 @@ export const CopilotCliCard: React.FC<{
|
||||
onCustomPathChange: (path: string) => void;
|
||||
onRecheckPath: () => void;
|
||||
onResetPath?: () => void;
|
||||
i18nPrefix?: "ai.copilot" | "ai.cursor" | "ai.opencode" | "ai.grok";
|
||||
i18nPrefix?: "ai.copilot" | "ai.cursor" | "ai.opencode" | "ai.grok" | "ai.mimo";
|
||||
allowEmptyCheck?: boolean;
|
||||
showCustomPathInput?: boolean;
|
||||
/** Grok only: ACP (default) vs headless streaming-json. */
|
||||
|
||||
@@ -38,6 +38,7 @@ const GrantCapabilitySelect: React.FC<{
|
||||
options: readonly string[];
|
||||
onChange: (value: string) => void;
|
||||
}> = ({ value, options, onChange }) => {
|
||||
const { t } = useI18n();
|
||||
const selectOptions = useMemo(() => {
|
||||
if (options.includes(value)) return options;
|
||||
return [value, ...options];
|
||||
@@ -52,7 +53,7 @@ const GrantCapabilitySelect: React.FC<{
|
||||
>
|
||||
{selectOptions.map((capabilityId) => (
|
||||
<option key={capabilityId} value={capabilityId}>
|
||||
{capabilityId}
|
||||
{capabilityId === '*' ? t('ai.externalMcp.allowHost') : capabilityId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -204,6 +205,11 @@ export const PermissionGrantsSettings: React.FC<{
|
||||
updateGrant(grant.id, updates);
|
||||
}}
|
||||
/>
|
||||
{grant.sessionPattern.startsWith('host:') && (
|
||||
<div className="mt-1 truncate text-[10px] text-muted-foreground" title={grant.sessionPattern}>
|
||||
{t('ai.chat.targetLabel')}: {grant.note || grant.sessionPattern.slice(5)}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-2 py-2 align-middle max-w-0">
|
||||
{supportsCommandPattern ? (
|
||||
|
||||
@@ -111,7 +111,9 @@ export function buildManagedAgentState(
|
||||
? { ...(existingManaged?.env ?? {}), CODEBUDDY_CODE_PATH: pathInfo.path }
|
||||
: agentKey === "opencode"
|
||||
? { ...(existingManaged?.env ?? {}), OPENCODE_BIN: pathInfo.path }
|
||||
: existingManaged?.env;
|
||||
: agentKey === "mimo"
|
||||
? { ...(existingManaged?.env ?? {}), MIMOCODE_BIN: pathInfo.path }
|
||||
: existingManaged?.env;
|
||||
const cursorAuthMode = agentKey === "cursor"
|
||||
? (existingManaged?.cursorAuthMode
|
||||
?? (pathInfo.authSource === "cli-login" || pathInfo.cliLoginOk ? "cli-login" : "api-key"))
|
||||
@@ -235,5 +237,6 @@ export function getInitialManagedAgentPaths(agents: ExternalAgentConfig[]) {
|
||||
codebuddy: getAutoManagedAgentStoredPath(agents, "codebuddy") ?? "",
|
||||
opencode: getAutoManagedAgentStoredPath(agents, "opencode") ?? "",
|
||||
grok: getAutoManagedAgentStoredPath(agents, "grok") ?? "",
|
||||
mimo: getAutoManagedAgentStoredPath(agents, "mimo") ?? "",
|
||||
};
|
||||
}
|
||||
@@ -235,6 +235,12 @@ export const AGENT_DEFAULTS: Record<string, Omit<ExternalAgentConfig, "id" | "co
|
||||
icon: "grok",
|
||||
sdkBackend: "grok",
|
||||
},
|
||||
mimo: {
|
||||
name: "MiMo Code",
|
||||
args: [],
|
||||
icon: "mimo",
|
||||
sdkBackend: "mimo",
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -51,6 +51,7 @@ interface SftpPaneDialogsProps {
|
||||
showDeleteConfirm: boolean;
|
||||
setShowDeleteConfirm: (open: boolean) => void;
|
||||
deleteTargets: string[];
|
||||
deleteError?: string | null;
|
||||
handleDelete: () => void;
|
||||
isDeleting: boolean;
|
||||
// Host picker (connected view)
|
||||
@@ -104,6 +105,7 @@ export const SftpPaneDialogs: React.FC<SftpPaneDialogsProps> = ({
|
||||
showDeleteConfirm,
|
||||
setShowDeleteConfirm,
|
||||
deleteTargets,
|
||||
deleteError,
|
||||
handleDelete,
|
||||
isDeleting,
|
||||
showHostPicker,
|
||||
@@ -351,16 +353,24 @@ export const SftpPaneDialogs: React.FC<SftpPaneDialogsProps> = ({
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{deleteError ? (
|
||||
<p className="break-words text-xs text-destructive [overflow-wrap:anywhere]">
|
||||
{deleteError}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowDeleteConfirm(false)}
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
ref={deleteConfirmButtonRef}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
|
||||
@@ -694,27 +694,48 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : pane.error && !pane.reconnecting ? (
|
||||
) : pane.error && !pane.reconnecting && pane.files.length === 0 ? (
|
||||
<SftpErrorWithLogs
|
||||
error={pane.error}
|
||||
connectionLogs={pane.connectionLogs}
|
||||
onRetry={onRefresh}
|
||||
t={t}
|
||||
/>
|
||||
) : sortedDisplayFiles.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
|
||||
<Folder size={32} className="mb-2 opacity-50" />
|
||||
<span className="text-sm">{t("sftp.emptyDirectory")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
shouldVirtualize ? "relative" : "divide-y divide-border/30",
|
||||
<>
|
||||
{pane.error && !pane.reconnecting ? (
|
||||
<div className="sticky top-0 z-10 flex items-center gap-2 border-b border-destructive/30 bg-destructive/10 px-3 py-1.5 text-xs text-destructive">
|
||||
<span className="min-w-0 flex-1 break-words [overflow-wrap:anywhere]">{t(pane.error)}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 shrink-0 px-2 text-xs"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRefresh();
|
||||
}}
|
||||
>
|
||||
{t("sftp.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{sortedDisplayFiles.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
|
||||
<Folder size={32} className="mb-2 opacity-50" />
|
||||
<span className="text-sm">{t("sftp.emptyDirectory")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
shouldVirtualize ? "relative" : "divide-y divide-border/30",
|
||||
)}
|
||||
style={shouldVirtualize ? { height: totalHeight } : undefined}
|
||||
>
|
||||
{fileRows}
|
||||
</div>
|
||||
)}
|
||||
style={shouldVirtualize ? { height: totalHeight } : undefined}
|
||||
>
|
||||
{fileRows}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Drop overlay */}
|
||||
|
||||
@@ -292,6 +292,7 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
renameName,
|
||||
showDeleteConfirm,
|
||||
deleteTargets,
|
||||
deleteError,
|
||||
isCreating,
|
||||
isCreatingFile,
|
||||
isRenaming,
|
||||
@@ -736,6 +737,7 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
showDeleteConfirm={showDeleteConfirm}
|
||||
setShowDeleteConfirm={setShowDeleteConfirm}
|
||||
deleteTargets={deleteTargets}
|
||||
deleteError={deleteError}
|
||||
handleDelete={handleDelete}
|
||||
isDeleting={isDeleting}
|
||||
showHostPicker={showHostPicker}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import type { SftpPaneCallbacks } from "../SftpContext";
|
||||
import type { SftpPane } from "../../../application/state/sftp/types";
|
||||
import { isSessionError, unwrapSftpIpcError } from "../../../application/state/sftp/errors";
|
||||
import { getFileName, getParentPath } from "../../../application/state/sftp/utils";
|
||||
import { logger } from "../../../lib/logger";
|
||||
|
||||
@@ -62,6 +63,7 @@ interface UseSftpPaneDialogsResult {
|
||||
isCreatingFile: boolean;
|
||||
isRenaming: boolean;
|
||||
isDeleting: boolean;
|
||||
deleteError: string | null;
|
||||
setShowHostPicker: (open: boolean) => void;
|
||||
setHostSearch: (value: string) => void;
|
||||
setShowNewFolderDialog: (open: boolean) => void;
|
||||
@@ -110,8 +112,13 @@ export const useSftpPaneDialogs = ({
|
||||
const [showRenameDialog, setShowRenameDialog] = useState(false);
|
||||
const [renameTarget, setRenameTarget] = useState<string | null>(null);
|
||||
const [renameName, setRenameName] = useState("");
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||
const [showDeleteConfirm, setShowDeleteConfirmState] = useState(false);
|
||||
const [deleteTargets, setDeleteTargets] = useState<string[]>([]);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
const setShowDeleteConfirm = useCallback((open: boolean) => {
|
||||
if (!open) setDeleteError(null);
|
||||
setShowDeleteConfirmState(open);
|
||||
}, []);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [isCreatingFile, setIsCreatingFile] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
@@ -262,8 +269,8 @@ export const useSftpPaneDialogs = ({
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (deleteTargetsRef.current.length === 0 || isDeleting) return;
|
||||
setIsDeleting(true);
|
||||
setDeleteError(null);
|
||||
try {
|
||||
// deleteTargets are full paths; group by parent dir and use path-aware variant
|
||||
const byDir = new Map<string, string[]>();
|
||||
for (const fullPath of deleteTargetsRef.current) {
|
||||
const dir = getParentPath(fullPath);
|
||||
@@ -280,15 +287,22 @@ export const useSftpPaneDialogs = ({
|
||||
await onDeleteFilesAtPath(connectionId, dir, names);
|
||||
}
|
||||
onMutateSuccess?.(Array.from(byDir.keys()));
|
||||
setDeleteError(null);
|
||||
setShowDeleteConfirm(false);
|
||||
setDeleteTargets([]);
|
||||
onClearSelection();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to delete files", err);
|
||||
if (isSessionError(err)) {
|
||||
setDeleteTargets([]);
|
||||
setShowDeleteConfirm(false);
|
||||
return;
|
||||
}
|
||||
setDeleteError(`${t("sftp.error.deleteFailed")}: ${unwrapSftpIpcError(err)}`);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
}, [isDeleting, onDeleteFilesAtPath, onMutateSuccess, onClearSelection]);
|
||||
}, [isDeleting, onClearSelection, onDeleteFilesAtPath, onMutateSuccess, t]);
|
||||
|
||||
// entryPath is the full path; renameName is initialized to the basename
|
||||
const openRenameDialog = useCallback((entryPath: string) => {
|
||||
@@ -325,6 +339,7 @@ export const useSftpPaneDialogs = ({
|
||||
}, []);
|
||||
|
||||
const openDeleteConfirm = useCallback((names: string[]) => {
|
||||
setDeleteError(null);
|
||||
setDeleteTargets(names);
|
||||
setShowDeleteConfirm(true);
|
||||
}, []);
|
||||
@@ -344,6 +359,7 @@ export const useSftpPaneDialogs = ({
|
||||
renameName,
|
||||
showDeleteConfirm,
|
||||
deleteTargets,
|
||||
deleteError,
|
||||
isCreating,
|
||||
isCreatingFile,
|
||||
isRenaming,
|
||||
|
||||
@@ -45,3 +45,16 @@ test("locate-path uses focused session fallback when SFTP cannot reuse the termi
|
||||
/focusedSessionId=\{panelFocusedSessionId\}/,
|
||||
);
|
||||
});
|
||||
|
||||
test("single-channel SFTP opens a dedicated connection instead of the terminal channel", () => {
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/const dedicatedSftpLogin = sftpBannerDecision\?\.sessionId === activeSessionId\s*&& sftpBannerDecision\.singleChannel;/,
|
||||
);
|
||||
assert.doesNotMatch(sidePanelSource, /activeHost\.singleChannelSsh/);
|
||||
assert.match(sidePanelSource, /reuseTransport: false/);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/const reuseTerminalTransport = !dedicatedSftpLogin &&/,
|
||||
);
|
||||
});
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
shouldCancelSettledPendingSftpRebindWithoutTarget,
|
||||
shouldDeferPendingSftpUploadForOriginFocus,
|
||||
shouldDeferSftpSidePanelAutoConnectForSession,
|
||||
isSplitFocusSftpStillConnected,
|
||||
shouldKeepConnectedSftpOnSplitFocus,
|
||||
shouldRebindSftpSidePanelSourceSession,
|
||||
shouldResetSftpSidePanelSourceSession,
|
||||
shouldSkipSftpSidePanelAutoConnect,
|
||||
@@ -770,3 +772,42 @@ test("session change still requires rebind even when the endpoint key matches",
|
||||
tab,
|
||||
);
|
||||
});
|
||||
|
||||
test("split focus keeps an SFTP login that is already connected", () => {
|
||||
assert.equal(shouldKeepConnectedSftpOnSplitFocus({
|
||||
sessionChanged: true,
|
||||
previousSessionId: "pane-a",
|
||||
nextSessionId: "pane-b",
|
||||
endpointAlreadyConnected: true,
|
||||
}), true);
|
||||
assert.equal(shouldKeepConnectedSftpOnSplitFocus({
|
||||
sessionChanged: true,
|
||||
previousSessionId: "pane-b",
|
||||
nextSessionId: "pane-a",
|
||||
endpointAlreadyConnected: true,
|
||||
}), true);
|
||||
assert.equal(shouldKeepConnectedSftpOnSplitFocus({
|
||||
sessionChanged: true,
|
||||
previousSessionId: "pane-a",
|
||||
nextSessionId: "pane-a",
|
||||
endpointAlreadyConnected: true,
|
||||
}), false);
|
||||
assert.equal(shouldKeepConnectedSftpOnSplitFocus({
|
||||
sessionChanged: true,
|
||||
previousSessionId: "pane-a",
|
||||
nextSessionId: "pane-b",
|
||||
endpointAlreadyConnected: false,
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("split focus still counts a listing-in-progress SFTP session as connected", () => {
|
||||
const tab = remoteConnectedTab({ loading: true });
|
||||
assert.equal(
|
||||
isSplitFocusSftpStillConnected("host-key", "host-key", tab, true, "host-key"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
shouldSkipSftpSidePanelAutoConnect("host-key", "host-key", tab, true, "host-key"),
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -314,6 +314,38 @@ export function findReusableSftpSidePanelTab(
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* A directory listing in progress is still the same SSH login. Split focus
|
||||
* must not treat that as "disconnected" and start another handshake.
|
||||
*/
|
||||
export function isSplitFocusSftpStillConnected(
|
||||
connectionKey: string,
|
||||
connectedKey: string | null,
|
||||
activeTab: SftpSidePanelTabHealth | null | undefined,
|
||||
hasBackendSession: boolean,
|
||||
activeTabConnectionKey?: string | null,
|
||||
): boolean {
|
||||
if (connectedKey !== connectionKey) return false;
|
||||
if (!activeTab?.connection || activeTab.connection.isLocal) return false;
|
||||
if (activeTabConnectionKey !== connectionKey) return false;
|
||||
if (activeTab.connection.status !== "connected") return false;
|
||||
return hasBackendSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switching Split panes of the same host, including back to a pane that was
|
||||
* already used, must keep the SFTP login that is already up.
|
||||
*/
|
||||
export function shouldKeepConnectedSftpOnSplitFocus(params: {
|
||||
sessionChanged: boolean;
|
||||
previousSessionId?: string | null;
|
||||
nextSessionId?: string | null;
|
||||
endpointAlreadyConnected: boolean;
|
||||
}): boolean {
|
||||
if (!params.sessionChanged || !params.endpointAlreadyConnected) return false;
|
||||
return shouldResetSftpSidePanelSourceSession(params.previousSessionId, params.nextSessionId);
|
||||
}
|
||||
|
||||
/** True when the linked terminal SSH session id changed. */
|
||||
export function shouldResetSftpSidePanelSourceSession(
|
||||
previousSessionId: string | null | undefined,
|
||||
|
||||
@@ -16,12 +16,21 @@ test("SFTP side panel rebinds after same-tab SSH start-over", () => {
|
||||
sidePanelSource,
|
||||
/previousStatus:\s*lastSourceSessionStatusRef\.current/,
|
||||
);
|
||||
// Reuse only after SSH is connected; linked id may arrive while reconnecting.
|
||||
// Reuse the terminal transport only when SSH is connected, or when a strict
|
||||
// pending source id is already pinned. A dedicated single-channel login never
|
||||
// reuses that transport. A linked id may arrive while reconnecting.
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/activeSessionStatus === "connected" \? \(activeSessionId \?\? undefined\) : undefined/,
|
||||
/const reuseTerminalTransport = !dedicatedSftpLogin && \(\s*Boolean\(pendingStrictSourceSessionId\) \|\| activeSessionStatus === "connected"\s*\);/,
|
||||
);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/sourceSessionId: reuseTerminalTransport\s*\?\s*\(pendingStrictSourceSessionId \?\? \(activeSessionId \?\? undefined\)\)\s*: undefined/,
|
||||
);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/requireSourceSessionReuse: reuseTerminalTransport && Boolean\(pendingStrictSourceSessionId\)/,
|
||||
);
|
||||
assert.match(sidePanelSource, /requireSourceSessionReuse:\s*Boolean\(pendingStrictSourceSessionId\)/);
|
||||
assert.match(sidePanelSource, /resolveSftpSidePanelTrackedSourceStatusUpdate\(/);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
|
||||
@@ -4,6 +4,8 @@ import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useState
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { SYSTEM_MANAGER_TAB_LAYOUT_DEFAULTS } from '../../application/state/systemManagerTabLayout';
|
||||
import { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend';
|
||||
import { useTerminalBackend } from '../../application/state/useTerminalBackend';
|
||||
import { remoteSoftwareRequiresSingleChannel } from '../../domain/singleChannelSshBanner.shared.mjs';
|
||||
import { useToolbarItemLayout } from '../../application/state/useToolbarItemLayout';
|
||||
import type { TerminalSettings } from '../../domain/models';
|
||||
import type { Host } from '../../domain/models/connection';
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
buildSystemManagerTabs,
|
||||
shouldCollectServerStats,
|
||||
} from '../../domain/systemManager/systemTarget';
|
||||
|
||||
import { partitionToolbarItems } from '../../domain/toolbarItemLayout';
|
||||
import { STORAGE_KEY_SYSTEM_MANAGER_TAB_LAYOUT } from '../../infrastructure/config/storageKeys';
|
||||
import type { Snippet, TerminalSession } from '../../types';
|
||||
@@ -78,12 +81,41 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
|
||||
}: SystemManagerSidePanelProps) {
|
||||
const { t } = useI18n();
|
||||
const backend = useSystemManagerBackend();
|
||||
const terminalBackend = useTerminalBackend();
|
||||
const sessionId = session?.id ?? null;
|
||||
const isConnected = session?.status === 'connected';
|
||||
const [peerSingleChannel, setPeerSingleChannel] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId || !isConnected) {
|
||||
setPeerSingleChannel(false);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setPeerSingleChannel(null);
|
||||
void terminalBackend.getSessionRemoteInfo(sessionId).then((info) => {
|
||||
if (cancelled) return;
|
||||
setPeerSingleChannel(remoteSoftwareRequiresSingleChannel(info?.remoteSshVersion));
|
||||
}).catch(() => {
|
||||
if (!cancelled) setPeerSingleChannel(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isConnected, sessionId, terminalBackend]);
|
||||
|
||||
const systemManagerSupported = peerSingleChannel !== true;
|
||||
const capabilitiesEnabled = systemManagerSupported && peerSingleChannel !== null;
|
||||
|
||||
const capabilitiesTtlMs = terminalSettings.systemManagerProcessRefreshInterval * 1000;
|
||||
|
||||
const { capabilities, refreshCapabilities } = useSessionCapabilities(sessionId, isConnected, backend, isVisible, capabilitiesTtlMs);
|
||||
const { capabilities, refreshCapabilities } = useSessionCapabilities(
|
||||
sessionId,
|
||||
isConnected,
|
||||
backend,
|
||||
isVisible && capabilitiesEnabled,
|
||||
capabilitiesTtlMs,
|
||||
);
|
||||
|
||||
const availableTabs = useMemo(
|
||||
() => buildSystemManagerTabs(sessionHost, capabilities, session),
|
||||
@@ -356,6 +388,15 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
|
||||
);
|
||||
}
|
||||
|
||||
if (!systemManagerSupported) {
|
||||
return (
|
||||
<SystemPanelShell section="system-manager-panel">
|
||||
{workspaceHostHeader}
|
||||
<SystemPanelEmpty icon={Activity} message={t('systemManager.unsupportedRemote')} />
|
||||
</SystemPanelShell>
|
||||
);
|
||||
}
|
||||
|
||||
const tmuxReady = capabilities?.hasTmux === true;
|
||||
const dockerReady = capabilities?.hasDocker === true;
|
||||
const gpuReady = capabilities?.hasNvidiaSmi === true || capabilities?.hasNpuSmi === true;
|
||||
@@ -495,7 +536,7 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({
|
||||
<SystemOverviewTab
|
||||
sessionId={sessionId}
|
||||
isVisible={isVisible && resolvedTab === 'overview'}
|
||||
isSupportedOs={isStatsSupportedOs}
|
||||
isSupportedOs={isStatsSupportedOs && peerSingleChannel !== true}
|
||||
refreshIntervalSec={terminalSettings.serverStatsRefreshInterval}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -7,9 +7,12 @@ import { GripHorizontal, Pin, Plus, Radio, Search, X } from 'lucide-react';
|
||||
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useComposeBarHistory } from '../../application/state/useComposeBarHistory';
|
||||
import { canNavigateComposeBarHistory } from '../../domain/composeBarHistory';
|
||||
import { STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS } from '../../infrastructure/config/storageKeys';
|
||||
import { useStoredBoolean } from '../../application/state/useStoredBoolean';
|
||||
import { useComposeBarHeight } from '../../application/state/useComposeBarHeight';
|
||||
import { useComposeBarPinnedSnippets } from '../../application/state/useComposeBarPinnedSnippets';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
|
||||
import { resolveSnippetCommand } from '../SnippetExecutionProvider';
|
||||
import { Snippet } from '../../types';
|
||||
import { cn } from '../../lib/utils';
|
||||
@@ -292,6 +295,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
themeColors,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const { readClipboardText, writeClipboardText } = useClipboardBackend();
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const restoreDraft = useCallback((draft: string) => {
|
||||
if (textareaRef.current) textareaRef.current.value = draft;
|
||||
@@ -319,6 +323,88 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const theme = useMemo(() => buildTheme(themeColors), [themeColors]);
|
||||
|
||||
// Opt-in "broadcast without password protection" (#3488). Shared storage key
|
||||
// with the terminal runtime, which reads it to keep broadcasting during
|
||||
// password / interactive prompts while this switch is on.
|
||||
const [allowPasswordBroadcast, setAllowPasswordBroadcast] = useStoredBoolean(
|
||||
STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS,
|
||||
false,
|
||||
);
|
||||
const [broadcastMenuAnchor, setBroadcastMenuAnchor] = useState<{ x: number; y: number; inTextarea: boolean } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!broadcastMenuAnchor) return;
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
if (event.target instanceof Element && event.target.closest('[data-compose-broadcast-menu]')) return;
|
||||
setBroadcastMenuAnchor(null);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setBroadcastMenuAnchor(null);
|
||||
};
|
||||
window.addEventListener('pointerdown', handlePointerDown);
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', handlePointerDown);
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [broadcastMenuAnchor]);
|
||||
|
||||
const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => {
|
||||
if (!isBroadcastEnabled) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setBroadcastMenuAnchor({
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
inTextarea: event.target instanceof Element && Boolean(event.target.closest('textarea')),
|
||||
});
|
||||
}, [isBroadcastEnabled]);
|
||||
|
||||
const handleComposeMenuEdit = useCallback(async (action: 'cut' | 'copy' | 'paste' | 'selectAll') => {
|
||||
setBroadcastMenuAnchor(null);
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
textarea.focus();
|
||||
if (action === 'selectAll') {
|
||||
textarea.select();
|
||||
return;
|
||||
}
|
||||
const start = textarea.selectionStart;
|
||||
const end = textarea.selectionEnd;
|
||||
try {
|
||||
if (action === 'paste') {
|
||||
let text: string | undefined;
|
||||
try { text = await readClipboardText(); } catch { /* Use browser clipboard. */ }
|
||||
if (typeof text !== 'string') text = await navigator.clipboard.readText();
|
||||
if (!text) return;
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('insertText', false, text)) {
|
||||
textarea.setRangeText(text, start, end, 'end');
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
if (start === end) return;
|
||||
const selectedText = textarea.value.slice(start, end);
|
||||
let wroteToBridge = false;
|
||||
try { wroteToBridge = await writeClipboardText(selectedText); } catch { /* Use browser clipboard. */ }
|
||||
if (!wroteToBridge) {
|
||||
await navigator.clipboard.writeText(selectedText);
|
||||
}
|
||||
if (action === 'cut') {
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('delete')) {
|
||||
textarea.setRangeText('', start, end, 'end');
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
reset();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Compose bar clipboard action failed', error);
|
||||
}
|
||||
}, [readClipboardText, reset, writeClipboardText]);
|
||||
|
||||
const snippetsById = useMemo(
|
||||
() => mergeComposeBarSnippetMap(snippets),
|
||||
[snippets],
|
||||
@@ -459,6 +545,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
backgroundColor: theme.resolvedBg,
|
||||
borderTop: `1px solid ${theme.borderColor}`,
|
||||
}}
|
||||
onContextMenu={handleBroadcastContextMenu}
|
||||
>
|
||||
<div
|
||||
role="separator"
|
||||
@@ -561,6 +648,54 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{broadcastMenuAnchor && (
|
||||
<div
|
||||
data-compose-broadcast-menu
|
||||
className="fixed z-[120] min-w-[240px] rounded-md border py-1 shadow-lg"
|
||||
style={{
|
||||
// Clamp horizontally so the 240px-min menu stays on-screen even
|
||||
// when the compose bar is right-clicked near the right edge.
|
||||
left: Math.max(4, Math.min(broadcastMenuAnchor.x, window.innerWidth - 244)),
|
||||
top: Math.max(4, Math.min(broadcastMenuAnchor.y, window.innerHeight - (broadcastMenuAnchor.inTextarea ? 160 : 48))),
|
||||
backgroundColor: theme.resolvedBg,
|
||||
borderColor: theme.borderColor,
|
||||
color: theme.resolvedFg,
|
||||
}}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{broadcastMenuAnchor.inTextarea && (
|
||||
<>
|
||||
{(['cut', 'copy', 'paste', 'selectAll'] as const).map((action) => (
|
||||
<button
|
||||
key={action}
|
||||
type="button"
|
||||
className="flex w-full items-center px-2.5 py-1.5 text-left text-[11px] transition-colors duration-150 hover:bg-black/20"
|
||||
onClick={() => { void handleComposeMenuEdit(action); }}
|
||||
>
|
||||
{t(`terminal.menu.${action}`)}
|
||||
</button>
|
||||
))}
|
||||
<div className="my-1 border-t" style={{ borderColor: theme.borderColor }} />
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
data-compose-broadcast-toggle
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] transition-colors duration-150 hover:bg-black/20"
|
||||
onClick={() => {
|
||||
setAllowPasswordBroadcast((prev) => !prev);
|
||||
setBroadcastMenuAnchor(null);
|
||||
}}
|
||||
>
|
||||
<span className="w-3 shrink-0 text-center" aria-hidden="true">
|
||||
{allowPasswordBroadcast ? '✓' : ''}
|
||||
</span>
|
||||
{t('terminal.composeBar.broadcastAllowPassword')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1315,8 +1315,28 @@ function TerminalViewInner({ ctx, isPaneMagnified = false }: { ctx: TerminalView
|
||||
onSend={async (text) => {
|
||||
if (sessionRef.current) {
|
||||
const sensitive = isTerminalSensitiveInputActive(sessionId);
|
||||
const sent = await executeSnippetCommand(text, false);
|
||||
return sent && !sensitive && !isTerminalSensitiveInputActive(sessionId);
|
||||
// A bypassed fan-out (#3488) can deliver the payload into a
|
||||
// peer's sensitive prompt even when this source session is
|
||||
// non-sensitive (#3491): that payload is the peer's
|
||||
// password/MFA input, so the send must stay history-
|
||||
// ineligible, like the workspace compose path does.
|
||||
let anyRecipientSensitive = false;
|
||||
let broadcastRecipientIds: readonly string[] = [];
|
||||
const sent = await executeSnippetCommand(text, false, {
|
||||
onBroadcastDelivered: (sessionIds) => {
|
||||
broadcastRecipientIds = sessionIds;
|
||||
if (sessionIds.some((id) => isTerminalSensitiveInputActive(id))) {
|
||||
anyRecipientSensitive = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
// A lagging peer can reach its password prompt by delivery
|
||||
// time; re-check the recorded recipients after the send.
|
||||
if (broadcastRecipientIds.some((id) => isTerminalSensitiveInputActive(id))) {
|
||||
anyRecipientSensitive = true;
|
||||
}
|
||||
return sent && !sensitive && !anyRecipientSensitive
|
||||
&& !isTerminalSensitiveInputActive(sessionId);
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
|
||||
@@ -251,6 +251,8 @@ export async function getCompletions(
|
||||
sessionId?: string;
|
||||
/** Connection protocol (ssh, local, telnet, serial) */
|
||||
protocol?: string;
|
||||
/** Skip remote/local path listings that need extra SSH exec (single-channel bastions). */
|
||||
skipPathCompletion?: boolean;
|
||||
/** Current working directory (from OSC 7) */
|
||||
cwd?: string;
|
||||
cwdSource?: AutocompleteCwdSource;
|
||||
@@ -339,7 +341,7 @@ export async function getCompletions(
|
||||
}
|
||||
}
|
||||
|
||||
const canQueryPaths = options.protocol === "local" || options.sessionId !== undefined;
|
||||
const canQueryPaths = !options.skipPathCompletion && (options.protocol === "local" || options.sessionId !== undefined);
|
||||
|
||||
const pathEntries = canQueryPaths && pathCheck.shouldComplete
|
||||
? await getPathSuggestionsWithinBudget(
|
||||
|
||||
@@ -16,11 +16,14 @@ type TerminalAutocompleteSettingFields = {
|
||||
export function resolveTerminalAutocompleteSettings(input: {
|
||||
protocol?: string;
|
||||
terminalSettings?: TerminalAutocompleteSettingFields;
|
||||
/** Vendor CLI / network-device session: skip live-preview PTY rewrites (#1193). */
|
||||
/** Vendor CLI / network device: skip live-preview PTY rewrites. */
|
||||
isNetworkDevice?: boolean;
|
||||
/** One-channel bastion: Ctrl-U line replacement kills the session (#1193). */
|
||||
restrictPtyRewrites?: boolean;
|
||||
systemUnknown?: boolean;
|
||||
}): Partial<AutocompleteSettings> | undefined {
|
||||
const { protocol, terminalSettings, isNetworkDevice, systemUnknown } = input;
|
||||
const { protocol, terminalSettings, isNetworkDevice, restrictPtyRewrites, systemUnknown } = input;
|
||||
const blockLivePreview = isNetworkDevice === true || restrictPtyRewrites === true;
|
||||
|
||||
if (protocol === "serial" || systemUnknown) {
|
||||
return {
|
||||
@@ -38,15 +41,19 @@ export function resolveTerminalAutocompleteSettings(input: {
|
||||
}
|
||||
|
||||
if (!terminalSettings) {
|
||||
return isNetworkDevice ? { livePreview: false } : undefined;
|
||||
if (!blockLivePreview && restrictPtyRewrites !== true) return undefined;
|
||||
return {
|
||||
...(blockLivePreview ? { livePreview: false } : {}),
|
||||
...(restrictPtyRewrites ? { allowLineReplacement: false } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: terminalSettings.autocompleteEnabled ?? true,
|
||||
showGhostText: terminalSettings.autocompleteGhostText ?? true,
|
||||
showPopupMenu: terminalSettings.autocompletePopupMenu ?? true,
|
||||
livePreview: shouldWriteAutocompleteLivePreview(true, isNetworkDevice),
|
||||
allowLineReplacement: true,
|
||||
livePreview: shouldWriteAutocompleteLivePreview(true, blockLivePreview),
|
||||
allowLineReplacement: restrictPtyRewrites !== true,
|
||||
debounceMs: terminalSettings.autocompleteDebounceMs ?? 100,
|
||||
minChars: terminalSettings.autocompleteMinChars ?? 1,
|
||||
maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 50,
|
||||
|
||||
@@ -554,6 +554,7 @@ export function useTerminalAutocomplete(
|
||||
|
||||
/** Fetch directory listing via IPC. */
|
||||
const fetchDirEntries = useCallback(async (dirPath: string): Promise<SubDirEntry[]> => {
|
||||
if (isNetworkDeviceRef.current) return [];
|
||||
return listDirectoryEntries(dirPath, {
|
||||
sessionId: sessionIdRef.current,
|
||||
protocol: protocolRef.current,
|
||||
@@ -1159,6 +1160,7 @@ export function useTerminalAutocomplete(
|
||||
historyScope: settingsRef.current.historyScope,
|
||||
sessionId: sessionIdRef.current,
|
||||
protocol: protocolRef.current,
|
||||
skipPathCompletion: isNetworkDeviceRef.current,
|
||||
cwd: cwdResolution.cwd,
|
||||
cwdSource: cwdResolution.source,
|
||||
snippets: snippetsRef.current,
|
||||
|
||||
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user