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
feat(chat): answer controls on the ⌘M Plan / Question cards
review695947ea33b3
diff --git a/CLAUDE.md b/CLAUDE.mdindex ea64d7f49..fde6c333f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2535,6 +2535,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilekept to one line with emphasis escaped), degrading to no body (the old chip) on any other shape;ChatPanel shows a part with a body as an expanded "Plan"/"Question" card through `MarkdownText` with its result under it, andthe find-bar index (`linesFrom`) indexes the body in full like assistant text.+ **Answer controls on those cards (2026-09).** Only the card the node's `held` ticket belongs to gets+ controls (`lib/chatAnswer.ts` `activeAnswerCard`: newest unanswered card of the held tool; a question+ also needs identical question texts — `held.questions` and the card's `questions` come from the ONE+ `readQuestions`), and only while the pane is in a dialog state. They send a `PermissionAnswer`+ through `answerPermission`; a refusal is a quiet retryable error pointing at the terminal. Plan's+ default button is `restore` — never auto. See docs/hook-reply-approvals.md.- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`normalized events (from Claude's `PreToolUse`/`PostToolUse` on tool `Agent`/`Task`, correlatedby `tool_use_id`) drive a transient `state/agentNodes.ts` store. Claude launches subagentsdiff --git a/docs/hook-reply-approvals.md b/docs/hook-reply-approvals.mdindex ed4b83822..3e8143fd2 100644--- a/docs/hook-reply-approvals.md+++ b/docs/hook-reply-approvals.md@@ -147,6 +147,22 @@ agent-status store keeps it while the node is `blocked` or `waiting` — separatthe mirror still strips from a question so approve/deny never lights on a picker. The phone mirror fileis unchanged (`held` is not persisted there).+**Answer controls in the ⌘M view (2026-09).** The Plan / Question card in `ChatPanel` carries+controls only when the node's `held` belongs to it (`renderer/lib/chatAnswer.ts` `activeAnswerCard`):+the newest unanswered card of the held tool, and — for a question — the SAME question texts in the+same order. That is why a held question also carries its texts (`held.questions`), read by the one+`readQuestions` (`shared/agents/permission-answer.ts`) that also fills the card's structured+`questions` (`core/transcript-reader.ts`), so the two sides cannot disagree about a text. Plan:+"Approve · previous mode" (`restore`, first and primary), "Approve · accept edits", "Approve · ask+before edits", "Revise…" (feedback → `plan-revise`). Question: radio (single) / checkbox (multiSelect),+an "Other" text field (the only input on a question with no options), Submit once every question is+answered; a multi-select "Other" joins the ticked labels and the text with `", "` as one free-text+answer. The ticket is re-checked against the store at send time; `false` (or a rejection) shows+"Couldn't send — answer in the terminal (⌘M)" and leaves the controls usable — never a stuck "Sent".+While controls are up, the composer placeholder and the status row point at the card+(`chatComposerPlaceholder({answerOnCard})`). The kanban card modal mounts the same `ChatPanel`, so the+controls appear there too.+**Surfaces.** Desktop: local + SSH (ControlMaster read + stdin write). Server Edition: local projects(SSH projects remain unsupported there, as before). Relay: unchanged. Mobile: keeps writing`allow`/`deny`; its plan approve now works through the script mapping once the host's script is current;diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 40c1c2bb1..342d3f79d 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -1129,7 +1129,8 @@ describe('recordAgentEvent enrichment (returned broadcast event)', () => {const out = recordAgentEvent(perm)expect(out.askKind).toBe('question')expect(out.pendingId).toBeUndefined() // no approve/deny on a picker — unchanged- expect(out.held).toEqual({ pendingId: 'e9-1-1', toolName: 'AskUserQuestion' })+ // The question texts ride along (answer controls match their card by them).+ expect(out.held).toEqual({ pendingId: 'e9-1-1', toolName: 'AskUserQuestion', questions: ['Which theme?'] })})it('a held question with NO PreToolUse stash is classified as an approval and keeps pendingId', () => {diff --git a/src/core/agents/permission-decision.ts b/src/core/agents/permission-decision.tsindex 249e3aa95..32013de31 100644--- a/src/core/agents/permission-decision.ts+++ b/src/core/agents/permission-decision.ts@@ -17,6 +17,7 @@import {ASK_USER_QUESTION_TOOL,+ ANSWER_TEXT_MAX_CHARS,EXIT_PLAN_MODE_TOOL,isSafeToolName,type PermissionAnswer@@ -57,8 +58,8 @@ export const PERM_WAIT_SECS_INTERACTIVE = 540/** Caps on user-typed text, in UTF-16 code units (`string.length`) — a person-sized limit, not a* wire limit; the whole decision's BYTE cap above is what bounds the file. */-export const PLAN_REVISE_MAX_CHARS = 8000-export const FREE_TEXT_MAX_CHARS = 8000+export const PLAN_REVISE_MAX_CHARS = ANSWER_TEXT_MAX_CHARS+export const FREE_TEXT_MAX_CHARS = ANSWER_TEXT_MAX_CHARSconst PLAN_REVISE_PREFIX = 'The user reviewed the plan and wants changes before you proceed: 'diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.tsindex 5a6371cd4..4166bb61c 100644--- a/src/core/transcript-reader.test.ts+++ b/src/core/transcript-reader.test.ts@@ -353,6 +353,30 @@ describe('tool bodies in the chat parse', () => {expect(olderPage.messages[0].parts[0]).toMatchObject({ kind: 'tool', id: 'p2', body: PLAN })})+ it('a question carries its structured questions beside the markdown body (the answer controls)', () => {+ const input = {+ questions: [+ { question: 'Pick one?', header: 'H', multiSelect: false, options: [{ label: 'A', description: 'a' }, { label: 'B' }] }+ ]+ }+ const line = jl({ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'q1', name: 'AskUserQuestion', input }] } })+ const legacy = parseChatMessages(line.split('\n'))[0].parts[0]+ const paged = parseChatWindow(Buffer.from(line), 0).messages[0].parts[0]+ for (const part of [legacy, paged]) {+ expect(part).toMatchObject({+ kind: 'tool',+ name: 'AskUserQuestion',+ questions: [+ { question: 'Pick one?', header: 'H', multiSelect: false, options: [{ label: 'A', description: 'a' }, { label: 'B' }] }+ ]+ })+ expect(part.kind === 'tool' && part.body).toContain('Pick one?')+ }+ // A plan carries no questions.+ const plan = parseChatMessages(planUse('p1').split('\n'))[0].parts[0]+ expect(plan.kind === 'tool' && 'questions' in plan).toBe(false)+ })+it('a tool with no body keeps today\'s shape exactly (no body key)', () => {const msgs = parseChatMessages(toolUse('t1', 'ls').split('\n'))expect(msgs[0].parts[0]).toEqual({ kind: 'tool', name: 'Bash', arg: 'ls' })diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex 8456e16c4..e453a27e4 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -9,6 +9,7 @@ import { transcriptRootFor } from './claude-accounts-core'import { linkedClaudeConfigDirFor } from './claude-config-dir'import { platform } from './platform'import { toolBody } from './chat-tool-body'+import { ASK_USER_QUESTION_TOOL, readQuestions } from '../shared/agents/permission-answer'// Transcript root for a managed account (its `projects` dir) or the system default// (`~/.claude/projects` when accountId is undefined — bit-for-bit the old behavior). Impure@@ -178,6 +179,10 @@ function parseChatRecords(}const body = toolBody(part.name, c.input)if (body) part.body = body+ if (part.name === ASK_USER_QUESTION_TOOL) {+ const questions = readQuestions(c.input)+ if (questions) part.questions = questions+ }if (paged && typeof c.id === 'string' && c.id) part.id = c.idparts.push(part)if (c.id) toolById.set(c.id, part)diff --git a/src/renderer/lib/chatAnswer.test.ts b/src/renderer/lib/chatAnswer.test.tsnew file mode 100644index 000000000..869539aad--- /dev/null+++ b/src/renderer/lib/chatAnswer.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from 'vitest'+import type { ChatMessage } from '@shared/types'+import type { ChatQuestion } from '@shared/agents/permission-answer'+import {+ PLAN_CHOICES,+ activeAnswerCard,+ emptySelection,+ planReviseAnswer,+ questionAnswerFrom,+ toggleLabel+} from './chatAnswer'++const SINGLE: ChatQuestion = { question: 'Pick one?', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }+const MULTI: ChatQuestion = {+ question: 'Which surfaces?',+ multiSelect: true,+ options: [{ label: 'Desktop' }, { label: 'Server' }, { label: 'Phone' }]+}+const FREE: ChatQuestion = { question: 'Name?', multiSelect: false, options: [] }++const plan = (key: number, result?: string): ChatMessage => ({+ role: 'assistant',+ key,+ parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: '# plan', ...(result ? { result } : {}) }]+})+const ask = (key: number, questions: ChatQuestion[] | undefined, result?: string): ChatMessage => ({+ role: 'assistant',+ key,+ parts: [+ { kind: 'text', text: 'before' },+ {+ kind: 'tool',+ name: 'AskUserQuestion',+ arg: '',+ body: 'q',+ ...(questions ? { questions } : {}),+ ...(result ? { result } : {})+ }+ ]+})++describe('PLAN_CHOICES', () => {+ it('offers the three approve modes, restore first, and never auto', () => {+ expect(PLAN_CHOICES.map((c) => c.mode)).toEqual(['restore', 'acceptEdits', 'manual'])+ // The default names what it does: restore the mode that preceded plan mode.+ expect(PLAN_CHOICES[0].label.toLowerCase()).toContain('previous mode')+ })+})++describe('activeAnswerCard — only the card the held ticket belongs to gets controls', () => {+ const heldPlan = { pendingId: 'n-1', toolName: 'ExitPlanMode' }+ it('the LAST unanswered plan card matches a held plan; older cards stay read-only', () => {+ const msgs = [plan(0, 'User approved'), plan(10), { role: 'user', parts: [{ kind: 'text', text: 'x' }] } as ChatMessage]+ expect(activeAnswerCard(msgs, heldPlan)).toEqual({ message: 1, part: 0 })+ expect(activeAnswerCard([plan(0), plan(10)], heldPlan)).toEqual({ message: 1, part: 0 })+ })+ it('no controls when the newest plan card already has its result, or nothing is held', () => {+ expect(activeAnswerCard([plan(0), plan(10, 'User approved')], heldPlan)).toBeNull()+ expect(activeAnswerCard([plan(0)], undefined)).toBeNull()+ expect(activeAnswerCard([plan(0)], { pendingId: 'n-1', toolName: 'Bash' })).toBeNull()+ })+ it('a question card matches only when its question texts equal the held ones, in order', () => {+ const held = { pendingId: 'n-2', toolName: 'AskUserQuestion', questions: ['Pick one?', 'Which surfaces?'] }+ expect(activeAnswerCard([ask(0, [SINGLE, MULTI])], held)).toEqual({ message: 0, part: 1 })+ expect(activeAnswerCard([ask(0, [MULTI, SINGLE])], held)).toBeNull()+ expect(activeAnswerCard([ask(0, [SINGLE])], held)).toBeNull()+ // The texts match an OLDER card but the newest question card is another one: read-only.+ expect(activeAnswerCard([ask(0, [SINGLE, MULTI]), ask(10, [FREE])], held)).toBeNull()+ })+ it('a held question without texts, or a card without structured questions, gets no controls', () => {+ expect(activeAnswerCard([ask(0, [SINGLE])], { pendingId: 'n-2', toolName: 'AskUserQuestion' })).toBeNull()+ expect(+ activeAnswerCard([ask(0, undefined)], { pendingId: 'n-2', toolName: 'AskUserQuestion', questions: ['Pick one?'] })+ ).toBeNull()+ })+})++describe('questionAnswerFrom — UI selection → the structured answer core validates', () => {+ it('single choice → the label string', () => {+ const sel = emptySelection([SINGLE])+ sel[0].labels = ['B']+ expect(questionAnswerFrom([SINGLE], sel)).toEqual({ kind: 'question', answers: { 'Pick one?': 'B' } })+ })+ it('multi choice → labels in OPTION order, whatever order they were ticked', () => {+ const sel = emptySelection([MULTI])+ sel[0].labels = toggleLabel(toggleLabel([], 'Phone', true), 'Desktop', true)+ expect(questionAnswerFrom([MULTI], sel)).toEqual({ kind: 'question', answers: { 'Which surfaces?': ['Desktop', 'Phone'] } })+ })+ it('"Other" on a single choice → free text listed in freeText', () => {+ const sel = emptySelection([SINGLE])+ sel[0].other = true+ sel[0].otherText = ' neither '+ expect(questionAnswerFrom([SINGLE], sel)).toEqual({+ kind: 'question',+ answers: { 'Pick one?': 'neither' },+ freeText: ['Pick one?']+ })+ })+ it('"Other" on a multi choice joins the ticked labels and the typed text the way the TUI does', () => {+ const sel = emptySelection([MULTI])+ sel[0].labels = ['Server']+ sel[0].other = true+ sel[0].otherText = 'Watch'+ expect(questionAnswerFrom([MULTI], sel)).toEqual({+ kind: 'question',+ answers: { 'Which surfaces?': 'Server, Watch' },+ freeText: ['Which surfaces?']+ })+ })+ it('a question with no options is answered by its text field alone', () => {+ const sel = emptySelection([FREE])+ sel[0].otherText = 'Ada'+ expect(questionAnswerFrom([FREE], sel)).toEqual({ kind: 'question', answers: { 'Name?': 'Ada' }, freeText: ['Name?'] })+ })+ it('several questions answer together; every one must be answered', () => {+ const sel = emptySelection([SINGLE, MULTI])+ sel[0].labels = ['A']+ expect(questionAnswerFrom([SINGLE, MULTI], sel)).toBeNull()+ sel[1].labels = ['Server']+ expect(questionAnswerFrom([SINGLE, MULTI], sel)).toEqual({+ kind: 'question',+ answers: { 'Pick one?': 'A', 'Which surfaces?': ['Server'] }+ })+ })+ it('incomplete selections produce nothing to send', () => {+ const sel = emptySelection([SINGLE])+ expect(questionAnswerFrom([SINGLE], sel)).toBeNull()+ sel[0].other = true+ sel[0].otherText = ' '+ expect(questionAnswerFrom([SINGLE], sel)).toBeNull()+ expect(questionAnswerFrom([FREE], emptySelection([FREE]))).toBeNull()+ })+ it('a label that is not one of the question\'s options is never sent', () => {+ const sel = emptySelection([SINGLE])+ sel[0].labels = ['Z']+ expect(questionAnswerFrom([SINGLE], sel)).toBeNull()+ })+})++describe('planReviseAnswer', () => {+ it('trims, and refuses a blank message', () => {+ expect(planReviseAnswer(' add tests ')).toEqual({ kind: 'plan-revise', message: 'add tests' })+ expect(planReviseAnswer(' ')).toBeNull()+ })+})+diff --git a/src/renderer/lib/chatAnswer.ts b/src/renderer/lib/chatAnswer.tsnew file mode 100644index 000000000..0f57f29b6--- /dev/null+++ b/src/renderer/lib/chatAnswer.ts@@ -0,0 +1,121 @@+import type { ChatMessage } from '@shared/types'+import {+ ANSWER_TEXT_MAX_CHARS,+ ASK_USER_QUESTION_TOOL,+ EXIT_PLAN_MODE_TOOL,+ type ChatQuestion,+ type HeldPermission,+ type PermissionAnswer+} from '@shared/agents/permission-answer'++/**+ * Pure decisions behind the ⌘M panel's answer controls on a Plan / Question card+ * (`nodes/ChatAnswerControls.tsx`): which card the held request belongs to, and what a selection+ * turns into. The renderer only ever builds a `PermissionAnswer`; core validates every field against+ * the pending request file and builds the hook's JSON (`core/agents/permission-decision.ts`).+ */++/** The three ways to approve a plan, in button order. There is deliberately no `auto`+ * (see `PermissionAnswer`), and the default names what it actually does. */+export const PLAN_CHOICES: ReadonlyArray<{ mode: 'restore' | 'acceptEdits' | 'manual'; label: string; hint: string }> = [+ { mode: 'restore', label: 'Approve · previous mode', hint: 'Continue in the mode you were in before plan mode' },+ { mode: 'acceptEdits', label: 'Approve · accept edits', hint: 'Continue with file edits auto-approved' },+ { mode: 'manual', label: 'Approve · ask before edits', hint: 'Continue, asking before each edit' }+]++/** Typed text limit for "Revise…" and "Other" — the shared limit core enforces. */+export const CHAT_ANSWER_TEXT_MAX = ANSWER_TEXT_MAX_CHARS++/** Where a card lives in the rendered thread. */+export interface AnswerCardRef {+ message: number+ part: number+}++/**+ * The ONE card the node's held request belongs to, or null (every card stays read-only).+ *+ * The candidate is the NEWEST tool part named like the held tool — an older plan or question is+ * history — and it must still be unanswered (no result). A question card must also carry the SAME+ * question texts, in order, as the held request (both come from `readQuestions`): a held ticket+ * whose texts are unknown, or a card whose questions could not be read, gets no controls.+ */+export function activeAnswerCard(messages: readonly ChatMessage[], held: HeldPermission | undefined): AnswerCardRef | null {+ if (!held || (held.toolName !== EXIT_PLAN_MODE_TOOL && held.toolName !== ASK_USER_QUESTION_TOOL)) return null+ for (let i = messages.length - 1; i >= 0; i--) {+ const parts = messages[i].parts+ for (let j = parts.length - 1; j >= 0; j--) {+ const p = parts[j]+ if (p.kind !== 'tool' || p.name !== held.toolName) continue+ if (p.result !== undefined || !p.body) return null+ if (held.toolName === EXIT_PLAN_MODE_TOOL) return { message: i, part: j }+ const texts = held.questions+ const qs = p.questions+ if (!texts || !qs || texts.length !== qs.length || !qs.every((q, k) => q.question === texts[k])) return null+ return { message: i, part: j }+ }+ }+ return null+}++/** What the user has picked for one question. `labels` are option labels; `other` + `otherText`+ * is the free-text "Other" (the only input on a question with no options). */+export interface QuestionSelection {+ labels: string[]+ other: boolean+ otherText: string+}++export const emptySelection = (questions: readonly ChatQuestion[]): QuestionSelection[] =>+ questions.map(() => ({ labels: [], other: false, otherText: '' }))++/** Add or remove one label (a checkbox). */+export function toggleLabel(labels: readonly string[], label: string, on: boolean): string[] {+ const rest = labels.filter((l) => l !== label)+ return on ? [...rest, label] : rest+}++/**+ * The structured answer for a set of selections, or null while any question is unanswered or a+ * pick is not one of that question's own options (never sent — core would refuse it anyway).+ *+ * - single choice → the label; multi choice → its labels in OPTION order;+ * - "Other" (or a question with no options) → the typed text, listed in `freeText`. On a multi+ * choice the ticked labels come first, joined with ", " — the TUI's own multi-select format —+ * because core carries one free-text string per question, not labels plus text.+ */+export function questionAnswerFrom(+ questions: readonly ChatQuestion[],+ selections: readonly QuestionSelection[]+): Extract<PermissionAnswer, { kind: 'question' }> | null {+ if (questions.length === 0 || selections.length !== questions.length) return null+ const answers: Record<string, string | string[]> = {}+ const freeText: string[] = []+ for (let i = 0; i < questions.length; i++) {+ const q = questions[i]+ const sel = selections[i]+ const known = q.options.map((o) => o.label)+ if (!sel.labels.every((l) => known.includes(l))) return null+ const labels = known.filter((l) => sel.labels.includes(l))+ const typed = sel.otherText.trim()+ const wantsText = sel.other || q.options.length === 0+ if (wantsText) {+ if (!typed || typed.length > CHAT_ANSWER_TEXT_MAX) return null+ answers[q.question] = q.multiSelect && labels.length ? [...labels, typed].join(', ') : typed+ freeText.push(q.question)+ } else if (q.multiSelect) {+ if (labels.length === 0) return null+ answers[q.question] = labels+ } else {+ if (labels.length !== 1) return null+ answers[q.question] = labels[0]+ }+ }+ return freeText.length ? { kind: 'question', answers, freeText } : { kind: 'question', answers }+}++/** "Revise…": the feedback message, or null while it is blank. */+export function planReviseAnswer(text: string): Extract<PermissionAnswer, { kind: 'plan-revise' }> | null {+ const message = text.trim()+ return message && message.length <= CHAT_ANSWER_TEXT_MAX ? { kind: 'plan-revise', message } : null+}diff --git a/src/renderer/lib/chatSendGate.test.ts b/src/renderer/lib/chatSendGate.test.tsindex 501278558..1a0c61cd7 100644--- a/src/renderer/lib/chatSendGate.test.ts+++ b/src/renderer/lib/chatSendGate.test.ts@@ -71,6 +71,17 @@ describe('chatComposerPlaceholder', () => {expect(chatComposerPlaceholder({ ...base, refusal: 'working' })).toBe('Grok is working…')})+ it('points a dialog at the answer card when that card has controls — the chord is the fallback', () => {+ expect(chatComposerPlaceholder({ ...base, refusal: 'dialog', answerOnCard: true })).toBe(+ 'Grok is waiting for your answer — answer on the card above, or press ⌘M to answer in the terminal'+ )+ expect(chatComposerPlaceholder({ ...base, chip: '', refusal: 'dialog', answerOnCard: true })).toBe(+ 'Grok is waiting for your answer — answer on the card above'+ )+ // Only the dialog copy changes.+ expect(chatComposerPlaceholder({ ...base, refusal: 'working', answerOnCard: true })).toBe('Grok is working…')+ })+it('points a dialog back at the terminal through the bound chord', () => {expect(chatComposerPlaceholder({ ...base, refusal: 'dialog' })).toBe('Grok is waiting for an answer in the terminal — press ⌘M to answer there'diff --git a/src/renderer/lib/chatSendGate.ts b/src/renderer/lib/chatSendGate.tsindex dbf49d5eb..7dac3ef09 100644--- a/src/renderer/lib/chatSendGate.ts+++ b/src/renderer/lib/chatSendGate.ts@@ -66,23 +66,34 @@ export function canSendFromChat(agentId: string, s: ChatGateStatus): boolean {* in the header of the canvas node and of the kanban card modal alike (hence "the header"). An* exited CLI has no such chip: it is relaunched in the terminal itself. A write failure* (`readonly`) outranks everything: no state change will make that session writable.+ *+ * `answerOnCard`: the dialog is a held plan / question whose card in the thread carries answer+ * controls (`lib/chatAnswer.ts`), so the copy points at the card first and keeps the terminal as+ * the fallback — the card is the shorter path, the terminal still works.*/export function chatComposerPlaceholder({readonly,refusal,agentLabel,- chip+ chip,+ answerOnCard = false}: {readonly: booleanrefusal: ChatSendRefusalagentLabel: stringchip: string+ answerOnCard?: boolean}): string {if (readonly) return "Can't write to this session"switch (refusal) {case 'working':return `${agentLabel} is working…`case 'dialog':+ if (answerOnCard) {+ return chip+ ? `${agentLabel} is waiting for your answer — answer on the card above, or press ${chip} to answer in the terminal`+ : `${agentLabel} is waiting for your answer — answer on the card above`+ }return chip? `${agentLabel} is waiting for an answer in the terminal — press ${chip} to answer there`: `${agentLabel} is waiting for an answer in the terminal — switch back to the terminal to answer`diff --git a/src/renderer/nodes/ChatAnswerControls.tsx b/src/renderer/nodes/ChatAnswerControls.tsxnew file mode 100644index 000000000..03b2e5a74--- /dev/null+++ b/src/renderer/nodes/ChatAnswerControls.tsx@@ -0,0 +1,228 @@+import { useCallback, useId, useRef, useState, type FormEvent } from 'react'+import type { ChatQuestion, PermissionAnswer } from '@shared/agents/permission-answer'+import {+ CHAT_ANSWER_TEXT_MAX,+ PLAN_CHOICES,+ emptySelection,+ planReviseAnswer,+ questionAnswerFrom,+ toggleLabel,+ type QuestionSelection+} from '../lib/chatAnswer'++/**+ * Answer controls under the ⌘M panel's Plan / Question card — rendered ONLY on the card the node's+ * held request belongs to (`activeAnswerCard`), and keyed by that request's ticket in ChatPanel, so+ * a new hold starts clean. They build a `PermissionAnswer` and hand it to `onSubmit`+ * (`answerPermission`); what the hook prints is core's decision, never ours.+ *+ * Status, deliberately quiet: "Sending…" while the call is out, "Sent" once core wrote the answer+ * (the hook's "answered" POST then flips the node to working and the card turns read-only — so a+ * "Sent" cannot outlive the hold), and on a refusal (`false`: an expired hold, a ticket core has no+ * record of, a hook script too old to read it) or a rejected call, one line that names the terminal+ * path — the TUI dialog is still up and still works — with every control usable again for a retry.+ */++type SubmitStatus = 'idle' | 'sending' | 'sent' | 'error'++interface Common {+ onSubmit: (answer: PermissionAnswer) => Promise<boolean>+ /** The node's agent, for "Sent — waiting for Claude Code…". */+ agentLabel: string+ /** The effective ⌘M chord ('' = unbound), for the terminal fallback in the error line. */+ chip: string+}++function useSubmit(onSubmit: Common['onSubmit']) {+ const [status, setStatus] = useState<SubmitStatus>('idle')+ const inFlight = useRef(false)+ const submit = useCallback(+ async (answer: PermissionAnswer) => {+ if (inFlight.current) return+ inFlight.current = true+ setStatus('sending')+ let ok = false+ try {+ ok = (await onSubmit(answer)) === true+ } catch {+ ok = false+ }+ inFlight.current = false+ setStatus(ok ? 'sent' : 'error')+ },+ [onSubmit]+ )+ return { status, submit, busy: status === 'sending' || status === 'sent' }+}++function StatusLine({ status, agentLabel, chip }: { status: SubmitStatus; agentLabel: string; chip: string }) {+ // Always mounted, so the live region is not remounted (and re-announced) as the status changes.+ const text =+ status === 'sending'+ ? 'Sending…'+ : status === 'sent'+ ? `Sent — waiting for ${agentLabel}…`+ : status === 'error'+ ? chip+ ? `Couldn't send — answer in the terminal (${chip})`+ : "Couldn't send — answer in the terminal"+ : ''+ return (+ <div+ className={`term-chat__answer-status${status === 'error' ? ' term-chat__answer-status--error' : ''}`}+ role="status"+ aria-live="polite"+ >+ {text}+ </div>+ )+}++export function PlanAnswerControls({ onSubmit, agentLabel, chip }: Common) {+ const { status, submit, busy } = useSubmit(onSubmit)+ const [revising, setRevising] = useState(false)+ const [feedback, setFeedback] = useState('')+ const revise = planReviseAnswer(feedback)+ const feedbackId = useId()++ const sendRevise = (e: FormEvent) => {+ e.preventDefault()+ if (revise && !busy) void submit(revise)+ }++ return (+ <div className="term-chat__answer" role="group" aria-label="Answer the plan">+ {!revising ? (+ <div className="term-chat__answer-row">+ {PLAN_CHOICES.map((c, i) => (+ <button+ key={c.mode}+ type="button"+ className={`term-chat__answer-btn${i === 0 ? ' term-chat__answer-btn--primary' : ''}`}+ title={c.hint}+ disabled={busy}+ onClick={() => void submit({ kind: 'plan', mode: c.mode })}+ >+ {c.label}+ </button>+ ))}+ <button type="button" className="term-chat__answer-btn" disabled={busy} onClick={() => setRevising(true)}>+ Revise…+ </button>+ </div>+ ) : (+ <form className="term-chat__answer-revise" onSubmit={sendRevise}>+ <label htmlFor={feedbackId} className="term-chat__answer-label">+ What should change in the plan?+ </label>+ <textarea+ id={feedbackId}+ className="term-chat__input"+ rows={3}+ maxLength={CHAT_ANSWER_TEXT_MAX}+ value={feedback}+ disabled={busy}+ autoFocus+ onChange={(e) => setFeedback(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape' && !busy) {+ e.stopPropagation()+ setRevising(false)+ }+ }}+ />+ <div className="term-chat__answer-row">+ <button type="submit" className="term-chat__answer-btn term-chat__answer-btn--primary" disabled={busy || !revise}>+ Send feedback+ </button>+ <button type="button" className="term-chat__answer-btn" disabled={busy} onClick={() => setRevising(false)}>+ Cancel+ </button>+ </div>+ </form>+ )}+ <StatusLine status={status} agentLabel={agentLabel} chip={chip} />+ </div>+ )+}++export function QuestionAnswerControls({ questions, onSubmit, agentLabel, chip }: Common & { questions: ChatQuestion[] }) {+ const { status, submit, busy } = useSubmit(onSubmit)+ const [sel, setSel] = useState<QuestionSelection[]>(() => emptySelection(questions))+ const answer = questionAnswerFrom(questions, sel)+ const baseId = useId()++ const update = (i: number, next: Partial<QuestionSelection>) =>+ setSel((s) => s.map((x, k) => (k === i ? { ...x, ...next } : x)))++ const onFormSubmit = (e: FormEvent) => {+ e.preventDefault()+ if (answer && !busy) void submit(answer)+ }++ return (+ <form className="term-chat__answer" aria-label="Answer the question" onSubmit={onFormSubmit}>+ {questions.map((q, i) => {+ const s = sel[i]+ const name = `${baseId}-q${i}`+ const otherId = `${name}-other`+ const noOptions = q.options.length === 0+ return (+ <fieldset key={q.question} className="term-chat__answer-q" disabled={busy}>+ <legend className="term-chat__answer-label">{q.question}</legend>+ {q.options.map((o) => (+ <label key={o.label} className="term-chat__answer-option">+ <input+ type={q.multiSelect ? 'checkbox' : 'radio'}+ name={name}+ checked={s.labels.includes(o.label) && (q.multiSelect || !s.other)}+ onChange={(e) =>+ q.multiSelect+ ? update(i, { labels: toggleLabel(s.labels, o.label, e.target.checked) })+ : update(i, { labels: [o.label], other: false })+ }+ />+ <span>{o.label}</span>+ {o.description && <span className="term-chat__answer-desc">{o.description}</span>}+ </label>+ ))}+ {!noOptions && (+ <label className="term-chat__answer-option">+ <input+ type={q.multiSelect ? 'checkbox' : 'radio'}+ name={name}+ checked={s.other}+ onChange={(e) =>+ q.multiSelect+ ? update(i, { other: e.target.checked })+ : update(i, { other: true, labels: [] })+ }+ />+ <span>Other</span>+ </label>+ )}+ <input+ type="text"+ className="term-chat__input term-chat__answer-text"+ aria-label={noOptions ? `Your answer: ${q.question}` : `Other answer: ${q.question}`}+ placeholder={noOptions ? 'Your answer' : 'Type another answer'}+ id={otherId}+ maxLength={CHAT_ANSWER_TEXT_MAX}+ value={s.otherText}+ // Typing is choosing "Other" (on a single choice it replaces the picked option).+ onChange={(e) =>+ update(i, q.multiSelect ? { otherText: e.target.value, other: true } : { otherText: e.target.value, other: true, labels: [] })+ }+ />+ </fieldset>+ )+ })}+ <div className="term-chat__answer-row">+ <button type="submit" className="term-chat__answer-btn term-chat__answer-btn--primary" disabled={busy || !answer}>+ Submit+ </button>+ </div>+ <StatusLine status={status} agentLabel={agentLabel} chip={chip} />+ </form>+ )+}diff --git a/src/renderer/nodes/ChatPanel.answers.test.tsx b/src/renderer/nodes/ChatPanel.answers.test.tsxnew file mode 100644index 000000000..acf89b927--- /dev/null+++ b/src/renderer/nodes/ChatPanel.answers.test.tsx@@ -0,0 +1,271 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ChatMessage, ChatTranscriptResult } from '@shared/types'+import type { AnswerPermissionPayload, ChatQuestion, HeldPermission } from '@shared/agents/permission-answer'+import { useAgentStatus } from '../state/agentStatus'++/**+ * Answer controls on the ⌘M Plan / Question card (pure mapping: `lib/chatAnswer.test.ts`). Pins the+ * glue: controls only on the card the held ticket belongs to, the structured answer handed to+ * `answerPermission`, "Sent" on success, a quiet retryable error on refusal, and the composer copy.+ */++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const { session, answerPermission, reads } = vi.hoisted(() => {+ const reads: { messages: unknown[] } = { messages: [] }+ const answerPermission = vi.fn(async (_p: unknown) => true)+ const session = {+ api: {+ chat: {+ readTranscript: async () => ({ messages: reads.messages, found: true, olderCursor: null, unmatchedResults: [] })+ },+ pty: { sendText: vi.fn(async () => true as const) },+ answerPermission+ }+ }+ return { session, answerPermission, reads }+})+vi.mock('../session/session', () => ({ useSession: () => session }))++import { ChatPanel } from './ChatPanel'++const NODE = 'n-chat-answers'+let host: HTMLDivElement+let root: Root++const SINGLE: ChatQuestion = {+ question: 'Pick one?',+ multiSelect: false,+ options: [{ label: 'A', description: 'first' }, { label: 'B' }]+}+const MULTI: ChatQuestion = { question: 'Which surfaces?', multiSelect: true, options: [{ label: 'Desktop' }, { label: 'Server' }] }++const planMsg = (key: number, result?: string): ChatMessage => ({+ role: 'assistant',+ key,+ parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: `# Plan ${key}`, ...(result ? { result } : {}) }]+})+const askMsg = (key: number, questions: ChatQuestion[], result?: string): ChatMessage => ({+ role: 'assistant',+ key,+ parts: [{ kind: 'tool', name: 'AskUserQuestion', arg: '', body: 'questions', questions, ...(result ? { result } : {}) }]+})++async function hold(state: 'blocked' | 'waiting', held: HeldPermission | undefined): Promise<void> {+ await act(async () => {+ useAgentStatus.getState().setState(NODE, state, 'claude', false, held?.pendingId, true, false, held)+ })+}+async function mount(messages: ChatMessage[]): Promise<void> {+ reads.messages = messages+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)+ })+}+const cards = (): HTMLElement[] => [...host.querySelectorAll<HTMLElement>('.term-chat__tool-card')]+const button = (scope: ParentNode, text: string): HTMLButtonElement =>+ [...scope.querySelectorAll('button')].find((b) => b.textContent === text) as HTMLButtonElement+const click = async (el: HTMLElement): Promise<void> => {+ await act(async () => {+ el.click()+ })+}+const type = async (el: HTMLInputElement | HTMLTextAreaElement, text: string): Promise<void> => {+ const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype+ await act(async () => {+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(el, text)+ el.dispatchEvent(new Event('input', { bubbles: true }))+ })+}+const sent = (): AnswerPermissionPayload => answerPermission.mock.calls.at(-1)![0] as AnswerPermissionPayload+const statusText = (): string => host.querySelector('.term-chat__answer-status')?.textContent ?? ''++beforeEach(() => {+ answerPermission.mockReset()+ answerPermission.mockResolvedValue(true)+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(async () => {+ await act(async () => root.unmount())+ host.remove()+ useAgentStatus.setState((s) => {+ const byId = { ...s.byId }+ delete byId[NODE]+ return { byId }+ })+})++describe('plan card', () => {+ const HELD = { pendingId: 'n-p-1', toolName: 'ExitPlanMode' }++ it('the held plan card gets the approve buttons; each sends its mode', async () => {+ await hold('blocked', HELD)+ await mount([planMsg(0)])+ const card = cards()[0]+ expect([...card.querySelectorAll('button')].map((b) => b.textContent)).toEqual([+ 'Approve · previous mode',+ 'Approve · accept edits',+ 'Approve · ask before edits',+ 'Revise…'+ ])+ await click(button(card, 'Approve · accept edits'))+ expect(sent()).toEqual({ nodeId: NODE, pendingId: 'n-p-1', answer: { kind: 'plan', mode: 'acceptEdits' } })+ expect(statusText()).toBe('Sent — waiting for Claude Code…')+ // Sent: the controls lock, so a second click cannot send a second answer.+ expect(button(card, 'Approve · previous mode').disabled).toBe(true)+ })++ it('"Revise…" opens a feedback box; Send feedback sends plan-revise', async () => {+ await hold('blocked', HELD)+ await mount([planMsg(0)])+ await click(button(cards()[0], 'Revise…'))+ const ta = cards()[0].querySelector('textarea') as HTMLTextAreaElement+ expect(button(cards()[0], 'Send feedback').disabled).toBe(true) // nothing typed yet+ await type(ta, ' split step 2 ')+ await click(button(cards()[0], 'Send feedback'))+ expect(sent().answer).toEqual({ kind: 'plan-revise', message: 'split step 2' })+ })++ it('a refusal shows a quiet error pointing at the terminal and keeps the buttons usable', async () => {+ answerPermission.mockResolvedValueOnce(false)+ await hold('blocked', HELD)+ await mount([planMsg(0)])+ await click(button(cards()[0], 'Approve · previous mode'))+ expect(statusText()).toMatch(/^Couldn't send — answer in the terminal/)+ expect(statusText()).not.toContain('Sent')+ expect(button(cards()[0], 'Approve · previous mode').disabled).toBe(false)+ // Retry works.+ await click(button(cards()[0], 'Approve · previous mode'))+ expect(answerPermission).toHaveBeenCalledTimes(2)+ expect(statusText()).toBe('Sent — waiting for Claude Code…')+ })++ it('a hold that ended while the user was choosing is not answered (read as a refusal)', async () => {+ await hold('blocked', HELD)+ await mount([planMsg(0)])+ const approve = button(cards()[0], 'Approve · previous mode')+ // Replaced in the store under the rendered card, without a re-render having happened yet.+ useAgentStatus.getState().byId[NODE]!.held = { pendingId: 'n-p-2', toolName: 'ExitPlanMode' }+ await click(approve)+ expect(answerPermission).not.toHaveBeenCalled()+ expect(statusText()).toMatch(/^Couldn't send/)+ })++ it('an older plan card stays read-only; only the newest unanswered one gets controls', async () => {+ await hold('blocked', HELD)+ await mount([planMsg(0, 'User rejected'), planMsg(10)])+ expect(cards()[0].querySelector('.term-chat__answer')).toBeNull()+ expect(cards()[1].querySelector('.term-chat__answer')).not.toBeNull()+ })++ it('no controls without a held ticket (old hook script), or once the node is working again', async () => {+ await hold('blocked', undefined)+ await mount([planMsg(0)])+ expect(host.querySelector('.term-chat__answer')).toBeNull()+ await hold('blocked', HELD)+ expect(host.querySelector('.term-chat__answer')).not.toBeNull()+ await act(async () => {+ useAgentStatus.getState().setState(NODE, 'working', 'claude')+ })+ expect(host.querySelector('.term-chat__answer')).toBeNull()+ })++ it('the composer points at the card while controls are up, at the terminal otherwise', async () => {+ await hold('blocked', HELD)+ await mount([planMsg(0)])+ const ta = host.querySelector('.term-chat__compose textarea') as HTMLTextAreaElement+ expect(ta.placeholder).toContain('answer on the card above')+ // The status row at the end says the same.+ expect(host.querySelector('.term-chat__activity')?.textContent).toContain('answer on the card above')+ await hold('blocked', undefined)+ await act(async () => {+ useAgentStatus.getState().setState(NODE, 'blocked', 'claude', false, 'n-p-9', true, false, { pendingId: 'n-p-9', toolName: 'Bash' })+ })+ expect(ta.placeholder).toContain('waiting for an answer in the terminal')+ })+})++describe('question card', () => {+ const held = (questions: string[]): HeldPermission => ({ pendingId: 'n-q-1', toolName: 'AskUserQuestion', questions })+ const radio = (label: string): HTMLInputElement =>+ [...host.querySelectorAll<HTMLLabelElement>('.term-chat__answer-option')]+ .find((l) => l.querySelector('span')?.textContent === label)!+ .querySelector('input') as HTMLInputElement++ it('single choice: radio options, Submit sends the label', async () => {+ await hold('waiting', held(['Pick one?']))+ await mount([askMsg(0, [SINGLE])])+ expect(radio('A').type).toBe('radio')+ const submit = button(cards()[0], 'Submit')+ expect(submit.disabled).toBe(true)+ await click(radio('B'))+ expect(submit.disabled).toBe(false)+ await click(submit)+ expect(sent()).toEqual({+ nodeId: NODE,+ pendingId: 'n-q-1',+ answer: { kind: 'question', answers: { 'Pick one?': 'B' } }+ })+ })++ it('multi choice: checkboxes, labels sent in option order', async () => {+ await hold('waiting', held(['Which surfaces?']))+ await mount([askMsg(0, [MULTI])])+ expect(radio('Desktop').type).toBe('checkbox')+ await click(radio('Server'))+ await click(radio('Desktop'))+ await click(button(cards()[0], 'Submit'))+ expect(sent().answer).toEqual({ kind: 'question', answers: { 'Which surfaces?': ['Desktop', 'Server'] } })+ })++ it('"Other": typing picks it and sends free text', async () => {+ await hold('waiting', held(['Pick one?']))+ await mount([askMsg(0, [SINGLE])])+ await click(radio('A'))+ await type(host.querySelector('.term-chat__answer-text') as HTMLInputElement, 'neither')+ expect(radio('Other').checked).toBe(true)+ expect(radio('A').checked).toBe(false)+ await click(button(cards()[0], 'Submit'))+ expect(sent().answer).toEqual({ kind: 'question', answers: { 'Pick one?': 'neither' }, freeText: ['Pick one?'] })+ })++ it('several questions: Submit waits for all of them', async () => {+ await hold('waiting', held(['Pick one?', 'Which surfaces?']))+ await mount([askMsg(0, [SINGLE, MULTI])])+ await click(radio('A'))+ expect(button(cards()[0], 'Submit').disabled).toBe(true)+ await click(radio('Server'))+ await click(button(cards()[0], 'Submit'))+ expect(sent().answer).toEqual({ kind: 'question', answers: { 'Pick one?': 'A', 'Which surfaces?': ['Server'] } })+ })++ it('a card whose questions do not match the held request stays read-only', async () => {+ await hold('waiting', held(['Something else?']))+ await mount([askMsg(0, [SINGLE])])+ expect(host.querySelector('.term-chat__answer')).toBeNull()+ expect(host.querySelector('.term-chat__compose textarea')!.getAttribute('placeholder')).toContain(+ 'waiting for an answer in the terminal'+ )+ })++ it('an answered question card stays read-only and shows its result', async () => {+ await hold('waiting', held(['Pick one?']))+ await mount([askMsg(0, [SINGLE], 'User answered: B')])+ expect(host.querySelector('.term-chat__answer')).toBeNull()+ expect(cards()[0].textContent).toContain('User answered: B')+ })++ it('a read-only transcript (closed node) never shows controls', async () => {+ await hold('waiting', held(['Pick one?']))+ reads.messages = [askMsg(0, [SINGLE])]+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" readOnly />)+ })+ expect(host.querySelector('.term-chat__answer')).toBeNull()+ })+})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex d864a16e6..8486968b9 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -21,6 +21,9 @@ import { E_UNSUPPORTED } from '@shared/rpc'import { Spinner } from '../components/Spinner'import { CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'import { ChatLoadingStatus } from './ChatPanelFallback'+import { activeAnswerCard } from '../lib/chatAnswer'+import { PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'+import type { PermissionAnswer } from '@shared/agents/permission-answer'// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.@@ -137,6 +140,9 @@ export function ChatPanel({const paused = useAgentStatus((s) => s.byId[nodeId]?.paused)const dropped = useAgentStatus((s) => s.byId[nodeId]?.dropped)const sessionEnded = useAgentStatus((s) => s.byId[nodeId]?.sessionEnded)+ // The request the node's managed hook is holding (plan / question / permission). The store keeps+ // the same object across same-ticket events, so this selector re-renders only on a new hold.+ const held = useAgentStatus((s) => s.byId[nodeId]?.held)const customAgents = useSettings((s) => s.settings.customAgents)// Not just `working`: a TUI dialog (`waiting`/`blocked`) would be ANSWERED by sendText's Enter,// and a pane whose CLI is gone (hibernated/paused/dropped/exited) is a SHELL that would execute it.@@ -146,6 +152,14 @@ export function ChatPanel({// send and the first hook event: set by `send`, retired by the next state change (the real state// takes over) or, for an agent whose hooks never report, after a bounded timeout.const activity = chatActivity({ refusal, optimistic, readOnly: !!readOnly })+ // The one Plan / Question card that gets answer controls (lib/chatAnswer.ts): only while the pane+ // holds a TUI dialog (`dialog` — the CLI is in the pane and waiting) and only on the card the held+ // ticket belongs to. A host whose hook script predates structured answers never sends `held`, so+ // its cards stay read-only — the terminal path is then the only one, exactly as before.+ const answerCard = useMemo(+ () => (!readOnly && refusal === 'dialog' ? activeAnswerCard(messages, held) : null),+ [readOnly, refusal, messages, held]+ )const msgsRef = useRef<HTMLDivElement>(null)const prevState = useRef(state)// Request token: only the NEWEST readTranscript may land. An older read resolving late (the@@ -486,6 +500,19 @@ export function ChatPanel({setInput('')}, [api, input, nodeId, agentId])+ // Answer the held request through core, which validates the answer against the pending request+ // file and builds what the hook prints. The ticket is re-checked against the store at SEND time:+ // a hold that ended (answered in the TUI, timed out, replaced) while the user was choosing must+ // not receive an answer meant for it — that reads as a refusal, and the card says to use the+ // terminal. `false` from core is the same (see ChatAnswerControls).+ const answerHeld = useCallback(+ async (pendingId: string, answer: PermissionAnswer): Promise<boolean> => {+ if (useAgentStatus.getState().byId[nodeId]?.held?.pendingId !== pendingId) return false+ return api.answerPermission({ nodeId, pendingId, answer })+ },+ [api, nodeId]+ )+const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {// Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.const action = chatKeyAction({@@ -585,6 +612,25 @@ export function ChatPanel({<div className="term-chat__tool-card-title">{toolCardTitle(p.name)}</div><MarkdownText text={p.body} />{p.result && <pre className="term-chat__tool-result">{p.result}</pre>}+ {answerCard && held && answerCard.message === i && answerCard.part === j && (+ // Keyed by the ticket: a new hold on the same card starts from a clean state.+ p.name === 'AskUserQuestion' && p.questions ? (+ <QuestionAnswerControls+ key={held.pendingId}+ questions={p.questions}+ agentLabel={agentLabel}+ chip={mdChip}+ onSubmit={(a) => answerHeld(held.pendingId, a)}+ />+ ) : (+ <PlanAnswerControls+ key={held.pendingId}+ agentLabel={agentLabel}+ chip={mdChip}+ onSubmit={(a) => answerHeld(held.pendingId, a)}+ />+ )+ )}</div>) : (<details key={j} className="term-chat__tool">@@ -604,7 +650,13 @@ export function ChatPanel({// composer placeholder's own (`chatComposerPlaceholder`), so the two never disagree.<div className="term-chat__activity" role="status" aria-live="polite">{activity === 'working' && <Spinner />}- {chatComposerPlaceholder({ readonly: false, refusal: activity, agentLabel, chip: mdChip })}+ {chatComposerPlaceholder({+ readonly: false,+ refusal: activity,+ agentLabel,+ chip: mdChip,+ answerOnCard: answerCard !== null+ })}</div>)}</div>@@ -615,7 +667,13 @@ export function ChatPanel({value={input}onChange={(e) => setInput(e.target.value)}onKeyDown={onKeyDown}- placeholder={chatComposerPlaceholder({ readonly, refusal, agentLabel, chip: mdChip })}+ placeholder={chatComposerPlaceholder({+ readonly,+ refusal,+ agentLabel,+ chip: mdChip,+ answerOnCard: answerCard !== null+ })}disabled={readonly || refusal !== null}rows={2}/>diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 9658f1aa2..edbaa7b8a 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3287,6 +3287,95 @@ body,padding-top: 6px;border-top: 1px solid rgba(var(--tint-rgb), 0.1);}+/* Answer controls under a held Plan / Question card (nodes/ChatAnswerControls.tsx). Plain rows in+ the card's own flow: no fill of their own, so they read the same on every appearance. */+.term-chat__answer {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-top: 8px;+ padding-top: 8px;+ border-top: 1px solid rgba(var(--tint-rgb), 0.1);+}+.term-chat__answer-row {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}+.term-chat__answer-btn {+ padding: 4px 10px;+ font-size: 12px;+ color: var(--text);+ background: rgba(var(--tint-rgb), 0.06);+ border: 1px solid rgba(var(--tint-rgb), 0.14);+ border-radius: 6px;+ cursor: pointer;+}+.term-chat__answer-btn:hover:not(:disabled) {+ background: rgba(var(--tint-rgb), 0.12);+}+.term-chat__answer-btn--primary {+ color: #fff;+ background: var(--accent);+ border-color: transparent;+}+.term-chat__answer-btn--primary:hover:not(:disabled) {+ background: var(--accent);+ filter: brightness(1.1);+}+.term-chat__answer-btn:disabled {+ opacity: 0.5;+ cursor: default;+}+.term-chat__answer-btn:focus-visible,+.term-chat__answer-option input:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 1px;+}+.term-chat__answer-revise {+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.term-chat__answer-q {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin: 0;+ padding: 0;+ border: 0;+ min-width: 0;+}+.term-chat__answer-label {+ margin-bottom: 2px;+ padding: 0;+ font-size: 12px;+ font-weight: 600;+ color: var(--text);+}+.term-chat__answer-option {+ display: flex;+ align-items: baseline;+ gap: 6px;+ font-size: 12px;+ color: var(--text);+ cursor: pointer;+}+.term-chat__answer-desc {+ color: var(--muted);+}+.term-chat__answer-text {+ font-size: 12px;+ padding: 5px 8px;+}+/* Always rendered (a live region that appears is not reliably announced); empty = no height. */+.term-chat__answer-status {+ font-size: 11px;+ color: var(--muted);+}+.term-chat__answer-status--error {+ color: var(--danger);+}/* Shared loading spinner (`components/Spinner.tsx`). CSS-only: a ring with one transparentquarter, rotated. It inherits `currentColor` and scales with the surrounding font size, so thesame element sits beside 11px bar text and 12px placeholder text without per-site sizing.diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex 3b61bc1df..fe9346a32 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -139,6 +139,33 @@ describe('normalizeClaude — held tool (structured answers)', () => {expect(bad && 'held' in bad).toBe(false)expect(bad).toMatchObject({ pendingId: 'n1-1-1' }) // the approval ticket itself is untouched})+ it('a held question also carries its exact question texts, so a surface can match its card', () => {+ const e = normalizeClaude(+ env({+ hook_event_name: 'PermissionRequest',+ tool_name: 'AskUserQuestion',+ nodeterm_pending_id: 'n1-1-1',+ tool_input: { questions: [{ question: 'Pick one?', options: [{ label: 'A' }] }, { question: 'And?' }] }+ })+ )+ expect(e).toMatchObject({ held: { pendingId: 'n1-1-1', toolName: 'AskUserQuestion', questions: ['Pick one?', 'And?'] } })+ })+ it('an unreadable question input keeps the held ticket but carries no texts (no controls)', () => {+ const e = normalizeClaude(+ env({+ hook_event_name: 'PermissionRequest',+ tool_name: 'AskUserQuestion',+ nodeterm_pending_id: 'n1-1-1',+ tool_input: { questions: 'nope' }+ })+ )+ expect(e && e.held).toEqual({ pendingId: 'n1-1-1', toolName: 'AskUserQuestion' })+ // A plan never carries question texts.+ const plan = normalizeClaude(+ env({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', nodeterm_pending_id: 'n1-1-1', tool_input: { plan: 'p' } })+ )+ expect(plan && plan.held).toEqual({ pendingId: 'n1-1-1', toolName: 'ExitPlanMode' })+ })it('the answered signal carries no held request (the hold is over)', () => {const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', nodeterm_pending_id: 'n1-1-1', nodeterm_answered: 'allow' })diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 072f60899..9016a0f92 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -1,6 +1,6 @@import type { AgentId } from './config'import type { ObservedClaudeAccount } from '../types'-import { isSafeToolName, type HeldPermission } from './permission-answer'+import { ASK_USER_QUESTION_TOOL, isSafeToolName, readQuestions, type HeldPermission } from './permission-answer'export type AgentState = 'working' | 'waiting' | 'blocked' | 'done'@@ -176,6 +176,8 @@ interface ClaudePayload {cron?: string/** Bash only: the task was launched as a background shell (`run_in_background: true`). */run_in_background?: boolean+ /** AskUserQuestion only — read through `readQuestions`, never trusted as typed. */+ questions?: unknown}tool_response?: {status?: string@@ -197,6 +199,14 @@ export function isAsyncSubagentLaunch(r: { status?: string; isAsync?: boolean }return r?.status === 'async_launched' || r?.isAsync === true}+/** The held request a PermissionRequest names. A question also carries its exact texts (the same+ * reader the question card uses), so a surface offers controls only on the card it belongs to. */+function heldOf(pendingId: string, toolName: string, p: ClaudePayload): HeldPermission {+ if (toolName !== ASK_USER_QUESTION_TOOL) return { pendingId, toolName }+ const qs = readQuestions(p.tool_input)+ return qs ? { pendingId, toolName, questions: qs.map((q) => q.question) } : { pendingId, toolName }+}+export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | null {const p = env.payload as ClaudePayload// Child tool activity cannot drive the parent, but permission requests still need a reply.@@ -327,9 +337,7 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nulastMessage: p.last_assistant_message,// Deterministic-approval ticket (present only when the wait-branch of the managed hook ran)....(p.nodeterm_pending_id ? { pendingId: p.nodeterm_pending_id } : {}),- ...(p.nodeterm_pending_id && isSafeToolName(tool)- ? { held: { pendingId: p.nodeterm_pending_id, toolName: tool } }- : {})+ ...(p.nodeterm_pending_id && isSafeToolName(tool) ? { held: heldOf(p.nodeterm_pending_id, tool, p) } : {})}}if (ev === 'Notification') {diff --git a/src/shared/agents/permission-answer.test.ts b/src/shared/agents/permission-answer.test.tsnew file mode 100644index 000000000..5dccfe3d8--- /dev/null+++ b/src/shared/agents/permission-answer.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest'+import { QUESTION_TEXT_MAX_CHARS, QUESTIONS_MAX, readQuestions } from './permission-answer'++// Real shape: AskUserQuestion's `questions`, copied from a transcript's toolUseResult (v2.1.258).+const REAL = [+ {+ question: "Canvas'a baktığında bir ipin sana öncelikle NEYİ söylemesini istiyorsun?",+ header: 'İp anlamı',+ options: [+ { label: 'Sıra / bağımlılık (Recommended)', description: 'Kim kimden sonra çalışır (--after).' },+ { label: 'Kim kimi okuyabilir (context)', description: 'Bilgi akışı asıl şey.' }+ ],+ multiSelect: false+ },+ {+ question: 'Which surfaces should get it?',+ header: 'Surfaces',+ options: [{ label: 'Desktop' }, { label: 'Server Edition', description: 'Browser' }],+ multiSelect: true+ }+]++describe('readQuestions — the ONE reader of an AskUserQuestion input for the answer UI', () => {+ it('reads a real input exactly (the texts are answer keys and must never be altered)', () => {+ expect(readQuestions({ questions: REAL })).toEqual([+ {+ question: REAL[0].question,+ header: 'İp anlamı',+ multiSelect: false,+ options: [+ { label: 'Sıra / bağımlılık (Recommended)', description: 'Kim kimden sonra çalışır (--after).' },+ { label: 'Kim kimi okuyabilir (context)', description: 'Bilgi akışı asıl şey.' }+ ]+ },+ {+ question: 'Which surfaces should get it?',+ header: 'Surfaces',+ multiSelect: true,+ options: [{ label: 'Desktop' }, { label: 'Server Edition', description: 'Browser' }]+ }+ ])+ })++ it('a question with no options (the free-text variant) is kept with an empty option list', () => {+ expect(readQuestions({ questions: [{ question: 'Name?', kind: 'text' }] })).toEqual([+ { question: 'Name?', multiSelect: false, options: [] }+ ])+ })++ it('refuses the WHOLE input rather than dropping a question it cannot read', () => {+ // A partial list would let the UI submit an answer that silently skips a question.+ expect(readQuestions({ questions: [REAL[0], { question: '' }] })).toBeUndefined()+ expect(readQuestions({ questions: [REAL[0], 'nope'] })).toBeUndefined()+ expect(readQuestions({ questions: [{ question: 'Q', options: [{ label: 7 }] }] })).toBeUndefined()+ expect(readQuestions({ questions: [] })).toBeUndefined()+ expect(readQuestions({})).toBeUndefined()+ expect(readQuestions(null)).toBeUndefined()+ })++ it('refuses oversized input instead of truncating an answer key', () => {+ const long = 'x'.repeat(QUESTION_TEXT_MAX_CHARS + 1)+ expect(readQuestions({ questions: [{ question: long, options: [] }] })).toBeUndefined()+ expect(readQuestions({ questions: [{ question: 'Q', options: [{ label: long }] }] })).toBeUndefined()+ const many = Array.from({ length: QUESTIONS_MAX + 1 }, (_, i) => ({ question: `Q${i}`, options: [] }))+ expect(readQuestions({ questions: many })).toBeUndefined()+ })++ it('a duplicated question text is refused (answers are keyed by it)', () => {+ expect(readQuestions({ questions: [REAL[1], REAL[1]] })).toBeUndefined()+ })+})diff --git a/src/shared/agents/permission-answer.ts b/src/shared/agents/permission-answer.tsindex 4e0c97ad3..136e53ec2 100644--- a/src/shared/agents/permission-answer.ts+++ b/src/shared/agents/permission-answer.ts@@ -41,6 +41,11 @@ export type PermissionAnswer =| { kind: 'plan-revise'; message: string }| { kind: 'question'; answers: Record<string, string | string[]>; freeText?: string[] }+/** Typed text in an answer ("Revise…" feedback, a question's "Other"), in UTF-16 code units. ONE+ * definition: core refuses past it and the answer fields stop at it, so a field can never accept+ * text core would then refuse. A person-sized limit; the decision's byte cap bounds the file. */+export const ANSWER_TEXT_MAX_CHARS = 8000+/** The payload of `window.nodeTerminal.answerPermission`. `decision` is the pre-structured* contract and still works alone; when `answer` is present it wins. */export interface AnswerPermissionPayload {@@ -60,6 +65,69 @@ export interface AnswerPermissionPayload {export interface HeldPermission {pendingId: stringtoolName: string+ /** AskUserQuestion only: the held request's EXACT question texts (`readQuestions`), so a surface+ * can tell which question card the ticket belongs to. Absent = unreadable input = no controls. */+ questions?: string[]+}++/** One AskUserQuestion option, as a surface renders it. */+export interface ChatQuestionOption {+ label: string+ description?: string+}++/** One AskUserQuestion question, read for the answer controls. `question` and each `label` are+ * ANSWER KEYS (core matches them byte for byte against the pending request), so they are carried+ * exactly or not at all. `options` is empty for the free-text variant. */+export interface ChatQuestion {+ question: string+ header?: string+ multiSelect: boolean+ options: ChatQuestionOption[]+}++/** Bounds for `readQuestions`. Exceeding one refuses the input (an answer key cannot be truncated);+ * far above anything the picker shows, which lists a handful of questions with a handful of options. */+export const QUESTIONS_MAX = 16+export const QUESTION_OPTIONS_MAX = 32+export const QUESTION_TEXT_MAX_CHARS = 4000++const isRecord = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v)+const keyText = (v: unknown): v is string =>+ typeof v === 'string' && v !== '' && v.length <= QUESTION_TEXT_MAX_CHARS+/** A display-only string (header, description): kept when readable, dropped (never refused) when not. */+const displayText = (v: unknown): string | undefined => (keyText(v) && v.trim() !== '' ? v : undefined)++/**+ * The ONE reader of an AskUserQuestion `tool_input` for the answer UI — used for the question card+ * (`core/transcript-reader.ts`) AND for the held request's texts (`normalizeClaude`), so the two can+ * be compared without either side drifting. All or nothing: a question it cannot read, a duplicate+ * question text or anything over the bounds refuses the whole input, because a partial list would+ * let the UI submit an answer that silently skips a question. Undefined = no controls, read-only card.+ */+export function readQuestions(input: unknown): ChatQuestion[] | undefined {+ if (!isRecord(input) || !Array.isArray(input.questions)) return undefined+ const qs = input.questions+ if (qs.length === 0 || qs.length > QUESTIONS_MAX) return undefined+ const out: ChatQuestion[] = []+ const seen = new Set<string>()+ for (const q of qs) {+ if (!isRecord(q) || !keyText(q.question) || seen.has(q.question)) return undefined+ seen.add(q.question)+ const options: ChatQuestionOption[] = []+ if (q.options !== undefined) {+ if (!Array.isArray(q.options) || q.options.length > QUESTION_OPTIONS_MAX) return undefined+ for (const o of q.options) {+ if (!isRecord(o) || !keyText(o.label)) return undefined+ const description = displayText(o.description)+ options.push(description ? { label: o.label, description } : { label: o.label })+ }+ }+ const header = displayText(q.header)+ out.push({ question: q.question, ...(header ? { header } : {}), multiSelect: q.multiSelect === true, options })+ }+ return out}/** Tool names are agent-controlled text (MCP tools are `mcp__<server>__<tool>`); only a plaindiff --git a/src/shared/types.ts b/src/shared/types.tsindex 52c6fdccf..da009600a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -7,7 +7,7 @@ import type { CloneProgress } from './clone-url'import type { KeybindingOverrides, TerminalShortcutPolicy } from './keybindings'import type { NormalizedAgentEvent } from './agents/normalize'import type { PaneOwner } from './agents/pane-owner-predicate'-import type { AnswerPermissionPayload } from './agents/permission-answer'+import type { AnswerPermissionPayload, ChatQuestion } from './agents/permission-answer'import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'import type { ControlConfirmWaivers } from './control-confirm'import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'@@ -2804,6 +2804,10 @@ export type ChatPart =* its options — `core/chat-tool-body.ts`). Present = the renderer shows an expanded card* instead of the collapsed chip. Capped at 64K characters. */body?: string+ /** `AskUserQuestion` only: the questions read for the answer controls (`readQuestions`) —+ * the SAME reader the held request's texts come from, so a surface can match the card to the+ * held ticket. Absent = unreadable input = the card stays read-only. */+ questions?: ChatQuestion[]/** The transcript's `tool_use` id. Set only by a PAGED read (`ChatTranscriptResult.olderCursor`* present): a result carried across a page boundary (`unmatchedResults`) is attached by it. */id?: string