Skip to content

Window large responsive timelines - #1991

Closed
ymichael wants to merge 8 commits into
mainfrom
bb/perf-pr-5-window-large-responsive-timelines-thr_5tpw7hwyjg
Closed

ymichael wants to merge 8 commits into
mainfrom
bb/perf-pr-5-window-large-responsive-timelines-thr_5tpw7hwyjg

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

What was wrong

Very large thread timelines kept every top-level row mounted after older event pages loaded. Complex message, tool, diff, and Markdown subtrees therefore accumulated DOM nodes, listeners, style work, and memory even when they were far outside the viewport. A straightforward row window is unsafe here: replacing or realizing a row above the viewport changes scroll geometry, while a compensating scrollTop write during a touch gesture stops WebKit momentum.

What changed

Window top-level timelines after the measured crossover: 40 rows on compact viewports and 60 rows on wide viewports. The logical row list remains intact, but rows outside a 1,000 px overscan retain only lightweight measured-height wrappers. Rows needed for searched-message navigation, unread positioning, and active interactions stay realized; interaction pins are bounded.

Above-viewport realizations during an active scroll use measured placeholder donors so the swap is net-zero without a scrollTop write. Insolvent swaps wait for idle, residual corrections are suppressed during the gesture, late growth compensates only at idle, and estimate placeholders are re-budgeted from measured samples. Wide timelines use the same invariant. Searched-message scrolling now retries after the row is realized and again after placeholder re-budgeting so the target remains centered.

This is an app-only change in ThreadTimelineRows, its action tests, and useScrollToSearchedMessage. It preserves the older-page first-row height snapshot already upstream in #1975. Source review fixups beb7eaaa4 and f449a79df are folded into the donor-compensation stage. PR4's geometry batching commit 1d23f56a2, and all server/parser/query work, are intentionally excluded. There are no wire, daemon protocol, CLI, configuration, or documentation changes.

How you verified

The branch is based on exact fetched origin/main SHA 5f4f3dec733612fcf23defd8ac17c22462715e9d; the profiled head is e011f67cf2cf0471ecc24791c17cbfde69c3a046. Both phases restored the same stopped database snapshot (SHA-256 3647d3ceaefc12191d95588d88ea4e357737c6ed0c573a9d146222592b7723a3) and used the same production Turbo build and server settings.

Initial-load medians (p95 in parentheses), seven recorded repetitions after two warmups:

Production metric Baseline After Change
Desktop ready 1,524 ms (1,562) 1,304 ms (1,311) -14.4%
Desktop visible elements 3,010 (3,011) 2,087 (2,087) -30.7%
Desktop main-thread task time 1,437 ms (1,481) 1,211 ms (1,228) -15.7%
Desktop scripting / layout / style 1,102 / 49.9 / 85.5 ms 943 / 34.6 / 61.4 ms -14.4% / -30.6% / -28.2%
Desktop long-task total / max 698 / 355 ms 586 / 302 ms -16.0% / -14.9%
Mobile ready (30 rows, below cutoff) 1,268 ms (1,321) 1,222 ms (1,308) -3.6%
Mobile visible elements (below cutoff) 1,962 1,962 unchanged
Mobile main-thread task time 1,244 ms (1,278) 1,202 ms (1,287) -3.4%
Mobile long-task total / max 717 / 243 ms 668 / 231 ms -6.8% / -4.9%

After scrolling the largest thread upward until 110 logical rows were loaded and then back to latest content:

Interaction metric Baseline After Change
Desktop mounted rows / visible elements 110 / 4,260 28 / 2,213 -74.5% / -48.1%
Desktop task / layout / style time 1,231 / 315 / 530 ms 1,124 / 129 / 489 ms -8.7% / -59.1% / -7.7%
Desktop worst frame / long-task total 218 / 971 ms 158 / 547 ms -27.3% / -43.7%
Mobile mounted rows / visible elements 110 / 4,138 24 / 1,884 -78.2% / -54.5%
Mobile task / scripting / style time 1,155 / 279 / 447 ms 942 / 266 / 297 ms -18.4% / -4.7% / -33.5%
Mobile p95 / worst frame 10.2 / 217 ms 10.3 / 149 ms +1.0% / -31.2%
Mobile long-task count / total / max 6 / 734 / 209 ms 9 / 710 / 130 ms +3 / -3.3% / -37.8%

