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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(ssh): restore the reconnect pieces missing from 576d606
enes4017201f7f39
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 66c6fa0c0..3a829db91 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -50,6 +50,8 @@ describe('masterArgs', () => {'-o', 'ControlPath=/ud/ssh-cm/p.sock','-o', 'ControlPersist=300','-o', 'BatchMode=no',+ '-o', 'ServerAliveInterval=15',+ '-o', 'ServerAliveCountMax=4','-p', '2222','-i', '/k/id',diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex ef25b97aa..3ea329ce4 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -44,6 +44,14 @@ export function masterArgs(conn: SshConnection, controlPath: string): string[] {'ControlPersist=300','-o','BatchMode=no',+ // Keepalives on the ONE connection every terminal multiplexes over: keep NAT/firewall+ // entries warm, and detect a dead link in ~60s (15s × 4) instead of hanging half-dead+ // after sleep/wake or a network change. The client then exits 255 and the renderer's+ // SshReconnector takes over.+ '-o',+ 'ServerAliveInterval=15',+ '-o',+ 'ServerAliveCountMax=4',...portArgs(conn)]if (conn.identityFile) args.push('-i', conn.identityFile)diff --git a/src/renderer/lib/sshReconnect.test.ts b/src/renderer/lib/sshReconnect.test.tsnew file mode 100644index 000000000..3a21480ae--- /dev/null+++ b/src/renderer/lib/sshReconnect.test.ts@@ -0,0 +1,129 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { SshReconnector, RECONNECT_DELAYS_MS, RESPAWN_REFUSE_MS } from './sshReconnect'++describe('SshReconnector', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ const make = (connectImpl?: (projectId: string) => Promise<boolean>) => {+ const connect = vi.fn(connectImpl ?? (async () => true))+ const respawn = vi.fn()+ const rec = new SshReconnector({ connect, respawn })+ return { rec, connect, respawn }+ }++ it('reconnects after a drop and respawns the reported node', async () => {+ const { rec, connect, respawn } = make()+ rec.reportDrop('p1', 'n1')+ expect(connect).not.toHaveBeenCalled() // debounced: first attempt waits for the first delay+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(connect).toHaveBeenCalledTimes(1)+ expect(connect).toHaveBeenCalledWith('p1')+ expect(respawn).toHaveBeenCalledWith('p1', ['n1'])+ })++ it('coalesces multiple dropped nodes of one project into a single connect + respawn', async () => {+ const { rec, connect, respawn } = make()+ rec.reportDrop('p1', 'n1')+ rec.reportDrop('p1', 'n2')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(connect).toHaveBeenCalledTimes(1)+ expect(respawn).toHaveBeenCalledTimes(1)+ expect(respawn.mock.calls[0][0]).toBe('p1')+ expect([...respawn.mock.calls[0][1]].sort()).toEqual(['n1', 'n2'])+ })++ it('backs off on failure and gives up after the schedule is exhausted (~30s total)', async () => {+ const { rec, connect, respawn } = make(async () => false)+ rec.reportDrop('p1', 'n1')+ for (const d of RECONNECT_DELAYS_MS) await vi.advanceTimersByTimeAsync(d)+ expect(connect).toHaveBeenCalledTimes(RECONNECT_DELAYS_MS.length)+ // Exhausted: no further attempts, no respawn.+ await vi.advanceTimersByTimeAsync(120_000)+ expect(connect).toHaveBeenCalledTimes(RECONNECT_DELAYS_MS.length)+ expect(respawn).not.toHaveBeenCalled()+ })++ it('a connect() that throws counts as a failed attempt (backoff continues)', async () => {+ const { rec, connect } = make(async () => {+ throw new Error('boom')+ })+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[1])+ expect(connect).toHaveBeenCalledTimes(2)+ })++ it('onConnected flushes pending nodes after the loop gave up (tab-switch reconnect heals)', async () => {+ const { rec, respawn } = make(async () => false)+ rec.reportDrop('p1', 'n1')+ for (const d of RECONNECT_DELAYS_MS) await vi.advanceTimersByTimeAsync(d)+ expect(respawn).not.toHaveBeenCalled()+ rec.onConnected('p1')+ expect(respawn).toHaveBeenCalledWith('p1', ['n1'])+ })++ it('onConnected cancels an in-progress backoff loop (no duplicate respawn)', async () => {+ const { rec, connect, respawn } = make(async () => false)+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0]) // one failed attempt+ rec.onConnected('p1')+ expect(respawn).toHaveBeenCalledTimes(1)+ const attempts = connect.mock.calls.length+ await vi.advanceTimersByTimeAsync(120_000)+ expect(connect).toHaveBeenCalledTimes(attempts) // loop stopped+ expect(respawn).toHaveBeenCalledTimes(1)+ })++ it('onConnected with nothing pending does not respawn', () => {+ const { rec, respawn } = make()+ rec.onConnected('p1')+ expect(respawn).not.toHaveBeenCalled()+ })++ it(`refuses a re-drop within ${RESPAWN_REFUSE_MS}ms of that node's respawn (no hot loop)`, async () => {+ const { rec, connect, respawn } = make()+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(respawn).toHaveBeenCalledTimes(1)+ // The respawned node's ssh dies again immediately (broken spawn): refuse it.+ await vi.advanceTimersByTimeAsync(RESPAWN_REFUSE_MS - 1000)+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(120_000)+ expect(connect).toHaveBeenCalledTimes(1)+ expect(respawn).toHaveBeenCalledTimes(1)+ })++ it('accepts a re-drop after the refuse window (a real later drop reconnects again)', async () => {+ const { rec, respawn } = make()+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(respawn).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(RESPAWN_REFUSE_MS + 1000)+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(respawn).toHaveBeenCalledTimes(2)+ })++ it('tracks projects independently', async () => {+ const { rec, respawn } = make()+ rec.reportDrop('p1', 'n1')+ rec.reportDrop('p2', 'n2')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(respawn).toHaveBeenCalledWith('p1', ['n1'])+ expect(respawn).toHaveBeenCalledWith('p2', ['n2'])+ })++ it('dispose cancels pending loops (no connects or respawns afterwards)', async () => {+ const { rec, connect, respawn } = make()+ rec.reportDrop('p1', 'n1')+ rec.dispose()+ await vi.advanceTimersByTimeAsync(120_000)+ expect(connect).not.toHaveBeenCalled()+ expect(respawn).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/lib/sshReconnect.ts b/src/renderer/lib/sshReconnect.tsnew file mode 100644index 000000000..232b81ad7--- /dev/null+++ b/src/renderer/lib/sshReconnect.ts@@ -0,0 +1,115 @@+/**+ * Auto-reconnect coordinator for SSH-project terminals whose ssh client died with a CONNECTION+ * failure (exit 255 — sleep/wake, network change, NAT idle drop). The remote tmux sessions+ * survive such drops, so all that's needed is to re-establish the project's ControlMaster and+ * respawn the dead nodes (`new-session -A` reattaches).+ *+ * Pure timer/state logic — Canvas injects `connect` (re-establish the master) and `respawn`+ * (bump the nodes' respawnNonce). TerminalNode feeds drops in via Canvas's setSshDropHandler+ * bridge; Canvas forwards every 'connected' status event to onConnected so an EXTERNAL+ * reconnect (the active-project effect on a tab switch) also flushes pending nodes.+ */++/** Backoff schedule between connect attempts; ~30s total, then the loop gives up. A later+ * `onConnected` (tab-switch reconnect) still flushes whatever is pending. */+export const RECONNECT_DELAYS_MS = [1000, 2000, 4000, 8000, 15000]++/** A re-drop within this window of a node's respawn is refused: if the respawned ssh dies+ * instantly the spawn itself is broken (bad key, revoked host, …) and reconnecting again+ * would hot-loop connect→respawn→die forever. */+export const RESPAWN_REFUSE_MS = 10_000++interface ProjectLoop {+ /** Nodes waiting for a respawn once the master is back. */+ pending: Set<string>+ timer: ReturnType<typeof setTimeout> | null+ /** Index into RECONNECT_DELAYS_MS for the NEXT attempt; delays.length ⇒ gave up. */+ attempt: number+}++export interface SshReconnectorDeps {+ /** Re-establish the project's ControlMaster. Resolve true on success. */+ connect: (projectId: string) => Promise<boolean>+ /** Respawn the given (dead) terminal nodes of the project. */+ respawn: (projectId: string, nodeIds: string[]) => void+}++export class SshReconnector {+ private readonly deps: SshReconnectorDeps+ private readonly loops = new Map<string, ProjectLoop>()+ private readonly lastRespawn = new Map<string, number>()+ private disposed = false++ constructor(deps: SshReconnectorDeps) {+ this.deps = deps+ }++ /** A remote terminal's ssh died with exit 255: queue it and (re)start the project's loop. */+ reportDrop(projectId: string, nodeId: string): void {+ if (this.disposed) return+ const respawnedAt = this.lastRespawn.get(nodeId)+ if (respawnedAt !== undefined && Date.now() - respawnedAt < RESPAWN_REFUSE_MS) return+ let loop = this.loops.get(projectId)+ if (!loop) {+ loop = { pending: new Set(), timer: null, attempt: 0 }+ this.loops.set(projectId, loop)+ }+ loop.pending.add(nodeId)+ // Only kick the loop when idle AND not exhausted: an exhausted loop stays parked until+ // onConnected; a running one will pick this node up on its own flush.+ if (loop.timer === null && loop.attempt < RECONNECT_DELAYS_MS.length) this.schedule(projectId, loop)+ }++ /** The project's master is (re)connected — by our loop or anyone else's. Flush pending nodes. */+ onConnected(projectId: string): void {+ if (this.disposed) return+ const loop = this.loops.get(projectId)+ if (!loop) return+ if (loop.timer !== null) clearTimeout(loop.timer)+ this.loops.delete(projectId)+ this.flush(projectId, loop)+ }++ dispose(): void {+ this.disposed = true+ for (const loop of this.loops.values()) {+ if (loop.timer !== null) clearTimeout(loop.timer)+ }+ this.loops.clear()+ }++ private schedule(projectId: string, loop: ProjectLoop): void {+ loop.timer = setTimeout(() => {+ loop.timer = null+ void this.tryConnect(projectId, loop)+ }, RECONNECT_DELAYS_MS[loop.attempt])+ loop.attempt+++ }++ private async tryConnect(projectId: string, loop: ProjectLoop): Promise<void> {+ let ok = false+ try {+ ok = await this.deps.connect(projectId)+ } catch {+ ok = false+ }+ if (this.disposed) return+ // onConnected may have flushed (and deleted) the loop while connect was in flight.+ if (this.loops.get(projectId) !== loop) return+ if (ok) {+ this.loops.delete(projectId)+ this.flush(projectId, loop)+ } else if (loop.attempt < RECONNECT_DELAYS_MS.length) {+ this.schedule(projectId, loop)+ }+ // else: exhausted — keep the loop parked with its pending set so onConnected can flush it.+ }++ private flush(projectId: string, loop: ProjectLoop): void {+ if (loop.pending.size === 0) return+ const nodeIds = [...loop.pending]+ const now = Date.now()+ for (const id of nodeIds) this.lastRespawn.set(id, now)+ this.deps.respawn(projectId, nodeIds)+ }+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 82b565073..265fb71e9 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -144,6 +144,17 @@ export function setMoveIntoWorktreeHandler(fn: ((nodeId: string) => void) | nullmoveIntoWorktreeHandler = fn}+/**+ * SSH-drop handler bridge (same pattern as the move-into-worktree bridge above). Canvas+ * registers the SshReconnector's reportDrop here; an SSH-project terminal whose ssh client+ * exits 255 (connection drop — the remote tmux session survives) reports (projectId, nodeId)+ * so the coordinator can re-establish the master and respawn the node.+ */+let sshDropHandler: ((projectId: string, nodeId: string) => void) | null = null+export function setSshDropHandler(fn: ((projectId: string, nodeId: string) => void) | null): void {+ sshDropHandler = fn+}+/*** Parked terminals: when a node unmounts (project switch), its xterm instance and live PTY* session are kept — the `.xterm` element is detached from the DOM and held here — so a remount@@ -800,6 +811,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// `ssh` as a LOCAL pty program. Only the latter sets shell:'ssh' + buildSshArgs.const sshRemoteTmux = !!data.sshRemoteTmuxconst localSsh = !!ssh && !sshRemoteTmux+ // Owning project of an SSH-project terminal, captured at spawn time for the exit-255 drop+ // report below (a node only exists in the active project's React Flow, so the active+ // project is its owner — same assumption as resolveSshRemote).+ const sshProjectId = sshRemoteTmux ? useProjects.getState().activeProjectId : null// Prefetch the persisted scrollback in parallel with the spawn so it's ready to replay the// instant the session resolves (a cold restart after a reboot recreates the tmux session// empty — see the `fresh` handling below). Cheap no-op ('') when there's no snapshot.@@ -1063,6 +1078,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNcleanups.push(transport.onExit(sid, (code) => {term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)+ // ssh exiting 255 on an SSH-project terminal is a CONNECTION drop (sleep/wake,+ // network change, NAT idle) — the remote tmux session survives. Report it so the+ // reconnect coordinator can re-establish the master and respawn this node.+ if (code === 255 && sshProjectId) sshDropHandler?.(sshProjectId, id)}))cleanups.push(