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.

feat(chat): working indicator + live tail refresh in the ⌘M panel

review650e771fda75
diff --git a/CLAUDE.md b/CLAUDE.md
index f5caf83ef..c59224eda 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2494,6 +2494,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
store at send time, not only at render. Same trap as the in-place restart's `/exit`. The bar's ↻
reloads on demand (beside the empty state's Retry), since a session whose hooks never report
`working` never takes the turn-finish reload.
+ **Live progress (2026-09).** While the agent works, a `role=status` row closes the thread (the ONE
+ spinner + the placeholder's own "<agent> is working…"/"waiting for an answer" sentence; optimistic
+ right after a send, bounded by `CHAT_OPTIMISTIC_WORKING_MS`), and every hook event re-reads the
+ 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.
**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/chatLive.test.ts b/src/renderer/lib/chatLive.test.ts
new file mode 100644
index 000000000..d0e8bc880
--- /dev/null
+++ b/src/renderer/lib/chatLive.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest'
+import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from './chatLive'
+
+describe('chatActivity — the status row at the end of the ⌘M thread', () => {
+ it('a working agent shows the working row', () => {
+ expect(chatActivity({ refusal: 'working', optimistic: false, readOnly: false })).toBe('working')
+ })
+ it('a dialog state shows the waiting-for-an-answer row, never the spinner', () => {
+ expect(chatActivity({ refusal: 'dialog', optimistic: false, readOnly: false })).toBe('dialog')
+ expect(chatActivity({ refusal: 'dialog', optimistic: true, readOnly: false })).toBe('dialog')
+ })
+ it('right after a send (no working event yet) the row is optimistic', () => {
+ expect(chatActivity({ refusal: null, optimistic: true, readOnly: false })).toBe('working')
+ expect(chatActivity({ refusal: null, optimistic: false, readOnly: false })).toBeNull()
+ })
+ it('a pane the CLI has left shows no row, optimistic or not', () => {
+ for (const r of ['asleep', 'paused', 'dropped', 'exited'] as const) {
+ expect(chatActivity({ refusal: r, optimistic: true, readOnly: false })).toBeNull()
+ }
+ })
+ it('a read-only transcript (closed node) never shows a row', () => {
+ expect(chatActivity({ refusal: 'working', optimistic: true, readOnly: true })).toBeNull()
+ })
+})
+
+describe('planLiveReload — throttled, single-flight, visible-only tail refresh', () => {
+ const base = { working: true, visible: true, inFlight: false, now: 10_000, lastStartAt: null as number | null }
+ it('runs at once when nothing ran recently', () => {
+ expect(planLiveReload(base)).toEqual({ kind: 'run' })
+ expect(planLiveReload({ ...base, lastStartAt: 10_000 - CHAT_LIVE_RELOAD_MIN_MS })).toEqual({ kind: 'run' })
+ })
+ it('waits out the rest of the interval (the trailing call), never drops it', () => {
+ expect(planLiveReload({ ...base, lastStartAt: 10_000 - 500 })).toEqual({
+ kind: 'wait',
+ ms: CHAT_LIVE_RELOAD_MIN_MS - 500
+ })
+ })
+ it('holds while a tail read is in flight — never overlaps one', () => {
+ expect(planLiveReload({ ...base, inFlight: true })).toEqual({ kind: 'hold' })
+ })
+ it('holds while the panel or the document is hidden', () => {
+ expect(planLiveReload({ ...base, visible: false })).toEqual({ kind: 'hold' })
+ })
+ it('skips once the agent is no longer working (the turn-end reload owns that)', () => {
+ expect(planLiveReload({ ...base, working: false })).toEqual({ kind: 'skip' })
+ expect(planLiveReload({ ...base, working: false, visible: false, inFlight: true })).toEqual({ kind: 'skip' })
+ })
+ it('keeps the interval in the 1.5–2 s band and the optimistic window bounded', () => {
+ expect(CHAT_LIVE_RELOAD_MIN_MS).toBeGreaterThanOrEqual(1500)
+ expect(CHAT_LIVE_RELOAD_MIN_MS).toBeLessThanOrEqual(2000)
+ expect(CHAT_OPTIMISTIC_WORKING_MS).toBeGreaterThan(0)
+ expect(CHAT_OPTIMISTIC_WORKING_MS).toBeLessThanOrEqual(30_000)
+ })
+})
diff --git a/src/renderer/lib/chatLive.ts b/src/renderer/lib/chatLive.ts
new file mode 100644
index 000000000..39c9aec06
--- /dev/null
+++ b/src/renderer/lib/chatLive.ts
@@ -0,0 +1,73 @@
+import type { ChatSendRefusal } from './chatSendGate'
+
+/**
+ * Pure decisions behind the ⌘M panel's live progress (`nodes/ChatPanel.tsx`): the status row at the
+ * end of the thread while the agent works, and the throttled tail refresh that makes the answer
+ * appear as it is written instead of only when the turn ends.
+ */
+
+/**
+ * Minimum gap between two tail reads started by hook events. An SSH project reads its transcript
+ * over ssh (a ranged `dd` per read), and a busy turn fires a hook event per tool call — so the
+ * refresh is throttled, with a TRAILING read guaranteed (see `planLiveReload`), so the last event
+ * of a burst is never lost.
+ */
+export const CHAT_LIVE_RELOAD_MIN_MS = 1500
+
+/**
+ * How long the working row shows after a send with no `working` hook event behind it. Normally
+ * UserPromptSubmit flips the state within a second and the real state takes over; this bounds the
+ * row for an agent whose hooks never report (a custom agent, a session with hooks unwired), so a
+ * spinner can never spin forever over a turn nobody is tracking.
+ */
+export const CHAT_OPTIMISTIC_WORKING_MS = 15_000
+
+/** What the row at the end of the thread says; `null` = no row. */
+export type ChatActivity = 'working' | 'dialog' | null
+
+/**
+ * Derived from the composer's send refusal (`lib/chatSendGate.ts`), not from the raw state, so the
+ * row and the placeholder can never disagree — and a pane the CLI has left (asleep / paused /
+ * dropped / exited) shows no spinner even while a stale `working` or an optimistic send says so.
+ * `optimistic` = the user just sent and no state change has happened since (the glue retires it on
+ * the next state change or after `CHAT_OPTIMISTIC_WORKING_MS`). A read-only transcript (a closed
+ * node) has no live session to report on.
+ */
+export function chatActivity(s: { refusal: ChatSendRefusal; optimistic: boolean; readOnly: boolean }): ChatActivity {
+ if (s.readOnly) return null
+ if (s.refusal === 'working') return 'working'
+ if (s.refusal === 'dialog') return 'dialog'
+ if (s.refusal === null && s.optimistic) return 'working'
+ return null
+}
+
+export type LiveReloadPlan = { kind: 'run' } | { kind: 'wait'; ms: number } | { kind: 'hold' } | { kind: 'skip' }
+
+/**
+ * A hook event arrived for this node (or a deferred one is being retried): what now?
+ * - `skip` — the agent is no longer working. The working→idle reload already reads the final tail;
+ * a pending event is dropped.
+ * - `hold` — keep the event pending and do nothing: a tail read is in flight (never overlap one —
+ * its settle retries), or the panel has no layout box / the document is hidden (the same gate as
+ * paging; reveal and visibilitychange retry). A hidden panel costs no ssh round trips.
+ * - `wait` — a read started less than `minMs` ago: retry after the rest of the interval (the
+ * trailing call).
+ * - `run` — read the tail now.
+ */
+export function planLiveReload(s: {
+ working: boolean
+ visible: boolean
+ inFlight: boolean
+ now: number
+ lastStartAt: number | null
+ minMs?: number
+}): LiveReloadPlan {
+ const minMs = s.minMs ?? CHAT_LIVE_RELOAD_MIN_MS
+ if (!s.working) return { kind: 'skip' }
+ if (s.inFlight || !s.visible) return { kind: 'hold' }
+ if (s.lastStartAt !== null) {
+ const since = s.now - s.lastStartAt
+ if (since < minMs) return { kind: 'wait', ms: minMs - since }
+ }
+ return { kind: 'run' }
+}
diff --git a/src/renderer/nodes/ChatPanel.live.test.tsx b/src/renderer/nodes/ChatPanel.live.test.tsx
new file mode 100644
index 000000000..32d051827
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.live.test.tsx
@@ -0,0 +1,262 @@
+// @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 { 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'
+
+/**
+ * The ⌘M panel's live progress glue (the decisions are unit-tested in `lib/chatLive.test.ts`): a
+ * working row at the end of the thread (optimistic right after a send), and a throttled,
+ * single-flight tail refresh on every hook event while the agent works — never for a hidden panel.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+interface Pending {
+ page: ChatTranscriptPageRequest | undefined
+ resolve: (r: ChatTranscriptResult) => void
+}
+
+const { pending, session, sendText } = vi.hoisted(() => {
+ const pending: Pending[] = []
+ const readTranscript = (
+ _s: string | undefined,
+ _c: string | undefined,
+ _a?: string,
+ _n?: string,
+ _g?: string,
+ page?: ChatTranscriptPageRequest
+ ) => new Promise<ChatTranscriptResult>((resolve) => pending.push({ page, resolve }))
+ const sendText = vi.fn(async (_id: string, _t: string) => true as const)
+ const session = { api: { chat: { readTranscript }, pty: { sendText } } }
+ return { pending, session, sendText }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-live'
+let host: HTMLDivElement
+let root: Root
+const geo = { clientHeight: 400 }
+
+const say = (key: number, t: string): ChatMessage => ({ role: 'assistant', key, parts: [{ kind: 'text', text: t }] })
+const bubbles = (): string[] => [...host.querySelectorAll('.term-chat__msg')].map((e) => e.textContent?.trim() ?? '')
+const activity = (): HTMLElement | null => host.querySelector('.term-chat__activity')
+
+async function render(): Promise<void> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)
+ })
+ const el = host.querySelector('.term-chat__msgs') as HTMLDivElement
+ Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => geo.clientHeight })
+ Object.defineProperty(el, 'scrollHeight', { configurable: true, get: () => 10_000 })
+}
+async function settle(i: number, r: Partial<ChatTranscriptResult>): Promise<void> {
+ await act(async () => {
+ pending[i].resolve({ messages: [], found: true, olderCursor: null, unmatchedResults: [], ...r })
+ })
+}
+async function hook(state: 'working' | 'waiting' | 'blocked' | 'done' | undefined, newTurn = false): Promise<void> {
+ await act(async () => {
+ useAgentStatus.getState().setState(NODE, state, 'claude', newTurn)
+ })
+}
+async function advance(ms: number): Promise<void> {
+ await act(async () => {
+ vi.advanceTimersByTime(ms)
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ pending.length = 0
+ sendText.mockClear()
+ geo.clientHeight = 400
+ 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()
+})
+
+describe('ChatPanel live progress', () => {
+ it('a send shows the working row at once, before any hook event — and the working state keeps it', async () => {
+ await hook('done')
+ await render()
+ await settle(0, { messages: [say(0, 'hello')] })
+ expect(activity()).toBeNull()
+ 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(sendText).toHaveBeenCalledOnce()
+ const row = activity()!
+ expect(row.textContent).toBe('Claude Code is working…')
+ expect(row.getAttribute('role')).toBe('status')
+ expect(row.getAttribute('aria-live')).toBe('polite')
+ expect(row.querySelector('.nt-spinner')).not.toBeNull()
+ // The row sits at the END of the thread, after the optimistic prompt bubble.
+ expect(host.querySelector('.term-chat__msgs')!.lastElementChild).toBe(row)
+ await hook('working', true)
+ expect(activity()?.textContent).toBe('Claude Code is working…')
+ })
+
+ it('an optimistic row with no working event behind it clears after a bounded timeout', async () => {
+ await hook('done')
+ await render()
+ await settle(0, { messages: [say(0, 'hello')] })
+ const ta = host.querySelector('textarea') as HTMLTextAreaElement
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, 'x')
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ expect(activity()).not.toBeNull()
+ await advance(CHAT_OPTIMISTIC_WORKING_MS)
+ expect(activity()).toBeNull()
+ })
+
+ it('hook events while working drive throttled, single-flight tail reloads that append', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')], olderCursor: null })
+ expect(activity()?.querySelector('.nt-spinner')).not.toBeNull()
+
+ // First event: nothing ran for a while? The initial read just started — so it waits the rest.
+ await hook('working')
+ expect(pending).toHaveLength(1)
+ await advance(CHAT_LIVE_RELOAD_MIN_MS)
+ expect(pending).toHaveLength(2)
+ expect(pending[1].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
+
+ // A burst while that read is in flight: held, never overlapped…
+ await hook('working')
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+ expect(pending).toHaveLength(2)
+ await settle(1, { messages: [say(0, 'q'), say(100, 'part 1')], olderCursor: null })
+ expect(bubbles()).toEqual(['q', 'part 1'])
+ // …and served by ONE trailing read once it settles (the interval had already elapsed).
+ expect(pending).toHaveLength(3)
+ await settle(2, { messages: [say(0, 'q'), say(100, 'part 1'), say(200, 'part 2')], olderCursor: null })
+ expect(bubbles()).toEqual(['q', 'part 1', 'part 2'])
+ // The row stays at the end, under the new message.
+ expect(host.querySelector('.term-chat__msgs')!.lastElementChild).toBe(activity())
+ // Nothing pending: no further reads.
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+ expect(pending).toHaveLength(3)
+ })
+
+ it('a live reload never cancels an older page the user is scrolling back to — it waits for it', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ // Scroll to the top: an older page is requested.
+ 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'))
+ })
+ expect(pending).toHaveLength(2)
+ expect(pending[1].page).toMatchObject({ before: 1000 })
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+ expect(pending).toHaveLength(2) // held behind the older page
+ await settle(1, { messages: [say(0, 'older')], olderCursor: null })
+ expect(bubbles()).toEqual(['older', 'tail'])
+ expect(pending).toHaveLength(3) // …then served once it landed
+ expect(pending[2].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
+ })
+
+ it('done clears the row and takes the final reload', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ expect(activity()).not.toBeNull()
+ await hook('done')
+ expect(activity()).toBeNull()
+ expect(pending).toHaveLength(2)
+ await settle(1, { messages: [say(0, 'q'), say(100, 'answer')] })
+ expect(bubbles()).toEqual(['q', 'answer'])
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 3)
+ expect(pending).toHaveLength(2)
+ })
+
+ it('a dialog state says the agent is waiting for an answer, with no spinner', async () => {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('waiting')
+ const row = activity()!
+ expect(row.textContent).toContain('Claude Code is waiting for an answer in the terminal')
+ expect(row.querySelector('.nt-spinner')).toBeNull()
+ // It is the composer placeholder's own sentence, not a second copy.
+ expect(row.textContent).toBe(host.querySelector('textarea')!.getAttribute('placeholder'))
+ })
+
+ it('a HIDDEN panel takes no live reloads — and catches up once when it gets a box', async () => {
+ const observers: Array<() => void> = []
+ ;(globalThis as { ResizeObserver?: unknown }).ResizeObserver = class {
+ constructor(private cb: () => void) {}
+ observe(): void {
+ observers.push(this.cb)
+ }
+ disconnect(): void {}
+ }
+ try {
+ geo.clientHeight = 0
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('working')
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 5)
+ expect(pending).toHaveLength(1)
+ geo.clientHeight = 400
+ await act(async () => {
+ for (const cb of observers) cb()
+ })
+ expect(pending).toHaveLength(2)
+ } finally {
+ delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver
+ }
+ })
+
+ it('a hidden DOCUMENT takes no live reloads', async () => {
+ const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+ try {
+ await hook('working', true)
+ await render()
+ await settle(0, { messages: [say(0, 'q')] })
+ await hook('working')
+ await advance(CHAT_LIVE_RELOAD_MIN_MS * 5)
+ expect(pending).toHaveLength(1)
+ hidden.mockReturnValue(false)
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ })
+ expect(pending).toHaveLength(2)
+ } finally {
+ hidden.mockRestore()
+ }
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index a4838afe3..d712d0d99 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -19,6 +19,7 @@ import {
} from '../lib/chatPaging'
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'
// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each
@@ -86,8 +87,9 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
/**
* Chat view for a chat-capable agent node (Cmd+M). Renders the session transcript as
* markdown bubbles with collapsible tool calls, and sends new prompts into the running tmux
- * session via pty.sendText. Phase 1 reloads the transcript whenever a turn finishes
- * (working -> idle); live streaming is a later phase. Replaces the markdown-of-output overlay.
+ * session via pty.sendText. While a turn runs, a status row closes the thread and the tail is
+ * re-read (throttled) on every hook event, so the answer grows as it is written; the turn's end
+ * (working -> idle) takes one final reload. Replaces the markdown-of-output overlay.
*/
export function ChatPanel({
nodeId,
@@ -124,6 +126,7 @@ export function ChatPanel({
olderStateRef.current = olderState
const [input, setInput] = useState('')
const [readonly, setReadonly] = useState(false)
+ const [optimistic, setOptimistic] = useState(false)
const state = useAgentStatus((s) => s.byId[nodeId]?.state)
// The shell-owned-pane flags, each as its own primitive selector (an object selector would
// re-render on every hook event for every node). See lib/chatSendGate.ts for why they gate.
@@ -132,6 +135,14 @@ export function ChatPanel({
const dropped = useAgentStatus((s) => s.byId[nodeId]?.dropped)
const sessionEnded = useAgentStatus((s) => s.byId[nodeId]?.sessionEnded)
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.
+ const refusal = chatSendRefusal(agentId, { state, hibernated, paused, dropped, sessionEnded })
+ const agentLabel = chatAgentLabel(agentId, customAgents)
+ // What the row closing the thread says (lib/chatLive.ts). `optimistic` covers the gap between a
+ // 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 })
const msgsRef = useRef<HTMLDivElement>(null)
const prevState = useRef(state)
// Request token: only the NEWEST readTranscript may land. An older read resolving late (the
@@ -157,6 +168,19 @@ export function ChatPanel({
const el = msgsRef.current
if (el && el.clientHeight > 0) anchorRef.current = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight }
}
+ // Live refresh bookkeeping (lib/chatLive.ts `planLiveReload`). Refs, not state: none of it is
+ // rendered, and a hook event must not re-render the panel just to note that it arrived.
+ // - a TAIL read is in flight (any: initial, ↻, turn-end or live) — live reads never overlap one
+ // (nor an older-page fetch, `olderInFlightRef`);
+ // - when the last tail read started — the throttle's clock;
+ // - a hook event not yet served by a read — the trailing call, retried on settle / timer /
+ // reveal / visibilitychange;
+ // - the trailing timer.
+ const tailInFlightRef = useRef(false)
+ const lastTailStartRef = useRef<number | null>(null)
+ const livePendingRef = useRef(false)
+ const liveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const attemptLiveRef = useRef<() => void>(() => {})
const load = useCallback(() => {
const token = ++reqRef.current
@@ -167,6 +191,8 @@ export function ChatPanel({
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
// `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
@@ -178,6 +204,9 @@ export function ChatPanel({
(res) => {
if (token !== reqRef.current) return
setTailLoading(false)
+ tailInFlightRef.current = false
+ // A hook event held while this read was in flight gets its (trailing) read now.
+ queueMicrotask(() => attemptLiveRef.current())
if (!res.found) {
// `missing` only when there is nothing of THIS transcript on screen. A reload that
// failed to resolve (an SSH master blip) must not blank a thread the user is reading.
@@ -198,6 +227,8 @@ export function ChatPanel({
(e: unknown) => {
if (token !== reqRef.current) return
setTailLoading(false)
+ tailInFlightRef.current = false
+ queueMicrotask(() => attemptLiveRef.current())
// Same rule as a failed resolution: a rendered thread of this transcript stays usable.
const t = threadRef.current
if (t.identity === identity && t.messages.length > 0) {
@@ -224,6 +255,8 @@ export function ChatPanel({
setOlderState('loading')
const settle = () => {
olderInFlightRef.current = false
+ // A hook event held behind this page gets its (trailing) tail read now.
+ queueMicrotask(() => attemptLiveRef.current())
}
void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {
before,
@@ -259,10 +292,69 @@ export function ChatPanel({
() => () => {
reqRef.current++
olderReqRef.current++
+ livePendingRef.current = false
+ attemptLiveRef.current = () => {}
+ if (liveTimerRef.current !== null) clearTimeout(liveTimerRef.current)
+ liveTimerRef.current = null
},
[]
)
+ // Serve a pending hook event if the plan allows it now; otherwise leave it pending for whichever
+ // retry the plan waits on. Everything is read at call time (store, geometry, visibility): it
+ // runs from timers and settles, long after the render that defined it.
+ attemptLiveRef.current = () => {
+ if (!livePendingRef.current) return
+ const el = msgsRef.current
+ const plan = planLiveReload({
+ working: useAgentStatus.getState().byId[nodeId]?.state === 'working',
+ // No layout box (collapsed node, display:none) = the paging gate; a hidden document too.
+ visible: !!el && el.clientHeight > 0 && !document.hidden,
+ // An older page in flight counts too: `load` cancels it, and a live read every interval
+ // would keep restarting the user's scroll-up paging for the whole turn.
+ inFlight: tailInFlightRef.current || olderInFlightRef.current,
+ now: Date.now(),
+ lastStartAt: lastTailStartRef.current
+ })
+ switch (plan.kind) {
+ case 'skip':
+ livePendingRef.current = false
+ return
+ case 'hold':
+ return
+ case 'wait':
+ if (liveTimerRef.current === null) {
+ liveTimerRef.current = setTimeout(() => {
+ liveTimerRef.current = null
+ attemptLiveRef.current()
+ }, plan.ms)
+ }
+ return
+ case 'run':
+ livePendingRef.current = false
+ load()
+ }
+ }
+
+ // Every hook event for this node — same-state ones included, which no zustand selector sees (the
+ // store refreshes `stateAt` in place without notifying; see `onHookEvent`). While the agent is
+ // working each one may have written to the transcript, so each asks for a tail refresh.
+ useEffect(
+ () =>
+ useAgentStatus.getState().onHookEvent(nodeId, () => {
+ livePendingRef.current = true
+ attemptLiveRef.current()
+ }),
+ [nodeId]
+ )
+
+ // A tab that comes back into view serves what was held while it was hidden.
+ useEffect(() => {
+ const onVisibility = () => attemptLiveRef.current()
+ document.addEventListener('visibilitychange', onVisibility)
+ 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.
useEffect(() => {
@@ -270,6 +362,16 @@ export function ChatPanel({
prevState.current = state
}, [state, load])
+ // Any state change retires the optimistic working row: from here the real state speaks.
+ useEffect(() => {
+ setOptimistic(false)
+ }, [state])
+ useEffect(() => {
+ if (!optimistic) return
+ const t = setTimeout(() => setOptimistic(false), CHAT_OPTIMISTIC_WORKING_MS)
+ return () => clearTimeout(t)
+ }, [optimistic])
+
// Follow the newest message only when the user was already at the bottom or just sent; a user
// scrolled up reading an earlier answer keeps their place. Layout effect: the jump lands before
// paint, so a followed thread never flashes one frame short.
@@ -291,7 +393,8 @@ export function ChatPanel({
nearBottomRef.current = true
}
justSentRef.current = false
- }, [messages, olderState])
+ // `activity`: the status row appearing at the end grows the thread like a message does.
+ }, [messages, olderState, activity])
const maybeLoadOlder = useCallback(() => {
const el = msgsRef.current
@@ -333,6 +436,7 @@ export function ChatPanel({
if (hasBox && !hadBox && nearBottomRef.current) el.scrollTop = el.scrollHeight
hadBox = hasBox
maybeLoadOlderRef.current()
+ attemptLiveRef.current() // a hook event held while the panel was hidden
})
ro.observe(el)
return () => ro.disconnect()
@@ -344,11 +448,6 @@ export function ChatPanel({
maybeLoadOlder()
}
- // 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.
- const refusal = chatSendRefusal(agentId, { state, hibernated, paused, dropped, sessionEnded })
- const agentLabel = chatAgentLabel(agentId, customAgents)
-
const send = useCallback(async () => {
const text = input.trim()
// Read the store at SEND time, not the render-time values: a PermissionRequest (or an Eco
@@ -367,6 +466,7 @@ export function ChatPanel({
// Optimistic: show the prompt immediately; the next load() reconciles from the transcript.
justSentRef.current = true
setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))
+ setOptimistic(true)
setInput('')
}, [api, input, nodeId, agentId])
@@ -482,6 +582,15 @@ export function ChatPanel({
)}
</div>
))}
+ {activity && (
+ // One live region for both sentences, so working → waiting changes its text instead of
+ // remounting it (a remounted role=status is announced again). The words are the
+ // 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 })}
+ </div>
+ )}
</div>
{!readOnly && (
<div className="term-chat__compose">
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index 08f9ae0f0..c63d26f3d 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -350,3 +350,40 @@ describe('the verified evidence for a transition', () => {
}
})
})
+
+describe('onHookEvent — a per-node pulse for EVERY hook event, same-state ones included', () => {
+ it('a same-state event notifies no zustand subscriber (the in-place fast path) — which is why the pulse exists', () => {
+ const id = nid()
+ useAgentStatus.getState().setState(id, 'working', 'claude', true)
+ const sub = vi.fn()
+ const unsub = useAgentStatus.subscribe(sub)
+ useAgentStatus.getState().setState(id, 'working', 'claude')
+ expect(sub).not.toHaveBeenCalled()
+ unsub()
+ })
+
+ it('fires for transitions and same-state events of that node only, and unsubscribes', () => {
+ const id = nid()
+ const other = nid()
+ const cb = vi.fn()
+ const unsub = useAgentStatus.getState().onHookEvent(id, cb)
+ useAgentStatus.getState().setState(id, 'working', 'claude', true)
+ useAgentStatus.getState().setState(id, 'working', 'claude')
+ useAgentStatus.getState().setState(other, 'working', 'claude', true)
+ expect(cb).toHaveBeenCalledTimes(2)
+ unsub()
+ useAgentStatus.getState().setState(id, 'done', 'claude')
+ expect(cb).toHaveBeenCalledTimes(2)
+ })
+
+ it('sees the store already updated when it fires', () => {
+ const id = nid()
+ let seen: string | undefined
+ const unsub = useAgentStatus.getState().onHookEvent(id, () => {
+ seen = useAgentStatus.getState().byId[id]?.state
+ })
+ useAgentStatus.getState().setState(id, 'working', 'claude', true)
+ expect(seen).toBe('working')
+ unsub()
+ })
+})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index 6ef7f0856..6e834e8a8 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -260,6 +260,14 @@ export interface AgentStatusStore {
verified?: boolean,
errored?: boolean
): void
+ /**
+ * Subscribe to EVERY hook event `setState` records for node `id` — same-state ones included, and
+ * only once the store already reflects it. A zustand selector cannot see those: the same-state
+ * fast path refreshes `stateAt` IN PLACE and returns the same state object, so no subscriber is
+ * notified (deliberately — a notification per tool event would re-run every header's selector).
+ * This side channel is how the ⌘M panel refreshes its tail while a turn runs. Returns unsubscribe.
+ */
+ onHookEvent(id: string, cb: () => void): () => void
/** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */
sweepStaleWorking(staleMs?: number): void
setSession(id: string, session: string): void
@@ -494,17 +502,34 @@ export function createAgentStatusSession(
}
}
+ // `onHookEvent` listeners, per node id. Outside zustand on purpose (see the interface).
+ 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()
+ }
+
const store = create<AgentStatusStore>((set) => ({
byId: load(),
activeId: null,
+ onHookEvent: (id, cb) => {
+ let subs = hookEventSubs.get(id)
+ if (!subs) hookEventSubs.set(id, (subs = new Set()))
+ subs.add(cb)
+ return () => {
+ subs.delete(cb)
+ if (subs.size === 0 && hookEventSubs.get(id) === subs) hookEventSubs.delete(id)
+ }
+ },
+
setActive: (id, active) =>
set((s) => {
if (active) return s.activeId === id ? s : { activeId: id }
return s.activeId === id ? { activeId: null } : s
}),
- setState: (id, state, agentId, newTurn, pendingId, verified, errored) =>
+ setState: (id, state, agentId, newTurn, pendingId, verified, errored) => {
set((s) => {
const prev = s.byId[id] ?? EMPTY
const now = Date.now()
@@ -637,7 +662,10 @@ export function createAgentStatusSession(
// that has been demonstrably running since.
if (alive && (prev.hibernated || prev.paused)) save(byId)
return { byId }
- }),
+ })
+ // After the set: a listener reads the store and must see this event applied.
+ pulse(id)
+ },
sweepStaleWorking: (staleMs = STALE_WORKING_MS) =>
set((s) => {
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 32be98df6..9658f1aa2 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3328,6 +3328,16 @@ body,
font-size: 12px;
color: rgba(var(--tint-rgb), 0.45);
}
+/* The ⌘M chat panel's live-progress row, closing the thread while the agent works (or waits for
+ an answer in the terminal). Left-aligned under the last message, unlike the centred loading row. */
+.term-chat__activity {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 2px 4px;
+ font-size: 12px;
+ color: rgba(var(--tint-rgb), 0.55);
+}
/* The ⌘M output view's initial "Capturing…" placeholder, spinner beside the text. */
.term-md__capturing {
display: inline-flex;