Compare commits

..
Author SHA1 Message Date
bincxz 86f32f7c2c fix: preserve prompt guardrails after dynamic context 2026-09-29 01:40:10 +08:00
netcatty-bot 69eabe8296 fix(#3545): automated AI fix 2026-09-28 17:26:21 +00:00
289 changed files with 631 additions and 13584 deletions

No files matched your search

-23
View File
@@ -70,26 +70,3 @@ 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
+2 -6
View File
@@ -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, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from '../../domain/host';
import { getEffectiveHostDistro, classifyDistroId, shouldProbeSessionCwd } from '../../domain/host';
import { getAvailablePaneMagnificationController } from '../../domain/paneMagnification';
import { sanitizeHostIconFields } from '../../domain/hostIcon';
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
@@ -535,11 +535,7 @@ 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,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(host),
});
allowSshProbe = shouldProbeSessionCwd({ isNetworkDevice: false, remoteSshVersion: info?.remoteSshVersion });
} catch {
allowSshProbe = false;
}
@@ -1,21 +0,0 @@
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/);
});
+13 -30
View File
@@ -98,11 +98,6 @@ 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';
@@ -265,7 +260,6 @@ export function AppSideEffects() {
copyWorkspace,
createSessionFromCloneSource,
getSessionRestoreCwd,
renameSessionInline,
} = sessionState;
// Presentation-field thrash stays off Host bags (Hosts use retainStable);
@@ -1404,14 +1398,6 @@ 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
@@ -1479,16 +1465,15 @@ export function AppSideEffects() {
// deep links until unlock so saved-credential connects cannot start behind
// the lock screen.
const pendingDeepLinksWhileLockedRef = useRef<Array<
| { kind: 'ssh'; payload: DeepLinkPayload }
| { kind: 'telnet'; payload: DeepLinkPayload }
| { kind: 'ssh'; payload: { url?: string } }
| { kind: 'telnet'; payload: { url?: string } }
| { kind: 'jms'; payload: { url?: string } }
| { kind: 'open-terminal-path'; payload: { path?: string } }
>>([]);
const _processSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
const _processSshDeepLink = useEffectEvent((payload: { url?: string }) => {
startupLaunchIntentReceivedRef.current = true;
const rawUrl = payload?.url || '';
const tabName = payload?.tabName?.trim();
const target = parseSshDeepLink(rawUrl);
if (!target) {
toast.warning(t('deepLink.ssh.invalid'));
@@ -1517,26 +1502,25 @@ export function AppSideEffects() {
? buildSshDeepLinkEphemeralHostFromSaved(matchedEffectiveHost, target, draftOptions)
: buildSshDeepLinkEphemeralHost(target, draftOptions);
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHostWithTabName(ephemeralHost, tabName);
handleConnectToHost(ephemeralHost);
return;
}
if (matchedEffectiveHost) {
const originalHost = hosts.find((host) => host.id === matchedEffectiveHost.id) ?? matchedEffectiveHost;
handleConnectToHostWithTabName(buildSshDeepLinkConnectionHost(originalHost), tabName);
handleConnectToHost(buildSshDeepLinkConnectionHost(originalHost));
return;
}
const hostDraft = buildSshDeepLinkHostDraft(target, {
setDeepLinkHostDraft(buildSshDeepLinkHostDraft(target, {
id: crypto.randomUUID(),
now: Date.now(),
});
setDeepLinkHostDraft(tabName ? { ...hostDraft, label: tabName } : hostDraft);
}));
setNavigateToSection('hosts');
setActiveTabId('vault');
});
const _handleSshDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
const _handleSshDeepLink = useEffectEvent((payload: { url?: string }) => {
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
pendingDeepLinksWhileLockedRef.current.push({ kind: 'ssh', payload: payload || {} });
return;
@@ -1553,10 +1537,9 @@ export function AppSideEffects() {
});
}, [isPeerSessionWindow]);
const _processTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
const _processTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
startupLaunchIntentReceivedRef.current = true;
const rawUrl = payload?.url || '';
const tabName = payload?.tabName?.trim();
const target = parseTelnetDeepLink(rawUrl);
if (!target) {
toast.warning(t('deepLink.telnet.invalid'));
@@ -1577,10 +1560,10 @@ export function AppSideEffects() {
now: Date.now(),
});
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHostWithTabName(ephemeralHost, tabName);
handleConnectToHost(ephemeralHost);
return;
}
handleConnectToHostWithTabName(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost), tabName);
handleConnectToHost(buildTelnetDeepLinkConnectionHost(matchedEffectiveHost));
return;
}
@@ -1589,10 +1572,10 @@ export function AppSideEffects() {
now: Date.now(),
});
setEphemeralHosts((prev) => [...prev, ephemeralHost]);
handleConnectToHostWithTabName(ephemeralHost, tabName);
handleConnectToHost(ephemeralHost);
});
const _handleTelnetDeepLink = useEffectEvent((payload: DeepLinkPayload) => {
const _handleTelnetDeepLink = useEffectEvent((payload: { url?: string }) => {
if (shouldDeferExternalActionWhileAppLocked({ locked: appLockLocked })) {
pendingDeepLinksWhileLockedRef.current.push({ kind: 'telnet', payload: payload || {} });
return;
-19
View File
@@ -288,18 +288,6 @@ 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.",
@@ -336,13 +324,6 @@ 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',
+3 -8
View File
@@ -312,11 +312,8 @@ 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': '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.closeToTray': 'Close to System Tray',
'settings.globalHotkey.closeToTrayDesc': 'When enabled, closing the window will minimize to the system tray instead of quitting.',
'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).',
@@ -541,7 +538,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. On Windows, the notification area icon uses the same style. 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. 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',
@@ -617,8 +614,6 @@ 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',
-3
View File
@@ -27,9 +27,6 @@ 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,7 +31,6 @@ 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…',
-2
View File
@@ -61,7 +61,6 @@ 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...',
@@ -135,7 +134,6 @@ 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',
-1
View File
@@ -407,7 +407,6 @@ export const enVaultMessages: Messages = {
'sftp.transferCenter.prioritize': 'Transfer next',
'sftp.transferCenter.pauseAll': 'Pause all',
'sftp.transferCenter.resumeAll': 'Resume all',
'sftp.transferCenter.cancelAll': 'Cancel all',
'sftp.transferCenter.empty': 'No transfers in this category',
'sftp.transferCenter.showBackground': 'Show {count} background transfers',
'sftp.transferCenter.hideBackground': 'Hide background transfers',
-19
View File
@@ -279,18 +279,6 @@ 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.",
@@ -327,13 +315,6 @@ 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',
+3 -8
View File
@@ -227,11 +227,8 @@ 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': '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.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.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).',
@@ -456,7 +453,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. 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.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.original': 'Original',
'settings.appearance.appIcon.bright': 'Brillante',
'settings.appearance.appIcon.dark': 'Oscuro',
@@ -532,8 +529,6 @@ 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',
-3
View File
@@ -27,9 +27,6 @@ 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,7 +31,6 @@ 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…',
-2
View File
@@ -61,7 +61,6 @@ 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...',
@@ -135,7 +134,6 @@ 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',
-1
View File
@@ -407,7 +407,6 @@ export const esVaultMessages: Messages = {
'sftp.transferCenter.prioritize': 'Transferir a continuación',
'sftp.transferCenter.pauseAll': 'Pausar todas',
'sftp.transferCenter.resumeAll': 'Reanudar todas',
'sftp.transferCenter.cancelAll': 'Cancelar todas',
'sftp.transferCenter.empty': 'No hay transferencias en esta categoría',
'sftp.transferCenter.showBackground': 'Mostrar {count} transferencias en segundo plano',
'sftp.transferCenter.hideBackground': 'Ocultar transferencias en segundo plano',
-7
View File
@@ -283,13 +283,6 @@ 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': 'Режим доступности',
+3 -8
View File
@@ -296,11 +296,8 @@ export const ruCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': 'Нажмите сочетание клавиш, чтобы задать глобальную горячую клавишу для показа или скрытия окна.',
'settings.globalHotkey.notSet': 'Не задано',
'settings.globalHotkey.reset': 'Сбросить по умолчанию',
'settings.globalHotkey.closeToTray': 'Оставлять приложение в фоне при закрытии окна',
'settings.globalHotkey.closeToTrayDesc': 'При закрытии окно скрывается, а приложение продолжает работать. Отображение значка в трее настраивается отдельно.',
'settings.globalHotkey.showTrayIcon': 'Показывать значок в системном трее',
'settings.globalHotkey.showTrayIconDesc': 'Если отключено, значок в трее скрыт, но приложение продолжает работать в фоне.',
'settings.globalHotkey.showTrayIconHiddenHint': 'Значок в трее скрыт. Запустите приложение снова или используйте глобальную горячую клавишу, чтобы вернуть окно, затем снова включите этот параметр, чтобы восстановить значок.',
'settings.globalHotkey.closeToTray': 'Сворачивать в системный трей',
'settings.globalHotkey.closeToTrayDesc': 'Если включено, при закрытии окно будет сворачиваться в системный трей вместо выхода из приложения.',
'settings.globalHotkey.enabled': 'Включить глобальную горячую клавишу',
'settings.globalHotkey.enabledDesc': 'Регистрировать системные сочетания клавиш. Когда отключено, все глобальные горячие клавиши снимаются с регистрации.',
'settings.globalHotkey.hint': 'Глобальная горячая клавиша работает на уровне всей системы и позволяет быстро показывать или скрывать окно (терминал в стиле Quake).',
@@ -510,7 +507,7 @@ export const ruCoreMessages: Messages = {
'settings.appearance.windowOpacity': 'Прозрачность окна',
'settings.appearance.windowOpacity.desc': 'Настройте прозрачность всего окна приложения. При низких значениях текст терминала тоже бледнеет. В некоторых средах Linux это может не поддерживаться.',
'settings.appearance.appIcon': 'Значок приложения',
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. В Windows значок области уведомлений использует тот же стиль. Применяется во время работы; значок установленного пакета не меняется.',
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. Применяется во время работы; значок установленного пакета не меняется.',
'settings.appearance.appIcon.original': 'Оригинал',
'settings.appearance.appIcon.bright': 'Яркий',
'settings.appearance.appIcon.dark': 'Тёмный',
@@ -585,8 +582,6 @@ 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': 'Тип эмуляции терминала',
-3
View File
@@ -27,9 +27,6 @@ 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,7 +31,6 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
'systemManager.errors.sshChannelUnavailable': 'Сервер отказался открыть новый канал выполнения. Повторите попытку позже или переподключите этот хост.',
'systemManager.unsupportedRemote': 'Этот хост не разрешает дополнительные SSH exec-каналы, поэтому системная панель недоступна. Открытие панели больше не разрывает терминал.',
'systemManager.overview.empty': 'Данных обзора пока нет.',
'systemManager.overview.loading': 'Загрузка обзора системы…',
-2
View File
@@ -82,7 +82,6 @@ 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': 'Поиск сниппетов...',
@@ -156,7 +155,6 @@ 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': 'Загрузить изображение из буфера',
-1
View File
@@ -445,7 +445,6 @@ export const ruVaultMessages: Messages = {
'sftp.transferCenter.prioritize': 'Передать следующей',
'sftp.transferCenter.pauseAll': 'Приостановить все',
'sftp.transferCenter.resumeAll': 'Продолжить все',
'sftp.transferCenter.cancelAll': 'Отменить все',
'sftp.transferCenter.empty': 'В этой категории нет передач',
'sftp.transferCenter.showBackground': 'Показать фоновые: {count}',
'sftp.transferCenter.hideBackground': 'Скрыть фоновые',
-19
View File
@@ -288,18 +288,6 @@ 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 选择。',
@@ -336,13 +324,6 @@ 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': '可用模式',
+3 -7
View File
@@ -316,11 +316,8 @@ export const zhCNCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': '按下组合键以设置显示/隐藏窗口的全局快捷键。',
'settings.globalHotkey.notSet': '未设置',
'settings.globalHotkey.reset': '恢复默认',
'settings.globalHotkey.closeToTray': '关闭窗口后在后台运行',
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口会隐藏窗口,应用继续在后台运行。托盘图标可单独开关。',
'settings.globalHotkey.showTrayIcon': '显示系统托盘图标',
'settings.globalHotkey.showTrayIconDesc': '关闭后,托盘图标将被隐藏,但应用仍会在后台正常运行。',
'settings.globalHotkey.showTrayIconHiddenHint': '托盘图标已隐藏。再次启动应用或使用全局显示/隐藏快捷键即可找回窗口,然后重新打开此设置即可恢复图标。',
'settings.globalHotkey.closeToTray': '关闭时最小化到托盘',
'settings.globalHotkey.closeToTrayDesc': '启用后,关闭窗口将最小化到系统托盘而不是退出程序。',
'settings.globalHotkey.enabled': '启用全局快捷键',
'settings.globalHotkey.enabledDesc': '注册系统级键盘快捷键。禁用后将取消所有全局快捷键注册。',
'settings.globalHotkey.hint': '全局快捷键在系统范围内工作,可快速显示或隐藏窗口(下拉式终端风格)。',
@@ -545,7 +542,7 @@ export const zhCNCoreMessages: Messages = {
'settings.appearance.windowOpacity': '窗口透明度',
'settings.appearance.windowOpacity.desc': '调节整个应用窗口的透明度,方便叠在其他内容上方。较低时终端文字也会变淡;部分 Linux 桌面环境可能不支持。',
'settings.appearance.appIcon': '应用图标',
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。Windows 通知区域图标会使用同一套风格。运行时生效,安装包内的图标不会改变。',
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。运行时生效,安装包内的图标不会改变。',
'settings.appearance.appIcon.original': '原始',
'settings.appearance.appIcon.bright': '明亮',
'settings.appearance.appIcon.dark': '深色',
@@ -1051,7 +1048,6 @@ export const zhCNCoreMessages: Messages = {
'sftp.transferCenter.prioritize': '优先传输',
'sftp.transferCenter.pauseAll': '全部暂停',
'sftp.transferCenter.resumeAll': '全部继续',
'sftp.transferCenter.cancelAll': '全部取消',
'sftp.transferCenter.empty': '当前分类没有传输任务',
'sftp.transferCenter.showBackground': '显示 {count} 个后台任务',
'sftp.transferCenter.hideBackground': '隐藏后台任务',
@@ -27,9 +27,6 @@ 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,7 +31,6 @@ export const zhCnSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': '加载监听端口失败',
'systemManager.errors.loadServices': '加载 systemd 服务失败',
'systemManager.errors.sshChannelUnavailable': '服务器拒绝打开新的执行通道。请稍后重试,或重新连接当前主机。',
'systemManager.unsupportedRemote': '该主机不允许额外的 SSH 执行通道,系统面板不可用。打开此面板不会再断开当前终端。',
'systemManager.overview.empty': '暂无系统概览数据。',
'systemManager.overview.loading': '正在加载系统概览…',
@@ -278,8 +278,6 @@ 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': '终端仿真类型',
-2
View File
@@ -466,7 +466,6 @@ 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': '搜索代码片段...',
@@ -538,7 +537,6 @@ 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': '添加到对话',
-19
View File
@@ -279,18 +279,6 @@ 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 選擇。',
@@ -326,13 +314,6 @@ 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': '可用模式',
+3 -7
View File
@@ -318,11 +318,8 @@ export const zhTWCoreMessages: Messages = {
'settings.globalHotkey.toggleWindowDesc': '按下組合鍵以設定顯示/隱藏視窗的全域快速鍵。',
'settings.globalHotkey.notSet': '未設定',
'settings.globalHotkey.reset': '恢復預設',
'settings.globalHotkey.closeToTray': '關閉視窗後在背景執行',
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗會隱藏視窗,應用程式繼續在背景執行。系統匣圖示可另外開關。',
'settings.globalHotkey.showTrayIcon': '顯示系統匣圖示',
'settings.globalHotkey.showTrayIconDesc': '關閉後,系統匣圖示將被隱藏,但應用程式仍會在背景正常執行。',
'settings.globalHotkey.showTrayIconHiddenHint': '系統匣圖示已隱藏。再次啟動應用程式或使用全域顯示/隱藏快捷鍵即可找回視窗,然後重新開啟此設定即可恢復圖示。',
'settings.globalHotkey.closeToTray': '關閉時最小化到系統匣',
'settings.globalHotkey.closeToTrayDesc': '啟用後,關閉視窗將最小化到系統匣而不是結束程式。',
'settings.globalHotkey.enabled': '啟用全域快速鍵',
'settings.globalHotkey.enabledDesc': '註冊系統級鍵盤快速鍵。停用後將取消所有全域快速鍵註冊。',
'settings.globalHotkey.hint': '全域快速鍵在系統範圍內工作,可快速顯示或隱藏視窗(下拉式終端風格)。',
@@ -547,7 +544,7 @@ export const zhTWCoreMessages: Messages = {
'settings.appearance.windowOpacity': '視窗透明度',
'settings.appearance.windowOpacity.desc': '調節整個應用程式視窗的透明度,方便疊在其他內容上方。較低時終端文字也會變淡;部分 Linux 桌面環境可能不支援。',
'settings.appearance.appIcon': '應用程式圖示',
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。Windows 通知區域圖示會使用同一套風格。執行時生效,安裝檔內的圖示不會改變。',
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。執行時生效,安裝檔內的圖示不會改變。',
'settings.appearance.appIcon.original': '原始',
'settings.appearance.appIcon.bright': '明亮',
'settings.appearance.appIcon.dark': '深色',
@@ -1053,7 +1050,6 @@ export const zhTWCoreMessages: Messages = {
'sftp.transferCenter.prioritize': '優先傳輸',
'sftp.transferCenter.pauseAll': '全部暫停',
'sftp.transferCenter.resumeAll': '全部繼續',
'sftp.transferCenter.cancelAll': '全部取消',
'sftp.transferCenter.empty': '目前分類沒有傳輸工作',
'sftp.transferCenter.showBackground': '顯示 {count} 個背景工作',
'sftp.transferCenter.hideBackground': '隱藏背景工作',
@@ -27,9 +27,6 @@ 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,7 +31,6 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.errors.loadPorts': '載入監聽連接埠失敗',
'systemManager.errors.loadServices': '載入 systemd 服務失敗',
'systemManager.errors.sshChannelUnavailable': '伺服器拒絕開啟新的執行通道。請稍後重試,或重新連線目前主機。',
'systemManager.unsupportedRemote': '此主機不允許額外的 SSH 執行通道,系統面板無法使用。開啟此面板不會再中斷目前終端。',
'systemManager.overview.empty': '暫無系統概覽資料。',
'systemManager.overview.loading': '正在載入系統概覽…',
@@ -278,8 +278,6 @@ 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': '終端模擬型別',
-2
View File
@@ -466,7 +466,6 @@ 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': '搜尋程式碼片段...',
@@ -538,7 +537,6 @@ 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': '新增到對話',
@@ -1,7 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
runAutomationScript,
runConnectScriptsSequential,
selectScriptOverlayRun,
setScriptRuns,
@@ -9,7 +8,6 @@ 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 () => {
@@ -248,127 +246,3 @@ 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,10 +95,8 @@ 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 = params.initiatedBy === 'user' ? 'auto' : readPermissionMode();
const permissionMode = readPermissionMode();
if (permissionMode === 'observer' && scriptContainsWriteOperations(params.snippet.command)) {
throw new Error('Observer mode blocks scripts that write to the terminal.');
}
+1 -13
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isMissingStatError, unwrapSftpIpcError } from "./errors";
import { isMissingStatError } 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,15 +64,3 @@ 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");
});
-9
View File
@@ -18,13 +18,4 @@ 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";
@@ -520,24 +520,3 @@ test("folder resume releases a completed child compacted while pause was drainin
assert.equal(resumed.handled, true);
assert.equal(isTransferPauseLatched(child.id), false, "the worker still waits on this child even though its history row is gone");
});
test("late pause acknowledgement cannot restart a cancelling stream before settlement", async (t) => {
const { markTransferCancelledTree, resetTransferCancelLatchesForTests } = await import("./transferCancelLatch");
const { bumpTransferControlEpoch } = await import("./transferControlEpoch");
const { releaseTransferPauseTree } = await import("./transferPauseLatch");
t.after(() => { resetTransferCancelLatchesForTests(); resetTransferPauseLatchesForTests(); });
let finishPause!: (value: { success: boolean }) => void;
let resumes = 0;
const { host } = createHost([makeTask("cancel-during-pause")], () => ({
pauseTransfer: () => new Promise((resolve) => { finishPause = resolve; }),
resumeTransfer: async () => { resumes += 1; return { success: true }; },
}));
const pause = softPauseTransfer(host, "cancel-during-pause");
markTransferCancelledTree("cancel-during-pause");
bumpTransferControlEpoch("cancel-during-pause");
releaseTransferPauseTree("cancel-during-pause");
finishPause({ success: true });
await pause;
assert.equal(resumes, 0);
});
@@ -24,7 +24,6 @@ import {
latchTransferPauseTree,
releaseTransferPauseTree,
} from "./transferPauseLatch";
import { isTransferOrRootCancelled } from "./transferCancelLatch";
import { isTransferWalkInFlight } from "./transferWalkRegistry";
export type TransferControlBridge = {
@@ -73,7 +72,7 @@ export function reconcileSupersededControls(
requestedAction: "pause" | "resume",
controlTaskId = taskId,
): void {
if (!isTransferControlEpochCurrent(controlTaskId, epoch) || isTransferOrRootCancelled(taskId)) return;
if (!isTransferControlEpochCurrent(controlTaskId, epoch)) return;
const task = host.getTasks().find((candidate) => candidate.id === taskId);
if (!task || ["completed", "cancelled", "failed"].includes(task.status)) return;
const apply = (id: string, descendants: string[], action: "pause" | "resume" | "cancel") => {
@@ -235,7 +234,7 @@ export async function softPauseTransfer(
const undoObsoletePause = async (id: string) => {
const live = host.getTasks().find((candidate) => candidate.id === taskId);
if (!live || ["completed", "cancelled", "failed", "interrupted"].includes(live.status)) return;
if (isTransferOrRootPauseLatched(taskId, id) || isTransferOrRootCancelled(taskId, id)) return;
if (isTransferOrRootPauseLatched(taskId, id)) return;
try { await bridge!.resumeTransfer?.(id); } catch { /* best-effort */ }
};
const pauseOne = async (id: string) => {
@@ -1,46 +0,0 @@
import type { TransferTask } from "../../../domain/models";
import { isValidDirectoryResumeCheckpoint } from "../../../domain/sftpDirectoryCheckpoint";
/** Apply only after backend cancellation AND the old walk have settled. */
export function settleCancelledTransferTree(
tasks: readonly TransferTask[],
rootId: string,
cancelledIds: ReadonlySet<string>,
failedIds: ReadonlySet<string>,
retainedTasks: readonly TransferTask[] = [],
): TransferTask[] {
const existingTasks = new Map(tasks.map((task) => [task.id, task]));
// Use observed terminal outcomes rather than stale pre-cancel snapshots.
// Missing completed children already covered by the parent stay compacted;
// cancelled/failed exceptions still need their rows for the recovery walk.
const settledTasks = failedIds.size > 0
? [...tasks, ...retainedTasks.filter((task) => {
if (existingTasks.has(task.id)) return false;
const checkpoint = task.parentTaskId
? existingTasks.get(task.parentTaskId)?.directoryResumeCheckpoint
: undefined;
return !(task.status === "completed"
&& isValidDirectoryResumeCheckpoint(checkpoint)
&& Number.isSafeInteger(task.directoryEntryIndex)
&& (task.directoryEntryIndex ?? -1) >= 0
&& task.directoryEntryIndex! < checkpoint.coveredEntries);
})]
: tasks;
return settledTasks.map((task) => {
// Natural completion/failure wins a race with Cancel. Rows cancelled by
// this attempt can be re-admitted only when the whole tree needs recovery.
if (!cancelledIds.has(task.id) || task.status === "completed" || task.status === "failed") return task;
const failed = failedIds.has(task.id) || (task.id === rootId && failedIds.size > 0);
const recoverable = failedIds.size > 0;
return {
...task,
status: failed ? "attention" : recoverable ? "interrupted" : "cancelled",
error: failed ? "Could not cancel transfer. Please try again." : undefined,
reconnectRequired: recoverable,
endTime: recoverable ? undefined : Date.now(),
speed: 0,
phase: undefined,
conflict: undefined,
};
});
}
@@ -1,375 +0,0 @@
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import type { TransferTask } from "../../../domain/models";
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
import { createSftpTransferCenterStore } from "../sftpTransferCenterStore";
import { globalSftpTransferScheduler } from "./globalTransferScheduler";
import { isTransferOrRootCancelled, resetTransferCancelLatchesForTests } from "./transferCancelLatch";
import { createTransferRuntime, resetTransferRuntimeRunsForTests } from "./transferRuntime";
import { resetTransferWalkRegistryForTests } from "./transferWalkRegistry";
const task = (id: string, extra: Partial<TransferTask> = {}): TransferTask => ({
id, fileName: id, sourcePath: `/source/${id}`, targetPath: `/target/${id}`,
sourceConnectionId: "local", targetConnectionId: "fixture", direction: "upload",
status: "transferring", totalBytes: 8, transferredBytes: 0, speed: 0,
startTime: 1, isDirectory: false, resumable: true, ...extra,
});
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test("failed cancellation waits for the old walk, then Resume restores scheduler-rejected file bytes", async (t) => {
const root = await mkdtemp(join(tmpdir(), "netcatty-cancel-"));
const originalGet = netcattyBridge.get;
t.after(async () => {
netcattyBridge.get = originalGet;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
resetTransferRuntimeRunsForTests();
await rm(root, { recursive: true, force: true });
});
const store = createSftpTransferCenterStore();
const runtime = createTransferRuntime(store);
const ids = ["active", "queued-1", "queued-2"];
const expected = ids.map((id) => Buffer.from(`bytes-of-${id}`));
const children = ids.map((id) => task(id, { parentTaskId: "folder", targetPath: join(root, id) }));
store.publishOwner("closed-panel", [task("folder", { isDirectory: true, targetHostId: "fixture-host" }), ...children]);
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
t.after(() => release());
let softResumeCalls = 0;
let pauseCalls = 0;
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => ({ success: id !== "active" }),
pauseTransfer: async () => { pauseCalls += 1; return { success: true }; },
clearPendingTransferCancel: async () => undefined,
resumeTransfer: async () => { softResumeCalls += 1; return { success: true }; },
} as unknown as ReturnType<typeof netcattyBridge.get>);
let starts = 0;
const walking = runtime.runWalk("folder", async () => {
await Promise.all(children.map((child, index) => globalSftpTransferScheduler.run(
"closed-panel", child.id, ["cancel-fixture"], () => 1, async () => {
starts += 1;
await held;
await writeFile(child.targetPath, expected[index]);
store.patchTask(child.id, { status: "completed" });
},
).catch(() => store.patchTask(child.id, { status: "cancelled" }))));
store.patchTask("folder", { status: "cancelled" });
});
await tick();
assert.equal(starts, 1);
let cancelSettled = false;
const cancelling = store.cancel("folder").then(() => { cancelSettled = true; });
const resuming = store.resume("folder");
await tick();
assert.equal(cancelSettled, true, "failed cancel must return promptly so the user can retry");
assert.equal(store.getTask("folder")?.status, "attention");
assert.equal(isTransferOrRootCancelled("folder"), true);
assert.equal(softResumeCalls, 0, "must not unlatch the old walk");
await store.pause("folder");
assert.equal(pauseCalls, 0, "a late row-level Pause must not park the cancelling walk");
let freshWalks = 0;
store.setDedicatedResumeHandler(async () => {
freshWalks += 1;
assert.equal(runtime.isWalkInFlight("folder"), false);
for (let index = 0; index < children.length; index += 1) {
const child = children[index];
if (store.getTask(child.id)?.status === "completed") continue;
assert.equal(store.admitTaskRun(child), "ready");
await writeFile(child.targetPath, expected[index]);
store.patchTask(child.id, { status: "completed" });
}
return { success: true };
});
release();
await Promise.all([walking, cancelling, resuming]);
assert.equal(freshWalks, 1);
assert.equal(starts, 1, "cancelled queue callbacks cannot silently count as transferred files");
assert.equal(store.getTask("folder")?.status, "completed");
for (let index = 0; index < children.length; index += 1) {
assert.deepEqual(await readFile(children[index].targetPath), expected[index]);
}
});
test("failed ownerless compression cancellation retries the same backend", async (t) => {
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; resetTransferCancelLatchesForTests(); });
const store = createSftpTransferCenterStore();
const calls: string[] = [];
netcattyBridge.get = () => ({
cancelCompressedUpload: async (id: string) => {
calls.push(`compressed:${id}`);
return { success: calls.length > 1 };
},
cancelTransfer: async (id: string) => { calls.push(`stream:${id}`); return { success: true }; },
} as unknown as ReturnType<typeof netcattyBridge.get>);
store.publishOwner("closed-panel", [task("archive", { controlKind: "compressed-upload" })]);
await store.cancel("archive");
assert.equal(store.getTask("archive")?.status, "attention");
await store.cancel("archive");
assert.deepEqual(calls, ["compressed:archive", "compressed:archive"]);
assert.equal(store.getTask("archive")?.status, "cancelled");
});
test("late completion survives cancellation, while an unrelated paused batch peer stays paused", async (t) => {
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; resetTransferCancelLatchesForTests(); });
const store = createSftpTransferCenterStore();
const calls: string[] = [];
store.publishOwner("gone", [task("selected", { batchId: "batch" }), task("peer", { batchId: "batch", status: "paused" })]);
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => {
calls.push(id);
store.patchTask(id, { status: "completed" });
return { success: true };
},
} as unknown as ReturnType<typeof netcattyBridge.get>);
await store.cancel("selected");
assert.deepEqual(calls, ["selected"]);
assert.equal(store.getTask("selected")?.status, "completed");
assert.equal(store.getTask("peer")?.status, "paused");
});
test("Resume cannot revive a tree pre-latched by an upcoming Cancel all batch", async (t) => {
const { markTransferCancelledTree } = await import("./transferCancelLatch");
t.after(resetTransferCancelLatchesForTests);
const store = createSftpTransferCenterStore();
store.publishOwner("gone", [task("waiting-cancel-batch", { status: "paused", isDirectory: true })]);
markTransferCancelledTree("waiting-cancel-batch");
await store.resume("waiting-cancel-batch");
assert.equal(store.getTask("waiting-cancel-batch")?.status, "paused");
assert.equal(isTransferOrRootCancelled("waiting-cancel-batch"), true);
});
test("failed cancel can be retried while its old walk is still running", async (t) => {
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; resetTransferCancelLatchesForTests(); });
const store = createSftpTransferCenterStore();
const runtime = createTransferRuntime(store);
store.publishOwner("gone", [task("retry-live-cancel", { isDirectory: true })]);
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
t.after(() => release());
const walking = runtime.runWalk("retry-live-cancel", async () => { await held; });
let attempts = 0;
netcattyBridge.get = () => ({
cancelTransfer: async () => {
attempts += 1;
if (attempts === 1) return { success: false };
release();
return { success: true };
},
cleanupTransferArtifacts: async () => undefined,
} as unknown as ReturnType<typeof netcattyBridge.get>);
await store.cancel("retry-live-cancel");
assert.equal(runtime.isWalkInFlight("retry-live-cancel"), true);
assert.equal(store.getTask("retry-live-cancel")?.status, "attention");
const resume = store.resume("retry-live-cancel");
await store.cancel("retry-live-cancel");
await Promise.all([walking, resume]);
assert.equal(attempts, 2, "second cancel must reach the backend before natural completion");
assert.equal(store.getTask("retry-live-cancel")?.status, "cancelled", "new successful cancel owns final outcome");
});
test("large orphan recovery clears pending cancellations in bounded concurrent batches", async (t) => {
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; resetTransferCancelLatchesForTests(); });
const store = createSftpTransferCenterStore();
store.publishOwner("gone", [task("cleanup-root", { isDirectory: true }),
...Array.from({ length: 2200 }, (_, index) => task(`cleanup-${index}`, { parentTaskId: "cleanup-root" }))]);
let active = 0;
let peak = 0;
let cleared = 0;
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => ({ success: id !== "cleanup-0" }),
clearPendingTransferCancel: async () => {
active += 1;
peak = Math.max(peak, active);
await new Promise<void>((resolve) => setImmediate(resolve));
active -= 1;
cleared += 1;
},
} as unknown as ReturnType<typeof netcattyBridge.get>);
await store.cancel("cleanup-root");
assert.equal(cleared, 2201);
assert.ok(peak > 1, "recovery must not serialize one IPC per row");
assert.ok(peak <= 32, "recovery uses the cancellation batch bound");
});
for (const completeDuring of ["backend-cancel", "walk-settlement"] as const) {
test(`failed cancellation preserves compacted completion during ${completeDuring} on dedicated resume`, async (t) => {
const { sftpTransferCenterStore: store } = await import("../sftpTransferCenterStore");
const { createDirectoryEntryIdentity } = await import("../../../domain/sftpDirectoryCheckpoint");
const { resumeTransferWithDedicatedSession, resetDedicatedSessionOpenGateForTests } =
await import("./dedicatedTransferResume");
const originalGet = netcattyBridge.get;
const previousStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
});
const parent = task(`compacted-cancel-${completeDuring}`, {
sourcePath: "/source/folder", targetPath: "/target/folder", targetHostId: "fixture-host",
isDirectory: true, progressMode: "files", totalBytes: 3,
});
const children = ["completed", "cancelled", "cancel-failed"].map((name, index) => {
const child = task(`${parent.id}-${name}`, {
parentTaskId: parent.id, fileName: name,
sourcePath: `${parent.sourcePath}/${name}`, targetPath: `${parent.targetPath}/${name}`,
sourceLastModified: 1, directoryEntryIndex: index,
});
return { ...child, directoryEntryIdentity: createDirectoryEntryIdentity({
sourcePath: child.sourcePath, targetPath: child.targetPath, size: child.totalBytes, lastModified: 1,
}) };
});
// Match the sorted traversal order so dedicated resume validates the actual checkpoint.
children.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath));
children.forEach((child, index) => { child.directoryEntryIndex = index; });
const completed = children.find((child) => child.fileName === "completed")!;
const cancelled = children.find((child) => child.fileName === "cancelled")!;
const failed = children.find((child) => child.fileName === "cancel-failed")!;
const runtime = createTransferRuntime(store);
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
let walking: Promise<unknown> | undefined;
t.after(async () => {
release();
await walking;
store.setDedicatedResumeHandler(null);
store.patchTask(parent.id, { status: "completed" });
store.dismiss(parent.id);
netcattyBridge.get = originalGet;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
resetTransferRuntimeRunsForTests();
resetDedicatedSessionOpenGateForTests();
if (previousStorage) Object.defineProperty(globalThis, "localStorage", previousStorage);
else Reflect.deleteProperty(globalThis, "localStorage");
});
const uploads: string[] = [];
const progress: number[] = [];
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => {
if (completeDuring === "backend-cancel" && id === completed.id) {
store.ingestBackgroundEvent({ type: "completed", transferId: id, transferred: 8, totalBytes: 8 });
}
return { success: id !== failed.id };
},
clearPendingTransferCancel: async () => undefined,
openSftp: async () => "reconnected-sftp", closeSftp: async () => {},
listLocalTree: async () => children.map((child) => ({
localPath: child.sourcePath, relativePath: child.fileName,
type: "file", size: 8, lastModified: 1,
})),
mkdirSftp: async () => {},
statLocal: async () => ({ size: 8, lastModified: 1 }),
startStreamTransfer: async (options: { sourcePath: string; checkpointBytes: number }) => {
if (options.sourcePath === cancelled.sourcePath) assert.equal(options.checkpointBytes, 4);
uploads.push(options.sourcePath);
return {};
},
} as unknown as ReturnType<typeof netcattyBridge.get>);
store.publishOwner("closed-panel", [parent, ...children]);
walking = runtime.runWalk(parent.id, async () => {
await held;
if (completeDuring === "walk-settlement") {
store.ingestBackgroundEvent({ type: "completed", transferId: completed.id, transferred: 8, totalBytes: 8 });
}
store.patchTask(cancelled.id, { status: "cancelled", checkpointBytes: 4 });
store.patchTask(parent.id, { status: "cancelled" });
});
await store.cancel(parent.id);
assert.equal(runtime.isWalkInFlight(parent.id), true);
store.setDedicatedResumeHandler(async (root) => {
assert.equal(root.directoryResumeCheckpoint?.completedEntries, 1);
assert.equal(store.getTask(completed.id), undefined, "the finished child stays compacted");
assert.equal(store.getTask(cancelled.id)?.status, "interrupted");
assert.equal(store.getTask(failed.id)?.status, "attention");
return resumeTransferWithDedicatedSession(root, {
hosts: [{ id: "fixture-host", label: "fixture", hostname: "fixture", port: 22,
username: "test", authMethod: "password", protocol: "ssh", tags: [], os: "linux" }],
keys: [], identities: [],
}, (value) => { progress.push(value.transferred); }, {
children: store.getSnapshot().tasks.filter((child) => child.parentTaskId === parent.id),
onChildUpdate: (child) => { store.upsertTasks([child]); },
onDirectoryCheckpointUpdate: (checkpoint) => store.patchTask(parent.id, { directoryResumeCheckpoint: checkpoint }),
});
});
const resuming = store.resume(parent.id);
release();
await Promise.all([walking, resuming]);
assert.deepEqual(uploads.sort(), [cancelled.sourcePath, failed.sourcePath].sort(),
"only cancelled and failed-to-cancel children should upload again");
assert.equal(store.getTask(parent.id)?.status, "completed");
assert.ok(progress.every((count) => count <= 3), "compacted completion must count exactly once");
assert.equal(progress.at(-1), 3);
});
}
for (const rejects of [false, true]) {
test(`failed live compression cancellation resumes the same compression job: rejects=${rejects}`, async (t) => {
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; resetTransferCancelLatchesForTests(); });
const store = createSftpTransferCenterStore();
const calls: string[] = [];
netcattyBridge.get = () => ({
cancelCompressedUpload: async () => {
if (rejects) throw new Error("Cancel IPC failed");
return { success: false };
},
resumeCompressedUpload: async () => { calls.push("compressed"); return { success: true }; },
resumeTransfer: async () => { calls.push("generic"); return { success: false, reason: "not active" }; },
clearPendingTransferCancel: async () => {},
} as unknown as ReturnType<typeof netcattyBridge.get>);
store.setDedicatedResumeHandler(async () => { calls.push("dedicated"); return { success: true }; });
store.publishOwner("closed-panel", [task("live-compressed", {
isDirectory: true, controlKind: "compressed-upload", reconnectRequired: false,
})]);
await store.cancel("live-compressed");
assert.equal(store.getTask("live-compressed")?.status, "attention");
await store.resume("live-compressed");
assert.deepEqual(calls, ["compressed"], "failed cancellation must not start a second destination writer");
assert.equal(store.getTask("live-compressed")?.status, "transferring");
});
}
for (const hasConflict of [false, true]) {
test(`restored compressed attention uses reconnect and preserves conflict gating: conflict=${hasConflict}`, async (t) => {
const { serializeSftpTransferCenter } = await import("../../../domain/sftpTransferCenter");
const { listGloballyResumableTransferIds } = await import("../../../domain/sftpTransferActions");
const { restoreSftpTransferHistoryCooperatively } = await import("./transferHistoryRestoreMigration");
const originalGet = netcattyBridge.get;
t.after(() => { netcattyBridge.get = originalGet; });
const saved = task("restored-compressed", {
status: "attention", isDirectory: true, controlKind: "compressed-upload", reconnectRequired: false,
error: "Could not cancel the compressed upload.",
...(hasConflict ? { conflict: {
transferId: "restored-compressed", fileName: "folder", sourcePath: "/source/folder", targetPath: "/target/folder",
isDirectory: true, existingSize: 8, newSize: 8, existingModified: 1, newModified: 1,
} } : {}),
});
const raw = serializeSftpTransferCenter([saved]);
const restored = createSftpTransferCenterStore({ read: () => raw, write: () => {} });
const cooperative = await restoreSftpTransferHistoryCooperatively(JSON.stringify({ version: 1, tasks: [saved] }));
assert.equal(restored.getTask(saved.id)?.reconnectRequired, true);
assert.equal(cooperative.tasks[0]?.reconnectRequired, true);
assert.equal(restored.getTask(saved.id)?.status, "attention");
assert.deepEqual(restored.getTask(saved.id)?.conflict, saved.conflict);
assert.equal(saved.reconnectRequired, false, "saving must not reclassify the current live row");
const calls: string[] = [];
netcattyBridge.get = () => ({
resumeCompressedUpload: async () => { calls.push("compressed"); return { success: true }; },
clearPendingTransferCancel: async () => {},
} as unknown as ReturnType<typeof netcattyBridge.get>);
restored.setDedicatedResumeHandler(async () => { calls.push("dedicated"); return { success: true }; });
const resumeIds = listGloballyResumableTransferIds(restored.getSnapshot().tasks);
assert.deepEqual(resumeIds, hasConflict ? [] : [saved.id]);
for (const id of resumeIds) await restored.resume(id);
assert.deepEqual(calls, hasConflict ? [] : ["dedicated"]);
});
}
@@ -972,10 +972,13 @@ export function useSftpDirectoryTransferOps({
if (isTransferCancelledError(err)) {
// Keep cancelled status; do not rethrow — other workers must finish
// and the parent should not become a clean completed tree.
setTransfers((prev) => prev.map((task) =>
task.id === fileId
? { ...task, status: "cancelled" as TransferStatus, error: undefined, endTime: Date.now() }
: task));
setTransfers((prev) =>
prev.map((t) =>
t.id === fileId
? { ...t, status: "cancelled" as TransferStatus, error: undefined, endTime: Date.now() }
: t,
),
);
errors.push(err instanceof Error ? err : new Error(message));
return;
}
@@ -51,7 +51,6 @@ export interface TransferRuntime {
* walk is dead / reconnectRequired. Single external operation.
*/
resume(taskId: string): Promise<void>;
/** Wait for backend cancellation requests; Resume remains fenced on walk settlement. */
cancel(taskId: string): Promise<void>;
/**
+11 -14
View File
@@ -71,24 +71,21 @@ export function useSftpTransferTaskOps({
const bridge = netcattyBridge.get();
const cancelTransferAtBackend = bridge?.cancelTransfer;
const cancelCompressedUpload = bridge?.cancelCompressedUpload;
if (!cancelTransferAtBackend && !cancelCompressedUpload) return [];
if (!cancelTransferAtBackend && !cancelCompressedUpload) return;
const failed: string[] = [];
const ids = [...idsToCancel];
for (let offset = 0; offset < ids.length; offset += 32) {
await Promise.all(ids.slice(offset, offset + 32).map(async (id) => {
await Promise.all(
Array.from(idsToCancel).map(async (id) => {
const candidate = currentTransfers.find((task) => task.id === id);
const compressed = candidate?.controlKind === "compressed-upload";
try {
const result = await (compressed ? cancelCompressedUpload?.(id) : cancelTransferAtBackend?.(id));
if (result && result.success === false) failed.push(id);
} catch {
failed.push(id);
const operation = compressed
? cancelCompressedUpload?.(id)
: cancelTransferAtBackend?.(id);
const results = operation ? await Promise.allSettled([operation]) : [];
if (results.some((result) => result.status === "rejected")) {
logger.warn("Failed to cancel one or more transfer backends");
}
}));
}
if (failed.length > 0) logger.warn("Failed to cancel one or more transfer backends");
return failed;
}),
);
}, [activeChildIdsRef, cancelledTasksRef, transfersRef]);
const markBatchStopped = useCallback(
+1 -15
View File
@@ -6,7 +6,6 @@
*/
const inFlightRootIds = new Set<string>();
const settlementWaiters = new Map<string, Set<() => void>>();
export function registerTransferWalk(rootTaskId: string): void {
inFlightRootIds.add(rootTaskId);
@@ -14,28 +13,15 @@ export function registerTransferWalk(rootTaskId: string): void {
export function unregisterTransferWalk(rootTaskId: string): void {
inFlightRootIds.delete(rootTaskId);
const waiters = settlementWaiters.get(rootTaskId);
settlementWaiters.delete(rootTaskId);
for (const resolve of waiters ?? []) resolve();
}
export function isTransferWalkInFlight(rootTaskId: string): boolean {
return inFlightRootIds.has(rootTaskId);
}
/** Wait for the current walk to finish; cancellation must not resume a dying walk. */
export function waitForTransferWalkSettled(rootTaskId: string): Promise<void> {
if (!inFlightRootIds.has(rootTaskId)) return Promise.resolve();
return new Promise((resolve) => {
const waiters = settlementWaiters.get(rootTaskId) ?? new Set();
waiters.add(resolve);
settlementWaiters.set(rootTaskId, waiters);
});
}
/** Test helper. */
export function resetTransferWalkRegistryForTests(): void {
for (const id of inFlightRootIds) unregisterTransferWalk(id);
inFlightRootIds.clear();
}
export function listTransferWalksForTests(): string[] {
@@ -62,8 +62,6 @@ 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. */
@@ -1076,7 +1074,6 @@ export const useSftpConnections = ({
openOptions: {
sessionId: sftpSessionId,
...credentials,
...(options?.reuseTransport === false ? { reuseTransport: false } : {}),
},
});
@@ -85,60 +85,6 @@ 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,9 +16,6 @@ import {
shouldReleaseInitialFollowSyncAttempt,
shouldResetInitialFollowTerminalCwdSync,
type SftpFollowTerminalCwdBlock,
resolveTerminalCwdForSftp,
isSftpFollowTargetPath,
fallbackFollowPathForUntrackedSession,
} from "../../../domain/sftpFollowTerminalCwd";
import type { Host } from "../../../types";
import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActions";
@@ -26,7 +23,6 @@ import type { SftpNavigateOptions, SftpNavigateResult } from "./useSftpPaneActio
type FollowConnection = {
id: string;
currentPath?: string | null;
homeDir?: string | null;
status: string;
isLocal?: boolean;
};
@@ -52,7 +48,6 @@ type GetTerminalCwd = (options?: {
type InitialFollowConnection = {
id: string;
currentPath?: string | null;
homeDir?: string | null;
status: string;
isLocal?: boolean;
};
@@ -90,21 +85,13 @@ 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 !== targetPath ? staleTerminalCwd : targetPath,
terminalCwd: staleTerminalCwd && staleTerminalCwd !== cwd ? staleTerminalCwd : cwd,
});
if (live.currentPath === targetPath) return true;
if (live.currentPath === cwd) return true;
const navigateResult = await navigate(targetPath, isEligible);
const navigateResult = await navigate(cwd, isEligible);
if (!isEligible()) return false;
const current = getConnection();
if (!current || current.id !== expectedConnectionId || current.status !== "connected") {
@@ -187,7 +174,6 @@ 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;
@@ -271,16 +257,10 @@ export function useSftpFollowTerminalCwd({
});
if (!cwd) return;
if (!shouldApply()) return;
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 });
const navigateResult = await sftpRef.current.navigateTo("left", cwd, { 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 };
}
@@ -295,23 +275,9 @@ 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 && 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) {
if (!terminalCwd) {
terminalCwd = await onGetTerminalCwd({
preferFreshBackend: true,
allowRendererFallback: false,
@@ -369,36 +335,26 @@ export function useSftpFollowTerminalCwd({
liveTerminalCwd: activeTerminalCwdRef.current,
requireLiveTerminalCwd: usesLiveTerminalCwd,
});
if (!connection) return;
const targetPath = resolveTerminalCwdForSftp(
terminalCwd,
connection.homeDir,
connection.currentPath,
);
if (!isSftpFollowTargetPath(targetPath)) return;
const navigateResult = await sftpRef.current.navigateTo("left", targetPath, {
const navigateResult = await sftpRef.current.navigateTo("left", terminalCwd, {
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: targetPath };
blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
} else if (navigateResult === "superseded") {
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
} else if (navigateResult === "reached") {
blockedFollowRef.current = null;
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd };
}
}, [
activeSessionId,
activeTerminalCwd,
activeTerminalCwdTrusted,
canFollowTerminalCwd,
effectiveFollowTerminalCwd,
focusedSessionId,
hasActiveWork,
isVisible,
onGetTerminalCwd,
@@ -424,7 +380,6 @@ export function useSftpFollowTerminalCwd({
if (!effectiveFollowTerminalCwd || !canFollowTerminalCwd || !isVisible || hasActiveWork) return;
void syncFollowToTerminalCwd();
}, [
activeSessionId,
activeTerminalCwd,
activeTerminalCwdTrusted,
canFollowTerminalCwd,
@@ -432,7 +387,6 @@ export function useSftpFollowTerminalCwd({
connectionIsLocal,
connectionStatus,
effectiveFollowTerminalCwd,
focusedSessionId,
hasActiveWork,
isVisible,
syncFollowToTerminalCwd,
@@ -579,7 +533,7 @@ export function useSftpFollowTerminalCwd({
getConnection: () => sftpRef.current.leftPane.connection,
navigate: (cwd, shouldApply) => {
navigationStarted = true;
return sftpRef.current.navigateTo("left", cwd, { shouldApply, quiet: true });
return sftpRef.current.navigateTo("left", cwd, { shouldApply });
},
setHandled: (value) => { handledFollowRef.current = value; },
setBlocked: (value) => { blockedFollowRef.current = value; },
+2 -31
View File
@@ -2,7 +2,6 @@ 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,
@@ -56,8 +55,6 @@ export type SftpNavigateOptions = {
force?: boolean;
tabId?: string;
shouldApply?: () => boolean;
/** Restore the previous listing without showing a pane error. */
quiet?: boolean;
};
interface UseSftpPaneActionsResult {
@@ -419,9 +416,8 @@ export const useSftpPaneActions = ({
files: previousFiles,
selectedFiles: previousSelection,
filter: getSftpFilterAfterPathChangeError(clearFilterForPathChange, previousFilter, prev.filter),
error: options?.quiet
? previousError
: unwrapSftpIpcError(err) || "Failed to list directory",
error:
err instanceof Error ? err.message : "Failed to list directory",
loading: false,
};
});
@@ -1034,30 +1030,6 @@ 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,
@@ -1075,7 +1047,6 @@ export const useSftpPaneActions = ({
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -1,665 +0,0 @@
/** @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();
}
});
test("owned cancelled directory settles recoverable children without dropping completed bytes", async () => {
const { writeFile, readFile, mkdtemp, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { transferRuntime } = await import("./transferRuntime");
const root = await mkdtemp(join(tmpdir(), "netcatty-owner-cancel-"));
const completedPath = join(root, "completed.txt");
await writeFile(completedPath, "completed bytes must remain");
const ownerId = "cancel-owner-large";
const rootId = "cancel-root-large";
const base = {
id: rootId, fileName: "folder", sourcePath: "/opt/folder", targetPath: root,
sourceConnectionId: "remote-conn", targetConnectionId: "local-conn",
sourceHostId: "host-1", direction: "download" as const, status: "transferring" as const,
totalBytes: 2201, transferredBytes: 1, speed: 0, startTime: 1, isDirectory: true,
};
const children = Array.from({ length: 2200 }, (_, index) => ({
...base, id: `cancel-child-${index}`, parentTaskId: rootId, isDirectory: false,
sourcePath: `/opt/folder/${index}`, targetPath: join(root, String(index)),
totalBytes: 10, transferredBytes: 4, status: "queued" as const,
}));
sftpTransferCenterStore.publishOwner(ownerId, [base, ...children, {
...base, id: "cancel-completed", parentTaskId: rootId, isDirectory: false,
sourcePath: "/opt/folder/completed.txt", targetPath: completedPath, status: "completed",
}]);
let active = 0;
let peak = 0;
let clearing = 0;
let clearPeak = 0;
let clearCount = 0;
const cleaned: string[] = [];
const restore = installGlobals({
cancelTransfer: async (id: string) => {
assert.notEqual(id, "cancel-completed");
active += 1;
peak = Math.max(peak, active);
await new Promise((resolve) => setImmediate(resolve));
active -= 1;
return { success: id !== "cancel-child-0" };
},
clearPendingTransferCancel: async () => {
clearing += 1;
clearPeak = Math.max(clearPeak, clearing);
await new Promise((resolve) => setImmediate(resolve));
clearing -= 1;
clearCount += 1;
},
cleanupTransferArtifacts: async ({ transferId }: { transferId: string }) => { cleaned.push(transferId); },
});
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
ops = useSftpTransfers({
ownerId,
getActivePane: (side) => makePane(side),
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;
}
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
const walking = transferRuntime.runWalk(rootId, async () => {
await held;
// Old scheduler callbacks settle as cancelled before the outcome is applied.
sftpTransferCenterStore.publishOwner(ownerId, sftpTransferCenterStore.getOwnerTasks(ownerId).map((task) =>
task.status === "completed" ? task : {
...task, status: "cancelled",
checkpointBytes: task.id === "cancel-child-1" ? 6 : task.checkpointBytes,
}));
});
await act(async () => {
const cancellation = ops!.cancelTransfer(rootId);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(transferRuntime.isWalkInFlight(rootId), true);
release();
await Promise.all([walking, cancellation]);
});
assert.ok(peak <= 32, `bounded cancellation IPC, got ${peak}`);
assert.equal(clearCount, 2201);
assert.ok(clearPeak > 1 && clearPeak <= 32, `bounded concurrent cleanup, got ${clearPeak}`);
assert.equal(sftpTransferCenterStore.getTask(rootId)?.status, "attention");
assert.equal(sftpTransferCenterStore.getTask("cancel-child-0")?.status, "attention");
const remaining = sftpTransferCenterStore.getTask("cancel-child-1");
assert.equal(remaining?.status, "interrupted", "evicted cancelled children remain recoverable");
assert.equal(remaining?.checkpointBytes, 6, "retain the terminal checkpoint, not the pre-cancel snapshot");
assert.deepEqual(cleaned, [], "no stage cleanup during partial cancellation recovery");
assert.equal(await readFile(completedPath, "utf8"), "completed bytes must remain");
} finally {
release();
await act(async () => { renderer?.unmount(); });
restore();
await rm(root, { recursive: true, force: true });
}
});
+85 -257
View File
@@ -63,21 +63,6 @@ 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);
@@ -222,6 +207,7 @@ 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(() => {
@@ -627,30 +613,9 @@ export const useSftpTransfers = ({
const sameHost = sameHostEndpoints && !!sourceSftpId && !!targetSftpId;
// 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 };
};
const discoverTransferSize = async () => {
try {
if (task.totalBytes > 0 || !!task.sourceLastModified) return null;
if (task.totalBytes > 0 || !!task.sourceLastModified) return;
if (sourcePane.connection?.isLocal) {
const stat = await netcattyBridge.get()?.statLocal?.(task.sourcePath);
@@ -663,41 +628,17 @@ export const useSftpTransfers = ({
totalBytes: stat.size,
});
}
return { size: stat.size, lastModified: stat.lastModified, plan: true };
}
return null;
return;
}
if (sourceSftpId) {
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) {
const stat = await netcattyBridge.get()?.statSftp?.(
sourceSftpId,
task.sourcePath,
sourceEncoding,
);
if (stat) {
if (!task.sourceLastModified && stat.lastModified) {
task.sourceLastModified = stat.lastModified;
}
@@ -706,18 +647,12 @@ 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();
}
};
@@ -811,35 +746,16 @@ export const useSftpTransfers = ({
return null;
})();
// 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();
// For single files: fire-and-forget size discovery
if (!task.isDirectory) {
void 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")
@@ -903,9 +819,7 @@ export const useSftpTransfers = ({
setConflicts((prev) => [...prev, conflict]);
updateTask({
status: "attention",
// 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,
totalBytes: conflict.newSize || task.totalBytes || 0,
conflict,
});
return "attention";
@@ -1180,84 +1094,6 @@ 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
@@ -1266,30 +1102,12 @@ export const useSftpTransfers = ({
? "download"
: "remote-to-remote";
// 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.
// 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.
const fileEntry = fileEntryMap?.get(file.name);
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 fileSize = file.isDirectory ? 0 : (fileEntry?.size ?? 0);
const sourceLastModified = fileEntry?.lastModified ?? 0;
const nextSourcePath = joinPath(sourcePath, file.name);
const nextTargetPath = joinPath(targetPath, file.name);
@@ -1349,9 +1167,8 @@ export const useSftpTransfers = ({
}
continue;
}
const taskId = crypto.randomUUID();
newTasks.push({
id: taskId,
id: crypto.randomUUID(),
batchId,
fileName: file.name,
originalFileName: file.name,
@@ -1372,7 +1189,6 @@ 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,
@@ -1418,66 +1234,77 @@ export const useSftpTransfers = ({
releasePausedTransfer(transferId);
globalSftpTransferScheduler.cancel(transferId);
// Keep child rows and checkpoints until the old walk has stopped. A
// partial backend failure needs a fresh re-walk, including queued jobs
// the scheduler has already rejected and will never run again.
const children = transfersRef.current.filter((task) =>
task.parentTaskId === transferId
&& !["completed", "cancelled", "failed"].includes(task.status));
const childIds = new Set([
...children.map((task) => task.id),
...(activeChildIdsRef.current.get(transferId) ?? []),
]);
for (const id of childIds) {
cancelledTasksRef.current.add(id);
releasePausedTransfer(id);
globalSftpTransferScheduler.cancel(id);
// Cancel parent + remove child tasks
const childIdsToCancel = new Set<string>();
const childrenToCleanup: TransferTask[] = [];
for (const t of transfersRef.current) {
if (t.parentTaskId === transferId && !["completed", "cancelled", "failed"].includes(t.status)) {
childIdsToCancel.add(t.id);
childrenToCleanup.push(t);
}
}
markTransferCancelledTree(transferId, [...childIds]);
conflictsRef.current = conflictsRef.current.filter((conflict) =>
conflict.transferId !== transferId && !childIds.has(conflict.transferId));
for (const cid of activeChildIdsRef.current.get(transferId) ?? []) {
if (!childIdsToCancel.has(cid)) {
childIdsToCancel.add(cid);
if (taskToCancel) {
childrenToCleanup.push({
...taskToCancel,
id: cid,
parentTaskId: transferId,
});
}
}
}
for (const cid of childIdsToCancel) {
cancelledTasksRef.current.add(cid);
markTransferCancelled(cid);
globalSftpTransferScheduler.cancel(cid);
}
markTransferCancelledTree(transferId, [...childIdsToCancel]);
// Keep refs in sync immediately so same-turn resolveConflict/resume sees cancel.
const nextTransfers = transfersRef.current
.filter((t) => t.parentTaskId !== transferId)
.map((t) =>
t.id === transferId
? { ...t, status: "cancelled" as TransferStatus, endTime: Date.now(), conflict: undefined }
: t,
);
setTransfers(nextTransfers);
conflictsRef.current = conflictsRef.current.filter((c) => c.transferId !== transferId && !childIdsToCancel.has(c.transferId));
setConflicts(conflictsRef.current);
const ids = new Set([transferId, ...childIds]);
const retainedTasks = (taskToCancel ? [taskToCancel, ...children] : children)
.map((task) => ({ task, ...sftpTransferCenterStore.observeTaskSettlement(task) }));
const failedIds = new Set(await cancelBackendTransfers([...ids]));
await sftpTransferCenterStore.settleCancellation(
transferId, ids, failedIds, retainedTasks,
async () => {
setTransfers(sftpTransferCenterStore.getOwnerTasks(ownerId));
for (const id of ids) clearCancelledTask(id);
clearTransferCancelledTree(transferId, [...childIds]);
if (failedIds.size > 0) {
// Preserve stages while any writer could not be cancelled. The
// fresh recovery walk reuses ids only after this settlement.
const recoveryIds = [...ids];
for (let offset = 0; offset < recoveryIds.length; offset += 32) {
await Promise.all(recoveryIds.slice(offset, offset + 32).map(async (id) => {
try { await netcattyBridge.get()?.clearPendingTransferCancel?.(id); } catch { /* best-effort */ }
}));
}
return;
}
if (taskToCancel && sftpTransferCenterStore.getTask(transferId)?.status === "cancelled") {
try { await cleanupTaskArtifacts(taskToCancel); } catch { /* best-effort */ }
}
for (const child of children) {
if (sftpTransferCenterStore.getTask(child.id)?.status === "completed") continue;
try { await cleanupTaskArtifacts(child); } catch { /* best-effort */ }
}
},
);
await cancelBackendTransfers([transferId, ...childIdsToCancel]);
if (taskToCancel) await cleanupTaskArtifacts(taskToCancel);
// Child stages are keyed by per-file transferId — clean each known child.
for (const child of childrenToCleanup) {
try {
await cleanupTaskArtifacts(child);
} catch {
// best-effort
}
}
},
[cancelBackendTransfers, clearCancelledTask, cleanupTaskArtifacts, ownerId, releasePausedTransfer, setTransfers],
[cancelBackendTransfers, cleanupTaskArtifacts, releasePausedTransfer, setTransfers],
);
// All controls go through the process-global runtime, including cancellation
// settlement. A panel must never clear cancellation latches on Resume.
// Soft pause/resume: single TransferRuntime entry (store soft-control +
// dedicated hard reconnect). No panel-local soft-control dual path.
const resumeTransfer = useCallback(async (transferId: string) => {
// Clear sticky child cancel latches so re-walk can retry same child ids.
clearCancelledTask(transferId);
for (const child of transfersRef.current) {
if (child.parentTaskId === transferId) clearCancelledTask(child.id);
}
for (const childId of activeChildIdsRef.current.get(transferId) ?? []) {
clearCancelledTask(childId);
}
clearTransferCancelledTree(
transferId,
[...(activeChildIdsRef.current.get(transferId) ?? [])],
);
await transferRuntime.resume(transferId);
}, []);
}, [clearCancelledTask]);
const prioritizeTransfer = useCallback((transferId: string) => {
globalSftpTransferScheduler.prioritize(transferId);
@@ -2254,6 +2081,7 @@ export const useSftpTransfers = ({
await transferRuntime.pause(taskId);
},
resume: async (taskId: string) => {
// Use resumeTransfer so cancel latches are cleared before soft/hard resume.
await resumeTransfer(taskId);
},
cancel: cancelTransfer,
@@ -2278,7 +2106,7 @@ export const useSftpTransfers = ({
activeTransfersCount,
startTransfer,
downloadToLocal,
cancelTransfer: transferRuntime.cancel,
cancelTransfer,
// Single process-level control surface (TransferRuntime).
pauseTransfer: async (transferId: string) => {
await transferRuntime.pause(transferId);
@@ -1622,46 +1622,6 @@ test("orphan compressed upload resume and cancel keep using the compression job"
assert.equal(store.getSnapshot().tasks[0]?.status, "cancelled");
});
test("compressed upload completing during cancel IPC keeps its completed paint", async (t) => {
const calls: string[] = [];
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
let storeRef: ReturnType<typeof createSftpTransferCenterStore> | undefined;
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
netcatty: {
// Inactive-compression responses report success even after the upload
// already finished; the completion repaint must survive the cancel.
cancelCompressedUpload: async (id: string) => {
calls.push(`cancel:${id}`);
storeRef?.ingestBackgroundEvent({ type: "completed", transferId: id });
return { success: true };
},
},
},
});
const store = createSftpTransferCenterStore();
storeRef = store;
store.publishOwner("closed-panel", [{
...makeTask("compressed-race", "transferring"),
fileName: "done (compressed)",
isDirectory: true,
phase: "compressing",
controlKind: "compressed-upload",
} as TransferTask]);
await store.cancel("compressed-race");
assert.deepEqual(calls, ["cancel:compressed-race"]);
assert.equal(store.getSnapshot().tasks[0]?.status, "completed");
});
test("orphan cancel marks process-global cancel so surviving walks stop", async (t) => {
const {
isTransferCancelledFlag,
@@ -1690,10 +1650,6 @@ test("orphan cancel marks process-global cancel so surviving walks stop", async
}]);
await store.cancel("walk-1");
assert.equal(isTransferCancelledFlag("walk-1"), true);
const resuming = store.resume("walk-1");
unregisterTransferWalk("walk-1");
await resuming;
assert.equal(isTransferCancelledFlag("walk-1"), false);
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "walk-1")?.status, "cancelled");
});
@@ -2750,39 +2706,6 @@ test("an interrupted task without its old controller can still be cancelled", as
assert.equal(store.getSnapshot().tasks[0]?.status, "cancelled");
});
test("orphan cancel keeps failed work visible and leaves completed children alone", async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
});
const cancelledIds: string[] = [];
Object.defineProperty(globalThis, "window", {
configurable: true,
value: { netcatty: {
cancelTransfer: async (id: string) => {
cancelledIds.push(id);
return { success: id !== "unfinished" };
},
} },
});
const store = createSftpTransferCenterStore();
store.publishOwner("closed-panel", [
{ ...makeTask("directory", "paused"), isDirectory: true },
{ ...makeTask("finished", "completed"), parentTaskId: "directory" },
{ ...makeTask("unfinished", "queued"), parentTaskId: "directory" },
]);
const finishedBeforeCancel = store.getTask("finished");
await store.cancel("directory");
assert.deepEqual(cancelledIds, ["directory", "unfinished"]);
assert.equal(store.getTask("finished")?.status, finishedBeforeCancel?.status);
assert.equal(store.getTask("unfinished")?.status, "attention");
assert.equal(store.getTask("directory")?.status, "attention");
assert.match(store.getTask("directory")?.error ?? "", /Could not cancel/);
});
test("concurrent resume clicks adopt a task only once", async () => {
let adoptCount = 0;
const store = createSftpTransferCenterStore();
@@ -3944,66 +3867,3 @@ for (const outcome of ["rejected", "stream-gone"] as const) {
assert.equal(resumeCalls, 1, "obsolete resume must not issue another resume after the held run ends");
});
}
test("partial cancel failure resets recovered folder children so the re-walk can re-admit them", async (t) => {
const { netcattyBridge } = await import("../../infrastructure/services/netcattyBridge");
const { resetTransferCancelLatchesForTests, isTransferOrRootCancelled } =
await import("./sftp/transferCancelLatch");
const { resetTransferWalkRegistryForTests } = await import("./sftp/transferWalkRegistry");
const originalGet = netcattyBridge.get;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
t.after(() => {
netcattyBridge.get = originalGet;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
});
// Only child2 fails to cancel; the folder must stay recoverable via Resume.
let failChild2 = true;
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => ({ success: id !== "dir-child-2" || !failChild2 }),
cleanupTransferArtifacts: async () => ({}),
} as unknown as ReturnType<typeof netcattyBridge.get>);
const store = createSftpTransferCenterStore();
const child = (id: string): TransferTask => ({
...makeTask(id),
parentTaskId: "dir-root",
isDirectory: false,
transferredBytes: 4,
directoryEntryIndex: 0,
directoryEntryIdentity: "a".repeat(64),
});
store.publishOwner("gone-panel", [
{ ...makeTask("dir-root"), isDirectory: true, transferredBytes: 10, totalBytes: 20, directoryEntryIndex: 0 },
child("dir-child-1"),
child("dir-child-2"),
]);
await store.cancel("dir-root");
const rows = store.getSnapshot().tasks;
const parent = rows.find((row) => row.id === "dir-root");
const child1 = rows.find((row) => row.id === "dir-child-1");
const child2 = rows.find((row) => row.id === "dir-child-2");
assert.equal(parent?.status, "attention");
assert.equal(parent?.error, "Could not cancel transfer. Please try again.");
// A failed backend cancellation keeps the folder recoverable: successfully
// cancelled siblings must not settle as terminal "cancelled", or admitTaskRun
// would reject the recovery re-walk and leave the destination incomplete.
assert.equal(child1?.status, "interrupted");
assert.equal(child1?.error, undefined);
assert.equal(child2?.status, "attention");
assert.equal(isTransferOrRootCancelled("dir-root"), false, "recovery latch must be cleared");
// The directory re-walk (Resume) can re-admit the reset sibling.
const incoming = { ...child("dir-child-1"), directoryEntryIndex: 0, directoryEntryIdentity: "a".repeat(64) };
assert.equal(store.admitTaskRun(incoming), "ready");
assert.equal(store.getTask("dir-child-1")?.status, "transferring");
// Without any cancellation failure the tree still settles fully cancelled.
failChild2 = false;
await store.cancel("dir-root");
const afterFullCancel = store.getSnapshot().tasks;
for (const id of ["dir-root", "dir-child-1", "dir-child-2"]) {
assert.equal(afterFullCancel.find((row) => row.id === id)?.status, "cancelled");
}
});
+34 -133
View File
@@ -26,10 +26,8 @@ import {
isTransferControlEpochCurrent,
settleTransferControlEpochTree,
} from "./sftp/transferControlEpoch";
import { isTransferWalkInFlight, waitForTransferWalkSettled } from "./sftp/transferWalkRegistry";
import { settleCancelledTransferTree } from "./sftp/transferCancelOutcome";
import { isTransferWalkInFlight } from "./sftp/transferWalkRegistry";
import {
clearTransferCancelledTree,
isTransferOrRootCancelled,
markTransferCancelledTree,
settleTransferCancelTree,
@@ -95,12 +93,6 @@ export type DedicatedTransferResumeHandler = (task: TransferTask) => Promise<{
resetCheckpoint?: boolean;
}>;
interface RetainedCancellationTask {
task: TransferTask;
read(): TransferTask | undefined;
dispose(): void;
}
export interface SftpTransferCenterStore {
subscribe(listener: Listener): () => void;
/**
@@ -129,10 +121,7 @@ export interface SftpTransferCenterStore {
isResuming(taskId: string): boolean;
pause(taskId: string): Promise<void>;
resume(taskId: string): Promise<void>;
/** Wait for backend cancellation requests; live walks settle separately. */
cancel(taskId: string): Promise<void>;
/** Publish one cancellation outcome after the old execution has settled. */
settleCancellation(taskId: string, taskIds: ReadonlySet<string>, failedIds: ReadonlySet<string>, retainedTasks: readonly RetainedCancellationTask[], onSettled: () => Promise<void>): Promise<void>;
retry(taskId: string): Promise<void>;
prioritize(taskId: string): Promise<void>;
dismiss(taskId: string): void;
@@ -475,8 +464,6 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
let persistenceDirty = false;
let persistenceTimer: ReturnType<typeof setTimeout> | null = null;
const resumeInvocations = new Map<string, Promise<void>>();
const cancelInvocations = new Map<string, Promise<void>>();
const cancelSettlements = new Map<string, Promise<void>>();
// Ephemeral control intent: never serialize this or change bridge lifecycle epochs.
const resumeRequests = new Map<string, symbol>();
const resumeListeners = new Set<Listener>();
@@ -831,7 +818,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// Compressed soft-control is process-global: do not gate on a live panel owner.
const liveCompressedJob = task?.controlKind === "compressed-upload"
&& task.reconnectRequired !== true
&& task.status !== "interrupted";
&& task.status !== "interrupted"
&& task.status !== "attention";
if (liveCompressedJob && (action === "pause" || action === "resume" || action === "cancel")) {
const bridge = netcattyBridge.get();
if (action === "pause") {
@@ -891,17 +879,8 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if (!result.success && result.reason) notify.warning(result.reason, "SFTP");
return;
}
const result = await Promise.resolve(bridge?.cancelCompressedUpload?.(taskId)
?? { success: false }).catch(() => ({ success: false }));
// The upload may finish while this cancel is still awaiting IPC: its
// completion event has already repainted the row terminal. The new
// inactive-compression response still reports success, so recheck the
// latest row before applying the cancellation result — otherwise Cancel
// all misreports a successfully completed upload as cancelled.
const latestAfterCancelIpc = tasks.find((candidate) => candidate.id === taskId);
if (latestAfterCancelIpc && ["completed", "failed", "cancelled"].includes(latestAfterCancelIpc.status)) {
return;
}
const result = await (bridge?.cancelCompressedUpload?.(taskId)
?? { success: false });
if (!result.success) {
const reason = "Could not cancel the compressed upload.";
tasks = tasks.map((candidate) => candidate.id === taskId ? {
@@ -910,13 +889,6 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
error: reason,
speed: 0,
} : candidate);
if (isTransferOrRootCancelled(taskId)) {
// The row is kept in attention for recovery instead of settling as
// cancelled. Drop the pre-installed cancellation latch now, or a
// later Resume is rejected outright by admitTaskRun's cancelled-root
// check (compressed uploads have no runWalk settlement to clear it).
clearTransferCancelledTree(taskId);
}
emit();
notify.warning(reason, "SFTP");
return;
@@ -1329,9 +1301,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
emit();
}
}
if (!controller && action === "cancel" && task && !["completed", "cancelled"].includes(task.status)) {
if (!controller && action === "cancel" && task && ["paused", "interrupted", "attention", "pending", "queued", "transferring", "pausing"].includes(task.status)) {
const childIds = tasks
.filter((candidate) => candidate.parentTaskId === taskId && !["completed", "cancelled", "failed"].includes(candidate.status))
.filter((candidate) => candidate.parentTaskId === taskId)
.map((candidate) => candidate.id);
// Stop surviving processTransfer walks immediately (panel-local
// cancelledTasksRef is gone after unmount).
@@ -1343,43 +1315,33 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
} catch {
// best-effort
}
const failedIds = new Set<string>();
const cancelIds = [taskId, ...childIds];
const cancelledIdSet = new Set(cancelIds);
const retainedTasks = tasks.filter((candidate) => cancelledIdSet.has(candidate.id))
.map((task) => ({ task, ...store.observeTaskSettlement(task) }));
for (let offset = 0; offset < cancelIds.length; offset += 32) {
await Promise.all(cancelIds.slice(offset, offset + 32).map(async (id) => {
try {
const result: unknown = await netcattyBridge.get()?.cancelTransfer?.(id);
if (result && typeof result === "object" && "success" in result && result.success === false) {
failedIds.add(id);
}
} catch {
failedIds.add(id);
}
}));
}
await store.settleCancellation(taskId, cancelledIdSet, failedIds, retainedTasks, async () => {
clearTransferCancelledTree(taskId, childIds);
if (failedIds.size > 0) {
const recoveryIds = cancelIds;
for (let offset = 0; offset < recoveryIds.length; offset += 32) {
await Promise.all(recoveryIds.slice(offset, offset + 32).map(async (id) => {
try { await netcattyBridge.get()?.clearPendingTransferCancel?.(id); } catch { /* best-effort */ }
}));
}
} else if (tasks.find((candidate) => candidate.id === taskId)?.status === "cancelled") {
try {
await netcattyBridge.get()?.cleanupTransferArtifacts?.({
transferId: taskId,
sourcePath: task.sourcePath,
targetPath: task.targetPath,
stagedTargetPath: task.stagedTargetPath,
});
} catch { /* best-effort */ }
try {
await netcattyBridge.get()?.cancelTransfer?.(taskId);
for (const childId of childIds) {
try { await netcattyBridge.get()?.cancelTransfer?.(childId); } catch { /* best-effort */ }
}
});
} catch {
// Best-effort backend cancel when the owning panel is gone / no window.
}
try {
await netcattyBridge.get()?.cleanupTransferArtifacts?.({
transferId: taskId,
sourcePath: task.sourcePath,
targetPath: task.targetPath,
stagedTargetPath: task.stagedTargetPath,
});
} catch {
// best-effort temp/.part cleanup
}
const cancelIds = new Set([taskId, ...childIds]);
tasks = tasks.map((candidate) => cancelIds.has(candidate.id) ? {
...candidate,
status: "cancelled",
error: undefined,
endTime: Date.now(),
speed: 0,
conflict: undefined,
} : candidate);
emit();
return;
}
@@ -1832,28 +1794,10 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
&& ["paused", "interrupted", "attention", "pending", "queued"].includes(task.status);
},
pause(taskId) {
if (cancelInvocations.has(taskId) || isTransferOrRootCancelled(taskId)) return Promise.resolve();
clearResumeRequest(taskId);
return invoke(taskId, "pause");
},
async resume(taskId) {
// A cancelled scheduler job cannot be soft-resumed. Wait for the cancel
// outcome and fresh re-walk rather than unlatching the old walk.
const cancelling = cancelInvocations.get(taskId);
if (cancelling) {
await cancelling;
const task = tasks.find((candidate) => candidate.id === taskId);
if (!task || ["completed", "cancelled", "failed"].includes(task.status)) return;
}
// Failed cancellation reports immediately, but its old walk must still
// settle before Resume can start a fresh scan. A retried Cancel may have
// replaced the awaited outcome, so drain the latest settlement as well.
while (cancelSettlements.has(taskId)) await cancelSettlements.get(taskId);
const afterCancellation = tasks.find((candidate) => candidate.id === taskId);
if (!afterCancellation || ["completed", "cancelled"].includes(afterCancellation.status)) return;
// Cancel all latches every selected tree before its bounded IPC batches.
// A row-level Resume must not revive a tree whose batch has not run yet.
if (isTransferOrRootCancelled(taskId)) return;
const request = Symbol("resume");
resumeRequests.set(taskId, request);
notifyResume();
@@ -1969,52 +1913,9 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
if (resumeRequests.get(taskId) === request) clearResumeRequest(taskId);
}
},
async settleCancellation(taskId, taskIds, failedIds, retainedTasks, onSettled) {
const walkStillRunning = isTransferWalkInFlight(taskId);
const settlement = (async () => {
await waitForTransferWalkSettled(taskId);
// A later cancel attempt owns the outcome, even if this older attempt
// failed. Never repaint a successful retry as a failed cancellation.
if (cancelSettlements.get(taskId) !== settlement) return;
tasks = settleCancelledTransferTree(
tasks, taskId, taskIds, failedIds,
retainedTasks.map((retained) => retained.read() ?? retained.task),
);
await onSettled();
emit();
})().finally(() => {
for (const retained of retainedTasks) retained.dispose();
if (cancelSettlements.get(taskId) === settlement) cancelSettlements.delete(taskId);
});
cancelSettlements.set(taskId, settlement);
if (walkStillRunning) {
if (failedIds.size > 0) {
tasks = tasks.map((task) => task.id === taskId
&& !["completed", "failed"].includes(task.status)
? { ...task, status: "attention", error: "Could not cancel transfer. Please try again.", speed: 0 }
: task);
emit();
}
// Backend requests are done: let Cancel all dispatch its next batch.
// Resume, final status, and cleanup still wait on this settlement.
void settlement.catch(() => {});
return;
}
await settlement;
},
cancel(taskId) {
clearResumeRequest(taskId);
const existing = cancelInvocations.get(taskId);
if (existing) return existing;
bumpTransferControlEpoch(taskId);
for (const task of tasks) {
if (task.parentTaskId === taskId) bumpTransferControlEpoch(task.id);
}
const running = invoke(taskId, "cancel").finally(() => {
if (cancelInvocations.get(taskId) === running) cancelInvocations.delete(taskId);
});
cancelInvocations.set(taskId, running);
return running;
return invoke(taskId, "cancel");
},
async retry(taskId) {
const ownerId = findOwner(taskId);
@@ -2,7 +2,6 @@ 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,
@@ -43,7 +42,6 @@ interface UseSystemSettingsEffectsParams {
toggleWindowHotkey: string;
globalHotkeyEnabled: boolean;
closeToTray: boolean;
showTrayIcon: boolean;
autoLaunchEnabled: boolean;
windowOpacityRecord: WindowOpacityRecord;
windowOpacityMutationSourceRef: MutableRefObject<WindowOpacityMutationSource>;
@@ -64,7 +62,6 @@ export function useSystemSettingsEffects({
toggleWindowHotkey,
globalHotkeyEnabled,
closeToTray,
showTrayIcon,
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
@@ -176,24 +173,6 @@ 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 -1
View File
@@ -1,6 +1,6 @@
type Listener = () => void;
export type TerminalCwdSource = "osc7" | "inferred" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
export type TerminalCwdSource = "osc7" | "backend-strict" | "backend" | "snapshot" | "stale" | "unknown";
/**
* Live terminal CWD map + version token.
+3 -8
View File
@@ -174,13 +174,10 @@ export function useAgentDiscovery(
? { ...(ea.env ?? {}), CLAUDE_CODE_EXECUTABLE: matchPath }
: match.command === 'opencode'
? { ...(ea.env ?? {}), OPENCODE_BIN: matchPath }
: match.command === 'mimo'
? { ...(ea.env ?? {}), MIMOCODE_BIN: matchPath }
: ea.env;
: ea.env;
const envChanged =
(match.command === 'claude' && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath)
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath)
|| (match.command === 'mimo' && ea.env?.MIMOCODE_BIN !== matchPath);
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath);
const versionChanged = Boolean(match.version) && ea.cliVersion !== match.version;
if (currentArgs !== newArgs || backendChanged || envChanged || versionChanged) {
changed = true;
@@ -223,9 +220,7 @@ 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 || '' } }
: {}),
: {}),
};
},
[],
+1 -7
View File
@@ -10,11 +10,5 @@ export const useClipboardBackend = () => {
return typeof text === "string" ? text : "";
}, []);
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 };
return { readClipboardText };
};
@@ -1,147 +0,0 @@
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 { TransferTask } from "../../domain/models";
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
import { sftpTransferCenterStore as store } from "./sftpTransferCenterStore";
import { useGlobalSftpTransferActions } from "./useGlobalSftpTransferActions";
import { isTransferOrRootCancelled, resetTransferCancelLatchesForTests } from "./sftp/transferCancelLatch";
import { resetTransferRuntimeRunsForTests, transferRuntime } from "./sftp/transferRuntime";
import { resetTransferWalkRegistryForTests } from "./sftp/transferWalkRegistry";
test("Cancel all releases a skipped late failure so one Retry executes while the old walk unwinds", async (t) => {
const previousAct = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
const originalGet = netcattyBridge.get;
const tasks: TransferTask[] = Array.from({ length: 33 }, (_, index) => ({
id: `late-failure-${index}`, fileName: `${index}.bin`,
sourcePath: `/source/${index}`, targetPath: `/target/${index}`,
sourceConnectionId: "local", targetConnectionId: "remote", targetHostId: "host",
direction: "upload", status: "transferring", totalBytes: 8, transferredBytes: 0,
speed: 0, startTime: Date.now() + index, isDirectory: false, resumable: true,
}));
const later = tasks[32];
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
let renderer: ReactTestRenderer | undefined;
let actions: ReturnType<typeof useGlobalSftpTransferActions> | undefined;
function Probe() {
actions = useGlobalSftpTransferActions(store.getSnapshot().tasks);
return null;
}
store.publishOwner("closed-panel", tasks);
const walking = transferRuntime.runWalk(later.id, async () => { await held; });
t.after(async () => {
release();
await walking;
await act(async () => { renderer?.unmount(); });
store.setDedicatedResumeHandler(null);
for (const task of tasks) store.dismiss(task.id);
netcattyBridge.get = originalGet;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
resetTransferRuntimeRunsForTests();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: previousAct });
});
const cancellations: string[] = [];
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => {
cancellations.push(id);
if (id === tasks[0].id) store.patchTask(later.id, { status: "failed", error: "Connection lost" });
return { success: true };
},
resumeTransfer: async () => ({ success: false, reason: "Transfer is no longer active" }),
clearPendingTransferCancel: async () => {}, cleanupTransferArtifacts: async () => {},
} as unknown as ReturnType<typeof netcattyBridge.get>);
let retries = 0;
store.setDedicatedResumeHandler(async () => { retries += 1; return { success: true }; });
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => { await actions!.cancelAll(); });
assert.equal(cancellations.length, 32, "the late failure must be skipped by the second batch");
assert.equal(store.getTask(later.id)?.status, "failed");
assert.equal(store.getTask(later.id)?.error, "Connection lost");
assert.equal(transferRuntime.isWalkInFlight(later.id), true);
await store.retry(later.id);
assert.equal(retries, 1, "one Retry must reach recovery instead of being swallowed by the pre-latch");
assert.equal(store.getTask(later.id)?.status, "completed");
assert.equal(isTransferOrRootCancelled(later.id), false);
});
for (const firstCancelSucceeds of [true, false]) {
test(`Cancel all dispatches later batches before walk settlement: success=${firstCancelSucceeds}`, async (t) => {
const previousAct = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
const originalGet = netcattyBridge.get;
const tasks: TransferTask[] = Array.from({ length: 33 }, (_, index) => ({
id: `dispatch-${firstCancelSucceeds}-${index}`, fileName: `${index}.bin`,
sourcePath: `/source/${index}`, targetPath: `/target/${index}`,
sourceConnectionId: "local", targetConnectionId: "remote", targetHostId: "host",
direction: "upload", status: "transferring", totalBytes: 8, transferredBytes: 0,
speed: 0, startTime: Date.now() + index, isDirectory: false, resumable: true,
}));
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
let renderer: ReactTestRenderer | undefined;
let actions: ReturnType<typeof useGlobalSftpTransferActions> | undefined;
let cancelling: Promise<void> | undefined;
function Probe() {
actions = useGlobalSftpTransferActions(store.getSnapshot().tasks);
return null;
}
store.publishOwner("closed-panel", tasks);
const first = tasks[0].id;
const walking = transferRuntime.runWalk(first, async () => { await held; });
t.after(async () => {
release();
await walking;
await act(async () => { await cancelling; renderer?.unmount(); });
store.setDedicatedResumeHandler(null);
for (const task of tasks) store.dismiss(task.id);
netcattyBridge.get = originalGet;
resetTransferCancelLatchesForTests();
resetTransferWalkRegistryForTests();
resetTransferRuntimeRunsForTests();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: previousAct });
});
const calls: string[] = [];
const cleaned: string[] = [];
let active = 0;
let peak = 0;
let recoveryCalls = 0;
netcattyBridge.get = () => ({
cancelTransfer: async (id: string) => {
calls.push(id);
peak = Math.max(peak, ++active);
await new Promise((resolve) => setImmediate(resolve));
active -= 1;
return { success: id !== first || firstCancelSucceeds };
},
clearPendingTransferCancel: async () => {},
cleanupTransferArtifacts: async ({ transferId }: { transferId: string }) => { cleaned.push(transferId); },
} as unknown as ReturnType<typeof netcattyBridge.get>);
store.setDedicatedResumeHandler(async () => { recoveryCalls += 1; return { success: true }; });
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
cancelling = actions!.cancelAll();
for (let tick = 0; tick < 5; tick += 1) await new Promise((resolve) => setImmediate(resolve));
});
assert.equal(calls.length, 33, "the later active stream must receive cancellation before the first walk finishes");
assert.ok(peak > 1 && peak <= 32, "backend cancellation remains bounded");
assert.equal(transferRuntime.isWalkInFlight(first), true);
assert.equal(isTransferOrRootCancelled(first), true, "dispatch completion must not clear the old walk latch");
assert.equal(cleaned.includes(first), false, "artifact cleanup still waits for settlement");
let resumeFinished = false;
const resuming = store.resume(first).then(() => { resumeFinished = true; });
await new Promise((resolve) => setImmediate(resolve));
assert.equal(resumeFinished, false, "Resume must still wait for the cancelling walk");
assert.equal(recoveryCalls, 0);
release();
await Promise.all([walking, cancelling, resuming]);
assert.equal(recoveryCalls, firstCancelSucceeds ? 0 : 1);
assert.equal(store.getTask(first)?.status, firstCancelSucceeds ? "cancelled" : "completed");
});
}
@@ -1,95 +1,28 @@
import { useCallback, useMemo, useRef, useState } from "react";
import { useCallback, useMemo } from "react";
import type { TransferTask } from "../../domain/models";
import {
getGlobalTransferBatchEligibility,
listGloballyCancellableTransferIds,
listGloballyPausableTransferIds,
listGloballyResumableTransferIds,
} from "../../domain/sftpTransferActions";
import { sftpTransferCenterStore } from "./sftpTransferCenterStore";
import { globalSftpTransferScheduler } from "./sftp/globalTransferScheduler";
import { clearTransferCancelledTree, markTransferCancelledTree } from "./sftp/transferCancelLatch";
import { transferRuntime } from "./sftp/transferRuntime";
export function useGlobalSftpTransferActions(tasks: readonly TransferTask[]) {
const cancellingRef = useRef(false);
const [isCancelling, setIsCancelling] = useState(false);
const batchEligibility = useMemo(
() => getGlobalTransferBatchEligibility(tasks),
[tasks],
);
const pauseAll = useCallback(() => {
// Ignore clicks racing a cancelAll batch: re-enabling these tasks would
// restart work cancelAll has already pre-cancelled at the scheduler.
if (cancellingRef.current) return;
for (const taskId of listGloballyPausableTransferIds(tasks)) {
void sftpTransferCenterStore.pause(taskId);
}
}, [tasks]);
const resumeAll = useCallback(() => {
if (cancellingRef.current) return;
for (const taskId of listGloballyResumableTransferIds(tasks)) {
void sftpTransferCenterStore.resume(taskId);
}
}, [tasks]);
const cancelAll = useCallback(async () => {
if (cancellingRef.current) return;
cancellingRef.current = true;
setIsCancelling(true);
const currentTasks = transferRuntime.getSnapshot().tasks;
const ids = listGloballyCancellableTransferIds(currentTasks);
try {
// Stop queued work before yielding to IPC, including children of folder
// transfers. Otherwise later batches could start while earlier ones stop.
const selected = new Set(ids);
const children = new Map<string, string[]>();
for (const task of currentTasks) {
if (!task.parentTaskId || !selected.has(task.parentTaskId)
|| ["completed", "failed", "cancelled"].includes(task.status)) continue;
const idsForParent = children.get(task.parentTaskId) ?? [];
idsForParent.push(task.id);
children.set(task.parentTaskId, idsForParent);
globalSftpTransferScheduler.cancel(task.id);
}
for (const id of ids) {
markTransferCancelledTree(id, children.get(id));
globalSftpTransferScheduler.cancel(id);
}
// Bound IPC work for large queues while active transfers stop promptly.
for (let offset = 0; offset < ids.length; offset += 32) {
await Promise.all(ids.slice(offset, offset + 32).map(async (taskId) => {
const current = transferRuntime.getTask(taskId);
// "failed" is terminal here just like the initial eligibility filter:
// a queued task can fail naturally while its cancel batch awaits IPC,
// and cancel's owner/orphan recovery paths would repaint the row as
// cancelled, hiding the real failure and its diagnostic.
if (!current || ["completed", "failed", "cancelled"].includes(current.status)) {
// No cancel invocation will own this pre-latch. Release it here so
// Retry is not discarded while the finished walk is unwinding.
clearTransferCancelledTree(taskId, children.get(taskId));
return;
}
try {
await transferRuntime.cancel(taskId);
} catch {
// The row is kept in attention for recovery, so the pre-installed
// cancellation latch must be dropped or a later Resume is rejected
// outright by admitTaskRun's cancelled-root check.
clearTransferCancelledTree(taskId, children.get(taskId));
sftpTransferCenterStore.patchTask(taskId, {
status: "attention",
error: "Could not cancel transfer. Please try again.",
});
}
}));
}
} finally {
cancellingRef.current = false;
setIsCancelling(false);
}
}, []);
return { batchEligibility, pauseAll, resumeAll, cancelAll, isCancelling };
return { batchEligibility, pauseAll, resumeAll };
}
-16
View File
@@ -66,8 +66,6 @@ import {
getSessionConnectionLabel,
} from '../../domain/sessionTabTitle';
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import { useVaultSnapshotField } from './vaultSnapshotStore';
export function addWorkspaceIfMissing(
workspaces: Workspace[],
@@ -269,20 +267,6 @@ 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
@@ -1,103 +0,0 @@
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();
});
});
-11
View File
@@ -67,7 +67,6 @@ 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,
@@ -551,13 +550,6 @@ 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>(() => {
@@ -1799,7 +1791,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
toggleWindowHotkey,
globalHotkeyEnabled,
closeToTray,
showTrayIcon,
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
@@ -2165,8 +2156,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setToggleWindowHotkey,
closeToTray,
setCloseToTray,
showTrayIcon,
setShowTrayIcon,
autoLaunchEnabled,
setAutoLaunchEnabled,
autoLaunchSupported,
-4
View File
@@ -469,7 +469,6 @@ export const useSftpState = (
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -782,7 +781,6 @@ export const useSftpState = (
createFileAtPath,
deleteFiles,
deleteFilesAtPath,
removeListedNames,
renameFile,
renameFileAtPath,
moveEntriesToPath,
@@ -859,8 +857,6 @@ 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),
-3
View File
@@ -15,9 +15,6 @@ 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');
}
+1 -1
View File
@@ -521,7 +521,7 @@ export const useTerminalBackend = () => {
const getSessionPwd = useCallback(async (
sessionId: string,
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean; timeoutMs?: number },
options?: { allowHomeFallback?: boolean; allowLoginShellFallback?: boolean },
) => {
const bridge = netcattyBridge.get();
if (!bridge?.getSessionPwd) return { success: false, error: 'getSessionPwd unavailable' };
@@ -1,7 +1,6 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import {
applyAgentNotesUpdate,
haveSameVaultAgentSnapshot,
resolveVaultAgentEffectiveHost,
resolveVaultAgentNotes,
@@ -28,33 +27,6 @@ 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 = {
+2 -19
View File
@@ -89,20 +89,6 @@ 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,
@@ -159,7 +145,6 @@ 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,
@@ -254,10 +239,8 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
vaultSnapshotRef.current.notes = notes;
applyUpdateNotes(notes);
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
@@ -175,22 +175,6 @@ 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']) {
+1 -10
View File
@@ -54,14 +54,6 @@ 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',
@@ -274,8 +266,7 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
|| sdkBackend === 'cursor'
|| sdkBackend === 'codebuddy'
|| sdkBackend === 'opencode'
|| sdkBackend === 'grok'
|| sdkBackend === 'mimo';
|| sdkBackend === 'grok';
}
export function shouldAdoptSdkCurrentModel(
+2 -17
View File
@@ -2,7 +2,6 @@ import assert from "node:assert/strict";
import test from "node:test";
import type { TransferTask } from "../domain/models";
import { listGloballyCancellableTransferIds } from "../domain/sftpTransferActions";
import {
buildGlobalTransferProgressDisplay,
getGlobalConflictActionPresentation,
@@ -66,28 +65,14 @@ test("batch actions are disabled when no task can accept them", () => {
assert.deepEqual(getGlobalTransferBatchEligibility([
task("done", "completed"),
task("cancelled", "cancelled"),
]), { cancellableCount: 0, pausableCount: 0, resumableCount: 0 });
]), { pausableCount: 0, resumableCount: 0 });
assert.deepEqual(getGlobalTransferBatchEligibility([
task("running", "transferring"),
task("waiting", "queued"),
task("paused", "paused"),
{ ...task("failed", "failed"), checkpointBytes: 4 },
]), { cancellableCount: 3, pausableCount: 2, resumableCount: 2 });
});
test("cancel all selects unfinished top-level tasks without touching completed files", () => {
const statuses: TransferTask["status"][] = [
"pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention",
];
const tasks = [
...statuses.map((status) => task(status, status)),
task("completed", "completed"),
task("failed", "failed"),
task("cancelled", "cancelled"),
{ ...task("child", "queued"), parentTaskId: "pending" },
];
assert.deepEqual(listGloballyCancellableTransferIds(tasks), statuses);
]), { pausableCount: 2, resumableCount: 2 });
});
test("paused transfer errors remain visible instead of looking safely paused", () => {
+4 -7
View File
@@ -837,7 +837,7 @@ export function GlobalSftpTransferCenter() {
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || b.startTime - a.startTime), [bucket, snapshot.tasks]);
const { visible, collapsed } = splitBackgroundTransfers(bucketTasks);
const displayed = showBackground ? [...visible, ...collapsed] : visible;
const { batchEligibility, pauseAll, resumeAll, cancelAll, isCancelling } = useGlobalSftpTransferActions(snapshot.tasks);
const { batchEligibility, pauseAll, resumeAll } = useGlobalSftpTransferActions(snapshot.tasks);
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -877,16 +877,13 @@ export function GlobalSftpTransferCenter() {
<div className="min-w-0 pr-2 text-sm font-semibold">
{t("sftp.transferCenter.title")}
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={pauseAll} disabled={isCancelling || batchEligibility.pausableCount === 0}>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={pauseAll} disabled={batchEligibility.pausableCount === 0}>
<Pause size={12} className="mr-1" />{t("sftp.transferCenter.pauseAll")}
</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={resumeAll} disabled={isCancelling || batchEligibility.resumableCount === 0}>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={resumeAll} disabled={batchEligibility.resumableCount === 0}>
<Play size={12} className="mr-1" />{t("sftp.transferCenter.resumeAll")}
</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs text-destructive" onClick={() => { void cancelAll(); }} disabled={isCancelling || batchEligibility.cancellableCount === 0}>
<X size={12} className="mr-1" />{t("sftp.transferCenter.cancelAll")}
</Button>
</div>
</div>
-13
View File
@@ -53,19 +53,6 @@ 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/);
-29
View File
@@ -10,7 +10,6 @@
import {
CheckSquare,
ChevronRight,
Copy,
Edit2,
Expand,
FolderPlus,
@@ -55,7 +54,6 @@ 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';
@@ -891,20 +889,6 @@ 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;
@@ -1145,8 +1129,6 @@ 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}
@@ -1200,8 +1182,6 @@ 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}
@@ -1525,8 +1505,6 @@ interface SnippetRowProps {
onDelete: () => void;
onRunParallel?: () => void;
onRunSequential?: () => void;
onCopyCommand?: () => void;
copyCommandLabel?: string;
runParallelLabel?: string;
runSequentialLabel?: string;
editLabel: string;
@@ -1549,8 +1527,6 @@ const SnippetRow = memo<SnippetRowProps>(({
onDelete,
onRunParallel,
onRunSequential,
onCopyCommand,
copyCommandLabel,
runParallelLabel,
runSequentialLabel,
editLabel,
@@ -1628,11 +1604,6 @@ 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>
-2
View File
@@ -677,8 +677,6 @@ 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}
+13 -93
View File
@@ -76,7 +76,6 @@ 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";
@@ -96,8 +95,6 @@ import {
shouldCancelSettledPendingSftpRebindWithoutTarget,
shouldDeferPendingSftpUploadForOriginFocus,
shouldDeferSftpSidePanelAutoConnectForSession,
isSplitFocusSftpStillConnected,
shouldKeepConnectedSftpOnSplitFocus,
shouldRebindSftpSidePanelSourceSession,
shouldSkipSftpSidePanelAutoConnect,
shouldStartPendingSftpUploadRebind,
@@ -573,41 +570,6 @@ 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(
@@ -731,16 +693,6 @@ 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;
@@ -756,33 +708,16 @@ 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 (
!pendingRequiresForcedRebind
&& (endpointAlreadyConnected || splitEndpointStillUp)
&& (!sessionChanged || keepSplitSftp)
!sessionChanged
&& !pendingRequiresForcedRebind
&& shouldSkipSftpSidePanelAutoConnect(
connectionKey,
connectedKeyRef.current,
activeTab,
activeConnectionId ? hasBackendSession(activeConnectionId) : false,
activeTabConnectionKey,
)
) {
if (activeSessionId) {
lastSourceSessionIdRef.current = activeSessionId;
@@ -934,20 +869,13 @@ 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: reuseTerminalTransport
? (pendingStrictSourceSessionId ?? (activeSessionId ?? undefined))
: undefined,
requireSourceSessionReuse: reuseTerminalTransport && Boolean(pendingStrictSourceSessionId),
...(reuseTerminalTransport ? {} : { reuseTransport: false }),
sourceSessionId: pendingStrictSourceSessionId
?? (activeSessionStatus === "connected" ? (activeSessionId ?? undefined) : undefined),
requireSourceSessionReuse: Boolean(pendingStrictSourceSessionId),
...(connectRequestKey ? { connectRequestKey } : undefined),
onConnectionCreated,
...(initialPath ? { initialPath } : undefined),
@@ -979,7 +907,6 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
pendingUploadRebindSettledRequestId,
pendingUploadRebindStartedIdRef,
sessions,
sftpBannerDecision,
startPendingUploadRebind,
]);
@@ -1381,10 +1308,6 @@ const SftpSidePanelInner: React.FC<SftpSidePanelProps> = ({
sftpDefaultViewMode={sftpDefaultViewMode}
activeHost={activeHost}
activeSessionId={activeSessionId}
bannerRequiresSingleChannel={
sftpBannerDecision?.sessionId === activeSessionId
&& sftpBannerDecision.singleChannel
}
focusedSessionId={focusedSessionId}
showWorkspaceHostHeader={showWorkspaceHostHeader}
renderOverlays={renderOverlays}
@@ -1433,7 +1356,6 @@ type SftpSidePanelInteractiveBodyProps = {
sftpDefaultViewMode: "list" | "tree";
activeHost: Host | null;
activeSessionId?: string | null;
bannerRequiresSingleChannel?: boolean;
focusedSessionId?: string | null;
showWorkspaceHostHeader: boolean;
renderOverlays: boolean;
@@ -1484,7 +1406,6 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
sftpDefaultViewMode,
activeHost,
activeSessionId = null,
bannerRequiresSingleChannel = false,
focusedSessionId = null,
showWorkspaceHostHeader,
renderOverlays,
@@ -1692,12 +1613,11 @@ 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;
}, [bannerRequiresSingleChannel, followTerminalCwdHost, onGetTerminalCwd]);
}, [followTerminalCwdHost, onGetTerminalCwd]);
const hasActiveWork = showTextEditor || !!permissionsState || showFileOpenerDialog
|| (sftp.activeFileWatchCountRef?.current ?? 0) > 0
+20 -85
View File
@@ -1,6 +1,4 @@
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";
@@ -47,7 +45,7 @@ import {
resolveTerminalContextLineWindow,
type TerminalContextReader,
} from "../domain/terminalContextRead";
import { classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from "../domain/host";
import { classifyDistroId, shouldProbeSessionCwd } from "../domain/host";
import { shouldCollectServerStats } from "../domain/systemManager/systemTarget";
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
import { CONNECTION_PROGRESS_START } from "./terminal/connectionProgress";
@@ -203,7 +201,6 @@ import {
import {
createTerminalCwdTracker,
invalidateTerminalCwdAfterCommand,
shouldPreserveTerminalCwdAcrossCommand,
resolvePreferredTerminalCwd,
type TerminalCwdChangeMeta,
} from "./terminal/sftpCwd";
@@ -838,15 +835,6 @@ 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;
@@ -1077,17 +1065,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
// Broadcast to other sessions if broadcast mode is enabled
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);
if (!sensitive && isBroadcastEnabledRef.current && onBroadcastInputRef.current) {
onBroadcastInputRef.current(text, sessionId);
}
// ESC-prefixed writes (Esc+. yank-last-arg) are shell editor commands.
@@ -1160,15 +1139,12 @@ 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: skipBackendPwd
? async () => ({ success: false })
: (id, pwdOptions) => terminalBackend.getSessionPwd(id, pwdOptions),
preferFreshBackend: skipBackendPwd ? false : options?.preferFreshBackend,
getSessionPwd: (id, options) => terminalBackend.getSessionPwd(id, options),
preferFreshBackend: options?.preferFreshBackend,
allowRendererFallback: options?.allowRendererFallback,
requireActiveShellCwd: options?.requireActiveShellCwd,
});
@@ -2404,17 +2380,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const cwdAwareOnCommandSubmitted = useCallback((
...args: Parameters<NonNullable<typeof onCommandSubmitted>>
) => {
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]);
invalidateTerminalCwdAfterCommand(
terminalCwdTracker,
sessionId,
() => { knownCwdRef.current = undefined; },
onTerminalCwdChange,
);
onCommandSubmitted?.(...args);
}, [onCommandSubmitted, onTerminalCwdChange, sessionId, terminalCwdTracker]);
const pluginAwareOnCommandCompleted = useCallback(() => {
pluginTerminalLifecycle.onCommandCompleted();
void xtermRuntimeRef.current?.pluginProviderHost?.commandCompleted();
@@ -3297,26 +3270,15 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const broadcastUserPasteData = useCallback((
data: string,
options?: { lineDelayMs?: number; sensitive?: boolean },
options?: { lineDelayMs?: number },
) => {
if (
shouldBroadcastDuringSensitivePrompt({
sensitivePromptActive: passwordPromptActiveRef.current,
broadcastPasswordBypass: broadcastPasswordBypassRef.current,
})
!passwordPromptActiveRef.current
&& sessionRef.current
&& isBroadcastEnabledRef.current
&& onBroadcastInputRef.current
) {
// 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);
onBroadcastInputRef.current(data, sessionId, options);
return true;
}
return false;
@@ -3330,10 +3292,6 @@ 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
@@ -3388,32 +3346,13 @@ 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.
// 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, {
const sensitive = passwordPromptActiveRef.current;
if (!sensitive && options?.broadcast !== false && isBroadcastEnabledRef.current && onBroadcastInputRef.current) {
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);
@@ -3443,7 +3382,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
await runAutomationScript({
snippet,
sessionId,
initiatedBy: 'user',
sessionMeta: {
connected: true,
name: scriptSessionName,
@@ -3483,7 +3421,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
isBroadcastEnabledRef,
onBroadcastInputRef,
passwordPromptActiveRef,
broadcastPasswordBypassRef,
isLocalConnection,
supportsRemoteImagePaste,
autoUploadClipboardImageOnPasteRef,
@@ -4074,7 +4011,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
terminalBackend,
isSensitiveInput: () => passwordPromptActiveRef.current,
scrollOnPasteRef,
broadcastPasswordBypassRef,
onPasteData: broadcastUserPasteData,
scrollToBottomAfterProgrammaticInput,
containerRef,
@@ -4317,7 +4253,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
onOpenExternalError,
isBroadcastEnabledRef,
onBroadcastInputRef,
broadcastPasswordBypassRef,
snippetsRef,
onSnippetShortkeyRef,
sessionId,
@@ -4624,7 +4559,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
onWake: wakeFromHibernateRuntime,
});
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 });
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, 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 (
<>
+18 -80
View File
@@ -27,7 +27,6 @@ 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,
@@ -118,7 +117,7 @@ import {
type RendererCwdSource,
type TerminalCwdChangeMeta,
} from './terminal/sftpCwd';
import { classifyDistroId, hostRestrictsExtraSshChannels, shouldProbeSessionCwd } from '../domain/host';
import { classifyDistroId, shouldProbeSessionCwd } from '../domain/host';
import {
collectSidePanelPanes,
sidePanelLayoutHasTool,
@@ -742,14 +741,6 @@ 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);
@@ -1250,13 +1241,10 @@ 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 || (!passwordBypass && isTerminalSensitiveInputActive(sourceSessionId))) return [];
if (!paced.targets || isTerminalSensitiveInputActive(sourceSessionId)) return [];
paced.targets = paced.targets.filter(target => isTerminalBroadcastInputCurrent(target)
&& (passwordBypass || !isTerminalSensitiveInputActive(target.sessionId)));
&& !isTerminalSensitiveInputActive(target.sessionId));
}
const targetSessionIds = resolveTerminalBroadcastTargetIds({
sessions: sessionsRef.current,
@@ -1265,7 +1253,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 => passwordBypass || !isTerminalSensitiveInputActive(id)).map(id => {
paced.targets = targetSessionIds.filter(id => !isTerminalSensitiveInputActive(id)).map(id => {
markTerminalBroadcastUserInput(id);
terminalBackend.interruptSession(id, undefined, { cancelPendingWritesOnly: true });
return captureTerminalBroadcastInput(id);
@@ -1287,9 +1275,6 @@ 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;
@@ -1312,15 +1297,10 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
terminalBackend.interruptSession(session.id);
continue;
}
if (!passwordBypass && isTerminalSensitiveInputActive(session.id)) continue;
if (isTerminalSensitiveInputActive(session.id)) continue;
terminalBackend.writeToSession(session.id, data, {
automated: options?.automated === true,
// 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),
sensitive: false,
...(lineDelayMs ? { lineDelayMs } : {}),
});
deliveredSessionIds.push(session.id);
@@ -1343,7 +1323,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
visibleSftpHost,
sessionHost,
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
})) return;
const osc7SignalAtCommand = terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0;
@@ -1359,14 +1338,13 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (cwdProbeGenerationRef.current.get(sessionId) !== probeGeneration) return false;
const host = sessionHostsMapRef.current.get(sessionId);
if (!host) return false;
const hostDeviceClass = classifyDistroId(host.distro);
const hostIsNetworkDevice =
host.deviceType === 'network' || hostDeviceClass === 'network-device';
const detectedDeviceClass = classifyDistroId(host.distro);
const isNetworkDevice =
host.deviceType === 'network' || detectedDeviceClass === 'network-device';
const info = await terminalBackend.getSessionRemoteInfo?.(sessionId);
return shouldProbeSessionCwd({
isNetworkDevice: hostIsNetworkDevice,
isNetworkDevice,
remoteSshVersion: info?.remoteSshVersion,
restrictExtraSshChannels: hostRestrictsExtraSshChannels(host),
});
},
onProbedCwd: (cwd) => {
@@ -1574,18 +1552,14 @@ 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: skipBackendPwd
? async () => ({ success: false })
: (id, pwdOptions) => terminalBackend.getSessionPwd(id, pwdOptions),
preferFreshBackend: skipBackendPwd ? false : options?.preferFreshBackend,
getSessionPwd: (id, options) => terminalBackend.getSessionPwd(id, options),
preferFreshBackend: options?.preferFreshBackend,
allowRendererFallback: options?.allowRendererFallback,
requireActiveShellCwd: options?.requireActiveShellCwd,
});
@@ -2155,7 +2129,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
await runAutomationScript({
snippet,
sessionId,
initiatedBy: 'user',
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
});
} catch (err) {
@@ -2181,7 +2154,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
await runAutomationScript({
snippet,
sessionId,
initiatedBy: 'user',
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
});
} catch (err) {
@@ -2267,7 +2239,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
await runAutomationScript({
snippet,
sessionId,
initiatedBy: 'user',
sessionMeta: buildScriptSessionMeta(sessionId, sessionsRef.current, hosts),
});
} catch (err) {
@@ -2337,7 +2308,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const runOnSession = (sid: string) => runAutomationScript({
snippet,
sessionId: sid,
initiatedBy: 'user',
sessionMeta: buildScriptSessionMeta(sid, sessionsRef.current, hosts),
});
if (mode === 'sequential') {
@@ -2387,55 +2357,29 @@ 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 && (broadcastPasswordBypass || !focusedSensitive)) {
if (broadcastEnabled && !focusedSensitive) {
const allSessionIds = sessionsRef.current
.filter((session) => session.workspaceId === activeWorkspace.id)
.map((session) => session.id);
for (const sid of allSessionIds) {
const recipientSensitive = isTerminalSensitiveInputActive(sid);
if (!broadcastPasswordBypass && recipientSensitive) continue;
if (isTerminalSensitiveInputActive(sid)) continue;
const executor = snippetExecutorsRef.current.get(sid);
if (executor) {
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));
},
pendingSends.push(Promise.resolve(executor(text, false, { broadcast: false })).then(
(sent) => sent && !isTerminalSensitiveInputActive(sid),
));
} else {
const session = sessionsRef.current.find((candidate) => candidate.id === sid);
if (!session || !canUseDirectSessionWriteFallback(session)) continue;
// 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;
terminalBackend.writeToSession(sid, payload, { sensitive: false });
recordHistory = recordHistory || session.status === 'connected';
}
}
@@ -2463,13 +2407,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}
}
const results = await Promise.allSettled(pendingSends);
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;
return recordHistory || results.some((result) => result.status === 'fulfilled' && result.value);
}, [isBroadcastEnabled, terminalBackend]);
const sessionLogConfig = useMemo(
+10 -29
View File
@@ -249,7 +249,7 @@ function formatToolResult(result: unknown): string {
const obj = JSON.parse(parsed);
if (obj && typeof obj === 'object') parsed = obj;
} catch {
return result as string;
return parsed;
}
}
@@ -272,7 +272,6 @@ 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;
@@ -293,7 +292,6 @@ 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> {
@@ -323,8 +321,8 @@ async function copyTextToClipboard(text: string): Promise<boolean> {
}
export const ToolCall = ({
name, args, result, isError, isLoading, isInterrupted, approvalTarget,
approvalStatus, approvalId, onApprove, onReject, onApproveOnce, onAlwaysAllow, alwaysAllowLabel, alwaysAllowTitle,
name, args, result, isError, isLoading, isInterrupted,
approvalStatus, approvalId, onApprove, onReject, onApproveOnce, onAlwaysAllow, alwaysAllowLabel,
className, ...props
}: ToolCallProps) => {
const { t } = useI18n();
@@ -522,47 +520,31 @@ 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">
{(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">
{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">
{t('ai.chat.targetLabel')}
</span>
{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 && (
{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>
@@ -674,7 +656,6 @@ 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>
-1
View File
@@ -843,7 +843,6 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
<ToolCall
name={req.toolName}
args={req.args}
approvalTarget={req.target}
isLoading={false}
isInterrupted={false}
approvalStatus={'pending'}
+14 -95
View File
@@ -6,7 +6,6 @@
import React, { useCallback, useEffect, useState } from 'react';
import { ToolCall } from '../ai-elements/tool-call';
import { Button } from '../ui/button';
import {
onApprovalCleared,
onApprovalRequest,
@@ -16,7 +15,6 @@ import {
} from '../../infrastructure/ai/shared/approvalGate';
import {
buildGrantsFromApproval,
createPermissionGrantId,
resolveCapabilityId,
} from '../../infrastructure/ai/harness/permissionGrants';
import { useI18n } from '../../application/i18n/I18nProvider';
@@ -63,10 +61,7 @@ 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)
.map((grant) => request.target?.hostId
? { ...grant, sessionPattern: `host:${request.target.hostId}` }
: grant);
const persistGrants = buildGrantsFromApproval(capabilityId, request.args, request.chatSessionId);
resolveApproval(toolCallId, { approved: true, persistGrants });
setPendingApprovals((prev) => {
const next = new Map(prev);
@@ -75,35 +70,6 @@ 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) => {
@@ -118,7 +84,7 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
return (
<div
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"
className="pointer-events-auto fixed bottom-4 right-4 z-[80] flex w-[min(420px,calc(100vw-2rem))] flex-col gap-2"
data-testid="external-mcp-approvals-host"
>
<div className="rounded-lg border border-border/60 bg-background/95 p-3 shadow-lg backdrop-blur-sm">
@@ -127,65 +93,18 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
</div>
<div className="space-y-2">
{entries.map(([id, req]) => (
<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>
<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>
</div>
-17
View File
@@ -345,23 +345,6 @@ 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,34 +50,4 @@ 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,8 +6,6 @@ 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',
@@ -32,16 +30,8 @@ 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 {
@@ -94,26 +84,6 @@ 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 {
@@ -121,11 +91,15 @@ 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 = collectCliCommandWords(afterCli).join(' ');
const commandKey = afterCli
.split(/\s+/)
.filter((part) => part && !part.startsWith('-'))
.slice(0, 3)
.join(' ');
return CLI_ARTIFACT_TOOL_NAMES.get(commandKey);
}
@@ -11,13 +11,6 @@ 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,7 +26,6 @@ export type VaultArtifactVisualKind =
| 'noteUpdate'
| 'noteRead'
| 'noteList'
| 'noteImport'
| 'host'
| 'hostCreate'
| 'hostImport'
@@ -55,7 +54,6 @@ 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' },
@@ -85,7 +83,6 @@ 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';
@@ -101,7 +98,6 @@ 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';
@@ -143,8 +139,6 @@ 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,20 +16,6 @@ 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,7 +84,6 @@ 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',
@@ -222,13 +221,6 @@ 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);
+6 -39
View File
@@ -226,7 +226,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
codebuddy: string;
opencode: string;
grok: string;
mimo: string;
} | null>(null);
if (!initialManagedPathsRef.current) {
initialManagedPathsRef.current = getInitialManagedAgentPaths(externalAgents);
@@ -299,12 +298,6 @@ 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],
@@ -355,7 +348,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
return () => {
mountedRef.current = false;
codexRequestIdRef.current += 1;
for (const key of ["codex", "claude", "copilot", "cursor", "codebuddy", "opencode", "grok", "mimo"] as ManagedAgentKey[]) {
for (const key of ["codex", "claude", "copilot", "cursor", "codebuddy", "opencode", "grok"] as ManagedAgentKey[]) {
agentPathRequestIds[key] = (agentPathRequestIds[key] ?? 0) + 1;
}
};
@@ -378,9 +371,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
? setCodebuddyPathInfo
: agentKey === "opencode"
? setOpencodePathInfo
: agentKey === "grok"
? setGrokPathInfo
: setMimoPathInfo;
: setGrokPathInfo;
setInfo(result);
@@ -423,9 +414,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
? setIsResolvingCodebuddy
: agentKey === "opencode"
? setIsResolvingOpencode
: agentKey === "grok"
? setIsResolvingGrok
: setIsResolvingMimo;
: setIsResolvingGrok;
setResolving(true);
const requestId = (agentPathRequestIdRef.current[agentKey] ?? 0) + 1;
@@ -466,9 +455,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
? setCodebuddyPathInfo
: agentKey === "opencode"
? setOpencodePathInfo
: agentKey === "grok"
? setGrokPathInfo
: setMimoPathInfo;
: setGrokPathInfo;
setInfo(result);
return result;
}
@@ -507,7 +494,6 @@ 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])
@@ -768,9 +754,7 @@ 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",
@@ -782,7 +766,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
codexPath: result?.path || customPath.trim() || undefined,
});
}
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, mimoCustomPath, resolveAgentPath, refreshCodexIntegration]);
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, resolveAgentPath, refreshCodexIntegration]);
const handleResetCustomPath = useCallback(async (agentKey: ManagedAgentKey) => {
if (agentKey === "codex") {
@@ -797,8 +781,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
setOpencodeCustomPath("");
} else if (agentKey === "grok") {
setGrokCustomPath("");
} else if (agentKey === "mimo") {
setMimoCustomPath("");
}
const result = await resolveAgentPath(agentKey, "", {
@@ -1225,21 +1207,6 @@ 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,8 +121,6 @@ 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;
@@ -175,8 +173,6 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
setToggleWindowHotkey,
closeToTray,
setCloseToTray,
showTrayIcon,
setShowTrayIcon,
autoLaunchEnabled,
setAutoLaunchEnabled,
autoLaunchSupported,
@@ -1317,23 +1313,6 @@ 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>
@@ -602,17 +602,6 @@ 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")}
@@ -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" | "ai.mimo";
i18nPrefix?: "ai.copilot" | "ai.cursor" | "ai.opencode" | "ai.grok";
allowEmptyCheck?: boolean;
showCustomPathInput?: boolean;
/** Grok only: ACP (default) vs headless streaming-json. */
@@ -38,7 +38,6 @@ 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];
@@ -53,7 +52,7 @@ const GrantCapabilitySelect: React.FC<{
>
{selectOptions.map((capabilityId) => (
<option key={capabilityId} value={capabilityId}>
{capabilityId === '*' ? t('ai.externalMcp.allowHost') : capabilityId}
{capabilityId}
</option>
))}
</select>
@@ -205,11 +204,6 @@ 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,9 +111,7 @@ export function buildManagedAgentState(
? { ...(existingManaged?.env ?? {}), CODEBUDDY_CODE_PATH: pathInfo.path }
: agentKey === "opencode"
? { ...(existingManaged?.env ?? {}), OPENCODE_BIN: pathInfo.path }
: agentKey === "mimo"
? { ...(existingManaged?.env ?? {}), MIMOCODE_BIN: pathInfo.path }
: existingManaged?.env;
: existingManaged?.env;
const cursorAuthMode = agentKey === "cursor"
? (existingManaged?.cursorAuthMode
?? (pathInfo.authSource === "cli-login" || pathInfo.cliLoginOk ? "cli-login" : "api-key"))
@@ -237,6 +235,5 @@ export function getInitialManagedAgentPaths(agents: ExternalAgentConfig[]) {
codebuddy: getAutoManagedAgentStoredPath(agents, "codebuddy") ?? "",
opencode: getAutoManagedAgentStoredPath(agents, "opencode") ?? "",
grok: getAutoManagedAgentStoredPath(agents, "grok") ?? "",
mimo: getAutoManagedAgentStoredPath(agents, "mimo") ?? "",
};
}
-6
View File
@@ -235,12 +235,6 @@ export const AGENT_DEFAULTS: Record<string, Omit<ExternalAgentConfig, "id" | "co
icon: "grok",
sdkBackend: "grok",
},
mimo: {
name: "MiMo Code",
args: [],
icon: "mimo",
sdkBackend: "mimo",
},
};
// ---------------------------------------------------------------------------
-10
View File
@@ -51,7 +51,6 @@ interface SftpPaneDialogsProps {
showDeleteConfirm: boolean;
setShowDeleteConfirm: (open: boolean) => void;
deleteTargets: string[];
deleteError?: string | null;
handleDelete: () => void;
isDeleting: boolean;
// Host picker (connected view)
@@ -105,7 +104,6 @@ export const SftpPaneDialogs: React.FC<SftpPaneDialogsProps> = ({
showDeleteConfirm,
setShowDeleteConfirm,
deleteTargets,
deleteError,
handleDelete,
isDeleting,
showHostPicker,
@@ -353,24 +351,16 @@ 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}
+13 -34
View File
@@ -694,48 +694,27 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
</div>
)}
</div>
) : pane.error && !pane.reconnecting && pane.files.length === 0 ? (
) : pane.error && !pane.reconnecting ? (
<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>
) : (
<>
{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>
<div
className={cn(
shouldVirtualize ? "relative" : "divide-y divide-border/30",
)}
</>
style={shouldVirtualize ? { height: totalHeight } : undefined}
>
{fileRows}
</div>
)}
{/* Drop overlay */}
-2
View File
@@ -292,7 +292,6 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
renameName,
showDeleteConfirm,
deleteTargets,
deleteError,
isCreating,
isCreatingFile,
isRenaming,
@@ -737,7 +736,6 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
showDeleteConfirm={showDeleteConfirm}
setShowDeleteConfirm={setShowDeleteConfirm}
deleteTargets={deleteTargets}
deleteError={deleteError}
handleDelete={handleDelete}
isDeleting={isDeleting}
showHostPicker={showHostPicker}
+3 -19
View File
@@ -1,7 +1,6 @@
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";
@@ -63,7 +62,6 @@ interface UseSftpPaneDialogsResult {
isCreatingFile: boolean;
isRenaming: boolean;
isDeleting: boolean;
deleteError: string | null;
setShowHostPicker: (open: boolean) => void;
setHostSearch: (value: string) => void;
setShowNewFolderDialog: (open: boolean) => void;
@@ -112,13 +110,8 @@ export const useSftpPaneDialogs = ({
const [showRenameDialog, setShowRenameDialog] = useState(false);
const [renameTarget, setRenameTarget] = useState<string | null>(null);
const [renameName, setRenameName] = useState("");
const [showDeleteConfirm, setShowDeleteConfirmState] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = 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);
@@ -269,8 +262,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);
@@ -287,22 +280,15 @@ 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, onClearSelection, onDeleteFilesAtPath, onMutateSuccess, t]);
}, [isDeleting, onDeleteFilesAtPath, onMutateSuccess, onClearSelection]);
// entryPath is the full path; renameName is initialized to the basename
const openRenameDialog = useCallback((entryPath: string) => {
@@ -339,7 +325,6 @@ export const useSftpPaneDialogs = ({
}, []);
const openDeleteConfirm = useCallback((names: string[]) => {
setDeleteError(null);
setDeleteTargets(names);
setShowDeleteConfirm(true);
}, []);
@@ -359,7 +344,6 @@ export const useSftpPaneDialogs = ({
renameName,
showDeleteConfirm,
deleteTargets,
deleteError,
isCreating,
isCreatingFile,
isRenaming,
@@ -45,16 +45,3 @@ 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 &&/,
);
});
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff. Show more