Skip to content

The agent that grows with you

fix(desktop): only the last holder exits a shared SSH ControlMaster

Austin Pickett05d832d685ad
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index 2cd4224ae95..74e1853f05d 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -29,6 +29,7 @@ import {
validateSshTarget,
withRemoteTimeout
} from './ssh-connection'
+import { createControlMasterHolders } from './ssh-control-master-holders'
const execFileAsync = promisify(execFile)
@@ -681,7 +682,12 @@ test('close() does not report a signal-killed -O exit with empty stderr as unrea
const conn = new SshConnection(
{ host: 'box', user: 'me' },
- { spawnFn, controlDir: '/tmp/d', rememberLog: line => logs.push(line) }
+ {
+ spawnFn,
+ controlDir: '/tmp/d',
+ controlMasterHolders: createControlMasterHolders(),
+ rememberLog: line => logs.push(line)
+ }
)
await conn.open()
@@ -1251,7 +1257,12 @@ test('failed ControlMaster close disowns the master instead of retrying it', asy
// contract: a master that refuses -O exit is disowned — socket dropped,
// connection marked closed — so the next open dials fresh.
const spawnFn = scriptedSpawn([{ code: 255, stderr: 'master refused exit' }])
- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d' })
+
+ const conn = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn, mux: true, controlDir: '/tmp/d', controlMasterHolders: createControlMasterHolders() }
+ )
+
conn._opened = true
await conn.close()
assert.equal(conn._opened, false)
@@ -1374,3 +1385,145 @@ test('withRemoteTimeout kills a hung probe remotely instead of orphaning it (#11
assert.equal(grandStrays.trim(), '', 'watchdog killed the launcher’s grandchild too')
}
})
+
+// #97264: every attempt for one scope/host/identity hashes to the same
+// ControlPath, so a stale attempt's `-O exit` used to kill the master its
+// successor had attached to (the live backend's forward died ~40s after
+// "ready"). Script the master as shared state so each op reflects it.
+function sharedMasterSpawn() {
+ const state = { alive: false, exits: 0 }
+
+ const spawnFn = scriptedSpawn(args => {
+ if (args.includes('check')) {
+ return state.alive ? { code: 0 } : { code: 255, stderr: 'no control master' }
+ }
+
+ if (args.includes('-M')) {
+ state.alive = true
+
+ return { code: 0 }
+ }
+
+ if (args.includes('-O') && args.includes('exit')) {
+ state.exits += 1
+ state.alive = false
+
+ return { code: 0 }
+ }
+
+ return { code: 0 } // `exit 0` verify exec through the live master
+ })
+
+ return { spawnFn, state }
+}
+
+test('a stale attempt closing late leaves the master its successor attached to (#97264)', async () => {
+ const { spawnFn, state } = sharedMasterSpawn()
+ const controlMasterHolders = createControlMasterHolders()
+ const opts = { spawnFn, mux: true, controlDir: '/tmp/d', controlMasterHolders }
+
+ const stale = new SshConnection({ host: 'box', user: 'me' }, opts)
+ await stale.open()
+
+ const winner = new SshConnection({ host: 'box', user: 'me' }, opts)
+ await winner.open()
+ assert.equal(winner.controlPath, stale.controlPath, 'precondition: both attempts share one ControlPath')
+
+ await stale.close()
+ assert.equal(state.exits, 0, 'the stale attempt must not run -O exit on the shared socket')
+ assert.equal(await winner.isAlive(), true, 'the winning attempt keeps its master')
+
+ await winner.close()
+ assert.equal(state.exits, 1, 'the last holder still tears the master down')
+ assert.equal(state.alive, false)
+})
+
+test('a failed newer attempt does not kill the master an older live connection holds (#97264)', async () => {
+ const { spawnFn, state } = sharedMasterSpawn()
+ const controlMasterHolders = createControlMasterHolders()
+ const opts = { spawnFn, mux: true, controlDir: '/tmp/d', controlMasterHolders }
+
+ const live = new SshConnection({ host: 'box', user: 'me' }, opts)
+ await live.open()
+ const failed = new SshConnection({ host: 'box', user: 'me' }, opts)
+ await failed.open()
+
+ await failed.close()
+ assert.equal(state.exits, 0)
+ assert.equal(await live.isAlive(), true)
+})
+
+test('a stale close while a successor is still dialing does not exit the master (#97264)', async () => {
+ const controlMasterHolders = createControlMasterHolders()
+ const exits: string[][] = []
+
+ let releaseMaster: () => void = () => {}
+
+ const spawnFn: any = (_cmd, args) => {
+ if (args.includes('-O') && args.includes('exit')) {
+ exits.push(args)
+ }
+
+ if (args.includes('check')) {
+ return fakeChild({ code: 255 })
+ }
+
+ if (args.includes('-M')) {
+ const child = fakeChild({ hang: true })
+ releaseMaster = () => child.emit('close', 0, null)
+
+ return child
+ }
+
+ return fakeChild({ code: 0 })
+ }
+
+ const opts = { spawnFn, mux: true, controlDir: '/tmp/d', controlMasterHolders, connectTimeoutMs: 5000 }
+ const staleSpawn = scriptedSpawn(args => (args.includes('check') ? { code: 255 } : { code: 0 }))
+
+ const stale = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn: staleSpawn, mux: true, controlDir: '/tmp/d', controlMasterHolders }
+ )
+
+ await stale.open()
+
+ const successor = new SshConnection({ host: 'box', user: 'me' }, opts)
+ const dialing = successor.open()
+ await new Promise(resolve => setImmediate(resolve))
+
+ await stale.close()
+ assert.ok(
+ !staleSpawn.calls.some(args => args.includes('-O') && args.includes('exit')),
+ 'the stale attempt must not exit a master a dialing successor is attaching to'
+ )
+
+ releaseMaster()
+ await dialing
+ assert.equal(controlMasterHolders.count(successor.controlPath), 1)
+})
+
+test('a failed open releases its claim so the remaining holder can still close the master', async () => {
+ const controlMasterHolders = createControlMasterHolders()
+ const { spawnFn, state } = sharedMasterSpawn()
+
+ const live = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn, mux: true, controlDir: '/tmp/d', controlMasterHolders }
+ )
+
+ await live.open()
+
+ const authFail = scriptedSpawn(args =>
+ args.includes('check') ? { code: 255 } : { code: 255, stderr: 'Permission denied (publickey).' }
+ )
+
+ const broken = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn: authFail, mux: true, controlDir: '/tmp/d', controlMasterHolders }
+ )
+
+ await assert.rejects(() => broken.open())
+ await live.close()
+ assert.equal(state.exits, 1, 'the failed opener left no phantom claim behind')
+})
diff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.ts
index 63728dc6e5b..c52ea0b01ec 100644
--- a/apps/desktop/electron/ssh-connection.ts
+++ b/apps/desktop/electron/ssh-connection.ts
@@ -37,6 +37,7 @@ import os from 'node:os'
import path from 'node:path'
import { platformDefaultHermesHome } from './data-paths'
+import { type ControlMasterHolders, sharedControlMasterHolders } from './ssh-control-master-holders'
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
const DEFAULT_EXEC_TIMEOUT_MS = 20_000
@@ -650,6 +651,7 @@ class SshConnection {
_opened: boolean
_mux: boolean
_tunnels: Map<string, any>
+ _controlMasters: ControlMasterHolders
constructor(cfg, opts: any = {}) {
if (!cfg || !cfg.host) {
@@ -681,6 +683,7 @@ class SshConnection {
})
: ''
this._tunnels = new Map()
+ this._controlMasters = opts.controlMasterHolders || sharedControlMasterHolders
this._spawnFn = opts.spawnFn || spawn
@@ -760,6 +763,23 @@ class SshConnection {
// a live master is a no-op). No-mux: there is no master; validate auth +
// reachability with a one-shot `ssh true` so failures classify identically.
async open({ signal }: any = {}) {
+ if (!this._mux) {
+ return this._open({ signal })
+ }
+
+ // Claim the socket before dialing: a stale connection closing while this
+ // one is still attaching must not exit the master out from under it.
+ this._controlMasters.acquire(this.controlPath, this)
+
+ try {
+ await this._open({ signal })
+ } catch (error) {
+ this._controlMasters.release(this.controlPath, this)
+ throw error
+ }
+ }
+
+ async _open({ signal }: any = {}) {
if (this._mux) {
const controlDir = path.dirname(this.controlPath)
@@ -1156,9 +1176,13 @@ class SshConnection {
}
}
- // Tear down. Mux: exit the master (drops every forward with it). No-mux:
- // kill the tunnel children. Best-effort; never throws.
+ // Tear down. Mux: exit the master (drops every forward with it) unless
+ // another connection still holds the same ControlPath — then only release
+ // this connection's claim (#97264). No-mux: kill the tunnel children.
+ // Best-effort; never throws.
async close() {
+ const action = this._mux ? this._controlMasters.release(this.controlPath, this) : 'exit-master'
+
if (!this._opened) {
return
}
@@ -1183,6 +1207,15 @@ class SshConnection {
return
}
+ if (action === 'release-only') {
+ this._opened = false
+ this._logLine(
+ `control master left running: ${this._controlMasters.count(this.controlPath)} other connection(s) still use it`
+ )
+
+ return
+ }
+
const args = buildControlArgs(this, 'exit', [], this._connectTimeoutMs)
try {
diff --git a/apps/desktop/electron/ssh-control-master-holders.test.ts b/apps/desktop/electron/ssh-control-master-holders.test.ts
new file mode 100644
index 00000000000..d656c7b9d36
--- /dev/null
+++ b/apps/desktop/electron/ssh-control-master-holders.test.ts
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { controlMasterCloseAction, createControlMasterHolders } from './ssh-control-master-holders'
+
+test('controlMasterCloseAction exits the master only for the last holder', () => {
+ assert.equal(controlMasterCloseAction(0), 'exit-master')
+ assert.equal(controlMasterCloseAction(1), 'release-only')
+ assert.equal(controlMasterCloseAction(3), 'release-only')
+})
+
+test('holders are counted per ControlPath and released in any order', () => {
+ const holders = createControlMasterHolders()
+ const older = {}
+ const newer = {}
+ const elsewhere = {}
+
+ holders.acquire('/s/a.sock', older)
+ holders.acquire('/s/a.sock', newer)
+ holders.acquire('/s/b.sock', elsewhere)
+
+ assert.equal(holders.release('/s/a.sock', older), 'release-only', 'older closer leaves the newer holder its master')
+ assert.equal(holders.release('/s/a.sock', newer), 'exit-master')
+ assert.equal(holders.count('/s/a.sock'), 0)
+ assert.equal(holders.count('/s/b.sock'), 1, 'other sockets are unaffected')
+})
+
+test('re-acquiring and double-releasing are idempotent', () => {
+ const holders = createControlMasterHolders()
+ const conn = {}
+
+ holders.acquire('/s/a.sock', conn)
+ holders.acquire('/s/a.sock', conn)
+ assert.equal(holders.count('/s/a.sock'), 1)
+ assert.equal(holders.release('/s/a.sock', conn), 'exit-master')
+ assert.equal(holders.release('/s/a.sock', conn), 'exit-master', 'releasing an unknown holder never blocks a close')
+})
+
+test('an empty ControlPath (no-mux) is never tracked', () => {
+ const holders = createControlMasterHolders()
+
+ holders.acquire('', {})
+ assert.equal(holders.count(''), 0)
+})
diff --git a/apps/desktop/electron/ssh-control-master-holders.ts b/apps/desktop/electron/ssh-control-master-holders.ts
new file mode 100644
index 00000000000..20933423014
--- /dev/null
+++ b/apps/desktop/electron/ssh-control-master-holders.ts
@@ -0,0 +1,60 @@
+// Who may run `ssh -O exit` on a shared ControlMaster socket.
+//
+// Every SshConnection built for the same scope/host/identity hashes to the
+// same ControlPath, and ControlMaster=auto makes a later connection attach to
+// whatever master is already listening there. `-O exit` therefore tears down
+// the master for every attached connection, not just the caller. A stale
+// bootstrap attempt (timed out, superseded, or rolled back) that closes late
+// used to kill the master its successor had already attached to and forwarded
+// the live backend through (#97264). A connection now registers as a holder of
+// its ControlPath from the moment it starts opening, and only the last holder
+// to close exits the master; earlier closers just release their claim.
+
+export type ControlMasterCloseAction = 'exit-master' | 'release-only'
+
+export interface ControlMasterHolders {
+ acquire(controlPath: string, holder: object): void
+ // Drops `holder` and returns what its close should do with the master.
+ release(controlPath: string, holder: object): ControlMasterCloseAction
+ count(controlPath: string): number
+}
+
+// Pure decision: the master belongs to whoever is still attached. Exit it only
+// when the closing connection was the last holder of the socket.
+export function controlMasterCloseAction(otherHolders: number): ControlMasterCloseAction {
+ return otherHolders > 0 ? 'release-only' : 'exit-master'
+}
+
+export function createControlMasterHolders(): ControlMasterHolders {
+ const holders = new Map<string, Set<object>>()
+
+ return {
+ acquire(controlPath, holder) {
+ if (!controlPath) {
+ return
+ }
+
+ const set = holders.get(controlPath) || new Set<object>()
+ set.add(holder)
+ holders.set(controlPath, set)
+ },
+ release(controlPath, holder) {
+ const set = holders.get(controlPath)
+
+ set?.delete(holder)
+
+ if (set && set.size === 0) {
+ holders.delete(controlPath)
+ }
+
+ return controlMasterCloseAction(set?.size || 0)
+ },
+ count(controlPath) {
+ return holders.get(controlPath)?.size || 0
+ }
+ }
+}
+
+// Process-wide: every SshConnection in the Electron main process shares one
+// view of which sockets are still in use.
+export const sharedControlMasterHolders: ControlMasterHolders = createControlMasterHolders()