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(relay): team resume never resumes one node twice at once
review546e8c1788a3
diff --git a/CLAUDE.md b/CLAUDE.mdindex 28f87b09a..77d599373 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8457,7 +8457,10 @@ invariants:project (and says so when the undo itself fails); after it, the SSH project is NEVER reopened,even when the kill or the join fails, because that would be a second writer. `team resume` re-askswith the core's exact `sessionVerdict` (the folded `sessionExists` prefix-matches): present ⇒- `already-running`, unknown ⇒ refused, so a re-run never doubles an agent.+ `already-running`, unknown ⇒ refused, and a node another request in this process is still+ launching is `already-running` too (`ResumeDeps.inFlight`, ONE set per server process, claimed+ before the first await): the desktop's call times out at 60 s while the server keeps draining, so+ a re-run never doubles an agent.- **What may be handed over is read twice, and only what the user confirmed may change nothing.**Busy is `working`, `blocked` AND `waiting` (a Codex approval prompt and an open AskUserQuestionare `waiting`); an agent only the status store knows (launched by hand) counts as busydiff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex 0a78fbc0a..8024ef895 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -139,8 +139,10 @@ Every entry is checked again here: the node must be a terminal of that project rthe agent must be resumable and not run under a managed account, and the session id must pass thesame rule as every other resume; an unknown permission mode gives the bare command. A node whose`nt-<id>` session already exists on this core's socket (`node-terminal`, checked with the exact-target) is `already-running`, and one whose session this core cannot check is refused rather than-started, so a re-run never puts a second agent on one conversation. Launches run four at a time, in+target) is `already-running`, and so is a node another `team resume` on this server is still+launching (the desktop's call gives up after 60 s while the server keeps going, and the user may+share again). One whose session this core cannot check is refused rather than started, so a re-run+never puts a second agent on one conversation. Launches run four at a time, inthe node's folder and with this core's hook environment, so each agent's status reaches everyteammate. Share with team calls it only for sessions it has verified gone from the desktop's socket.diff --git a/src/core/relay/team-resume.test.ts b/src/core/relay/team-resume.test.tsindex c470e6ab1..0b38c4872 100644--- a/src/core/relay/team-resume.test.ts+++ b/src/core/relay/team-resume.test.ts@@ -16,11 +16,12 @@ const PROJECT = {]} as unknown as Project-function deps(o: { verdict?: Record<string, 'present' | 'absent' | 'unknown'>; launch?: 'delivered' | 'failed' } = {}) {+function deps(o: { verdict?: Record<string, 'present' | 'absent' | 'unknown'>; launch?: 'delivered' | 'failed'; inFlight?: Set<string> } = {}) {const launched: Array<{ nodeId: string; command: string }> = []let inFlight = 0let peak = 0const d: ResumeDeps = {+ inFlight: o.inFlight ?? new Set<string>(),loadProject: async (id) => (id === 'project-1' ? PROJECT : null),sessionVerdict: async (nodeId) => o.verdict?.[nodeId] ?? 'absent',command: async (entry) => `${entry.agentId} --resume ${entry.sessionId}${entry.permissionMode ? ` <${entry.permissionMode}>` : ''}`,@@ -81,6 +82,37 @@ describe('runResume', () => {const { d } = deps()await expect(runResume(d, { projectId: 'nope', sessions: [] })).rejects.toMatchObject({ code: 'E_BAD_REQUEST' })})+ it('two overlapping requests never resume one node twice; the node is free again once its launch settles', async () => {+ // The CLI's 60 s timeout can end the desktop's call while the server keeps draining it, and the+ // user runs Share again: both requests would see `absent` and type `--resume` twice.+ const shared = new Set<string>()+ const first = deps({ inFlight: shared })+ let release!: () => void+ const held = new Promise<void>((r) => (release = r))+ const realLaunch = first.d.launch+ first.d.launch = async (...args) => {+ await held+ return realLaunch(...args)+ }+ const running = runResume(first.d, { projectId: 'project-1', sessions: [E('term-a'), E('term-b', 'codex', 's2')] })+ await new Promise((r) => setTimeout(r, 0))+ const second = deps({ inFlight: shared })+ const overlap = await runResume(second.d, { projectId: 'project-1', sessions: [E('term-a')] })+ expect(overlap.results).toEqual([{ nodeId: 'term-a', status: 'already-running' }])+ expect(second.launched).toEqual([])+ release()+ expect((await running).results.map((x) => x.status)).toEqual(['resumed', 'resumed'])+ expect(shared.size).toBe(0)+ // Released after a FAILED launch too: a later request may try again.+ const failing = deps({ inFlight: shared })+ failing.d.launch = async () => {+ throw new Error('boom')+ }+ expect((await runResume(failing.d, { projectId: 'project-1', sessions: [E('term-a')] })).results[0]).toMatchObject({ status: 'refused' })+ expect(shared.size).toBe(0)+ const third = deps({ inFlight: shared })+ expect((await runResume(third.d, { projectId: 'project-1', sessions: [E('term-a')] })).results[0].status).toBe('resumed')+ })it(`never runs more than ${RESUME_CONCURRENCY} launches at once, and keeps result order`, async () => {const nodes = Array.from({ length: 10 }, (_, i) => node({ id: `t${i}`, agentId: 'claude' }))const { d, peak } = deps()diff --git a/src/core/relay/team-resume.ts b/src/core/relay/team-resume.tsindex 3e07d3fa2..2fa18618f 100644--- a/src/core/relay/team-resume.ts+++ b/src/core/relay/team-resume.ts@@ -3,7 +3,8 @@// desktop VERIFIED each node's old `nodeterm-rmt` session is gone — two processes on one// conversation would interleave its transcript — and re-checked here per node with the EXACT tmux// target (a bare `has-session` prefix-matches, so `nt-x-1` would answer for `nt-x-12`).-// Idempotent: a session that already exists is `already-running`, so a re-run never doubles.+// Idempotent: a session that already exists is `already-running`, and so is a node another request+// in this process is resuming right now, so a re-run never doubles.import type { CanvasNodeState, Project } from '../../shared/types'import type { HeadlessLaunchResult } from '../../shared/headless-launch'import { RESUMABLE_AGENTS, isPermissionMode, type AgentPermissionMode } from '../../shared/agents/config'@@ -23,6 +24,10 @@ export interface ValidResumeEntry {permissionMode?: AgentPermissionMode}export interface ResumeDeps {+ /** The nodes a resume is launching right now, ONE set for the whole process. A second request for+ * a node still in it answers `already-running`: the desktop's call can time out while this server+ * keeps draining it, and a re-run would otherwise see `absent` too and type the resume twice. */+ inFlight: Set<string>loadProject(projectId: string): Promise<Project | null>sessionVerdict(nodeId: string): Promise<'present' | 'absent' | 'unknown'>/** The command line that resumes this entry on this host (null = cannot be composed). */@@ -66,18 +71,25 @@ export async function runResume(...(isPermissionMode(e.permissionMode) ? { permissionMode: e.permissionMode } : {})}return async (): Promise<ResumeResultEntry> => {- const verdict = await deps.sessionVerdict(e.nodeId)- if (verdict === 'present') return { nodeId: e.nodeId, status: 'already-running' }- // Never a launch on uncertainty: a session we could not see may still be running the agent.- if (verdict === 'unknown') {- return { nodeId: e.nodeId, status: 'refused', reason: 'could not check whether its session is running' }+ // Claimed before the first await, so two overlapping requests cannot both pass this check.+ if (deps.inFlight.has(e.nodeId)) return { nodeId: e.nodeId, status: 'already-running' }+ deps.inFlight.add(e.nodeId)+ try {+ const verdict = await deps.sessionVerdict(e.nodeId)+ if (verdict === 'present') return { nodeId: e.nodeId, status: 'already-running' }+ // Never a launch on uncertainty: a session we could not see may still be running the agent.+ if (verdict === 'unknown') {+ return { nodeId: e.nodeId, status: 'refused', reason: 'could not check whether its session is running' }+ }+ const command = await deps.command(entry, node, project)+ if (!command) return { nodeId: e.nodeId, status: 'refused', reason: 'no resume command for this agent' }+ const r = await deps.launch(project, node, command)+ return r.outcome === 'delivered'+ ? { nodeId: e.nodeId, status: 'resumed' }+ : { nodeId: e.nodeId, status: 'refused', reason: `launch failed (${r.reason})` }+ } finally {+ deps.inFlight.delete(e.nodeId)}- const command = await deps.command(entry, node, project)- if (!command) return { nodeId: e.nodeId, status: 'refused', reason: 'no resume command for this agent' }- const r = await deps.launch(project, node, command)- return r.outcome === 'delivered'- ? { nodeId: e.nodeId, status: 'resumed' }- : { nodeId: e.nodeId, status: 'refused', reason: `launch failed (${r.reason})` }}})const results: ResumeResultEntry[] = new Array(jobs.length)diff --git a/src/server/hosted-boot.test.ts b/src/server/hosted-boot.test.tsindex 6d7d1552b..31ce5401e 100644--- a/src/server/hosted-boot.test.ts+++ b/src/server/hosted-boot.test.ts@@ -43,6 +43,14 @@ describe('hosted team boot wiring (source)', () => {expect(main).not.toMatch(/argv\[0\] === 'team'/)})+ it('team resume shares ONE in-flight set across requests (a set made per call would not dedupe)', () => {+ const made = src.indexOf('const resumesInFlight = new Set<string>()')+ const resume = src.indexOf('resume: (req) =>')+ expect(made).toBeGreaterThan(0)+ expect(made).toBeLessThan(resume)+ expect(src.slice(resume, resume + 200)).toContain('inFlight: resumesInFlight')+ })+it('projectsOfNode uses the store\'s memoized lookup, not a persistedCanvases scan per call', () => {expect(src).toMatch(/projectsOfNode: \(nodeId\) => workspaceStore\.projectIdsForNode\(nodeId\)/)})diff --git a/src/server/index.ts b/src/server/index.tsindex a6ef541e8..7586b3b56 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -991,6 +991,8 @@ export async function startServer(// unix socket, or Windows, disables administration — it must not take the rest of the Server// Edition down with it.let otherServerHere = false+ // One set for the whole process: the nodes a `team resume` is launching right now (runResume).+ const resumesInFlight = new Set<string>()const teamAdmin = await startTeamAdmin(config.dataDir, hosted, {// `team bootstrap`: adopt the folder into THIS core's workspace (saved before it is shared, so// the canvas authority can read it). The server runs as the SSH login user, so its home is the@@ -1002,6 +1004,7 @@ export async function startServer(resume: (req) =>runResume({+ inFlight: resumesInFlight,loadProject: async (id) => (await workspaceStore.load({ sideline: false })).projects.find((p) => p.id === id) ?? null,sessionVerdict: (nodeId) => ptyManager.sessionVerdict(nodeId),command: async (entry, node) => {