Skip to content

perf(renderer): publish agent status bursts once - #13974

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-agent-status-batch-publish
Aug 13, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-agent-status-batch-publish

Conversation

@nwparker

@nwparker nwparker commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

The problem, in one line

When lots of agent updates arrive at once, the app told the whole UI about every single one, one at a time — and each one made the sidebar do a full search to figure out which pane it belonged to.

Why that hurts

There are about 9,300 things listening for store changes in a big workspace. Every update wakes all of them.

Reconnect to a remote host with 256 panes and you get 256 separate updates → roughly 2.4 million wake-ups for what is really one event: "here's the current state of everything."

Measured on main, 100 worktrees + 100 agent rows:

Listeners in the store 9,279
Renderer CPU, sitting idle 6.63%
Renderer CPU, 2,000 updates 18.25%
How late timers ran (median) 5,150 ms

That ~12-point CPU jump is the cost of announcing updates one at a time. The 5-second timer delay is why the app feels frozen.

What this PR does

Collects the updates that arrive together, applies them in order, then announces the result 3 times instead of 2 per update:

  1. once for the statuses
  2. once for auto-generated tab titles
  3. once for terminal tab titles

Same end state, far fewer announcements. It also builds the "which pane owns this?" lookup table once per batch instead of once per update.

The catch, and how it's handled

Announcing less often means some code could miss a step. If a pane goes working → done → working quickly, the UI now hears "working" once, not three separate things.

That's fine for anything that just reads the current state. It is not fine for code that watches for changes. Every listener was checked one by one; two needed fixing:

  • Windows terminals. A coalesced done → working → done looked like "no change", so the terminal never reset its keyboard mode and typing got corrupted. Now it tracks when the last turn actually finished, so it can't be fooled. This would have been a real bug — it's fixed here.
  • Scheduled automations. These watched for a done that could now be swallowed, and would have hung forever. They now read the history instead of just the current state.

A third was checked and left alone: it's driven by React renders, not this path, so it already behaved this way.

The full list of every listener and which category it falls into is in the first comment. Worth keeping, because tests cannot catch this kind of bug — the final state is identical either way, so nothing fails. Only reading the code finds it.

Other fixes in here

  • Memory. An earlier version kept the last assistant message on all 20 history entries per pane — about 80 MB worst case, in a renderer that already has a cap specifically to avoid running out of memory. Now it keeps one message per pane, ~4 MB.
  • Dropped updates on error. If applying a batch threw, the whole queue was already emptied and those updates were gone for good, leaving panes stuck showing stale state. They're now put back and retried.
  • A footgun. The batch used to overwrite the store wholesale, which would silently undo any unrelated write that happened at the same time. It now merges instead, and the type signature makes overwriting impossible to reintroduce.

Known limits, not fixed here

  • If two turns finish inside the same 33 ms window, an automation can record the wrong turn's output. Deliberate trade for bounded memory.
  • Remote hosts still send one message per pane on reconnect. This PR makes handling that cheap; it doesn't make the host send less. Tracked in STA-3983.

Checks

  • 741 tests pass across the 6 changed files
  • Typecheck clean
  • Each fix has a test verified to fail without it — including the Windows terminal case, the store-overwrite guard, and the dropped-updates case
  • Nothing sent between machines changed, so old and new versions still talk to each other

@nwparker

Copy link
Copy Markdown
Contributor Author

Edge-triggered consumer audit

Coalescing N publications into 1 is safe only for level-triggered consumers (those that recompute from current state). Edge-triggered consumers diff against a remembered previous value and silently stop firing when transitions collapse.

This class produces no error, no exception, and an identical end state, so CI structurally cannot catch it — any test comparing end state passes. The audit is the safety mechanism. Recorded here so future subscribers can be checked against it.

Every consumer of an agent-status store publication, classified. Level-triggered = recomputes from current state, safe under coalescing. Edge-triggered = diffs against a remembered previous value, breaks when N transitions collapse into 1.

EDGE-TRIGGERED — fixed in this PR

  • useAutomationDispatchEvents.ts:494 — diffed entry.state; now walks newly appended stateHistory rows and reads entry.lastCompletedAssistantMessage. (Ship the F1 3-line deletion with it.)
  • pty-connection.ts:3638 (Windows ConPTY idle keyboard reset) — compared state to a closure-local; now tracks the newest completed turn's stateStartedAt across live entry + history.

