Skip to content

The agent that grows with you

fix(desktop): hold SSH-isolated keepalive WS so idle-exit won't retire owned siblings

KoNit-Ke78512893418
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 288c97e00d2..a4ae90e9cd6 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -378,6 +378,7 @@ import { ensureLoginShellPath } from './shell-path'
import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator'
import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'
import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'
+import { createSshIsolatedKeepaliveRegistry } from './ssh-isolated-keepalive'
import { createSshTeardownTracker } from './ssh-teardown'
import { createStreamThrottle } from './stream-throttle'
import { registerTerminalIpc } from './terminal-ipc'
@@ -10107,6 +10108,9 @@ async function buildRemoteConnection(
}
const sshConnections = new Map<string, any>()
+const sshIsolatedKeepalives = createSshIsolatedKeepaliveRegistry({
+ log: chunk => sshRememberLog(chunk)
+})
const desktopInstallationId = loadOrCreateInstallationId(DESKTOP_INSTALLATION_PATH)
// Managed SSH update lifecycle (#93042): while an update owns a registered
@@ -10317,6 +10321,7 @@ async function sshProbeReuseProof(baseUrl, token, spawnNonce) {
async function teardownSshConnection(profile) {
const scope = sshScopeKey(profile)
+ sshIsolatedKeepalives.stop(scope)
const state = sshConnections.get(scope)
if (!state) {
@@ -10590,6 +10595,7 @@ async function rollbackSshBootstrapResult(ssh, result, profile, sshConfig, bound
}
if (sshConnections.get(scope)?.ssh === ssh) {
+ sshIsolatedKeepalives.stop(scope)
sshConnections.delete(scope)
}
@@ -10624,6 +10630,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
}
ssh = null
+ sshIsolatedKeepalives.stop(scope)
sshConnections.delete(scope)
}
@@ -10749,6 +10756,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
// site may label a registry-qualified SSH scope as the primary backend.
primaryRegistryScope: metadata.primaryRegistryScope === true
})
+ sshIsolatedKeepalives.start(scope, { baseUrl: result.baseUrl, token: result.token })
},
rollback: error => rollbackSshBootstrapResult(ssh, result, profile, sshConfig, error)
})
@@ -12147,6 +12155,7 @@ async function drainManagedSshScope(scope) {
}
if (state && sshConnections.get(scope.key) === state) {
+ sshIsolatedKeepalives.stop(scope.key)
sshConnections.delete(scope.key)
}
}
@@ -17152,6 +17161,7 @@ app.on('before-quit', () => {
// Close the pooled keep-alive sockets on quit so lingering connections can't
// hold the event loop open or leak FDs past app teardown.
app.on('will-quit', () => {
+ sshIsolatedKeepalives.stopAll()
destroyKeepaliveAgents()
})
diff --git a/apps/desktop/electron/ssh-isolated-keepalive.test.ts b/apps/desktop/electron/ssh-isolated-keepalive.test.ts
new file mode 100644
index 00000000000..963a6762c88
--- /dev/null
+++ b/apps/desktop/electron/ssh-isolated-keepalive.test.ts
@@ -0,0 +1,216 @@
+/**
+ * #106935: Desktop main must hold a long-lived keep-alive WebSocket for every
+ * published SSH-isolated backend. Idle-exit (#101626) treats accepted WS as
+ * ownership liveness; renderer sockets can drop while sshConnections still owns
+ * the scope. Sticky artifacts (nonce / token file / lockfile) are NOT liveness.
+ */
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const here = path.dirname(fileURLToPath(import.meta.url))
+const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
+
+function makeFakeWs(): { FakeWs: new (url: string) => any; instances: any[] } {
+ const instances: any[] = []
+
+ class FakeWs {
+ url: string
+ closed = false
+ listeners: Record<string, Array<(event?: any) => void>> = {}
+
+ constructor(url: string) {
+ this.url = url
+ instances.push(this)
+ }
+
+ addEventListener(type: string, fn: (event?: any) => void) {
+ ;(this.listeners[type] ||= []).push(fn)
+ }
+
+ close() {
+ this.closed = true
+ }
+
+ emit(type: string, event?: any) {
+ for (const fn of this.listeners[type] || []) {
+ fn(event)
+ }
+ }
+ }
+
+ return { FakeWs, instances }
+}
+
+describe('main.ts wiring for SSH-isolated keep-alive WS (#106935)', () => {
+ it('starts a keep-alive WebSocket after publishing sshConnections', () => {
+ const publishStart = mainSource.indexOf('publish: () => {')
+ expect(publishStart).toBeGreaterThan(-1)
+
+ const publishSlice = mainSource.slice(publishStart, publishStart + 4_000)
+ const setIdx = publishSlice.indexOf('sshConnections.set(scope, {')
+ expect(setIdx).toBeGreaterThan(-1)
+
+ const afterSet = publishSlice.slice(setIdx)
+ expect(afterSet).toMatch(/sshIsolatedKeepalives\.start\(\s*scope/)
+ expect(afterSet).toMatch(/baseUrl:\s*result\.baseUrl/)
+ expect(afterSet).toMatch(/token:\s*result\.token/)
+ })
+
+ it('stops the keep-alive in teardownSshConnection so sockets cannot leak', () => {
+ const fnStart = mainSource.indexOf('async function teardownSshConnection(')
+ expect(fnStart).toBeGreaterThan(-1)
+
+ const nextFn = mainSource.indexOf('\nfunction activeSshTerminalTarget(', fnStart + 1)
+ const body = mainSource.slice(fnStart, nextFn === -1 ? fnStart + 1_200 : nextFn)
+
+ expect(body).toContain('sshConnections.delete(scope)')
+ expect(body).toMatch(/sshIsolatedKeepalives\.stop\(\s*scope/)
+ })
+
+ it('imports the keep-alive registry from the electron helper (not inline in main)', () => {
+ expect(mainSource).toMatch(/createSshIsolatedKeepaliveRegistry/)
+ expect(mainSource).toMatch(/from '\.\/ssh-isolated-keepalive'/)
+ })
+
+ it('starts keep-alive with the published scope as-is, including empty v1/global primary', () => {
+ const publishStart = mainSource.indexOf('publish: () => {')
+ const publishSlice = mainSource.slice(publishStart, publishStart + 4_000)
+ const afterSet = publishSlice.slice(publishSlice.indexOf('sshConnections.set(scope, {'))
+
+ // sshScopeKey(null) is '' for the settings/registry primary. Do not
+ // truthiness-guard the scope before arming — that would skip the live WS.
+ expect(afterSet).toMatch(/sshIsolatedKeepalives\.start\(\s*scope,\s*\{\s*baseUrl:\s*result\.baseUrl,\s*token:\s*result\.token\s*\}\)/)
+ expect(afterSet).not.toMatch(/if\s*\(\s*scope\s*\)/)
+ expect(afterSet).not.toMatch(/scope\s*\|\|/)
+ })
+})
+
+describe('ssh-isolated keep-alive registry (#106935)', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('holds an open WebSocket for the published baseUrl+token until stop', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
+
+ registry.start('conn:office::work', {
+ baseUrl: 'http://127.0.0.1:53101',
+ token: 'sess-work'
+ })
+
+ expect(instances).toHaveLength(1)
+ expect(instances[0].url).toBe('ws://127.0.0.1:53101/api/ws?token=sess-work')
+ expect(instances[0].closed).toBe(false)
+ expect(registry.isArmed('conn:office::work')).toBe(true)
+
+ instances[0].emit('open')
+ expect(instances[0].closed).toBe(false)
+ expect(registry.openUrl('conn:office::work')).toBe('ws://127.0.0.1:53101/api/ws?token=sess-work')
+
+ registry.stop('conn:office::work')
+ expect(instances[0].closed).toBe(true)
+ expect(registry.isArmed('conn:office::work')).toBe(false)
+ expect(registry.openUrl('conn:office::work')).toBeNull()
+ })
+
+ it('stop clears the keep-alive and does not leak a later reconnect', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({
+ WebSocketImpl: FakeWs,
+ reconnectDelayMs: 25
+ })
+
+ registry.start('scope-a', { baseUrl: 'http://127.0.0.1:9', token: 'tok' })
+ expect(instances).toHaveLength(1)
+
+ instances[0].emit('open')
+ registry.stop('scope-a')
+ expect(instances[0].closed).toBe(true)
+
+ instances[0].emit('close', { code: 1006 })
+ await new Promise(resolve => setTimeout(resolve, 50))
+ expect(instances).toHaveLength(1)
+ expect(registry.isArmed('scope-a')).toBe(false)
+ })
+
+ it('replaces a prior socket when the same scope is published again', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
+
+ registry.start('scope-a', { baseUrl: 'http://127.0.0.1:9', token: 'old' })
+ registry.start('scope-a', { baseUrl: 'http://127.0.0.1:9', token: 'new' })
+
+ expect(instances).toHaveLength(2)
+ expect(instances[0].closed).toBe(true)
+ expect(instances[1].closed).toBe(false)
+ expect(instances[1].url).toBe('ws://127.0.0.1:9/api/ws?token=new')
+ })
+
+ it('fail-open: a missing WebSocket impl does not throw and does not invent liveness', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: undefined })
+
+ expect(() => {
+ registry.start('scope-a', { baseUrl: 'http://127.0.0.1:9', token: 'tok' })
+ }).not.toThrow()
+ expect(registry.isArmed('scope-a')).toBe(false)
+ expect(registry.openUrl('scope-a')).toBeNull()
+ })
+
+ it('treats empty-string scope as the v1/global SSH primary and holds a WS until stop', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
+
+ registry.start('', { baseUrl: 'http://127.0.0.1:53100', token: 'primary' })
+
+ expect(instances).toHaveLength(1)
+ expect(instances[0].url).toBe('ws://127.0.0.1:53100/api/ws?token=primary')
+ expect(instances[0].closed).toBe(false)
+ expect(registry.isArmed('')).toBe(true)
+
+ instances[0].emit('open')
+ expect(registry.openUrl('')).toBe('ws://127.0.0.1:53100/api/ws?token=primary')
+
+ registry.stop('')
+ expect(instances[0].closed).toBe(true)
+ expect(registry.isArmed('')).toBe(false)
+ expect(registry.openUrl('')).toBeNull()
+ })
+
+ it('rejects missing baseUrl or token even when the scope is the empty primary key', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
+
+ registry.start('', { baseUrl: '', token: 'tok' })
+ registry.start('', { baseUrl: 'http://127.0.0.1:9', token: '' })
+ registry.start('', { baseUrl: 'http://127.0.0.1:9', token: undefined as unknown as string })
+ registry.start('', { baseUrl: undefined as unknown as string, token: 'tok' })
+
+ expect(instances).toHaveLength(0)
+ expect(registry.isArmed('')).toBe(false)
+ })
+
+ it('tracks independent scopes so tearing down one sibling cannot drop the other', async () => {
+ const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
+ const { FakeWs, instances } = makeFakeWs()
+ const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
+
+ registry.start('profile-less', { baseUrl: 'http://127.0.0.1:53101', token: 'a' })
+ registry.start('profile-work', { baseUrl: 'http://127.0.0.1:53102', token: 'b' })
+
+ expect(instances).toHaveLength(2)
+ registry.stop('profile-work')
+ expect(instances[0].closed).toBe(false)
+ expect(instances[1].closed).toBe(true)
+ expect(registry.isArmed('profile-less')).toBe(true)
+ })
+})
diff --git a/apps/desktop/electron/ssh-isolated-keepalive.ts b/apps/desktop/electron/ssh-isolated-keepalive.ts
new file mode 100644
index 00000000000..fc128e21e59
--- /dev/null
+++ b/apps/desktop/electron/ssh-isolated-keepalive.ts
@@ -0,0 +1,197 @@
+/**
+ * Long-lived keep-alive WebSocket from Electron main for every published
+ * SSH-isolated backend (#106935).
+ *
+ * `web_server_idle_exit` (#101626) treats accepted WebSockets as ownership
+ * liveness. Renderer sockets can vanish (`disposeSecondary` /
+ * `pruneSecondaryGateways`) while Desktop still owns the backend via
+ * `sshConnections`. Sticky spawn artifacts (owner-nonce, token file, lockfile)
+ * are NOT liveness and must not suppress idle-exit.
+ *
+ * Fail-open: if the keep-alive cannot connect, backend behavior is unchanged
+ * (it may still idle-exit). This module never consults nonce/lock/token files.
+ */
+import { buildGatewayWsUrl } from './connection-config'
+
+export type SshIsolatedKeepaliveTarget = {
+ baseUrl: string
+ token: string
+}
+
+export type SshIsolatedKeepaliveOptions = {
+ WebSocketImpl?: any
+ buildWsUrl?: (baseUrl: string, token: string) => string
+ log?: (message: string) => void
+ reconnectDelayMs?: number
+}
+
+type KeepaliveEntry = {
+ generation: number
+ reconnectTimer: ReturnType<typeof setTimeout> | null
+ scope: string
+ socket: { close?: () => void; url?: string } | null
+ target: SshIsolatedKeepaliveTarget
+}
+
+const DEFAULT_RECONNECT_DELAY_MS = 2_000
+
+function addListener(socket: any, type: string, handler: (event?: any) => void) {
+ if (typeof socket?.addEventListener === 'function') {
+ socket.addEventListener(type, handler)
+ return
+ }
+
+ if (typeof socket?.on === 'function') {
+ socket.on(type, handler)
+ }
+}
+
+export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepaliveOptions = {}) {
+ const WebSocketImpl =
+ 'WebSocketImpl' in options ? options.WebSocketImpl : (globalThis as { WebSocket?: unknown }).WebSocket
+ const buildWsUrl = options.buildWsUrl ?? buildGatewayWsUrl
+ const log = options.log
+ const reconnectDelayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS
+ const entries = new Map<string, KeepaliveEntry>()
+
+ function clearTimer(entry: KeepaliveEntry) {
+ if (entry.reconnectTimer == null) {
+ return
+ }
+
+ clearTimeout(entry.reconnectTimer)
+ entry.reconnectTimer = null
+ }
+
+ function closeSocket(entry: KeepaliveEntry) {
+ const socket = entry.socket
+ entry.socket = null
+
+ if (!socket) {
+ return
+ }
+
+ try {
+ socket.close?.()
+ } catch {
+ // Best-effort teardown; a dead socket must not block scope cleanup.
+ }
+ }
+
+ function scheduleReconnect(entry: KeepaliveEntry) {
+ if (entries.get(entry.scope) !== entry || entry.reconnectTimer != null) {
+ return
+ }
+
+ entry.reconnectTimer = setTimeout(() => {
+ entry.reconnectTimer = null
+ connect(entry)
+ }, reconnectDelayMs)
+ }
+
+ function connect(entry: KeepaliveEntry) {
+ if (entries.get(entry.scope) !== entry) {
+ return
+ }
+
+ if (typeof WebSocketImpl !== 'function') {
+ return
+ }
+
+ entry.generation += 1
+ const generation = entry.generation
+ clearTimer(entry)
+ closeSocket(entry)
+
+ let socket: any
+ let url: string
+
+ try {
+ url = buildWsUrl(entry.target.baseUrl, entry.target.token)
+ socket = new WebSocketImpl(url)
+ } catch (error) {
+ log?.(
+ `[ssh] keep-alive WS failed to open for ${entry.scope}: ${error instanceof Error ? error.message : error}`
+ )
+ scheduleReconnect(entry)
+ return
+ }
+
+ entry.socket = socket
+
+ const abandonIfStale = () => {
+ if (entries.get(entry.scope) !== entry || entry.generation !== generation) {
+ return
+ }
+
+ if (entry.socket === socket) {
+ entry.socket = null
+ }
+
+ scheduleReconnect(entry)
+ }
+
+ addListener(socket, 'close', abandonIfStale)
+ addListener(socket, 'error', abandonIfStale)
+ }
+
+ function start(scope: string, target: SshIsolatedKeepaliveTarget) {
+ // '' is a real published key: sshScopeKey(null) for the v1/global SSH primary.
+ if (typeof scope !== 'string') {
+ return
+ }
+
+ const baseUrl = typeof target?.baseUrl === 'string' ? target.baseUrl : ''
+ const token = typeof target?.token === 'string' ? target.token : ''
+
+ if (!baseUrl || !token) {
+ return
+ }
+
+ stop(scope)
+
+ if (typeof WebSocketImpl !== 'function') {
+ return
+ }
+
+ const entry: KeepaliveEntry = {
+ generation: 0,
+ reconnectTimer: null,
+ scope,
+ socket: null,
+ target: { baseUrl, token }
+ }
+ entries.set(scope, entry)
+ connect(entry)
+ }
+
+ function stop(scope: string) {
+ const entry = entries.get(scope)
+
+ if (!entry) {
+ return
+ }
+
+ entries.delete(scope)
+ entry.generation += 1
+ clearTimer(entry)
+ closeSocket(entry)
+ }
+
+ function stopAll() {
+ for (const scope of [...entries.keys()]) {
+ stop(scope)
+ }
+ }
+
+ function isArmed(scope: string) {
+ return entries.has(scope)
+ }
+
+ function openUrl(scope: string) {
+ const url = entries.get(scope)?.socket?.url
+ return typeof url === 'string' ? url : null
+ }
+
+ return { isArmed, openUrl, start, stop, stopAll }
+}