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): correlate pending Claude questions with their answers
enesae80009e62db
diff --git a/CLAUDE.md b/CLAUDE.mdindex f108819c7..6880a2969 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4685,3 +4685,10 @@ sessions is a hazard whatever kills it; this removes the hazard, not a proven cafollow-up note rather than same-PR work — but flag it so it isn't forgotten.When a change is genuinely desktop-only (native menus, auto-update, Keychain), say so; thepoint is to make the call consciously, not to leave the other surfaces to rot.++An unanswered Claude `AskUserQuestion` is correlated by session and tool-use ID in the core+mirror, independently of its short-lived display stash. Ordinary hooks, subagent activity and+unrelated transcript results must not clear attention or archive its inbox card. Both shells+use `recordQuestionResult` for transcript rescue (including Escape/decline), and broadcast the+mirror's effective event. Keep result IDs through local and SSH tails; a boolean “some tool+finished” is insufficient. Explicit new user turns, interrupts and session boundaries reset it.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0223794bd..069df50eb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -690,3 +690,10 @@ Two files, two audiences:**If you change or discover something other contributors must know, update this file too.** Aninvariant that only lives in a commit message is one refactor away from being violated by someonewho never saw it.++An unanswered Claude `AskUserQuestion` is correlated by session and tool-use ID in the core+mirror, independently of its short-lived display stash. Ordinary hooks, subagent activity and+unrelated transcript results must not clear attention or archive its inbox card. Both shells+use `recordQuestionResult` for transcript rescue (including Escape/decline), and broadcast the+mirror's effective event. Keep result IDs through local and SSH tails; a boolean “some tool+finished” is insufficient. Explicit new user turns, interrupts and session boundaries reset it.diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex c052e9c38..f95cc162b 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -38,6 +38,8 @@ export const EXPIRE_MS = 6 * 60 * 60_000export const WRITE_DEBOUNCE_MS = 300export interface MirrorEntry {+ /** Live question identity, independent of the short-lived display stash. */+ pendingQuestion?: { sessionId: string; toolUseId: string }/** working/waiting/blocked/done; undefined = idle/unknown (e.g. after a session reset). */state?: AgentStateagentId?: AgentId@@ -475,6 +477,20 @@ function reduceEffectiveEntry(// boot", and gate 2 will read it as the former.delete next.restored}+ // Unrelated tool hooks (including untagged child hooks) are not answers. Keep both+ // the state and its original evidence/identity until a correlated result or explicit reset.+ const ask = prev?.pendingQuestion+ if (ask) {+ const sameSession = ev.sessionId === ask.sessionId+ const reset = (ev.kind === 'session' && ev.sessionPhase === 'start') ||+ (sameSession && (ev.kind === 'session' || ev.newTurn || ev.interrupted))+ const answered = sameSession && ev.answeredQuestionId === ask.toolUseId+ if (!reset && !answered) return next+ delete next.pendingQuestion+ }+ if (ev.questionId && ev.sessionId) {+ next.pendingQuestion = { sessionId: ev.sessionId, toolUseId: ev.questionId }+ }// Identity is captured off ANY event (mirrors the renderer's per-event setSessionId +// agentId threading). agentId is always present on a NormalizedAgentEvent.if (ev.agentId) next.agentId = ev.agentId@@ -1407,6 +1423,13 @@ export function recordAgentEvent(rawEvent: NormalizedAgentEvent): NormalizedAgen// the broadcast to what the reducer decided, so every consumer (canvas store, notch, phone)// agrees the node is still waiting rather than each re-deriving it from the raw done.let out = ev+ if (next.pendingQuestion && prev?.pendingQuestion && next.state) {+ if (ev.kind !== 'state' && ev.kind !== 'session') return ev+ // Broadcast the same held state to Desktop, Server, canvas/board and the phone.+ return { ...ev, kind: 'state', state: next.state, sessionId: next.sessionId,+ verified: ev.verified, newTurn: undefined, interrupted: undefined,+ askKind: 'question', pendingId: undefined }+ }if (ev.kind === 'state' && ev.state === 'done' && next.awaitingInput && next.state === 'waiting') {out = { ...ev, state: 'waiting' }}@@ -1436,9 +1459,9 @@ function produceInboxFromState(if (ev.kind === 'session' || (ev.kind === 'state' && ev.state === 'working' && ev.newTurn)) {pendingQuestions.delete(nodeId)}- // Leaving blocked/waiting (any newer, different state — incl. a session reset to idle) resolves+ // Leaving needs-you (including a session reset to idle) resolves// that node's pending approval/question cards; they move to the phone's archive.- if ((prevState === 'blocked' || prevState === 'waiting') && nextState !== prevState) {+ if ((prevState === 'blocked' || prevState === 'waiting') && nextState !== 'blocked' && nextState !== 'waiting') {resolveUnresolvedFor(nodeId)pendingQuestions.delete(nodeId)}@@ -1620,6 +1643,14 @@ function clearActivity(nodeId: string, now: number): void {inboxNodes.set(nodeId, { contextPercent: n.contextPercent, updatedAt: now })}+/** Child hooks must not replace the parent transcript association while a picker is open. */+export function ignoreQuestionHook(nodeId: string, payload: Record<string, unknown>): boolean {+ if (payload.agent_id) return true+ const ask = state.get(nodeId)?.pendingQuestion+ return !!ask && payload.hook_event_name !== 'SessionStart' &&+ typeof payload.session_id === 'string' && payload.session_id !== ask.sessionId+}+/*** Fold a RAW hook tool event into the per-node "what it's doing now" line (spec:* mobile-usage-inbox). Called from the shells' `setRawListener` for claude events. PreToolUse sets@@ -1627,7 +1658,7 @@ function clearActivity(nodeId: string, now: number): void {* the line actually changes (raw POSTs are bursty).*/export function recordRawToolEvent(nodeId: string, payload: Record<string, unknown>): void {- if (!nodeId) return+ if (!nodeId || ignoreQuestionHook(nodeId, payload)) returnconst hook = typeof payload.hook_event_name === 'string' ? payload.hook_event_name : ''const now = Date.now()if (hook === 'PreToolUse') {@@ -1815,6 +1846,16 @@ export function nodeSessionName(nodeId: string): string | undefined {return state.get(nodeId)?.name}+/** Shared Desktop/Server transcript rescue. An unrelated result is never an answer. */+export function recordQuestionResult(+ nodeId: string, sessionId: string, toolUseId: string+): NormalizedAgentEvent | undefined {+ const ask = state.get(nodeId)?.pendingQuestion+ if (!ask || ask.sessionId !== sessionId || ask.toolUseId !== toolUseId) return+ return recordAgentEvent({ nodeId, agentId: 'claude', sessionId, kind: 'state',+ state: 'working', answeredQuestionId: toolUseId })+}+/** A node's current main state, or undefined when unknown. Read-only peek for the shells. */export function nodeState(nodeId: string): AgentState | undefined {return state.get(nodeId)?.statediff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.tsindex 2c298bfb7..d6d38afda 100644--- a/src/core/context-tail.test.ts+++ b/src/core/context-tail.test.ts@@ -256,3 +256,28 @@ describe('createContextTail — `wholeFile` (grok: a document rewritten, not appexpect(JSON.stringify(pushes)).not.toContain('222222')}, 8000)})++it('delivers each tool result ID across a torn local transcript read', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-question-tail-'))+ const file = path.join(dir, 'session.jsonl')+ const onToolResult = vi.fn()+ const tail = createContextTail(() => {}, { onToolResult })+ try {+ fs.writeFileSync(file, '')+ tail.track('session', file)+ await new Promise(resolve => setTimeout(resolve, 1200))+ const line = JSON.stringify({ type: 'user', message: { content: [+ { type: 'tool_result', tool_use_id: 'other', content: 'ok' },+ { type: 'tool_result', tool_use_id: 'ask', content: 'User declined to answer questions' }+ ] } })+ fs.appendFileSync(file, line.slice(0, 40))+ await new Promise(resolve => setTimeout(resolve, 1200))+ expect(onToolResult).not.toHaveBeenCalled()+ fs.appendFileSync(file, line.slice(40) + '\n')+ await new Promise(resolve => setTimeout(resolve, 1200))+ expect(onToolResult.mock.calls).toEqual([['session', 'other'], ['session', 'ask']])+ } finally {+ tail.untrack('session')+ fs.rmSync(dir, { recursive: true, force: true })+ }+}, 8000)diff --git a/src/core/context-tail.ts b/src/core/context-tail.tsindex 60990b42a..304d61570 100644--- a/src/core/context-tail.ts+++ b/src/core/context-tail.ts@@ -107,19 +107,25 @@ export function parseTaskNotifications(text: string | string[]): TaskNotificatioreturn out}-/**- * Did this chunk of transcript carry a TOOL RESULT? That is the moment a tool the CLI was blocked- * on has settled — which is the only signal we get when an ask ENDS without a hook.- *- * The case: an `AskUserQuestion` picker is up (node = needs-you) and the user presses Esc. Claude- * records "User declined to answer questions" as the tool's result and carries on, but the aborted- * tool fires no PostToolUse, and Stop does not run either — so nothing told us the ask was over and- * the node sat on NEEDS YOU (badge, notch capsule, phone card) until the next prompt hours later.- *- * Deliberately not decline-specific: any tool_result means the blocking tool finished, whatever the- * answer was. The caller only acts on it while the node is still in needs-you, so a normal turn's- * constant stream of results costs nothing.- */+/** IDs of settled tools, including Escape/decline results. Never infer an answer from+ * another tool's result or from result text. */+export function parseToolResultIds(text: string | string[]): string[] {+ const ids: string[] = []+ for (const line of toLines(text)) {+ if (!line.includes('tool_result')) continue+ try {+ const o = JSON.parse(line)+ if (!Array.isArray(o.message?.content)) continue+ for (const c of o.message.content) {+ if (c?.type === 'tool_result' && typeof c.tool_use_id === 'string' && c.tool_use_id)+ ids.push(c.tool_use_id)+ }+ } catch { /* torn or malformed transcript line */ }+ }+ return ids+}++/** Legacy presence scanner; answer consumers must use parseToolResultIds. */export function hasToolResult(text: string | string[]): boolean {for (const line of toLines(text)) {const s = line.trim()@@ -141,8 +147,8 @@ export function hasToolResult(text: string | string[]): boolean {export interface ContextTailOptions {/** Fired when a tracked session's transcript announces a completed async subagent. */onTaskNotification?: (sessionId: string, n: TaskNotification) => void- /** Fired when a tracked session's transcript records a tool RESULT — see `hasToolResult`. */- onToolResult?: (sessionId: string) => void+ /** Fired when a tracked session's transcript records a tool RESULT — see `parseToolResultIds`. */+ onToolResult?: (sessionId: string, toolUseId: string) => void/*** How to read the used/window numbers out of this agent's transcript. Defaults to claude's* `parseLatestUsage`. gemini and codex pass their own (`core/gemini-session.ts`@@ -287,7 +293,8 @@ export function createContextTail(for (const n of parseTaskNotifications(completeLines))opts.onTaskNotification(sessionId, n)}- if (opts?.onToolResult && hasToolResult(completeLines)) opts.onToolResult(sessionId)+ if (opts?.onToolResult)+ for (const id of parseToolResultIds(completeLines)) opts.onToolResult(sessionId, id)}}diff --git a/src/core/pending-question.test.ts b/src/core/pending-question.test.tsnew file mode 100644index 000000000..4904720f7--- /dev/null+++ b/src/core/pending-question.test.ts@@ -0,0 +1,75 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { normalizeClaude } from '../shared/agents/normalize'+import { parseToolResultIds } from './context-tail'+import { _resetForTest, _snapshot, _inboxSnapshot, recordAgentEvent, recordRawToolEvent,+ recordQuestionResult, ignoreQuestionHook, STASH_MAX_AGE_MS, sweepStaleWorking } from './agent-status-mirror'++function hook(hook_event_name: string, extra: Record<string, unknown> = {}) {+ const payload = { hook_event_name, session_id: 'parent', ...extra }+ recordRawToolEvent('node', payload)+ const event = normalizeClaude({ nodeId: 'node', agentId: 'claude', payload })+ return event ? recordAgentEvent({ ...event, verified: true }) : null+}+function ask(id = 'ask-1') {+ return hook('PreToolUse', { tool_name: 'AskUserQuestion', tool_use_id: id,+ tool_input: { questions: [{ question: 'Which?', options: [{ label: 'A' }, { label: 'B' }] }] } })+}+beforeEach(() => { _resetForTest(); vi.useFakeTimers(); vi.setSystemTime(100000) })+afterEach(() => { _resetForTest(); vi.useRealTimers() })++describe('Claude pending question correlation (#821)', () => {+ it('keeps attention and the inbox open through unrelated and child activity beyond stash freshness', () => {+ ask()+ vi.setSystemTime(Date.now() + STASH_MAX_AGE_MS + 1)+ for (const extra of [{ tool_name: 'Bash' }, { tool_name: 'Read', session_id: 'child' }]) {+ expect(hook('PreToolUse', extra)?.state).toBe('waiting')+ }+ expect(ignoreQuestionHook('node', { session_id: 'child' })).toBe(true)+ expect(ignoreQuestionHook('node', { session_id: 'parent' })).toBe(false)+ expect(hook('PreToolUse', { tool_name: 'Bash', agent_id: 'child' })).toBeNull()+ expect(hook('Stop')?.state).toBe('waiting')+ expect(hook('Notification', { notification_type: 'permission_prompt' })?.state).toBe('waiting')+ expect(hook('UserPromptSubmit', { prompt: '<task-notification>done</task-notification>' })?.state).toBe('waiting')+ sweepStaleWorking(Date.now() + 30 * 60000)+ expect(_snapshot().node).toMatchObject({ state: 'waiting', sessionId: 'parent' })+ expect(_inboxSnapshot().events).toHaveLength(1)+ expect(_inboxSnapshot().events[0].resolved).not.toBe(true)+ })++ it('matches session and tool ID for hooks, including a delayed answer to an older question', () => {+ ask()+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'other' })?.state).toBe('waiting')+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1', session_id: 'child' })?.state).toBe('waiting')+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1' })?.state).toBe('working')+ expect(_inboxSnapshot().events[0].resolved).toBe(true)+ ask('ask-2')+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1' })?.state).toBe('waiting')+ })++ it.each(['User declined to answer questions', 'A'])('rescues the matching transcript result: %s', content => {+ ask()+ const ids = parseToolResultIds(JSON.stringify({ type: 'user', message: { content: [+ { type: 'tool_result', tool_use_id: 'unrelated', content: 'ok' },+ { type: 'tool_result', tool_use_id: 'ask-1', content }+ ] } }))+ expect(ids).toEqual(['unrelated', 'ask-1'])+ expect(recordQuestionResult('node', 'parent', ids[0])).toBeUndefined()+ expect(recordQuestionResult('node', 'other-session', ids[1])).toBeUndefined()+ expect(recordQuestionResult('node', 'parent', ids[1])?.state).toBe('working')+ expect(recordQuestionResult('node', 'parent', ids[1])).toBeUndefined()+ expect(_inboxSnapshot().events[0].resolved).toBe(true)+ })++ it.each(['UserPromptSubmit', 'SessionEnd', 'SessionStart', 'Stop'])('allows explicit reset: %s', event => {+ ask()+ hook(event, { is_interrupt: true, ...(event === 'SessionStart' ? { session_id: 'new' } : {}) })+ expect(_snapshot().node.pendingQuestion).toBeUndefined()+ expect(_inboxSnapshot().events[0].resolved).toBe(true)+ })++ it('does not let a transcript result dismiss an approval without a tracked question', () => {+ hook('PermissionRequest', { tool_name: 'Bash' })+ expect(recordQuestionResult('node', 'parent', 'tool')).toBeUndefined()+ expect(_snapshot().node.state).toBe('blocked')+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex 6e451993a..2955d12bf 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -158,6 +158,8 @@ import {onMirrorFlush,flush as flushAgentStatusMirror,recordAgentEvent,+ recordQuestionResult,+ ignoreQuestionHook,ackDone,recordRawToolEvent,recordContextUsage,@@ -2324,24 +2326,15 @@ app.whenReady().then(async () => {* A tool RESULT landed in a tracked transcript. Only interesting while the node is still in* needs-you: an `AskUserQuestion` the user declined with Esc fires no PostToolUse and no Stop, so* nothing ever moved the node off NEEDS YOU — badge, notch capsule and phone card all stuck until- * the next prompt. The result proves the ask settled; `working` is the honest next state (Claude+ * the next prompt. A matching session + tool-use ID proves the ask settled; `working` is the honest next state (Claude* carries on with "User declined to answer questions"), and any real event corrects it anyway.*/- const onToolResult = (sessionId: string): void => {+ const onToolResult = (sessionId: string, toolUseId: string): void => {let nodeId: string | undefinedfor (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nidif (!nodeId) return- const st = nodeState(nodeId)- if (st !== 'blocked' && st !== 'waiting') return- const ev = {- nodeId,- agentId: 'claude',- sessionId,- kind: 'state',- state: 'working'- } satisfies NormalizedAgentEvent- sendToMain(IPC.agentStatus, ev)- recordAgentEvent(ev)+ const ev = recordQuestionResult(nodeId, sessionId, toolUseId)+ if (ev) sendToMain(IPC.agentStatus, ev)}const onTaskNotification = (sessionId: string, n: TaskNotification): void => {let nodeId: string | undefined@@ -3131,7 +3124,7 @@ app.whenReady().then(async () => {if (p.hook_event_name === 'SessionEnd' && p.session_id) tail.untrack(p.session_id)return}- if (agentId !== 'claude') return+ if (agentId !== 'claude' || ignoreQuestionHook(nodeId, payload)) return// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).// Runs BEFORE the local/remote split so it covers remote (SSH) nodes too — it needs only// tool_name/tool_input, never the transcript path the split routes on.diff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.tsindex 39a994a61..6fd05c2c1 100644--- a/src/main/remote-context-tail.test.ts+++ b/src/main/remote-context-tail.test.ts@@ -100,3 +100,28 @@ describe('createRemoteContextTail', () => {tail.untrack('sess3')})})++it('passes SSH transcript result IDs to the correlated answer consumer', async () => {+ const { win } = fakeWin()+ const onToolResult = vi.fn()+ const result = (id: string) => JSON.stringify({ type: 'user', message: { content: [+ { type: 'tool_result', tool_use_id: id, content: 'User declined to answer questions' }+ ] } })+ const remoteFile = {+ readTail: vi.fn(async () => line(50, 'claude-haiku') + '\n'),+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {+ const text = result('other') + '\n' + result('ask') + '\n'+ return { text, newOffset: o + Buffer.byteLength(text) }+ })+ }+ const tail = createRemoteContextTail(win, remoteFile as never, { onToolResult })+ try {+ tail.track('session', ref)+ await tick()+ await vi.waitFor(() => expect(onToolResult.mock.calls).toEqual([+ ['session', 'other'], ['session', 'ask']+ ]), { timeout: 2500 })+ } finally {+ tail.untrack('session')+ }+})diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.tsindex fb094f8c8..4ba364b4d 100644--- a/src/main/remote-context-tail.ts+++ b/src/main/remote-context-tail.ts@@ -11,7 +11,7 @@ import { cachedWindowFor, resolveModelWindow } from '../core/model-window'import {parseLatestUsage,parseTaskNotifications,- hasToolResult,+ parseToolResultIds,type ContextTailOptions} from '../core/context-tail'import { splitCompleteLines } from '../core/subagent-tail'@@ -71,7 +71,8 @@ export function createRemoteContextTail(t.used = latest.usedt.model = latest.model ?? t.model}- if (opts?.onToolResult && hasToolResult(completeLines)) opts.onToolResult(sessionId)+ if (opts?.onToolResult)+ for (const id of parseToolResultIds(completeLines)) opts.onToolResult(sessionId, id)if (opts?.onTaskNotification) {for (const n of parseTaskNotifications(completeLines)) opts.onTaskNotification(sessionId, n)}diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.tsindex 5e1deb853..278565c0c 100644--- a/src/server/agent-status.test.ts+++ b/src/server/agent-status.test.ts@@ -10,6 +10,7 @@ import {registerClaudeAccountsSource,resetClaudeAccountsSourceForTests} from '../core/claude-config-dir'+import { normalizeClaude } from '../shared/agents/normalize'import { IPC } from '../shared/ipc'import { decodePtyData } from '../shared/rpc'@@ -99,6 +100,23 @@ describe('wireAgentStatus', () => {expect(sent).toContainEqual({ t: 'ev', channel: IPC.agentStatus, args: [ev] })})+ it('broadcasts the held question instead of unrelated working or done hooks', () => {+ const fh = fakeHooks()+ wireAgentStatus(platform, { hooks: fh.hooks as never })+ const fire = (payload: Record<string, unknown>) => {+ fh.fireRaw('claude', 'n1', payload)+ const e = normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload })+ if (e) fh.fireNormalized(e)+ }+ fire({ hook_event_name: 'PreToolUse', session_id: 's', tool_name: 'AskUserQuestion', tool_use_id: 'q' })+ for (const hook_event_name of ['PreToolUse', 'Stop']) {+ fire({ hook_event_name, session_id: 's', tool_name: 'Bash' })+ expect(lastAgentStatus()).toMatchObject({ state: 'waiting', askKind: 'question' })+ }+ fire({ hook_event_name: 'PostToolUse', session_id: 's', tool_name: 'AskUserQuestion', tool_use_id: 'q' })+ expect(lastAgentStatus()).toMatchObject({ state: 'working' })+ })+it('broadcasts the ENRICHED event: an AskUserQuestion blocked edge loses its pendingId (askKind question)', () => {const fh = fakeHooks()wireAgentStatus(platform, { hooks: fh.hooks as never })diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex 7f99e2647..647aece10 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,- nodeState+ recordQuestionResult, ignoreQuestionHook} from '../core/agent-status-mirror'import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'@@ -106,21 +106,12 @@ export function wireAgentStatus(/** See the identical handler in src/main/index.ts: a tool RESULT settles an ask that ended with* no hook (Esc on an AskUserQuestion), which otherwise left the node stuck on needs-you. */- const onToolResult = (sessionId: string): void => {+ const onToolResult = (sessionId: string, toolUseId: string): void => {let nodeId: string | undefinedfor (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nidif (!nodeId) return- const st = nodeState(nodeId)- if (st !== 'blocked' && st !== 'waiting') return- const ev = {- nodeId,- agentId: 'claude',- sessionId,- kind: 'state',- state: 'working'- } satisfies NormalizedAgentEvent- platform.broadcast(IPC.agentStatus, ev)- recordAgentEvent(ev)+ const ev = recordQuestionResult(nodeId, sessionId, toolUseId)+ if (ev) platform.broadcast(IPC.agentStatus, ev)}// Every context tail pushes through here, so an agent's meter reaches the browser and the phone's@@ -353,7 +344,7 @@ export function wireAgentStatus(if (p.hook_event_name === 'SessionEnd' && p.session_id) tail.untrack(p.session_id)return}- if (agentId !== 'claude') return+ if (agentId !== 'claude' || ignoreQuestionHook(nodeId, payload)) return// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).// Independent of the transcript-tailing below (no path needed), so it runs first.recordRawToolEvent(nodeId, payload)diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 2d3374ee7..bd36cff79 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -48,6 +48,9 @@ export interface NormalizedAgentEvent {// the node to a green "done" over a blocked session. Cleared by the next genuine turn, any// other tool activity, an interrupt, or a session boundary (see reduceEntry).awaitingInput?: boolean+ /** Claude picker lifecycle, correlated with its transcript tool_result. */+ questionId?: string+ answeredQuestionId?: string// true only for a genuine new turn (Claude UserPromptSubmit), so the renderer can// clear per-turn fan-out without clearing on every mid-turn tool event.newTurn?: boolean@@ -138,6 +141,7 @@ const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])const RECURRING_TOOLS = new Set(['Skill', 'CronCreate', 'ScheduleWakeup'])interface ClaudePayload {+ agent_id?: stringhook_event_name?: stringsession_id?: string/** Deterministic-approval ticket the managed hook script added to its POST body and the hook@@ -185,6 +189,7 @@ export function isAsyncSubagentLaunch(r: { status?: string; isAsync?: boolean }export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | null {const p = env.payload as ClaudePayload+ if (p.agent_id) return nullconst base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.session_id }// Deterministic hook-reply "answered" signal (docs/hook-reply-approvals.md): the managed hook// fires this the instant it reads a valid allow/deny answer file — the agent is about to proceed@@ -205,6 +210,11 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nuconst tool = p.tool_name ?? ''if (ev === 'PreToolUse' || ev === 'PostToolUse') {+ if (tool === 'AskUserQuestion' && p.tool_use_id) {+ return ev === 'PreToolUse'+ ? { ...base, kind: 'state', state: 'waiting', questionId: p.tool_use_id }+ : { ...base, kind: 'state', state: 'working', answeredQuestionId: p.tool_use_id }+ }if (SUBAGENT_TOOLS.has(tool)) {if (ev === 'PreToolUse') {return {