Skip to content

Studio: mount only the messages near the reader in long chats - #17504

Merged
danielhanchen merged 24 commits into
unslothai:mainfrom
wasimysaid:perf/long-chat-thread-window
Nov 12, 2026
Merged

danielhanchen merged 24 commits into
unslothai:mainfrom
wasimysaid:perf/long-chat-thread-window

Conversation

@wasimysaid

@wasimysaid wasimysaid commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

A long chat costs the Linux app in proportion to its length, on every interaction. All of that cost is on the web process main thread (script, style recalc, IntersectionObserver); the raster and compositor threads are close to idle, with Glass on or off. main mounts every message and never unmounts one, so opening Settings, typing a key, switching pages and coming back each pay for the whole thread.

This mounts only the rows near the reader. Two spacers stand in for the rows on either side, so the thread costs what is on screen and not its length. On all platforms, not only WebKitGTK.

Numbers

Native Tauri app, WebKitGTK 2.54.2, GPU compositing path, minified builds of main (9dc37ed) and this branch on top of it, measured in the same session on the same machine, in a nested offscreen KWin session at 60 Hz. The chat is the 600-message, ~911k-token scroll repro. Solid theme unless noted. "Longest freeze" is the longest gap between two animation frames after the click; medians of 3.

xychart-beta
    title "Longest freeze in a 600-message chat, ms (bars: main, line: this PR)"
    x-axis ["Settings open", "Settings close", "Model picker open", "Run settings open", "Run settings close"]
    y-axis "ms" 0 --> 300
    bar [273, 93, 105, 84, 72]
    line [109, 37, 49, 27, 25]
Loading
xychart-beta
    title "Seconds (bars: main, line: this PR)"
    x-axis ["Freeze returning from Model hub", "Jank in the 25 s after opening the chat", "Main-thread CPU in those 25 s"]
    y-axis "s" 0 --> 16
    bar [5.06, 13.83, 15.88]
    line [0.09, 0.43, 1.00]
Loading
600-message chat main this PR
Messages mounted 600 (599 with their bodies parked) 1-5, about 2,300 elements in the document
Web process memory, solid / Glass 3.6 / 2.9 GB 1.6 / 1.0 GB
Settings open, longest freeze, solid / Glass 273 / 287 ms 109 / 134 ms
Settings close 93 ms 37 ms
Model picker open 105 ms 49 ms
Run settings open / close 84 / 72 ms 27 / 25 ms
Returning to the chat from Model hub 5.0-5.3 s freeze 0.09-0.18 s
Opening the chat: first rows on screen 944 ms 379 ms
Opening the chat: jank over the next 25 s 13.8 s 0.43 s
Opening the chat: main-thread CPU over those 25 s 15.9 s 1.0 s
Typing 33 keys, web process CPU 0.65 s 0.36 s

A real 300k-token agent chat (54 messages, 98,000 px tall) behaves the same on this branch: one row mounted, Settings open 104 ms, model picker 43 ms.

Glass adds 14-25 ms to Settings open in both builds and nothing measurable elsewhere. WEBKIT_SKIA_MSAA_SAMPLE_COUNT 0 and 4, WEBKIT_LAYERS_TILE_SIZE and DDL off with GPU painting threads made no measurable difference under Glass (DDL off was worse on scroll), so none of them is set here.

What changed

