From 9d876cf6d565d415cc6f44622deebc56c31a02bb Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Tue, 4 Aug 2026 11:58:07 +0800 Subject: [PATCH] fix(ssh): use fresh connections for connect automation --- components/Terminal.tsx | 7 ++- .../createTerminalSessionStarters.test.ts | 35 ++++++++++++ .../runtime/createTerminalSessionStarters.ts | 6 +++ .../createTerminalSessionStarters.types.ts | 3 ++ domain/hostConnectScripts.test.ts | 20 +++++++ domain/hostConnectScripts.ts | 10 ++++ electron/bridges/sshBridge.cjs | 2 +- .../sshBridge.connectionReuse.test.cjs | 54 +++++++++++++++++++ electron/bridges/sshBridge/startSession.cjs | 12 +++-- global.d.ts | 9 ++-- 10 files changed, 148 insertions(+), 10 deletions(-) diff --git a/components/Terminal.tsx b/components/Terminal.tsx index ea034f62b..dae26ede0 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -108,7 +108,11 @@ import { resumeScriptRun, stopScriptRun, } from "@/application/state/scriptAutomationCoordinator.ts"; -import { resolveConnectScriptsForHost, hasUnresolvedConnectScriptBindings } from "@/domain/hostConnectScripts.ts"; +import { + hasHostConnectAutomation, + hasUnresolvedConnectScriptBindings, + resolveConnectScriptsForHost, +} from "@/domain/hostConnectScripts.ts"; import { isVaultInitialized } from "@/application/state/vaultInitStore.ts"; import { netcattyBridge } from "@/infrastructure/services/netcattyBridge.ts"; import { ScriptExecutionOverlay } from "./terminal/ScriptExecutionOverlay"; @@ -2138,6 +2142,7 @@ const TerminalComponent: React.FC = ({ resolvedChainHosts, sessionId, reuseConnectionFromSessionId, + hasConnectionAutomation: hasHostConnectAutomation(host, snippets), isNetworkDevice, startupCommand, noAutoRun, diff --git a/components/terminal/runtime/createTerminalSessionStarters.test.ts b/components/terminal/runtime/createTerminalSessionStarters.test.ts index b4bfc75b9..ef975663e 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.test.ts @@ -436,6 +436,41 @@ test("startSSH tells the bridge to skip shell discovery for network devices", as assert.equal(capturedOptions?.skipShellPidDiscovery, true); }); +test("startSSH requests a fresh transport for ordinary opens with connection automation", async () => { + const captured: Record[] = []; + const terminalBackend = { + backendAvailable: () => true, + startSSHSession: async (options: Record) => { + captured.push(options); + return `ssh-session-${captured.length}`; + }, + onSessionData: () => noop, + onSessionExit: () => noop, + onChainProgress: () => noop, + writeToSession: noop, + resizeSession: noop, + }; + + await createTerminalSessionStarters(createStarterContext({ + hasConnectionAutomation: true, + terminalBackend, + }) as never).startSSH(createTermStub() as never); + await createTerminalSessionStarters(createStarterContext({ + hasConnectionAutomation: true, + reuseConnectionFromSessionId: "source-session", + terminalBackend, + }) as never).startSSH(createTermStub() as never); + await createTerminalSessionStarters(createStarterContext({ + hasConnectionAutomation: false, + terminalBackend, + }) as never).startSSH(createTermStub() as never); + + assert.equal(captured[0].reuseTransport, false); + assert.equal(captured[1].reuseTransport, undefined); + assert.equal(captured[1].sourceSessionId, "source-session"); + assert.equal(captured[2].reuseTransport, undefined); +}); + test("startSSH uses the system agent when a synced vault key cannot be decrypted", async () => { let capturedOptions: Record | null = null; const terminalBackend = { diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index b867ff719..ecd729a41 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -600,6 +600,12 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex // bridge silently falls back to a fresh connection if the source is // gone, so reconnect/retry after the source closed still works. sourceSessionId: ctx.reuseConnectionFromSessionId, + // Connect-time automation must see the complete login sequence. An + // explicit Copy/Split keeps its source-session reuse contract, while + // an ordinary open bypasses endpoint/idle transport reuse. + reuseTransport: ctx.hasConnectionAutomation && !ctx.reuseConnectionFromSessionId + ? false + : undefined, skipShellPidDiscovery: ctx.isNetworkDevice === true, }); }; diff --git a/components/terminal/runtime/createTerminalSessionStarters.types.ts b/components/terminal/runtime/createTerminalSessionStarters.types.ts index 14415e0dc..72bb5c62c 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.types.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.types.ts @@ -150,6 +150,9 @@ export type TerminalSessionStartersContext = { // Source session id to reuse an authenticated SSH connection from when this // terminal was created from an existing SSH session. reuseConnectionFromSessionId?: string; + // Hosts with connect-time automation need the initial login output. Ordinary + // opens therefore use a fresh connection instead of an endpoint-pooled one. + hasConnectionAutomation?: boolean; isNetworkDevice?: boolean; startupCommand?: string; noAutoRun?: boolean; diff --git a/domain/hostConnectScripts.test.ts b/domain/hostConnectScripts.test.ts index d33e959a6..4fd7a62e8 100644 --- a/domain/hostConnectScripts.test.ts +++ b/domain/hostConnectScripts.test.ts @@ -5,6 +5,7 @@ import { appendHostConnectScript, getGlobalConnectScripts, getHostConnectScriptIds, + hasHostConnectAutomation, migrateHostConnectScriptIds, reorderHostConnectScript, removeHostConnectScript, @@ -54,6 +55,25 @@ test('resolveConnectScriptsForHost runs globals before host queue and dedupes', assert.deepEqual(resolved.map((item) => item.id), ['global', 'both', 'host-only']); }); +test('hasHostConnectAutomation covers host, global, and unresolved connect scripts', () => { + assert.equal( + hasHostConnectAutomation( + { ...host, connectScriptIds: ['host-script'] }, + [script({ id: 'host-script', targets: ['host-a'] })], + ), + true, + ); + assert.equal( + hasHostConnectAutomation(host, [script({ id: 'global', targetsAllHosts: true })]), + true, + ); + assert.equal( + hasHostConnectAutomation({ ...host, loginScriptId: 'not-loaded-yet' }, []), + true, + ); + assert.equal(hasHostConnectAutomation(host, []), false); +}); + test('append updates host connectScriptIds order', () => { const snippets = [ script({ id: 'a', targets: ['host-a'] }), diff --git a/domain/hostConnectScripts.ts b/domain/hostConnectScripts.ts index e86bcc2d3..c878b124c 100644 --- a/domain/hostConnectScripts.ts +++ b/domain/hostConnectScripts.ts @@ -118,6 +118,16 @@ export function resolveConnectScriptsForHost(host: Host, snippets: Snippet[]): S return [...globals, ...hostScripts]; } +/** + * Whether connecting this host can run automation that depends on the initial + * login output. Missing referenced scripts still count: vault hydration or a + * later sync may restore them after the terminal has already started. + */ +export function hasHostConnectAutomation(host: Host, snippets: Snippet[]): boolean { + return hasUnresolvedConnectScriptBindings(host, snippets) + || resolveConnectScriptsForHost(host, snippets).length > 0; +} + export function appendHostConnectScript(host: Host, scriptId: string, snippets: Snippet[]): Host { const snippet = scriptById(snippets, scriptId); if (!snippet) return host; diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 7a465f7ae..a41018ebb 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -1108,7 +1108,7 @@ function isStrictAgentAuthFailure(options, err) { } function canReuseExistingSession(options) { - if (!options.sourceSessionId || options.x11Forwarding) return false; + if (options.reuseTransport === false || !options.sourceSessionId || options.x11Forwarding) return false; return Boolean(findReusableSession(sessions, options.sourceSessionId, { hostname: options.hostname, port: options.port || 22, diff --git a/electron/bridges/sshBridge.connectionReuse.test.cjs b/electron/bridges/sshBridge.connectionReuse.test.cjs index b45f14d0d..ac460a6bd 100644 --- a/electron/bridges/sshBridge.connectionReuse.test.cjs +++ b/electron/bridges/sshBridge.connectionReuse.test.cjs @@ -104,6 +104,32 @@ test("simultaneous normal opens of the same host make one physical SSH dial", as assert.equal(sessions.get("normal-1").connRef.count, 2); }); +test("reuseTransport false makes simultaneous same-host opens dial independently", async (t) => { + resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 }); + t.after(() => resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 })); + const { bridge, getClientConstructCount } = loadBridgeWithMockedSsh2(t, { connectReady: true }); + const sessions = new Map(); + const start = registerStartHandler(bridge, sessions); + const options = { + hostname: "10.0.0.51", + username: "alice", + port: 22, + authMethod: "password", + password: "secret", + useSshAgent: false, + verifyHostKeys: false, + reuseTransport: false, + }; + + await Promise.all([ + start({ sender: makeSender() }, { ...options, sessionId: "fresh-1" }), + start({ sender: makeSender() }, { ...options, sessionId: "fresh-2" }), + ]); + + assert.equal(getClientConstructCount(), 2); + assert.notEqual(sessions.get("fresh-1").conn, sessions.get("fresh-2").conn); +}); + function makeSender() { return { id: 1, @@ -312,6 +338,34 @@ test("Copy Tab reuses the source connection instead of dialing fresh", async (t) assert.equal(getConnectionReuseFallbackEvents(sender).length, 0, "successful reuse should not emit fallback"); }); +test("reuseTransport false bypasses a matching live source and connects fresh", async (t) => { + const { bridge, getClientConstructCount } = loadBridgeWithMockedSsh2(t, { connectReady: true }); + const sessions = new Map(); + const sourceConn = makeReusableConn(); + sessions.set("source", makeSourceSession(sourceConn, { hostname: "10.0.0.1", username: "alice" })); + + const start = registerStartHandler(bridge, sessions); + await start( + { sender: makeSender() }, + { + sessionId: "fresh", + hostname: "10.0.0.1", + username: "alice", + port: 22, + authMethod: "password", + password: "secret", + useSshAgent: false, + verifyHostKeys: false, + sourceSessionId: "source", + reuseTransport: false, + }, + ); + + assert.equal(getClientConstructCount(), 1); + assert.equal(sourceConn.openedShells.length, 0); + assert.notEqual(sessions.get("fresh").conn, sourceConn); +}); + test("Copy Tab records a distinct remote shell for each shared terminal", async (t) => { const { bridge } = loadBridgeWithMockedSsh2(t); const sessions = new Map(); diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index 83f854594..a83a1afe9 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -871,8 +871,9 @@ printf '%s\n' '${scanCompleteMarker}'`; // X11. For X11 hosts we deliberately skip reuse and make a fresh // connection so the duplicate keeps working X11 forwarding. const reuseEndpoint = buildConnectionReuseEndpoint(options); + const allowTransportReuse = options.reuseTransport !== false; - if (options.sourceSessionId && !options.x11Forwarding) { + if (allowTransportReuse && options.sourceSessionId && !options.x11Forwarding) { const sourceSession = findReusableSession(sessions, options.sourceSessionId, reuseEndpoint); if (sourceSession) { try { @@ -897,7 +898,7 @@ printf '%s\n' '${scanCompleteMarker}'`; // Idle-park / endpoint reuse: after the last tab returns its lease the // transport may still be warm. Open a new shell channel without re-auth. - if (!options.x11Forwarding && typeof findTransportByEndpoint === "function") { + if (allowTransportReuse && !options.x11Forwarding && typeof findTransportByEndpoint === "function") { // Shell park reuse requires exact agentForwarding match so disabling // ForwardAgent cannot reattach to a warm conn that still exposes the agent. const parked = findTransportByEndpoint(reuseEndpoint, { kind: "shell" }); @@ -938,7 +939,12 @@ printf '%s\n' '${scanCompleteMarker}'`; // for the same compatible endpoint can wait for this leader and then // open its own channel on the authenticated transport. let pendingDialCoordination = options._pendingDialState?.coordination || null; - if (!pendingDialCoordination && !options.x11Forwarding && typeof beginTransportDial === "function") { + if ( + allowTransportReuse + && !pendingDialCoordination + && !options.x11Forwarding + && typeof beginTransportDial === "function" + ) { const coordination = beginTransportDial(reuseEndpoint, { kind: "shell" }); if (coordination.role === "reuse" || coordination.role === "join") { try { diff --git a/global.d.ts b/global.d.ts index 517b9104a..0ee662e8b 100644 --- a/global.d.ts +++ b/global.d.ts @@ -165,11 +165,10 @@ declare global { // Skip POSIX process discovery when copying a network-device session. skipShellPidDiscovery?: boolean; /** - * When false, openSftp must dial a fresh SSH connection and must not - * borrow a parked/shared registry transport. Used for dedicated bulk - * transfer / restart-resume so transfers do not attach to a terminal - * conn that may die or leave checkpoint resume half-bound. - * Default true (browse / MFA-skip reuse of parked transports). + * When false, terminal/SFTP opens must dial a fresh SSH connection and + * must not borrow a live, parked, or in-flight registry transport. Used by + * connect-time terminal automation and dedicated bulk transfers. + * Default true (normal terminal, browse, and MFA-skip reuse). */ reuseTransport?: boolean; }