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): harden the answer-card rebind (lagging card, one reload, quiet backoff)

reviewa8a778a70d08
diff --git a/CLAUDE.md b/CLAUDE.md
index ecf6fad05..7b0178f05 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2578,8 +2578,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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.
+ under A and cannot bind B, and behind an older-page fetch, which it never cancels). It is a QUIET
+ read (no "Loading…"), and one path owns it: on working → blocked the turn-end reload does. While a
+ card says "Updating…" it retries with backoff (`rebindRetryDelay`: 2 s doubling to 30 s, reset per
+ request). A read under B that still shows the card A was bound to (same tool id / line offset —
+ the transcript can lag the hook) stays "Updating…": B must surface on a card the thread shows as
+ new. 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 73d682b2b..b5289be7f 100644
--- a/docs/hook-reply-approvals.md
+++ b/docs/hook-reply-approvals.md
@@ -169,9 +169,11 @@ thread was read for (`answerCardState`; the iOS fix of the same race is #41): `t
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.
+"Updating… — or answer in the terminal" — and the panel forces a quiet tail reload (queued behind a
+read or an older-page fetch in flight; retried with 2 s → 30 s backoff while a card says "Updating…").
+A read under B that still shows the very card A was bound to does not bind B either: the transcript
+can lag the hook, and a new request must surface on a card the thread shows as new. 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
diff --git a/src/renderer/lib/chatAnswer.test.ts b/src/renderer/lib/chatAnswer.test.ts
index ff6a96b02..9802a3ce2 100644
--- a/src/renderer/lib/chatAnswer.test.ts
+++ b/src/renderer/lib/chatAnswer.test.ts
@@ -6,6 +6,10 @@ import {
activeAnswerCard,
answerCardState,
answerRebindPending,
+ answerCardKey,
+ rebindRetryDelay,
+ CHAT_ANSWER_REBIND_RETRY_MS,
+ CHAT_ANSWER_REBIND_RETRY_MAX_MS,
emptySelection,
latestUnansweredCard,
CHAT_ANSWER_TEXT_MAX,
@@ -190,7 +194,12 @@ describe('answerCardState (the card binds the request the thread was READ for)',
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' })
+ expect(answerCardState([plan(0)], A, 'p-A')).toEqual({
+ kind: 'active',
+ card: { message: 0, part: 0 },
+ cardKey: 'k0: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 } })
@@ -221,3 +230,44 @@ describe('answerRebindPending', () => {
expect(answerRebindPending(undefined, 'p-A')).toBe(false)
})
})
+
+describe('answerCardKey', () => {
+ it('prefers the tool_use id, else the line offset + part, else the position', () => {
+ const withId: ChatMessage = { role: 'assistant', key: 5, parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: 'p', id: 'toolu_1' }] }
+ expect(answerCardKey([withId], { message: 0, part: 0 })).toBe('toolu_1')
+ expect(answerCardKey([plan(7)], { message: 0, part: 0 })).toBe('k7:0')
+ const unkeyed: ChatMessage = { role: 'assistant', parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: 'p' }] }
+ expect(answerCardKey([unkeyed], { message: 0, part: 0 })).toBe('i0:0')
+ })
+})
+
+describe('answerCardState: a new request must surface on a card the thread shows as NEW', () => {
+ const B = { pendingId: 'p-B', toolName: 'ExitPlanMode' }
+ it('the card that was bound to the previous request stays "Updating…" even after a read under B', () => {
+ expect(answerCardState([plan(0)], B, 'p-B', { pendingId: 'p-A', cardKey: 'k0:0' })).toEqual({
+ kind: 'updating',
+ card: { message: 0, part: 0 }
+ })
+ })
+ it('a different card binds B; the same request re-reading its own card stays bound', () => {
+ expect(answerCardState([plan(0, 'rejected'), plan(10)], B, 'p-B', { pendingId: 'p-A', cardKey: 'k0:0' })).toMatchObject({
+ kind: 'active',
+ pendingId: 'p-B',
+ cardKey: 'k10:0'
+ })
+ expect(answerCardState([plan(0)], B, 'p-B', { pendingId: 'p-B', cardKey: 'k0:0' })).toMatchObject({ kind: 'active' })
+ })
+})
+
+describe('rebindRetryDelay', () => {
+ it('doubles from the base and caps', () => {
+ expect([0, 1, 2, 3, 4, 10].map(rebindRetryDelay)).toEqual([
+ CHAT_ANSWER_REBIND_RETRY_MS,
+ 2 * CHAT_ANSWER_REBIND_RETRY_MS,
+ 4 * CHAT_ANSWER_REBIND_RETRY_MS,
+ 8 * CHAT_ANSWER_REBIND_RETRY_MS,
+ CHAT_ANSWER_REBIND_RETRY_MAX_MS,
+ CHAT_ANSWER_REBIND_RETRY_MAX_MS
+ ])
+ })
+})
diff --git a/src/renderer/lib/chatAnswer.ts b/src/renderer/lib/chatAnswer.ts
index b77c0b059..995efaf98 100644
--- a/src/renderer/lib/chatAnswer.ts
+++ b/src/renderer/lib/chatAnswer.ts
@@ -84,6 +84,30 @@ export function latestUnansweredCard(messages: readonly ChatMessage[], toolName:
* 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
+/** The retry backs off (doubling) up to this, so a card that never updates costs one read per 30 s. */
+export const CHAT_ANSWER_REBIND_RETRY_MAX_MS = 30_000
+
+/** The delay before retry number `attempt` (0-based): 2 s, 4, 8, 16, then 30 s. */
+export function rebindRetryDelay(attempt: number): number {
+ return Math.min(CHAT_ANSWER_REBIND_RETRY_MS * 2 ** Math.max(0, attempt), CHAT_ANSWER_REBIND_RETRY_MAX_MS)
+}
+
+/**
+ * A stable name for a card across reads: the tool_use id when the paged reader gives one, else the
+ * source line's byte offset + part, else (an unkeyed thread) its position.
+ */
+export function answerCardKey(messages: readonly ChatMessage[], ref: AnswerCardRef): string {
+ const m = messages[ref.message]
+ const p = m?.parts[ref.part]
+ if (p && p.kind === 'tool' && p.id) return p.id
+ return m?.key !== undefined ? `k${m.key}:${ref.part}` : `i${ref.message}:${ref.part}`
+}
+
+/** The card a request was last bound to, so a NEW request cannot bind that same card. */
+export interface BoundAnswerCard {
+ pendingId: string
+ cardKey: string
+}
/** 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. */
@@ -93,7 +117,7 @@ export function answerRebindPending(held: HeldPermission | undefined, threadHeld
/** What the held plan / question card shows: controls bound to one request, or "Updating…". */
export type AnswerCardState =
- | { kind: 'active'; card: AnswerCardRef; pendingId: string }
+ | { kind: 'active'; card: AnswerCardRef; cardKey: string; pendingId: string }
| { kind: 'updating'; card: AnswerCardRef | null }
| null
@@ -106,17 +130,24 @@ export type AnswerCardState =
* 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.
+ * read that started under it lands — and, given `previous` (the card the last request was bound to),
+ * until the thread shows a card OTHER than that one. Active controls bind `threadHeldFor`, which is then the held id.
*/
export function answerCardState(
messages: readonly ChatMessage[],
held: HeldPermission | undefined,
- threadHeldFor: string | null | undefined
+ threadHeldFor: string | null | undefined,
+ previous?: BoundAnswerCard | null
): 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
+ if (!card) return null
+ const cardKey = answerCardKey(messages, card)
+ // A read under B that still shows the very card A was bound to has not caught up with B (the
+ // transcript may lag the hook): B must surface on a card the thread shows as NEW.
+ if (previous && previous.pendingId !== held.pendingId && previous.cardKey === cardKey) return { kind: 'updating', card }
+ return { kind: 'active', card, cardKey, pendingId: held.pendingId }
}
/** What the user has picked for one question. `labels` are option labels; `other` + `otherText`
diff --git a/src/renderer/nodes/ChatPanel.answerBind.test.tsx b/src/renderer/nodes/ChatPanel.answerBind.test.tsx
index 14a69d32f..73f286d39 100644
--- a/src/renderer/nodes/ChatPanel.answerBind.test.tsx
+++ b/src/renderer/nodes/ChatPanel.answerBind.test.tsx
@@ -5,7 +5,7 @@ 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'
+import { CHAT_ANSWER_REBIND_RETRY_MAX_MS, CHAT_ANSWER_REBIND_RETRY_MS } from '../lib/chatAnswer'
/**
* The ⌘M answer card binds the request the DISPLAYED thread was read for (`threadHeldFor` — the held
@@ -60,9 +60,9 @@ async function render(sessionId = 's1'): Promise<void> {
root.render(<ChatPanel nodeId={NODE} sessionId={sessionId} agentId="claude" />)
})
}
-async function settle(i: number, messages: ChatMessage[]): Promise<void> {
+async function settle(i: number, messages: ChatMessage[], olderCursor: number | null = null): Promise<void> {
await act(async () => {
- pending[i].resolve({ messages, found: true, olderCursor: null, unmatchedResults: [] })
+ pending[i].resolve({ messages, found: true, olderCursor, unmatchedResults: [] })
})
}
async function fail(i: number): Promise<void> {
@@ -178,9 +178,9 @@ describe('answer card binding', () => {
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)
+ // working → blocked with a new held id: ONE reload (the turn-end reload owns it), not two.
+ expect(pending).toHaveLength(2)
+ await settle(1, THREAD_A)
expect(controlsOn()).toEqual([0])
await act(async () => approve(cards()[0]).click())
expect(sent().pendingId).toBe('n-p-A')
@@ -203,4 +203,74 @@ describe('answer card binding', () => {
await act(async () => btn.click())
expect(answerPermission).not.toHaveBeenCalled()
})
+
+ it('a read under B that still shows the card A was bound to does not bind B (transcript lag)', async () => {
+ await boundToA()
+ await hold(B)
+ // The reload started under B, but the transcript has not written plan B yet: same card as A's.
+ await settle(1, THREAD_A)
+ expect(controlsOn()).toEqual([])
+ expect(updatingOn()).toEqual([0])
+ // Kept retrying; once plan B's card is there, B binds to it.
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ 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('retries back off (2 s, 4 s, …) and reset when the held request changes', async () => {
+ await boundToA()
+ await hold(B)
+ await fail(1)
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ expect(pending).toHaveLength(3)
+ await fail(2)
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ expect(pending).toHaveLength(3) // the second retry waits 4 s
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ expect(pending).toHaveLength(4)
+ await fail(3)
+ // Capped: never more often than… and never later than the max.
+ await advance(CHAT_ANSWER_REBIND_RETRY_MAX_MS)
+ expect(pending).toHaveLength(5)
+ // A new held request starts over: its reload is immediate, then 2 s again.
+ await hold({ pendingId: 'n-p-C', toolName: 'ExitPlanMode' })
+ await fail(4)
+ await fail(5)
+ await advance(CHAT_ANSWER_REBIND_RETRY_MS)
+ expect(pending).toHaveLength(7)
+ })
+
+ it('no retry when there is no card to update (nothing on screen would change)', async () => {
+ await hold(A)
+ await render()
+ await settle(0, [planMsg(0, 'Plan A', 'User rejected')])
+ await hold(B)
+ expect(pending).toHaveLength(2) // the one forced reload on the change
+ await fail(1)
+ await advance(CHAT_ANSWER_REBIND_RETRY_MAX_MS * 2)
+ expect(pending).toHaveLength(2)
+ })
+
+ it('the rebind reload never cancels an older-page fetch: it waits for it, and the page lands', async () => {
+ await hold(A)
+ await render()
+ const el = host.querySelector('.term-chat__msgs') as HTMLDivElement
+ Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => 400 })
+ Object.defineProperty(el, 'scrollHeight', { configurable: true, get: () => 100 })
+ // A thread with history behind it, shorter than the viewport: the older page is fetched at once.
+ await settle(0, [planMsg(100, 'Plan A')], 100)
+ expect(pending).toHaveLength(2)
+ await hold(B)
+ expect(pending).toHaveLength(2) // queued behind the older page, not started over it
+ await settle(1, [{ role: 'assistant', key: 0, parts: [{ kind: 'text', text: 'earlier' }] }])
+ expect(host.textContent).toContain('earlier') // the page was not cancelled
+ expect(pending).toHaveLength(3)
+ // A quiet reload: the thread stays on screen, no "Loading conversation…".
+ expect(host.textContent).not.toContain('Loading conversation')
+ await settle(2, [{ role: 'assistant', key: 0, parts: [{ kind: 'text', text: 'earlier' }] }, planMsg(100, 'Plan A', 'User rejected'), planMsg(200, 'Plan B')])
+ expect(controlsOn()).toEqual([1])
+ })
})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 577219da5..685748a10 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -21,7 +21,7 @@ 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 { CHAT_ANSWER_REBIND_RETRY_MS, answerCardState, answerRebindPending } from '../lib/chatAnswer'
+import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'
import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
import type { PermissionAnswer } from '@shared/agents/permission-answer'
import { ChatComposer } from './ChatComposer'
@@ -186,14 +186,30 @@ export function ChatPanel({
const threadHeldFor = heldRead && heldRead.identity === identity ? heldRead.pendingId : undefined
const threadHeldForRef = useRef(threadHeldFor)
threadHeldForRef.current = threadHeldFor
+ // The card the last request was bound to (per transcript identity): a NEW request must surface on
+ // a card the thread shows as new, never on that one — see `answerCardState`'s `previous`.
+ const [boundCard, setBoundCard] = useState<(BoundAnswerCard & { identity: string }) | null>(null)
+ const previousBound = boundCard && boundCard.identity === identity ? boundCard : null
const cardState = useMemo(
- () => (!readOnly && refusal === 'dialog' ? answerCardState(messages, held, threadHeldFor) : null),
- [readOnly, refusal, messages, held, threadHeldFor]
+ () => (!readOnly && refusal === 'dialog' ? answerCardState(messages, held, threadHeldFor, previousBound) : null),
+ [readOnly, refusal, messages, held, threadHeldFor, previousBound]
)
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 rebindForRef = useRef(rebindFor)
+ rebindForRef.current = rebindFor
+ const activePendingId = cardState?.kind === 'active' ? cardState.pendingId : null
+ const activeCardKey = cardState?.kind === 'active' ? cardState.cardKey : null
+ useEffect(() => {
+ if (activePendingId === null || activeCardKey === null) return
+ setBoundCard((b) =>
+ b && b.identity === identity && b.pendingId === activePendingId && b.cardKey === activeCardKey
+ ? b
+ : { identity, pendingId: activePendingId, cardKey: activeCardKey }
+ )
+ }, [identity, activePendingId, activeCardKey])
const msgsRef = useRef<HTMLDivElement>(null)
const prevState = useRef(state)
// Request token: only the NEWEST readTranscript may land. An older read resolving late (the
@@ -236,16 +252,20 @@ export function ChatPanel({
// (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>(() => {})
+ const loadRef = useRef<(live?: boolean, rebind?: 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
// unconfirmed sends on screen (`carryUnconfirmed`), leaves a failed older page's retry row alone
// (clearing it would re-arm a failing fetch every interval) and never flips the empty state to
// "Loading…" (which would strobe on every hook event).
- const load = useCallback((live = false) => {
+ //
+ // `rebind` = the held-request reload (see `requestHeldReload`): QUIET like a live read (no
+ // "Loading…", the older-page row left alone, unconfirmed sends kept), and it never cancels an
+ // older-page fetch — it is only ever started with none in flight.
+ const load = useCallback((live = false, rebind = false) => {
const token = ++reqRef.current
- olderReqRef.current++
+ if (!rebind) 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.
@@ -256,10 +276,10 @@ export function ChatPanel({
const settleHeldReload = (bound: string | null | undefined) => {
if (!heldReloadQueuedRef.current) return
heldReloadQueuedRef.current = false
- if (answerRebindPending(useAgentStatus.getState().byId[nodeId]?.held, bound)) loadRef.current()
+ if (answerRebindPending(useAgentStatus.getState().byId[nodeId]?.held, bound)) loadRef.current(false, true)
}
- olderInFlightRef.current = false
- if (!live) {
+ if (!rebind) olderInFlightRef.current = false
+ if (!live && !rebind) {
// Cancelling an older fetch (or clearing its error) removes a row ABOVE the viewport: anchor
// it like any other change up there, or the view jumps by the row's height.
if (olderStateRef.current !== 'idle') captureAnchor()
@@ -268,7 +288,7 @@ export function ChatPanel({
setTailLoading(true)
tailInFlightRef.current = true
lastTailStartRef.current = Date.now()
- if (!live) setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread
+ if (!live && !rebind) setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread
// `nodeId` is what lets an SSH-project node resolve on its host; the rejection branch is what
// keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently
// presenting itself as an empty conversation. Only the newest TAIL window is read — older
@@ -300,7 +320,7 @@ export function ChatPanel({
settleHeldReload(heldAtStart)
return
}
- setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live }))
+ setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live || rebind }))
setLoadState('ok')
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
@@ -341,6 +361,14 @@ export function ChatPanel({
olderInFlightRef.current = false
// A hook event held behind this page gets its (trailing) tail read now.
queueMicrotask(() => attemptLiveRef.current())
+ // …and so does a held-request reload queued behind it (`requestHeldReload`), once the page
+ // has landed (microtask: after its setThread below).
+ if (heldReloadQueuedRef.current) {
+ heldReloadQueuedRef.current = false
+ queueMicrotask(() => {
+ if (rebindForRef.current !== null) loadRef.current(false, true)
+ })
+ }
}
void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {
before,
@@ -375,21 +403,33 @@ export function ChatPanel({
// 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).
+ // An older-page fetch in flight is waited for too, never cancelled: the user's scroll-up paging
+ // must not restart because a plan was revised.
const requestHeldReload = useCallback(() => {
if (loadStateRef.current === 'unsupported') return
- if (tailInFlightRef.current) heldReloadQueuedRef.current = true
- else loadRef.current()
+ if (tailInFlightRef.current || olderInFlightRef.current) heldReloadQueuedRef.current = true
+ else loadRef.current(false, true)
}, [])
+ // Retries back off (`rebindRetryDelay`), counted per held request: a new one starts over.
+ const rebindAttemptRef = useRef(0)
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.
+ rebindAttemptRef.current = 0
+ // working → blocked with a new held id in the same render: the turn-end reload below (a full
+ // read that starts NOW, under the new request) owns it — one read, not two.
+ if (rebindFor !== null && !(prevState.current === 'working' && state !== 'working')) requestHeldReload()
+ }, [rebindFor, requestHeldReload]) // eslint-disable-line react-hooks/exhaustive-deps -- `state` is read, not a trigger
+ // …and while a card stays on "Updating…" with no read in flight (the reload failed, or the
+ // transcript has not caught up), try again: nothing else reads the tail while the agent is
+ // blocked. Only while there IS a card saying so — with none, a reload changes nothing on screen.
+ const hasUpdatingCard = updatingCard !== null
useEffect(() => {
- if (rebindFor === null || tailLoading) return
- const t = setTimeout(requestHeldReload, CHAT_ANSWER_REBIND_RETRY_MS)
+ if (rebindFor === null || tailLoading || !hasUpdatingCard) return
+ const t = setTimeout(() => {
+ rebindAttemptRef.current++
+ requestHeldReload()
+ }, rebindRetryDelay(rebindAttemptRef.current))
return () => clearTimeout(t)
- }, [rebindFor, tailLoading, requestHeldReload])
+ }, [rebindFor, tailLoading, hasUpdatingCard, requestHeldReload])
// Invalidate any in-flight read when the panel goes away.
useEffect(