The thread window (thread-window.ts for the maths, progressive-messages.tsx for the DOM and React side).

  • Rows mount within 2,000 px of the viewport and unmount past 4,000 px. Rows stay in normal flow between a top and a bottom spacer; nothing is positioned, so an append adds one node and touches nothing else.
  • A row that has rendered keeps its measured height. One that has not is estimated from the lines its text will render (so code is not sized as a paragraph) times what a line has taken in the rows measured so far, per role. On the agent fixture the scroll range is within 1.4% of the fully mounted thread before any row above the fold has rendered.
  • A height surprise above the reader is absorbed by the top spacer and not by scrollTop, so wheel momentum and a held scrollbar thumb are left alone. The slack is folded into scrollTop once input is quiet.
  • A thread is windowed by estimated height (40,000 px and 8 messages), not message count: an agent chat is often a few turns of very long replies.
  • Readers of the whole document still get it. Find, print and select all mount every row (progressively, pausing for scroll and input), and the window reopens when they are done. Each pass adds up to 32 rows each way but at most about 20,000 px of estimated height, so very long replies do not land 32 to a commit. Turn-rail jumps mount the target row directly.
  • Rows publish aria-setsize and aria-posinset while the thread is windowed.
  • A copy whose selection runs across a spacer mounts the missing rows before the clipboard is read, so the copy is never short.
  • The focused row, a row being edited, playing media, selected text and the reply being streamed are never unmounted. A row like that which the window moves away from stays mounted where it is, as a pin with a spacer on either side, so a scrollbar drag to the other end of the thread keeps an unsaved edit and does not mount what lies between.
  • A thread hidden behind another route does nothing: it has no boxes to measure. It does not count as a pending mount either, so it cannot hold up a reader of a thread that is on screen.

Root layout. The layout re-renders when Settings opens (its open flag gates the route shortcuts), and that re-rendered the sidebar, the navbar and the chat page. Those now bail out.

Composer. A keystroke re-rendered 297 components under the composer. The toolbar controls that never read the text are kept out of it, which leaves 68, and the input handler goes from about 3.5 to 1.9 ms per key (instrumented build). The draft, queue and submit logic is untouched.

The recorded "do not virtualize the message list" result

tests/studio/studiobench/CONTRIBUTING-perf.md records a virtualized list as built, measured and rejected. This PR has not been run through studiobench, so that record is left as it is. Each failure it lists was checked with other instruments:

  • First send into a freshly opened thread got slower (their mechanism: an end-anchored list re-renders and re-positions every mounted row, 60 ms of style recalc against 14). Here rows are in flow. Chromium, production build, 400 agent-style messages, medians of 3 fresh pages, windowed against the same build holding every row mounted: main-thread task time in the first 250 ms after send 62 ms against 243, style recalc 3.0 ms against 3.3, longest frame gap 22 ms against 63, whole 20-chunk stream 93 ms against 475. The second send costs the same as the first.
  • It lost the thread on an action. Model picker, Settings, leaving for Model hub and returning, and switching chats all keep the thread, in the native app.
  • Accessibility. aria-setsize / aria-posinset are published, as the bench's windowed readiness gate requires.
  • Select-all copy was truncated. The copy carries the whole thread: 1,985,097 characters on both builds in the native app, and equal to the fully mounted thread in the new gate.
  • Scroll extent. 1.4% from the mounted thread on open, against the bench's 10% allowance.

A studiobench A/B with a null control and --windowed-arm is still owed before the perf claim meets that document's bar.

Trade-offs

  • Select all then copy at once on a very long chat is slower. The rows have to exist to be copied. On the 911k-token chat that is a 14.7 s freeze against 6.2 s on main. main spends that time when the chat opens instead (about 15 s of background mounting, every time). Waiting after Ctrl+A lets it fill in the background, in passes of at most about 20,000 px of estimated height so input stays live while it runs: on 60 replies of about 5,000 px in Chromium the longest frame gap is 159 ms, against 1,097 ms with 32 rows to a pass, and the whole mount takes 4.5 s against 3.8 s. Serving that copy from the message store would remove the freeze but would copy markdown source and not rendered text; not done here.
  • Find covers a very long chat over several seconds (about 15 s on the 911k-token chat on WebKitGTK). The page stays responsive and matches appear as rows land.
  • React state inside a row that scrolls far away is lost, for example a reasoning block the reader expanded.
  • One very long message is still one row. A chat made of a few huge replies gains less.
  • A fling far beyond real input speeds can outrun the window (seen at 187,000 px/s in Chromium; covered at 75,000 px/s). It catches up within a few frames of stopping.

