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): show a finished reply without reopening the view

Paul Robertson6e0b69057a51
diff --git a/src/renderer/lib/chatLive.test.ts b/src/renderer/lib/chatLive.test.ts
index d0e8bc880..33e228b18 100644
--- a/src/renderer/lib/chatLive.test.ts
+++ b/src/renderer/lib/chatLive.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest'
-import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from './chatLive'
+import {
+ CHAT_LIVE_RELOAD_MIN_MS,
+ CHAT_OPTIMISTIC_WORKING_MS,
+ chatActivity,
+ planLiveReload,
+ turnEndReloadCarries
+} from './chatLive'
describe('chatActivity — the status row at the end of the ⌘M thread', () => {
it('a working agent shows the working row', () => {
@@ -52,3 +58,18 @@ describe('planLiveReload — throttled, single-flight, visible-only tail refresh
expect(CHAT_OPTIMISTIC_WORKING_MS).toBeLessThanOrEqual(30_000)
})
})
+
+describe('turnEndReloadCarries — which turn-end reloads keep unconfirmed sends', () => {
+ it('every reload but the last carries: a prompt sent as the turn ended may not be written yet', () => {
+ expect(turnEndReloadCarries({ final: false, working: false })).toBe(true)
+ expect(turnEndReloadCarries({ final: false, working: true })).toBe(true)
+ })
+
+ it('the last reconciles outright while idle — a send that never landed must not linger', () => {
+ expect(turnEndReloadCarries({ final: true, working: false })).toBe(false)
+ })
+
+ it('…but keeps carrying if the agent is working again (that send is the turn now running)', () => {
+ expect(turnEndReloadCarries({ final: true, working: true })).toBe(true)
+ })
+})
diff --git a/src/renderer/lib/chatLive.ts b/src/renderer/lib/chatLive.ts
index 39c9aec06..59e243477 100644
--- a/src/renderer/lib/chatLive.ts
+++ b/src/renderer/lib/chatLive.ts
@@ -22,6 +22,27 @@ export const CHAT_LIVE_RELOAD_MIN_MS = 1500
*/
export const CHAT_OPTIMISTIC_WORKING_MS = 15_000
+/**
+ * Extra tail reloads after a turn ends, in ms from the working -> idle edge. Claude Code fires its
+ * Stop hook (our `done`) BEFORE it appends the turn's final reply to the transcript — measured ~50 ms
+ * apart — so the one reload at `done` reads the file too early, the live refresh has already
+ * stopped (`planLiveReload` skips once the agent is idle), and the reply only appeared after
+ * reopening the view. A fixed schedule rather than "retry until the last message is the
+ * assistant's": a turn that ends on a tool call already has an assistant message last while its
+ * final text is still unwritten.
+ */
+export const TURN_END_RELOAD_DELAYS_MS: readonly number[] = [500, 2000]
+
+/**
+ * Does a turn-end reload keep the unconfirmed sends on screen (`applyTail`'s `carryUnconfirmed`)?
+ * Every reload but the LAST in the schedule does: a prompt sent right as the turn ended may not be
+ * in the transcript yet. The last one reconciles outright — a send that never landed must not
+ * linger — unless the agent is working again, i.e. that prompt is the turn now running.
+ */
+export function turnEndReloadCarries(s: { final: boolean; working: boolean }): boolean {
+ return !s.final || s.working
+}
+
/** What the row at the end of the thread says; `null` = no row. */
export type ChatActivity = 'working' | 'dialog' | null
diff --git a/src/renderer/nodes/ChatPanel.live.test.tsx b/src/renderer/nodes/ChatPanel.live.test.tsx
index 90067c222..1a8550f6e 100644
--- a/src/renderer/nodes/ChatPanel.live.test.tsx
+++ b/src/renderer/nodes/ChatPanel.live.test.tsx
@@ -6,7 +6,7 @@ import type { ChatMessage, ChatTranscriptResult } from '@shared/types'
import type { ChatTranscriptPageRequest } from '@shared/chat-page'
import { useAgentStatus } from '../state/agentStatus'
import { CHAT_TAIL_PAGE_BYTES } from '../lib/chatPaging'
-import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS } from '../lib/chatLive'
+import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, TURN_END_RELOAD_DELAYS_MS } from '../lib/chatLive'
/**
* The ⌘M panel's live progress glue (the decisions are unit-tested in `lib/chatLive.test.ts`): a
@@ -261,7 +261,7 @@ describe('ChatPanel live progress', () => {
expect(pending).toHaveLength(1)
})
- it('done clears the row and takes the final reload', async () => {
+ it('done clears the row, takes a read at once and the settle reloads — then stops', async () => {
await hook('working', true)
await render()
await settle(0, { messages: [say(0, 'q')] })
@@ -271,7 +271,79 @@ describe('ChatPanel live progress', () => {
expect(pending).toHaveLength(2)
await settle(1, { messages: [say(0, 'q'), say(100, 'answer')] })
expect(bubbles()).toEqual(['q', 'answer'])
+
+ await advance(TURN_END_RELOAD_DELAYS_MS[TURN_END_RELOAD_DELAYS_MS.length - 1])
+ expect(pending).toHaveLength(2 + TURN_END_RELOAD_DELAYS_MS.length)
await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+
+ expect(pending).toHaveLength(2 + TURN_END_RELOAD_DELAYS_MS.length)
+ })
+
+ it('shows a reply written AFTER the Stop hook without reopening the view', async () => {
+ // Claude Code fires Stop ~50 ms before it appends the final reply, so the read at `done` misses
+ // it; the first settle reload is what finds it.
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('done')
+ await settle(1, { messages: [say(0, 'q')] })
+ expect(bubbles()).toEqual(['q'])
+
+ await advance(TURN_END_RELOAD_DELAYS_MS[0])
+ await settle(2, { messages: [say(0, 'q'), say(100, 'the reply')] })
+
+ expect(bubbles()).toEqual(['q', 'the reply'])
+ })
+
+ it('a new turn does not cancel the settle reloads of the one that just ended', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('done')
+ await settle(1, { messages: [say(0, 'q')] })
+ // The next prompt starts a turn right away.
+ await hook('working', true)
+
+ await advance(TURN_END_RELOAD_DELAYS_MS[0])
+ await settle(pending.length - 1, { messages: [say(0, 'q'), say(100, 'first reply')] })
+
+ expect(bubbles()).toContain('first reply')
+ })
+
+ it('a prompt sent as the turn ends is kept until the last settle read, which drops it if it never landed', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('done')
+ await settle(1, { messages: [say(0, 'q'), say(100, 'a')] })
+ const ta = host.querySelector('textarea') as HTMLTextAreaElement
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, 'never landed')
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ await advance(TURN_END_RELOAD_DELAYS_MS[0])
+ await settle(pending.length - 1, { messages: [say(0, 'q'), say(100, 'a')] })
+ expect(bubbles()).toContain('never landed')
+
+ await advance(TURN_END_RELOAD_DELAYS_MS[TURN_END_RELOAD_DELAYS_MS.length - 1])
+ await settle(pending.length - 1, { messages: [say(0, 'q'), say(100, 'a')] })
+
+ expect(bubbles()).not.toContain('never landed')
+ })
+
+ it('unmounting cancels the settle reloads', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('done')
+ await act(async () => root.unmount())
+ root = createRoot(host)
+
+ await advance(TURN_END_RELOAD_DELAYS_MS[TURN_END_RELOAD_DELAYS_MS.length - 1])
+
expect(pending).toHaveLength(2)
})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index cbe4247f0..7efcb231e 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -22,7 +22,14 @@ import {
import { E_UNSUPPORTED } from '@shared/rpc'
import { GROK_AMBIGUOUS_SESSION_MESSAGE, isGrokAmbiguousSessionError } from '@shared/chat-page'
import { Spinner } from '../components/Spinner'
-import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'
+import {
+ CHAT_LIVE_RELOAD_MIN_MS,
+ CHAT_OPTIMISTIC_WORKING_MS,
+ TURN_END_RELOAD_DELAYS_MS,
+ chatActivity,
+ planLiveReload,
+ turnEndReloadCarries
+} from '../lib/chatLive'
import { sentCommand } from '@shared/chat-command'
import { isInteractiveBuiltin } from '@shared/chat-catalog'
import { capabilityAgentId, chatReadsLocalOnly } from '@shared/agents/config'
@@ -307,7 +314,9 @@ export function ChatPanel({
// The ONE tail read a sent local command schedules (see `send`): `/model` or `!ls` fires no hook,
// so neither a state change nor a live read would ever confirm it.
const commandReadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const loadRef = useRef<(live?: boolean, rebind?: boolean) => void>(() => {})
+ const loadRef = useRef<(live?: boolean, rebind?: boolean, carry?: boolean) => void>(() => {})
+ // The turn-end settle reloads (TURN_END_RELOAD_DELAYS_MS) still to fire; cleared on unmount.
+ const settleTimersRef = useRef<ReturnType<typeof setTimeout>[]>([])
const requestHeldReloadRef = useRef<() => void>(() => {})
// `live` = a read driven by a hook event while the agent works (see `attemptLive`), as opposed to
@@ -319,7 +328,10 @@ export function ChatPanel({
// `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) => {
+ //
+ // `carry` = keep unconfirmed sends (`carryUnconfirmed`). Every live and rebind read does; so do the
+ // turn-end settle reloads but the last (`turnEndReloadCarries`).
+ const load = useCallback((live = false, rebind = false, carry = live || rebind) => {
const token = ++reqRef.current
if (!rebind) olderReqRef.current++
// The held request this read starts under: once it is applied, the thread is known to show the
@@ -393,7 +405,7 @@ export function ChatPanel({
// command it is the ONLY signal (no hook fires). A command that starts a real turn is
// still covered — its `working` state keeps the row (and the send refusal) on its own.
if (tailConfirmsSends(threadRef.current, identity, res)) setOptimistic(false)
- setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live || rebind }))
+ setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: carry }))
setLoadState('ok')
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
@@ -516,6 +528,8 @@ export function ChatPanel({
attemptLiveRef.current = () => {}
if (liveTimerRef.current !== null) clearTimeout(liveTimerRef.current)
liveTimerRef.current = null
+ for (const t of settleTimersRef.current) clearTimeout(t)
+ settleTimersRef.current = []
},
[]
)
@@ -580,12 +594,26 @@ export function ChatPanel({
return () => document.removeEventListener('visibilitychange', onVisibility)
}, [])
- // Reload when a turn completes (working -> not working). Sessions whose hooks never report
- // `working` never take this path — the bar's ↻ is their reload.
+ // Reload when a turn completes (working -> not working), then again on the settle schedule
+ // (TURN_END_RELOAD_DELAYS_MS): the Stop hook lands before the final reply is written, so the read
+ // at the edge usually misses it. A new turn does NOT cancel the schedule: a prompt sent the moment
+ // the turn ended starts one at once, and cancelling there would hide the finished turn's reply
+ // until the next one ended. Sessions whose hooks never report `working` never take this path —
+ // the bar's ↻ is their reload.
useEffect(() => {
- if (prevState.current === 'working' && state !== 'working') load()
+ if (prevState.current === 'working' && state !== 'working') {
+ load(false, false, true)
+ for (const t of settleTimersRef.current) clearTimeout(t)
+ const last = TURN_END_RELOAD_DELAYS_MS.length - 1
+ settleTimersRef.current = TURN_END_RELOAD_DELAYS_MS.map((ms, i) =>
+ setTimeout(() => {
+ const working = useAgentStatus.getState().byId[nodeId]?.state === 'working'
+ loadRef.current(false, false, turnEndReloadCarries({ final: i === last, working }))
+ }, ms)
+ )
+ }
prevState.current = state
- }, [state, load])
+ }, [state, load, nodeId])
// Any state change retires the optimistic working row: from here the real state speaks.
useEffect(() => {