Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(ssh): self-healing mux children + master watchdog — stop the silent per-exec reconnect churn

enes7a49b63ee381
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 2728c80aa..56913b4e5 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -21,6 +21,19 @@ import {
const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
+/** The option prefix every child ssh shares: self-healing mux (auto + persist, so the first
+ * child after a cleanly-gone master rebuilds it), keepalives for when the child owns the
+ * transport, and the identity key (auth matters exactly when mux is unavailable). */
+const childPrefix = [
+ '-o', 'ControlMaster=auto',
+ '-o', 'ControlPath=/s.sock',
+ '-o', 'ControlPersist=300',
+ '-o', 'ServerAliveInterval=15',
+ '-o', 'ServerAliveCountMax=4',
+ '-p', '2222',
+ '-i', '/k/id'
+]
+
describe('mkDirArgs', () => {
it('mkdir -p the quoted remote path, leaving a leading ~ unquoted', () => {
expect(mkDirArgs(conn, '/s.sock', '~/new dir').join(' ')).toContain(`mkdir -p ~/'new dir'`)
@@ -62,21 +75,24 @@ describe('masterArgs', () => {
})
describe('childArgs', () => {
- it('reuses the master socket (no new master) and appends a remote command', () => {
- expect(childArgs(conn, '/s.sock', 'tmux ls')).toEqual([
- '-o', 'ControlMaster=no',
- '-o', 'ControlPath=/s.sock',
- '-p', '2222',
- 'tmux ls'
- ])
+ it('muxes over the master socket, self-healing (auto + persist), and appends a remote command', () => {
+ expect(childArgs(conn, '/s.sock', 'tmux ls')).toEqual([...childPrefix, '[email protected]', 'tmux ls'])
+ })
+ it('omits -i when the connection has no identityFile', () => {
+ const bare = { host: 'h.example.com', user: 'deploy', port: 2222 }
+ const args = childArgs(bare, '/s.sock', 'tmux ls')
+ expect(args).not.toContain('-i')
+ expect(args.at(-2)).toBe('[email protected]')
+ })
+ it('regression: never ControlMaster=no — a dead master made every child a silent fresh direct connection', () => {
+ expect(childArgs(conn, '/s.sock')).not.toContain('ControlMaster=no')
})
})
describe('remoteTmuxHasSessionArgs', () => {
it('checks the remote socket for the node session', () => {
expect(remoteTmuxHasSessionArgs(conn, '/s.sock', 'nt-x')).toEqual([
- '-o', 'ControlMaster=no', '-o', 'ControlPath=/s.sock', '-p', '2222',
+ ...childPrefix,
`tmux -L ${RMT_TMUX_SOCKET} has-session -t nt-x`
])
@@ -87,7 +103,7 @@ describe('remoteTmuxSendKeysArgs', () => {
it('sends literal text with -l -- (no Enter) when enter is false', () => {
const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'hello', false)
expect(args).toEqual([
- '-o', 'ControlMaster=no', '-o', 'ControlPath=/s.sock', '-p', '2222',
+ ...childPrefix,
`tmux -L ${RMT_TMUX_SOCKET} send-keys -t nt-x -l -- 'hello'`
])
@@ -196,21 +212,21 @@ describe('scpArgs', () => {
describe('listDirArgs', () => {
it('lists directory entries of a quoted absolute path', () => {
expect(listDirArgs(conn, '/s.sock', '/srv/app')).toEqual([
- '-o', 'ControlMaster=no', '-o', 'ControlPath=/s.sock', '-p', '2222',
+ ...childPrefix,
`ls -1Ap '/srv/app'`
])
})
it('leaves a bare ~ unquoted so the remote shell expands it', () => {
expect(listDirArgs(conn, '/s.sock', '~')).toEqual([
- '-o', 'ControlMaster=no', '-o', 'ControlPath=/s.sock', '-p', '2222',
+ ...childPrefix,
`ls -1Ap ~`
])
})
it('tilde-expands a home-relative path, quoting the remainder', () => {
expect(listDirArgs(conn, '/s.sock', '~/my dir')).toEqual([
- '-o', 'ControlMaster=no', '-o', 'ControlPath=/s.sock', '-p', '2222',
+ ...childPrefix,
`ls -1Ap ~/'my dir'`
])
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 465d24c64..3e809de8f 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -59,9 +59,41 @@ export function masterArgs(conn: SshConnection, controlPath: string): string[] {
return args
}
-/** Args for a child ssh that reuses the master socket; `remote` is an optional remote command. */
+/**
+ * Args for a child ssh that reuses the master socket; `remote` is an optional remote command.
+ *
+ * `ControlMaster=auto`, NOT `no` — this is the self-heal half of the churn fix. With a live
+ * master both behave identically (the child muxes over the socket, no new TCP/auth). But when
+ * the master is gone and its socket file is absent, `no` made every child SILENTLY fall back to
+ * a fresh direct connection — one full TCP+auth+close per poll (~2-3/s while the app is open;
+ * a field report counted ~72k root logins in 24h on one host), invisible because everything
+ * kept working. With `auto` + `ControlPersist`, the FIRST such child rebuilds a persistent
+ * background master and every later child muxes over it. A leftover DEAD socket file still
+ * blocks `auto` from binding (ssh refuses: "ControlSocket … already exists, disabling
+ * multiplexing" → direct fallback), which is what the manager's watchdog exists for
+ * (`ssh-project.ts` — periodic `-O check`, unlink stale socket, respawn master).
+ */
export function childArgs(conn: SshConnection, controlPath: string, remote?: string): string[] {
- const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]
+ const args = [
+ '-o',
+ 'ControlMaster=auto',
+ '-o',
+ `ControlPath=${controlPath}`,
+ '-o',
+ 'ControlPersist=300',
+ // Meaningful only when this child ends up owning the transport (became the master, or fell
+ // back to a direct connection) — a mux client rides the master's keepalives. Same values as
+ // masterArgs, for the same reason: detect a dead link in ~60s instead of hanging half-dead.
+ '-o',
+ 'ServerAliveInterval=15',
+ '-o',
+ 'ServerAliveCountMax=4',
+ ...portArgs(conn)
+ ]
+ // The key matters exactly when mux is NOT available (fallback / becoming master) — the case
+ // the old childArgs ignored: with a non-default identityFile every fallback exec failed auth.
+ if (conn.identityFile) args.push('-i', conn.identityFile)
+ args.push(target(conn))
if (remote !== undefined) args.push(remote)
return args
}
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index ba4a464a1..52075eb03 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -438,6 +438,75 @@ describe('SshProjectManager', () => {
})
})
+describe('master watchdog', () => {
+ // Real (tiny) intervals + vi.waitFor: connect() awaits real fs promises, which fake timers
+ // can't flush deterministically.
+ afterEach(() => vi.restoreAllMocks())
+
+ function makeWatchedMgr() {
+ // Keep the re-establish path off the real fs — controlPathFor hashes into the REAL
+ // ~/.nodeterm/ssh-cm, and an unmocked stat+rm could unlink a genuinely live socket there.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ const statuses: string[] = []
+ // `-O check` fails while checkFails is true; spawning a fresh master heals it — models a
+ // master that died behind our back and comes back only when the watchdog respawns it.
+ let checkFails = false
+ const spawnMaster = vi.fn(() => {
+ checkFails = false
+ return { kill: vi.fn(), on: vi.fn() }
+ })
+ const run = vi.fn(async (args: string[]) =>
+ checkFails && args.includes('-O') ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ )
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: (e) => statuses.push(e.status)
+ })
+ return { mgr, statuses, spawnMaster, setMasterDead: () => (checkFails = true) }
+ }
+
+ it('a healthy master is only checked — never respawned, no reconnecting status', async () => {
+ const { mgr, statuses, spawnMaster } = makeWatchedMgr()
+ await mgr.connect('p1', conn)
+ mgr.startWatchdog(5)
+ await new Promise((r) => setTimeout(r, 60))
+ mgr.stopWatchdog()
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ expect(statuses).not.toContain('reconnecting')
+ })
+
+ it('an unnoticed master death is healed: reconnecting status + a fresh master', async () => {
+ const { mgr, statuses, spawnMaster, setMasterDead } = makeWatchedMgr()
+ await mgr.connect('p1', conn)
+ setMasterDead()
+ mgr.startWatchdog(5)
+ try {
+ await vi.waitFor(() => expect(spawnMaster).toHaveBeenCalledTimes(2))
+ } finally {
+ mgr.stopWatchdog()
+ }
+ expect(statuses).toContain('reconnecting')
+ expect(statuses.at(-1)).toBe('connected')
+ })
+
+ it('startWatchdog is idempotent and stopWatchdog ends the ticking', async () => {
+ const { mgr, spawnMaster, setMasterDead } = makeWatchedMgr()
+ await mgr.connect('p1', conn)
+ mgr.startWatchdog(5)
+ mgr.startWatchdog(5)
+ mgr.stopWatchdog()
+ setMasterDead()
+ await new Promise((r) => setTimeout(r, 40))
+ expect(spawnMaster).toHaveBeenCalledTimes(1) // no tick fired after stop
+ })
+})
+
describe('lastSshErrorLine', () => {
it('picks the actionable last line, skipping debug noise', () => {
const stderr = [
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 6044a6edf..e2b35f84c 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -55,6 +55,11 @@ const PROBE_RETRY_DELAYS_MS = [5_000, 15_000, 30_000]
/** Cap on how much master stderr we retain (a misconfigured host can spew) — enough for the error. */
const MASTER_STDERR_CAP = 8 * 1024
+/** Master watchdog cadence (see `startWatchdog`). Healthy cost per tick: ONE mux'd `-O check`
+ * per connected project — no new TCP/auth — so this can afford to be brisk; 45s bounds how
+ * long exec polls can churn direct-fallback connections after an unnoticed master death. */
+const MASTER_WATCHDOG_MS = 45_000
+
/**
* Pick the most informative line from an ssh master's stderr for the error banner. `-v` isn't
* passed, so ordinary stderr has no `debug` noise, but we still skip `debug*`/`Warning:` lines and
@@ -163,10 +168,44 @@ export class SshProjectManager {
/** Projects whose agent-status mirror was actually pushed — gates the disconnect cleanup so a
* transient folder-picker browse (never pushed) doesn't pay an extra rm round-trip. */
private statusPushed = new Set<string>()
+ private watchdog?: ReturnType<typeof setInterval>
+ /** Re-entrancy guard: a tick mid-reconnect (slow host) must not stack a second revalidation. */
+ private revalidating = false
constructor(private r: Runners) {
this.remoteHooks = new RemoteHooks({ run: r.run })
}
+ /**
+ * Master watchdog. Nothing subscribes to the master process's death, and it can't: with
+ * `ControlPersist` the real master daemonizes away from the child we spawned, and a network
+ * change (no sleep event, so no powerMonitor 'resume' → `revalidateAll`) kills it with no
+ * signal to us. Every child ssh then silently falls back to a direct connection — sessions
+ * keep "working", so the dead master goes unnoticed while each 5s poll opens a fresh
+ * TCP+auth connection (the ~72k-logins/day field report). The mux'd pty clients' exit-255
+ * does fire the renderer's SshReconnector, but ptys respawned before the master is back up
+ * land on direct fallback connections and never migrate. So: periodically re-run the
+ * idempotent `connect()` per cached entry (via `revalidateAll`) — a live master costs one
+ * mux'd `-O check`; a dead one gets the full re-establish (stale socket unlinked, master
+ * respawned, 'reconnecting' status so the renderer flow engages). Interval is unref'd so it
+ * never holds the process open; an empty conns map makes a tick a no-op.
+ */
+ startWatchdog(intervalMs = MASTER_WATCHDOG_MS): void {
+ if (this.watchdog) return
+ this.watchdog = setInterval(() => {
+ if (this.revalidating || this.conns.size === 0) return
+ this.revalidating = true
+ void this.revalidateAll().finally(() => {
+ this.revalidating = false
+ })
+ }, intervalMs)
+ this.watchdog.unref?.()
+ }
+
+ stopWatchdog(): void {
+ if (this.watchdog) clearInterval(this.watchdog)
+ this.watchdog = undefined
+ }
+
async connect(
projectId: string,
conn: SshConnection,
@@ -655,6 +694,7 @@ export class SshProjectManager {
* reverse hook forward dies with the master, so cancelling it is unnecessary on quit.
*/
disconnectAll(): void {
+ this.stopWatchdog()
for (const projectId of [...this.conns.keys()]) {
const c = this.conns.get(projectId)
if (!c) continue
@@ -713,6 +753,7 @@ export function initSshProject(
if (!win.isDestroyed()) win.webContents.send(IPC.sshProjectStatus, e)
}
})
+ mgr.startWatchdog()
ipcMain.handle(IPC.sshConnectProject, async (_e, projectId: string, conn: SshConnection, remoteCwd?: string) => {
const res = await mgr.connect(projectId, conn, remoteCwd)
// Connection is up (master in the map) → reconcile the remote project file with our cache.