Tests

  • tests/studio/playwright_thread_window.py is new and added to the frontend CI job. Structure only, no timings: the DOM does not grow from 80 to 400 messages, ordinals are published, the scroll range matches the mounted thread, wheeling to the top the window catches up after every step and passes every message, a reader at rest does not move, a jump lands on rows, a focused row keeps its node and its focus across jumps to both ends and back, a copy across unmounted rows is complete and the window reopens after it, a hidden thread mounts nothing and is not counted as pending, a streamed reply lands at the tail, and no pass of a select-all mount exceeds the height budget. Passes in Chromium and Firefox.
  • smoke-thread-weight.html and smoke-heavy-thread.html measure what a whole thread costs in the DOM, so they now hold every row mounted (?window=1 on the first leaves the thread as the app opens it). The long-thread gate's area matrix and WebKit leg wait on the published thread length.
  • thread-window.test.ts covers the window maths; progressive-mount-glue.test.ts is rewritten for the new glue.
  • Frontend unit suite: 15,694 of 15,707 pass. The 12 that fail are locale and date formatting tests that fail the same way on main on this machine.
  • All 24 browser gates the frontend CI job runs pass locally in Chromium (Firefox too where the script takes engines), including the long-thread gate with its area matrix, heavy thread, find in page, chat autoscroll, stream pacing and tool activity. After rebasing onto current main, the typecheck, the unit suite and the window, long-chat, find, autoscroll, stream-pacing and composer gates were run again. After the review fixes (pinned rows, hidden threads, the full-mount budget), the typecheck, the unit suite and the window (Chromium and Firefox), long-thread, heavy-thread, long-chat, find, autoscroll, progressive-rows and stream-pacing gates were run again.
  • Native app: wheel scrolling up and down keeps the viewport covered with the reader's row within 0.1 px; jumps to the top, middle and bottom land on rows; turn-rail jumps, find, copy, Settings, the model picker, leaving for Model hub and switching chats were exercised on the 600-message chat.
  • Not run: the Playwright WebKit legs (WebKit cannot launch on this host; the native WebKitGTK app was the WebKit check), and studiobench.

Related to #16603. Builds on #16854; the WebKitGTK body parking from that PR is left in place and now only ever sees the few mounted rows.

Before / after in Studio

Same 300-message chat, seeded through the chat history API into two fresh Studio installs (merge base 31d7eb47e on the left, this branch at 935866a96 on the right), at the bottom of the thread as it opens and at the top after wheeling up.

At the bottom: both show Reply 148 and Reply 149. The base mounts all 300 messages (19,141 elements); this branch mounts 11 rows (1,856 elements) and publishes aria-setsize="300".

Bottom of a 300-message chat, base vs this branch

At the top: both show Prompt 0 through Reply 1. The base still holds 300 rows (20,101 elements); this branch holds 19 (2,282 elements).

Top of a 300-message chat, base vs this branch

A long thread mounted every message and never unmounted one, so opening a
dialog, typing and switching pages all paid for the whole thread on the web
process main thread.

Rows now mount within reach of the viewport and unmount past it, in normal flow
between two spacers sized from measured heights (estimated from rendered lines
until a row has been measured). A height surprise above the reader is taken by
the top spacer rather than scrollTop. Find, print and select all still mount
every row, a copy across unmounted rows mounts them first, and windowed rows
publish aria-setsize and aria-posinset.

The thread harness pages hold the full mount for the gates that measure a whole
thread in the DOM, and playwright_thread_window.py covers the windowed thread.
…renders

The layout re-renders when Settings opens, because the open flag gates the
route shortcuts, and that re-rendered everything under it. Components without
props are now one element made once, and the chat page is memoized.
The composer renders on every keystroke because it owns the draft. Its toolbar
controls never read the text, so their elements are kept between renders, and
the queue thread ids and queue context keep one identity. A keystroke goes from
297 component renders under the composer to 68.
@danielhanchen danielhanchen self-assigned this Nov 11, 2026
@wasimysaid

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T00:20:17.760798Z e44f16d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member

