Skip to content

Keep timeline pushes from re-rendering the thread view - #7599

Merged
ymichael merged 5 commits into
mainfrom
bb/timeline-push-renders-thr_edin4mcbec
Nov 17, 2026
Merged

ymichael merged 5 commits into
mainfrom
bb/timeline-push-renders-thr_edin4mcbec

Conversation

@ymichael

@ymichael ymichael commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

ThreadDetailViewInternal (and PluginThreadChatBody) called useThreadTimelineController, so every timeline push re-rendered the whole thread view from the top: header, secondary panel, ThreadScreen, prompt area and composer. In a profiling build that was about 183 component renders per text push. Inside the timeline, TimelineRowItemWrapper took a fresh children element, so every mounted row's wrapper re-rendered on every row change, and ConversationRow read three message-id contexts, so all conversation rows re-rendered whenever a new message became the latest or streaming one. ThreadScreen also passed the useSendThreadMessage() result, a new object each render, and read systemConfigQuery inside the prompt-area JSX, so the compiled prompt-area element was rebuilt on every ThreadScreen render.

Found in the client perf audit (thr_qgyt9gkt9f).

What changed

  • ThreadScreen owns useThreadTimelineController and takes timelineEnabled instead of a timeline result. ThreadDetailView and PluginThreadChat keep the fetch and realtime subscription starting before the thread loads through useThreadTimelineSubscription, an observer with notifyOnChangeProps: [] that never re-renders them. ThreadDetailView reads the provisioning-failure flag through useThreadTimelineProvisioningFailure, a select observer that re-renders only when the flag changes and checks rows only while the thread is in the error-without-environment state. Realtime subscriptions are ref-counted in wsManager, so the second useThreadTimeline call shares one subscription.
  • ThreadTimelineRows: the row wrapper is now MemoizedTimelineRowItem, which takes the row-view props directly and compares them with the existing areTimelineRowViewPropsEqual. TimelineRowsList computes each conversation row's isLatestActionableMessage and isStreamingMessage and passes them down as props, so a change re-renders only the rows whose flags flip.
  • ThreadScreen passes a memoized { isPending, mutateAsync } send handle and a derived steerActiveThreadOnEnter boolean.
  • tests/render-invariants: the "a streaming push re-renders no finished timeline row" invariant was pending on main because every mounted row wrapper re-rendered on each streamed delta. It now runs in CI, and docs/render-invariants.md marks it on.

The prompt area still re-renders when its own inputs change (context usage, thread). Because ThreadDetailPromptArea and useComposerRendererHostApi are not compiled yet, that re-render still reaches the composer. Getting them compiled is being done in a separate change.

How you verified

Render-invariant suite (real server, host daemon and compiled profiling app in headless Chromium), one streamed turn of about 27 pushes on the 40-turn fixture thread, three runs each, this branch merged with current main:

main this PR
Component re-renders 8,803–8,857 1,999
React commits 55 28
ThreadDetailViewInternal / ThreadDetailHeader / ThreadDetailPromptArea / ComposerBox re-renders 27 each 0
Finished timeline row re-renders 324–378 0

The full suite passes twice in a row with the streaming invariant on (5 passed, composer typing still pending).

Profiling build of the app (react-dom/profiling, compiler on) behind a pnpm start:worktree server, with a DevTools-hook render counter. Fixture: a thread with about 140 rows, and a turn of a 300-word paragraph followed by 5 Bash calls. Two runs each:

main this PR
Total renders 14,342 / 14,100 9,823 / 9,594
ThreadDetailViewInternal renders 28 / 27 6 / 6
Prompt area / ComposerBox renders 28 / 28 15 / 14
Row wrapper renders 363 / 393 87 / 87
ConversationRow renders 59 / 59 10 / 11
React actualDuration sum 98.7 / 105.9 ms 66.8 / 78.0 ms

A text push now commits about 16 to 24 component renders instead of about 183. The remaining large commits come from turn start and end (scopeActive flips the dimming on every row, which is expected) and from the sidebar re-rendering all rows on a thread update. The sidebar fan-out is handled in a separate change.

Tests (each fails on main and passes here):

  • ThreadTimelineRows.row-isolation.test.tsx: when the streaming row's text grows, only that row's TimelineRowItem and ConversationRow re-render. When a row is appended, only the new row and the previous latest row re-render.
  • ThreadDetailView.timeline-push.test.tsx: a timeline push that a subscribed probe sees does not re-render the thread view's ThreadScreen.