EDGE-TRIGGERED — pre-existing, exposure unchanged

  • StarNagAgentValueMomentObserver.tsx:34-35 — driven by useEffect(..., [agentStatusEpoch]), a React render. Main's flushPendingAgentStatuses already applies N events in one task, which React 18 auto-batches into one render, so it already missed intermediate transitions.

RESIDUAL — assessed, left as-is, on record

  • pty-connection.ts:3287 (process-exit notification suppression) — hasNewerActiveHookStatus() needs a live non-done level. A full hook turn (UserPromptSubmit→Stop) completing inside the 33ms burst window during the 250ms grace could produce one extra completion notification. Replay path excluded (replay never schedules notifications). Not reachable in practice; worst case is a duplicate notification, not corruption.

LEVEL-TRIGGERED — verified safe
agent-hook-completion-notifications.ts:127 (and the real coordinators are fed per-payload via afterCommit, one effect per event — no hook completion is coalesced away) · useAutoAckViewedAgent.ts:225 · terminal-pane-attention-subscriptions.ts:73 · App.tsx:1248 · useDashboardPopoutBridge.ts:93 · ai-vault-tab-title-sync.ts:190 · session-write-subscriber.ts:176 · sync-runtime-graph.ts:400/428/452 · hook-command-delayed-delivery.ts:52 · agent-startup-delayed-delivery.ts:101 · wake-sleeping-agents-in-background.ts:34 · automation-terminal-ownership.ts:94 · useIpcEvents.ts:1059 · codex-detached-pane-restart-scheduler.ts:27 · Terminal.tsx:539/2311 · editor-restored-tab-conflict-scan.ts:185 · editor-autosave-controller.ts:425 · worktree-agent-live-index-patch.ts:74 · web-session-tabs-sync.ts:1202/1283 · pty-connection.ts:2917 · parked-terminal-command-status.ts:181 · agent-completion-coordinator.ts (payload-driven).

Out of scope: mobile/ has its own store and row type; renderer batching does not reach it.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 624b5aa2-8ffd-412f-85fd-d60f94c6fb53

📥 Commits

Reviewing files that changed from the base of the PR and between fd08c4d and 447f805.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts

📝 Walkthrough

Walkthrough

The change adds transactional agent-status APIs with staged updates, deferred effects, freshness scheduling, and completed-message retention. Terminal title updates now use shared batch processors for backing and unified tabs. IPC ingestion batches status events and reuses indexed pane routing. Automation dispatch detects completion across recreated or historical status entries. Windows PTY handling resets terminal modes for newly completed turns. Tests cover batching, routing, title propagation, completion, hydration, and PTY behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the problem, approach, risks, and tests, but omits required template sections such as Linked Issue, Visual Proof, checklist, and review details. Use the repository template headings, add a valid Fixes # issue reference, provide visual proof or N/A with a reason, and complete testing, review, checklist, and applicable AI disclosure sections.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: batching renderer agent-status publications.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (7)
src/renderer/src/hooks/useIpcEvents.ts (2)

3369-3385: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the decorative-title projection asymmetry.

When isDecorativeAgentTitleFrameChange(title, terminalTitle) is true, the code still writes terminalTitle into tabTitlesByTabId, so the tab label is updated, but it projects the previous title and identityTitle for later events in the same batch. That split is deliberate for agent-type inference stability, but no comment states it. A future reader can read the projection as a missed update.

Add a one-line rationale comment.

