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(inbox): instant state flip on answer + approval cards say WHAT needs approving
enes68900c26170a
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 06d305e03..bd1eaecd4 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -3,6 +3,7 @@ import fs from 'fs'import os from 'os'import path from 'path'import type { NormalizedAgentEvent } from '@shared/agents/normalize'+import { syntheticAnsweredEvent } from './agents/pending-approvals'import {reduceEntry,buildFile,@@ -18,6 +19,7 @@ import {setMirrorUsageProvider,buildMirrorUsage,toolActivity,+ buildApprovalSummary,firstLine,extractQuestionOptions,extractQuestionText,@@ -362,6 +364,49 @@ describe('inbox event production (via recordAgentEvent)', () => {expect(_inboxSnapshot().events[0].resolved).toBe(true)})+ it('synthetic "answered" working transition resolves the open approval and adds no new ask', () => {+ // The deterministic-approval answered signal (built exactly as the hook POST / desktop optimistic+ // flip does) is a working state → it goes through the same blocked→working path a normal resume+ // would, resolving the approval without pushing a fresh approval/question.+ const changes: NodeStateChange[] = []+ const unsub = onNodeStateChange((c) => changes.push(c))+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-1-1' }))+ expect(_inboxSnapshot().events).toHaveLength(1)+ expect(_inboxSnapshot().events[0].resolved).toBeUndefined()+ // Isolate the state-change edges produced by the answered signal alone.+ changes.length = 0+ const answered = syntheticAnsweredEvent('n1', 'n1-1-1', 'allow')!+ recordAgentEvent(answered)+ const ib = _inboxSnapshot()+ // Approval resolved, and no second inbox event appended (working never produces an ask).+ expect(ib.events).toHaveLength(1)+ expect(ib.events[0].resolved).toBe(true)+ expect(_snapshot().n1.state).toBe('working')+ // Consistent with a normal blocked→working resume: exactly one working 'start' edge (the same+ // a plain `working` event fires on that edge), and no spurious extra state-change kinds.+ expect(changes).toHaveLength(1)+ expect(changes[0]).toMatchObject({ event: 'start', state: 'working' })+ unsub()+ })++ it('a duplicate answered signal is a no-op (same-state working re-assert)', () => {+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-2-2' }))+ const answered = syntheticAnsweredEvent('n1', 'n1-2-2', 'allow')!+ recordAgentEvent(answered) // optimistic flip (desktop write)+ const changes: NodeStateChange[] = []+ const unsub = onNodeStateChange((c) => changes.push(c))+ recordAgentEvent(answered) // the held hook's second POST — an idempotent duplicate+ // No new inbox event, still one (resolved) approval, still working, and no new state edge fired.+ const ib = _inboxSnapshot()+ expect(ib.events).toHaveLength(1)+ expect(ib.events[0].resolved).toBe(true)+ expect(_snapshot().n1.state).toBe('working')+ expect(changes).toHaveLength(0)+ unsub()+ })+it('emits one done per turn with a detail snippet and passes interrupted through', () => {recordAgentEvent(ev({ state: 'working', newTurn: true }))recordAgentEvent(ev({ state: 'done', lastMessage: 'All wired up.\nplus extra' }))@@ -611,6 +656,120 @@ describe('question options (AskUserQuestion)', () => {})})+// ---- Approval summary (PermissionRequest → "what's being approved") -------------------------++describe('buildApprovalSummary (builder table)', () => {+ it('summarizes each tool family with a title + detail', () => {+ // Edit: title from basename, detail = path with rough +added/−removed line counts.+ expect(buildApprovalSummary('Edit', { file_path: 'src/components/App.tsx', old_string: 'a\nb', new_string: 'x\ny\nz' }))+ .toEqual({ title: 'Edit App.tsx', detail: 'src/components/App.tsx +3 −2' })+ // NotebookEdit shares the Edit shape (notebook_path / *_source fallbacks).+ expect(buildApprovalSummary('NotebookEdit', { notebook_path: '/n/nb.ipynb', old_source: '', new_source: 'one' }))+ .toEqual({ title: 'Edit nb.ipynb', detail: '/n/nb.ipynb +1 −0' })+ // Write: line count of content.+ expect(buildApprovalSummary('Write', { file_path: 'x/bar.py', content: 'l1\nl2\nl3' }))+ .toEqual({ title: 'Write bar.py', detail: 'x/bar.py (3 lines)' })+ // Read: detail is the path.+ expect(buildApprovalSummary('Read', { file_path: '/a/baz.md' })).toEqual({ title: 'Read baz.md', detail: '/a/baz.md' })+ // Bash: generic title, command as detail.+ expect(buildApprovalSummary('Bash', { command: 'npm test' })).toEqual({ title: 'Run command', detail: 'npm test' })+ // Bash multiline: first line + " …".+ expect(buildApprovalSummary('Bash', { command: 'cd x\nnpm test' })).toEqual({ title: 'Run command', detail: 'cd x …' })+ // WebFetch: host in title, url in detail.+ expect(buildApprovalSummary('WebFetch', { url: 'https://example.com/x?q=1' }))+ .toEqual({ title: 'Fetch example.com', detail: 'https://example.com/x?q=1' })+ // WebSearch: fixed title, query in detail.+ expect(buildApprovalSummary('WebSearch', { query: 'weather today' })).toEqual({ title: 'Search', detail: 'weather today' })+ // Task: subagent launch.+ expect(buildApprovalSummary('Task', { description: 'refactor auth' }))+ .toEqual({ title: 'Launch subagent', detail: 'refactor auth' })+ // mcp__ tool: short name in title, stringified input in detail.+ expect(buildApprovalSummary('mcp__claude_ai_Gmail__get_message', { id: 'm1' }))+ .toEqual({ title: 'Use get_message', detail: '{"id":"m1"}' })+ // Unknown tool: "Use <tool>" + stringified input.+ expect(buildApprovalSummary('SomethingNew', { a: 1 })).toEqual({ title: 'Use SomethingNew', detail: '{"a":1}' })+ })++ it('clips title ≤120 and detail ≤240', () => {+ const longName = 'x'.repeat(300)+ const s = buildApprovalSummary('Read', { file_path: longName })!+ expect(s.title.length).toBe(120)+ expect(s.title.endsWith('…')).toBe(true)+ expect(s.detail!.length).toBe(240)+ expect(s.detail!.endsWith('…')).toBe(true)+ })++ it('fails open (no stash) on an empty tool name or a degenerate detail', () => {+ expect(buildApprovalSummary('', { file_path: 'x' })).toBeUndefined()+ // Missing path → title kept, degenerate detail dropped (no path to show).+ expect(buildApprovalSummary('Read', {})).toEqual({ title: 'Read file' })+ expect(buildApprovalSummary('Edit', {})).toEqual({ title: 'Edit file' })+ // Unknown tool with empty input → no useful detail.+ expect(buildApprovalSummary('Weird', {})).toEqual({ title: 'Use Weird' })+ // Garbage tool_input types don't throw.+ expect(buildApprovalSummary('Bash', { command: 42 } as unknown as Record<string, unknown>))+ .toEqual({ title: 'Run command' })+ })+})++describe('approval summary stash (PermissionRequest → approval card)', () => {+ beforeEach(() => _resetForTest())+ afterEach(() => _resetForTest())++ // A PermissionRequest raw hook stashes the summary; the following blocked event picks it up.+ function permReq(nodeId: string, toolName: string, toolInput: Record<string, unknown>): void {+ recordRawToolEvent(nodeId, { hook_event_name: 'PermissionRequest', tool_name: toolName, tool_input: toolInput })+ }++ it('titles + details a blocked approval from the stashed summary (title + detail precedence)', () => {+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ permReq('n1', 'Edit', { file_path: 'src/components/App.tsx', old_string: 'a\nb', new_string: 'x\ny' })+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Claude wants to edit a file', pendingId: 'n1-1-1' }))+ const e = _inboxSnapshot().events.find((x) => x.nodeId === 'n1')!+ expect(e.kind).toBe('approval')+ expect(e.title).toBe('Edit App.tsx') // stashed title beats the lastMessage+ expect(e.detail).toBe('src/components/App.tsx +2 −2')+ expect(e.pendingId).toBe('n1-1-1') // a real approval keeps its held-hook ticket+ })++ it('falls back to lastMessage then generic when there is no stash (detail dropped when == title)', () => {+ recordAgentEvent(ev({ nodeId: 'a', state: 'blocked', lastMessage: 'Approve write to /etc/hosts' }))+ recordAgentEvent(ev({ nodeId: 'b', state: 'blocked' }))+ const evs = _inboxSnapshot().events+ const a = evs.find((x) => x.nodeId === 'a')!+ expect(a.title).toBe('Approve write to /etc/hosts')+ expect(a.detail).toBeUndefined() // detail equal to the title (both from lastMessage) is dropped+ expect(evs.find((x) => x.nodeId === 'b')!.title).toBe('Needs approval')+ })++ it('does not misclassify an approval stash as a question (options are the only question signal)', () => {+ permReq('n2', 'Bash', { command: 'rm -rf /tmp/x' })+ recordAgentEvent(ev({ nodeId: 'n2', state: 'blocked', lastMessage: 'Approve?', pendingId: 'p' }))+ const e = _inboxSnapshot().events.find((x) => x.nodeId === 'n2')!+ expect(e.kind).toBe('approval')+ expect(e.options).toBeUndefined()+ expect(e.title).toBe('Run command')+ expect(e.detail).toBe('rm -rf /tmp/x')+ })++ it('leaves the question stash untouched — an AskUserQuestion still classifies as a question', () => {+ recordRawToolEvent('n3', {+ hook_event_name: 'PreToolUse',+ tool_name: 'AskUserQuestion',+ tool_input: { questions: [{ question: 'Which theme?', options: [{ label: 'Dark' }, { label: 'Light' }] }] }+ })+ // Even if a PermissionRequest for the AskUserQuestion tool itself also fires, options win.+ permReq('n3', 'AskUserQuestion', { questions: [{ question: 'Which theme?', options: [{ label: 'Dark' }] }] })+ recordAgentEvent(ev({ nodeId: 'n3', state: 'blocked', lastMessage: 'Approve?', pendingId: 'n3-1-1' }))+ const e = _inboxSnapshot().events.find((x) => x.nodeId === 'n3')!+ expect(e.kind).toBe('question')+ expect(e.options).toEqual(['Dark', 'Light'])+ expect(e.title).toBe('Which theme?')+ expect('pendingId' in e).toBe(false)+ expect(e.detail).toBeUndefined()+ })+})+describe('onNodeStateChange seam', () => {beforeEach(() => _resetForTest())afterEach(() => _resetForTest())@@ -632,6 +791,26 @@ describe('onNodeStateChange seam', () => {expect(seen[3].message).toBe('Finished')})+ it('folds the stashed approval summary into the needsYou message (title — detail)', () => {+ const seen: NodeStateChange[] = []+ onNodeStateChange((c) => seen.push(c))+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ recordRawToolEvent('n1', {+ hook_event_name: 'PermissionRequest',+ tool_name: 'Edit',+ tool_input: { file_path: 'src/components/App.tsx', old_string: 'a\nb', new_string: 'x\ny' }+ })+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Claude wants to edit a file', pendingId: 'n1-1-1' }))+ const nu = seen.find((c) => c.state === 'needsYou')!+ // Consistent with the inbox card (title + detail) so Live Activities / push alerts read the same.+ expect(nu.message).toBe('Edit App.tsx — src/components/App.tsx +2 −2')+ expect(nu.kind).toBe('approval')+ expect(nu.pendingId).toBe('n1-1-1')+ const card = _inboxSnapshot().events.find((x) => x.nodeId === 'n1')!+ expect(card.title).toBe('Edit App.tsx')+ expect(card.detail).toBe('src/components/App.tsx +2 −2')+ })+it('maps waiting to needsYou and titles interrupted done "Stopped"', () => {const seen: NodeStateChange[] = []onNodeStateChange((c) => seen.push(c))diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex fa0acb8dc..d8cc8a4f9 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -517,17 +517,22 @@ function fireNodeNowChange(c: NodeNowChange): void {}}-// Per-node stash of the pending AskUserQuestion picker (option labels + the question text), set-// from the raw-hook seam and attached to the next needs-you InboxEvent for that node. Cleared on-// state-leave / new turn / session boundary, and additionally time-guarded (STASH_MAX_AGE_MS)-// so a stash that was never consumed (e.g. a picker that auto-resolved) can't be picked up by a-// genuinely unrelated later approval in the same turn.+// Per-node stash of the pending needs-you detail, set from the raw-hook seam and attached to the+// next needs-you InboxEvent for that node. Two producers feed it:+// - an AskUserQuestion PreToolUse stashes the option labels + question text (`options`/`question`);+// - a PermissionRequest stashes a derived "what's being approved" summary (`approval`).+// `options` (a real picker) is the QUESTION classification signal; `approval` supplies an approval+// card's title/detail. Cleared on state-leave / new turn / session boundary, and additionally+// time-guarded (STASH_MAX_AGE_MS) so a stash that was never consumed (e.g. a picker that+// auto-resolved) can't be picked up by a genuinely unrelated later needs-you in the same turn.interface QuestionStash {- /** ≤4 labels, each ≤60 chars. */- options: string[]+ /** AskUserQuestion picker: ≤4 labels, each ≤60 chars. Its PRESENCE marks a real question. */+ options?: string[]/** The first question's prompt text, clipped to INBOX_TITLE_MAX. Absent if not present/parseable. */question?: string- /** When the AskUserQuestion PreToolUse stashed this — freshness-guard anchor. */+ /** PermissionRequest: the derived "what's being approved" summary (title + optional detail). */+ approval?: { title: string; detail?: string }+ /** When the AskUserQuestion PreToolUse / PermissionRequest stashed this — freshness-guard anchor. */at: number}const pendingQuestions = new Map<string, QuestionStash>()@@ -591,6 +596,106 @@ export function extractQuestionText(}}+/** mcp tool short name: `mcp__<server>__<tool>` → `<tool>`. Degrades gracefully on odd shapes. */+function mcpShortName(name: string): string {+ const parts = name.split('__').filter(Boolean)+ return parts.length ? parts[parts.length - 1] : name+}++/** JSON.stringify a value, returning undefined for empty/unserializable objects. */+function safeStringify(v: unknown): string | undefined {+ try {+ const s = JSON.stringify(v)+ return s && s !== '{}' && s !== 'null' ? s : undefined+ } catch {+ return undefined+ }+}++/**+ * Derive a human "what is being approved" summary from a PermissionRequest's tool_name/tool_input+ * (field report: approval cards showed only "Needs approval"). Pure; FAIL-OPEN — an empty tool name,+ * a shape mismatch, or any throw yields `undefined`, so the caller keeps today's lastMessage/generic+ * title. `title` is clipped to INBOX_TITLE_MAX, `detail` to INBOX_DETAIL_MAX.+ */+export function buildApprovalSummary(+ toolName: string,+ toolInput: Record<string, unknown> | undefined+): { title: string; detail?: string } | undefined {+ if (!toolName) return undefined+ try {+ const ti = toolInput ?? {}+ const str = (v: unknown): string => (typeof v === 'string' ? v : '')+ // Rough line count: newlines + 1 when non-empty (the field-report spec says rough is fine).+ const lineCount = (s: string): number => (s ? s.split('\n').length : 0)+ let title: string+ let detail: string | undefined+ switch (toolName) {+ case 'Edit':+ case 'NotebookEdit': {+ const p = str(ti.file_path) || str(ti.notebook_path)+ const added = lineCount(str(ti.new_string) || str(ti.new_source))+ const removed = lineCount(str(ti.old_string) || str(ti.old_source))+ title = `Edit ${basename(p) || 'file'}`+ detail = p ? `${p} +${added} −${removed}` : undefined+ break+ }+ case 'Write': {+ const p = str(ti.file_path)+ const n = lineCount(str(ti.content))+ title = `Write ${basename(p) || 'file'}`+ detail = p ? `${p} (${n} lines)` : undefined+ break+ }+ case 'Bash': {+ const cmd = str(ti.command)+ const first = cmd.split('\n')[0] ?? ''+ title = 'Run command'+ detail = cmd.includes('\n') ? `${first} …` : first || undefined+ break+ }+ case 'Read': {+ const p = str(ti.file_path) || str(ti.notebook_path)+ title = `Read ${basename(p) || 'file'}`+ detail = p || undefined+ break+ }+ case 'WebFetch': {+ const url = str(ti.url)+ let host = url+ try {+ host = new URL(url).host+ } catch {+ // not a parseable URL — show the raw string+ }+ title = `Fetch ${host || '…'}`+ detail = url || undefined+ break+ }+ case 'WebSearch': {+ title = 'Search'+ detail = str(ti.query) || undefined+ break+ }+ case 'Task': {+ title = 'Launch subagent'+ detail = str(ti.description) || str(ti.prompt) || undefined+ break+ }+ default: {+ title = toolName.startsWith('mcp__') ? `Use ${mcpShortName(toolName)}` : `Use ${toolName}`+ detail = safeStringify(ti)+ }+ }+ const t = clip(title, INBOX_TITLE_MAX)+ if (!t) return undefined+ const d = detail ? clip(detail, INBOX_DETAIL_MAX) : undefined+ return d ? { title: t, detail: d } : { title: t }+ } catch {+ return undefined+ }+}+function pushInboxEvent(e: Omit<InboxEvent, 'id'>): void {const id = `${e.ts}-${++inboxSeq}`const full: InboxEvent = { id, ...e }@@ -739,14 +844,27 @@ function produceInboxFromState(// needs-you state the CLI signaled; without a stash we keep today's mapping (blocked→approval,// waiting→question).const stash = freshStash(nodeId, now)- const kind: 'approval' | 'question' = stash || nextState === 'waiting' ? 'question' : 'approval'+ // Only a real AskUserQuestion picker (options present) forces the QUESTION classification — an+ // approval-only stash (a PermissionRequest summary) must stay an approval.const options = stash?.options- // Title: the AskUserQuestion's own question text wins (so the phone shows the real question),- // else the last assistant line, else a kind-appropriate generic.+ const hasQuestion = !!options+ const kind: 'approval' | 'question' = hasQuestion || nextState === 'waiting' ? 'question' : 'approval'+ const approval = kind === 'approval' ? stash?.approval : undefined+ // Title precedence: the stashed summary (AskUserQuestion's own question text for a question, or+ // the PermissionRequest's "what's being approved" title for an approval) wins so the phone shows+ // the real ask; else the last assistant line, else a kind-appropriate generic.const title =- stash?.question ||+ (hasQuestion ? stash?.question : approval?.title) ||firstLine(ev.lastMessage, INBOX_TITLE_MAX) ||(kind === 'approval' ? 'Needs approval' : 'Waiting for input')+ // Detail (approval only — a question renders options, not a detail line). Precedence: the stashed+ // summary detail, else the lastMessage line (today's fallback). Dropped when it merely repeats the+ // title (the common no-stash case where both derive from lastMessage).+ const rawDetail =+ kind === 'approval'+ ? approval?.detail || firstLine(ev.lastMessage, INBOX_DETAIL_MAX) || undefined+ : undefined+ const detail = rawDetail && rawDetail !== title ? rawDetail : undefined// pendingId (the deterministic hook-reply ticket) rides ONLY an approval. A stash-question// suppresses it even when a PermissionRequest fired for the AskUserQuestion tool itself:// approve/deny on a question is wrong UX — the phone answers with digit send-keys that drive@@ -757,13 +875,16 @@ function produceInboxFromState(// keeps the activity live). Carries the classified kind + options (question) / pendingId// (approval) so the Live Activity renders straight from this same code path// (spec: interactive-push-live-activities addendum).+ // The live-update headline folds the approval detail in (so Live Activities / push alerts read+ // "Edit App.tsx — src/components/App.tsx +2 −2"); a question / detail-less approval is just the title.+ const headline = clip(detail ? `${title} — ${detail}` : title, LIVE_MESSAGE_MAX)if (prevState !== nextState) {fireNodeStateChange({...stateBase,event: 'update',state: 'needsYou',kind,- message: clip(title, LIVE_MESSAGE_MAX),+ message: headline,...(options ? { options } : {}),...(pendingId ? { pendingId } : {})})@@ -773,6 +894,7 @@ function produceInboxFromState(...baseEvent,kind,title,+ ...(detail ? { detail } : {}),...(options ? { options } : {}),...(pendingId ? { pendingId } : {})})@@ -832,6 +954,23 @@ export function recordRawToolEvent(nodeId: string, payload: Record<string, unknoinboxNodes.set(nodeId, { activity, tool: toolName, contextPercent: cur?.contextPercent, updatedAt: now })fireNodeNowChange({ nodeId, activity, contextPercent: cur?.contextPercent, ts: now })scheduleWrite()+ } else if (hook === 'PermissionRequest') {+ // Stash a "what's being approved" summary derived from the tool call so the next needs-you+ // approval event/push carries a real title + detail instead of a bare "Needs approval" (field+ // report). The raw seam fires BEFORE the normalized blocked event that produces the card, so the+ // stash is ready when produceInboxFromState reads it. Fail-open — a shape mismatch leaves no+ // stash (the card falls back to lastMessage/generic). Merges onto any fresh AskUserQuestion+ // stash so its option labels (the question signal) survive; a stale one is dropped by freshStash.+ const toolName = typeof payload.tool_name === 'string' ? payload.tool_name : ''+ if (!toolName) return+ const toolInput =+ payload.tool_input && typeof payload.tool_input === 'object'+ ? (payload.tool_input as Record<string, unknown>)+ : undefined+ const summary = buildApprovalSummary(toolName, toolInput)+ if (!summary) return+ const cur = freshStash(nodeId, now)+ pendingQuestions.set(nodeId, { ...(cur ?? {}), approval: summary, at: now })} else if (hook === 'Stop' || hook === 'SessionEnd') {const before = inboxNodes.get(nodeId)?.activityclearActivity(nodeId, now)diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex d70e91d3f..d3508c076 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -140,6 +140,11 @@ class HookServer {// into the payload object so both the raw listener and the normalizers see it as if it// rode inside the hook JSON. See docs/hook-reply-approvals.md.if (form.nodeterm_pending_id) payload.nodeterm_pending_id = form.nodeterm_pending_id+ // Same treatment for the "answered" signal the wait branch fires on a valid allow/deny+ // answer (a separate form field it can't fold into the agent's JSON in POSIX sh). Merged+ // so the normalizer sees it and maps it to a synthetic working transition. See+ // docs/hook-reply-approvals.md.+ if (form.nodeterm_answered) payload.nodeterm_answered = form.nodeterm_answered// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.this.rawListener?.(agentId, nodeId, payload)diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex 01669ea6d..0ca3bed85 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -32,9 +32,30 @@ describe('buildManagedScript', () => {expect(s).toContain("tr -c 'A-Za-z0-9_-' '_'")})it('tags the POST body with nodeterm_pending_id on both transports', () => {- // Two POST blocks (unix-socket + TCP) — both carry the tag.+ // Four POST blocks now carry the tag: the initial request POST (unix-socket + TCP) AND the+ // "answered" signal POST fired from the wait branch (unix-socket + TCP).const matches = s.match(/--data-urlencode "nodeterm_pending_id=\$\{nt_pending\}"/g) ?? []- expect(matches.length).toBe(2)+ expect(matches.length).toBe(4)+ })+ it('fires a backgrounded "answered" POST in the wait branch after reading a valid answer', () => {+ // Guarded on a valid allow/deny answer, tagged nodeterm_answered on both transports, and+ // backgrounded (& + short --max-time) so the decision JSON is never delayed.+ expect(s).toContain('if [ "$nt_decision" = "allow" ] || [ "$nt_decision" = "deny" ]; then')+ const answered = s.match(/--data-urlencode "nodeterm_answered=\$\{nt_decision\}"/g) ?? []+ expect(answered.length).toBe(2)+ const backgrounded = s.match(/--data-urlencode "payload=\$\{payload\}" >\/dev\/null 2>&1 &/g) ?? []+ expect(backgrounded.length).toBe(2)+ expect(s).toContain('--max-time 1')+ })+ it('does NOT fire the answered POST on timeout (only inside the answer-found branch)', () => {+ // The answered POST lives strictly between reading the answer file and the timeout cleanup:+ // it appears before the "Timed out" comment, and the timeout tail has no answered field.+ const answeredIdx = s.indexOf('nodeterm_answered')+ const timeoutIdx = s.indexOf('# Timed out')+ expect(answeredIdx).toBeGreaterThan(-1)+ expect(timeoutIdx).toBeGreaterThan(answeredIdx)+ const timeoutTail = s.slice(timeoutIdx)+ expect(timeoutTail).not.toContain('nodeterm_answered')})it('polls the answer file every 0.5s up to the armed seconds', () => {expect(s).toContain('nt_answer="$HOME/.nodeterm/pending/$nt_pending.answer"')diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 587e2ff38..4df59a3ac 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -9,7 +9,9 @@// ~/.nodeterm/pending/, tags the POST body with nodeterm_pending_id (so the mirror/inbox// learns it), then polls for ~/.nodeterm/pending/<pendingId>.answer for up to that many// seconds. An answer ('allow' | 'deny') is echoed back as the hook's decision JSON; a-// timeout prints nothing and Claude falls through to its normal interactive prompt. The+// timeout prints nothing and Claude falls through to its normal interactive prompt. On a valid+// answer it ALSO fires a second, backgrounded "answered" POST (nodeterm_answered=<decision>) so the+// NEEDS YOU badge flips to working immediately rather than lingering until the agent's next hook. The// whole branch is a NO-OP when the env var is absent (a user's own terminals, older// nodeterm, non-claude agents), so behavior is bit-for-bit legacy there.export function buildManagedScript(agentId: string): string {@@ -71,6 +73,34 @@ export function buildManagedScript(agentId: string): string {' if [ -f "$nt_answer" ]; then',' nt_decision=$(cat "$nt_answer" 2>/dev/null)',' rm -f "$nt_answer" "$nt_pending_file" 2>/dev/null || :',+ ' # Fire-and-forget "answered" signal so the canvas/phone NEEDS YOU badge flips to working the',+ ' # instant we read a valid answer, instead of sticking until the agent\'s next hook (which,',+ ' # for a text-only reply, is not until the turn\'s Stop). Backgrounded (&) + short --max-time so',+ ' # the decision JSON below is NEVER delayed. Same POST mechanism as above, tagged',+ ' # nodeterm_answered=<decision>; only for a valid allow/deny (no POST on a bad/timed-out answer).',+ ' if [ "$nt_decision" = "allow" ] || [ "$nt_decision" = "deny" ]; then',+ ' if [ -n "$NODETERM_HOOK_SOCK" ]; then',+ ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,+ ' --connect-timeout 0.5 --max-time 1 \\',+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ' --data-urlencode "nodeterm_answered=${nt_decision}" \\',+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 &',+ ' elif [ -n "$NODETERM_HOOK_PORT" ]; then',+ ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,+ ' --connect-timeout 0.5 --max-time 1 \\',+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ' --data-urlencode "nodeterm_answered=${nt_decision}" \\',+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 &',+ ' fi',+ ' fi',' if [ "$nt_decision" = "allow" ]; then',' printf \'%s\\n\' \'{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}\'',' elif [ "$nt_decision" = "deny" ]; then',diff --git a/src/core/agents/pending-approvals.test.ts b/src/core/agents/pending-approvals.test.tsindex fecabf6b4..c067f87af 100644--- a/src/core/agents/pending-approvals.test.ts+++ b/src/core/agents/pending-approvals.test.ts@@ -7,6 +7,7 @@ import {pendingDir,writePendingAnswerLocal,sweepPendingDir,+ syntheticAnsweredEvent,PENDING_MAX_AGE_MS} from './pending-approvals'@@ -65,6 +66,28 @@ describe('writePendingAnswerLocal', () => {})})+describe('syntheticAnsweredEvent (optimistic-flip builder)', () => {+ it('builds a claude working-state event threading the pendingId (allow)', () => {+ const e = syntheticAnsweredEvent('node-1', 'node-1-99-7', 'allow')+ expect(e).toMatchObject({+ nodeId: 'node-1',+ agentId: 'claude',+ kind: 'state',+ state: 'working',+ pendingId: 'node-1-99-7'+ })+ })++ it('builds a working event for deny too (the agent continues the turn)', () => {+ expect(syntheticAnsweredEvent('n', 'n-1-1', 'deny')).toMatchObject({ state: 'working', pendingId: 'n-1-1' })+ })++ it('returns null on an out-of-contract decision', () => {+ // @ts-expect-error — exercising the runtime guard+ expect(syntheticAnsweredEvent('n', 'n-1-1', 'always')).toBeNull()+ })+})+describe('sweepPendingDir', () => {it('removes files older than the max age, keeps fresh ones', async () => {const dir = pendingDir(home)diff --git a/src/core/agents/pending-approvals.ts b/src/core/agents/pending-approvals.tsindex 70b32bafa..36cc6e3bd 100644--- a/src/core/agents/pending-approvals.ts+++ b/src/core/agents/pending-approvals.ts@@ -11,6 +11,7 @@import fs from 'fs'import os from 'os'import path from 'path'+import { normalizeClaude, type NormalizedAgentEvent } from '../../shared/agents/normalize'/** pendingId shape the script generates (`<node>-<ms>-<pid>`) and the ONLY thing we interpolate* into a filename. Validated everywhere a pendingId becomes a path so a forged value can't@@ -58,6 +59,28 @@ export async function writePendingAnswerLocal(}}+/**+ * Build the synthetic "answered" agent event the managed hook's second POST would produce, so a+ * caller that just wrote the answer file (the desktop Approve/Deny handler) can OPTIMISTICALLY flip+ * the badge to working before that POST round-trips. Goes through the same `normalizeClaude` path the+ * hook server uses, so its shape is identical — the later hook POST is an idempotent duplicate+ * (a same-state working re-assert is a no-op in the mirror + renderer store). Threads the pendingId+ * so the open approval resolves. Claude-only (PermissionRequest is a Claude concept). Returns null on+ * an invalid decision. See docs/hook-reply-approvals.md.+ */+export function syntheticAnsweredEvent(+ nodeId: string,+ pendingId: string,+ decision: 'allow' | 'deny'+): NormalizedAgentEvent | null {+ if (decision !== 'allow' && decision !== 'deny') return null+ return normalizeClaude({+ nodeId,+ agentId: 'claude',+ payload: { nodeterm_answered: decision, nodeterm_pending_id: pendingId }+ })+}+/*** Remove `.json` / `.answer` files under the pending dir older than `maxAgeMs` (orphans from killed* or timed-out sessions). Returns the count removed. Best-effort — a missing dir or unreadablediff --git a/src/main/index.ts b/src/main/index.tsindex 769585a04..2cc89a363 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -19,7 +19,12 @@ import { generateCommitMessage, generateGroupName, generateTerminalName } from 'import { initUpdater } from './updater'import { fetchCheck } from '../core/check'import { hookServer } from '../core/agents/hook-server'-import { writePendingAnswerLocal, startPendingSweep, isValidPendingId } from '../core/agents/pending-approvals'+import {+ writePendingAnswerLocal,+ startPendingSweep,+ isValidPendingId,+ syntheticAnsweredEvent+} from '../core/agents/pending-approvals'import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'import {initAgentStatusMirror,@@ -1024,10 +1029,14 @@ app.whenReady().then(async () => {console.warn(`[agent-hooks] account ${acct.id} hook install failed`, e)}}- hookServer.setListener((e) => {+ // Fan a normalized agent event to BOTH consumers: the renderer's agentStatus store (canvas badge)+ // and the mobile-facing mirror. Named so the deterministic-approval answer handler below can reuse+ // it for the optimistic flip.+ const emitAgentStatus = (e: NormalizedAgentEvent): void => {sendToMain(IPC.agentStatus, e)recordAgentEvent(e)- })+ }+ hookServer.setListener(emitAgentStatus)// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the canvas Approve/Deny// buttons (and any relay client) answer a held Claude permission hook here. Route by the node's// project: an SSH project's hook runs on the REMOTE host (write over its ControlMaster), a local@@ -1040,10 +1049,19 @@ app.whenReady().then(async () => {if (!isValidPendingId(pendingId)) return falseif (decision !== 'allow' && decision !== 'deny') return falseconst sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)- if (sshProjectId && sshProjectManager) {- return sshProjectManager.writePendingAnswer(sshProjectId, pendingId, decision)+ const ok =+ sshProjectId && sshProjectManager+ ? await sshProjectManager.writePendingAnswer(sshProjectId, pendingId, decision)+ : await writePendingAnswerLocal(pendingId, decision, homedir())+ // Optimistic flip: on a successful write, emit the same synthetic "answered" transition the+ // held hook's second POST will produce, so the NEEDS YOU badge clears instantly instead of+ // waiting for that POST to round-trip. The later hook POST is an idempotent duplicate (a+ // same-state working re-assert is a no-op). See docs/hook-reply-approvals.md.+ if (ok) {+ const ev = syntheticAnsweredEvent(nodeId, pendingId, decision)+ if (ev) emitAgentStatus(ev)}- return writePendingAnswerLocal(pendingId, decision, homedir())+ return ok})// Sweep stale request/answer files (~/.nodeterm/pending) on boot + hourly — orphans from killeddiff --git a/src/server/index.ts b/src/server/index.tsindex 3814c2b33..e6d5e4887 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -16,11 +16,17 @@ import { registerCoreHandlers } from './handlers'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'import os from 'os'import { hookServer } from '../core/agents/hook-server'-import { writePendingAnswerLocal, startPendingSweep, isValidPendingId } from '../core/agents/pending-approvals'+import {+ writePendingAnswerLocal,+ startPendingSweep,+ isValidPendingId,+ syntheticAnsweredEvent+} from '../core/agents/pending-approvals'import { installManagedAgentHooks } from '../core/agents/hooks'import {initAgentStatusMirror,flush as flushAgentStatusMirror,+ recordAgentEvent,setMirrorSettingsProvider,type MirrorSettings} from '../core/agent-status-mirror'@@ -203,7 +209,18 @@ export async function startServer(if (decision !== 'allow' && decision !== 'deny') return false// An SSH-project node has no reachable ControlMaster here (v1): answer only local nodes.if (workspaceStore.sshProjectIdForNode(nodeId)) return false- return writePendingAnswerLocal(pendingId, decision, os.homedir())+ const ok = await writePendingAnswerLocal(pendingId, decision, os.homedir())+ // Optimistic flip (parity with desktop): emit the synthetic "answered" transition so the+ // browser canvas NEEDS YOU badge clears instantly, ahead of the held hook's second POST (an+ // idempotent duplicate). See docs/hook-reply-approvals.md.+ if (ok) {+ const ev = syntheticAnsweredEvent(nodeId, pendingId, decision)+ if (ev) {+ platform.broadcast(IPC.agentStatus, ev)+ recordAgentEvent(ev)+ }+ }+ return ok})// Sweep stale ~/.nodeterm/pending files on boot + hourly (orphans from killed sessions).diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex 3e4e0acc1..23050c47a 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -45,6 +45,36 @@ describe('normalizeClaude — PermissionRequest (deterministic approvals)', () =})})+describe('normalizeClaude — deterministic-approval "answered" signal', () => {+ // The signal rides ALONGSIDE the original PermissionRequest payload, so it must be matched BEFORE+ // hook_event_name (which would otherwise map to blocked) and yield a synthetic working transition.+ it('nodeterm_answered=allow → working, threading pendingId, over the PermissionRequest payload', () => {+ const e = normalizeClaude(+ env({+ hook_event_name: 'PermissionRequest',+ session_id: 's1',+ nodeterm_pending_id: 'n1-1720-42',+ nodeterm_answered: 'allow'+ })+ )+ expect(e).toMatchObject({ kind: 'state', state: 'working', pendingId: 'n1-1720-42', sessionId: 's1' })+ // A working state carries no blocked/waiting signal — it never produces a new inbox ask.+ expect(e?.state).not.toBe('blocked')+ })++ it('nodeterm_answered=deny also → working (the agent typically continues the turn)', () => {+ const e = normalizeClaude(+ env({ hook_event_name: 'PermissionRequest', nodeterm_pending_id: 'n1-9-9', nodeterm_answered: 'deny' })+ )+ expect(e).toMatchObject({ kind: 'state', state: 'working', pendingId: 'n1-9-9' })+ })++ it('an unrecognized nodeterm_answered value is ignored (falls through to the PermissionRequest map)', () => {+ const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest', nodeterm_answered: 'maybe' }))+ expect(e).toMatchObject({ kind: 'state', state: 'blocked' })+ })+})+describe('normalizeClaude — async subagents', () => {it('PostToolUse for a sync subagent → subagent-end with stats', () => {const e = normalizeClaude(diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 3f56a8422..d9fcb2b29 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -59,6 +59,11 @@ interface ClaudePayload {/** Deterministic-approval ticket the managed hook script added to its POST body and the hook* server merged into this payload (PermissionRequest only). */nodeterm_pending_id?: string+ /** Deterministic-approval "answered" signal: the managed hook fired a second POST the instant it+ * read a valid allow/deny answer file, tagged nodeterm_answered=<decision>, merged into this+ * payload by the hook server. It rides alongside the original PermissionRequest payload, so it is+ * matched BEFORE hook_event_name and maps to a synthetic working transition (not a new ask). */+ nodeterm_answered?: stringnotification_type?: stringis_interrupt?: booleanlast_assistant_message?: string@@ -95,6 +100,21 @@ export function isAsyncSubagentLaunch(r: { status?: string; isAsync?: boolean }export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | null {const p = env.payload as ClaudePayloadconst 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+ // (on 'deny' it typically continues the turn too), so map both to a synthetic 'working' transition+ // that clears the NEEDS YOU badge without waiting for the agent's next real hook. Threads the+ // pendingId so the mirror's state-leave resolves the open approval. It is NOT a new ask — a+ // 'working' state never produces an inbox approval/question. Matched BEFORE hook_event_name because+ // it rides alongside the original PermissionRequest payload.+ if (p.nodeterm_answered === 'allow' || p.nodeterm_answered === 'deny') {+ return {+ ...base,+ kind: 'state',+ state: 'working',+ ...(p.nodeterm_pending_id ? { pendingId: p.nodeterm_pending_id } : {})+ }+ }const ev = p.hook_event_nameconst tool = p.tool_name ?? ''