Commands: pnpm exec turbo run typecheck --filter=@bb/app, and the targeted app tests (ThreadScreen, PluginThreadChat, ThreadDetailView*, ThreadTimelineRows*, useThreadTimelineController, ThreadTimelineSurface): 19 files, 197 tests passed. I also checked the branch build in a browser: the timeline, composer and a live turn render and stream with no page errors.

AGENT GENERATED

ymichael and others added 2 commits November 15, 2026 13:45
ThreadDetailViewInternal and PluginThreadChatBody owned the timeline
controller, so every streaming push re-rendered the whole thread view top
down: header, panels, prompt area and composer. ThreadScreen now owns the
controller; its parents keep a non-rendering observer so the fetch and
realtime subscription still start before the thread loads, and read the
provisioning-failure flag through a selector.

Timeline rows: the per-row wrapper is now a memoized TimelineRowItem, and
each conversation row's latest-actionable and streaming flags are computed
per row instead of read from contexts, so a push re-renders only the rows
it changes. ThreadScreen passes a stable send handle and the derived steer
setting so the compiled prompt-area element survives unrelated pushes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The push test now runs TanStack notifications synchronously, so it
measures only the renders the push causes. The render recorder types its
global hook slot without tripping the weak-type check and can report
renders outside a component's subtree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 16, 2026
## Human comments

## What was wrong

`usePluginSlots()` subscribed to the whole plugin slot snapshot, and 57
consumers called it, including per-row ones (`ThreadRowMetadata`, the
thread action registry used by every thread row and menu) and
`ThreadDetailViewInternal`. Any plugin registration, removal or
re-registration (enable, disable, reload, hot reload) re-rendered all of
them, even when the change touched an unrelated slot kind. Found in the
client perf audit (thr_qgyt9gkt9f).

## What changed

