Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(chat): bind ⌘M answer cards to the request the thread was read for

review33fdf7a501f9
diff --git a/CLAUDE.md b/CLAUDE.md
index 91784a8d0..ecf6fad05 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2572,6 +2572,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`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.
+ **A card answers only the request the THREAD was read for** (`answerCardState`, same rule as
+ iOS #41): `threadHeldFor` = the held ticket at the START of the last applied tail read, keyed by
+ transcript identity. While held moves A → B (a revised plan) plan A's card can still be on screen
+ unanswered, and a tool-name match would approve B from it — so until a read started under B lands,
+ the latest unanswered card of that tool says "Updating… — or answer in the terminal" and nothing
+ is answerable. A held change forces a tail reload (queued behind a read in flight, which started
+ under A and cannot bind B), retried every `CHAT_ANSWER_REBIND_RETRY_MS` while "Updating…"; the
+ answer payload carries the BOUND id, re-checked against store and binding at send time.
**The thread look (2026-09-26, claude.ai-style)**: the user's message is a neutral rounded bubble
on the right (`term-chat__bubble`, a tint lift — never the blue accent), the assistant's is plain
full-width text with no bubble. One quiet action row per assistant TURN (`lib/chatThread.ts`
diff --git a/docs/hook-reply-approvals.md b/docs/hook-reply-approvals.md
index 204042caf..73d682b2b 100644
--- a/docs/hook-reply-approvals.md
+++ b/docs/hook-reply-approvals.md
@@ -164,6 +164,15 @@ While controls are up, the composer placeholder and the status row point at the
(`chatComposerPlaceholder({answerOnCard})`). The kanban card modal mounts the same `ChatPanel`, so the
controls appear there too.
+**Binding to the thread that was read (2026-09-28).** A card answers only the request the DISPLAYED
+thread was read for (`answerCardState`; the iOS fix of the same race is #41): `threadHeldFor` is the
+held ticket at the start of the last applied tail read. While the hook moves held A → held B, plan A's
+card can still be on screen with no result; matched by tool name alone it would approve B. So a
+request the thread was not read for gets no controls — the latest unanswered card of its tool shows
+"Updating… — or answer in the terminal" — and the panel forces a tail reload (queued behind a read in
+flight, retried while "Updating…"). The answer payload names the bound id, re-checked against both the
+store and the binding at send time.
+
**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/renderer/lib/chatAnswer.test.ts b/src/renderer/lib/chatAnswer.test.ts
index 947e97862..ff6a96b02 100644
--- a/src/renderer/lib/chatAnswer.test.ts
+++ b/src/renderer/lib/chatAnswer.test.ts
@@ -4,7 +4,10 @@ import type { ChatQuestion } from '@shared/agents/permission-answer'
import {
PLAN_CHOICES,
activeAnswerCard,
+ answerCardState,
+ answerRebindPending,
emptySelection,
+ latestUnansweredCard,
CHAT_ANSWER_TEXT_MAX,
answerTooLong,
planReviseAnswer,
@@ -168,3 +171,53 @@ describe('planReviseAnswer', () => {
})
})
+
+describe('latestUnansweredCard', () => {
+ it('is the newest card of that tool when it has no result', () => {
+ expect(latestUnansweredCard([plan(0), plan(1)], 'ExitPlanMode')).toEqual({ message: 1, part: 0 })
+ })
+ it('is null when the newest card of that tool is answered (older unanswered ones are history)', () => {
+ expect(latestUnansweredCard([plan(0), plan(1, 'User approved')], 'ExitPlanMode')).toBeNull()
+ })
+ it('ignores other tools and needs no matching questions', () => {
+ expect(latestUnansweredCard([ask(0, undefined), plan(1, 'done')], 'AskUserQuestion')).toEqual({ message: 0, part: 1 })
+ expect(latestUnansweredCard([], 'ExitPlanMode')).toBeNull()
+ })
+})
+
+describe('answerCardState (the card binds the request the thread was READ for)', () => {
+ const A = { pendingId: 'p-A', toolName: 'ExitPlanMode' }
+ const B = { pendingId: 'p-B', toolName: 'ExitPlanMode' }
+
+ it('active, bound to the held id, when the thread was read for the request held now', () => {
+ expect(answerCardState([plan(0)], A, 'p-A')).toEqual({ kind: 'active', card: { message: 0, part: 0 }, pendingId: 'p-A' })
+ })
+ it('updating (no controls) while the thread was read for ANOTHER request: plan A card must not answer B', () => {
+ expect(answerCardState([plan(0)], B, 'p-A')).toEqual({ kind: 'updating', card: { message: 0, part: 0 } })
+ })
+ it('updating while the thread was read with nothing held (nil → held), or never read', () => {
+ expect(answerCardState([plan(0)], B, null)).toEqual({ kind: 'updating', card: { message: 0, part: 0 } })
+ expect(answerCardState([plan(0)], B, undefined)).toEqual({ kind: 'updating', card: { message: 0, part: 0 } })
+ })
+ it('updating shows on no card when the latest card of the held tool is answered', () => {
+ expect(answerCardState([plan(0, 'User rejected')], B, 'p-A')).toEqual({ kind: 'updating', card: null })
+ })
+ it('nothing held (held → nil), or a held tool with no card at all: null', () => {
+ expect(answerCardState([plan(0)], undefined, 'p-A')).toBeNull()
+ expect(answerCardState([plan(0)], { pendingId: 'p-A', toolName: 'Bash' }, null)).toBeNull()
+ })
+ it('bound but the card does not match (question texts): null, like activeAnswerCard', () => {
+ const q = { pendingId: 'p-Q', toolName: 'AskUserQuestion', questions: ['Other?'] }
+ expect(answerCardState([ask(0, [SINGLE])], q, 'p-Q')).toBeNull()
+ })
+})
+
+describe('answerRebindPending', () => {
+ it('only for a held plan / question the thread was not read for', () => {
+ expect(answerRebindPending({ pendingId: 'p-B', toolName: 'ExitPlanMode' }, 'p-A')).toBe(true)
+ expect(answerRebindPending({ pendingId: 'p-B', toolName: 'AskUserQuestion' }, null)).toBe(true)
+ expect(answerRebindPending({ pendingId: 'p-B', toolName: 'ExitPlanMode' }, 'p-B')).toBe(false)
+ expect(answerRebindPending({ pendingId: 'p-B', toolName: 'Bash' }, 'p-A')).toBe(false)
+ expect(answerRebindPending(undefined, 'p-A')).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/chatAnswer.ts b/src/renderer/lib/chatAnswer.ts
index ba1022161..b77c0b059 100644
--- a/src/renderer/lib/chatAnswer.ts
+++ b/src/renderer/lib/chatAnswer.ts
@@ -58,6 +58,67 @@ export function activeAnswerCard(messages: readonly ChatMessage[], held: HeldPer
return null
}
+/** A plan or a question: the two held tools whose card in the thread can carry answer controls. */
+const isAnswerCardTool = (name: string): boolean => name === EXIT_PLAN_MODE_TOOL || name === ASK_USER_QUESTION_TOOL
+
+/**
+ * The newest card of `toolName`, when it is still unanswered — the one card that says "Updating…"
+ * while the thread is re-read. Unlike `activeAnswerCard` it needs no matching question texts: it
+ * marks where the controls WILL be, it never answers anything.
+ */
+export function latestUnansweredCard(messages: readonly ChatMessage[], toolName: string): AnswerCardRef | 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 !== toolName) continue
+ return p.result === undefined ? { message: i, part: j } : null
+ }
+ }
+ return null
+}
+
+/**
+ * How long a card waits on "Updating…" before its reload is tried again. The held-request reload can
+ * fail (a downed ControlMaster, an unreadable transcript) and nothing else reads the tail while the
+ * agent is `blocked`, so without a retry the card would stay on "Updating…" for the whole hold.
+ */
+export const CHAT_ANSWER_REBIND_RETRY_MS = 2000
+
+/** A plan / question is held that the thread on screen was not read for: the tail must be re-read
+ * (and the card waits on "Updating…") before any card may answer it. */
+export function answerRebindPending(held: HeldPermission | undefined, threadHeldFor: string | null | undefined): boolean {
+ return !!held && isAnswerCardTool(held.toolName) && threadHeldFor !== held.pendingId
+}
+
+/** What the held plan / question card shows: controls bound to one request, or "Updating…". */
+export type AnswerCardState =
+ | { kind: 'active'; card: AnswerCardRef; pendingId: string }
+ | { kind: 'updating'; card: AnswerCardRef | null }
+ | null
+
+/**
+ * The answer card for the request held NOW, given the request the thread on screen was READ for
+ * (`threadHeldFor`: the held ticket at the START of the last applied tail read; `null` = read with
+ * nothing held, `undefined` = not read for this transcript yet).
+ *
+ * The card may only answer the request the thread was read for. While the hook moves held A → held
+ * B (plan A revised into plan B) the thread can still show plan A's card with no result, and a card
+ * matched by tool name alone would approve B from A's card. So a request the thread was not read
+ * for gets NO controls — only "Updating…" on the latest unanswered card of its tool, until a tail
+ * read that started under it lands. Active controls bind `threadHeldFor`, which is then the held id.
+ */
+export function answerCardState(
+ messages: readonly ChatMessage[],
+ held: HeldPermission | undefined,
+ threadHeldFor: string | null | undefined
+): AnswerCardState {
+ if (!held || !isAnswerCardTool(held.toolName)) return null
+ if (answerRebindPending(held, threadHeldFor)) return { kind: 'updating', card: latestUnansweredCard(messages, held.toolName) }
+ const card = activeAnswerCard(messages, held)
+ return card ? { kind: 'active', card, pendingId: held.pendingId } : 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 {
diff --git a/src/renderer/nodes/ChatAnswerControls.tsx b/src/renderer/nodes/ChatAnswerControls.tsx
index 87494e73b..d19500cd3 100644
--- a/src/renderer/nodes/ChatAnswerControls.tsx
+++ b/src/renderer/nodes/ChatAnswerControls.tsx
@@ -268,3 +268,17 @@ export function QuestionAnswerControls({ questions, onSubmit, agentLabel, chip }
</form>
)
}
+
+/**
+ * In place of the controls while the thread is re-read for a request it was not read for
+ * (`answerCardState` → `updating`): a new plan / question is held, and the card on screen may still
+ * be the previous one. Nothing here can answer anything; the terminal path still works, so the line
+ * names it — the same fallback the error line gives.
+ */
+export function AnswerControlsUpdating({ chip }: { chip: string }) {
+ return (
+ <div className="term-chat__answer term-chat__answer-updating" role="status" aria-live="polite">
+ {chip ? `Updating… — or answer in the terminal (${chip})` : 'Updating… — or answer in the terminal'}
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/ChatPanel.answerBind.test.tsx b/src/renderer/nodes/ChatPanel.answerBind.test.tsx
new file mode 100644
index 000000000..14a69d32f
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.answerBind.test.tsx
@@ -0,0 +1,206 @@
+// @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, HeldPermission } from '@shared/agents/permission-answer'
+import { useAgentStatus } from '../state/agentStatus'
+import { CHAT_ANSWER_REBIND_RETRY_MS } from '../lib/chatAnswer'
+
+/**
+ * The ⌘M answer card binds the request the DISPLAYED thread was read for (`threadHeldFor` — the held
+ * ticket at the START of the last applied tail read), never the request that happens to be held
+ * now. While the hook moves held A → held B (a revised plan) the thread on screen can still show
+ * plan A's card with no result, and a card matched only by tool name would approve B from A's card.
+ * Pure mapping: `lib/chatAnswer.test.ts` (`answerCardState`); this pins the orderings in the glue.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+interface Pending {
+ session: string | undefined
+ resolve: (r: ChatTranscriptResult) => void
+ reject: (e: unknown) => void
+}
+
+const { pending, session, answerPermission } = vi.hoisted(() => {
+ const pending: Pending[] = []
+ const readTranscript = (s: string | undefined) =>
+ new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ session: s, resolve, reject }))
+ const answerPermission = vi.fn(async (_p: unknown) => true)
+ const session = { api: { chat: { readTranscript }, pty: { sendText: vi.fn(async () => true as const) }, answerPermission } }
+ return { pending, session, answerPermission }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-answer-bind'
+const A: HeldPermission = { pendingId: 'n-p-A', toolName: 'ExitPlanMode' }
+const B: HeldPermission = { pendingId: 'n-p-B', toolName: 'ExitPlanMode' }
+let host: HTMLDivElement
+let root: Root
+
+const planMsg = (key: number, title: string, result?: string): ChatMessage => ({
+ role: 'assistant',
+ key,
+ parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: `# ${title}`, ...(result ? { result } : {}) }]
+})
+/** Plan A still unanswered on screen (the case the race is about), then plan B once the transcript has it. */
+const THREAD_A = [planMsg(0, 'Plan A')]
+const THREAD_B = [planMsg(0, 'Plan A', 'User rejected'), planMsg(10, 'Plan B')]
+
+async function hold(held: HeldPermission | undefined, state: 'blocked' | 'working' = 'blocked'): Promise<void> {
+ await act(async () => {
+ useAgentStatus.getState().setState(NODE, state, 'claude', false, held?.pendingId, true, false, held)
+ })
+}
+async function render(sessionId = 's1'): Promise<void> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId={sessionId} agentId="claude" />)
+ })
+}
+async function settle(i: number, messages: ChatMessage[]): Promise<void> {
+ await act(async () => {
+ pending[i].resolve({ messages, found: true, olderCursor: null, unmatchedResults: [] })
+ })
+}
+async function fail(i: number): Promise<void> {
+ await act(async () => {
+ pending[i].reject(new Error('master down'))
+ })
+}
+async function advance(ms: number): Promise<void> {
+ await act(async () => {
+ vi.advanceTimersByTime(ms)
+ })
+}
+const cards = (): HTMLElement[] => [...host.querySelectorAll<HTMLElement>('.term-chat__tool-card')]
+const controlsOn = (): number[] => cards().flatMap((c, i) => (c.querySelector('.term-chat__answer-row') ? [i] : []))
+const updatingOn = (): number[] => cards().flatMap((c, i) => (c.querySelector('.term-chat__answer-updating') ? [i] : []))
+const approve = (card: HTMLElement): HTMLButtonElement =>
+ [...card.querySelectorAll('button')].find((b) => b.textContent === 'Approve · previous mode') as HTMLButtonElement
+const sent = (): AnswerPermissionPayload => answerPermission.mock.calls.at(-1)![0] as AnswerPermissionPayload
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ pending.length = 0
+ 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 }
+ })
+ vi.useRealTimers()
+})
+
+/** Mounted with A held and plan A's card answerable. */
+async function boundToA(): Promise<void> {
+ await hold(A)
+ await render()
+ await settle(0, THREAD_A)
+ expect(controlsOn()).toEqual([0])
+}
+
+describe('answer card binding', () => {
+ it('held A → B with no read in flight: A card shows "Updating…", never controls, until B is read', async () => {
+ await boundToA()
+ await hold(B)
+ // The change forced a tail reload at once; until it lands, the A card is NOT answerable…
+ expect(pending).toHaveLength(2)
+ expect(controlsOn()).toEqual([])
+ expect(updatingOn()).toEqual([0])
+ expect(cards()[0].querySelector('.term-chat__answer-updating')!.textContent).toMatch(/Updating… — or answer in the terminal/)
+ // …the composer points at the terminal, not the card…
+ expect(host.querySelector('.term-chat__compose textarea')!.getAttribute('placeholder')).toContain(
+ 'waiting for an answer in the terminal'
+ )
+ // …and once B's thread lands, B's card gets controls bound to B.
+ await settle(1, THREAD_B)
+ expect(updatingOn()).toEqual([])
+ expect(controlsOn()).toEqual([1])
+ await act(async () => approve(cards()[1]).click())
+ expect(sent()).toEqual({ nodeId: NODE, pendingId: 'n-p-B', answer: { kind: 'plan', mode: 'restore' } })
+ })
+
+ it('held A → B while a read that started under A is in flight: that read does not bind B; the queued reload does', async () => {
+ await boundToA()
+ // A read starts while A is held (the ↻ button stands in for any in-flight tail read).
+ await act(async () => (host.querySelector('.term-chat__refresh') as HTMLButtonElement).click())
+ expect(pending).toHaveLength(2)
+ await hold(B)
+ // Queued, not started alongside (single-flight): still only the read that began under A.
+ expect(pending).toHaveLength(2)
+ // It lands with plan A's thread — read for A, so B stays "Updating…" with no controls.
+ await settle(1, THREAD_A)
+ expect(controlsOn()).toEqual([])
+ expect(updatingOn()).toEqual([0])
+ // The queued reload runs on settle and binds B.
+ expect(pending).toHaveLength(3)
+ await settle(2, THREAD_B)
+ expect(controlsOn()).toEqual([1])
+ await act(async () => approve(cards()[1]).click())
+ expect(sent().pendingId).toBe('n-p-B')
+ })
+
+ it('a failed reload does not leave the card stuck: it is retried while "Updating…"', async () => {
+ await boundToA()
+ await hold(B)
+ await fail(1)
+ expect(updatingOn()).toEqual([0])
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ expect(pending).toHaveLength(3)
+ await settle(2, THREAD_B)
+ expect(controlsOn()).toEqual([1])
+ })
+
+ it('held → nil: controls go away, no "Updating…", no reload', async () => {
+ await boundToA()
+ await hold(undefined, 'working')
+ expect(controlsOn()).toEqual([])
+ expect(updatingOn()).toEqual([])
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS * 3)
+ expect(pending).toHaveLength(1)
+ })
+
+ it('nil → held: a thread read with nothing held is not bound to the new request until re-read', async () => {
+ await hold(undefined, 'working')
+ await render()
+ await settle(0, THREAD_A)
+ await hold(A)
+ expect(controlsOn()).toEqual([])
+ expect(updatingOn()).toEqual([0])
+ // Re-read (working → blocked also takes the turn-end reload; every read here started under A).
+ expect(pending.length).toBeGreaterThan(1)
+ await settle(pending.length - 1, THREAD_A)
+ expect(controlsOn()).toEqual([0])
+ await act(async () => approve(cards()[0]).click())
+ expect(sent().pendingId).toBe('n-p-A')
+ })
+
+ it('session change: the previous session\'s binding does not carry over to the new thread', async () => {
+ await boundToA()
+ await render('s2')
+ // The new session's read is in flight: the card on screen (the old session's) is not answerable.
+ expect(pending.at(-1)!.session).toBe('s2')
+ expect(controlsOn()).toEqual([])
+ await settle(pending.length - 1, THREAD_A)
+ expect(controlsOn()).toEqual([0])
+ })
+
+ it('a click on a bound card after the store moved on (no re-render yet) answers nothing', async () => {
+ await boundToA()
+ const btn = approve(cards()[0])
+ useAgentStatus.getState().byId[NODE]!.held = B
+ await act(async () => btn.click())
+ expect(answerPermission).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 69f6ba8bd..577219da5 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -21,8 +21,8 @@ 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 { CHAT_ANSWER_REBIND_RETRY_MS, answerCardState, answerRebindPending } from '../lib/chatAnswer'
+import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
import type { PermissionAnswer } from '@shared/agents/permission-answer'
import { ChatComposer } from './ChatComposer'
import { ChatTurnActions } from './ChatTurnActions'
@@ -176,10 +176,24 @@ export function ChatPanel({
// 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]
+ //
+ // …and only when the thread on screen was READ for that ticket (`threadHeldFor`, lib/chatAnswer.ts
+ // `answerCardState`): while the hook moves held A → held B the thread can still show plan A's card
+ // with no result, and matching by tool name alone would approve B from A's card. Until a tail read
+ // that started under B lands, the latest card says "Updating…" instead. Keyed by the transcript
+ // identity, so a session change never carries the previous thread's binding over.
+ const [heldRead, setHeldRead] = useState<{ identity: string; pendingId: string | null } | null>(null)
+ const threadHeldFor = heldRead && heldRead.identity === identity ? heldRead.pendingId : undefined
+ const threadHeldForRef = useRef(threadHeldFor)
+ threadHeldForRef.current = threadHeldFor
+ const cardState = useMemo(
+ () => (!readOnly && refusal === 'dialog' ? answerCardState(messages, held, threadHeldFor) : null),
+ [readOnly, refusal, messages, held, threadHeldFor]
)
+ const answerCard = cardState?.kind === 'active' ? cardState : null
+ const updatingCard = cardState?.kind === 'updating' ? cardState.card : null
+ // The request a rebind reload is owed for (null = none): drives the forced reload and its retry.
+ const rebindFor = cardState?.kind === 'updating' ? (held?.pendingId ?? null) : null
const msgsRef = useRef<HTMLDivElement>(null)
const prevState = useRef(state)
// Request token: only the NEWEST readTranscript may land. An older read resolving late (the
@@ -218,6 +232,11 @@ export function ChatPanel({
const livePendingRef = useRef(false)
const liveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const attemptLiveRef = useRef<() => void>(() => {})
+ // A held-request reload asked for while a tail read was in flight: run when that read settles
+ // (single-flight, like the live reads) — never dropped, since the read in flight started under the
+ // PREVIOUS request and cannot bind the new one. Any read that STARTS later satisfies it.
+ const heldReloadQueuedRef = useRef(false)
+ const loadRef = useRef<(live?: boolean) => void>(() => {})
// `live` = a read driven by a hook event while the agent works (see `attemptLive`), as opposed to
// the first open, the turn-end reload and ↻. A live read is background refresh: it keeps
@@ -227,6 +246,18 @@ export function ChatPanel({
const load = useCallback((live = false) => {
const token = ++reqRef.current
olderReqRef.current++
+ // The held request this read starts under: once it is applied, the thread is known to show the
+ // transcript as of (at least) that request. Read from the store, not the render: a hold that
+ // landed since the last render is exactly what this must see.
+ const heldAtStart = useAgentStatus.getState().byId[nodeId]?.held?.pendingId ?? null
+ heldReloadQueuedRef.current = false
+ // After this read settles: a queued held-request reload runs if the thread is still not read
+ // for the request held NOW (`bound` = what the thread is read for after this read).
+ const settleHeldReload = (bound: string | null | undefined) => {
+ if (!heldReloadQueuedRef.current) return
+ heldReloadQueuedRef.current = false
+ if (answerRebindPending(useAgentStatus.getState().byId[nodeId]?.held, bound)) loadRef.current()
+ }
olderInFlightRef.current = false
if (!live) {
// Cancelling an older fetch (or clearing its error) removes a row ABOVE the viewport: anchor
@@ -259,14 +290,20 @@ export function ChatPanel({
// The thread on screen is still this transcript's: back to `ok`, or the `loading` this
// reload set would stick and silently disable older paging (it waits for `ok`).
setLoadState('ok')
+ // Nothing was applied: the thread is still read for what it was read for before.
+ settleHeldReload(threadHeldForRef.current)
return
}
setThread(emptyThread(identity))
setLoadState('missing')
+ setHeldRead({ identity, pendingId: heldAtStart })
+ settleHeldReload(heldAtStart)
return
}
setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live }))
setLoadState('ok')
+ setHeldRead({ identity, pendingId: heldAtStart })
+ settleHeldReload(heldAtStart)
},
(e: unknown) => {
if (token !== reqRef.current) return
@@ -277,15 +314,18 @@ export function ChatPanel({
const t = threadRef.current
if (t.identity === identity && t.messages.length > 0) {
setLoadState('ok')
+ settleHeldReload(threadHeldForRef.current)
return
}
// …and, as there, a thread of ANOTHER transcript (the session changed under the panel) is
// cleared: the error message must not sit under the previous session's conversation.
if (t.identity !== identity) setThread(emptyThread(identity))
setLoadState(isUnsupported(e) ? 'unsupported' : 'error')
+ settleHeldReload(threadHeldForRef.current)
}
)
}, [api, sessionId, cwd, accountId, nodeId, agentId, identity])
+ loadRef.current = load
// Fetch the next OLDER page and prepend it. One in flight at a time; a result that arrives
// after a newer tail load (or unmount) is dropped by its token. A `found:false` here is a failed
@@ -331,6 +371,26 @@ export function ChatPanel({
load()
}, [load])
+ // A newly held plan / question the thread was not read for: re-read the tail now (declared after
+ // the initial load, so on mount this QUEUES behind that read rather than superseding it) — or, with a
+ // read in flight (it started under the previous request), queue it for that read's settle. Not
+ // for a surface that cannot read transcripts at all (every read would be refused).
+ const requestHeldReload = useCallback(() => {
+ if (loadStateRef.current === 'unsupported') return
+ if (tailInFlightRef.current) heldReloadQueuedRef.current = true
+ else loadRef.current()
+ }, [])
+ useEffect(() => {
+ if (rebindFor !== null) requestHeldReload()
+ }, [rebindFor, requestHeldReload])
+ // …and while the card stays on "Updating…" with no read in flight (the reload failed, or found
+ // nothing new), try again: nothing else reads the tail while the agent is blocked.
+ useEffect(() => {
+ if (rebindFor === null || tailLoading) return
+ const t = setTimeout(requestHeldReload, CHAT_ANSWER_REBIND_RETRY_MS)
+ return () => clearTimeout(t)
+ }, [rebindFor, tailLoading, requestHeldReload])
+
// Invalidate any in-flight read when the panel goes away.
useEffect(
() => () => {
@@ -523,13 +583,15 @@ export function ChatPanel({
const onWriteRefused = useCallback(() => setReadonly(true), [])
// 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:
+ // file and builds what the hook prints. `pendingId` is the request the CARD was bound to
+ // (`answerCardState`), re-checked at SEND time against both the store and the thread's binding:
// 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
+ if (threadHeldForRef.current !== pendingId) return false
return api.answerPermission({ nodeId, pendingId, answer })
},
[api, nodeId]
@@ -643,25 +705,29 @@ 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.
+ {answerCard && answerCard.card.message === i && answerCard.card.part === j && (
+ // Keyed by the BOUND ticket: a new hold on the same card starts from a clean
+ // state, and every answer names the request this card was drawn for.
p.name === 'AskUserQuestion' && p.questions ? (
<QuestionAnswerControls
- key={held.pendingId}
+ key={answerCard.pendingId}
questions={p.questions}
agentLabel={agentLabel}
chip={mdChip}
- onSubmit={(a) => answerHeld(held.pendingId, a)}
+ onSubmit={(a) => answerHeld(answerCard.pendingId, a)}
/>
) : (
<PlanAnswerControls
- key={held.pendingId}
+ key={answerCard.pendingId}
agentLabel={agentLabel}
chip={mdChip}
- onSubmit={(a) => answerHeld(held.pendingId, a)}
+ onSubmit={(a) => answerHeld(answerCard.pendingId, a)}
/>
)
)}
+ {updatingCard && updatingCard.message === i && updatingCard.part === j && (
+ <AnswerControlsUpdating chip={mdChip} />
+ )}
</div>
) : (
<details key={j} className="term-chat__tool">
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index f1d6fa952..0cb06130b 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3468,6 +3468,11 @@ body,
.term-chat__answer-status--error {
color: var(--danger);
}
+/* "Updating…" in place of the controls while the thread is re-read for a newly held request. */
+.term-chat__answer-updating {
+ font-size: 11px;
+ color: var(--muted);
+}
/* Shared loading spinner (`components/Spinner.tsx`). CSS-only: a ring with one transparent
quarter, rotated. It inherits `currentColor` and scales with the surrounding font size, so the
same element sits beside 11px bar text and 12px placeholder text without per-site sizing.