The ten-thread desktop sweep first activates windowing at 62 rendered rows (834 stored events): visible elements fall 2,835 -> 2,135, ready time 1,584 -> 1,406 ms, task time 1,556 -> 1,379 ms, layout 49.8 -> 40.2 ms, and style 161 -> 121 ms. Threads through 48 rendered rows remain on the unchanged path. The compact initial page has 30 rows and remains unchanged; its benefit appears after upward pagination crosses 40 rows.

The trace retains all 110 logical wrappers while mounted rows fall to 28 and page elements fall 4,260 -> 2,213. Windowing performs more, smaller swaps: layout calls rise 26 -> 96, but total layout falls 168 -> 145 ms and peak layout falls 148 -> 38 ms; UpdateLayoutTree total/peak falls 352/216 -> 292/151 ms; FunctionCall total stays 693 -> 689 ms while its peak falls 217 -> 161 ms. The trace's worst frame falls 234 -> 175 ms.

CDP memory counters were available but garbage-collection/document retention was noisy. At the end of the same scroll, desktop live heap/nodes were 48.1 MB/5,475 -> 43.4 MB/2,676; mobile was 46.5 MB/5,344 -> 53.3 MB/9,025 because detached rows remained uncollected. Visible element counts and trace work, rather than those nondeterministic counters, are the attributable memory/rendering evidence.

Production profiling used a seed-1 fixture with 12 seeded projects plus personal, 1,200 threads, 402,298 events, and 22,939 search segments on a MacBook Pro Mac16,6 (M4 Max 12P+4E, 48 GB), macOS 26.5.1, and Chromium 145. Viewports were 1440x1000 and 390x844, with 4x CPU slowdown and 80 ms RTT / 10 Mbps down / 5 Mbps up. Storage/cache was cleared at phase start, followed by a root warmup and two target warmups. Raw JSON, traces, call counts, logs, fixture metadata, and exact commands are in /tmp/bb-pr5-perf.d962Jb; superseded runs are isolated under its obsolete-* directories. No mbp-intel worker was available.

Browser QA on the final production build covered the largest thread, ten crossover threads, switching among three large threads, searched-message navigation, simulated streaming, and desktop/portrait/landscape/desktop resize. In a 91-row compact gesture, 34 above-viewport rows realized with 121 donor mutations and zero programmatic scrollTop writes during the gesture; scroll height changed only 6,941 -> 6,942 px from CSS-pixel rounding. Searched row 831 realized, flashed, and centered at 492 px. All responsive states returned exactly to bottom; placeholders were aria-hidden with zero focusable descendants. The streaming story produced 30 child-list and three text mutations, retained bottom anchoring in the bottom-anchored stages, and logged no errors. Compact drawers were untouched.

iOS 18.4 Simulator Safari rendered the final large timeline at its bottom without a visual failure. The local UI automation bridge could not drive a native Safari swipe, so native iOS momentum itself remains a manual-device limitation; the Chromium gesture instrumentation above is what proves no mid-gesture geometry write. DevBrowser's development-server diagnostic also passed with 91 logical rows, 24 realized rows, 67 placeholders, exact bottom anchoring, and no console errors.

Validation:

pnpm exec turbo run test --filter=@bb/app --force -- <5 focused timeline files>
  5 files, 51 tests passed
pnpm exec turbo run test --filter=@bb/app --force
  411 files, 3,152 passed, 3 skipped
pnpm exec turbo run typecheck --filter=@bb/app
  passed
pnpm exec turbo run build --filter=@bb/app --filter=@bb/server --filter=@bb/host-daemon --filter=@get-bb/plugin-sdk
  8 tasks passed

Fixes: no linked issue.

AGENT GENERATED: by GPT-5.6 Codex

SawyerHood and others added 8 commits August 19, 2026 18:01
During a scroll the windowing observer skipped its anchor compensation
and trusted native scroll anchoring, but WebKit has none. A placeholder
that realized above or over the viewport shifted visible content by the
placeholder-vs-real height delta, so the timeline skipped and jittered.

