Skip to content

perf(native-chat): stop rebuilding every transcript row on every stream frame - #18744

Merged
nwparker merged 1 commit into
mainfrom
perf/native-chat-message-memo
Sep 5, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/native-chat-message-memo

Conversation

@nwparker

@nwparker nwparker commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​175 $\color{#cf222e}{\Huge{\mathbf{−}}}$​160 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​15

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: MessageRow is wrapped in React.memo. Every prop is a primitive or an already-stable reference (onScrollMessageToTop is a useCallback([]); onLinkClick comes from a useCallback over a useShallow store selection; runtimeContext is useMemo'd at both call sites; failedDeliveryMessageIds?.has(...) collapses to a boolean), and message.blocks gets 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.tsx over max-lines. Per AGENTS.md a suppression is not an option, so MessageRow moves to NativeChatMessageRow.tsx verbatim.

Pure-move evidence

diff <(git show origin/main:.../NativeChatMessageList.tsx | sed -n '35,179p') NativeChatMessageRow.tsx — the base MessageRow block against the new file — is exactly:

0a1,17
> import { memo, useCallback, useMemo, useRef } from 'react'
> import CommentMarkdown, { type CommentMarkdownLinkClickHandler } from '@/components/sidebar/CommentMarkdown'
> ...  (13 more import lines, all copied from the base file's header)
>
3,4c20,23
<  *  lifted card, assistant prose as body copy, reasoning de-emphasized. */
< function MessageRow({
---
>  *  lifted card, assistant prose as body copy, reasoning de-emphasized.
>  *  Memoized: a stream frame republishes the whole transcript, but settled rows
>  *  keep their block identity, so only the changed row re-renders. */
> export const MessageRow = memo(function MessageRow({
145c164
< }
---
> })

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 to origin/main. NativeChatMessageList.tsx itself only loses that block and the imports that went with it, and swaps NativeChatToolRun for MessageRow in its import list.

Earlier revisions of this PR also folded four derivations into one useMemo, memoized NativeChatToolRun, and memoized a slice in useNativeChatTurnStatus. 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 (nativeChatProseToMarkdown invocations) rather than a render counter a refactor could game.

Before After
markdown rebuilds per stream frame 120 1

Verified as a genuine guard: removing the memo( wrapper and re-running fails with AssertionError: expected 120 to be less than 12.

Negative user-facing trade-offs

None identified. This is memoization on unchanged props only:

  • No visual change. A memoized row renders identical output for identical props; when props change it re-renders exactly as before.
  • No ordering, scroll-anchoring, or lifecycle change. loadEarlier, jump-to-latest, the typing indicator, turn status rows, and expandSignal behaviour are all untouched — they are outside MessageRow.
  • No staleness. message.blocks identity is what changes per frame for the streaming tail, so the live row still updates on every frame.
  • Not virtualization. I deliberately did not virtualize the list: that would trade scroll anchoring on loadEarlier and 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.tsx via the pure-move diff above rather than line by line. The only behavioural line in the PR is export const MessageRow = memo(function MessageRow({.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 5, 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: Team

Run ID: 8eeef7d4-6478-4e28-a938-caee97cab669

📥 Commits

Reviewing files that changed from the base of the PR and between bdb4bf6 and 71e3abc.

📒 Files selected for processing (1)
  • src/renderer/src/components/native-chat/NativeChatMessageRow.tsx

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The change moves MessageRow into a memoized module and preserves rendering for user, assistant, reasoning, system, and provider-frame messages. The message list now imports the extracted component. A performance test renders a 120-message transcript, updates the streaming tail for 20 frames, and verifies that markdown conversion remains below one-tenth of the transcript length per frame.

Merge Risk: ⚪ Minimal · up to 71e3a

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 `Fixes… Add the issue number or valid issue link in the Linked Issue section, for example Fixes #12345``. Verify that the referenced issue matches this performance change.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preventing unchanged native-chat transcript rows from rebuilding during streaming.
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.
Full details: Description check

Explanation

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 Fixes #.

  • Fix all pre-merge checks with AI
✨ 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.

@pullfrog pullfrog 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.

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.

  • MessageRow memoization — the four per-row derivations (splitNativeChatBlocks, nativeChatProseToMarkdown, the image-block scan, the provider-frame lookup) collapse into a single useMemo keyed on message.blocks.
  • NativeChatToolRun memoization — four passes over the block list collapse into two useMemos.
  • useNativeChatTurnStatus — the messages.slice(...).some(...) is now memoized on [messages, latestUserIndex].
  • Perf test — 120-message transcript, 20-frame stream, counting real nativeChatProseToMarkdown invocations 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 useNativeChatTurnStatus comment ("this runs on every render of a list that re-renders on every stream frame") slightly overstates the memo's effect: messages is 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the perf/native-chat-message-memo branch from e527866 to bdb4bf6 Compare September 5, 2026 01:08

@pullfrog pullfrog 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.

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 NativeChatToolRun memoization — reverted to a plain component, removing the React.memo wrapper and both useMemos.
  • Dropped useNativeChatTurnStatus memoization — the messages.slice(...).some(...) useMemo is gone.
  • Collapsed MessageRow's useMemo — only splitNativeChatBlocks(message.blocks) remains memoized; markdown, hasImages, and providerFrame are derived inline again, byte-identical to main.
  • 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.
@nwparker
nwparker force-pushed the perf/native-chat-message-memo branch from bdb4bf6 to 71e3abc Compare September 5, 2026 06:50

@pullfrog pullfrog 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.

ℹ️ 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-prose CommentMarkdown regains linkifyFilePaths={onLinkClick !== undefined}, which the previous commit's move had silently dropped; the row is byte-identical to main again.
  • Folded the row derivations into the useMemo — splitNativeChatBlocks, nativeChatProseToMarkdown, and the image scan now share one useMemo keyed on message.blocks (safe: all three are pure functions of blocks).

ℹ️ 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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

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.

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.

@nwparker
nwparker merged commit 12a3e64 into main Sep 5, 2026
28 checks passed
@nwparker
nwparker deleted the perf/native-chat-message-memo branch September 5, 2026 07:05
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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