diff --git a/src/main/ipc/ssh.test.ts b/src/main/ipc/ssh.test.ts index e21975a78..a1db12efa 100644 --- a/src/main/ipc/ssh.test.ts +++ b/src/main/ipc/ssh.test.ts @@ -253,6 +253,27 @@ describe('SSH IPC handlers', () => { setCallbacks: vi.fn(), callbacksRef: { current: null as unknown } }) + type RelayDisposeCallback = (reason: 'shutdown' | 'connection_lost') => void + const relayReconnectDelaysMs = [500, 1000, 2000, 4000, 8000, 15_000] as const + const relayLostStabilizedMs = 5_000 + const createRelayLaunchResult = () => ({ + transport: { write: vi.fn(), onData: vi.fn(), onClose: vi.fn() }, + platform: 'linux-x64' + }) + const getLatestRelayDisposeCallback = (): RelayDisposeCallback => { + const calls = mockMux.onDispose.mock.calls + const callback = calls.at(-1)?.[0] as RelayDisposeCallback | undefined + expect(callback).toBeDefined() + return callback! + } + const useSlowRelayLaunchOnce = (delayMs: number): void => { + mockDeployAndLaunchRelay.mockImplementationOnce( + () => + new Promise((resolve) => { + setTimeout(() => resolve(createRelayLaunchResult()), delayMs) + }) + ) + } beforeEach(async () => { await resetSshHandlerStateForTests() @@ -621,6 +642,105 @@ describe('SSH IPC handlers', () => { } }) + it('keeps counting slow unstable relay reconnects until manual reconnect is required', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + try { + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + for (const delayMs of relayReconnectDelaysMs) { + useSlowRelayLaunchOnce(relayLostStabilizedMs + 1) + getLatestRelayDisposeCallback()('connection_lost') + await vi.advanceTimersByTimeAsync(delayMs + relayLostStabilizedMs + 1) + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + } + + getLatestRelayDisposeCallback()('connection_lost') + + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'error', + error: 'Relay channel kept dropping. Click Reconnect on the SSH target before retrying.', + reconnectAttempt: 0 + }) + } finally { + vi.useRealTimers() + } + }) + + it('reuses a fast relay reconnect after the post-ready stabilization window', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + try { + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + getLatestRelayDisposeCallback()('connection_lost') + await vi.advanceTimersByTimeAsync(relayReconnectDelaysMs[0]) + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + await vi.advanceTimersByTimeAsync(relayLostStabilizedMs + 1) + mockDeployAndLaunchRelay.mockClear() + mockPortForwardManager.removeAllForwards.mockClear() + + await expect(handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' })).resolves.toEqual({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + expect(mockPortForwardManager.removeAllForwards).not.toHaveBeenCalled() + expect(mockDeployAndLaunchRelay).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + it('forwards remote PTY events into the runtime', async () => { const runtime = { onPtyData: vi.fn(), diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 649d85f0d..15f95306c 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -176,11 +176,11 @@ const testingTargets = new Set() // both the local main process and the remote sshd in a tight loop. Track // per-target reconnect attempts and apply exponential backoff so the loop // terminates with a recoverable error instead of running forever. Successful -// `ready` resets the attempt counter for the next genuine drop. +// post-ready uptime resets the attempt counter for the next genuine drop. type RelayLostBackoffState = { attempts: number - lastAttemptStartedAt: number - pendingTimer: ReturnType | null + reconnectTimer: ReturnType | null + stabilizedTimer: ReturnType | null } const relayLostBackoff = new Map() const relayStateOverrides = new Map() @@ -197,8 +197,11 @@ const RELAY_LOST_STABILIZED_MS = 5_000 function clearRelayLostBackoff(targetId: string): void { const state = relayLostBackoff.get(targetId) - if (state?.pendingTimer) { - clearTimeout(state.pendingTimer) + if (state?.reconnectTimer) { + clearTimeout(state.reconnectTimer) + } + if (state?.stabilizedTimer) { + clearTimeout(state.stabilizedTimer) } relayLostBackoff.delete(targetId) } @@ -530,10 +533,14 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { // tight loop spawning relay deploys until the user force-quits. const state = relayLostBackoff.get(tid) ?? { attempts: 0, - lastAttemptStartedAt: 0, - pendingTimer: null + reconnectTimer: null, + stabilizedTimer: null } - if (state.pendingTimer) { + if (state.stabilizedTimer) { + clearTimeout(state.stabilizedTimer) + state.stabilizedTimer = null + } + if (state.reconnectTimer) { return } if (state.attempts >= RELAY_LOST_MAX_ATTEMPTS) { @@ -562,9 +569,8 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { 'Relay channel lost. Reconnecting...', state.attempts ) - state.pendingTimer = setTimeout(() => { - state.pendingTimer = null - state.lastAttemptStartedAt = Date.now() + state.reconnectTimer = setTimeout(() => { + state.reconnectTimer = null relayLostBackoff.set(tid, state) const liveConn = connectionManager?.getConnection(tid) if (!liveConn || !activeSessions.has(tid)) { @@ -584,12 +590,18 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { session.setOnReady((tid) => { const state = relayLostBackoff.get(tid) if (state) { - const stabilized = - state.lastAttemptStartedAt === 0 || - Date.now() - state.lastAttemptStartedAt >= RELAY_LOST_STABILIZED_MS - if (stabilized) { - relayLostBackoff.delete(tid) + if (state.stabilizedTimer) { + clearTimeout(state.stabilizedTimer) } + // Why: stabilization is post-ready uptime. Slow deployment time before + // `ready` does not prove the new relay survived user-visible work. + state.stabilizedTimer = setTimeout(() => { + const current = relayLostBackoff.get(tid) + if (current === state && !current.reconnectTimer) { + relayLostBackoff.delete(tid) + } + }, RELAY_LOST_STABILIZED_MS) + relayLostBackoff.set(tid, state) } clearRelayStateOverride(tid) if (!testingTargets.has(tid)) {