Now, while the scroll marker is set, only height-neutral updates apply
immediately: derealizations swap in their measured height, and
realizations fully below the viewport push layout downward only.
Realizations at or above the viewport wait in a pending set; when
scroll events stay silent past the idle delay, they flush through the
existing capture-anchor / flushSync / restore path, which can no longer
kill momentum because the scroll has stopped.

Co-Authored-By: Claude Fable 5 <[email protected]>
Waiting for full scroll idle made rows blank for the whole momentum
tail: iOS emits scroll events through the entire deceleration, so every
event pushed the idle flush out and everything the user scrolled up
into stayed empty until the scroll fully stopped.

Rows above the viewport now realize the moment they enter the margin,
even mid-scroll. The realized height delta is balanced against
placeholder donors that also sit fully above the viewport, in a second
synchronous commit in the same task, so the net height above the
viewport stays zero: nothing visible moves, no scrollTop write happens,
and momentum survives. Donors shrink topmost-first and self-correct
when they later realize or derealize. A row with no donor capacity
(near the top of the timeline) reverts to its unchanged placeholder and
keeps the idle-flush fallback with scrollTop compensation.

Co-Authored-By: Claude Fable 5 <[email protected]>
Placeholder estimates undershoot real row heights, so upward scrolling
drained the donor pool monotonically; once dry, every realization wrote
scrollTop and stopped WebKit momentum.

Two changes keep the pool solvent and the writes rare:
- Idle re-budgeting: track the running average of first-measured row
  heights, and once the scroll idles re-seed every never-realized
  placeholder to that average through the anchor-compensated path (a
  scrollTop write is free at idle). This refills drained donors and
  keeps the estimate budget tracking the timeline's real heights.
- Residual tolerance: a shortfall of 48px or less shifts content
  instead of writing scrollTop — a sub-threshold stutter reads better
  than a momentum stop.

Co-Authored-By: Claude Fable 5 <[email protected]>
The SlopCop-driven changes traded the momentum-preserving revert
fallback for mid-scroll scrollTop writes and tolerated sub-threshold
shifts, and let ResizeObserver rebalance donors during active scrolls.
All three mutate what the user sees mid-gesture, which reads as
snapping.

Restore the invariant: while a scroll is active, the only geometry
change is the exact net-zero donor swap. Everything else waits for the
idle pass:
- An insolvent realization reverts to its unchanged placeholder and
  mounts at idle with anchor compensation (brief near-top blanks, made
  rare by re-budgeting).
- Late content growth above the viewport compensates with a direct
  scrollTop nudge at idle only; during a scroll just the baseline
  updates.
- The pending-realize flush and the placeholder re-budget share one
  idle pass and one anchor-compensated commit.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ymichael

Copy link
Copy Markdown
Collaborator Author

Superseded by #2011, which preserves the top-level geometry work and combines it with recursive nested-row windowing, long-session bounds, fast-traversal deferral, and the default-off experiment gate so there is a single review surface.

@ymichael ymichael closed this Aug 20, 2026
ymichael added a commit that referenced this pull request Aug 20, 2026
## What was wrong

Long timelines kept every rich top-level row mounted after older history
loaded, and expanded delegation/turn details likewise kept every nested
row mounted. A long-lived client that streams across multiple threads
therefore accumulated DOM, rich markdown trees, observers, and row-local
interaction state even though almost all content was outside the
viewport.

The first prototype fixed the resting DOM size with a bespoke 826-line
virtualizer, but it added too much custom geometry and gesture policy to
land comfortably. Its cold full-history traversal also mounted each rich
row once, producing 4.96 s round trips and 66.3 ms p95 frames.

## What changed

Add the default-off `timelineWindowing` experiment using the existing
`@tanstack/react-virtual` dependency for range calculation,
variable-height measurement, scroll correction, and momentum-safe
updates. A thin timeline adapter retains only product policy:

