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.

feat(ssh): resync working agents when a reconnect re-verifies the hook tunnel

enes2cc6ae90cbb0
diff --git a/src/main/index.ts b/src/main/index.ts
index a1e42b8bb..86f85dee5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -62,7 +62,8 @@ import {
setNodeSessionName,
sessionNameSweepEntries,
nodeState,
- nodeSessionName
+ nodeSessionName,
+ workingNodes
} from '../core/agent-status-mirror'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
@@ -133,6 +134,7 @@ import { connectRelayClient, type RelayClientSession } from './remote/relay-clie
import { decodeOffer } from './remote/pairing'
import { loadOrCreatePeerKeyPair } from './remote/peer-identity'
import { initSshProject } from './remote-ssh/ssh-project'
+import { resyncProjectAgents } from './remote-ssh/agent-resync'
import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'
import { SshFs, sshAppendArgs, sshTailArgs, sshSizeArgs, sshWriteArgs } from './ssh-fs'
import { makeRemoteWorkspaceIO } from './remote-workspace-io'
@@ -1869,7 +1871,28 @@ app.whenReady().then(async () => {
})
.catch(() => {})
},
- askpassScriptPath
+ askpassScriptPath,
+ // The project's reverse hook tunnel is verified again on a freshly established master: every
+ // hook event fired while it was down is gone (the POSTs are fire-and-forget and nothing queues
+ // them on the host), so ask the host what is actually true for the nodes we still believe are
+ // working. Fire-and-forget — this must never delay or fail the connect that has already
+ // reported `connected`.
+ (_projectId, controlPath) => {
+ void resyncProjectAgents(controlPath, {
+ workingNodes,
+ remoteFor: (nodeId) => ptyManager.sshRemoteForNode(nodeId),
+ paneCommand: (nodeId) => ptyManager.paneCommand(nodeId),
+ readTranscriptTail: async (nodeId, sessionId) => {
+ // cwd/accountId are unknown here; the locator falls back to its cross-root glob, and a
+ // hook-fed ref (the common case) is already cached by session id.
+ const ref = await remoteTranscriptRefFor(sessionId, undefined, undefined, nodeId)
+ return ref ? await readRemoteTranscript(sessionId, ref) : null
+ },
+ emit: emitAgentStatus
+ }).catch(() => {
+ // best-effort: a failed resync leaves the stale sweep as the backstop, exactly as today
+ })
+ }
)
// Wake-from-sleep: re-validate every SSH master NOW instead of letting ServerAlive discover the
// dead TCP ~60s later — until it does, every remote terminal looks alive and is dead (no echo,
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 9c0fd0fb3..f2709d1e5 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -759,6 +759,67 @@ describe('SshProjectManager', () => {
})
})
+ // --- the reverse hook tunnel came back --------------------------------------------------------
+ //
+ // Hook POSTs are fire-and-forget, so every agent event fired while the master was down is gone.
+ // Production hangs the working-agent resync off this hook; the gate it needs is "a master was
+ // genuinely (re-)established", which connect()'s own control flow already answers.
+ describe('tunnel-verified hook', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ /** A manager whose remote hook tunnel VERIFIES: `$HOME` resolves and the verify curl answers
+ * 204, exactly as in the live-orphan tests above (the shared `makeMgr` runner answers neither,
+ * so its tunnel never verifies and no endpoint path is ever produced). No leftover socket, so
+ * connect() takes the ordinary fresh-master path — a genuine establish. */
+ function makeVerifiedMgr(
+ onTunnelVerified: (projectId: string, controlPath: string) => void,
+ httpCode = '204'
+ ) {
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ 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: httpCode }
+ return { code: 0, stdout: '' }
+ })
+ return new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ onTunnelVerified
+ })
+ }
+
+ it('fires after a genuine re-establish, naming the project and its control path', async () => {
+ const onTunnelVerified = vi.fn()
+ const mgr = makeVerifiedMgr(onTunnelVerified)
+ await mgr.connect('p1', conn, '/remote/cwd')
+ expect(onTunnelVerified).toHaveBeenCalledWith('p1', controlPathFor('p1'))
+ })
+
+ it('does NOT fire on the reuse branch — a live master never lost its tunnel', async () => {
+ const onTunnelVerified = vi.fn()
+ const mgr = makeVerifiedMgr(onTunnelVerified)
+ await mgr.connect('p1', conn, '/remote/cwd')
+ onTunnelVerified.mockClear()
+ await mgr.connect('p1', conn, '/remote/cwd') // `-O check` answers → early return
+ expect(onTunnelVerified).not.toHaveBeenCalled()
+ })
+
+ it('does NOT fire when the tunnel failed verification (there is nothing to resync through)', async () => {
+ const onTunnelVerified = vi.fn()
+ const mgr = makeVerifiedMgr(onTunnelVerified, '000') // dead listener → setup() returns null
+ await mgr.connect('p1', conn, '/remote/cwd')
+ expect(onTunnelVerified).not.toHaveBeenCalled()
+ })
+ })
+
// --- concurrent connect for one project ---------------------------------------------------
//
// Four callers can fire at once (watchdog revalidateAll, powerMonitor resume, the renderer's
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 6f0ac0e15..05b39dd61 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -77,6 +77,11 @@ interface Runners {
/** The last SSH connection just went away through a user-facing disconnect. Production schedules
* the app-private agent's shutdown, which is what "forget the key" actually means. */
onIdle?: () => void
+ /** A project's reverse hook tunnel was just VERIFIED on a freshly established master. Production
+ * resyncs that project's working agents: hook events lost while the tunnel was down are gone for
+ * good, so a node can be stranded at `working` until the 20-minute stale sweep. Deliberately not
+ * called on the reuse branch — a master that answered `-O check` never lost its tunnel. */
+ onTunnelVerified?: (projectId: string, controlPath: string) => void
/** Synchronous one-shot ssh, for `disconnectAll()` only: `before-quit` is sync, so an awaited
* `-O exit` never lands and the daemonized ControlPersist master survives the app. */
runSync?: (args: string[]) => void
@@ -517,6 +522,11 @@ export class SshProjectManager {
continue
}
const hookEndpointPath = res?.endpointPath
+ // The tunnel is live again on a master we just established (the reuse branch returned long
+ // before this line), so this is exactly the moment the hook events lost while it was down
+ // can be reconstructed from the host. Fire-and-forget: the resync runs several remote round
+ // trips and must never delay (or fail) the connect that is already reporting `connected`.
+ if (hookEndpointPath) this.r.onTunnelVerified?.(projectId, controlPath)
// 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
// unresolved home just disables the remote context meter / subagent transcript / search.
@@ -1381,7 +1391,11 @@ export function resolvePassphrasePrompt(requestId: string, value: string | null)
export function initSshProject(
onConnected?: (projectId: string) => void,
- askpassScriptPath?: string
+ askpassScriptPath?: string,
+ /** Passed straight through to the manager's `onTunnelVerified` (see Runners). It lives on the
+ * caller because the resync it drives needs main's agent-status funnel and transcript readers,
+ * none of which this module knows about. */
+ onTunnelVerified?: (projectId: string, controlPath: string) => void
): SshProjectManager {
const ssh = sshBin()
const scp = scpBin()
@@ -1436,6 +1450,7 @@ export function initSshProject(
// see scheduleStop — the connect dialog's throwaway browse master disconnects right before the
// real project connects).
onIdle: () => appSshAgent.scheduleStop(),
+ onTunnelVerified,
askpassWasCancelled: (masterPid) => askpassServer.wasCancelledBy(masterPid),
askpassIsPrompting: () => askpassServer.isPromptingAny(),
askpassAsked: (masterPid) => askpassServer.askedBy(masterPid),