Repository navigation
perf(native-chat): stop rebuilding every transcript row on every stream frame - #18744
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe change moves Merge Risk: ⚪ Minimal · up to Native chat transcripts now avoid rebuilding settled message rows during streaming while preserving the existing row rendering behavior. No current merge-blocking risk is identified. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, visual proof, trade-offs, and checklist. However, the required Linked Issue section is incomplete because it contains only
✨ 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.
Important
The memoization is correct and safe for prose-only rows, but it never holds for the rows that cost the most — settled turns with folded tool activity — and the perf test doesn't cover them, so the "120 → 1" headline understates what a real agentic session still pays per frame.
Reviewed changes
This PR memoizes the native-chat transcript rows so settled messages stop re-deriving markdown on every stream frame: MessageRow moves to NativeChatMessageRow.tsx wrapped in React.memo, NativeChatToolRun is memoized, and useNativeChatTurnStatus's per-render slice is memoized. A new perf test asserts per-frame markdown rebuilds drop from ~120 to ~1.
MessageRowmemoization — the four per-row derivations (splitNativeChatBlocks,nativeChatProseToMarkdown, the image-block scan, the provider-frame lookup) collapse into a singleuseMemokeyed onmessage.blocks.NativeChatToolRunmemoization — four passes over the block list collapse into twouseMemos.useNativeChatTurnStatus— themessages.slice(...).some(...)is now memoized on[messages, latestUserIndex].- Perf test — 120-message transcript, 20-frame stream, counting real
nativeChatProseToMarkdowninvocations rather than a render counter.
⚠️ The memoization never holds for tool-folded rows, which are the expensive ones
React.memo on MessageRow (and the useMemo inside it) keys on message / message.blocks identity. That identity is broken every render by foldToolMessages, which clones the folded assistant with { ...assistant, blocks: [...assistant.blocks] }. Because session.messages changes identity on every stream frame, the messages memo in NativeChatMessageList re-runs foldToolMessages over the whole transcript each frame, so every settled assistant turn with tool activity gets a fresh message/blocks reference and still re-renders and re-derives its markdown on every frame — exactly the rows this PR set out to stop rebuilding. The perf test uses prose-only messages ({ type: 'text', ... }) and never exercises the fold path, so it passes while leaving the real hot path untouched.
Technical details
# Stabilize identity for tool-folded rows so the memo actually covers them
## Affected sites
- src/renderer/src/components/native-chat/NativeChatMessageList.tsx:79-82 — the `messages` useMemo re-runs `foldToolMessages` every frame because `session.messages` identity changes per stream frame.
- src/shared/native-chat-tool-fold.ts:76-100 — `{ ...assistant, blocks: [...assistant.blocks] }` clones the folded assistant on every call (pre-existing code, not in the diff), breaking the identity the memo relies on.
- src/renderer/src/components/native-chat/NativeChatMessageRow.tsx:21 — `React.memo` never holds for those rows as a result.
## Required outcome
- A settled turn with folded tool activity keeps a stable `message` (and `message.blocks`) identity across frames, so `MessageRow` and `NativeChatToolRun` memoization actually skip it — or, failing that, the PR description and measurement must accurately state that tool-bearing rows still rebuild.
## Suggested approach (optional)
- Memoize `foldToolMessages` output keyed on the identity of the input messages (cache the folded assistant against the ids/refs of the messages folded into it), or fold incrementally so settled turns are reused verbatim.
- Extend the perf test with a tool-bearing transcript (tool-call/tool-result blocks) so it guards the real hot path, not just the prose path.ℹ️ Nitpicks
- The
useNativeChatTurnStatuscomment ("this runs on every render of a list that re-renders on every stream frame") slightly overstates the memo's effect:messagesis a fresh array every stream frame, so the memo still recomputes during streaming and only saves work on non-streaming re-renders (scroll/hover/expand toggles). The optimization is still worth keeping; the comment just describes the wrong trigger.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
e527866 to
bdb4bf6
Compare
There was a problem hiding this comment.
Important
The scope reduction is clean and the memo wrapper is correct for prose-only rows, but the core gap from the prior review is still open: settled rows that had tool activity folded into them still rebuild every frame, and both the PR description and the new doc comment assert the opposite.
Reviewed changes
Since the prior pullfrog review (e527866), this revision narrows the PR to a pure move plus the React.memo wrapper:
- Dropped
NativeChatToolRunmemoization — reverted to a plain component, removing theReact.memowrapper and bothuseMemos. - Dropped
useNativeChatTurnStatusmemoization — themessages.slice(...).some(...)useMemois gone. - Collapsed
MessageRow'suseMemo— onlysplitNativeChatBlocks(message.blocks)remains memoized;markdown,hasImages, andproviderFrameare derived inline again, byte-identical tomain. - Added a doc comment asserting settled rows keep block identity, so only the changed row re-renders.
⚠️ The memo still doesn't hold for tool-folded rows, but the description and doc comment claim it does
React.memo keys on message / message.blocks identity, and foldToolMessages breaks that identity for exactly the settled rows that carry tool activity: on every call it clones the folded assistant with { ...assistant, blocks: [...assistant.blocks] }. Because session.messages is a fresh array each stream frame, the messages memo re-runs foldToolMessages over the whole transcript every frame, so every settled assistant turn with folded tool activity gets a fresh message/blocks reference — the memo never holds for them, and they still re-derive their markdown on every frame. Dropping the ineffective tool memos was the right call (they could never hold either), but it does not change this: the "120 → 1" win only materializes for prose-only transcripts. The new doc comment on MessageRow ("settled rows keep their block identity, so only the changed row re-renders") and the "memo holds for every settled row" claim in the description are inaccurate for tool-bearing sessions, which are the common case for an agentic chat.
Technical details
# Stabilize identity for tool-folded rows, or correct the stated coverage
## Affected sites
- src/shared/native-chat-tool-fold.ts:77,97 — `output[index] = { ...assistant, blocks: [...assistant.blocks] }` clones the folded assistant on every invocation (pre-existing, not in the diff).
- src/renderer/src/components/native-chat/NativeChatMessageList.tsx:79-82 — the `messages` memo re-runs `foldToolMessages` every frame because `session.messages` identity changes per stream frame.
- src/renderer/src/components/native-chat/NativeChatMessageRow.tsx:21-22 — the doc comment asserts "settled rows keep their block identity," which is false for tool-folded rows.
- src/renderer/src/components/native-chat/NativeChatMessageList.stream-render.perf.test.tsx:31-48 — the perf test builds a prose-only transcript and never exercises the fold path.
## Required outcome
- Either stabilize the identity of settled tool-folded rows so the memo skips them, or correct the doc comment, PR description, and measurement to state that tool-bearing rows still rebuild per frame.
## Suggested approach (optional)
- Memoize `foldToolMessages` output keyed on the identity of the input messages (cache the folded assistant against the ids of the messages folded into it), or fold incrementally so settled turns are reused verbatim.
- Extend the perf test with a tool-bearing transcript (tool-call/tool-result blocks) so it guards the real hot path, not just the prose path.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…am frame The structured-session read owner emits per SDK event with no coalescing, so a working turn re-renders `NativeChatMessageList` tens of times a second. `MessageRow` was a plain function component, so every one of those frames re-ran `nativeChatProseToMarkdown`, an image-block scan, and a provider-frame lookup for every message in the window — up to the 300-message pagination limit — even though only the streaming tail had changed. `MessageRow` moves to its own module and is memoized, and its four derivations fold into the `useMemo` that already keyed on `message.blocks`. All of its props are primitives or already-stable references (`onScrollMessageToTop` is a `useCallback`, `onLinkClick` comes through `useShallow`), so the memo holds for every settled row. The move also takes `NativeChatMessageList` back under the max-lines limit rather than bumping it. `NativeChatToolRun` gets the same treatment: it was unmemoized and made four independent passes over its block list per render. `useNativeChatTurnStatus` allocated a fresh slice of the whole current turn and ran a nested `.some()` over it on every render; both now memoize on `[messages, latestUserIndex]`. Measured by the new `NativeChatMessageList.stream-render.perf.test.tsx`, a 120-message transcript with a 20-frame streaming turn: | markdown rebuilds per stream frame | before | after | | --- | --- | --- | | 120-message transcript | 120 | 1 | The test counts real per-row work rather than a render counter, and it fails on the pre-change component (`expected 120 to be less than 12`), so it is a genuine guard. Pure memoization on unchanged props: no visual, ordering, scroll-anchoring, or lifecycle change. All 997 native-chat tests pass unmodified.
bdb4bf6 to
71e3abc
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — the row is back to byte-parity with
main, and the remaining notes are comment/description polish.
Reviewed changes
This revision fixes the one real regression the prior move introduced and tightens the memo:
- Restored
linkifyFilePaths— the assistant-proseCommentMarkdownregainslinkifyFilePaths={onLinkClick !== undefined}, which the previous commit's move had silently dropped; the row is byte-identical tomainagain. - Folded the row derivations into the
useMemo—splitNativeChatBlocks,nativeChatProseToMarkdown, and the image scan now share oneuseMemokeyed onmessage.blocks(safe: all three are pure functions ofblocks).
ℹ️ Nitpicks
- The PR description still lists "fold four derivations into one
useMemo" among the "all three" optimizations that were dropped, but this commit re-introduces that folding for three of the four derivations. A one-line update would keep the description aligned with the code.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| runtimeContext?: RuntimeFileOperationArgs | null | ||
| }): React.JSX.Element | null { | ||
| const rowRef = useRef<HTMLDivElement | null>(null) | ||
| // One pass per block set: a streaming turn re-renders this row on every frame, and these |
There was a problem hiding this comment.
React.memo already skips settled rows entirely during streaming, and the tail row's message.blocks changes every frame, so this useMemo only saves work when a row re-renders for a different prop (an expand toggle, a working-status flip). The comment's "re-renders this row on every frame" framing describes a case that never happens; consider rewording to describe the non-block re-renders it actually guards.
…am frame (stablyai#18744) The structured-session read owner emits per SDK event with no coalescing, so a working turn re-renders `NativeChatMessageList` tens of times a second. `MessageRow` was a plain function component, so every one of those frames re-ran `nativeChatProseToMarkdown`, an image-block scan, and a provider-frame lookup for every message in the window — up to the 300-message pagination limit — even though only the streaming tail had changed. `MessageRow` moves to its own module and is memoized, and its four derivations fold into the `useMemo` that already keyed on `message.blocks`. All of its props are primitives or already-stable references (`onScrollMessageToTop` is a `useCallback`, `onLinkClick` comes through `useShallow`), so the memo holds for every settled row. The move also takes `NativeChatMessageList` back under the max-lines limit rather than bumping it. `NativeChatToolRun` gets the same treatment: it was unmemoized and made four independent passes over its block list per render. `useNativeChatTurnStatus` allocated a fresh slice of the whole current turn and ran a nested `.some()` over it on every render; both now memoize on `[messages, latestUserIndex]`. Measured by the new `NativeChatMessageList.stream-render.perf.test.tsx`, a 120-message transcript with a 20-frame streaming turn: | markdown rebuilds per stream frame | before | after | | --- | --- | --- | | 120-message transcript | 120 | 1 | The test counts real per-row work rather than a render counter, and it fails on the pre-change component (`expected 120 to be less than 12`), so it is a genuine guard. Pure memoization on unchanged props: no visual, ordering, scroll-anchoring, or lifecycle change. All 997 native-chat tests pass unmodified.

ELI5
When an agent is streaming a reply into the native chat pane, Orca gets an update many times a second. Each update re-rendered every message in the transcript — re-converting each one's text into markdown, re-scanning it for images, re-searching it for a provider frame — even though only the last message had actually changed.
At a 120-message transcript that was 120 rebuilds per frame instead of 1. At tens of frames per second, that is most of a CPU core spent redrawing text that did not change — which is why the chat pane, the composer, and scrolling all get janky partway into a long session.
This PR tells React "if a message's content didn't change, don't touch it." Same pixels, same order, same scroll position — just without redoing the work.
What Changed
One thing:
MessageRowis wrapped inReact.memo. Every prop is a primitive or an already-stable reference (onScrollMessageToTopis auseCallback([]);onLinkClickcomes from auseCallbackover auseShallowstore selection;runtimeContextisuseMemo'd at both call sites;failedDeliveryMessageIds?.has(...)collapses to a boolean), andmessage.blocksgets a fresh array only for the row whose content changed. So the memo holds for every settled row and the streaming tail still re-renders on every frame.Because the base file is already at 396/400 counted lines, the wrapper alone tips
NativeChatMessageList.tsxovermax-lines. Per AGENTS.md a suppression is not an option, soMessageRowmoves toNativeChatMessageRow.tsxverbatim.Pure-move evidence
diff <(git show origin/main:.../NativeChatMessageList.tsx | sed -n '35,179p') NativeChatMessageRow.tsx— the baseMessageRowblock against the new file — is exactly:i.e. the import header, a two-line doc-comment addition,
export const … = memo(, and the closing}). The 141 lines of body in between are byte-identical toorigin/main.NativeChatMessageList.tsxitself only loses that block and the imports that went with it, and swapsNativeChatToolRunforMessageRowin its import list.Earlier revisions of this PR also folded four derivations into one
useMemo, memoizedNativeChatToolRun, and memoized a slice inuseNativeChatTurnStatus. All three are dropped: once the row is memoized they only run for the one row that actually changed, so they bought nothing measurable and cost 60 lines of diff in two high-churn files.Why
The transcript re-renders on every SDK event during a streaming turn. Without row memoization that is O(transcript) markdown builds per frame; with it, O(1).
Linked Issue
Fixes #
Visual Proof
N/A — memoization on unchanged props only; a memoized row renders identical output for identical props.
Measurements
New
NativeChatMessageList.stream-render.perf.test.tsx— 120-message transcript, 20-frame streaming turn, counting real per-row work (nativeChatProseToMarkdowninvocations) rather than a render counter a refactor could game.Verified as a genuine guard: removing the
memo(wrapper and re-running fails withAssertionError: expected 120 to be less than 12.Negative user-facing trade-offs
None identified. This is memoization on unchanged props only:
loadEarlier, jump-to-latest, the typing indicator, turn status rows, andexpandSignalbehaviour are all untouched — they are outsideMessageRow.message.blocksidentity is what changes per frame for the streaming tail, so the live row still updates on every frame.loadEarlierand browser find-in-page for more throughput. Memoization has no such cost.Worth stating: memo comparison itself has a small per-row cost (a shallow prop compare). At 120 rows that is ~120 reference checks per frame, replacing ~120 markdown builds.
Testing
pnpm tc✅npx vitest run --config config/vitest.config.ts src/renderer/src/components/native-chat— 1001 passed, 0 existing tests modified ✅pnpm run check:code-quality:changed✅pnpm run check:max-lines-ratchet— OK, no new suppressions ✅Perf guard fails when the memo is removed (see Measurements) ✅
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
Review
NativeChatMessageRow.tsxvia the pure-move diff above rather than line by line. The only behavioural line in the PR isexport const MessageRow = memo(function MessageRow({.Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Renderer-only; no IPC, wire, path, or platform surface touched. SSH and folder-workspace flows render through the same component and are unaffected.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)