studiobench CI / Real-path session, every action ran fails on this PR before any action runs:

waiting: 1/18 mounted, outstanding ['all_messages_mounted', 'end_present']
cell FAILED: ThreadNotReady: the thread was not ready in full mode: all_messages_mounted, end_present (mounted 1 of 18; aria-setsize 18; aria-posinset 18..18 on 1 of 1 rows, 1 distinct; last row 'assistant'; 0px from the bottom)

Two separate things show up here:

  • all_messages_mounted is expected to go false with this change: the bench's readiness check (tests/studio/studiobench/runtime/readiness.py) runs in "full" mode, which assumes every message is in the DOM. It already has a windowed mode that drops that condition (see test_studiobench_readiness_live.py around line 530), so the bench needs to run windowed for a virtualized thread.
  • end_present failing looks like a real problem in the PR rather than the bench: only one row (posinset 18 of 18) is mounted while scrolled to the bottom, and the check that the end of the thread is rendered still does not pass. With 18 messages, the rows near the reader should be mounted, not just the last one.

So the fix is likely both: switch the bench to its windowed readiness for this thread, and make sure the window around the bottom mounts more than a single row.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a0e40698d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…ound a full-mount pass by height

Pinned rows. A row with focus, an open edit, playing media or selected text was
only protected from the trim. A scrollbar drag, a turn jump and the window
re-opening after a full mount all replace the window outright, and took the row
with them; the reply editor is uncontrolled, so its draft was gone when the row
came back. Such a row now stays mounted where it is, as a pin outside the
window with a spacer on either side, instead of the window stretching to it
(which also kept every row between a focused button and the reader mounted).
Spacers are keyed by where they sit among the rows, so React never moves a
row's node past one, and they are sized before any layout effect runs: a spacer
node created by a commit had no height yet, and a row reading layout in its own
effect let the browser clamp scrollTop to a thread a few rows long.

Hidden threads. A thread hidden behind another route stops at its no-boxes
guard, so a full mount it was in the middle of never finished and it counted as
pending for good: the turn rail of every Compare pane waited on it. A hidden
thread is no longer pending or withholding, answers a request for every row at
once, and lets go of readers already waiting. A full mount nobody is waiting
for any more (find closed half way) is dropped instead of finished.

Select all. A full-mount pass added up to 32 rows each way whatever their
height, which with very long replies is a second of layout in one commit. A
pass now adds at most about 20,000 px of estimated height, and always one row.
Chromium, 60 replies of about 5,000 px: longest frame gap 1,097 ms to 159 ms;
the whole mount takes 4.5 s where it took 3.8 s.

The window gate's wheel sweep waits for the window to catch up after each step
instead of asserting coverage on every frame, which measured the runner. It
gains checks for a pinned row across jumps, a hidden thread's pending count and
the height of each full-mount pass.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A window at the tail also mounts the prompt its reply answers, so a reply taller than the
keep distance no longer leaves the latest exchange half mounted (studiobench's windowed
readiness requires it). Rows are matched by message id: a prompt being edited renders as an
EditComposer with no data-role and was invisible to measurement and pinning. A spacer in view
is restored synchronously instead of behind a transition, heights reset on a column width
change, print mounts over an in-flight commit, select all ignores a hidden thread, a held
selection's end is rechecked, a remounted prompt does not replay its arrival animation, and
rows carry role=article with their ordinals. The studiobench workflows declare the windowed
arms.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…in the thread window

Spacers carry the KaTeX equation counter increments of the rows they stand for (counted in
the DOM once a row has rendered, estimated from its text until then), so page-wide equation
numbers no longer shift as the window moves. A copy across a spacer rebuilds its range on the
rows the spacer stood for, read after the full mount: a spacer keyed by a pin is replaced by it,
and a detached node made setStartBefore throw. A mounted row that shrinks (a collapsed code
block) wakes the window, so a bared spacer is filled without a scroll.
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 11, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ber code block views

