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): rebuild an adopted orphan master whose hook tunnel is dead

enesdef241dcf337
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 12286e785..e94da7224 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -420,9 +420,16 @@ describe('SshProjectManager', () => {
expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])
})
- it('adopts a LIVE orphan master instead of spawning a second one', async () => {
+ it('adopts a LIVE orphan master (whose hook tunnel verifies) instead of spawning a second one', async () => {
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
- const run = vi.fn(async (_args: string[]) => ({ code: 0, stdout: '' })) // live master answers
+ // Live master answers `-O check`; its reverse hook tunnel VERIFIES (the curl returns 204), so
+ // `remoteHooks.setup` succeeds and the orphan is kept — no fresh master is built.
+ const run = vi.fn(async (args: string[]) => {
+ const j = args.join(' ')
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }
+ return { code: 0, stdout: '' }
+ })
vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)
const rmSpy = vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
const statuses: string[] = []
@@ -440,6 +447,44 @@ describe('SshProjectManager', () => {
expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])
})
+ it('rebuilds a FRESH master when the adopted orphan cannot re-establish the hook tunnel', async () => {
+ // Fresh-launch-straight-to-SSH field bug: the adopted live-orphan master still serves the
+ // PREVIOUS run's reverse-hook forward (dead port), so `setup()`'s tunnel never verifies over it.
+ // The reverse tunnel — and with it every remote agent's status hooks — must come back WITHOUT
+ // any local activity, so connect() drops the orphan and rebuilds a fresh master, over which the
+ // tunnel verifies. The `%{http_code}` curl answers 000 (dead) until a fresh master is spawned.
+ let respawned = false
+ const spawnMaster = vi.fn(() => {
+ respawned = true
+ return { kill: vi.fn(), on: vi.fn() }
+ })
+ const run = vi.fn(async (args: string[]) => {
+ const j = args.join(' ')
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) return { code: 0, stdout: respawned ? '204' : '000' }
+ return { code: 0, stdout: '' }
+ })
+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)
+ const rmSpy = vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ const statuses: string[] = []
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
+ onStatus: (e) => statuses.push(e.status)
+ })
+ const info = await mgr.connect('p1', conn)
+ // The orphan was dropped (its `-O exit` ran + socket unlinked) and a fresh master spawned once.
+ expect(run.mock.calls.some(([a]) => a[0] === '-O' && a[1] === 'exit')).toBe(true)
+ expect(rmSpy).toHaveBeenCalledWith(controlPathFor('p1'), { force: true })
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ // The retried setup over the fresh master verified → the remote endpoint file is advertised.
+ expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])
+ })
+
it('skips the probe entirely when no socket file exists (the normal path)', async () => {
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
const checks: string[][] = []
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 8f27fd6d3..1514f894c 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -261,6 +261,11 @@ export class SshProjectManager {
// case (no leftover) skips straight to spawn with no extra round-trip.
let master: Conn['master']
let leftover = false
+ // A reused live-orphan master (adopted just below) still holds the PREVIOUS app run's reverse
+ // hook forward, bound to that run's now-dead hook port (`hookServer` picks a fresh ephemeral
+ // port every launch). If the tunnel then fails to verify, we rebuild a fresh master (below):
+ // this flag says the current master was inherited, so that rebuild only fires on the orphan path.
+ let reusedOrphan = false
try {
leftover = (await fs.stat(controlPath)).isSocket()
} catch {
@@ -269,6 +274,7 @@ export class SshProjectManager {
if (leftover && (await this.r.run(checkMasterArgs(conn, controlPath))).code === 0) {
// Live orphan: reuse it. `kill()` sends `-O exit` (what `disconnect` does anyway); the loop
// below succeeds on its first `-O check` and runs the normal post-connect setup.
+ reusedOrphan = true
master = {
kill: () => {
void this.r.run(exitMasterArgs(conn, controlPath)).catch(() => {})
@@ -286,7 +292,30 @@ export class SshProjectManager {
if (code === 0) {
// Master is up. Best-effort remote hook setup (reverse tunnel + endpoint + install);
// fail-open — a null result just means the remote agents run without hooks.
- const res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
+ let res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
+ // Fresh-launch-straight-to-SSH failure mode (field report: no RUNNING badges from remote
+ // sessions until a reconnect): an ADOPTED live-orphan master carries the previous app run's
+ // `-R <sock>:127.0.0.1:<oldPort>` reverse-hook forward. Its target port died with that run,
+ // and sshd can keep serving the stale listener across our rm+rebind (the "two fds on one
+ // sshd" `remote-hooks` notes), so `setup()`'s tunnel never verifies → it returns null → the
+ // remote endpoint file is never written → every remote hook POST vanishes → dead status for
+ // the whole session. A client-side forward-cancel can't reliably displace the leaked listener;
+ // the certain cure is a FRESH master, whose predecessor's forwards sshd tears down on `-O exit`.
+ // Rebuild once and retry — ONLY on the orphan+failure path, so a clean connect is untouched.
+ if (!res && reusedOrphan) {
+ await this.r.run(exitMasterArgs(conn, controlPath)).catch(() => {}) // drop the orphan + its forwards
+ await fs.rm(controlPath, { force: true }).catch(() => {})
+ reusedOrphan = false
+ master = this.r.spawnMaster(masterArgs(conn, controlPath))
+ this.conns.set(projectId, { conn, controlPath, master, remoteCwd })
+ for (let j = 0; j < 50 && !res; j++) {
+ if ((await this.r.run(checkMasterArgs(conn, controlPath))).code === 0) {
+ res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
+ break
+ }
+ await new Promise((r) => setTimeout(r, 100))
+ }
+ }
const hookEndpointPath = res?.endpointPath
// Resolve the remote $HOME once and retain it (the hook setup above also learns it but
// doesn't surface it). Phase 2b uses it to jail remote transcript reads. Fail-open: an