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): keep unconfirmed sends across live reads; quieter live loads

reviewad3198660971
diff --git a/CLAUDE.md b/CLAUDE.md
index c59224eda..f37981d13 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2500,6 +2500,11 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
tail — throttled (`CHAT_LIVE_RELOAD_MIN_MS`, trailing read guaranteed), single-flight, never for a
hidden panel or document (`lib/chatLive.ts`). The trigger is `agentStatus.onHookEvent`, NOT a
`stateAt` selector: same-state events refresh `stateAt` in place and notify no zustand subscriber.
+ A live read passes `applyTail(…, {carryUnconfirmed})`, which keeps the trailing unkeyed optimistic
+ send until the tail holds a matching user line (the send's own UserPromptSubmit read races the
+ transcript write); it never resets a failed older page or flips an empty state to "Loading…".
+ Gap: the panel reads the DEFAULT agent-status store, the only one Canvas's hook listener writes, so
+ a relay tab gets neither the row nor live reads until relay status is routed per session.
**Plan and question bodies (2026-09).** A tool call is normally a collapsed chip (`name` + a
≤200-char `arg`), which left an `ExitPlanMode` plan — the full markdown the terminal shows as
"Here is Claude's plan" — and an `AskUserQuestion` question + options unreadable in ⌘M, the one
diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.ts
index e40c285c8..d9812c706 100644
--- a/src/renderer/lib/chatPaging.test.ts
+++ b/src/renderer/lib/chatPaging.test.ts
@@ -104,6 +104,56 @@ describe('applyTail', () => {
})
})
+describe('applyTail — unconfirmed optimistic sends (live reads)', () => {
+ const ID = 'id'
+ const base = (msgs: ChatMessage[], olderCursor: number | null = null): ChatThread => ({
+ identity: ID,
+ messages: msgs,
+ olderCursor,
+ pending: new Map()
+ })
+
+ it('a live read whose tail lacks the prompt keeps the optimistic bubble at the end', () => {
+ const t = base([say(0, 'q'), say(100, 'a'), say(undefined, 'do it', 'user')], 0)
+ const out = applyTail(t, ID, page([say(0, 'q'), say(100, 'a'), say(200, 'thinking…')], 0), { carryUnconfirmed: true })
+ expect(texts(out)).toEqual(['q', 'a', 'thinking…', 'do it'])
+ expect(out.messages.at(-1)?.key).toBeUndefined()
+ })
+
+ it('a live read whose tail HAS the prompt shows it exactly once (the transcript copy)', () => {
+ const t = base([say(0, 'q'), say(undefined, ' do it\n', 'user')], 0)
+ const out = applyTail(t, ID, page([say(0, 'q'), say(300, 'do it', 'user'), say(400, 'ok')], 0), { carryUnconfirmed: true })
+ expect(texts(out)).toEqual(['q', 'do it', 'ok'])
+ expect(out.messages.every((m) => m.key !== undefined)).toBe(true)
+ })
+
+ it('matches one-for-one, and never against a user line the thread already had', () => {
+ // An OLD "yes" (key 100, already rendered) must not confirm the NEW unconfirmed "yes".
+ const t = base([say(100, 'yes', 'user'), say(undefined, 'yes', 'user'), say(undefined, 'yes', 'user')], 100)
+ const one = applyTail(t, ID, page([say(100, 'yes', 'user'), say(300, 'yes', 'user')], 100), { carryUnconfirmed: true })
+ expect(texts(one)).toEqual(['yes', 'yes', 'yes']) // key 100, key 300, one still unconfirmed
+ expect(one.messages.map((m) => m.key)).toEqual([100, 300, undefined])
+ })
+
+ it('also carries over a whole-file read (olderCursor null) of the same transcript', () => {
+ const t = base([say(0, 'q'), say(undefined, 'go', 'user')])
+ const out = applyTail(t, ID, page([say(0, 'q')], null), { carryUnconfirmed: true })
+ expect(texts(out)).toEqual(['q', 'go'])
+ })
+
+ it('never carries into ANOTHER transcript', () => {
+ const t = base([say(undefined, 'go', 'user')])
+ const out = applyTail(t, 'other', page([say(0, 'x')], null), { carryUnconfirmed: true })
+ expect(texts(out)).toEqual(['x'])
+ })
+
+ it('a NON-live reload (turn end, ↻) retires any unconfirmed carry', () => {
+ const t = base([say(0, 'q'), say(undefined, 'never matches', 'user')], 0)
+ const out = applyTail(t, ID, page([say(0, 'q'), say(100, 'transformed prompt', 'user')], 0))
+ expect(texts(out)).toEqual(['q', 'transformed prompt'])
+ })
+})
+
describe('applyOlder — the page-boundary carry', () => {
it('prepends and attaches results the newer page carried', () => {
let t = applyTail(emptyThread('A'), 'A', page([say(200, 'done')], 180, [{ id: 't9', result: 'build ok' }]))
diff --git a/src/renderer/lib/chatPaging.ts b/src/renderer/lib/chatPaging.ts
index a2fa05061..bbab4bc79 100644
--- a/src/renderer/lib/chatPaging.ts
+++ b/src/renderer/lib/chatPaging.ts
@@ -80,12 +80,25 @@ const carriedOf = (res: ChatTranscriptResult): Array<[string, string]> =>
* - Otherwise merge by key: every loaded message older than the tail window is KEPT (older pages
* the user already scrolled through survive a turn end), everything from the window on is
* replaced by the tail — so nothing duplicates, and the optimistic unkeyed "just sent" bubble
- * is dropped because the transcript now carries the real one.
+ * is dropped because the transcript now carries the real one (a LIVE read passes
+ * `carryUnconfirmed` and keeps it until the transcript does — see `unconfirmedSends`).
* - Unless no loaded message reaches into the new window: then the turn wrote more than a whole
* window, and the bytes between what is rendered and the new window were never read. Stitching
* would hide them silently, so the thread resets to the tail and pages back normally.
*/
-export function applyTail(t: ChatThread, identity: string, res: ChatTranscriptResult): ChatThread {
+export function applyTail(
+ t: ChatThread,
+ identity: string,
+ res: ChatTranscriptResult,
+ opts: { carryUnconfirmed?: boolean } = {}
+): ChatThread {
+ const next = mergeTail(t, identity, res)
+ if (!opts.carryUnconfirmed || t.identity !== identity) return next
+ const carry = unconfirmedSends(t, res)
+ return carry.length === 0 ? next : { ...next, messages: [...next.messages, ...carry] }
+}
+
+function mergeTail(t: ChatThread, identity: string, res: ChatTranscriptResult): ChatThread {
const cursor = res.olderCursor ?? null
const fresh = (): ChatThread => ({
identity,
@@ -108,6 +121,48 @@ export function applyTail(t: ChatThread, identity: string, res: ChatTranscriptRe
}
}
+const userText = (m: ChatMessage): string =>
+ m.parts
+ .map((p) => (p.kind === 'text' ? p.text : ''))
+ .join('')
+ .trim()
+
+/**
+ * The optimistic "just sent" bubbles a LIVE tail read must not drop. A live read fires on the very
+ * hook event the send caused (UserPromptSubmit), racing the agent's own transcript write — so the
+ * tail it returns often does not contain the prompt yet, and a plain merge (which keeps only keyed
+ * messages) would erase the user's own words for the rest of the turn.
+ *
+ * Carried: the thread's TRAILING unkeyed `user` messages (in a paged thread only sends are
+ * unkeyed; grok's thread is unkeyed throughout, but its whole-file read contains every prompt it
+ * rendered, so each one is matched and dropped). Each one is dropped when the new read contains a user message with
+ * the same trimmed text, ONE-FOR-ONE, and only among messages NEWER than anything the thread had
+ * keyed — an older identical "yes" already on screen must not confirm a new "yes".
+ *
+ * A non-live reload (turn end, ↻) never carries: by then the transcript holds the prompt, and a
+ * send whose transcript line never matches (a CLI that rewrites the prompt) must not stay duplicated.
+ */
+function unconfirmedSends(t: ChatThread, res: ChatTranscriptResult): ChatMessage[] {
+ const trailing: ChatMessage[] = []
+ for (let i = t.messages.length - 1; i >= 0; i--) {
+ const m = t.messages[i]
+ if (m.key !== undefined || m.role !== 'user') break
+ trailing.unshift(m)
+ }
+ if (trailing.length === 0) return []
+ let newest = -Infinity
+ for (const m of t.messages) if (m.key !== undefined && m.key > newest) newest = m.key
+ const available = res.messages
+ .filter((m) => m.role === 'user' && (m.key === undefined || m.key > newest))
+ .map(userText)
+ return trailing.filter((m) => {
+ const i = available.indexOf(userText(m))
+ if (i < 0) return true
+ available.splice(i, 1)
+ return false
+ })
+}
+
/**
* Prepend an OLDER page (a read with `before` = the thread's cursor). Held results claim their
* tools in it; its own carried results (tools older still) join the held set; at the start of the
diff --git a/src/renderer/nodes/ChatPanel.live.test.tsx b/src/renderer/nodes/ChatPanel.live.test.tsx
index 32d051827..0ab776847 100644
--- a/src/renderer/nodes/ChatPanel.live.test.tsx
+++ b/src/renderer/nodes/ChatPanel.live.test.tsx
@@ -19,6 +19,7 @@ import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS } from '../lib/chat
interface Pending {
page: ChatTranscriptPageRequest | undefined
resolve: (r: ChatTranscriptResult) => void
+ reject: (e: unknown) => void
}
const { pending, session, sendText } = vi.hoisted(() => {
@@ -30,7 +31,7 @@ const { pending, session, sendText } = vi.hoisted(() => {
_n?: string,
_g?: string,
page?: ChatTranscriptPageRequest
- ) => new Promise<ChatTranscriptResult>((resolve) => pending.push({ page, resolve }))
+ ) => new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ page, resolve, reject }))
const sendText = vi.fn(async (_id: string, _t: string) => true as const)
const session = { api: { chat: { readTranscript }, pty: { sendText } } }
return { pending, session, sendText }
@@ -187,6 +188,79 @@ describe('ChatPanel live progress', () => {
expect(pending[2].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
})
+ it('the live read the send itself triggers does not erase the prompt the transcript lacks yet', async () => {
+ await hook('done')
+ await render()
+ await settle(0, { messages: [say(0, 'hello')], olderCursor: 0 })
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 2) // the initial read is long past: the next one runs at once
+ const ta = host.querySelector('textarea') as HTMLTextAreaElement
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, 'do it')
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ expect(bubbles()).toEqual(['hello', 'do it'])
+ await hook('working', true) // UserPromptSubmit
+ expect(pending).toHaveLength(2)
+ // The agent has not written the prompt line yet.
+ await settle(1, { messages: [say(0, 'hello')], olderCursor: 0 })
+ expect(bubbles()).toEqual(['hello', 'do it'])
+ // Once it has, exactly one copy — the transcript's.
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS)
+ await settle(2, {
+ messages: [say(0, 'hello'), { role: 'user', key: 50, parts: [{ kind: 'text', text: 'do it' }] }],
+ olderCursor: 0
+ })
+ expect(bubbles()).toEqual(['hello', 'do it'])
+ expect(host.querySelectorAll('.term-chat__msg--user')).toHaveLength(1)
+ })
+
+ it('a live read leaves a failed older page\'s retry row alone', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ const el = host.querySelector('.term-chat__msgs') as HTMLDivElement
+ Object.defineProperty(el, 'scrollTop', { configurable: true, get: () => 0, set: () => {} })
+ await act(async () => {
+ el.dispatchEvent(new Event('scroll'))
+ })
+ await act(async () => pending[1].reject(new Error('host blip')))
+ expect(host.querySelector('.term-chat__older--error')).not.toBeNull()
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS)
+ expect(pending).toHaveLength(3)
+ expect(pending[2].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
+ expect(host.querySelector('.term-chat__older--error')).not.toBeNull()
+ await settle(2, { messages: [say(1000, 'tail'), say(2000, 'more')], olderCursor: 1000 })
+ expect(host.querySelector('.term-chat__older--error')).not.toBeNull()
+ expect(pending).toHaveLength(3) // no re-armed older fetch
+ })
+
+ it('a live read never flips an empty state to "Loading conversation…"', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { found: false })
+ expect(host.textContent).toContain('No transcript found')
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS)
+ expect(pending).toHaveLength(2)
+ expect(host.textContent).not.toContain('Loading conversation…')
+ expect(host.textContent).toContain('No transcript found')
+ })
+
+ it('a surface that cannot read transcripts takes no live reads', async () => {
+ await hook('working', true)
+ await render()
+ await act(async () => pending[0].reject(Object.assign(new Error('nope'), { code: 'E_UNSUPPORTED' })))
+ expect(host.textContent).toContain("Transcripts can't be read on this surface.")
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+ expect(pending).toHaveLength(1)
+ })
+
it('done clears the row and takes the final reload', async () => {
await hook('working', true)
await render()
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index d712d0d99..d864a16e6 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -114,6 +114,9 @@ export function ChatPanel({
const threadRef = useRef(thread)
threadRef.current = thread
const [loadState, setLoadState] = useState<LoadState>('loading')
+ // Mirror for `attemptLive`, which runs from timers and settles, outside any render.
+ const loadStateRef = useRef(loadState)
+ loadStateRef.current = loadState
// The older-page fetch (scroll-up paging): its own in-flight flag and token, and a failed page
// gets a retry row instead of retrying on every scroll event.
const [olderState, setOlderState] = useState<'idle' | 'loading' | 'error'>('idle')
@@ -182,18 +185,25 @@ export function ChatPanel({
const liveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const attemptLiveRef = useRef<() => void>(() => {})
- const load = useCallback(() => {
+ // `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) => {
const token = ++reqRef.current
olderReqRef.current++
olderInFlightRef.current = false
- // 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()
- setOlderState('idle')
+ if (!live) {
+ // 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()
+ setOlderState('idle')
+ }
setTailLoading(true)
tailInFlightRef.current = true
lastTailStartRef.current = Date.now()
- setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread
+ if (!live) 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
@@ -221,7 +231,7 @@ export function ChatPanel({
setLoadState('missing')
return
}
- setThread((t) => applyTail(t, identity, res))
+ setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live }))
setLoadState('ok')
},
(e: unknown) => {
@@ -305,6 +315,11 @@ export function ChatPanel({
// runs from timers and settles, long after the render that defined it.
attemptLiveRef.current = () => {
if (!livePendingRef.current) return
+ // This surface cannot read transcripts at all (relay tab): every live read would be refused.
+ if (loadStateRef.current === 'unsupported') {
+ livePendingRef.current = false
+ return
+ }
const el = msgsRef.current
const plan = planLiveReload({
working: useAgentStatus.getState().byId[nodeId]?.state === 'working',
@@ -332,7 +347,7 @@ export function ChatPanel({
return
case 'run':
livePendingRef.current = false
- load()
+ load(true)
}
}
@@ -463,7 +478,8 @@ export function ChatPanel({
setReadonly(true)
return
}
- // Optimistic: show the prompt immediately; the next load() reconciles from the transcript.
+ // Optimistic: show the prompt immediately. A live read keeps it until the transcript carries it
+ // (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.
justSentRef.current = true
setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))
setOptimistic(true)
@@ -503,7 +519,7 @@ export function ChatPanel({
<span className="term-chat__bar-end">
<button
className="term-chat__refresh"
- onClick={load}
+ onClick={() => load()}
title="Reload conversation"
aria-label="Reload conversation"
>
@@ -542,7 +558,7 @@ export function ChatPanel({
<div className="term-chat__empty-detail">{EMPTY_TEXT[loadState].detail}</div>
)}
{loadState !== 'unsupported' && loadState !== 'ok' && (
- <button className="term-chat__retry" onClick={load}>
+ <button className="term-chat__retry" onClick={() => load()}>
Retry
</button>
)}
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index c63d26f3d..d1269f4a0 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -376,6 +376,22 @@ describe('onHookEvent — a per-node pulse for EVERY hook event, same-state ones
expect(cb).toHaveBeenCalledTimes(2)
})
+ it('a throwing listener neither aborts setState nor starves the next listener', () => {
+ const id = nid()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const bad = useAgentStatus.getState().onHookEvent(id, () => {
+ throw new Error('boom')
+ })
+ const good = vi.fn()
+ const unsub = useAgentStatus.getState().onHookEvent(id, good)
+ expect(() => useAgentStatus.getState().setState(id, 'working', 'claude', true)).not.toThrow()
+ expect(good).toHaveBeenCalledOnce()
+ expect(useAgentStatus.getState().byId[id]?.state).toBe('working')
+ bad()
+ unsub()
+ warn.mockRestore()
+ })
+
it('sees the store already updated when it fires', () => {
const id = nid()
let seen: string | undefined
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index 6e834e8a8..91c0d7846 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -506,7 +506,16 @@ export function createAgentStatusSession(
const hookEventSubs = new Map<string, Set<() => void>>()
const pulse = (id: string): void => {
const subs = hookEventSubs.get(id)
- if (subs) for (const cb of [...subs]) cb()
+ if (!subs) return
+ for (const cb of [...subs]) {
+ // Runs inside Canvas's hook-event handler, after the store write: one throwing listener must
+ // neither abort that handler nor starve the listeners after it.
+ try {
+ cb()
+ } catch (e) {
+ console.warn('[agentStatus] onHookEvent listener threw', e)
+ }
+ }
}
const store = create<AgentStatusStore>((set) => ({