- `lib/plugin-slots.ts`: adds `usePluginSlotKind(kind)` and exports
`PluginSlotKind`. `buildSnapshot` already keeps each kind's array
identity when another kind changes, so a consumer of one kind now
re-renders only when that kind changes.
- Every consumer moves to `usePluginSlotKind` for the kinds it reads,
including the hand-written per-kind `useSyncExternalStore` calls in
`ThreadTimelineRows` (four), `composer-slot-hooks.ts` and
`PluginTimelineRendererBody.tsx`, which now use the hook. The plugin
capabilities page keeps `usePluginSlots()`, because it lists every kind
for one plugin.
- Two tests that mocked `@/lib/plugin-slots` mock `usePluginSlotKind`
instead.
- `src/test/render-recorder.ts`: a test helper that records renders
through a React DevTools hook (identical to the copy in #7599, #7602 and
#7606).

## How you verified

Profiling build of the app (react-dom/profiling, compiler on) behind
`pnpm start:worktree`, with a thread view open. Test: `bb plugin disable
bb--github-star`, then `bb plugin enable bb--github-star`. Two runs
each:

| | main | this PR |
|---|---|---|
| Commits | 15 / 15 | 13 / 13 |
| Total renders | 3,511 / 3,511 | 2,613 / 2,613 |
| React `actualDuration` | 15.6 / 17.0 ms | 12.2 / 12.2 ms |
| `ThreadDetailViewInternal` renders | 6 / 6 | 4 / 4 |

Test added: `lib/plugin-slots.render.test.tsx`. Registering a plugin
that contributes only a settings section re-renders no
`ThreadRowMetadata` row. Registering row metadata re-renders each row.
The test fails when `ThreadRowMetadata` uses the whole snapshot again.

Commands:
- `pnpm exec turbo run typecheck lint --filter=@bb/app`
- After the follow-up commit: composer, timeline-renderer and
plugin-slot render tests (10 files, 106 tests).
- App tests under `src/components`, `src/lib`, `src/views` and
`src/hooks`: 661 files, 6,983 tests passed.

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael and others added 3 commits November 16, 2026 14:34
…ers-thr_edin4mcbec

# Conflicts:
#	apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx
Timeline rows no longer re-render on every streamed delta, so the
"a streaming push re-renders no finished timeline row" invariant now holds
on this branch. Run it in CI and drop its pending cause from the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ers-thr_edin4mcbec

# Conflicts:
#	apps/app/src/views/thread-detail/ThreadScreen.test.tsx
@ymichael
ymichael merged commit f663f6e into main Nov 17, 2026
96 of 97 checks passed
@ymichael
ymichael deleted the bb/timeline-push-renders-thr_edin4mcbec branch November 17, 2026 03:45
ymichael added a commit that referenced this pull request Nov 17, 2026
…hole timeline per push (#7613)

## Human comments

## What was wrong

Streaming a long answer cost more per push the longer the answer got, in
three places (perf audit hotspot 1, thr_qgyt9gkt9f):

- **Wire.** A timeline delta upserted every changed row whole, so each
push re-sent the full accumulated message text (up to ~27 KB per frame).
- **Render.** Block-incremental markdown re-cloned every settled piece
on every new body, so React re-rendered the entire settled message on
each push. Mounting a table also walked its ancestors with
`getComputedStyle` in a layout effect, forcing a style recalc.
- **Layout.** The page scrollers (`data-page-scroll-viewport`) were also
`@container/page` query containers. A scroll container that is a size
container makes Blink lay out its whole scrolled subtree on every
content change. An append that dirtied 27 layout objects still took
~8–10 ms of layout at 4× CPU, and in the trace that cost grew with the
number of mounted objects. `scroll-position-keeper` `apply` was the top
self-time entry because it was the first to read layout after each
commit.

## What changed

- **Append-only deltas** (`packages/server-contract`)
- New optional field `delta.patchRows: { id, ops }[]` for rows the base
window already holds. Ops are `["append", path, text]`, `["set", path,
value]` and `["delete", path]` on JSON paths inside the row.
- `computeThreadTimelineDelta` diffs each changed row. A string that
grew at its end becomes an `append`. `upsertRows` now carries only rows
that are new to the window.
- `applyThreadTimelineDelta` applies patches with structural sharing. It
returns `null`, and the client refetches instead of rendering the row,
when an op does not fit the held row (a path that does not exist, an
append to a non-string, an index past the end) or when the result
changes the row's `id` or `kind`.
- The patched row is not re-validated against `timelineRowSchema`. A
delta applies only to the window whose tag it names, so the client
patches exactly the row the server diffed against, and full rows in
`upsertRows` are not schema-checked on the client either. Leaving the
schema out keeps it off the boot path without a registry, and applying
stays synchronous.
- In a live stream on the built branch, every delta push applied with no
timeline refetch, and the rendered message matched the server's text.
- I chose JSON-path ops over a typed per-field append contract. Every
streamed push also changes `sourceSeqEnd`, `createdAt` and `messageSeq`,
and streamed output lives under different fields per row kind (message
`text`, command and tool `output`, delegation `output`), so a typed
contract would need a field list for each row kind.
- HTTP reads with `afterTag` and WebSocket pushes share this code. The
daemon wire is unchanged, so `HOST_DAEMON_PROTOCOL_VERSION` is not
bumped. Documented in `docs/timeline-pagination.md`.
- **Settled markdown stays put** (`markdown-incremental-pieces.ts`)
- Reused pieces keep their elements and directive mounts by identity, so
React skips them.
- `MountedMessageDirectiveView` is now a memo boundary keyed on the
mount.
- The raw thread-mention hooks used to read the query cache without
subscribing and depended on that re-render to pick up titles. They now
subscribe to their cache entries. I copied this part verbatim from
#7603, which makes the same change, so whichever PR lands first, the
other rebases cleanly.
- **Table geometry** (`markdown-preview.tsx`): the breakout width adds
`--page-container-inset-end` to `100cqw`, because the page container now
sits inside the context-card inset. Resolving the clip ancestor lazily
instead of in the mount layout effect landed separately in #7612, so
this PR no longer changes it.
- **Query containers moved off scrollers**
- `bottom-anchored-scroll-body` (thread timeline): the container moves
to the existing content child. The context-card inset is passed as
`--page-container-inset-end`, so the table breakout's `100cqw` math
stays identical.
- Static `PageShell`, `RootComposeHome` (non-compact) and the tasks
list: a plain container wrapper inside the scroller.
- Plugin Guide: the size container moves to the existing outer element.
The `3cqh` stage gap subtracts the scroller padding it no longer sees,
so the gap is unchanged.
- New guard `scroll-container-queries.test.ts` fails on any class string
that makes one element both a scroll container and a query container. It
flags all five of these on main. I added the rule to AGENTS.md (UI).

Not changed: how `TimelineWindowedItems` mounts rows. #7612 has since
changed that path; this PR does not touch it.

Old tabs: a tab still running the previous app ignores `patchRows`. That
is acceptable because `AppUpdateHost` reloads the page when the server's
version or commit changes, and the mobile and desktop apps load the app
from the server.

Refs #6816.

## How you verified

**Benchmark.** Production builds of main (`da3e60b81d`) and this branch,
each served by `pnpm start:worktree` with the same seeded 500-thread
fixture and stream provider. The stream was 4 × 24 KB markdown messages
with 3 streamed commands (`stream:120:40 rep:8`) into the 2.9k-item
thread, with 48 characters typed during the stream. Headless Chrome 145
at 1600×1000. Three rounds, alternating main and branch run by run on a
loaded machine. Medians of 3:

| | main 1× | branch 1× | main 4× | branch 4× |
|---|---|---|---|---|
| Typing 48 chars during the stream | 3.37 s | 3.12 s | 5.51 s | **4.18
s** |
| Long animation frames (count / total) | 3 / 243 ms | 3 / 223 ms | 187
/ 17.9 s | **78 / 6.9 s** |
| Frames > 100 ms | 0 | 0 | 55 | **10** |
| Forced style + layout in LoAF | 92 ms | 83 ms | 9.8 s | **3.3 s** |
| Layout time (`Performance.getMetrics`) | 2.78 s | 0.83 s | 10.4 s |
**3.6 s** |
| WebSocket bytes received | 3.48 MB | **0.55 MB** | 3.51 MB | **0.55
MB** |

- **After the rebase onto #7599 and #7612, without patched-row
validation** (echo provider streaming 199 chunks of paragraphs, links,
inline code, tables and code blocks, about 25 KB, every 40 ms, into a
thread with 8 earlier answers of that size; headless Chrome 1600×1000 at
4× CPU, typing 48 characters during the stream; main measured before
those PRs landed, so this is not a strict A/B):
- Timeline WebSocket bytes 1.46 MB → 0.15 MB; the last push 27.5 KB →
1.3 KB.
- Layout 3.8 s → 0.33–0.35 s; long animation frames 68–72 → 4; forced
style and layout 2.9 s → 40–48 ms; typing 5.7–6.0 s → 2.4–2.5 s.
- **Wire.** Timeline frames for the same stream fell from 3.50 MB to
0.47 MB of deltas, with the same final text length. About 210 KB of the
rest is `timelinePage.olderCursor` and `historySnapshot`. Both embed
`maxSeq`, so they change on every push (~760 B each time). That cost is
constant per push and does not grow with the answer, so I left it.
- **Layout probe.** Appending text to the last paragraph of a 24 KB
message and then reading layout costs 6–10 ms at 4× with the container
on the scroller, and 1.4 ms with it on the child. `contain: layout` on
rows, blocks or the preview, and replacing the flex columns with blocks,
made no difference.
- **iOS 18.4 Simulator Safari** (iPhone 16 Pro, same stream,
alternating; noisy because another simulator was running on the same
CPU):
- Painted frames over the stream went from 352–468 to 548–612. Frame p95
went from 230–507 ms to 186–196 ms, and typing p95 from 243–1,187 ms to
275–353 ms.
  - Frames over 100 ms did not change (44–53).
- WebKit does not have the container cost: both placements laid out in
under 1 ms.
- **Layout parity.** I compared the bounding rect of every text-bearing
element on main and on this branch: a thread, Settings, Settings ›
Appearance, home, Tasks and the Plugin Guide, at 1600×1000, plus home, a
thread and Settings at 500×900. They are identical except timestamp and
relative-date text, because the two fixtures were seeded minutes apart.

**Tests.** Each new test fails on main and passes here.
- `thread-timeline-delta.test.ts`
- A grown message row is sent as an `append` of only the new text; the
delta does not contain the old text.
- 300 random steps of growth, rewrites, added and removed keys and
nested arrays round-trip exactly.
- Patches that do not fit (append to a non-string, a missing key, an
unknown row) return `null`.
  - A `__proto__` key stays data.
  - A patch that changes a row's `id` or `kind` returns `null`.
- `thread-timeline-push.test.tsx`: a pushed row patch is applied, and a
patch that does not fit the held row leaves the cache unchanged and
refetches with the held tag.
- `markdown-incremental-pieces.test.ts`: settled pieces keep their
elements and directive mounts by identity when the body grows.
- `markdown-preview.incremental.test.tsx`
- While content grows, the DOM only gains nodes for new blocks; nothing
inside a settled block is mutated or removed. On main, settled links get
attribute rewrites on every body.
- A settled plugin directive renders once and does not re-run its
attribute effect.
- `scroll-container-queries.test.ts` (the guard above).

**Commands.**
- `pnpm exec turbo run typecheck --filter=@bb/app
--filter=@bb/server-contract --filter=bb-plugin-tasks
--filter=bb-plugin-plugin-api-docs`
- `pnpm exec turbo run lint` on the same packages: no new findings.
- `pnpm exec turbo run test --filter=bb-plugin-tasks
--filter=bb-plugin-plugin-api-docs`
- Targeted vitest: the server timeline delta, push, scrollback,
event-budget and pruning tests (78 passed); app markdown, timeline-push,
scroll-keeper, page-shell, RootComposeHome and ThreadTitleMentions
tests; and client-core `timeline-merge`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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