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(control): name the request id on a timeout; finish late answers too
review3a120d5b8ec0
diff --git a/CLAUDE.md b/CLAUDE.mdindex f7fd2f0f5..6233fe778 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3171,15 +3171,28 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile(desktop main's 120 s wait, now `src/main/control-forward.ts`: the renderer is not cancelled, andan `open-worktree` whose `git worktree add` outlives the wait still completes) or throws, and therow becomes UNKNOWN — refused, never re-run; the forwarder hands a late renderer answer back via- the handler's `onLateAnswer`, and settlement only moves up (unknown → answer, never the reverse);+ the handler's `onLateAnswer`, and settlement only moves up (unknown → answer, never the reverse).+ **A late answer is finished exactly like an on-time one**: everything main does with a renderer+ answer (the `open-browser` ownership claim, `browser-open-claim.ts`; the `open-project` grant) is+ ONE `finishAnswer` step the forwarder runs on whichever answer arrives — replaying a late+ "opened browser b1" without the claim told the agent it had a browser it could never drive. And+ **an indeterminate reply names its id**: the route adds a `request id: <id>` line saying to pass+ it back as `--request-id <id>`, and the in-flight/unknown refusals spell the flag with its value —+ the shim's per-run id is otherwise never seen, so "retry with the same --request-id" sent agents+ to re-run the bare command, get a fresh id and open a second one;(7) an explicit id on a verb outside the set is REFUSED (`request-id-unsupported`), like`--dry-run` — an agent believing its `write` is protected when it is not is the failure the flagexists to end — while a malformed or out-of-set per-run id is silently ignored; (8) a dry runneither claims nor replays. The ledger is **process memory** (24 h, 256 per caller, 4096 in total,in-flight rows never evicted): an app restart between the effect and the retry runs the retryagain, which is the case that matters least and costs a store with atomic writes on every call- to cover. The timeout sentence is now verb-aware (`controlTimeoutError`): only a confirm-gated- verb, whose dialog dismisses itself at the same deadline, is still called "safe to retry". An SSH+ to cover. The timeout sentence is verb- and claim-aware (`controlTimeoutError`): only a+ confirm-gated verb, whose dialog dismisses itself at the same deadline, is still called "safe to+ retry"; a call with no ledger row (no id, or an unverified caller) is told to check the canvas for+ its effect before retrying, never pointed at a flag it has no value for. Ids suggested to agents+ must be UNIQUE (a uuid, or a readable name with a random part): rows are per node for 24 h, so a+ later conversation in the same node reusing a readable id for the same call would be answered+ with the earlier reply. An SSHhost keeps the shim it got at its last connect, so until that project reconnects its runs carryno per-run id (an explicit `--request-id` still works through the old loop). Agent-facing textis rendered from `REQUEST_ID_VERBS` / `REQUEST_ID_RETRYABLE` / `REQUEST_ID_OUTCOME_GLOSS`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ac6c85258..db214d3da 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -343,8 +343,11 @@ anything else. Board-level fields survive every transform — `pullLinks` is one(`src/core/control-request-ledger.ts`). A new verb that opens a node, a team, a worktree or a framejoins `REQUEST_ID_VERBS` in the same PR; the agent-facing text renders from that set. A handlerthat gives up before it knows whether its effect happened answers `indeterminate: true`, never a- plain failure that says "safe to retry" — the retry would then open a second one. Do not move the- ledger into one shell's handler: the other shell silently loses it.+ plain failure that says "safe to retry" — the retry would then open a second one. Anything desktop+ main does with a renderer answer belongs in its `finishAnswer` step, which the forwarder also runs+ on a LATE answer (the one a retry is replayed): post-processing written after the `await` instead+ runs only on time. Do not move the ledger into one shell's handler: the other shell silently loses+ it.- **A new canvas-control open path must record who opened the node.** When a station stops, theagent that opened it is told (`src/core/agents/station-notice.ts`) — and a rope alone cannot saydiff --git a/src/core/agents/hook-server.request-id.test.ts b/src/core/agents/hook-server.request-id.test.tsindex 78e75e6ff..4d1e201ba 100644--- a/src/core/agents/hook-server.request-id.test.ts+++ b/src/core/agents/hook-server.request-id.test.ts@@ -10,12 +10,14 @@ import { initPlatform, resetPlatformForTests } from '../platform'import { fakePlatform } from '../platform-fake'import { hookServer } from './hook-server'import { nodeAuthToken } from './node-auth-token'-import { REQUEST_ID_REPLAYED_LEAD } from '../control-request-ledger'+import { REQUEST_ID_HINT_LEAD, REQUEST_ID_REPLAYED_LEAD } from '../control-request-ledger'const secret = Buffer.alloc(32, 7)let dir: stringtype Cmd = { verb: string; nodeId: string; args: Record<string, string>; verified: boolean }let handled: Cmd[] = []+/** Whether each call was handed the late-answer path — main words its timeout by exactly this. */+let lateOffered: boolean[] = []let next: (cmd: Cmd, late?: (r: { ok: boolean; message?: string }) => void) => Promise<{ok: booleanmessage?: string@@ -32,11 +34,13 @@ beforeAll(async () => {hookServer.setNodeAuthSecret(secret)hookServer.setControlHandler(async (cmd) => {handled.push({ verb: cmd.verb, nodeId: cmd.nodeId, args: cmd.args, verified: cmd.verified })+ lateOffered.push(typeof cmd.onLateAnswer === 'function')return next(cmd, cmd.onLateAnswer)})})beforeEach(() => {handled = []+ lateOffered = []let n = 0next = async (cmd) => ({ ok: true, message: `opened n${++n}`, result: { ids: [`n${n}`], verb: cmd.verb } })})@@ -231,6 +235,62 @@ describe('control route: --request-id makes a retried open idempotent', () => {expect(handled).toHaveLength(1)})+ // Review follow-up to #1027: the timeout told the caller to "retry with the same --request-id" and+ // never said what that id was. For the per-run id the shim generates, the caller has never seen+ // it — so its natural retry was the bare command, a FRESH id, and a second open.+ it('an indeterminate answer names the request id it holds — the per-run one included — and how to pass it', async () => {+ next = async () => ({ ok: false, error: 'no answer within 120s — may still complete', indeterminate: true })+ const text = await post('open-worktree', { node: freshNode(), args: { branch: 'b' }, cliRequestId: 'cli-feed01' })+ expect(text.status).toBe(400)+ expect(text.body).toContain('no answer within 120s')+ expect(text.body).toContain(`${REQUEST_ID_HINT_LEAD} cli-feed01`)+ expect(text.body).toContain('--request-id cli-feed01')+ const json = JSON.parse(+ (await post('open-worktree', { node: freshNode(), args: { branch: 'b' }, cliRequestId: 'cli-feed02', json: true }))+ .body+ )+ expect(json.requestId).toBe('cli-feed02')+ expect(json.message).toContain('--request-id cli-feed02')+ expect(json.error).toContain('no answer within 120s')+ })++ it('with no claim there is no id to name, and the handler is offered no late-answer path', async () => {+ next = async () => ({ ok: false, error: 'no answer within 120s — check the canvas', indeterminate: true })+ const unverified = await post('open-worktree', {+ node: freshNode(),+ args: { branch: 'b', 'request-id': 'mine' },+ verified: false+ })+ expect(unverified.body).not.toContain(REQUEST_ID_HINT_LEAD)+ const noId = await post('open-worktree', { node: freshNode(), args: { branch: 'b' } })+ expect(noId.body).not.toContain(REQUEST_ID_HINT_LEAD)+ await post('open-worktree', { node: freshNode(), args: { branch: 'b' }, cliRequestId: 'cli-x1' })+ expect(lateOffered).toEqual([false, false, true])+ })++ it('an in-flight or unknown refusal spells the flag WITH its value, so a per-run id can be passed back', async () => {+ const node = freshNode()+ let release!: () => void+ next = () =>+ new Promise((resolve) => {+ release = () => resolve({ ok: false, error: 'late', indeterminate: true })+ })+ const firstP = post('open-agent', { node, args: { agent: 'claude' }, cliRequestId: 'cli-abc123' })+ await vi_waitFor(() => handled.length === 1)+ const during = await post('open-agent', { node, args: { agent: 'claude' }, cliRequestId: 'cli-abc123' })+ expect(during.body).toMatch(/^request-in-flight: /)+ expect(during.body).toContain('--request-id cli-abc123')+ release()+ await firstP+ const unknown = await post('open-agent', { node, args: { agent: 'claude' }, cliRequestId: 'cli-abc123' })+ expect(unknown.body).toMatch(/^request-outcome-unknown: /)+ expect(unknown.body).toContain('--request-id cli-abc123')+ // …and passing it back as --request-id is the same call, not a conflict.+ const passedBack = await post('open-agent', { node, args: { agent: 'claude', 'request-id': 'cli-abc123' } })+ expect(passedBack.body).toMatch(/^request-outcome-unknown: /)+ expect(handled).toHaveLength(1)+ })+it('a handler that throws leaves the id unknown: the retry is refused, not re-run', async () => {const node = freshNode()next = async () => {diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 6e36305d0..f44964d01 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -41,6 +41,7 @@ import {requestIdGate,requestIdOutcomeMessage,requestIdReplayLine,+ requestIdRetryHint,type LedgerClaim} from '../control-request-ledger'@@ -358,6 +359,8 @@ export class HookServer {error?: string// The handler could not tell whether its effect happened (see control-request-ledger.ts).indeterminate?: boolean+ // Set by the route, never a handler: the id an indeterminate call is filed under.+ requestId?: string}>)| null = null/**@@ -826,6 +829,16 @@ export class HookServer {throw e}held?.settle(result)+ // A call that may still complete names the id it is filed under, and how to pass it back:+ // for the shim's per-run id this is the only place the caller ever sees it.+ if (held && idGate.requestId && result.indeterminate) {+ const hint = requestIdRetryHint(idGate.requestId)+ result = {+ ...result,+ message: `${result.message ?? result.error ?? 'control request failed'}\n${hint}`,+ requestId: idGate.requestId+ }+ }// Which note, not whether: an unmintable node warned with the restart line is sent round// the same loop the refusal path already knows better than to send it round.const note = [decision === 'allow-with-warning' ? this.identityWarningNote(nodeId) : '', idNote]diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 0fde6136d..b9c2957bd 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -33,6 +33,7 @@ import { STATION_NOTICE_FROM } from '../shared/agents/agent-messaging'import { PR_DEADLINE_DEFAULT_MS, PR_DEADLINE_MAX_MS, PR_WAIT_MAX, afterPrFlagRefusal } from '../shared/pr-wait'import { ISSUE_BRANCH_SLUG_MAX, issueWorktreeBranch } from '../shared/issue-worktree'import {+ REQUEST_ID_HINT_LEAD,REQUEST_ID_MAX_LENGTH,REQUEST_ID_OUTCOME_GLOSS,REQUEST_ID_REPLAYED_LEAD,@@ -481,7 +482,10 @@ function requestIdDocLines(): string[] {'Retrying safely (`--request-id`):',`- The verbs that create something (${[...REQUEST_ID_VERBS].join(', ')}) take`,` \`--request-id <id>\`: 1-${REQUEST_ID_MAX_LENGTH} letters, digits, \`.\`, \`_\`, \`:\` or \`-\`, starting with`,- ' a letter or digit. Give each operation its own id (a uuid, or a name like `wave2-reviewer-1`).',+ ' a letter or digit. Make each id UNIQUE: a uuid (`uuidgen`), or a readable name with a random',+ ' part (`wave2-reviewer-1-7f3a9c`). A bare readable name can come back: ids are remembered per',+ ` node for ${Math.round(REQUEST_LEDGER_TTL_MS / 3_600_000)} hours, so a later conversation in the same node that reuses one for the same`,+ ' call is answered with the earlier reply — an open that never happened this time.','- When a call\'s reply never reached you — your tool call timed out, the connection dropped, the',' output was cut off — run the SAME command with the SAME id. nodeterm recognises it and, instead',' of opening a second node, returns the first call\'s reply, whose first line starts',@@ -491,6 +495,9 @@ function requestIdDocLines(): string[] {' refused, and opens nothing.',`- Retry with the SAME id after a short wait: ${yes.join('; ')}.`,`- A same-id retry never clears these — fix the call: ${no.join('; ')}.`,+ `- A reply that says a call may still complete names its id on a \`${REQUEST_ID_HINT_LEAD}\` line — also`,+ ' when you passed none, because the CLI picks one per run. To retry, pass exactly that id with',+ ' `--request-id`. Never re-run the bare command: it gets a fresh id and can open a second one.','- Without `--request-id` the CLI still tags each RUN with its own id, so its own automatic',' re-send to another endpoint never opens twice — but a second run is a second call. An id is',` matched only for a session whose node identity is verified (the reply says so otherwise), for ${hours} hours,`,diff --git a/src/core/control-request-ledger.ts b/src/core/control-request-ledger.tsindex e8f0bccd4..bbe8a5230 100644--- a/src/core/control-request-ledger.ts+++ b/src/core/control-request-ledger.ts@@ -130,6 +130,22 @@ export function requestIdReplayLine(requestId: string, ageMs: number): string {)}+/** The line that names the id a call may still complete under. Exported so tests quote it. */+export const REQUEST_ID_HINT_LEAD = 'request id:'++/**+ * Added to a reply that could not say whether its call took effect, when the route holds a row for+ * it. It must carry the id ITSELF: the shim's per-run id is otherwise never seen, so "retry with the+ * same --request-id" sent the agent to re-run the bare command — a fresh id, and a second open.+ */+export function requestIdRetryHint(requestId: string): string {+ return (+ `${REQUEST_ID_HINT_LEAD} ${requestId} — to retry, run the same command with ` ++ `\`--request-id ${requestId}\` added: you get this call's answer (or its refusal), never a ` ++ 'second one. Running it without that flag may open it twice.'+ )+}+/** Appended when the caller passed `--request-id` but its node identity is not verified. */export const REQUEST_ID_UNVERIFIED_NOTE ='request id ignored: this session\'s node identity is not verified, so a retry cannot be matched ' +@@ -150,15 +166,15 @@ export function requestIdOutcomeMessage(case 'request-in-flight':return (`request-in-flight: request ${id} is still running${since} — nothing new was started. ` +- 'Run the same command with the same --request-id again in a few seconds to get its reply.'+ `Run the same command with \`--request-id ${id}\` in a few seconds to get its reply.`)case 'request-outcome-unknown':return (`request-outcome-unknown: request ${id} ended without a confirmed answer${since}, so it MAY ` +- 'have taken effect — nothing new was started. Retry the same command with the same ' +- '--request-id in a minute: an answer that arrives late is returned then. If it keeps saying ' +- 'this, run `list` before opening anything again, and use a new --request-id only for ' +- 'something that is not there.'+ 'have taken effect — nothing new was started. Retry the same command with ' ++ `\`--request-id ${id}\` in a minute: an answer that arrives late is returned then. If it ` ++ 'keeps saying this, run `list` before opening anything again, and use a new --request-id ' ++ 'only for something that is not there.')case 'request-id-conflict':return (diff --git a/src/main/browser-open-claim.test.ts b/src/main/browser-open-claim.test.tsnew file mode 100644index 000000000..a79f91cce--- /dev/null+++ b/src/main/browser-open-claim.test.ts@@ -0,0 +1,63 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BrowserControlLedger } from './browser-control-ledger'+import { claimOpenedBrowser } from './browser-open-claim'+import { createControlForwarder } from './control-forward'++const opened = { ok: true, message: 'opened browser b1', result: { id: 'b1', projectId: 'p1', partition: 'persist:nt-agent-browser-p1' } }+const call = { verb: 'open-browser', ownerNodeId: 'agent-1', verified: true }++describe('claimOpenedBrowser', () => {+ it('records the verified caller as the owner of the browser it opened', () => {+ const ledger = new BrowserControlLedger()+ expect(claimOpenedBrowser(ledger, call, opened, 1234)).toBe(true)+ expect(ledger.get('b1', 'agent-1')).toMatchObject({+ ownerNodeId: 'agent-1',+ projectId: 'p1',+ partition: 'persist:nt-agent-browser-p1',+ navGeneration: 0,+ leaseActiveUntil: 0,+ openedAt: 1234+ })+ })++ it('records nothing for an unverified caller, a failed open, another verb, or a reply missing its project', () => {+ const ledger = new BrowserControlLedger()+ expect(claimOpenedBrowser(ledger, { ...call, verified: false }, opened, 1)).toBe(false)+ expect(claimOpenedBrowser(ledger, call, { ...opened, ok: false }, 1)).toBe(false)+ expect(claimOpenedBrowser(ledger, { ...call, verb: 'show-web' }, opened, 1)).toBe(false)+ for (const drop of ['id', 'projectId', 'partition'] as const) {+ const result = { ...opened.result, [drop]: undefined }+ expect(claimOpenedBrowser(ledger, call, { ...opened, result }, 1), drop).toBe(false)+ }+ expect(ledger.get('b1', 'agent-1')).toBe(null)+ })+})++// Review follow-up to #1027. After desktop main gives up waiting (120 s), the renderer's answer can+// still arrive, and the request ledger replays it to the next retry. That answer skipped the+// ownership recording the on-time path does, so a retry heard "opened browser b1" about a browser+// its opener could never drive. The forwarder now runs the same finishing step on both answers.+describe('a LATE open-browser answer records ownership exactly like an on-time one', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ it('the owner can drive the browser a late answer reports, and the replayed reply is the same answer', async () => {+ const ledger = new BrowserControlLedger()+ const sent: string[] = []+ const late = vi.fn()+ const fwd = createControlForwarder({ timeoutMs: 1000 })+ const p = fwd.forward('open-browser', (id) => sent.push(id), {+ onLate: late,+ finish: (reply) => {+ claimOpenedBrowser(ledger, call, reply, 1234)+ return reply+ }+ })+ vi.advanceTimersByTime(1000)+ expect((await p).indeterminate).toBe(true)+ expect(ledger.get('b1', 'agent-1')).toBe(null)+ fwd.answer({ requestId: sent[0], ...opened })+ expect(ledger.get('b1', 'agent-1')?.ownerNodeId).toBe('agent-1')+ expect(late).toHaveBeenCalledWith(opened)+ })+})diff --git a/src/main/browser-open-claim.ts b/src/main/browser-open-claim.tsnew file mode 100644index 000000000..940cf6d48--- /dev/null+++ b/src/main/browser-open-claim.ts@@ -0,0 +1,35 @@+// Record who owns a browser node an agent just opened — the one place that decides it, so the+// on-time answer and a LATE one (after desktop main's 120 s wait gave up; see control-forward.ts)+// are recorded by the same rule. Before this was shared, a late answer was replayed to the agent's+// retry as "opened browser b1" with no owner recorded, so the browser it opened was one it could+// never drive.+//+// The rule itself is unchanged from where it lived in src/main/index.ts: ONLY a successful+// `open-browser` whose caller's identity verdict for THIS request was `verified` (main's own verdict,+// never anything off the wire or project.json) creates an entry, owned by that caller, with the+// project id + partition the renderer's reply carries. Ownership is NEVER read from `Project.ropes`+// (browser-ownership-source.test.ts scans this file for exactly that).+import type { BrowserControlLedger } from './browser-control-ledger'++export function claimOpenedBrowser(+ ledger: BrowserControlLedger,+ call: { verb: string; ownerNodeId: string; verified: boolean },+ reply: { ok: boolean; result?: unknown },+ now: number+): boolean {+ if (call.verb !== 'open-browser' || !call.verified || !reply.ok) return false+ const opened = reply.result as { id?: string; projectId?: string; partition?: string } | undefined+ // Refuse to record an entry with no owning project: `releaseByProject('')` would match it, and a+ // project-less ownership record is meaningless. Fail-closed against future reply-shape drift —+ // today `partition` is present only when agentBrowserPartition(projectId) succeeded, so a+ // non-empty safe projectId always rides with it.+ if (!opened?.id || !opened.partition || !opened.projectId) return false+ return ledger.claim(opened.id, {+ ownerNodeId: call.ownerNodeId,+ projectId: opened.projectId,+ partition: opened.partition,+ navGeneration: 0,+ leaseActiveUntil: 0,+ openedAt: now+ })+}diff --git a/src/main/browser-ownership-source.test.ts b/src/main/browser-ownership-source.test.tsindex c22b21f7a..2a7516a38 100644--- a/src/main/browser-ownership-source.test.ts+++ b/src/main/browser-ownership-source.test.ts@@ -101,11 +101,17 @@ describe('ownership is never read out of Project.ropes — structural', () => {expect(disp).toContain('open-browser: ') // guard: the slice actually captured the dispatchout.push({ name: 'Canvas open-browser dispatch', code: disp })- // 3. The main-side claim wiring in index.ts (the setControlHandler open-browser claim block).+ // 3. The main-side claim wiring in index.ts: the step that finishes every renderer answer, on+ // time or late (the claim rule itself is in browser-open-claim.ts, covered by 1.).const index = fs.readFileSync(path.join(root, 'src', 'main', 'index.ts'), 'utf8')- const start = index.indexOf("if (verb === 'open-browser' && verified")- expect(start).toBeGreaterThan(-1) // guard: the claim block is where the test expects- out.push({ name: 'main open-browser claim', code: index.slice(start, start + 900) })+ const start = index.indexOf('const finishAnswer = ')+ const end = index.indexOf('return answer', start)+ expect(start).toBeGreaterThan(-1) // guard: the finishing step is where the test expects+ expect(end).toBeGreaterThan(start)+ const finish = index.slice(start, end)+ expect(finish).toContain('claimOpenedBrowser(') // guard: it is the step that records ownership+ out.push({ name: 'main open-browser claim', code: finish })+ expect(out.map((o) => o.name)).toContain('src/main/browser-open-claim.ts')return out}@@ -116,3 +122,20 @@ describe('ownership is never read out of Project.ropes — structural', () => {}})})++/**+ * The late path (review follow-up to #1027). The claim rule is proven by behaviour in+ * browser-open-claim.test.ts, and the forwarder's `finish` on both answers in control-forward.test.ts;+ * what neither can see is index.ts handing THIS finishing step to the forwarder. Drop it and a late+ * open-browser answer is replayed as a success nobody owns — and the on-time claim goes with it.+ */+describe('main hands its finishing step to the control forwarder', () => {+ it('the forward call passes the late-answer path AND finishAnswer', () => {+ const index = fs.readFileSync(path.resolve(__dirname, 'index.ts'), 'utf8').replace(/\r\n/g, '\n')+ const at = index.indexOf('await controlForwarder.forward(')+ expect(at).toBeGreaterThan(-1)+ const call = index.slice(at, index.indexOf('\n )', at))+ expect(call).toContain('onLate: onLateAnswer')+ expect(call).toContain('finish: finishAnswer')+ })+})diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex ba94005ab..8fb4290e4 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -15,6 +15,7 @@ import {} from '../core/agents/hook-sandbox-hint-sh'import { RETRYABLE } from '../core/agents/agent-message-decide'import {+ REQUEST_ID_HINT_LEAD,REQUEST_ID_MAX_LENGTH,REQUEST_ID_OUTCOME_GLOSS,REQUEST_ID_REPLAYED_LEAD,@@ -717,6 +718,15 @@ describe('parseControlRequest', () => {expect(section).toMatch(/NEW id/)expect(section).toMatch(/verified/)expect(section).toMatch(/24 hours/)+ // Review follow-up to #1027: the ids suggested must be UNIQUE (a readable name alone comes back+ // in a later conversation of the same node and replays the old reply), and a reply that may+ // still complete names its id — the CLI's own included — to be passed back with the flag.+ expect(section).toMatch(/UNIQUE/)+ expect(section).toContain('`uuidgen`')+ expect(section).toMatch(/random\s+part/)+ expect(section).not.toMatch(/a name like `wave2-reviewer-1`\)/)+ expect(section).toContain(`\`${REQUEST_ID_HINT_LEAD}\``)+ expect(section).toMatch(/Never re-run the bare command/)const yesAt = section.indexOf('Retry with the SAME id after a short wait')const noAt = section.indexOf('A same-id retry never clears these')expect(yesAt, name).toBeGreaterThan(-1)diff --git a/src/main/canvas-control-shim.request-id.test.ts b/src/main/canvas-control-shim.request-id.test.tsindex 3e464f192..8a22f360a 100644--- a/src/main/canvas-control-shim.request-id.test.ts+++ b/src/main/canvas-control-shim.request-id.test.ts@@ -32,6 +32,10 @@ let home = ''let proxy: net.Serverlet proxied = 0let handled: { verb: string; args: Record<string, string> }[] = []+/** When set, the handler answers like desktop main after its 120 s wait: indeterminate, with the+ * real answer handed back later through `onLateAnswer`. */+let timeOutNext = false+let lateAnswer: ((r: { ok: boolean; message?: string }) => void) | undefinedbeforeAll(async () => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-shim-rid-'))@@ -43,6 +47,11 @@ beforeAll(async () => {hookServer.setNodeAuthSecret(SECRET)hookServer.setControlHandler(async (cmd) => {handled.push({ verb: cmd.verb, args: cmd.args })+ if (timeOutNext) {+ timeOutNext = false+ lateAnswer = cmd.onLateAnswer+ return { ok: false, error: 'no answer within 120s — the request may still complete', indeterminate: true }+ }return { ok: true, message: `opened node #${handled.length}` }})@@ -86,6 +95,8 @@ beforeAll(async () => {beforeEach(() => {handled = []proxied = 0+ timeOutNext = false+ lateAnswer = undefined})afterAll(async () => {@@ -144,6 +155,25 @@ describe('canvas-control shim: a retried open does not open a second node', () =expect(handled).toHaveLength(1)})+ // Review follow-up to #1027. The per-run id is invisible to the agent — until a call times out,+ // when it is the only handle on a call that may still complete. The reply prints it; passing it+ // back as --request-id turns the retry into the SAME call, which answers with what really happened.+ it('a timed-out run prints its per-run id, and passing it back recovers the late answer — one node', async () => {+ timeOutNext = true+ const err = await callShim('node-b', liveEndpoint, ['open-agent', '--agent', 'claude']).then(+ () => null,+ (e: { code: number; stderr: string }) => e+ )+ expect(err?.code).toBe(1)+ const id = /--request-id (cli-[0-9a-f]+)/.exec(err?.stderr ?? '')?.[1]+ expect(id, err?.stderr).toBeDefined()+ lateAnswer?.({ ok: true, message: 'opened node #1 (late)' })+ const retry = await callShim('node-b', liveEndpoint, ['open-agent', '--agent', 'claude', '--request-id', id!])+ expect(retry.stdout).toContain(REQUEST_ID_REPLAYED_LEAD)+ expect(retry.stdout).toContain('opened node #1 (late)')+ expect(handled).toHaveLength(1)+ })+it('two runs without --request-id are two calls: the per-run id protects a run, not a repeat', async () => {await callShim('node-a', liveEndpoint, ['open-terminal'])await callShim('node-a', liveEndpoint, ['open-terminal'])diff --git a/src/main/control-forward.test.ts b/src/main/control-forward.test.tsindex 792422d94..043ef1b3a 100644--- a/src/main/control-forward.test.ts+++ b/src/main/control-forward.test.ts@@ -26,7 +26,7 @@ describe('createControlForwarder', () => {const sent: string[] = []const late = vi.fn()const fwd = createControlForwarder({ timeoutMs: 1000, lateWindowMs: 60_000 })- const p = fwd.forward('open-worktree', (id) => sent.push(id), late)+ const p = fwd.forward('open-worktree', (id) => sent.push(id), { onLate: late })vi.advanceTimersByTime(1000)await pfwd.answer({ requestId: sent[0], ok: true, message: 'opened worktree feat-x' })@@ -39,7 +39,7 @@ describe('createControlForwarder', () => {const sent: string[] = []const late = vi.fn()const fwd = createControlForwarder({ timeoutMs: 1000, lateWindowMs: 5000 })- const p = fwd.forward('open-terminal', (id) => sent.push(id), late)+ const p = fwd.forward('open-terminal', (id) => sent.push(id), { onLate: late })vi.advanceTimersByTime(1000)await pvi.advanceTimersByTime(5000)@@ -56,28 +56,68 @@ describe('createControlForwarder', () => {const fwd = createControlForwarder({ timeoutMs: 1000 })expect(() => fwd.answer({ requestId: 'nope', ok: true })).not.toThrow()})++ // The post-processing main does with an answer (recording who owns an opened browser, a project+ // grant) must run on the answer the caller is eventually TOLD about — which, after a timeout, is+ // the late one the request ledger replays. Skipping it there replayed "opened browser b1" for a+ // browser nobody owned, so the agent could never drive it.+ it('runs `finish` on an on-time answer and returns what it returns', async () => {+ const sent: string[] = []+ const finish = vi.fn((r: { ok: boolean; message?: string }) => ({ ...r, message: `${r.message} (finished)` }))+ const fwd = createControlForwarder({ timeoutMs: 1000 })+ const p = fwd.forward('open-browser', (id) => sent.push(id), { finish })+ fwd.answer({ requestId: sent[0], ok: true, message: 'opened b1' })+ await expect(p).resolves.toEqual({ ok: true, message: 'opened b1 (finished)' })+ expect(finish).toHaveBeenCalledTimes(1)+ })++ it('runs `finish` on a LATE answer before handing it back, and never on the timeout itself', async () => {+ const sent: string[] = []+ const finish = vi.fn((r: { ok: boolean; message?: string }) => ({ ...r, message: `${r.message} (finished)` }))+ const late = vi.fn()+ const fwd = createControlForwarder({ timeoutMs: 1000 })+ const p = fwd.forward('open-browser', (id) => sent.push(id), { onLate: late, finish })+ vi.advanceTimersByTime(1000)+ expect((await p).indeterminate).toBe(true)+ expect(finish).not.toHaveBeenCalled()+ fwd.answer({ requestId: sent[0], ok: true, message: 'opened b1' })+ expect(finish).toHaveBeenCalledTimes(1)+ expect(late).toHaveBeenCalledWith({ ok: true, message: 'opened b1 (finished)' })+ })++ it('without a request-id claim, a timed-out open is told to check the canvas — never pointed at a flag', async () => {+ const fwd = createControlForwarder({ timeoutMs: 120_000 })+ const p = fwd.forward('open-agent', () => {})+ vi.advanceTimersByTime(120_000)+ const r = await p+ expect(r.error).toMatch(/check the canvas for its effect before retrying/)+ expect(r.error).not.toMatch(/--request-id/)+ })})describe('controlTimeoutError', () => {it('a confirm-gated verb keeps its dialog wording: the dialog dismisses itself at the same deadline', () => {- expect(controlTimeoutError('write', 120_000)).toBe(+ expect(controlTimeoutError('write', 120_000, false)).toBe('no answer within 120s — the confirmation dialog has been dismissed; safe to retry')})- it('a verb that creates something is NOT called safe to retry: the renderer was not cancelled', () => {- const msg = controlTimeoutError('open-worktree', 120_000)+ it('with a claim, says the call may have taken effect and leaves the id to the route that holds it', () => {+ const msg = controlTimeoutError('open-worktree', 120_000, true)expect(msg).toMatch(/^no answer within 120s/)expect(msg).not.toMatch(/safe to retry/)expect(msg).toMatch(/may still complete/)- expect(msg).toMatch(/--request-id/)- expect(msg).toMatch(/`list`/)+ // The forwarder never sees the id; printing a flag with no value to pass is how an agent came to+ // re-run the bare command and open a second one.+ expect(msg).not.toMatch(/--request-id/)})- it('any other verb is told to check before retrying, and is not pointed at a flag it cannot take', () => {- const msg = controlTimeoutError('rename', 120_000)- expect(msg).not.toMatch(/safe to retry/)- expect(msg).not.toMatch(/--request-id/)- expect(msg).toMatch(/may still complete/)+ it('without a claim, every verb gets the generic check-the-canvas sentence', () => {+ for (const verb of ['open-worktree', 'open-agent', 'rename']) {+ const msg = controlTimeoutError(verb, 120_000, false)+ expect(msg, verb).not.toMatch(/safe to retry/)+ expect(msg, verb).not.toMatch(/--request-id/)+ expect(msg, verb).toMatch(/may still complete; check the canvas for its effect before retrying/)+ }})})diff --git a/src/main/control-forward.ts b/src/main/control-forward.tsindex 0058e9d22..fbbf09062 100644--- a/src/main/control-forward.ts+++ b/src/main/control-forward.ts@@ -9,9 +9,14 @@// the timeout answers `indeterminate: true` (the request ledger then refuses a retry as "unknown"// instead of running it a second time), and an answer that arrives afterwards is handed to the// caller's `onLate` so the ledger can replay what really happened to the next retry.+//+// WHATEVER MAIN DOES WITH AN ANSWER RUNS ON BOTH. Main post-processes the renderer's answer+// (recording who owns an opened browser, a project grant). That step is `finish`, and the forwarder+// applies it to the on-time answer AND to a late one before handing it off: the late answer is the+// one the ledger replays, and replaying "opened browser b1" without the ownership record told the+// agent it had a browser it could never drive.import { randomUUID } from 'node:crypto'import { isDestructiveVerb } from '../shared/control-verbs'-import { REQUEST_ID_VERBS } from '../core/control-request-ledger'export interface ControlForwardReply {ok: boolean@@ -25,18 +30,19 @@ export interface ControlForwardReply {* The timeout's sentence, by what the verb could still be doing. Only a confirm-gated verb may be* called safe to retry: its dialog is gone, so nothing was confirmed. Anything else may still* complete, and telling an agent it is safe to retry an open is how a second node gets opened.+ *+ * `claimed` = the request ledger holds a row for this call (the forwarder was given `onLate`). Then+ * the ROUTE, which holds the id, adds the line that names it and says to pass it as `--request-id`+ * (`requestIdRetryHint`); this sentence must not point at the flag itself, because the forwarder+ * never sees the id — and a flag with no value to pass is how an agent came to re-run the bare+ * command, get a fresh id, and open a second one. Without a claim there is no id to pass at all:+ * the only honest advice is to look before retrying.*/-export function controlTimeoutError(verb: string, timeoutMs: number): string {+export function controlTimeoutError(verb: string, timeoutMs: number, claimed: boolean): string {const lead = `no answer within ${timeoutMs / 1000}s`if (isDestructiveVerb(verb)) return `${lead} — the confirmation dialog has been dismissed; safe to retry`- if (REQUEST_ID_VERBS.has(verb)) {- return (- `${lead} — the request was not cancelled and may still complete, so it may have taken effect: ` +- 'retry the same command with the same --request-id to get its answer, or run `list` before ' +- 'opening anything again'- )- }- return `${lead} — the request was not cancelled and may still complete; check its effect before retrying`+ if (claimed) return `${lead} — the request was not cancelled and may still complete, so it may have taken effect`+ return `${lead} — the request was not cancelled and may still complete; check the canvas for its effect before retrying`}/** How long a late renderer answer is still worth handing back. Past it the ledger row stays@@ -48,32 +54,51 @@ export function createControlForwarder(opts: {lateWindowMs?: numbernewId?: () => string}): {- /** Send via `send(requestId)` and wait for `answer` with that id, at most `timeoutMs`. */+ /**+ * Send via `send(requestId)` and wait for `answer` with that id, at most `timeoutMs`. `finish`+ * post-processes whichever answer arrives (on time, or late before it goes to `onLate`); it never+ * runs on the timeout's own reply, which is not an answer.+ */forward(verb: string,send: (requestId: string) => void,- onLate?: (reply: ControlForwardReply) => void+ opts?: {+ onLate?: (reply: ControlForwardReply) => void+ finish?: (reply: ControlForwardReply) => ControlForwardReply+ }): Promise<ControlForwardReply>/** The renderer's answer (the `agentControlResult` IPC). */answer(payload: { requestId: string } & ControlForwardReply): void} {const newId = opts.newId ?? randomUUIDconst lateWindowMs = opts.lateWindowMs ?? LATE_CONTROL_ANSWER_MS- const pending = new Map<string, { resolve: (r: ControlForwardReply) => void; timer: NodeJS.Timeout }>()- const late = new Map<string, { onLate: (r: ControlForwardReply) => void; timer: NodeJS.Timeout }>()+ type Finish = (r: ControlForwardReply) => ControlForwardReply+ const same: Finish = (r) => r+ const pending = new Map<+ string,+ { resolve: (r: ControlForwardReply) => void; finish: Finish; timer: NodeJS.Timeout }+ >()+ const late = new Map<+ string,+ { onLate: (r: ControlForwardReply) => void; finish: Finish; timer: NodeJS.Timeout }+ >()return {- forward(verb, send, onLate) {+ forward(verb, send, { onLate, finish = same } = {}) {const requestId = newId()return new Promise<ControlForwardReply>((resolve) => {const timer = setTimeout(() => {pending.delete(requestId)if (onLate) {const lateTimer = setTimeout(() => late.delete(requestId), lateWindowMs)- late.set(requestId, { onLate, timer: lateTimer })+ late.set(requestId, { onLate, finish, timer: lateTimer })}- resolve({ ok: false, error: controlTimeoutError(verb, opts.timeoutMs), indeterminate: true })+ resolve({+ ok: false,+ error: controlTimeoutError(verb, opts.timeoutMs, onLate !== undefined),+ indeterminate: true+ })}, opts.timeoutMs)- pending.set(requestId, { resolve, timer })+ pending.set(requestId, { resolve, finish, timer })send(requestId)})},@@ -82,14 +107,14 @@ export function createControlForwarder(opts: {if (waiting) {clearTimeout(waiting.timer)pending.delete(requestId)- waiting.resolve(reply)+ waiting.resolve(waiting.finish(reply))return}const after = late.get(requestId)if (!after) returnclearTimeout(after.timer)late.delete(requestId)- after.onLate(reply)+ after.onLate(after.finish(reply))}}}diff --git a/src/main/index.ts b/src/main/index.tsindex dc060d42c..c38d143e2 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -276,7 +276,8 @@ import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/controlimport { issueFlagRefusal } from '../core/canvas-control-core'import { afterPrFlagRefusal } from '../shared/pr-wait'import { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'-import { createControlForwarder } from './control-forward'+import { createControlForwarder, type ControlForwardReply } from './control-forward'+import { claimOpenedBrowser } from './browser-open-claim'import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'@@ -3824,66 +3825,60 @@ app.whenReady().then(async () => {}const target = getMainWindow()if (!target) return { ok: false, error: 'window unavailable' }- // The timeout is NAMED, and what it says depends on the verb (`controlTimeoutError`): a DENIAL- // is a different answer (`denied by user`, final), and only a confirm-gated verb, whose dialog- // dismisses itself at the same deadline (ConfirmState.expiresAt), may be called safe to retry.- // An open is not cancelled by main giving up, so its timeout is indeterminate and its late- // answer goes back to the request ledger through `onLateAnswer`.- const result = await controlForwarder.forward(- verb,- (requestId) =>- target.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args }),- onLateAnswer- )- // Record browser ownership the moment an open-browser succeeds — and ONLY when the caller's- // identity verdict for THIS request was `verified` (main's own verdict, not anything off the- // wire or project.json). A `legacy`/warned caller may open a browser but owns nothing, so it- // can drive nothing. The owner is the verified caller (`nodeId`); the project id + partition- // ride along from the renderer's reply for release-by-project and the indicator. This is the- // browser sibling of pane-ownership's record-at-fresh-spawn. See browser-control-ledger.ts and- // browser-ownership-source.test.ts (ownership is NEVER read from Project.ropes).- if (verb === 'open-browser' && verified && result.ok) {- const opened = result.result as { id?: string; projectId?: string; partition?: string } | undefined- // Refuse to record an entry with no owning project: `releaseByProject('')` would match it, and- // a project-less ownership record is meaningless. Fail-closed against future reply-shape drift- // — today `partition` is present only when agentBrowserPartition(projectId) succeeded, so a- // non-empty safe projectId always rides with it.- if (opened?.id && opened.partition && opened.projectId) {- browserLedger.claim(opened.id, {- ownerNodeId: nodeId,- projectId: opened.projectId,- partition: opened.partition,- navGeneration: 0,- leaseActiveUntil: 0,- openedAt: Date.now()- })+ // What main does with the renderer's answer, as ONE step the forwarder runs on whichever answer+ // arrives: on time, or LATE — after the 120 s wait below gave up — before the request ledger+ // stores it for a retry to replay. A late answer is the same answer, only later: the node exists+ // and this caller opened it, so it owes exactly what an on-time answer owes. Keeping it off this+ // path replayed "opened browser b1" for a browser its opener could never drive.+ const finishAnswer = (answer: ControlForwardReply): ControlForwardReply => {+ // Record browser ownership the moment an open-browser succeeds — and ONLY when the caller's+ // identity verdict for THIS request was `verified` (main's own verdict, not anything off the+ // wire or project.json). A `legacy`/warned caller may open a browser but owns nothing, so it+ // can drive nothing. The owner is the verified caller (`nodeId`); the project id + partition+ // ride along from the renderer's reply for release-by-project and the indicator. This is the+ // browser sibling of pane-ownership's record-at-fresh-spawn. See browser-open-claim.ts,+ // browser-control-ledger.ts and browser-ownership-source.test.ts (ownership is NEVER read+ // from Project.ropes).+ if (claimOpenedBrowser(browserLedger, { verb, ownerNodeId: nodeId, verified }, answer, Date.now())) {// A claim carries no live lease (a verb sets that in PR 7), so this does not light the chip;// it keeps the renderer's view consistent from the moment ownership exists.pushBrowserLeases()}- }- // Record a project grant the moment an open-project succeeds — the open-browser ledger- // pattern above, same conditions: ONLY when the caller's identity verdict for THIS request- // was `verified` (main's own verdict, never anything off the wire) AND the renderer's reply- // carries a non-empty projectId. Inert until PR 2: today the renderer's `default:` case- // answers `unknown verb: open-project` with ok: false, so nothing is ever recorded — but the- // record path ships fail-closed and finished, not stubbed.- if (verb === 'open-project') {- // The whole decision (verified && ok && string projectId → grant; cap race detection) is- // the PURE recordOpenProjectGrant — proven branch by branch in project-grants.test.ts.- // 'cap' = the pre-forward atCap() check passed but a concurrent open-project from the same- // caller filled the last slot while this one was in flight (PR #362 review, M1): the- // caller must NOT hear ok while holding no targeting right, so the named refusal replaces- // the success reply. Nothing is lost — open-project is idempotent (B1), so a re-run once- // grants have cleared returns the same project id and records the grant.- if (recordOpenProjectGrant(nodeId, result, verified) === 'cap') {- console.warn(- `[project-grants] grant cap raced for caller ${nodeId}: open-project succeeded but ` +- 'the grant was not recorded; replying open-project-grant-cap'- )- return { ok: false, error: OPEN_PROJECT_GRANT_CAP, message: OPEN_PROJECT_GRANT_CAP }+ // Record a project grant the moment an open-project succeeds — the open-browser ledger+ // pattern above, same conditions: ONLY when the caller's identity verdict for THIS request+ // was `verified` (main's own verdict, never anything off the wire) AND the renderer's reply+ // carries a non-empty projectId. (open-project never claims a request-ledger row, so it never+ // gets a late answer; it is here so no finishing step can be left off one path.)+ if (verb === 'open-project') {+ // The whole decision (verified && ok && string projectId → grant; cap race detection) is+ // the PURE recordOpenProjectGrant — proven branch by branch in project-grants.test.ts.+ // 'cap' = the pre-forward atCap() check passed but a concurrent open-project from the same+ // caller filled the last slot while this one was in flight (PR #362 review, M1): the+ // caller must NOT hear ok while holding no targeting right, so the named refusal replaces+ // the success reply. Nothing is lost — open-project is idempotent (B1), so a re-run once+ // grants have cleared returns the same project id and records the grant.+ if (recordOpenProjectGrant(nodeId, answer, verified) === 'cap') {+ console.warn(+ `[project-grants] grant cap raced for caller ${nodeId}: open-project succeeded but ` ++ 'the grant was not recorded; replying open-project-grant-cap'+ )+ return { ok: false, error: OPEN_PROJECT_GRANT_CAP, message: OPEN_PROJECT_GRANT_CAP }+ }}+ return answer}+ // The timeout is NAMED, and what it says depends on the verb and on whether the request ledger+ // holds a row for this call (`controlTimeoutError`): a DENIAL is a different answer (`denied by+ // user`, final), and only a confirm-gated verb, whose dialog dismisses itself at the same+ // deadline (ConfirmState.expiresAt), may be called safe to retry. An open is not cancelled by+ // main giving up, so its timeout is indeterminate and its late answer goes back to the request+ // ledger through `onLateAnswer` — finished first.+ const result = await controlForwarder.forward(+ verb,+ (requestId) =>+ target.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args }),+ { onLate: onLateAnswer, finish: finishAnswer }+ )return result})initMediaProtocol()diff --git a/src/main/project-grants.test.ts b/src/main/project-grants.test.tsindex 19105856c..f54f6cef0 100644--- a/src/main/project-grants.test.ts+++ b/src/main/project-grants.test.ts@@ -355,11 +355,13 @@ describe('main wiring (structural) — the wrapper records, consumes and clears// through that function exactly once, with main's own verdict, and a 'cap' answer replaces// the success reply with the named refusal (review M1 — no ok without a recorded right).expect(src.match(/recordOpenProjectGrant\(/g)?.length).toBe(1)+ // It sits in `finishAnswer`, the step main runs on every renderer answer — on time or late+ // (src/main/control-forward.ts) — so the reply it guards is `answer`, not the awaited result.expect(src).toMatch(- /if \(recordOpenProjectGrant\(nodeId, result, verified\) === 'cap'\) \{/+ /if \(recordOpenProjectGrant\(nodeId, answer, verified\) === 'cap'\) \{/)- const at = src.indexOf("recordOpenProjectGrant(nodeId, result, verified) === 'cap'")- const block = src.slice(at, src.indexOf('return result', at))+ const at = src.indexOf("recordOpenProjectGrant(nodeId, answer, verified) === 'cap'")+ const block = src.slice(at, src.indexOf('return answer', at))expect(block).toContain('error: OPEN_PROJECT_GRANT_CAP')// No raw grant() call sneaks around the pure decision anywhere in main's entry.expect(src).not.toMatch(/\bgrantProjectTo\(|[^A-Za-z]grant\(nodeId/)