Skip to content

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.

fix(control): announce the per-run id before posting; guard finishAnswer

reviewaa8c289bb04f
diff --git a/CLAUDE.md b/CLAUDE.md
index 6233fe778..3d1398e8b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3179,7 +3179,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
**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;
+ to re-run the bare command, get a fresh id and open a second one. That reply is not enough on
+ its own: an agent's tool call is typically killed at 120 s — the SAME instant the app gives up —
+ so the shim also prints the per-run id to stderr BEFORE posting an open it carries no caller id
+ for (`requestIdAnnounceLine`, skipped for a caller's own `--request-id` and for `--dry-run`), and
+ both agent bodies say to pass an OWN unique id up front for slow opens (open-worktree,
+ spawn-team, verify) with a tool timeout above 120 s. A `finishAnswer` step that throws never
+ escapes into the IPC listener: on time it resolves indeterminate, late it hands nothing back (the
+ row stays unknown);
(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 flag
exists to end — while a malformed or out-of-set per-run id is silently ignored; (8) a dry run
@@ -3190,7 +3197,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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
+ must be UNIQUE (a uuid — `$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)`, since slim
+ Linux lacks `uuidgen` and macOS lacks `/proc` — 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 SSH
host keeps the shim it got at its last connect, so until that project reconnects its runs carry
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index b9c2957bd..dc1d5d28f 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -32,6 +32,7 @@ import {
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 { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'
import {
REQUEST_ID_HINT_LEAD,
REQUEST_ID_MAX_LENGTH,
@@ -39,7 +40,8 @@ import {
REQUEST_ID_REPLAYED_LEAD,
REQUEST_ID_RETRYABLE,
REQUEST_ID_VERBS,
- REQUEST_LEDGER_TTL_MS
+ REQUEST_LEDGER_TTL_MS,
+ requestIdAnnounceLine
} from './control-request-ledger'
/**
@@ -470,6 +472,9 @@ function dryRunDocLines(): string[] {
* the retention — the same derive-don't-retype rule as `messagingGuidanceLines`, so an outcome or a
* verb added there lands in the text an agent reads the day it is added.
*/
+// The opens that can take longer than the app's own wait: git work, a whole team, a review panel.
+const SLOW_OPEN_VERBS = ['open-worktree', 'spawn-team', 'verify'] as const
+
function requestIdDocLines(): string[] {
const yes: string[] = []
const no: string[] = []
@@ -482,7 +487,9 @@ 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. Make each id UNIQUE: a uuid (`uuidgen`), or a readable name with a random',
+ ' a letter or digit. Make each id UNIQUE: a uuid',
+ ' (`$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)`: slim Linux images lack',
+ ' `uuidgen`, macOS lacks `/proc`), 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.',
@@ -495,8 +502,13 @@ 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',
+ `- For an open that can be slow — ${SLOW_OPEN_VERBS.join(', ')}, or any open while the app may be busy —`,
+ ' pass your OWN unique `--request-id` up front, and give the tool call a timeout longer than',
+ ` the app's own ${CONTROL_REQUEST_TIMEOUT_MS / 1000}s wait (180s is safe). At a ${CONTROL_REQUEST_TIMEOUT_MS / 1000}s tool default the tool is killed at the`,
+ ' same moment the app gives up, and the reply that would have named the id is lost with it.',
+ `- When you pass none, the CLI picks an id per run and prints it to stderr BEFORE it sends the`,
+ ` open (\`${requestIdAnnounceLine('<id>')}\`); a reply that says the call may still`,
+ ` complete names it again on a \`${REQUEST_ID_HINT_LEAD}\` line. 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',
@@ -957,6 +969,17 @@ fi
# write/close/rename/color/branch/send/reply/sticky/run forms accept — into curl --data-urlencode arguments. The positional
# list doubles as the accumulator: originals are consumed from the front, translated pairs
# appended at the back, so "$@" holds exactly the curl args once the loop drains.
+# Two flags the shim itself acts on (before posting, below): a caller that named its own
+# --request-id already knows it, and a --dry-run claims nothing.
+nt_own_request_id=""
+nt_dry_run=""
+nt_note_flag() {
+ case "$1" in
+ request-id) nt_own_request_id=1 ;;
+ dry-run) nt_dry_run=1 ;;
+ esac
+}
+
nt_seen_pos=0
nt_count=$#
nt_i=0
@@ -969,6 +992,7 @@ while [ "$nt_i" -lt "$nt_count" ]; do
nt_k=\${nt_a#--}
nt_v=\${nt_k#*=}
nt_k=\${nt_k%%=*}
+ nt_note_flag "$nt_k"
set -- "$@" --data-urlencode "arg.$nt_k=$nt_v"
;;
--*)
@@ -984,6 +1008,7 @@ while [ "$nt_i" -lt "$nt_count" ]; do
# \`--text=--oops\`, which the branch above exists for and which was previously unexpressible
# in either direction.
nt_k=\${nt_a#--}
+ nt_note_flag "$nt_k"
nt_v=""
if [ "$nt_i" -lt "$nt_count" ]; then
case "$1" in
@@ -1049,6 +1074,15 @@ nt_control_post() {
# Only a dead transport or an explicit wrong-owner (421) answer permits failover; 403 stays final.
nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ] && [ "$nt_code" != "421" ]; }
+# Say the per-run id BEFORE posting an open (see requestIdAnnounceLine): an agent's own tool call is
+# usually killed at 120 s, the same instant the app gives up waiting, and with it the reply that
+# would have named the id. On stderr, so stdout stays the reply alone.
+if [ -z "$nt_own_request_id" ] && [ -z "$nt_dry_run" ]; then
+ case "$nt_verb" in
+ ${[...REQUEST_ID_VERBS].join('|')}) echo "${requestIdAnnounceLine('$nt_request_id')}" >&2 ;;
+ esac
+fi
+
nt_had_transport=""
nt_control_post "$@"
diff --git a/src/core/control-request-ledger.ts b/src/core/control-request-ledger.ts
index bbe8a5230..f43cedf23 100644
--- a/src/core/control-request-ledger.ts
+++ b/src/core/control-request-ledger.ts
@@ -146,6 +146,16 @@ export function requestIdRetryHint(requestId: string): string {
)
}
+/**
+ * What the shim prints to STDERR before it posts an open the caller gave no id for. An agent's own
+ * tool call is usually killed at 120 s — the same instant the app gives up waiting — so the reply
+ * carrying `requestIdRetryHint` may never be seen; this line is on screen before anything can go
+ * wrong. `id` is interpolated as-is, so the shim passes its shell variable.
+ */
+export function requestIdAnnounceLine(id: string): string {
+ return `${REQUEST_ID_HINT_LEAD} ${id} (pass --request-id ${id} if you retry)`
+}
+
/** 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 ' +
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 8fb4290e4..197c029e1 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -38,7 +38,7 @@ import {
SETTINGS_VERB_KEY_LIST,
readSettingsValue
} from '../shared/settings-verb'
-import { decideControlConfirm, isWaivableVerb } from '../shared/control-confirm'
+import { CONTROL_REQUEST_TIMEOUT_MS, decideControlConfirm, isWaivableVerb } from '../shared/control-confirm'
import { DEFAULT_SETTINGS } from '../shared/types'
import { serverSettingsControl } from '../server/settings-control'
import {
@@ -722,8 +722,17 @@ describe('parseControlRequest', () => {
// 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`')
+ // A portable uuid: `uuidgen` is missing on slim Debian/Ubuntu (uuid-runtime), macOS has no /proc.
+ expect(section).toContain('`$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)`')
expect(section).toMatch(/random\s+part/)
+ // Review follow-up to #1033: an agent's tool call is typically killed at the same 120 s the app
+ // waits, so the advice for a slow open is to name the id up front and give the tool more time;
+ // and the CLI's own id is on stderr before the POST, whatever becomes of the reply.
+ expect(section).toMatch(/OWN\s+unique\s+`--request-id`\s+up\s+front/)
+ for (const verb of ['open-worktree', 'spawn-team', 'verify']) expect(section).toContain(verb)
+ expect(section).toContain(`${CONTROL_REQUEST_TIMEOUT_MS / 1000}s`)
+ expect(section).toMatch(/timeout\s+longer\s+than/)
+ expect(section).toMatch(/to\s+stderr\s+BEFORE\s+it\s+sends/)
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/)
diff --git a/src/main/canvas-control-shim.request-id.test.ts b/src/main/canvas-control-shim.request-id.test.ts
index 8a22f360a..7eac6c3d4 100644
--- a/src/main/canvas-control-shim.request-id.test.ts
+++ b/src/main/canvas-control-shim.request-id.test.ts
@@ -7,7 +7,7 @@
// the shim walk to another endpoint of the same app and POST again (issue #445's failover). Before
// the per-run request id, that re-post was a second call and opened a second node.
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'
-import { execFile } from 'node:child_process'
+import { execFile, spawn } from 'node:child_process'
import fs from 'node:fs'
import net from 'node:net'
import os from 'node:os'
@@ -16,7 +16,7 @@ import { promisify } from 'node:util'
import { CONTROL_SHIM_SCRIPT } from '../core/canvas-control-core'
import { hookServer } from '../core/agents/hook-server'
import { nodeAuthToken } from '../core/agents/node-auth-token'
-import { REQUEST_ID_REPLAYED_LEAD } from '../core/control-request-ledger'
+import { REQUEST_ID_REPLAYED_LEAD, requestIdAnnounceLine } from '../core/control-request-ledger'
import { initPlatform, resetPlatformForTests } from '../core/platform'
import { fakePlatform } from '../core/platform-fake'
@@ -36,6 +36,8 @@ let handled: { verb: string; args: Record<string, string> }[] = []
* real answer handed back later through `onLateAnswer`. */
let timeOutNext = false
let lateAnswer: ((r: { ok: boolean; message?: string }) => void) | undefined
+/** When set, the handler parks until the test releases it — a call still in flight. */
+let parkNext: Promise<void> | undefined
beforeAll(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-shim-rid-'))
@@ -47,6 +49,11 @@ beforeAll(async () => {
hookServer.setNodeAuthSecret(SECRET)
hookServer.setControlHandler(async (cmd) => {
handled.push({ verb: cmd.verb, args: cmd.args })
+ if (parkNext) {
+ const parked = parkNext
+ parkNext = undefined
+ await parked
+ }
if (timeOutNext) {
timeOutNext = false
lateAnswer = cmd.onLateAnswer
@@ -97,6 +104,7 @@ beforeEach(() => {
proxied = 0
timeOutNext = false
lateAnswer = undefined
+ parkNext = undefined
})
afterAll(async () => {
@@ -174,6 +182,43 @@ describe('canvas-control shim: a retried open does not open a second node', () =
expect(handled).toHaveLength(1)
})
+ // Review follow-up to #1033. The `request id:` line on a timed-out reply only helps a caller that
+ // SEES the reply, and an agent's tool call is usually killed at 120 s — the same instant the app
+ // gives up. So the id is on stderr BEFORE the POST: here while the call is still in flight, with no
+ // reply anywhere, and it is the id the ledger holds (passing it back replays, never re-runs).
+ it('announces the per-run id on stderr before any reply exists, and that id is the one the ledger holds', async () => {
+ let release!: () => void
+ parkNext = new Promise<void>((resolve) => (release = resolve))
+ const child = spawn('/bin/sh', [shim, 'open-worktree', '--branch', 'feat-slow'], {
+ env: {
+ PATH: process.env.PATH ?? '',
+ NODETERM_CANVAS_CONTROL: '1',
+ NODETERM_NODE_ID: 'node-c',
+ NODETERM_HOOK_ENDPOINT: liveEndpoint,
+ HOME: home
+ }
+ })
+ let stderr = ''
+ let stdout = ''
+ child.stderr.on('data', (c: Buffer) => (stderr += c.toString()))
+ child.stdout.on('data', (c: Buffer) => (stdout += c.toString()))
+ const exited = new Promise<number | null>((resolve) => child.on('exit', resolve))
+ for (let i = 0; i < 400 && !(handled.length === 1 && /request id: /.test(stderr)); i++) {
+ await new Promise((r) => setTimeout(r, 10))
+ }
+ // In flight: the server is holding the call and has answered nothing, yet the id is on screen.
+ expect(handled).toHaveLength(1)
+ expect(stdout).toBe('')
+ const id = /request id: (cli-[0-9a-f]+) /.exec(stderr)?.[1]
+ expect(id, stderr).toBeDefined()
+ expect(stderr).toContain(requestIdAnnounceLine(id!))
+ release()
+ expect(await exited).toBe(0)
+ const retry = await callShim('node-c', liveEndpoint, ['open-worktree', '--branch', 'feat-slow', '--request-id', id!])
+ expect(retry.stdout).toContain(REQUEST_ID_REPLAYED_LEAD)
+ 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.ts
index 043ef1b3a..ee60d1d09 100644
--- a/src/main/control-forward.test.ts
+++ b/src/main/control-forward.test.ts
@@ -85,6 +85,53 @@ describe('createControlForwarder', () => {
expect(late).toHaveBeenCalledWith({ ok: true, message: 'opened b1 (finished)' })
})
+ // Review NIT on #1033: `finish` runs after the pending entry is gone. A throw there used to escape
+ // into the IPC listener with `resolve` never called — the route's handler hung, and its ledger row
+ // sat in flight until stale. The answer existed, so the effect may have happened: indeterminate.
+ it('a finishing step that throws on an on-time answer resolves INDETERMINATE instead of hanging', async () => {
+ const sent: string[] = []
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const fwd = createControlForwarder({ timeoutMs: 1000 })
+ const p = fwd.forward('open-browser', (id) => sent.push(id), {
+ onLate: () => {},
+ finish: () => {
+ throw new Error('ledger exploded')
+ }
+ })
+ expect(() => fwd.answer({ requestId: sent[0], ok: true, message: 'opened b1' })).not.toThrow()
+ const r = await p
+ expect(r.ok).toBe(false)
+ expect(r.indeterminate).toBe(true)
+ expect(r.error).toMatch(/may have taken effect/)
+ expect(warn).toHaveBeenCalled()
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('a finishing step that throws on a LATE answer hands nothing back and does not throw', async () => {
+ const sent: string[] = []
+ const late = vi.fn()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const fwd = createControlForwarder({ timeoutMs: 1000 })
+ const p = fwd.forward('open-browser', (id) => sent.push(id), {
+ onLate: late,
+ finish: () => {
+ throw new Error('ledger exploded')
+ }
+ })
+ vi.advanceTimersByTime(1000)
+ await p
+ expect(() => fwd.answer({ requestId: sent[0], ok: true, message: 'opened b1' })).not.toThrow()
+ // The row stays unknown: an answer main could not finish is not one to replay.
+ expect(late).not.toHaveBeenCalled()
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
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', () => {})
diff --git a/src/main/control-forward.ts b/src/main/control-forward.ts
index fbbf09062..a8f8f3805 100644
--- a/src/main/control-forward.ts
+++ b/src/main/control-forward.ts
@@ -45,6 +45,17 @@ export function controlTimeoutError(verb: string, timeoutMs: number, claimed: bo
return `${lead} — the request was not cancelled and may still complete; check the canvas for its effect before retrying`
}
+/**
+ * The reply when main's own finishing step throws on an answer the renderer DID give. The effect may
+ * well have happened (the renderer answered), so this is indeterminate like a timeout — and worded by
+ * the same claim rule: with a ledger row the route adds the id to pass back, without one the only
+ * honest advice is to look first.
+ */
+export function controlFinishError(verb: string, claimed: boolean): string {
+ const lead = `${verb}: the app could not finish processing the answer, so it may have taken effect`
+ return claimed ? lead : `${lead}; 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
* unknown and a retry is told to `list`. */
export const LATE_CONTROL_ANSWER_MS = 30 * 60 * 1000
@@ -74,13 +85,31 @@ export function createControlForwarder(opts: {
const lateWindowMs = opts.lateWindowMs ?? LATE_CONTROL_ANSWER_MS
type Finish = (r: ControlForwardReply) => ControlForwardReply
const same: Finish = (r) => r
+ // `finish` runs after the pending entry is gone, inside the IPC listener. A throw there must not
+ // escape (nothing would resolve the route's handler, and its ledger row would sit in flight until
+ // stale): it becomes an indeterminate reply on time, and on the late path no answer at all — the
+ // row stays unknown, because an answer main could not finish is not one to replay.
+ const guarded = (verb: string, finish: Finish, reply: ControlForwardReply): ControlForwardReply | null => {
+ try {
+ return finish(reply)
+ } catch (e) {
+ console.warn(`[canvas-control] finishing the ${verb} answer failed`, e)
+ return null
+ }
+ }
const pending = new Map<
string,
- { resolve: (r: ControlForwardReply) => void; finish: Finish; timer: NodeJS.Timeout }
+ {
+ resolve: (r: ControlForwardReply) => void
+ verb: string
+ claimed: boolean
+ finish: Finish
+ timer: NodeJS.Timeout
+ }
>()
const late = new Map<
string,
- { onLate: (r: ControlForwardReply) => void; finish: Finish; timer: NodeJS.Timeout }
+ { onLate: (r: ControlForwardReply) => void; verb: string; finish: Finish; timer: NodeJS.Timeout }
>()
return {
forward(verb, send, { onLate, finish = same } = {}) {
@@ -90,7 +119,7 @@ export function createControlForwarder(opts: {
pending.delete(requestId)
if (onLate) {
const lateTimer = setTimeout(() => late.delete(requestId), lateWindowMs)
- late.set(requestId, { onLate, finish, timer: lateTimer })
+ late.set(requestId, { onLate, verb, finish, timer: lateTimer })
}
resolve({
ok: false,
@@ -98,7 +127,7 @@ export function createControlForwarder(opts: {
indeterminate: true
})
}, opts.timeoutMs)
- pending.set(requestId, { resolve, finish, timer })
+ pending.set(requestId, { resolve, verb, claimed: onLate !== undefined, finish, timer })
send(requestId)
})
},
@@ -107,14 +136,22 @@ export function createControlForwarder(opts: {
if (waiting) {
clearTimeout(waiting.timer)
pending.delete(requestId)
- waiting.resolve(waiting.finish(reply))
+ const finished = guarded(waiting.verb, waiting.finish, reply)
+ waiting.resolve(
+ finished ?? {
+ ok: false,
+ error: controlFinishError(waiting.verb, waiting.claimed),
+ indeterminate: true
+ }
+ )
return
}
const after = late.get(requestId)
if (!after) return
clearTimeout(after.timer)
late.delete(requestId)
- after.onLate(after.finish(reply))
+ const finished = guarded(after.verb, after.finish, reply)
+ if (finished) after.onLate(finished)
}
}
}
diff --git a/src/main/control-shim-parse.test.ts b/src/main/control-shim-parse.test.ts
index 3998fd05a..f30fa323d 100644
--- a/src/main/control-shim-parse.test.ts
+++ b/src/main/control-shim-parse.test.ts
@@ -10,13 +10,13 @@
// failure and exit 1, and every case here would fail for a reason that has nothing to do with
// parsing. stderr is no good either — the shim sends curl's stderr to /dev/null.
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
-import { execFileSync } from 'node:child_process'
+import { execFileSync, spawnSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { CONTROL_SHIM_SCRIPT } from '../core/canvas-control-core'
import { runNowRequested } from '../shared/control-verbs'
-import { isValidRequestId } from '../core/control-request-ledger'
+import { REQUEST_ID_VERBS, isValidRequestId, requestIdAnnounceLine } from '../core/control-request-ledger'
let dir = ''
@@ -90,6 +90,40 @@ describe('the control shim tags each run with its own request id', () => {
expect(isValidRequestId(got[0])).toBe(true)
})
+ // Review follow-up to #1033: an agent's own tool call is usually killed at 120 s — the same
+ // instant the app gives up — so the reply naming the id may never be seen. The id is therefore
+ // printed to stderr BEFORE the POST, for every verb the ledger covers, and only when the caller did
+ // not pass its own (then it already knows it) and it is not a dry run (which claims nothing).
+ it('announces the per-run id on stderr before posting, for exactly the verbs the ledger covers', () => {
+ const stderrOf = (args: string[]): string =>
+ spawnSync('sh', [path.join(dir, 'shim.sh'), ...args], {
+ env: {
+ PATH: `${path.join(dir, 'bin')}:${process.env.PATH ?? ''}`,
+ NODETERM_CANVAS_CONTROL: '1',
+ NODETERM_HOOK_PORT: '1',
+ NODETERM_NODE_ID: 'n1',
+ NT_ARGV_LOG: path.join(dir, 'argv.log'),
+ HOME: dir
+ },
+ encoding: 'utf8'
+ }).stderr
+ for (const verb of REQUEST_ID_VERBS) {
+ const err = stderrOf([verb])
+ const posted = ids([verb])
+ expect(err, verb).toMatch(/^request id: cli-/)
+ // The announced id is well-formed and has the exact announced shape.
+ const announced = /^request id: (\S+) /.exec(err)?.[1] ?? ''
+ expect(isValidRequestId(announced), verb).toBe(true)
+ expect(err, verb).toContain(requestIdAnnounceLine(announced))
+ expect(posted, verb).toHaveLength(1)
+ }
+ expect(stderrOf(['rename', '--node', 'n1', '--title', 't'])).not.toMatch(/request id:/)
+ expect(stderrOf(['list'])).not.toMatch(/request id:/)
+ expect(stderrOf(['open-agent', '--agent', 'claude', '--request-id', 'mine-1'])).not.toMatch(/request id:/)
+ expect(stderrOf(['open-agent', '--agent', 'claude', '--request-id=mine-1'])).not.toMatch(/request id:/)
+ expect(stderrOf(['spawn-team', '--dry-run', '--team', '[]'])).not.toMatch(/request id:/)
+ })
+
it('an explicit --request-id rides as an ordinary arg next to the per-run id', () => {
expect(run(['open-terminal', '--request-id', 'wave1-a'])).toEqual(['arg.request-id=wave1-a'])
expect(ids(['open-terminal', '--request-id', 'wave1-a'])).toHaveLength(1)