- Window top-level lists at 60 rows on desktop or 40 on compact
viewports, and nested/bundle lists at 20 rows.
- Keep eight realized rows of overscan and use measured stable-row
heights for distant placeholders.
- Recursively window expanded turn and delegation details against their
own capped scroll root; collapsing a group unmounts its detail subtree
immediately.
- Keep last-row, unread-divider, searched-row, saved-scroll-anchor,
focused, and clicked rows available when they are outside the visible
range.
- Bound interaction pins at 24 and retained exact measurements at 2,000
for long-lived streaming sessions.
- Render cheap measured placeholders during high-velocity traversal,
then realize the settled viewport.
- Initialize nested virtualizers from the shared scroll element's
current offset so expanding or collapsing a nested list cannot reset the
parent scroll position.

The experiment-off path renders the existing full list. A small
`React.lazy` boundary keeps the 346-line TanStack adapter out of the
route closure until windowing is enabled and a list crosses its
threshold; the disabled app does not request that module.

The experiment is exposed in Settings, `bb settings experiment
timelineWindowing <true|false>`, system defaults, docs, templates, and
the built-in CLI skill. This does not alter the server/host-daemon wire
contract, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.

This PR supersedes #1991 with one experiment that covers top-level and
recursive nested rows.

### Complexity reduction

| Scope | Earlier prototype | This PR |
| --- | ---: | ---: |
| Gross additions | 1,856 | 1,370 |
| Net additions | 1,790 | 1,244 |
| Custom windowing implementation | 826 lines | 428 lines (adapter +
lazy boundary) |
| Runtime diff | — | +783 / -122 |
| Tests and docs diff | — | +587 / -4 |

The implementation is about 26% smaller in gross additions and the
custom windowing layer is about 48% smaller. TanStack owns the difficult
virtualizer mechanics; repository code owns the timeline-specific
behavior and experiment integration.

## How you verified

Final focused validation after rebasing onto current `origin/main`:

```text
@bb/app timeline windowing + scroll preservation: 3 files, 25 tests passed
@bb/app typecheck: passed
@bb/app lint: passed with 0 errors (pre-existing warnings remain)
@bb/app production build: passed
bundle budget: boot 425.2 / 428.0 KiB Brotli; route closure 654.0 / 655.0 KiB Brotli
```

A full app run before the lazy-boundary-only follow-up passed 3,102
tests with three skipped. The replacement GitHub Actions run validates
the exact final revision.

Dev Browser QA used a production-derived SQLite copy containing 620,222
events across 504 threads. The benchmark thread contained 38,946
underlying events, 577 projected top-level rows, and about 134.8k px of
history.

Matched full-history benchmark:

| Metric | Control | Windowed | Change |
| --- | ---: | ---: | ---: |
| Elements at rest | 16,450 | 1,420 | -91.4% |
| DOM nodes at rest | 26,380 | 1,998 | -92.4% |
| Used JS heap | 162.9 MiB | 100.3 MiB | -38.4% |
| Embedder heap | 44.0 MiB | 17.4 MiB | -60.5% |
| Style flush p50 | 38.7 ms | 7.0 ms | -81.9% |
| Style flush p95 | 42.5 ms | 8.7 ms | -79.5% |
| Full traversal | 1,168 ms | 1,187 ms | +1.6% |
| Frame p95 | 9.9 ms | 10.0 ms | +0.1 ms |
| Frames over 32 ms | 0 | 0 | unchanged |
| Peak mounted top rows | 577 | 13 | -97.7% |

Real-data nested QA expanded a 103-row turn. It mounted 39 rows at the
header and 46 while scrolled through the middle (visible range plus the
pinned final row), rather than retaining all 103. Expanding and
collapsing it preserved the shared scroll position exactly at
`scrollTop=41900`. Compact-viewport QA also crossed the 40-row threshold
and windowed correctly.

The CLI toggled the experiment off and on against the same development
server. With 188 loaded rows, the disabled path mounted all 188 with no
virtual spacer and did not request the adapter module; the enabled path
mounted 15 with a virtual spacer preserving the full scroll geometry. No
timeline runtime errors were observed.

No enrolled `mbp-intel` host was available for a hardware-specific
rerun; the connected machines were M4 and M5. The benchmark above was
run on the production-derived dataset on the M4 host.

Fixes: no linked issue.

> AGENT GENERATED: by GPT-5.6 Codex
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.

2 participants