A scroll extends the full-mount pause only within a few seconds of the reader's own input, so
the autoscroll following a stream no longer holds Find off until the reply ends. Rows holding
an iframe (an inline MCP app with its bridge port and unsaved state) stay mounted like an open
edit. A code block's own wrap and expand choices are remembered by language and code, so a row
the window remounts comes back as the reader left it.

[skip ci]
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 11, 2026
@unslothai unslothai deleted a comment from wasimysaid Nov 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 11, 2026
@danielhanchen
danielhanchen merged commit d6841bb into unslothai:main Nov 12, 2026
danielhanchen added a commit that referenced this pull request Nov 12, 2026
…ck (#17571)

## Summary

`studiobench CI` (`Real-path session, every action ran`) has failed on
main since #17504, and so have `Merge base vs head` and `Merge base vs
itself, the null` on PRs that touch the thread (e.g. #17565):

```
thread_reopen: ran EXPECT FAILED -- the reopened thread never reached a ready state: the thread was not ready in windowed mode: pin_settled (mounted 8 of 25; aria-setsize 25; aria-posinset 18..25 on 8 of 8 rows, 8 distinct; last row 'assistant'; 0px from the bottom)
```

#17504 switched these jobs to the windowed readiness gate
(`--windowed-arm`), which is the only mode that checks `pin_settled`.
That condition read "the autoscroll is still pinning" as
"`--aui-scroll-stabilizer` is set on the viewport". But
`use-intent-aware-autoscroll.tsx` leaves the stabilizer's last value in
place as residual padding once the follow window ends, and drops it only
when the user scrolls up ("Drop residual stabilizer padding once the
user scrolls up so the bottom stays flush"). So a thread that has
finished pinning can keep the property for as long as the reader stays
at the bottom, and the gate times out on a page that is otherwise ready
(in the log above, every other condition held for the whole wait).

This is not caused by the windowing itself. The null control on #17504
ran the merge base (fully mounted, before #17504) on both sides and
failed the same way:

```
cell FAILED: ThreadNotReady: the thread was not ready in windowed mode: pin_settled (mounted 18 of 18; aria-setsize None; ...; 0px from the bottom)
```

The app behaves as designed, and #17504 is right to run the windowed
gate. The gate's reading of the stabilizer is what is wrong.

## Change

- `tests/studio/studiobench/runtime/readiness.py`: the probe also
returns the stabilizer's value. `pin_settled` holds when the property is
absent, or when it carries the same value as on the previous probe and
the page has settled (same mounted count, element count and scroll
height). A value that is still changing, or a page whose height is still
moving, still counts as mid-pin, and the gate still needs its
consecutive settled samples before it passes.
- `INTERFACES.md`: the `pin_settled` row says the same.
- No app code changes, so nothing changes for Studio or Desktop users.

## Guard

New `test_residual_stabilizer_padding_settles_the_pin` in
`test_studiobench_readiness_live.py`:

- residual padding unchanged across two settled probes passes;
- the first probe, a changed value, or a moving scroll height does not
pass;
- a cleared stabilizer passes.

With the old `pin_settled` line, the test fails.

## Testing

- `test_studiobench_readiness_live.py` (including its live browser
cases), `test_studiobench_thread_reopen_gate.py`,
`test_studiobench_windowed_parity.py`,
`test_studiobench_completeness_gate_rows.py`: 142 passed.
- This PR's own `studiobench CI` run is the end-to-end check.
danielhanchen added a commit that referenced this pull request Nov 12, 2026
…hread (#17577)

## Summary

`Parity verdict, scored against the null` (`studiobench-ui-parity.yml`)
fails on PRs that touch the Studio frontend, depending on the run (seen
on #17571, and earlier on #17504's own run):

```
outputs/parity-result: TOO LITTLE COMPARED: 12 of 32 pair(s) carry a verdict, below the floor of 16.
```

Every pair it could not score says the same thing:

```
cell r100K.base.rep0 FAILED its completeness gate: the head of the thread mounted, but coverage of the middle was NOT ESTABLISHED: 1 of 18 ordinals never mounted, but consecutive stops of the gesture did not overlap, so rows between two stops were never in view.
```

Since #17504, the thread mounts only the messages near the reader.
Before an arm's actions are scored, `probe_thread_completeness` scrolls
to the top to confirm every message can still be reached. It moves in
steps of 2,000px, but a windowed list mounts little more than the
viewport, which is about 700px in CI. A short user message sitting
between two tall replies can fall between two stops, so its ordinal is
never seen. The harness then correctly refuses to call that data loss
and marks coverage as unmeasured, and every pair in that cell is dropped
from the verdict. When enough cells hit this, the run falls below the
comparison floor.

The app is fine here: whether the probe sees that row depends on where
the 2,000px stops land, not on what the arm mounts. #17504 is right, and
the parity gate is right to refuse a verdict it cannot back. The probe's
step is what is too coarse.

## Change

- `tests/studio/studiobench/runtime/readiness.py`, `TRAVERSE_JS`: on the
way up, a step is at most 3/4 of the viewport's height, so each stop
shares at least one row with the one before it and the sweep is
continuous. The distance budget (`steps * step_px`, 800,000px by
default) stays the same, so the tallest rung still reaches the top, and
the walk still stops as soon as it gets there. The way back down keeps
the old step, since nothing is recorded from it.
- The probe now reports the step it actually used as `traverse_step_px`.
- No app code changes.

## Guard

`test_a_virtualised_thread_passes_the_completeness_probe` used to pin
the coarse default ("the default 2,000px step jumps straight past this
2,160px thread, so coverage is unmeasured"). It now asserts that the
default step is capped to 300px on the fixture's 400px viewport, that
the sweep is continuous, and that coverage is complete. With the cap
removed, it fails. The tests that check a lost middle is still caught
(`test_a_thread_that_lost_the_middle_...`) and that an unreached top is
still unmeasured are unchanged and pass.

## Testing

- `tests/studio/studiobench/runtime/selftest/` (including the live
browser cases), `test_studiobench_thread_reopen_gate.py`,
`test_studiobench_windowed_parity.py`: 411 passed, 1 skipped.
- This PR's own `studiobench-ui-parity` and `studiobench CI` runs are
the end-to-end check.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 12, 2026
bjornts added a commit to bjornts/unsloth that referenced this pull request Nov 13, 2026
Mount ChatSkillsDialog through useMemo like the other composer dialogs (unslothai#17504).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…are long-chat cost with the base build in CI (#17597)

## Problem

#17504 mounts only the messages near the reader. A window slide that is
not urgent goes out as a React transition, and every streamed chunk is a
synchronous store update, so React restarts that transition from the
root on each chunk. A slide issued while a reply streams therefore
re-rendered its rows (markdown, KaTeX) for every chunk and landed only
after the reply ended. A reader who scrolled up during a reply looked at
an empty spacer until it finished, and the wasted renders showed up as
main-thread time:

- studiobench standard 100K, base (main before #17504) vs main with
#17504: `stream_cost_ms_per_kchar` 229 -> 744 (+226%), `stream_busy_pct`
6.4 -> 19.6, null-controlled.
- Within studiobench, all of it sits in the streaming window right after
`scroll_during_generation` parks the reader away from the reply (blocked
3241-3410 ms per 8 s vs 328-374 on base); windows where the reader
follows the reply were at or below base.

## Fix

Windowing stays; only what happens while a reply streams changes
(`progressive-messages.tsx`, `thread-window.ts`):

- A slide that can wait is held until the reply pauses (no chunk for 1
s, `TailPulse`), instead of starting a transition that cannot land.
- A spacer coming into view is still committed synchronously in the
frame that shows it.
- A transition already in flight when a stream starts is finished
synchronously.
- A full mount a reader is waiting on (find, print) goes in small
synchronous passes during a stream.
- The reply being written is not re-measured on every chunk (each chunk
moved the height estimate and every spacer).

## Results

studiobench standard 100K, 4 reps, null-controlled, base = main before
#17504, treatment = this fix:

| metric | base | this PR | verdict |
|---|---|---|---|
| stream_cost_ms_per_kchar | 260.9 | 253.3 | within noise (main with
#17504: +226%) |
| stream_busy_pct | 7.2 | 6.7 | within noise |
| thread_reopen.reopen_ms | 2130 | 1586 | faster |
| reasoning_toggle.open_ms | 473 | 281 | faster |
| select_all_copy.select_all_ms | 321 | 62 | faster |
| select_all_copy.copy_ms | 748 | 1435 | slower, unchanged from #17504
(follow-up) |

Behaviour parity: 20 invariants held, 0 broken. The select-all copy cost
(every unmounted row is mounted before the clipboard fills) is left for
a follow-up that builds the clipboard from the message store.

## CI: compare long-chat cost with the base build

The existing long-chat gate compares a build with itself (40 vs 200
turns), so it passed #17504. `tests/studio/long_thread_ab.py` builds the
PR's base too and runs the same 200-turn chat on both builds,
alternating on fresh pages: streaming a reply, typing, scrolling, and a
reply streaming while the reader wheels away and then stops to read. It
fails when head's median main-thread or long-task time is over 1.5x base
with no overlap, or when any head reading leaves the viewport blank
while base stayed filled. A new step in `studio-frontend-ci.yml` runs it
on pull requests (5 reps per side, a few minutes; a base that cannot
build with the PR's node_modules is a warning).

Validated on clean runners (scroll-away area, 5 reps each):

| pair | verdict |
|---|---|
| base vs base, 3 runners | pass, 0 false positives |
| main before #17504 vs main with #17504, 4 runners | fail on all 4
(viewport blank in 2 to 4 of 5 reps) |
| main before #17504 vs this fix | pass, never blank |
| main vs this fix, 2 runners | pass; main blanks, this fix never does |

Every bisected #17504 commit also measured below its base on stream,
typing and scrolling CPU, so the check gates on what readers see as well
as on time.

## Tests

- `npx tsc --noEmit -p .` clean; `tests/thread-window.test.ts` and
`tests/progressive-mount-glue.test.ts` 88 pass, including new tests for
`TailPulse` and the deferral.
- `tests/studio/playwright_thread_window.py` check 14: wheel away from a
600-chunk streaming reply, rows must cover the reader 20 frames later
while it still streams; fails on main, passes here.


## Declared UI difference (`affects UI#`)

studiobench's visible-region parity reports one difference, in
`stop_generation`: base shows message 19 on screen during the action,
this PR does not. A per-frame trace (IntersectionObserver entries,
scrolls, mounts) shows why. On main, when Enter jumps to the bottom, the
finished reply is still mounted at a stale mid-stream height (675 px
against a real 1371 px), so the jump lands about 700 px short for one
frame: message 19 sits at -3..123 px for about 25 ms, then the scroll
follows to the true bottom. This PR mounts the reply at its real height
in the same frame as the jump, so it lands on the settled view directly;
message 19 is mounted, just above the viewport, and no frame shows a
spacer. The null control (main against main) shows the same one-frame
flash on every cell. Every behavioural invariant holds, the structural
mode is clean, and the final screenshots match.

The long-chat check moved to its own job (`Long-chat cost against the
base build`): the build job already runs 29 to 35 minutes against its 40
minute timeout.


## Before / after

![Before: viewport empty while the reply streams after the reader
wheeled away. After: rows fill the
viewport](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/17597/pr17597_before_after-c3595c8ec002.png)

Two isolated Studio installs (merge base `b2784e3e6`, this PR), the same
400-message chat, a reply streamed into it (answered in the page, no
model), the reader wheels up 12 steps and stops while it streams. Each
side ran 6 attempts and shows its emptiest one. Before: the viewport was
empty in 1 of 6 attempts (rows filled 0% of it). After: filled in 6 of
6.
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…17588)

