Repository navigation
perf(renderer): publish agent status bursts once - #13974
Conversation
Edge-triggered consumer auditCoalescing 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
EDGE-TRIGGERED — pre-existing, exposure unchanged
RESIDUAL — assessed, left as-is, on record
LEVEL-TRIGGERED — verified safe Out of scope: |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
src/renderer/src/hooks/useIpcEvents.ts (2)
3369-3385: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the decorative-title projection asymmetry.
When
isDecorativeAgentTitleFrameChange(title, terminalTitle)is true, the code still writesterminalTitleintotabTitlesByTabId, so the tab label is updated, but it projects the previoustitleandidentityTitlefor 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 liftConsider deriving
resolvePaneKeyfrom the indexed resolver.
resolvePaneKeyandresolvePaneKeyFromRoutingIndexnow duplicate the same resolution rules: tab lookup, leaf presence, pane-title fallback, identity-title precedence, connection resolution, andtitleUsesTabTitle. The two paths must stay identical, or single-event routing and batched routing will diverge silently.Build a single-entry index inside
resolvePaneKeyand delegate, or extract the shared rules into one function.src/renderer/src/hooks/useIpcEvents.test.ts (1)
5044-5103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConfirm that passing rejected updates to
setAgentStatusesmatches production.
installMockAgentStatusTransactionforwardsattemptedUpdates, which includes updates thatapplyMockAgentStatusUpdaterejected 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 winRecord the cross-file invariant that keeps historical
donecompletion safe.The live-entry branch at Line 478 rejects
sessionBoundary === true, butAgentStateHistoryEntrycarries nosessionBoundaryfield, so the historical branch cannot apply the same guard. The historical branch is safe only becausesetAgentStatusinsrc/renderer/src/store/slices/agent-status.tsnever pushes a session-boundarydoneintostateHistory(it short-circuits onexisting.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 winDocument the field as live-only.
lastCompletedAssistantMessageis renderer-derived and is absent fromAgentStatusIpcPayloadandlast-status.json. Add aNot persisted...note to its comment.src/renderer/src/store/slices/terminal-tab-title-batch.test.ts (1)
93-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument the derivation of the 305 read budget.
The bound
305encodes an expected number oftab.idreads 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 winUse the production selector in this mock. The mock skips trimming and hard-codes
capturedAt: 1, whileselectAutomationRunOutputSnapshottrims assistant text and usesDate.now(). Mock only the buffer factory and assertcapturedAtwithexpect.any(Number).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9c233c40-4356-4918-89ea-093728018ba4
📒 Files selected for processing (13)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/hooks/useAutomationDispatchEvents.test.tssrc/renderer/src/hooks/useAutomationDispatchEvents.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/agent-status-batch.test.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.tssrc/renderer/src/store/slices/terminal-tab-title-batch.test.tssrc/renderer/src/store/slices/terminal-tab-title-batch.tssrc/renderer/src/store/slices/terminals.tssrc/shared/agent-status-types.ts
| latestStoreSubscriber() | ||
| latestStoreSubscriber() | ||
| await Promise.resolve() | ||
|
|
||
| expect(mockMarkDispatchResult).not.toHaveBeenCalledWith( | ||
| expect.objectContaining({ status: 'completed' }) | ||
| ) |
There was a problem hiding this comment.
🎯 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.
| 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.
fd08c4d to
447f805
Compare
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.
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: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:
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 → workingquickly, 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:
done → working → donelooked 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.donethat 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
Known limits, not fixed here
Checks