Repository navigation
Conversation
Rows mounted while scrolling no longer read layout during the commit. Row heights, message overflow toggles, and markdown table geometry are measured in one read-then-write ResizeObserver batch after the browser's own layout, which then reconciles the reading position once. A scroll that uncovers the viewport mounts its rows in the same frame's animation frame callback instead of with flushSync inside the scroll event. The window is a key range, so rows appended past an end-reaching window or inserted inside it mount in the same render. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reconciling the reading position moved from the prepend's commit to the ResizeObserver step after layout, so the post-commit sentinel check saw the uncorrected position and loaded a second and third page. The check now runs after that frame instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/stop-forced-layout-when-timeline-rows-mount-on-s-thr_y96yv34ywx
branch
November 17, 2026 03:50
This was referenced Nov 17, 2026
Merged
ymichael
added a commit
that referenced
this pull request
Nov 17, 2026
## Human comments ## What was wrong A `ResizeObserver` callback runs after layout and before paint, but React applies a plain `setState` from that callback in a later task, after the browser has painted. Any layout derived from a measured size therefore painted one frame with the old layout at the new size. #7497 (context card), #5067 and #6488 (composer prompt stack) each fixed one instance by hand with `flushSync`. A survey found about 30 more sites with the same pattern: TOC show/hide, header action overflow, message action row count, "Show more" toggles, File Preview header buttons, panel size limits, resource toolbar, overflow fades, and others across `apps/app`, `shared-ui`, plugins and `apps/web`. Measured in headless Chrome, crossing a width threshold 10 times: | How the measured size reaches React | Frames painted with the old layout | |---|---| | plain `setState` in the observer | 10 of 10 | | `flushSync` | 0 | | `useSyncExternalStore` | 0 | ## What changed - **One path for element sizes.** `observeSharedResize` moved from `apps/app/src/lib` to `@bb/shared-ui/lib/shared-resize-observer`, which also makes it a component-registry item for forkable plugins. It keeps the one-`flushSync`-per-batch writes and `settleAfterSharedResizeWrites` that #7612 added, so React state from a resize renders before paint. It now also: - accepts a list of targets and runs each registration once per batch; - returns a no-op where `ResizeObserver` is missing. - **`useMeasuredValue(target, read, initial)`** in `@bb/shared-ui/hooks/use-measured-value` for the simple ref-to-value case. It replaces usehooks-ts `useResizeObserver` in the git plugin. - **Lint guard.** `bb/no-raw-resize-observer` in `scripts/oxlint-plugin.mjs` rejects `new ResizeObserver` and usehooks-ts `useResizeObserver` outside the shared module, apart from tests and stories. Two files are exempt in `.oxlintrc.json` because their own callback batching only writes the DOM and doesn't set React state: - `scroll-position-keeper.ts`: the timeline engine's own observer, which reconciles once per batch. - the landing hero feed animation in `apps/web`. - **Migration.** 58 sites across `apps/app`, `shared-ui`, 13 plugins and `apps/web` now use the shared path. Read steps only read layout; write steps write the DOM and set state. - The `flushSync` workarounds in the sidebar header slot and context card are gone. - The composer prompt stack keeps its inner `flushSync`, because `positionKeeper.remeasure()` must run after the new height commits. - #7612's new call sites (timeline row heights, `useIsOverflowing`, markdown table geometry) import the moved scheduler. - TOC visibility and the background-commands card now measure on first paint instead of waiting for the observer's first callback. - `ThreadDetailHeader` keeps a narrow/wide flag instead of the pane width, so a divider drag no longer re-renders the header every frame. - The component registry is regenerated: a new `shared-resize-observer` item, and expandable-text, question-form, resource-pagination and resource-toolbar now depend on it. No wire, CLI or user-facing configuration changes. ## How you verified - New tests in `packages/shared-ui/src/lib/shared-resize-observer.test.tsx`: - state written by a resize renders before the observer callback returns; - `useMeasuredValue` measures on mount and on each resize; - a registration with several targets runs once per batch. - The first two fail with the `flushSync` batching removed. - The lint rule flags the original code of the past fixes at the exact line each one changed: `PluginThreadContextCard.tsx:371` (#7497), `FollowUpPromptBox.tsx:668` (#5067) and `FollowUpPromptBox.tsx:685` (#6488). - `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`: 180/180 passed. - `pnpm exec turbo run test` on every affected package passed after the fixes below: - Two `@bb/app` tests failed because their `ResizeObserver` stubs called the callback without entries; I fixed the stubs. - These failed under load and passed on a rerun alone: - `bb-plugin-connect` `connect.test.ts` (72/72) - four `@bb/server` files (131/131) - `CommandPalette.test.tsx` - `marketplace-exposure.test.tsx` - `plugin-guide.test.ts` failed because an interrupted bundling run had left a gitignored `plugins/.bundled-stage-*` copy of navigation. Removing it made it pass. - Live, with `pnpm start:worktree`, the experiment on and the context card pinned, I recorded every resize frame while opening and closing the right panel twice at 1440, 1600 and 2560px: - main before #7497: 1 stale frame per band crossing; - this branch: 0 at every width. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Rows that mounted while scrolling forced synchronous layout. When a scroll uncovered the viewport,
TimelineWindowedItemscommitted the new window withflushSyncfrom inside the scroll event. During that commit the new rows read layout before the browser had laid them out: the row ref readgetBoundingClientRect,useOverflowMeasurementreadscrollWidth/scrollHeightin a layout effect, markdown tables calledgetComputedStyleto find their clip ancestor (a full layout here, because the scroll area is a size container), and the list's own layout effect reconciled and re-synced the window. Each of these components already had a ResizeObserver that reports the same sizes. At 4× CPU, one fling spent about 1.3–1.6 s in forced style and layout, nearly all of it inside the scroll handler (perf hotspot 2 in the Nov 15 client audit). The class is "read layout while rows mount", and it is related to #4396 and #7332.What changed
useIsOverflowing, which replaces the tri-stateuseOverflowMeasurement), and markdown table geometry are now registered with the existing read/write schedulerobserveSharedResize(lib/shared-resize-observer.ts). They are no longer three separate observers plus mount-time reads. In one batch, after the browser's layout, the scheduler:flushSync, so a "Show more" toggle is still correct before the first paint,settleAfterSharedResizeWrites). The timeline uses this to reconcile itsScrollPositionKeeper(reconcileAfterLayout) a single time.reconcile+syncWindowlayout effect is gone; it only mounts the held row now.flushSyncin the scroll handler. An uncovered viewport queues its window for the next animation frame callback and commits it there. Scroll events fire just before animation frame callbacks, so the rows still mount in the frame the scroll lands in, before that frame's layout. Updates in the same frame coalesce.useAutoLoadOlderRows): the post-commit sentinel check now runs after the frame (animation frame, then a task), because reconciliation happens after layout. Before this fix, iOS loaded 2–3 pages per scroll to the top instead of 1: the check read the position before the prepend had been compensated.test/fake-flow-layout.tsmodels a frame (frame()= animation frame callbacks, then ResizeObserver delivery), andtest/resize-observer-deliveries.tsdelivers observer entries for component tests. Tests that relied on the synchronous mount read now deliver the observer before asserting.docs/timeline-pagination.mddescribes the new path.No wire, CLI or configuration changes.
How you verified
Invariant test (
ThreadTimelineRows.mount-layout-reads.test.tsx). It renders realThreadTimelineRows(long user messages, tables, code fences, tool rows) in a realBottomAnchoredScrollBodyand records every layout-reading API, as sets rather than budgets:On main, both cases fail: rows mount inside the scroll event, and the append commit reads layout 29 times (
scrollWidth,clientWidth,scrollHeight,getBoundingClientRect,scrollTop, ...).useAutoLoadOlderRows.test.tsxadds "checks the sentinel after the frame reconciles a prepended page, not inside its commit", which fails on main's hook.Real built app. I measured on the seeded fixture: 500 threads, a 9,664-item timeline, headless Chrome at 1600×1000. Main's and the branch's dists were served through proxies in front of one server, and the variants alternated run by run on a loaded machine. Medians of 3 runs:
At 1× CPU, forced style+layout fell to roughly zero: fling up 89 → 9 ms, fling down 51 → 0 ms, wheel up 0 → 0 ms. Frame percentiles were identical at 1×.
Frame percentiles barely move at 4×. Each frame still has to render and lay out the roughly 26 rows a 3,000 px jump mounts; that work now runs once, in the browser's own layout pass, instead of as forced layout inside the scroll handler. I also tried mounting only ±2 rows of overscan while a scroll is active and widening after it settles. That gave no p95 win (fling up 108 vs 107 ms, wheel up p95 worse), so it is not in this PR.
A spacer-exposure probe (IntersectionObserver on the window spacers) saw no blank viewport in either build, and neither build fired ResizeObserver loop errors.
Re-tracing the branch shows the scroll handler with no layouts. The remaining forced work is the style recalc that hover invalidation leaves dirty when the scroll event arrives (~12 ms per event at 4×), plus the one re-layout after toggles and table variables are written in the observer batch.
iOS Simulator Safari (iPhone 17 Pro, iOS 26.5; windowing is off on iOS WebKit), through a probe injected by the proxy. Positions are sampled after the app's observers, i.e. what paints:
The fling jump detector flags frame-to-frame deviations over 48 px. The swipes include a reversal, which triggers it on main too.
Parity. On the 3k-item thread, both builds render the same "Show more" toggles, faded bodies, table width/breakout variables, row count, scrollTop and scrollHeight on first load.
Tests.
vitest run src/components/thread/timeline/ src/components/ui/ src/lib/shared-resize-observer.test.tsx src/views/thread-detail/: 118 files, 1,452 tests pass.pnpm exec turbo run typecheck lint --filter=@bb/apppasses; the one lint warning inTimelineWindowedItems.tsx(renderItemreceivingitemRef) is also on main.apps/app/.ladle/tests/timeline-scrollback.mjsfails identically on main and on this branch in headless dev-browser ("Scrolling up loaded nothing"). The story's older-page request reaches the Ladle server (404) instead of the story's fetch stub, so I could not use it here.🤖 Generated with Claude Code