Scrolling a long chat got slower after #17504 merged. The cause is when
the thread window writes `role="article"` (and the ordinals) onto the
rows: in the commit's layout effect, after the anchor reads had already
computed the new rows' style. The stylesheet has selectors on `[role]`,
so each newly mounted row was restyled a second time, and while
scrolling the window mounts rows on almost every step.

This publishes the role and ordinals in an insertion effect instead:
after React has inserted the rows and before anything reads their style,
so each row is styled once. The markup is unchanged: rows carry
`role="article"`, `aria-posinset` and `aria-setsize` while the thread is
windowed and none of them when it is fully mounted, exactly as on
`main`.

## Numbers

Window gate's thread (400 agent-style messages), headless Chromium, the
same wheel sweep (250 steps up, 120 down), medians of 5. Main-thread
time from CDP `Performance.getMetrics` over the sweep.

```mermaid
xychart-beta
    title "Style recalculation during the sweep, ms (lower is better)"
    x-axis ["main", "this PR", "no role at all"]
    y-axis "ms" 0 --> 2800
    bar [2533, 1731, 1736]
```

| | main | this PR | no role at all |
|---|---|---|---|
| Style recalculation | 2,533 ms | 1,731 ms | 1,736 ms |
| Main-thread task time | 10,708 ms | 9,980 ms | 10,159 ms |
| p95 frame gap | 35.7 ms | 29.7 ms | 30.2 ms |
| Worst frame | 47.8 ms | 40.4 ms | 39.9 ms |
| Window commits, rows mounted | same | same | same |

