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
feat(ssh): resync a project's working agents against the host
enes21a316daa0ad
diff --git a/src/main/remote-ssh/agent-resync.test.ts b/src/main/remote-ssh/agent-resync.test.tsnew file mode 100644index 000000000..f54e52235--- /dev/null+++ b/src/main/remote-ssh/agent-resync.test.ts@@ -0,0 +1,105 @@+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 }] } })++const assistantToolUse = (id: string): string =>+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id, name: 'Bash' }] } })++function deps(over: Partial<AgentResyncDeps> = {}): AgentResyncDeps & { emitted: NormalizedAgentEvent[] } {+ const emitted: NormalizedAgentEvent[] = []+ return {+ emitted,+ workingNodes: () => [{ nodeId: 'n1', agentId: 'claude', sessionId: 's1' }],+ remoteFor: () => ({ controlPath: '/cm/p1', conn: CONN }),+ paneCommand: async () => 'claude',+ readTranscriptTail: async () => assistantText('Finished.'),+ emit: (e) => void emitted.push(e),+ ...over+ }+}++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)++ expect(ended).toEqual(['n1'])+ expect(d.emitted).toEqual([+ { nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'done', idle: true, sessionId: 's1' }+ ])+ })++ 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(d.emitted).toEqual([])+ })++ it('emits nothing when every probe fails — undecided leaves the node alone', async () => {+ const d = deps({+ paneCommand: async () => null,+ readTranscriptTail: async () => null+ })+ expect(await resyncProjectAgents('/cm/p1', 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([])+ expect(d.emitted).toEqual([])+ })++ it('skips local nodes', async () => {+ const d = deps({ remoteFor: () => undefined })+ expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(d.emitted).toEqual([])+ })++ 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(d.emitted).toEqual([])+ })++ it('a throwing probe is undecided, never a crash and never an ended', async () => {+ const d = deps({+ paneCommand: async () => {+ throw new Error('master died again')+ },+ readTranscriptTail: async () => {+ throw new Error('master died again')+ }+ })+ expect(await resyncProjectAgents('/cm/p1', d)).toEqual([])+ expect(d.emitted).toEqual([])+ })++ it('does not read a transcript when the pane already answered', async () => {+ const readTranscriptTail = vi.fn(async () => assistantText('x'))+ const d = deps({ paneCommand: async () => 'zsh', readTranscriptTail })++ expect(await resyncProjectAgents('/cm/p1', d)).toEqual(['n1'])+ expect(readTranscriptTail).not.toHaveBeenCalled()+ })++ it('handles several nodes independently', async () => {+ const d = deps({+ workingNodes: () => [+ { nodeId: 'done1', agentId: 'claude', sessionId: 'sa' },+ { nodeId: 'busy1', agentId: 'claude', sessionId: 'sb' }+ ],+ paneCommand: async (nodeId) => (nodeId === 'done1' ? 'zsh' : 'claude'),+ readTranscriptTail: async () => assistantToolUse('t2')+ })++ expect(await resyncProjectAgents('/cm/p1', 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.tsnew file mode 100644index 000000000..110b54afd--- /dev/null+++ b/src/main/remote-ssh/agent-resync.ts@@ -0,0 +1,78 @@+// Repair agent status after an SSH project's reverse hook tunnel comes back.+//+// Hook events are fire-and-forget POSTs through that tunnel, and nothing on the host queues them:+// an agent that finishes while the master is down loses its `done` for good. The node then sits at+// `working` on every surface until `sweepStaleWorking` guesses from silence 20 minutes later — so+// the user cannot tell "finished" from "waiting on a permission prompt" from "the CLI died".+//+// So when the tunnel is verified again, ask the host what is actually true. This module is the+// orchestration only: the judgement is the pure `decideNode` (core/remote-ssh/agent-resync-decide),+// and every side effect is an injected dep.++import { decideNode } from '../../core/remote-ssh/agent-resync-decide'+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). */+ 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>+ /** The single normalized-event funnel (main/index.ts emitAgentStatus). */+ emit: (e: NormalizedAgentEvent) => void+}++/**+ * Resync every working node that belongs to the project owning `controlPath`.+ *+ * 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+ * within seconds, because hook events fire continuously through a turn.+ *+ * 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[]> {+ const ended: string[] = []+ for (const node of deps.workingNodes()) {+ // 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++ const pane = await deps.paneCommand(node.nodeId).catch(() => null)+ let tail: string | null = null+ // Only pay for the transcript read when the pane could not answer on its own.+ if (!isDecisivePane(pane) && node.sessionId) {+ tail = await deps.readTranscriptTail(node.nodeId, node.sessionId).catch(() => null)+ }++ if (decideNode(pane, tail) !== 'ended') continue++ // `idle: true` is the existing rescue-signal flag: a done carrying it may only move a node that+ // is still `working`, so a node parked on a permission prompt can never be cleared from here.+ deps.emit({+ nodeId: node.nodeId,+ agentId: node.agentId as AgentId,+ kind: 'state',+ state: 'done',+ idle: true,+ ...(node.sessionId ? { sessionId: node.sessionId } : {})+ })+ ended.push(node.nodeId)+ }+ return ended+}++/** Did the pane probe settle it by itself? Mirrors decideFromPane's 'ended' branch. */+function isDecisivePane(pane: string | null): boolean {+ return decideNode(pane, null) === 'ended'+}