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): resync nodes the host is running, not only the ones still attached
enes3fb5792c5a8e
diff --git a/src/main/index.ts b/src/main/index.tsindex 86f85dee5..b1a0b507b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -93,7 +93,13 @@ import { registerTranscriptIpc, resolveTranscript } from '../core/transcript-ipcimport { createRemoteContextTail } from './remote-context-tail'import { createRemoteSubagentTail } from './remote-subagent-tail'import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'-import { childArgs } from '../core/remote-ssh/control-master'+import {+ childArgs,+ parseRemoteSessionNames,+ remoteListSessionsArgs,+ remotePaneCommandArgs+} from '../core/remote-ssh/control-master'+import { sessionName } from '../core/tmux-naming'import { posixQuote } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'import { initContextLink, setNodeTranscript } from '../core/context-link'@@ -1221,18 +1227,24 @@ app.whenReady().then(async () => {* node id buys us; a hit is cached under the sessionId so the title poll and the next read get* it for free. Fail-open at every step: no node id / not an SSH session / no resolved home /* a failed ssh call all mean "not remote", which is the pre-existing local path.+ *+ * `remote` overrides the live-pty lookup for callers that already know which host the node runs+ * on. `PtyManager.kill()` forgets a session on detach, so a backgrounded project's nodes are+ * absent from that map — and the reconnect resync runs on exactly those nodes. Absent ⇒ the+ * lookup, i.e. the pre-existing behavior byte for byte.*/const remoteTranscriptRefFor = async (sessionId: string | undefined,cwd: string | undefined,accountId: string | undefined,- nodeId: string | undefined+ nodeId: string | undefined,+ remote?: { conn: import('../shared/ssh').SshConnection; controlPath: string }): Promise<RemoteFileRef | undefined> => {if (!sessionId) return undefinedconst cached = remoteTranscriptBySession.get(sessionId)if (cached) return cachedif (!nodeId) return undefined- const rt = ptyManager.sshRemoteForNode(nodeId)+ const rt = remote ?? ptyManager.sshRemoteForNode(nodeId)if (!rt || !sshProjectManager) return undefinedconst remoteHome = sshProjectManager.remoteHomeForControlPath(rt.controlPath)if (!remoteHome) return undefined@@ -1877,15 +1889,36 @@ app.whenReady().then(async () => {// 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, {+ (_projectId, controlPath, conn) => {+ void resyncProjectAgents({workingNodes,- remoteFor: (nodeId) => ptyManager.sshRemoteForNode(nodeId),- paneCommand: (nodeId) => ptyManager.paneCommand(nodeId),+ hostSessionNames: async () => {+ if (!sshProjectManager) return new Set<string>()+ const { code, stdout } = await sshProjectManager.sshRun(+ remoteListSessionsArgs(conn, controlPath)+ )+ // `list-sessions` exits non-zero when no tmux server is running — that is "no sessions",+ // not a failed read, and either way an empty set repairs nothing.+ return new Set(code === 0 ? parseRemoteSessionNames(stdout) : [])+ },+ paneCommand: async (nodeId) => {+ // The node's REMOTE pane, over this project's master. `PtyManager.paneCommand` would+ // read our live session map, which a backgrounded project has already been dropped from.+ if (!sshProjectManager) return null+ const { code, stdout } = await sshProjectManager.sshRun(+ remotePaneCommandArgs(conn, controlPath, sessionName(nodeId))+ )+ return code === 0 ? stdout.trim() || null : null+ },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)+ // cwd/accountId are unknown here: with no accountId there is exactly ONE transcript root+ // (the system one), so a managed-account node without a hook-fed ref simply stays+ // undecided. A hook-fed ref (the common case) is already cached by session id. The+ // explicit `remote` is what keeps this working for a node with no live pty session.+ const ref = await remoteTranscriptRefFor(sessionId, undefined, undefined, nodeId, {+ conn,+ controlPath+ })return ref ? await readRemoteTranscript(sessionId, ref) : null},emit: emitAgentStatusdiff --git a/src/main/remote-ssh/agent-resync.test.ts b/src/main/remote-ssh/agent-resync.test.tsindex f681da133..7fa6d6eee 100644--- a/src/main/remote-ssh/agent-resync.test.ts+++ b/src/main/remote-ssh/agent-resync.test.ts@@ -1,9 +1,6 @@import { describe, it, expect, vi } from 'vitest'import { resyncProjectAgents, type AgentResyncDeps } from './agent-resync'import type { NormalizedAgentEvent } from '@shared/agents/normalize'-import type { SshConnection } from '@shared/ssh'--const CONN: SshConnection = { host: 'h', user: 'u' }const assistantText = (text: string): string =>JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text }] } })@@ -16,7 +13,7 @@ function deps(over: Partial<AgentResyncDeps> = {}): AgentResyncDeps & { emitted:return {emitted,workingNodes: () => [{ nodeId: 'n1', agentId: 'claude', sessionId: 's1' }],- remoteFor: () => ({ controlPath: '/cm/p1', conn: CONN }),+ hostSessionNames: async () => new Set(['nt-n1']),paneCommand: async () => 'claude',readTranscriptTail: async () => assistantText('Finished.'),emit: (e) => void emitted.push(e),@@ -27,7 +24,7 @@ function deps(over: Partial<AgentResyncDeps> = {}): AgentResyncDeps & { emitted:describe('resyncProjectAgents', () => {it('emits a rescue done for a node whose turn demonstrably ended', async () => {const d = deps()- const ended = await resyncProjectAgents('/cm/p1', d)+ const ended = await resyncProjectAgents(d)expect(ended).toEqual(['n1'])expect(d.emitted).toEqual([@@ -37,7 +34,7 @@ describe('resyncProjectAgents', () => {it('emits nothing for a node that is still working', async () => {const d = deps({ readTranscriptTail: async () => assistantToolUse('t1') })- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})@@ -46,25 +43,48 @@ describe('resyncProjectAgents', () => {paneCommand: async () => null,readTranscriptTail: async () => null})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})- it('skips nodes belonging to another project', async () => {- const d = deps({ remoteFor: () => ({ controlPath: '/cm/OTHER', conn: CONN }) })- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ it('skips a node the host is not running — its tmux session is not there', async () => {+ const d = deps({ hostSessionNames: async () => new Set(['nt-someone-else']) })+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})- it('skips local nodes', async () => {- const d = deps({ remoteFor: () => undefined })- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ it('resyncs a node with no live pty — the host session is the only evidence needed', async () => {+ // The regression this whole task exists for: a backgrounded project's terminals are killed,+ // so nothing is registered locally, yet the node is exactly the one that needs repairing.+ const d = deps({ hostSessionNames: async () => new Set(['nt-n1']) })+ expect(await resyncProjectAgents(d)).toEqual(['n1'])+ })++ it('a failed session listing repairs nothing rather than guessing', async () => {+ const d = deps({+ hostSessionNames: async () => {+ throw new Error('master died')+ }+ })+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})+ it('matches forward by session name, never by parsing a node id back out of one', async () => {+ // `sessionName` is lossy (every non-[a-zA-Z0-9_-] char becomes `_`), so two node ids can share+ // one session name. Reversing would attribute a host session to the wrong node — and a rescue+ // `done` on the wrong node is a false completion notification.+ const d = deps({+ workingNodes: () => [{ nodeId: 'a:b', agentId: 'claude', sessionId: 's1' }],+ hostSessionNames: async () => new Set(['nt-a_b']),+ paneCommand: async () => 'zsh'+ })+ expect(await resyncProjectAgents(d)).toEqual(['a:b'])+ })+it('skips a node with no agentId — a synthetic event needs one to be well formed', async () => {const d = deps({ workingNodes: () => [{ nodeId: 'n1', sessionId: 's1' }] })- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})@@ -77,7 +97,7 @@ describe('resyncProjectAgents', () => {throw new Error('master died again')}})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})@@ -85,7 +105,7 @@ describe('resyncProjectAgents', () => {const readTranscriptTail = vi.fn(async () => assistantText('x'))const d = deps({ paneCommand: async () => 'zsh', readTranscriptTail })- expect(await resyncProjectAgents('/cm/p1', d)).toEqual(['n1'])+ expect(await resyncProjectAgents(d)).toEqual(['n1'])expect(readTranscriptTail).not.toHaveBeenCalled()})@@ -95,18 +115,25 @@ describe('resyncProjectAgents', () => {throw new Error('mirror unreadable')}})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(await resyncProjectAgents(d)).toEqual([])expect(d.emitted).toEqual([])})- it('a throwing remoteFor skips that node without rejecting', async () => {+ it('lists the host sessions once, however many nodes are working', async () => {+ // One ssh round trip for the whole project: the list is a project-level fact, and paying for it+ // per node would multiply the reconnect's remote traffic by the size of the canvas.+ const hostSessionNames = vi.fn(async () => new Set(['nt-n1', 'nt-n2']))const d = deps({- remoteFor: () => {- throw new Error('pty manager blew up')- }+ workingNodes: () => [+ { nodeId: 'n1', agentId: 'claude', sessionId: 'sa' },+ { nodeId: 'n2', agentId: 'claude', sessionId: 'sb' }+ ],+ paneCommand: async () => 'zsh',+ hostSessionNames})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])- expect(d.emitted).toEqual([])++ expect(await resyncProjectAgents(d)).toEqual(['n1', 'n2'])+ expect(hostSessionNames).toHaveBeenCalledTimes(1)})it('a throwing emit costs only its own node — the next one is still rescued', async () => {@@ -116,6 +143,7 @@ describe('resyncProjectAgents', () => {{ nodeId: 'n1', agentId: 'claude', sessionId: 'sa' },{ nodeId: 'n2', agentId: 'claude', sessionId: 'sb' }],+ hostSessionNames: async () => new Set(['nt-n1', 'nt-n2']),paneCommand: async () => 'zsh',emit: (e) => {if (e.nodeId === 'n1') throw new Error('mirror reducer blew up')@@ -123,7 +151,7 @@ describe('resyncProjectAgents', () => {}})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual(['n2'])+ expect(await resyncProjectAgents(d)).toEqual(['n2'])expect(emitted.map((e) => e.nodeId)).toEqual(['n2'])})@@ -136,7 +164,7 @@ describe('resyncProjectAgents', () => {// The transcript leg must still get its say: a synchronous throw is one failed probe, not the// end of this node's rescue.- expect(await resyncProjectAgents('/cm/p1', d)).toEqual(['n1'])+ expect(await resyncProjectAgents(d)).toEqual(['n1'])expect(d.emitted.map((e) => e.nodeId)).toEqual(['n1'])})@@ -146,11 +174,12 @@ describe('resyncProjectAgents', () => {{ nodeId: 'done1', agentId: 'claude', sessionId: 'sa' },{ nodeId: 'busy1', agentId: 'claude', sessionId: 'sb' }],+ hostSessionNames: async () => new Set(['nt-done1', 'nt-busy1']),paneCommand: async (nodeId) => (nodeId === 'done1' ? 'zsh' : 'claude'),readTranscriptTail: async () => assistantToolUse('t2')})- expect(await resyncProjectAgents('/cm/p1', d)).toEqual(['done1'])+ expect(await resyncProjectAgents(d)).toEqual(['done1'])expect(d.emitted.map((e) => e.nodeId)).toEqual(['done1'])})})diff --git a/src/main/remote-ssh/agent-resync.ts b/src/main/remote-ssh/agent-resync.tsindex 70383b054..a53b1f2a8 100644--- a/src/main/remote-ssh/agent-resync.ts+++ b/src/main/remote-ssh/agent-resync.ts@@ -10,16 +10,23 @@// and every side effect is an injected dep.import { decideNode } from '../../core/remote-ssh/agent-resync-decide'+import { sessionName } from '../../core/tmux-naming'import type { NormalizedAgentEvent } from '@shared/agents/normalize'import type { AgentId } from '@shared/agents/config'-import type { SshConnection } from '@shared/ssh'export interface AgentResyncDeps {/** Nodes the mirror still believes are working (agent-status-mirror.workingNodes). */workingNodes: () => { nodeId: string; agentId?: string; sessionId?: string }[]- /** The node's live remote handle, or undefined for a local session (PtyManager.sshRemoteForNode). */- remoteFor: (nodeId: string) => { controlPath: string; conn: SshConnection } | undefined- /** `#{pane_current_command}` for the node's tmux session (PtyManager.paneCommand). */+ /**+ * The nodeterm tmux session names the HOST is running, over this project's ControlMaster.+ *+ * This replaced a per-node lookup in our own live pty map. That map is emptied by+ * `PtyManager.kill()` on detach, so a backgrounded project — the case this feature exists for —+ * had no entries at all and every node was skipped. The host's session list survives detach,+ * which is the whole point of running the agents inside tmux.+ */+ hostSessionNames: () => Promise<Set<string>>+ /** `#{pane_current_command}` for the node's REMOTE tmux session, over the project's master. */paneCommand: (nodeId: string) => Promise<string | null>/** A bounded tail of the node's transcript on the host, or null when it can't be read. */readTranscriptTail: (nodeId: string, sessionId: string) => Promise<string | null>@@ -28,7 +35,7 @@ export interface AgentResyncDeps {}/**- * Resync every working node that belongs to the project owning `controlPath`.+ * Resync every working node the project's host is actually running.** Only nodes the mirror calls `working` are considered: that is the one state a lost hook event can* strand. The opposite error — a node we believe idle that is really working — corrects itself@@ -37,10 +44,7 @@ export interface AgentResyncDeps {* Returns the node ids declared ended (for logging/tests). Never throws: a probe that fails is* `undecided`, and undecided changes nothing.*/-export async function resyncProjectAgents(- controlPath: string,- deps: AgentResyncDeps-): Promise<string[]> {+export async function resyncProjectAgents(deps: AgentResyncDeps): Promise<string[]> {const ended: string[] = []let working: { nodeId: string; agentId?: string; sessionId?: string }[]try {@@ -49,6 +53,15 @@ export async function resyncProjectAgents(return ended // no list ⇒ nothing to repair, and still not a rejection for the reconnect path}+ // ONE listing for the whole project, and a failed listing repairs nothing: an empty set matches+ // no node, which is the same safe direction as every other failed probe here.+ let hostSessions: Set<string>+ try {+ hostSessions = await deps.hostSessionNames()+ } catch {+ return ended+ }+for (const node of working) {// One node's failure is `undecided` for THAT node — never a project-wide abort. `emit` is the// real risk here: it fans out into the mirror reducer, the inbox, a disk write and the HUD, and@@ -57,7 +70,10 @@ export async function resyncProjectAgents(// A synthetic event carries an agentId by contract; without one we cannot emit a well-formed// event, and inventing an agent would misattribute the node on every surface.if (!node.agentId) continue- if (deps.remoteFor(node.nodeId)?.controlPath !== controlPath) continue+ // FORWARD match only. `sessionName` is lossy (every non-[a-zA-Z0-9_-] char becomes `_`), so+ // parsing a node id back out of a session name could attribute the host's session to the+ // wrong node — and a rescue `done` on the wrong node is a false completion notification.+ if (!hostSessions.has(sessionName(node.nodeId))) continueconst pane = await probe(() => deps.paneCommand(node.nodeId))let tail: string | null = nulldiff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex c23b7bd4a..3cd285e11 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -7,8 +7,9 @@ import { SshProjectManager, lastSshErrorLine } from './ssh-project'import { AskpassServer } from './ssh-askpass'import { AppSshAgent } from './ssh-agent'import { controlPathFor } from '../../core/remote-ssh/control-master'+import type { SshConnection } from '@shared/ssh'-const conn = { host: 'h', user: 'u' }+const conn: SshConnection = { host: 'h', user: 'u' }function makeMgr() {const statuses: string[] = []@@ -774,7 +775,7 @@ describe('SshProjectManager', () => {* 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,+ onTunnelVerified: (projectId: string, controlPath: string, conn: SshConnection) => void,httpCode = '204') {vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)@@ -796,11 +797,12 @@ describe('SshProjectManager', () => {})}- it('fires after a genuine re-establish, naming the project and its control path', async () => {+ it('fires after a genuine re-establish, naming the project, its control path and its connection', async () => {const onTunnelVerified = vi.fn()const mgr = makeVerifiedMgr(onTunnelVerified)await mgr.connect('p1', conn, '/remote/cwd')- expect(onTunnelVerified).toHaveBeenCalledWith('p1', controlPathFor('p1'))+ // The connection rides along because the resync builds its own remote commands with it.+ expect(onTunnelVerified).toHaveBeenCalledWith('p1', controlPathFor('p1'), conn)})it('does NOT fire on the reuse branch — a live master never lost its tunnel', async () => {diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 21662723e..162ace2a6 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -80,8 +80,11 @@ interface Runners {/** 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+ * called on the reuse branch — a master that answered `-O check` never lost its tunnel. The+ * `conn` rides along because the resync builds its own remote commands (the host's tmux session+ * list, a pane probe) and the alternative — looking the connection back up by control path —+ * would add a public accessor for a fact this call site already holds. */+ onTunnelVerified?: (projectId: string, controlPath: string, conn: SshConnection) => 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@@ -533,7 +536,7 @@ export class SshProjectManager {// (`onStatus` above carries the same guard for the same hard-won reason.) Do not tidy away.if (hookEndpointPath) {try {- this.r.onTunnelVerified?.(projectId, controlPath)+ this.r.onTunnelVerified?.(projectId, controlPath, conn)} catch {// undecided changes nothing: the stale sweep remains the backstop, as before this hook}@@ -1406,7 +1409,7 @@ export function initSshProject(/** 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+ onTunnelVerified?: (projectId: string, controlPath: string, conn: SshConnection) => void): SshProjectManager {const ssh = sshBin()const scp = scpBin()