♻️ Proposed comment
             options.batch.tabTitlesByTabId.set(tabId, terminalTitle)
             if (titleUsesTabTitle) {
+              // Why: a spinner-frame-only change must not re-seed agent-type inference for later
+              // events in this batch, but the tab label still tracks the newest frame.
               const titleChanges =
                 !title || !isDecorativeAgentTitleFrameChange(title, terminalTitle)

Source: Coding guidelines


4026-4123: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Consider deriving resolvePaneKey from the indexed resolver.

resolvePaneKey and resolvePaneKeyFromRoutingIndex now duplicate the same resolution rules: tab lookup, leaf presence, pane-title fallback, identity-title precedence, connection resolution, and titleUsesTabTitle. The two paths must stay identical, or single-event routing and batched routing will diverge silently.

Build a single-entry index inside resolvePaneKey and delegate, or extract the shared rules into one function.

src/renderer/src/hooks/useIpcEvents.test.ts (1)

5044-5103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm that passing rejected updates to setAgentStatuses matches production.

installMockAgentStatusTransaction forwards attemptedUpdates, which includes updates that applyMockAgentStatusUpdate rejected as stale. The real slice also receives every attempted update and rejects stale ones internally, so the shapes agree. Add a short comment stating that, because a reader can otherwise treat the forwarded rejects as a mock bug.

src/renderer/src/hooks/useAutomationDispatchEvents.ts (1)

440-474: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Record the cross-file invariant that keeps historical done completion safe.

The live-entry branch at Line 478 rejects sessionBoundary === true, but AgentStateHistoryEntry carries no sessionBoundary field, so the historical branch cannot apply the same guard. The historical branch is safe only because setAgentStatus in src/renderer/src/store/slices/agent-status.ts never pushes a session-boundary done into stateHistory (it short-circuits on existing.state === 'done' && existing.sessionBoundary === true).

That invariant lives in another file and is load-bearing here. If it changes, an automation run completes on a launch connect and records an empty result. Add a comment naming the invariant.

♻️ Proposed comment
                   if (
                     historicalState.state === 'done' &&
                     (!options?.requireWorkingAfterStart || sawWorkingAfterStart)
                   ) {
+                    // Why: AgentStateHistoryEntry carries no sessionBoundary, so this branch relies on
+                    // setAgentStatus never pushing a session-boundary `done` into stateHistory.
                     // Why: this `done` already rolled out of the live entry, so its output
                     // survives only in the entry-level completed slot.
src/shared/agent-status-types.ts (1)

129-132: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Document the field as live-only. lastCompletedAssistantMessage is renderer-derived and is absent from AgentStatusIpcPayload and last-status.json. Add a Not persisted... note to its comment.

src/renderer/src/store/slices/terminal-tab-title-batch.test.ts (1)

93-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the derivation of the 305 read budget.

The bound 305 encodes an expected number of tab.id reads per staged tab. A future change that adds one incidental read per tab fails this assertion with no explanation of the intended budget. Add a short comment that states the per-tab read count this bound protects.

♻️ Proposed comment
-    expect(fixture.getIdReads()).toBeLessThanOrEqual(305)
+    // ~3 reads per updated tab (owner index + stage index) plus slack; a linear
+    // pass must not degrade into a per-update rescan.
+    expect(fixture.getIdReads()).toBeLessThanOrEqual(305)
src/renderer/src/hooks/useAutomationDispatchEvents.test.ts (1)

146-161: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the production selector in this mock. The mock skips trimming and hard-codes capturedAt: 1, while selectAutomationRunOutputSnapshot trims assistant text and uses Date.now(). Mock only the buffer factory and assert capturedAt with expect.any(Number).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c233c40-4356-4918-89ea-093728018ba4

📥 Commits

Reviewing files that changed from the base of the PR and between 4b9fb46 and fd08c4d.

📒 Files selected for processing (13)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/slices/agent-status-batch.test.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts
  • src/renderer/src/store/slices/terminal-tab-title-batch.test.ts
  • src/renderer/src/store/slices/terminal-tab-title-batch.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/agent-status-types.ts

Comment on lines +671 to +677
latestStoreSubscriber()
latestStoreSubscriber()
await Promise.resolve()

expect(mockMarkDispatchResult).not.toHaveBeenCalledWith(
expect.objectContaining({ status: 'completed' })
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Strengthen the negative control before asserting no completion.

The positive test at Line 630 needs vi.waitFor before mockFinalizeTerminalOwnership is observed, so the completion path settles over more than one microtask. This negative test waits only one microtask with await Promise.resolve(). A regression that completes on a later tick would still pass this assertion. Drain the same number of ticks the completion path needs, or assert on a positive settle signal first.

💚 Proposed fix
     latestStoreSubscriber()
     latestStoreSubscriber()
-    await Promise.resolve()
+    // Drain the same async depth the completion path uses in the positive tests.
+    await vi.waitFor(() => expect(mockObserveExistingAutomationSession).toHaveBeenCalled())
+    await Promise.resolve()
+    await Promise.resolve()
 
     expect(mockMarkDispatchResult).not.toHaveBeenCalledWith(
       expect.objectContaining({ status: 'completed' })
     )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
latestStoreSubscriber()
latestStoreSubscriber()
await Promise.resolve()
expect(mockMarkDispatchResult).not.toHaveBeenCalledWith(
expect.objectContaining({ status: 'completed' })
)
latestStoreSubscriber()
latestStoreSubscriber()
// Drain the same async depth the completion path uses in the positive tests.
await vi.waitFor(() => expect(mockObserveExistingAutomationSession).toHaveBeenCalled())
await Promise.resolve()
await Promise.resolve()
expect(mockMarkDispatchResult).not.toHaveBeenCalledWith(
expect.objectContaining({ status: 'completed' })
)

Agent-status events fan out multiplicatively: every event pays an
O(worktrees x tabs) pane-routing scan and its own zustand publication, and
WorktreeList's unconditional sortEpoch subscription re-renders the whole
sidebar root on each one. A 256-pane reconnect replay meant 256 full sidebar
re-renders.

Fold a burst into one status publication (plus one generated-title and one
tab-title publication - three total, not 2N) via transactAgentStatuses, and
build the pane-routing index once per batch.

Coalescing is only safe for level-triggered consumers. Two edge-triggered
ones needed work:

- useAutomationDispatchEvents diffed entry.state, so a swallowed intermediate
  `done` lost the run's completion output. It now walks the newly appended
  stateHistory rows and reads the completed turn's output from the entry-level
  lastCompletedAssistantMessage slot (one message per pane - putting it on
  every history row would retain 20 transcripts per live status and reprise
  the renderer OOM in #9872).

- pty-connection's native-Windows ConPTY reset compared `state` against a
  closure-local previous value, so a coalesced done -> [working, done] never
  re-fired RESET_TERMINAL_CURSOR_STYLE / RESET_KITTY_KEYBOARD_PROTOCOL and
  left the pane with kitty keyboard protocol armed, corrupting plain input.
  It now tracks the newest completed turn's start across stateHistory, which
  also keeps same-turn `done` repaints from re-resetting.

The transaction commits as a MERGE patch of the keys the fold changed, not a
REPLACE of its snapshot: a batched action reaching another slice through
get() writes straight to the real store, and a REPLACE would silently revert
it. The shadowed `set` is typed without zustand's `replace` parameter so no
call site can reintroduce semantics the merge cannot express.
@nwparker
nwparker force-pushed the nwparker/perf-agent-status-batch-publish branch from fd08c4d to 447f805 Compare August 13, 2026 00:36
@nwparker
nwparker merged commit 9772da8 into main Aug 13, 2026
44 checks passed
@nwparker
nwparker deleted the nwparker/perf-agent-status-batch-publish branch August 13, 2026 00:46
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Agent-status events fan out multiplicatively: every event pays an
O(worktrees x tabs) pane-routing scan and its own zustand publication, and
WorktreeList's unconditional sortEpoch subscription re-renders the whole
sidebar root on each one. A 256-pane reconnect replay meant 256 full sidebar
re-renders.

Fold a burst into one status publication (plus one generated-title and one
tab-title publication - three total, not 2N) via transactAgentStatuses, and
build the pane-routing index once per batch.

Coalescing is only safe for level-triggered consumers. Two edge-triggered
ones needed work:

- useAutomationDispatchEvents diffed entry.state, so a swallowed intermediate
  `done` lost the run's completion output. It now walks the newly appended
  stateHistory rows and reads the completed turn's output from the entry-level
  lastCompletedAssistantMessage slot (one message per pane - putting it on
  every history row would retain 20 transcripts per live status and reprise
  the renderer OOM in stablyai#9872).

- pty-connection's native-Windows ConPTY reset compared `state` against a
  closure-local previous value, so a coalesced done -> [working, done] never
  re-fired RESET_TERMINAL_CURSOR_STYLE / RESET_KITTY_KEYBOARD_PROTOCOL and
  left the pane with kitty keyboard protocol armed, corrupting plain input.
  It now tracks the newest completed turn's start across stateHistory, which
  also keeps same-turn `done` repaints from re-resetting.

The transaction commits as a MERGE patch of the keys the fold changed, not a
REPLACE of its snapshot: a batched action reaching another slice through
get() writes straight to the real store, and a REPLACE would silently revert
it. The shadowed `set` is typed without zustand's `replace` parameter so no
call site can reintroduce semantics the merge cannot express.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant