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(agents): only count an interrupt marker whose turn was opened before it
review061e1f5779ca
diff --git a/CLAUDE.md b/CLAUDE.mdindex e6a83bbb4..d52bd263d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2390,26 +2390,45 @@ else, and its context links must keep classifying across restarts).`prompt_id`** in every capture. Wiring, and the rules it rests on:- `normalizeClaude` puts `prompt_id` on the `UserPromptSubmit` event as **`turnId`**; the mirrorkeeps it (`MirrorEntry.turnId`, runtime-only, dropped at a session boundary).- - The claude context tails (local, and the desktop's SSH one) scan COMPLETE lines with- `parseTurnInterrupts` — a CLOSED set of the two texts, array content with exactly that one text- part, non-sidechain (a typed prompt is a plain string, so typing the words matches nothing) —- and call `onTurnInterrupted(sessionId, turnId)`.- - **Both shells** hand that to `recordTurnInterrupt` (pinned in `hook-verified-parity.test.ts`),- which ends the turn ONLY when the marker names the node's CURRENT turn (same session, same- `turnId`, state working/blocked/waiting). That exact match is the whole safety story: a marker- the local tail reads back from history on its first read, one from a finished turn or another- session, one after a restart (no `turnId` then) changes nothing. The event is an ordinary- `done` + `interrupted` (what a `Stop` with `is_interrupt` already produced), UNverified (a- transcript read is not a hook POST), so no completion alert and the question/approval resets- apply unchanged.+ - The claude context tails (local, and the desktop's SSH one) scan COMPLETE lines with ONE+ stateful scanner per tracked transcript (`createTurnInterruptScanner`): a CLOSED set of the two+ texts, array content with exactly that one text part, non-sidechain (a typed prompt is a plain+ string, so typing the words matches nothing) — **and a marker counts for turn P only if P's+ OPENING prompt record was read BEFORE it** (bounded set of seen prompt ids, 256). The id alone+ is NOT enough, and this is not theoretical: in real transcripts on the dev host (2.1.209–2.1.283)+ 34 of 114 accepted-shape markers carried the promptId of the prompt written AFTER them — "queue a+ message while Claude works, then Esc": the CLI tags the marker with the QUEUED prompt's id and+ writes that prompt ~36 ms later, and its `UserPromptSubmit` has already made it the node's+ current turn, so an id-only match ended the NEW live turn (fixture+ `__fixtures__/claude/interrupt-queued.json`). Measured on this host after the fix: all 26+ queued-shape markers rejected, no real interrupt lost. The one interrupt this drops is the one+ it cannot place; the interrupted turn really ended and the node is already in the next one. The+ remote tail's historical first read records prompts but never reports.+ - **Both shells** check the marker with `turnInterruptEvent` (a mirror PEEK) and push the result+ through their ONE hook-event path — desktop `emitAgentStatus` (mirror, broadcast, Notch HUD,+ agent messaging, station notices), Server Edition `emit` (mirror, broadcast, `opts.onEvent`:+ its delivery queue and `--after` scheduler). Pinned in `hook-verified-parity.test.ts`. It ends+ the turn ONLY when the marker names the node's CURRENT turn (same session, same `turnId`, state+ working/blocked/waiting): a marker read back from history, one from a finished turn or another+ session, one after a restart (no `turnId` then) changes nothing. A prompt event whose+ `prompt_id` is missing or not a plain token carries `turnId: ''`, which makes the mirror FORGET+ the previous id. The event is an ordinary `done` + `interrupted` (what a `Stop` with+ `is_interrupt` already produced), UNverified (a transcript read is not a hook POST), so no+ completion alert and the question/approval resets apply unchanged.- **`--after` does NOT release on an interrupted turn** (decision, 2026-09-30): the personstopped it, usually to redirect it, and the dependent would start on unfinished work — #521'sreasoning for an errored turn. It is its OWN annotation, `agentStatus.lastTurnInterrupted`(transient; set by an interrupted `done`, cleared by a new turn or a `done` that is not- interrupted), read only by `depSatisfied`, the QUEUED tooltip (`interruptedDeps`) and `list`- (`LAST TURN INTERRUPTED`; an error outranks it). It is deliberately NOT `lastTurnError`: the- TURN FAILED chip, the station-failure notice, team progress and issue runs do not treat an- interrupt as a failure. ▶ / `run` still start the dependent. The renderer's older keystroke+ interrupted), read by `depSatisfied`, the QUEUED tooltip (`interruptedDeps`), `list`+ (`LAST TURN INTERRUPTED`; an error outranks it), the canvas's `armedDepSig` (a verdict can clear+ under a steady `done` — a guessed interrupt then the real Stop — and the launch effect must+ re-run) and team progress (its own `interrupted` kind, NOT counted as done, so the ring never+ says "finished" beside a held dependent). It is deliberately NOT `lastTurnError`: the TURN+ FAILED chip, the station-failure notice and issue runs do not treat an interrupt as a failure.+ **The `idle_prompt` rescue does NOT set it** (`recordsTurnInterrupt`): it is flagged+ `interrupted` only to stay silent, and since `idle_prompt` follows a NORMAL Stop, a rescue means+ a lost Stop POST on a turn that finished — its dependents release as before. ▶ / `run` still+ start the dependent. The renderer's older keystrokeguess (`inferInterruptAfterSettle`, 1.5 s after a lone Esc/Ctrl-C typed into THAT terminal)now records an interrupted `done` too, so a guess cannot release dependents before the markerlands; it stays because it is the only signal for the next case.@@ -2427,7 +2446,9 @@ else, and its context links must keep classifying across restarts).clears within ~1 s, no chime, an armed `--after` dependent stays QUEUED with the interruptedtooltip; (b) SSH node: the same over the remote tail; (c) Server Edition browser tab; (d) aClaude older than 2.1.285 — whether the marker text and `promptId` match there is unmeasured- (a mismatch degrades to the old behaviour, never to a false end); (e) the phone's Live+ (a changed text or a missing `promptId` matches nothing and degrades to the old behaviour); (e)+ queue a message while a turn runs, then Esc: the node must STAY working on the queued prompt;+ (f) the phone's LiveActivity ends on the interrupt.- **Hook server (loopback HTTP)** — `src/core/agents/hook-server.ts` is a main-processloopback HTTP server (per-session bearer token, fail-open) that the installed hook scriptsdiff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex c645ee399..53bc07057 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -175,7 +175,7 @@ export interface MirrorEntry {* interrupt marker end exactly THIS turn (`recordTurnInterrupt`) — no hook fires for an* Esc/Ctrl+C, so the marker is the only signal, and one read back from history names an older* turn and must change nothing. Runtime-only (not in `buildFile`'s allowlist): after a restart- * no marker can match, which degrades to the stale sweep, never to a false end. Cleared by a+ * no marker can match, which degrades to the stale sweep. Cleared by a* session boundary.*/turnId?: string@@ -618,7 +618,11 @@ function reduceEffectiveEntry(if (ev.account) next.account = ev.account// The live turn's id rides the event that opens it; nothing else touches it until the next turn// or a session boundary (below). See `recordTurnInterrupt`.- if (ev.kind === 'state' && ev.turnId) next.turnId = ev.turnId+ // A prompt with no usable id (`''`) forgets the old one rather than keeping it.+ if (ev.kind === 'state' && ev.turnId !== undefined) {+ if (ev.turnId) next.turnId = ev.turnId+ else delete next.turnId+ }if (ev.kind === 'state' && ev.state) {// An `idle` done (Claude went quiet at its prompt) is a RESCUE, not a turn end: it may only@@ -2181,7 +2185,8 @@ export function recordQuestionResult(}/**- * A Claude transcript recorded an interrupt marker (`parseTurnInterrupts`) for turn `turnId`.+ * A Claude transcript recorded an interrupt marker (`parseTurnInterrupts`) for turn `turnId`: the+ * event that ends the node's turn, or undefined when the marker is not about the CURRENT turn.** Claude Code sends NO hook when the user interrupts a turn — Esc while it streams, runs a tool or* shows a permission dialog, or Ctrl+C once (measured on 2.1.285,@@ -2191,22 +2196,35 @@ export function recordQuestionResult(* stale sweep: `--after` dependents waited, Eco never saw it idle, the phone showed it working.** It ends the turn only when the marker names the turn the node is in NOW (same session, same- * `turnId`, state still working/blocked/waiting). That exact match is the whole safety story: a- * marker the tail reads back from history, one from a turn that already ended, one from another- * session, or one arriving after a restart (turnId is runtime-only) changes nothing.+ * `turnId`, state still working/blocked/waiting): a marker the tail reads back from history, one+ * from a turn that already ended, one from another session, or one arriving after a restart+ * (turnId is runtime-only) changes nothing. The id match is only HALF the safety story: on "queue a+ * message, then Esc" the CLI tags the marker with the QUEUED prompt's id, which is the current turn+ * by then — the tail's scanner therefore drops a marker whose turn it has not seen OPENED before it+ * (`createTurnInterruptScanner`, context-tail.ts).** The event is an ordinary interrupted `done` — the shape a `Stop` with `is_interrupt` already* produced — so every consumer handles it with the rules it already has (no completion alert,* the question/approval resets). It carries no `verified`: a transcript read is not a hook POST.*/-export function recordTurnInterrupt(+export function turnInterruptEvent(nodeId: string, sessionId: string, turnId: string): NormalizedAgentEvent | undefined {const e = state.get(nodeId)if (!e || e.sessionId !== sessionId || !e.turnId || e.turnId !== turnId) returnif (e.state !== 'working' && e.state !== 'blocked' && e.state !== 'waiting') return- return recordAgentEvent({ nodeId, agentId: e.agentId ?? 'claude', sessionId, kind: 'state',- state: 'done', interrupted: true })+ return { nodeId, agentId: e.agentId ?? 'claude', sessionId, kind: 'state', state: 'done', interrupted: true }+}++/** `turnInterruptEvent`, recorded. The shells do NOT call this: they push `turnInterruptEvent`'s+ * event through their normal hook-event path, so every consumer of that stream (the Notch HUD,+ * agent messaging's receipt watch, station notices, the Server Edition's delivery queue and+ * `--after` scheduler) sees the interrupt exactly as it sees a hook. */+export function recordTurnInterrupt(+ nodeId: string, sessionId: string, turnId: string+): NormalizedAgentEvent | undefined {+ const ev = turnInterruptEvent(nodeId, sessionId, turnId)+ return ev ? recordAgentEvent(ev) : undefined}/** A node's current main state, or undefined when unknown. Read-only peek for the shells. */diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.tsindex d13f3dd93..0a5bcead8 100644--- a/src/core/agents/hook-verified-parity.test.ts+++ b/src/core/agents/hook-verified-parity.test.ts@@ -227,8 +227,13 @@ describe('both shells register a 4-arg raw listener', () => {expect(src, `${rel}: the claude context tail is not given onTurnInterrupted`).toMatch(/createContextTail\(pushContextUpdate, \{ onTaskNotification, onToolResult, onTurnInterrupted \}\)/)- expect(src, `${rel}: the handler bypasses the mirror`).toMatch(- /const ev = recordTurnInterrupt\(nodeId, sessionId, turnId\)/+ // The event must go through the shell's ONE hook-event path (mirror + every tap), not be+ // broadcast on the side.+ expect(src, `${rel}: the handler does not ask the mirror`).toMatch(+ /const ev = turnInterruptEvent\(nodeId, sessionId, turnId\)/+ )+ expect(src, `${rel}: the interrupt bypasses the shell's hook-event path`).toMatch(+ rel.includes('main') ? /if \(ev\) emitAgentStatus\(ev\)/ : /if \(ev\) emit\(ev\)/)}expect(code('src/main/index.ts'), 'the desktop remote (SSH) tail is not given onTurnInterrupted').toMatch(diff --git a/src/core/claude-turn-interrupt.test.ts b/src/core/claude-turn-interrupt.test.tsindex d3cd18eb6..d1a508657 100644--- a/src/core/claude-turn-interrupt.test.ts+++ b/src/core/claude-turn-interrupt.test.ts@@ -7,7 +7,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'import fs from 'fs'import path from 'path'import { normalizeClaude, type NormalizedAgentEvent } from '@shared/agents/normalize'-import { parseTurnInterrupts, CLAUDE_INTERRUPT_MARKERS, createContextTail } from './context-tail'+import { parseTurnInterrupts, CLAUDE_INTERRUPT_MARKERS, createContextTail, createTurnInterruptScanner } from './context-tail'import {recordAgentEvent,recordTurnInterrupt,@@ -25,6 +25,15 @@ const fixture = JSON.parse(.replace(/\r\n/g, '\n')) as { claudeVersion: string; scenarios: Record<string, Scenario>; idlePrompt: { fired: Payload[] } }+// A REAL "queue a message, then Esc" transcript excerpt (redacted): the marker carries the QUEUED+// prompt's id and the queued prompt record comes right AFTER it.+const queued = JSON.parse(+ fs+ .readFileSync(path.join(__dirname, '../shared/agents/__fixtures__/claude/interrupt-queued.json'), 'utf8')+ .replace(/\r\n/g, '\n')+) as { interruptedTurn: string; queuedTurn: string; records: Payload[] }+const queuedLines = queued.records.map((r) => JSON.stringify(r))+const MARKED = ['esc_streaming', 'esc_tool_call', 'esc_permission_prompt', 'ctrl_c_streaming', 'esc_tool_call_then_80s_idle']const REWOUND = ['ctrl_c_before_first_token', 'esc_before_first_token']const sc = (k: string): Scenario => {@@ -77,6 +86,40 @@ describe('parseTurnInterrupts', () => {expect(parseTurnInterrupts(lines(sc('esc_after_background_subagent')))).toEqual([])})+ it('the queued-prompt case: the marker names the NEXT prompt, whose record comes after it — dropped', () => {+ const marker = queued.records.find(+ (r) => Array.isArray((r.message as { content?: unknown })?.content) &&+ CLAUDE_INTERRUPT_MARKERS.has(String(((r.message as { content: { text?: string }[] }).content[0])?.text))+ )!+ // The fact the rule rests on: the id is the queued prompt's, not the interrupted turn's.+ expect(marker.promptId).toBe(queued.queuedTurn)+ expect(marker.promptId).not.toBe(queued.interruptedTurn)+ expect(queued.records.some((r) => r.type === 'queue-operation')).toBe(true)+ expect(parseTurnInterrupts(queuedLines)).toEqual([])+ // Also when the tail read the interrupted turn's prompt in an EARLIER chunk.+ const scanner = createTurnInterruptScanner()+ expect(scanner.scan(queuedLines.slice(0, 3))).toEqual([])+ expect(scanner.scan(queuedLines.slice(3))).toEqual([])+ })++ it('a turn opened in an earlier chunk still counts (the scanner carries what it has read)', () => {+ const l = lines(sc('esc_streaming'))+ const scanner = createTurnInterruptScanner()+ expect(scanner.scan(l.slice(0, 1))).toEqual([])+ expect(scanner.scan(l.slice(1))).toEqual([promptIdOf(sc('esc_streaming'))])+ // record-only reads (the remote tail's history) remember prompts but never report.+ const r = createTurnInterruptScanner()+ expect(r.scan(l, { record: true })).toEqual([])+ })++ it('remembers a bounded number of turns, oldest dropped first', () => {+ const scanner = createTurnInterruptScanner(2)+ const prompt = (id: string) => JSON.stringify({ type: 'user', promptId: id, message: { content: 'hi' } })+ const mark = (id: string) => JSON.stringify({ type: 'user', promptId: id, message: { content: [{ type: 'text', text: '[Request interrupted by user]' }] } })+ scanner.scan([prompt('a'), prompt('b'), prompt('c')])+ expect(scanner.scan([mark('a'), mark('b'), mark('c')])).toEqual(['b', 'c'])+ })+const rec = (over: Payload): string =>JSON.stringify({type: 'user',@@ -86,18 +129,21 @@ describe('parseTurnInterrupts', () => {})it('refuses shapes that are not the CLI’s marker', () => {- expect(parseTurnInterrupts([rec({})])).toEqual(['p-1'])+ const opened = JSON.stringify({ type: 'user', promptId: 'p-1', message: { content: 'typed prompt' } })+ // No opening prompt before it: not this turn's marker.+ expect(parseTurnInterrupts([rec({})])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({})])).toEqual(['p-1'])// A prompt the user typed is a plain string, even when it says the same words.- expect(parseTurnInterrupts([rec({ message: { role: 'user', content: '[Request interrupted by user]' } })])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({ message: { role: 'user', content: '[Request interrupted by user]' } })])).toEqual([])// Other wording: closed set, a future spelling degrades to nothing.- expect(parseTurnInterrupts([rec({ message: { content: [{ type: 'text', text: '[Request interrupted by user!]' }] } })])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({ message: { content: [{ type: 'text', text: '[Request interrupted by user!]' }] } })])).toEqual([])// Extra parts, a sidechain, an assistant record, a hostile id, no id, a torn line.- expect(parseTurnInterrupts([rec({ message: { content: [{ type: 'text', text: '[Request interrupted by user]' }, { type: 'text', text: 'x' }] } })])).toEqual([])- expect(parseTurnInterrupts([rec({ isSidechain: true })])).toEqual([])- expect(parseTurnInterrupts([rec({ type: 'assistant' })])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({ message: { content: [{ type: 'text', text: '[Request interrupted by user]' }, { type: 'text', text: 'x' }] } })])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({ isSidechain: true })])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({ type: 'assistant' })])).toEqual([])expect(parseTurnInterrupts([rec({ promptId: 'a b;rm' })])).toEqual([])expect(parseTurnInterrupts([rec({ promptId: undefined })])).toEqual([])- expect(parseTurnInterrupts([rec({}).slice(0, 60)])).toEqual([])+ expect(parseTurnInterrupts([opened, rec({}).slice(0, 60)])).toEqual([])})})@@ -107,8 +153,11 @@ describe('normalizeClaude carries the turn id', () => {const evs = s.hooks.map((payload) => normalizeClaude({ nodeId: 'n', agentId: 'claude', payload }))expect(evs[0]).toMatchObject({ state: 'working', newTurn: true, turnId: promptIdOf(s) })expect(evs[1]?.turnId).toBeUndefined()+ // A prompt with no usable id says so with '' — which makes the mirror FORGET the old turn id.const hostile = normalizeClaude({ nodeId: 'n', agentId: 'claude', payload: { ...s.hooks[0], prompt_id: 'x y' } })- expect(hostile?.turnId).toBeUndefined()+ expect(hostile?.turnId).toBe('')+ const { prompt_id: _drop, ...noId } = s.hooks[0]+ expect(normalizeClaude({ nodeId: 'n', agentId: 'claude', payload: noId })?.turnId).toBe('')})})@@ -159,6 +208,26 @@ describe('recordTurnInterrupt (the status mirror decides)', () => {expect(_snapshot()[NODE]?.state).toBe('working')})+ it('queue a message, then Esc: the NEW live turn is NOT ended (the review’s blocker)', () => {+ const SID = 'sess-q'+ recordAgentEvent({ nodeId: NODE, agentId: 'claude', sessionId: SID, kind: 'state', state: 'working', newTurn: true, turnId: queued.interruptedTurn })+ // The queued prompt's UserPromptSubmit: it is the node's current turn now.+ recordAgentEvent({ nodeId: NODE, agentId: 'claude', sessionId: SID, kind: 'state', state: 'working', newTurn: true, turnId: queued.queuedTurn })+ // The tail's 1 Hz read lands after that hook and sees marker + queued prompt together — also+ // on a first read that starts at the queued prompt.+ for (const id of createTurnInterruptScanner().scan(queuedLines)) recordTurnInterrupt(NODE, SID, id)+ for (const id of createTurnInterruptScanner().scan(queuedLines.slice(-2))) recordTurnInterrupt(NODE, SID, id)+ expect(_snapshot()[NODE]?.state).toBe('working')+ })++ it('a prompt with no usable id forgets the previous turn id', () => {+ const s = sc('esc_tool_call')+ replayHooks(s)+ recordAgentEvent(normalizeClaude({ nodeId: NODE, agentId: 'claude', payload: { ...s.hooks[0], prompt_id: undefined } })!)+ expect(_snapshot()[NODE]?.turnId).toBeUndefined()+ expect(recordTurnInterrupt(NODE, sessionOf(s), promptIdOf(s))).toBeUndefined()+ })+it('refuses another session, a finished turn, and an entry with no turn id (after a restart)', () => {const s = sc('esc_tool_call')replayHooks(s)diff --git a/src/core/context-tail.ts b/src/core/context-tail.tsindex 83d248947..c21675d50 100644--- a/src/core/context-tail.ts+++ b/src/core/context-tail.ts@@ -148,40 +148,105 @@ export const CLAUDE_INTERRUPT_MARKERS: ReadonlySet<string> = new Set([const PROMPT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/+/** How many opening-prompt ids a per-session scanner remembers (oldest dropped first). */+export const TURN_PROMPTS_SEEN_MAX = 256++type TranscriptRecord = {+ type?: unknown+ isSidechain?: unknown+ isMeta?: unknown+ promptId?: unknown+ message?: { content?: unknown }+}++const isMarkerRecord = (o: TranscriptRecord): boolean => {+ const content = o.message?.content+ if (!Array.isArray(content) || content.length !== 1) return false+ const part = content[0] as { type?: unknown; text?: unknown } | null+ return part?.type === 'text' && typeof part.text === 'string' && CLAUDE_INTERRUPT_MARKERS.has(part.text)+}++/** A main-thread user record that OPENS a turn: the typed (or dequeued) prompt itself — not a tool+ * result, not a meta record, not the interrupt marker. */+const isOpeningPrompt = (o: TranscriptRecord): boolean => {+ if (o.isMeta === true) return false+ const content = o.message?.content+ if (typeof content === 'string') return true+ if (!Array.isArray(content) || content.length === 0) return false+ if (content.some((c) => (c as { type?: unknown } | null)?.type === 'tool_result')) return false+ return !isMarkerRecord(o)+}+/**- * Turn ids (`promptId`) of the interrupt markers in these transcript lines, in file order. Pure.+ * The interrupt markers of ONE transcript, read chunk by chunk. Stateful: it remembers the turn ids+ * whose OPENING prompt record it has already read (bounded, `TURN_PROMPTS_SEEN_MAX`), because a+ * marker only counts for a turn whose prompt came BEFORE it in the file.+ *+ * That order is not a detail. On "queue a message while Claude works, then press Esc" the CLI+ * writes the marker tagged with the QUEUED prompt's id and the queued prompt record ~36 ms AFTER+ * it (measured in real transcripts, 2.1.209–2.1.283: 34 of 114 accepted-shape markers carried the+ * NEXT prompt's id, 31 of them behind a `queue-operation`; redacted in+ * `shared/agents/__fixtures__/claude/interrupt-queued.json`). That queued prompt's+ * UserPromptSubmit makes it the node's current turn, so an id match alone ended the NEW live turn.+ * A marker whose turn was not opened earlier in what this scanner has read is dropped — the+ * interrupted turn really did end, but the node is already in the next one.+ *+ * `record` lines are read for prompts only and never report (the remote tail's historical read).+ */+export interface TurnInterruptScanner {+ scan(text: string | string[], opts?: { record?: boolean }): string[]+}++export function createTurnInterruptScanner(max = TURN_PROMPTS_SEEN_MAX): TurnInterruptScanner {+ const seen = new Set<string>()+ const remember = (id: string): void => {+ seen.delete(id)+ seen.add(id)+ if (seen.size > max) seen.delete(seen.values().next().value as string)+ }+ return {+ scan(text, opts) {+ const out: string[] = []+ for (const line of toLines(text)) {+ // Cheap pre-filter before the parse — this runs over every transcript chunk. Every record+ // this scanner cares about is a user record carrying a promptId.+ if (!line.includes('"promptId"') || !line.includes('"user"')) continue+ let o: TranscriptRecord+ try {+ o = JSON.parse(line)+ } catch {+ continue+ }+ if (o?.type !== 'user' || o.isSidechain === true) continue+ if (typeof o.promptId !== 'string' || !PROMPT_ID_RE.test(o.promptId)) continue+ if (isMarkerRecord(o)) {+ if (!opts?.record && seen.has(o.promptId)) out.push(o.promptId)+ } else if (isOpeningPrompt(o)) {+ remember(o.promptId)+ }+ }+ return out+ }+ }+}++/**+ * Turn ids (`promptId`) of the interrupt markers in these transcript lines, in file order, counting+ * a marker only when its turn's opening prompt precedes it IN THESE LINES (see+ * `createTurnInterruptScanner`, which the tails use to carry that across reads). Pure.** No hook fires when the user interrupts a Claude turn (Esc during streaming, a tool call or a* permission dialog; Ctrl+C once) — measured on 2.1.285 — and the CLI's `idle_prompt`* notification does not follow an interrupted turn either. This marker is the one trace the* interrupt leaves. The id is only a CANDIDATE: the status mirror acts on it only when it names- * the turn the node is in right now (`recordTurnInterrupt`), which is what makes a marker read- * back from history on the tail's first read harmless.+ * the turn the node is in right now (`recordTurnInterrupt`).** Only a main-thread user record whose content is an ARRAY holding exactly one text part with a* marker text counts. A prompt the user typed is stored as a plain string, so typing the marker's* words cannot produce one.*/export function parseTurnInterrupts(text: string | string[]): string[] {- const out: string[] = []- for (const line of toLines(text)) {- // Cheap pre-filter before the parse — this runs over every transcript chunk.- if (!line.includes('Request interrupted by user')) continue- let o: { type?: unknown; isSidechain?: unknown; promptId?: unknown; message?: { content?: unknown } }- try {- o = JSON.parse(line)- } catch {- continue- }- if (o?.type !== 'user' || o.isSidechain === true) continue- if (typeof o.promptId !== 'string' || !PROMPT_ID_RE.test(o.promptId)) continue- const content = o.message?.content- if (!Array.isArray(content) || content.length !== 1) continue- const part = content[0] as { type?: unknown; text?: unknown } | null- if (part?.type !== 'text' || typeof part.text !== 'string' || !CLAUDE_INTERRUPT_MARKERS.has(part.text)) continue- out.push(o.promptId)- }- return out+ return createTurnInterruptScanner().scan(text)}/** Legacy presence scanner; answer consumers must use parseToolResultIds. */@@ -238,6 +303,8 @@ export interface ContextTailOptions {}interface Tracked {+ /** Claude interrupt markers, with the opening prompts already read (see the scanner). */+ interrupts: TurnInterruptScannerpath: stringoffset: numberused: number@@ -367,7 +434,7 @@ export function createContextTail(if (opts?.onToolResult)for (const id of parseToolResultIds(completeLines)) opts.onToolResult(sessionId, id)if (opts?.onTurnInterrupted)- for (const id of parseTurnInterrupts(completeLines)) opts.onTurnInterrupted(sessionId, id)+ for (const id of t.interrupts.scan(completeLines)) opts.onTurnInterrupted(sessionId, id)}}@@ -415,6 +482,7 @@ export function createContextTail(return}const t: Tracked = {+ interrupts: createTurnInterruptScanner(),path: transcriptPath,offset: 0,used: 0,diff --git a/src/main/index.ts b/src/main/index.tsindex 4e890dedc..133fd9177 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -181,7 +181,7 @@ import {flush as flushAgentStatusMirror,recordAgentEvent,recordQuestionResult,- recordTurnInterrupt,+ turnInterruptEvent,ignoreQuestionHook,ackDone,recordRawToolEvent,@@ -2487,8 +2487,10 @@ app.whenReady().then(async () => {let nodeId: string | undefinedfor (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nidif (!nodeId) return- const ev = recordTurnInterrupt(nodeId, sessionId, turnId)- if (ev) sendToMain(IPC.agentStatus, ev)+ // Through the SAME fan-out as a hook event (declared further down, called only once hooks+ // flow): the mirror records it, and the Notch HUD, agent messaging and station notices see it.+ const ev = turnInterruptEvent(nodeId, sessionId, turnId)+ if (ev) emitAgentStatus(ev)}const onTaskNotification = (sessionId: string, n: TaskNotification): void => {let nodeId: string | undefineddiff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.tsindex d1d477c84..0b2a52a3b 100644--- a/src/main/remote-context-tail.ts+++ b/src/main/remote-context-tail.ts@@ -12,7 +12,8 @@ import {parseLatestUsage,parseTaskNotifications,parseToolResultIds,- parseTurnInterrupts,+ createTurnInterruptScanner,+ type TurnInterruptScanner,type ContextTailOptions} from '../core/context-tail'import { splitCompleteLines } from '../core/subagent-tail'@@ -48,6 +49,8 @@ export function logsFailure(failures: number): boolean {}interface Tracked {+ /** Claude interrupt markers, with the opening prompts already read (see the scanner). */+ interrupts: TurnInterruptScannerref: RemoteFileRefoffset: number | nullfailures: number@@ -126,8 +129,11 @@ export function createRemoteContextTail(if (opts?.onTaskNotification) {for (const n of parseTaskNotifications(eventLines)) opts.onTaskNotification(sessionId, n)}- if (opts?.onTurnInterrupted)- for (const id of parseTurnInterrupts(eventLines)) opts.onTurnInterrupted(sessionId, id)+ // A historical read still RECORDS the opening prompts it passes (a marker only counts for a turn+ // whose prompt came before it — see createTurnInterruptScanner); it never reports one.+ if (historical) t.interrupts.scan(completeLines, { record: true })+ else if (opts?.onTurnInterrupted)+ for (const id of t.interrupts.scan(eventLines)) opts.onTurnInterrupted(sessionId, id)}const push = (sessionId: string, t: Tracked): void => {@@ -257,6 +263,7 @@ export function createRemoteContextTail(return}const t: Tracked = {+ interrupts: createTurnInterruptScanner(),ref,offset: null,failures: 0,diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 7083e3942..6512c3310 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -406,7 +406,7 @@ import {writeSeenExplorerPinHint} from '../lib/explorerPinHint'import { useProjects } from '../state/projects'-import { useAgentStatus } from '../state/agentStatus'+import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'import { chatPaneRefusal } from '../lib/chatPaneGate'import { useLaunchDelivery } from '../state/launchDelivery'@@ -2035,7 +2035,13 @@ export function Canvas() {const p = n.data.pendingLaunchif (!p) continuesig += `${n.id}:`- for (const d of p.after) sig += `${d}=${s.byId[d]?.state ?? ''},`+ // The last-turn verdicts ride the signature too: a verdict can clear while the state stays+ // `done` (a keystroke-guessed interrupt, then the turn's real Stop), and the launch effect+ // must re-run to release the dependent then.+ for (const d of p.after) {+ const st = s.byId[d]+ sig += `${d}=${st?.state ?? ''}${st?.lastTurnError ? 'e' : ''}${st?.lastTurnInterrupted ? 'i' : ''},`+ }sig += '|'}return sig@@ -14985,7 +14991,7 @@ export function Canvas() {e.verified,e.errored,e.held,- e.interrupted+ recordsTurnInterrupt(e))// Claude's Stop names the BACKGROUND tasks still running (async subagents, nested ones,// background shells). A background subagent that ends its turn while its own work runsdiff --git a/src/renderer/lib/teamProgress.ts b/src/renderer/lib/teamProgress.tsindex 7150a3456..249d56edf 100644--- a/src/renderer/lib/teamProgress.ts+++ b/src/renderer/lib/teamProgress.ts@@ -58,6 +58,7 @@ export type StationKind =| 'working'| 'needs'| 'errored'+ | 'interrupted'| 'dropped'| 'queued'| 'unknown'@@ -167,7 +168,7 @@ export function stationsByOpener(}type StatusLike = Pick<AgentNodeStatus, 'state'> &- Partial<Pick<AgentNodeStatus, 'dropped' | 'paused' | 'hibernated' | 'lastTurnError' | 'agentId' | 'sessionEnded'>>+ Partial<Pick<AgentNodeStatus, 'dropped' | 'paused' | 'hibernated' | 'lastTurnError' | 'lastTurnInterrupted' | 'agentId' | 'sessionEnded'>>function reports(agentId: string | undefined): boolean {if (!agentId) return false@@ -191,7 +192,9 @@ export function stationKind(station: TeamStation, status: StatusLike | undefinedif (state === 'waiting' || state === 'blocked') return 'needs'if (state === 'working') return 'working'if (station.queued) return 'queued'- if (state === 'done') return status?.lastTurnError ? 'errored' : 'done'+ // An interrupted last turn is not "done" either: `--after` holds its dependents on it+ // (`lastTurnInterrupted`), and a ring saying "finished" beside a held dependent would disagree.+ if (state === 'done') return status?.lastTurnError ? 'errored' : status?.lastTurnInterrupted ? 'interrupted' : 'done'if (status?.paused || status?.hibernated) return 'paused'if (status?.sessionEnded) return 'ended'return reports(station.agentId ?? status?.agentId) ? 'unknown' : 'untracked'@@ -204,6 +207,7 @@ const CHAR: Record<StationKind, string> = {working: 'w',needs: 'n',errored: 'e',+ interrupted: 'i',dropped: 'x',queued: 'q',unknown: '?',@@ -261,6 +265,7 @@ export const STATION_LABEL: Record<StationKind, string> = {working: 'working',needs: 'needs you',errored: 'last turn failed',+ interrupted: 'interrupted',dropped: 'dropped',queued: 'queued',unknown: 'unknown',@@ -269,7 +274,7 @@ export const STATION_LABEL: Record<StationKind, string> = {/** Order of the breakdown in the tooltip and the list header — attention first. */const BREAKDOWN: readonly StationKind[] = [- 'dropped', 'errored', 'needs', 'working', 'queued', 'unknown', 'done', 'paused', 'ended', 'untracked'+ 'dropped', 'errored', 'needs', 'interrupted', 'working', 'queued', 'unknown', 'done', 'paused', 'ended', 'untracked']/** "2 of 5 done — 1 working, 1 needs you, 1 unknown" (+ the untracked count, outside M). */diff --git a/src/renderer/lib/turnInterrupt.test.ts b/src/renderer/lib/turnInterrupt.test.tsindex 8e211d10b..ec694b69c 100644--- a/src/renderer/lib/turnInterrupt.test.ts+++ b/src/renderer/lib/turnInterrupt.test.ts@@ -115,3 +115,31 @@ describe('--after holds on an interrupted upstream', () => {expect(text).not.toMatch(/e \[terminal\].*INTERRUPTED/)})})++describe('review follow-ups', () => {+ it('the idle rescue does NOT record an interrupt (it means a lost Stop on a normal turn)', async () => {+ const { recordsTurnInterrupt } = await import('../state/agentStatus')+ expect(recordsTurnInterrupt({ interrupted: true })).toBe(true)+ expect(recordsTurnInterrupt({ interrupted: true, idle: true })).toBe(false)+ expect(recordsTurnInterrupt({})).toBe(false)+ })++ it('Canvas: the launch effect re-runs when a last-turn verdict clears under a steady `done`', async () => {+ const { readFileSync } = await import('fs')+ const { resolve } = await import('path')+ const src = readFileSync(resolve(__dirname, '../canvas/Canvas.tsx'), 'utf8')+ const sig = src.slice(src.indexOf('const armedDepSig = useAgentStatus'), src.indexOf('// ---- the setup gate'))+ expect(sig).toContain('lastTurnInterrupted')+ expect(sig).toContain('lastTurnError')+ })++ it('team progress does not count an interrupted station as done', async () => {+ const { stationKind, summarizeTeam } = await import('./teamProgress')+ const k = stationKind({ id: 's', title: 's', agentId: 'claude', queued: false } as never, {+ state: 'done',+ lastTurnInterrupted: { at: 1 }+ })+ expect(k).toBe('interrupted')+ expect(summarizeTeam([k]).done).toBe(0)+ })+})diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.tsindex ba691d261..134cf227a 100644--- a/src/renderer/state/agentStatus.test.ts+++ b/src/renderer/state/agentStatus.test.ts@@ -305,7 +305,7 @@ describe('the verified evidence for a transition', () => {// argument list: nothing else in the suite would notice if the last argument disappeared.const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')expect(src).toMatch(- /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored,\s*e\.held,\s*e\.interrupted\s*\)/+ /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored,\s*e\.held,\s*recordsTurnInterrupt\(e\)\s*\)/)})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex d030b1575..d049d5fcc 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -289,6 +289,17 @@ export function interruptVerdict(return prev}+/**+ * Does this event record `lastTurnInterrupted`? An interrupted `done` does — EXCEPT the `idle`+ * rescue (Claude's `idle_prompt`), which is flagged interrupted only so it raises no completion+ * alert. Measured on 2.1.285, `idle_prompt` follows a NORMAL Stop and not an interrupted turn, so a+ * rescue that moves a working node means the Stop POST was lost (a flapping SSH tunnel) on a turn+ * that finished normally — holding its `--after` dependents would be wrong.+ */+export function recordsTurnInterrupt(e: { interrupted?: boolean; idle?: boolean }): boolean {+ return e.interrupted === true && e.idle !== true+}+export interface AgentStatusStore {byId: Record<string, AgentNodeStatus>/** The terminal node the user is currently focused in (for unread decisions). */diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 1de5cfe60..a79c0583f 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -11254,6 +11254,11 @@ button.pull-checks__name {background: var(--state-queued);border-color: transparent;}+/* Interrupted by the user: idle, not finished — `--after` holds its dependents on it. */+.team-progress__dot--interrupted {+ background: var(--state-warning);+ border-color: transparent;+}/* The session name in the card modal header: sized to its text, not a flex-filling detail line. */.kanban-modal__session {flex: 0 1 auto;diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex b27240337..c3bdd7cd8 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -12,7 +12,7 @@ import { join, resolve } from 'path'import { homedir } from 'os'import { hookServer } from '../core/agents/hook-server'import { recordAgentEvent, recordRawToolEvent, recordContextUsage,- recordQuestionResult, recordTurnInterrupt, ignoreQuestionHook+ recordQuestionResult, turnInterruptEvent, ignoreQuestionHook} from '../core/agent-status-mirror'import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'import { ClaudeSubagentLifecycle } from '../core/claude-subagent-lifecycle'@@ -131,8 +131,10 @@ export function wireAgentStatus(let nodeId: string | undefinedfor (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nidif (!nodeId) return- const ev = recordTurnInterrupt(nodeId, sessionId, turnId)- if (ev) platform.broadcast(IPC.agentStatus, ev)+ // Through the SAME path as a hook event (`emit`, below), so the mirror records it and the+ // delivery queue / `--after` scheduler tap (`opts.onEvent`) sees it.+ const ev = turnInterruptEvent(nodeId, sessionId, turnId)+ if (ev) emit(ev)}// Every context tail pushes through here, so an agent's meter reaches the browser and the phone's@@ -169,7 +171,7 @@ export function wireAgentStatus(wholeFile: true})- hooks.setListener((e) => {+ const emit = (e: NormalizedAgentEvent): void => {// Claude subagent events first become one card per child (claudeSubagents above); every other// event comes back as itself. Then, per event: record FIRST — recordAgentEvent computes the// stash-priority classification and returns the event ENRICHED for a needs-you edge (a question@@ -180,7 +182,8 @@ export function wireAgentStatus(platform.broadcast(IPC.agentStatus, enriched)opts.onEvent?.(enriched)}- })+ }+ hooks.setListener(emit)// Security: hook POSTs can be forged, so a forged POST could set transcript_path to an// arbitrary local path (e.g. ~/.ssh/id_rsa) and have the app read it. The tails read thediff --git a/src/shared/agents/__fixtures__/claude/interrupt-queued.json b/src/shared/agents/__fixtures__/claude/interrupt-queued.jsonnew file mode 100644index 000000000..8ef35e753--- /dev/null+++ b/src/shared/agents/__fixtures__/claude/interrupt-queued.json@@ -0,0 +1,155 @@+{+ "_provenance": "A REAL transcript excerpt from this development host (Claude Code 2.1.282, 2026-09-25): the user queued a message while Claude worked, then pressed Esc. The interrupt marker carries the QUEUED prompt`s promptId, and the queued prompt record is written ~36 ms AFTER it. Text, tool input/output and paths removed; record types, order, promptIds, uuids and timestamps unchanged. The queued prompt`s UserPromptSubmit hook was not captured; the test reconstructs it from the 2.1.285 capture`s shape (interrupt-capture.json).",+ "interruptedTurn": "66372fea-a1c9-47d2-a02a-bd7dded7eeb4",+ "records": [+ {+ "type": "user",+ "isSidechain": false,+ "promptId": "66372fea-a1c9-47d2-a02a-bd7dded7eeb4",+ "timestamp": "2026-09-25T21:46:08.008Z",+ "uuid": "5cb4bbb4-8d37-488a-82d2-0245c8da2cab",+ "parentUuid": "d4b4c7d9-d836-4d3c-9e79-cbf56b6e1994",+ "message": {+ "role": "user",+ "content": "[prompt text removed]"+ },+ "version": "2.1.282"+ },+ {+ "type": "assistant",+ "isSidechain": false,+ "timestamp": "2026-09-25T21:46:10.945Z",+ "uuid": "f6f7c7af-9282-46ad-ad76-5834d26eb67d",+ "parentUuid": "363d7fb7-e6c7-49ee-a03b-6ef2b02fe3fd",+ "message": {+ "role": "assistant",+ "content": [+ {+ "type": "thinking"+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "assistant",+ "isSidechain": false,+ "timestamp": "2026-09-25T21:46:12.403Z",+ "uuid": "52f15ed1-e9df-4db3-b9bf-668ec54c7045",+ "parentUuid": "f6f7c7af-9282-46ad-ad76-5834d26eb67d",+ "message": {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01BnKLDpyoNQsR22TpFp2UTo",+ "name": "Bash",+ "input": {}+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "user",+ "isSidechain": false,+ "promptId": "66372fea-a1c9-47d2-a02a-bd7dded7eeb4",+ "timestamp": "2026-09-25T21:46:14.093Z",+ "uuid": "59aab56f-c5f1-4054-adbf-54c265230223",+ "parentUuid": "52f15ed1-e9df-4db3-b9bf-668ec54c7045",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01BnKLDpyoNQsR22TpFp2UTo",+ "content": "[output removed]"+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "assistant",+ "isSidechain": false,+ "timestamp": "2026-09-25T21:46:16.091Z",+ "uuid": "cc95c208-c98c-4fc9-951f-e5234daaa6e6",+ "parentUuid": "ec50578c-2321-42ec-82ce-b4e9a1498a43",+ "message": {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01VNW49kWz28t2uu9nj9Egjs",+ "name": "Bash",+ "input": {}+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "user",+ "isSidechain": false,+ "promptId": "66372fea-a1c9-47d2-a02a-bd7dded7eeb4",+ "timestamp": "2026-09-25T21:46:17.468Z",+ "uuid": "ab0bedb7-0e09-4f30-8601-7196d7c2a3e7",+ "parentUuid": "cc95c208-c98c-4fc9-951f-e5234daaa6e6",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01VNW49kWz28t2uu9nj9Egjs",+ "content": "[output removed]"+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "queue-operation",+ "operation": "enqueue",+ "timestamp": "2026-09-25T21:46:43.527Z",+ "content": "[queued prompt text removed]"+ },+ {+ "type": "queue-operation",+ "operation": "dequeue",+ "timestamp": "2026-09-25T21:46:46.388Z"+ },+ {+ "type": "user",+ "isSidechain": false,+ "promptId": "dbf7c1fb-cfef-4424-b1b1-9bb2c9907302",+ "interruptedMessageId": "msg_011CfQteD2ychoR1eMFRSQnp",+ "timestamp": "2026-09-25T21:46:46.377Z",+ "uuid": "30f802fe-7c28-48d2-9e41-09b33a68c5e4",+ "parentUuid": "0dd26d34-c141-4a4f-a030-1d560c56ad21",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "[Request interrupted by user]"+ }+ ]+ },+ "version": "2.1.282"+ },+ {+ "type": "user",+ "isSidechain": false,+ "promptId": "dbf7c1fb-cfef-4424-b1b1-9bb2c9907302",+ "timestamp": "2026-09-25T21:46:46.413Z",+ "uuid": "ae5b107c-927f-41b7-811c-bc5e93721358",+ "parentUuid": "30f802fe-7c28-48d2-9e41-09b33a68c5e4",+ "message": {+ "role": "user",+ "content": "[prompt text removed]"+ },+ "version": "2.1.282"+ }+ ],+ "queuedTurn": "dbf7c1fb-cfef-4424-b1b1-9bb2c9907302"+}diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 93ce6d3d4..3e2967d04 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -63,8 +63,8 @@ export interface NormalizedAgentEvent {* Esc / Ctrl+C — the one trace an interrupted turn leaves, because no hook fires for it* (measured on 2.1.285, `__fixtures__/claude/interrupt-capture.json`). The status mirror keeps* this id so a marker can be matched to exactly the turn it ends (`recordTurnInterrupt`), never- * to an older one read back from the transcript. Absent when the payload has none or it is not- * a plain token.+ * to an older one read back from the transcript. `''` when the prompt event has no usable id (none,+ * or not a plain token) — which CLEARS the mirror's id; absent on every other event.*/turnId?: stringsessionId?: string@@ -193,8 +193,10 @@ const RECURRING_TOOLS = new Set(['Skill', 'CronCreate', 'ScheduleWakeup'])/** A Claude turn id (`prompt_id`, a uuid today) as a plain bounded token, else nothing. */const TURN_ID_RE = /^[A-Za-z0-9_-]{1,128}$/-function turnIdOf(v: unknown): { turnId?: string } {- return typeof v === 'string' && TURN_ID_RE.test(v) ? { turnId: v } : {}+function turnIdOf(v: unknown): { turnId: string } {+ // '' = "a prompt opened a turn, but with no usable id": the mirror then FORGETS the previous+ // turn's id instead of keeping it, so no marker can be matched to a turn that has ended.+ return { turnId: typeof v === 'string' && TURN_ID_RE.test(v) ? v : '' }}interface ClaudePayload {