`main` measured twice for noise: 2,533 and 2,514 ms of style
recalculation. With the role gone entirely the sweep costs the same as
with this change, so what cost was the late write and not the role.
Commit by commit over the 24 commits that made up #17504, style
recalculation was flat at about 1,760 ms up to 2d804f1, which added
the role write, and flat at about 2,450 ms from there on.

WebKitGTK (the Linux app) spends a larger share of its frame on style
recalculation than Chromium does, so this should be felt more there; not
measured in the native app for this PR.

## Tests

- `progressive-mount-glue.test.ts`: the role and ordinals are published
in an insertion effect, before the layout effect's anchor reads.
- `playwright_thread_window.py`: every windowed row carries
`role="article"`, the role its ordinals need. Passes in Chromium and
Firefox.
- Frontend unit suite and the thread browser gates (thread window,
long-thread gate, heavy thread, long-chat renders, find in page, chat
autoscroll, progressive rows, stream pacing, user message time,
non-modal menus, Firefox leg) run locally.

Related: #17504. This does not address the streaming cost studiobench
reported after a scroll during generation; I could not reproduce it
outside the real app, and the role write made no difference to
streamed-reply cost in my runs.


## Before / after (parity)

Two isolated Studio installs, merge base `6c15abd99` against this PR,
the same 300-message chat read at its bottom and at its top. The claim
is that nothing visible changes, and the scene facts match on both
sides: 11 mounted rows and 1,857 elements at the bottom with Reply
marker R0149 in view, 19 rows and 2,257 elements at the top with Prompt
marker P0000 in view, every windowed row carrying `aria-setsize` 300.

![Bottom of the chat, before and after:
identical](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/17588/pr17588_pair_00-781e5e06fa99.png)

![Top of the chat, before and after:
identical](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/17588/pr17588_pair_01-70887c89e4be.png)

---------

Co-authored-by: Daniel Han <[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.

2 participants