Skip to content

Studio: fix chat scrollbar freezes on long code fences - #13919

Merged
danielhanchen merged 19 commits into
unslothai:mainfrom
Sneakr:fix/chat-scroll-defer-highlighting
Oct 19, 2026
Merged

danielhanchen merged 19 commits into
unslothai:mainfrom
Sneakr:fix/chat-scroll-defer-highlighting

Conversation

@Sneakr

@Sneakr Sneakr commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Dragging the chat scrollbar thumb across a long code fence stalled Studio: the line window inside large fences moved on every frame of the drag, swapping hundreds of thousands of nodes. This PR fixes the stall and keeps the line window, which turned out to matter for every other way people read a long chat.

Original change by @Sneakr (defer highlighting by default, plus chunked fence rendering, hoisted line colour and a progressive highlight queue). The scrollbar guard is the one @oobabooga proposed in review. On top of that I merged main, kept the line window as the default, kept syntax colour in Thinking, and fixed two highlight-blocking bugs found while testing.

What changes

  • Scrollbar guard. A thumb press targets the scroller, an ancestor of the fence, so the existing drag guard never saw it. The held scrollbar is now tracked and the window stays put until release (code-fence-defer.tsx, onScrollbar in code-fence-window.ts).
  • Default stays window. defer is still reachable through __UNSLOTH_DEFER_FENCE_HIGHLIGHT__ / VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT. See the slow read numbers below for why.
  • Rendering work from this branch, kept: 32-line memoized line chunks, plain-text chunks, line-level colour hoisting (fewer spans), skipping source-only re-renders, and the input-aware highlight queue.
  • Thinking code keeps its colour (the Studio: keep syntax colour on settled thinking code in tilde, four-backtick and stopped fences #13415 path), so nothing visible changes for reasoning traces.
  • Fix: any non-empty selection on the page blocked the highlight queue, so after selecting a sentence and scrolling on, newly reached fences stayed uncoloured until the selection was cleared. Only a selection that ends inside a fence holds it now.
  • Fix: a handler that cancels dragstart (the model picker's pinned rows, the hub carousel) left the pointer marked as held forever, which stopped all deferred highlighting until the next real drag or a window blur.
  • Startup bundle: +11,012 B raw / +3,984 B transfer, budget raised with the measurement.

Measurements

Real Studio (production build, own backend), a thread of ten Python fences of 280 to 3,200 lines (about 134K characters in the largest), headless Chromium driving the native scrollbar thumb, each arm a fresh browser context, arms interleaved. "Long-frame time" is the time past one frame spent in frames over 50 ms.

Thumb drag across the 3,200-line fence, 8 s (Linux Chromium, median of 3):

main main + guard this PR as first submitted (defer) this PR
1x CPU: long-frame time 933 ms 50 ms 0 ms 33 ms
1x CPU: frames over 50 ms 15 1 0 1
4x CPU: long-frame time 4,166 ms 300 ms 350 ms 33 ms
line-window DOM swaps during the drag 72K to 229K 4.9K 0.5K 4.9K

The same drag on a Windows 11 runner in Microsoft Edge at 4x: main 3,940 ms of long frames, main + guard 67 ms, defer 0 ms, window + guard 267 ms. No renderer crash or browser disconnect in any arm, including 15 rapid back-and-forth drags per arm, so the STATUS_BREAKPOINT report did not reproduce on that machine.

Reading the thread slowly (mouse wheel, 400 px every 350 ms from the bottom to the top, then idle; two runs each, both shown):

main defer default this PR
DOM elements afterwards 34K / 35K 111K / 111K 28K / 28K
theme change, 1x 0.28 / 0.40 s 2.60 / 2.12 s 0.32 / 0.34 s
theme change, 4x 1.55 / 1.40 s 8.06 / 10.19 s 1.48 / 1.28 s
thumb drag after the read, 4x (long-frame time) 3.37 / 2.60 s 2.53 / 1.72 s 0.95 / 0.28 s

With defer every line the reader passes keeps its token spans, so a slow read of this thread ends with every token mounted. The window caps that, which is why this PR keeps it as the default. Long-frame time during the read itself was too noisy on this shared host to rank the window arms: main measured 1.2 and 3.7 s at 1x (29 and 22 s at 4x), main + guard 2.4 and 0.9 s (35 and 16 s), this PR 3.4 and 0.8 s (41 and 18 s), and defer 4.6 and 33.4 s (26 and 43 s).

Expanded Thinking (six turns, three 150-line fences each, all expanded, median of 3 at 1x): expand long-frame time main 200 ms / this PR 183 ms, DOM 18.3K / 14.3K, theme change 147 / 129 ms. Screenshots of the answer fences and of Thinking are pixel-identical to main in the thread area.

Testing

  • Frontend: 12,762 tests pass, typecheck, production build and bundle check. New tests for the scrollbar guard, the selection scope and the cancelled dragstart, each failing without its fix.
  • Cross-platform CI on Linux, macOS (Apple Silicon) and Windows: node tests green, Studio Playwright smoke OK.
  • Studio UI regression suite (auth, settings, model picker, chat UI, compaction, page crawl), base vs head: no regression. One crawl page diff is an animated remote image; two checks fail identically on main.
  • studiobench standard tier, A/B against main with a main-vs-main null control (4 repetitions): no metric outside the null control's detection floor. This host was heavily loaded, so the floors were wide.

Not covered

  • STATUS_BREAKPOINT itself was not reproduced (Edge on Windows 11 and Chromium on Linux, headless). Users who still hit it can set __UNSLOTH_DEFER_FENCE_HIGHLIGHT__ = "defer".
  • Overlay and left-side scrollbars and document-level scrolling are not covered by the guard; Studio's thread scrolls in its own viewport with a right-hand scrollbar.
  • WebKit and the macOS desktop app were covered by unit tests only.

Before and after

Same seeded thread on main (BEFORE) and this PR (AFTER), each served from its own production build. The thread area is identical in both scenes apart from one antialiased pixel.

Before and after: a 3,200-line code fence and expanded Thinking render the same on main and this PR

Use deferred highlighting without moving line windows so highlighted code
spans remain mounted during scrolling. Keep lazy highlighting, Thinking
colors, and explicit mode overrides available.

Update the default-mode regression check and cover override precedence
between defer and window.
@Sneakr
Sneakr requested a review from danielhanchen as a code owner October 15, 2026 19:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T10:34:59.796986Z b22f74b New commits
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: ab5063b53b

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

danielhanchen added a commit that referenced this pull request Oct 15, 2026
Main (bd06376) is red in Backend CI on five tests, seen on every PR
based on it (#13914, #13919). Four come from #13850 and #13806, which
are both right; one comes from my own #13909. Each is reproduced locally
on main and fixed here.

## From #13850 (token preview)

**`test_every_long_lived_spawner_consults_the_shutdown_latch`**:
`core/training/token_preview.py` adopts its worker with `adopt_pid` but
was in neither the gated nor the not-gated set. It already checks
`is_process_shutting_down()` before spawning, so it belongs with the
gated spawners, but a gated spawner also has to recheck after adopting:
a quit that lands between the check and `adopt_pid` happens after the
shutdown sweep took its snapshot, and the worker would outlive it.
`_spawn_locked` now rechecks right after adopting, and if the latch is
set it stops the new worker and raises `TokenPreviewError("Unsloth is
shutting down.")`, the same message `_start_locked` uses. The module
goes into the gated set.

New test `test_a_quit_that_races_the_spawn_reaps_the_new_worker` drives
that race: the latch flips inside `Process.start()`, and the worker must
be stopped and the call refused.

**`test_the_dataset_format_check_installs_the_decoder`**:
`check_format_response` now reads its rows through `load_preview_slice`,
which calls `ensure_audio_decoding()` before any tier, so the wiring is
intact. The test only read `check_format_response`'s own source. It now
checks that `check_format_response` reads through `load_preview_slice`,
and that `load_preview_slice` installs the decoder before its first read
(`resolve_dataset_path(` / `load_dataset(`), which also pins the
ordering the old form never checked.

**`test_the_subprocess_tokenizes_and_masks_typed_text`**: the
completion-masking half imports unsloth in the worker, as training does,
and Backend CI has torch but no `unsloth_zoo` (`Unsloth: Please install
unsloth_zoo via pip install unsloth_zoo then retry!`). The test skipped
only when torch was missing; it now also skips when `unsloth_zoo` is not
importable. The plain tokenization half still runs everywhere.

## From #13806 (drafter training)

**`test_owner_training_start_status_cancel_bytes_are_unchanged`**: the
training status details gained `"drafter": null`. The test pins the
exact status bytes on purpose, so a new field is a deliberate, one-line
update to the expected dict.

## From #13909 (mine)

**`test_python_children_are_told_to_emit_utf8`**: #13909 made the
drafter capability probe decode its child as UTF-8 but set
`PYTHONIOENCODING` on its own line, while this guard requires the child
env to go through `utf8_child_env()` at the call site. The probe now
passes `env = utf8_child_env(env)`, which sets the same variable through
the shared helper.

## Verification

- `test_audio_dataset_decode.py`, `test_chat_text_encoding.py`,
`test_job_accounts.py`, `test_orchestrator_unload_cancel.py`,
`test_token_preview.py`, `test_text_io_encoding.py`,
`test_drafter_training.py`: 1144 passed. One failure,
`test_capability_child_process_runs_for_real`, fails identically on main
on this host (it runs the probe in a real child interpreter) and is not
failing in CI.
- Without `unsloth_zoo` importable: the token preview real-worker test
tokenizes, then skips the masking half with its reason.
- Sabotage, the post-adopt recheck removed: the spawner-set guard fails
(`never rechecks the latch after adopting`) and the new race test fails
(`DID NOT RAISE TokenPreviewError`).
- Sabotage, `ensure_audio_decoding()` moved after
`resolve_dataset_path(` in `load_preview_slice`: the decoder test fails
(`the decoder must be installed before the first row is read`).
- `tests/test_formatter_fixed_point.py`: passes.
@oobabooga oobabooga self-assigned this Oct 15, 2026
@oobabooga

Copy link
Copy Markdown
Member

Flipping SHIP_DEFAULT to defer does stop the drag stall, but it brings back the #10769 first pass (1,690 to 2,050 ms at 4x throttle, 70.4K token spans against 9K), and the stall itself is draggingDuringFrame not seeing a scrollbar press, which a guard on that check removes with the window left on.

Root cause

draggingDuringFrame holds the window still while a pointer is down, but tests only body.contains(pointerHeld). A scrollbar press reports the scroller as its target, an ancestor of the fence body, so a thumb drag reads as "no pointer on this fence" and the window keeps moving. A MutationObserver on the fence <code> counted 12 window moves per 8 second drag, swapping about 7,200 nodes, and zero with the guard below.

Chrome dispatches pointerdown and pointerup for the thumb with the scroller as target and offsetX past its clientWidth, and sends no pointermove while it is held. Those two events are the whole signal.

The whole change, against 565630c6b4. barHeld is the scroller whose gutter is under a held pointer; it is set on pointerdown, cleared on release, and the existing heldLastFrame path remeasures once the thumb comes up. It stays behind the same current.current !== null condition as the flying and selection guards, so a cold first pass still builds its window and stays capped. Two test edits go with it: the structural pin in code-fence-print.test.ts that spells out the old call, and a truth table for the new predicate in code-fence-window.test.ts.

Patch (two files, applies with git apply)
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
@@ -28,6 +28,7 @@ import {
   lineRendered,
   pinBoundaryLines,
   samePins,
+  onScrollbar,
   OVERSCAN_VIEWPORTS,
   plainLineText,
   selectLineWindow,
@@ -886,6 +887,8 @@ let frameRects: Map<Element, DOMRect> | null = null;
 let frameFlying: Map<Element | null, boolean> | null = null;
 let frameSettle = false;
 let pointerHeld: Node | null = null;
+/** The scroller whose scrollbar is under a held pointer, or `null`. See `scrollbarOf`. */
+let barHeld: HTMLElement | null = null;
 let heldLastFrame = false;
 let frameSelection: { read: boolean; value: Selection | null } | null = null;
 const scrollerMotion = new WeakMap<Element, { top: number; at: number }>();
@@ -917,8 +920,40 @@ const selectionDuringFrame = (): Selection | null => {
   return frameSelection.value;
 };
 
-const draggingDuringFrame = (body: HTMLElement): boolean => {
-  const held = pointerHeld !== null && body.contains(pointerHeld);
+/*
+ * A POINTER ON A SCROLLBAR IS A DRAG TOO, and `pointerHeld` alone cannot see it. A thumb press
+ * reports the SCROLLER as its target, which is an ancestor of the fence and never `contains`ed by
+ * the body, so the selection guard below reads it as "no pointer on this fence" and the window
+ * moves on every frame the thumb crosses the hysteresis band. That is the stall #13919 reported:
+ * measured on a 3200-line fence, a throttled 8 s scrub moved the window 12 times and spent 4.2 s in
+ * frames over 50 ms, against 0 moves and none once the window is held.
+ * Chrome dispatches `pointerdown` for the thumb with the scroller as `target`, which `onScrollbar`
+ * in `code-fence-window.ts` tells apart from a content press; no `pointermove` arrives while the
+ * thumb is down, only `scroll`, so `pointerdown` and `pointerup` are the whole signal.
+ * Held, not disabled: the window stays exactly where the last settled frame left it, so a line the
+ * reader lands on may be uncoloured until `releasePointer` remeasures. That is the same bargain
+ * `code-fence-window.ts` already documents for a wrong window -- it costs colour, never text --
+ * and the same one the in-body selection guard has always made.
+ */
+const scrollbarOf = (event: PointerEvent): HTMLElement | null => {
+  const target = event.target;
+  if (!(target instanceof HTMLElement)) return null;
+  const spot = {
+    offsetX: event.offsetX,
+    offsetY: event.offsetY,
+    clientWidth: target.clientWidth,
+    clientHeight: target.clientHeight,
+  };
+  return onScrollbar(spot) && isScrollable(target) ? target : null;
+};
+
+const draggingDuringFrame = (
+  body: HTMLElement,
+  scroller: HTMLElement | null,
+): boolean => {
+  const held =
+    (pointerHeld !== null && body.contains(pointerHeld))
+    || (barHeld !== null && barHeld === scroller);
   if (held) heldLastFrame = true;
   return held;
 };
@@ -1062,11 +1097,13 @@ const scheduleRemeasure = (): void => {
 const onPointerDown = (event: PointerEvent): void => {
   if (event.pointerType === "touch" || event.button !== 0) return;
   pointerHeld = event.target instanceof Node ? event.target : null;
+  barHeld = scrollbarOf(event);
 };
 
 const releasePointer = (): void => {
-  if (pointerHeld === null) return;
+  if (pointerHeld === null && barHeld === null) return;
   pointerHeld = null;
+  barHeld = null;
   if (heldLastFrame) scheduleRemeasure();
 };
 
@@ -1141,6 +1178,7 @@ const unwatchWindows = (): void => {
   findBarObserver?.disconnect();
   findBarObserver = null;
   pointerHeld = null;
+  barHeld = null;
   heldLastFrame = false;
   if (windowFrame !== 0) {
     cancelAnimationFrame(windowFrame);
@@ -1356,7 +1394,7 @@ function useLineWindow(
       return;
     }
     if (current.current !== null && flyingDuringFrame(known.scroller, viewportHeight)) return;
-    if (current.current !== null && draggingDuringFrame(body)) return;
+    if (current.current !== null && draggingDuringFrame(body, known.scroller)) return;
     const next = selectLineWindow({
       lineCount: lines.current,
       lineHeight: known.lineHeight,
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-window.ts b/studio/frontend/src/components/assistant-ui/code-fence-window.ts
--- a/studio/frontend/src/components/assistant-ui/code-fence-window.ts
+++ b/studio/frontend/src/components/assistant-ui/code-fence-window.ts
@@ -32,6 +32,23 @@ export const OVERSCAN_VIEWPORTS = 1;
 // boundaries, the thrash that killed the earlier bidirectional gate.
 export const HYSTERESIS_VIEWPORTS = 0.5;
 
+/**
+ * WAS THIS POINTER PRESS ON A SCROLLBAR RATHER THAN ON CONTENT? Here rather than in
+ * `code-fence-defer.tsx` for the reason the rest of this module is: the type-stripping test runner
+ * can RUN it. `offsetX`/`offsetY` are measured from the padding box, so content tops out at
+ * `clientWidth - 1` and the gutter is the one place a press lands at or past it. Both bars count:
+ * the vertical one a thumb drag uses, and the horizontal one a fence wider than the thread has.
+ */
+export type PointerSpot = {
+  offsetX: number;
+  offsetY: number;
+  clientWidth: number;
+  clientHeight: number;
+};
+
+export const onScrollbar = (spot: PointerSpot): boolean =>
+  spot.offsetX >= spot.clientWidth || spot.offsetY >= spot.clientHeight;
+
 export type WindowGeometry = {
   lineCount: number;
   /** MEASURED from the rendered block, never assumed. */

Measurements

Studio from main (565630c6b4), real chat UI, headed Chrome 134 on Linux, Playwright dragging the native scrollbar thumb. Thread of 321K characters: nine fences of 280 to 700 lines plus one of 3,200 lines and 134K characters, the #10769 size. Three runs per cell, arms interleaved with the order reversed between repeats, one discarded warmup run per session. Ranges are min to max across the three runs.

Thumb dragged back and forth over the big fence for 8 seconds, after the thread has been rendered once, at 4x CPU throttle:

arm worst frame frames over 50 ms time in those frames
window (today) 110 to 120 ms 35 to 58 2,690 to 4,161 ms
defer (this PR) 30 to 40 ms 0 0 ms
window plus the guard 10 to 20 ms 0 0 ms

First pass over the same thread, where defer pays instead:

arm worst frame, 4x throttle worst frame, unthrottled token spans DOM nodes
window (today) 310 ms 70 to 80 ms 7.7 to 10.3K 16.2 to 18.8K
defer (this PR) 1,690 to 2,050 ms 410 to 420 ms 70.4K 78.9K
window plus the guard 310 ms 70 ms 7.9 to 8.3K 16.4 to 16.8K

Unthrottled, the drag itself stalls in no arm: zero frames over 50 ms in all three.

Cost of defer

Past the 240 line cap defer mounts every line's spans on first view, which is the second table. The guard reaches the same zero drag stall while leaving that first pass at window's 310 ms and the DOM seven times smaller.

Recommendation

Keep SHIP_DEFAULT on window and take the guard instead. It removes the stall you reported, keeps #10769 fixed, and leaves every override reachable. Mid-drag, lines the reader stops on stay uncoloured until the thumb comes up, never missing text, which is the same trade the in-body selection guard already makes. The smallest path is to repurpose this branch to carry the patch above.

Render code in short and full Thinking sections as plain text while streaming and after completion. Remove the unused Thinking color worker hook and token helpers, preserving text, copy controls, and answer highlighting.

Validated with 146 focused tests, frontend type checks, a production build, and saved-conversation content parity against the measured plain rendering.
@Sneakr

Sneakr commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@oobabooga The proposed guard addresses a scrollbar-target detection gap, but it does not resolve the Windows Chrome failure motivating this PR. STATUS_BREAKPOINT remains reproducible with the guard in place. That crash was not observed with defer.

Changing the default also does not revert #13255 or restore the original renderer associated with #10769. Per-line memoization, incremental tokenization, sliced highlight refreshes, and deferred highlighting remain intact.
The larger retained DOM and higher first-view rendering cost are real tradeoffs. However, those measurements alone do not establish that the original streaming regression has returned, or that the proposed guard fixes the native scrollbar failure.
This PR makes a scoped default-policy change to mitigate that failure while preserving the existing rendering improvements and overrides. Replacing it with the guard is premature while the Windows crash remains reproducible.

Below a video showcasing that #10769 can not be reproduced at all.

2026-10-16.13-20-15.mp4

Additionally, further improvements in: df2d05f


Code inside Thinking sections now stays plain, both while streaming and after completion. Answer syntax highlighting remains enabled. Full Thinking content, line breaks, and copy controls are preserved.

On the same large conversation with all six Thinking sections fully expanded:

Measurement Highlighted Thinking Plain Thinking
Renderer main-thread work, expansion + first traversal 5.49–5.70 s 3.42 s
Renderer main-thread work, warmed traversal 2.37–2.47 s 2.02–2.09 s
Worst frame, first traversal 233–317 ms 150–183 ms
Frames exceeding 50 ms, first traversal 6 2
Frames exceeding 50 ms, warmed traversal 0 0
Total page elements ~63,927 39,311

Plain Thinking reduced initial main-thread work by approximately 39%, warmed main-thread work by 15%, and page elements by 39%. Main-thread work here means accumulated work across the traversal—not a single blocking stall.

These production-build Chromium renderer measurements are separate from the native Windows scrollbar failure. Earlier Windows measurements showed browser-main-thread tasks reaching 3.29 seconds, while the renderer’s longest task was approximately 137 ms. Renderer timing alone therefore does not fully characterize that failure.

This change reduces Thinking’s rendering cost while preserving the existing answer-rendering improvements. The separate first-view cost of very large highlighted answer fences remains a tradeoff.


chatgpt-codex-connector[bot]

This comment was marked as resolved.

Apply paint containment to completed, fully highlighted code fences over
240 lines. Keep their text and dimensions intact, respect the existing
containment flag, and release containment for printing.

Cover eligibility, retained lines, and print styles in regression tests.
@Sneakr

Sneakr commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

a9c00b2 Added paint containment for completed, fully highlighted code fences over 240 lines to address the remaining scrolling microstutter. All text and highlighting remain mounted. The change respects the existing containment setting and is disabled for printing.
On the long conversation with all six Thinking sections expanded in Chrome 155:

  • PrePaint work decreased 84%.
  • Main-thread work decreased 35%.
  • p99 animation-frame callback interval improved from 16.6 ms to 4.3 ms.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: a9c00b2574

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

@Sneakr

Sneakr commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

One regression found by manual testing - resizing windows with large code block conversations are not as smooth, although scrolling and performance everywhere else improved. Working on it.

@oobabooga

Copy link
Copy Markdown
Member

Two corrections to my earlier comment, then measurements re-run against the current head.

Corrections

defer does not revert #13255 and does not reproduce #10769. Per-line memoization, worker tokenization and deferred highlighting all remain under it, and you report #10769 not reproducing. I attached #10769 to a first-view cost I had measured; the cost is in the table, the label was wrong.

My measurements do not cover the STATUS_BREAKPOINT crash. They are renderer-side, on Linux. Across 9 traced runs here the browser process main thread stayed between 209 and 277 ms busy with no task over 3.5 ms, against the 3.29 s of browser-main-thread work reported on Windows.

Setup

Three builds from this PR's merge base 5e55110278, each left at its own SHIP_DEFAULT so nothing is overridden: the base, this PR at a9c00b2574, and the base plus a guard that holds the line window still during a scrollbar drag. Headed Chrome 134 on Linux, Chrome tracing, three runs per arm, interleaved with the order reversed between repeats, one warmup run discarded. Thread of 321K characters whose largest fence is 3,200 lines and 134K characters.

Drag over the big fence, 8 seconds, 4x CPU throttle

arm worst frame frames over 50 ms time in those frames window moves
base (today) 100 to 110 ms 31 to 40 2,240 to 2,850 ms 11 to 22
this PR 30 to 40 ms 0 0 ms 0
base plus guard 10 ms 0 0 ms 0

Unthrottled, over the warm legs of the first-pass run below: zero frames over 50 ms on the base and on the guard, and 0 to 1 on this PR (worst 100 ms).

First pass over the thread

arm worst frame, 4x worst frame, unthrottled token spans DOM nodes
base (today) 310 ms 70 to 80 ms 8.1 to 9.1K 16.7 to 17.6K
this PR 1,720 ms 420 ms 70.4K 79.0K
base plus guard 310 to 350 ms 80 to 90 ms 7.9 to 8.5K 16.4 to 17.1K

a9c00b2574 did not change this: 1,720 ms at 4x in all three runs, against 1,690 to 2,050 ms with the fence mode forced to defer on a build without this commit. The span count is 70.4K either way.

Renderer main thread, whole traced drag session, 4x throttle

arm busy % of session longest task forced style/layout
base (today) 17.2 to 23.7 s 68 to 76% 218 to 224 ms 6.5 to 9.9 s
this PR 13.1 to 13.5 s 51 to 53% 1,426 to 1,592 ms 3.3 to 3.4 s
base plus guard 5.4 to 6.5 s 27 to 33% 219 to 246 ms 0.40 to 0.45 s

What each arm puts on the 3,200-line fence

window moves DOM during scroll content-visibility contain-intrinsic-size contain
base (today) yes auto auto 55810px none
this PR no visible none paint
base plus guard no auto auto 55810px none

window.__UNSLOTH_CODE_BLOCK_CONTAINMENT__ = false with the window left on drops content-visibility and the intrinsic size while keeping the DOM swaps, which separates those two from the window movement. The rows above were measured with it set at load; containment-flag.ts installs a setter that reapplies on assignment.

Notes

The crash repro, platform and Chrome version are not in the PR body; with them the failure could be checked independently of this setup.

The PR is now four commits over 15 files, including Thinking rendering changes in reasoning-transcript.tsx, use-thinking-code-colour.ts and the new reasoning-code-colour.ts.

The drag cost in the first table is present on the base under today's default and does not depend on this PR. The guard patch is in my earlier comment and applies to current main.

Reduce redundant token spans through stable per-line color inheritance and
keep completed code fences at their intrinsic width during resizing.
Scope sidebar sibling selectors to prevent responsive changes from
restyling the conversation subtree, preserving active states and printing.

Validated with 456 relevant tests, application and test typechecks,
production build and bundle checks, browser rendering parity, and manual
confirmation that window resizing and fast scrolling both remain smooth.
@Sneakr

Sneakr commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

@oobabooga Updated performance comparison for 08b77dfa47, including manual testing and automated benchmarks against merge base 5e55110278 + your suggested guard.

Summary

The current PR provides a noticeably smoother experience in manual testing, and the automated benchmarks support that result, particularly for sustained scrolling and frame consistency.

Manual testing — Guard vs Current PR

I manually tested both versions under normal browsing conditions, including scrolling, typing, searching, and navigating large conversations.

Guard (base + suggested guard):

  • Frequent, unpredictable lag and freezes during scrolling.
  • Noticeable stalls while typing and searching.
  • Occasional system-wide unresponsiveness during interaction.
  • The freezes occur inconsistently, making the experience difficult to use even when some interactions appear smooth.

Current PR (08b77dfa47):

  • Smooth, responsive scrolling.
  • Typing and searching remain responsive.
  • No comparable freezes or stalls observed during manual testing.
  • Consistently smoother overall interaction in the tested scenarios.

Side-by-side video recordings

I've attached two manually recorded comparisons demonstrating the difference:

** Guard (base + suggested guard)**
Shows the intermittent lag, freezing, and responsiveness issues observed during normal interaction.

guard_compressed.mp4
guard_2_compressed.mp4

** Current PR (08b77dfa47)**
Shows the same general interactions running smoothly without the observed stalls.

after_compressed.mp4
after_2_compressed.mp4

These videos are important because automated benchmarks do not fully reproduce real-world browsing behavior, especially intermittent freezes during mixed interactions such as scrolling, typing, and searching.

The manual tests and recordings illustrate the practical UX difference. The automated measurements below provide additional, repeatable data, but should not be interpreted as a complete representation of real-user responsiveness.


Automated benchmark results

Test environment: Windows, Chrome 155, 240 Hz display, three traced runs per comparison.

Configuration Description
Guard Merge base 5e55110278 + Ooba's suggested guard
Previous PR Earlier revision a9c00b2574
Current PR Latest revision 08b77dfa47

Workloads:

  • Expanded conversation: ~435K characters, all six Thinking sections expanded.
  • Answer-only proxy: ~324K characters, ten code fences, including one 3,200-line fence.

Results are averages across three automated runs. CPU 1× represents unthrottled execution; 4× represents CPU throttling.

1. Full-thread scrolling — Current PR substantially faster

Compositor presentation rate (higher is better)

Workload CPU Guard Current PR Result
Expanded conversation 1× 206.1/s 237.9/s PR +15%
Expanded conversation 4× 66.2/s 107.6/s PR +63%
Answer-only proxy 1× 210.0/s 239.9/s PR +14%
Answer-only proxy 4× 45.4/s 126.9/s PR +180% (2.8×)

At native CPU speed, the current PR approaches the display's 240 Hz refresh rate in both workloads.

Frame intervals — lower means smoother, more consistent presentation

Workload CPU Guard mean PR mean Guard p99 PR p99
Expanded 1× 4.85 ms 4.20 ms 16.68 ms 4.22 ms
Expanded 4× 15.13 ms 9.30 ms 143.06 ms 22.24 ms
Answer-only 1× 4.76 ms 4.17 ms 12.48 ms 4.20 ms
Answer-only 4× 22.04 ms 7.89 ms 113.89 ms 16.70 ms

The p99 values are particularly relevant: they represent the slow end of the recorded frame-interval distribution.

For example, under 4× CPU throttling:

  • Expanded: Guard p99 143 ms → PR 22 ms
  • Answer-only: Guard p99 114 ms → PR 17 ms

This demonstrates substantially fewer long frame intervals during automated traversal with the current PR.

2. Renderer work during scrolling — Current PR wins

Accumulated renderer task time during unthrottled full-thread traversal:

Workload Guard Current PR Work eliminated
Expanded 3.51 s 2.03 s 1.48 s (42%)
Answer-only 4.66 s 1.28 s 3.38 s (73%)

The PR completes the measured traversal with considerably less accumulated renderer work.

These are task-time totals across the traversal, not single-frame delays.

3. Native scrollbar dragging — Mixed automated results

Fast native scrollbar dragging was measured separately from full-thread traversal.

Workload CPU Guard rate PR rate Guard p99 PR p99
Expanded 1× 236.1/s 237.7/s 8.33 ms 5.60 ms
Expanded 4× 135.8/s 139.7/s 30.57 ms 26.40 ms
Answer-only 1× 240.0/s 239.8/s 4.20 ms 4.21 ms
Answer-only 4× 205.8/s 165.3/s 13.89 ms 19.45 ms

The current PR performs similarly or better for the expanded conversation. For the answer-only proxy at 4× CPU, the guard performs better in this particular automated drag test:

  • Guard: 13.89 ms p99
  • Current PR: 19.45 ms p99
  • Difference: 5.56 ms longer p99 frame interval on the PR, with 40.5 fewer presentations/s.

This is a measurable difference, but it does not describe the complete browsing experience or capture the intermittent freezes observed manually with the guard.

For expanded conversation dragging at 4×, the rate ranges overlap (Guard 135.4–136.3/s, PR 131.6–148.2/s), so the small average difference is not decisive.

4. Resizing — Previous PR regression resolved

The previous PR revision had noticeably slower resize measurements. The current revision brings resizing back to approximately guard-level performance.

Answer-only proxy:

Operation Guard Previous PR Current PR Best
Inward resize, 1× 27.6 ms 90.4 ms 27.1 ms PR
Outward resize, 1× 28.4 ms 89.0 ms 29.0 ms Guard by 0.6 ms
Inward resize, 4× 113.8 ms 463.1 ms 114.4 ms Guard by 0.6 ms

The earlier resize regression has effectively been eliminated. The current PR is within approximately 1 ms of the guard at native CPU speed.

5. Theme and font changes — One-time restyling costs

These are individual restyling operations, not continuous scrolling performance. Absolute times are shown rather than potentially misleading percentage increases.

Answer-only proxy

Operation Guard Previous PR Current PR PR vs Guard
Theme change, 1× 93 ms 462 ms 360 ms +267 ms
Theme change, 4× 0.52 s 2.70 s 2.06 s +1.54 s
Font change, 1× 210 ms 471 ms 350 ms +140 ms

Expanded conversation, native CPU

Operation Guard Current PR Difference
Theme change 120 ms 228 ms PR +108 ms
Font change 389 ms 270 ms PR 119 ms faster

Practical impact:

At native CPU speed, theme changes with the PR take approximately 0.23–0.36 seconds, and font changes take 0.27–0.35 seconds across the tested workloads.

The guard is faster for some of these one-time operations, typically by around 0.1–0.3 seconds, while the PR is faster for expanded-conversation font changes.

Under 4× throttling, the answer-only theme change takes 2.06 seconds with the PR versus 0.52 seconds with the guard. That 1.54-second difference is noticeable, but it occurs during an explicit theme change rather than during continuous scrolling.

The latest PR also improves these measurements substantially compared with the previous PR revision.

6. Cold entry and DOM size — Remaining trade-offs

Answer-only proxy:

Measurement Guard Previous PR Current PR
Longest cold-entry renderer task, 4× 236 ms 942 ms 693 ms
DOM elements after warm traversal, 1× 22,564 63,081 39,459

Cold entry: The current PR's longest individual renderer task is 693 ms versus 236 ms with the guard under 4× CPU throttling — an additional 457 ms for that task. This has improved by 249 ms compared with the previous revision.

This is not total page load time, so it should not be interpreted as an additional 457 ms of overall loading.

DOM size: The PR has 16,895 more elements than the guard after warm traversal, but 23,622 fewer than the previous PR revision.

Element count is not itself a responsiveness measurement; the scrolling benchmarks above measure the resulting behavior more directly.

7. Total renderer task time — Current PR wins across every workload

This measures accumulated renderer task wall time across the complete automated sequence: loading, expansion, traversal, dragging, resizing, theme/font changes, and measurement overhead.

Workload CPU Guard Current PR PR saves
Expanded 1× 19.30 s 15.36 s 3.94 s (20%)
Expanded 4× 80.35 s 61.64 s 18.71 s (23%)
Answer-only 1× 15.93 s 12.19 s 3.74 s (23%)
Answer-only 4× 66.34 s 53.54 s 12.80 s (19%)

Across every tested configuration, the current PR accumulates 19–23% less renderer task time than the suggested guard.

These are accumulated task wall-time totals, not CPU utilization or overall user-visible elapsed time.


Overall comparison

Area Better result Significance
Manual browsing UX Current PR Guard exhibits unpredictable stalls/freezes; PR remains smooth in observed manual tests
Full-thread scrolling Current PR Up to 2.8× presentation rate
Frame consistency Current PR Substantially lower p99 intervals
Traversal renderer work Current PR 42–73% less at native CPU
Native scrollbar dragging Mixed Guard wins answer-only at 4×; otherwise similar or PR-favored
Resizing Essentially equal Previous PR regression resolved
Theme changes Guard PR takes ~0.1–0.3 s longer at 1×, 1.54 s longer at 4× on answer-only
Font changes Mixed PR +140 ms on answer-only, 119 ms faster on expanded
Cold-entry longest task Guard PR's longest task is +457 ms at 4×
DOM element count Guard PR retains 16,895 more elements
Total renderer task time Current PR 19–23% less across all measured sequences

Conclusion

The manual comparison is the most important UX distinction here. With the suggested guard, I repeatedly observed unpredictable lag and freezing during ordinary browsing, scrolling, typing, and searching, sometimes affecting the responsiveness of the PC itself. With the current PR, those issues were not observed, and the experience remained smooth.

The two attached videos demonstrate this difference directly.

The automated benchmarks provide additional supporting evidence: the current PR achieves substantially better sustained scrolling cadence, more consistent frame presentation, and less accumulated renderer work.

There are measurable trade-offs in isolated operations such as theme changes, cold entry, and certain throttled dragging scenarios. Those are documented above using actual milliseconds and seconds, rather than presenting large relative percentages without context.

For the tested workloads, the current PR offers the better observed real-world browsing experience, and the automated results are broadly consistent with that assessment.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 08b77dfa47

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

Reuse stable code and plain-text chunks during streaming, and skip
source-only fence renders when the token result has not changed.

Schedule cold fence admission, token publication and background warming
after input settles. Apply highlighting in bounded batches while retaining
text, existing colors and selection. Keep streaming and print/find paths
immediate, and cancel obsolete work when a fence changes or unmounts.

Add focused coverage for chunk reuse, progressive highlighting, pointer
tracking, queued publication, cancellation and print handling.

Validation: 208 related unit tests, Chromium and Firefox renderer checks,
application and test typechecks, production build and bundle budget.
Reuse immutable count groups so color batches update only changed chunks
and avoid a second FenceLines render for each progress update. Keep
resize and find observers attached across consecutive queued batches.

Preserve existing reach admission, input guards and scheduling limits.
Add coverage for count-group reuse and observer lifecycle behavior.

Validation: 187 scoped unit tests, 56 Chromium/Firefox pipeline checks,
16 component checks, app/test typechecks, production build and bundle
budget. Focused Windows Chrome checks preserve final text/color parity;
end-to-end timing results remain mixed.
@Sneakr

Sneakr commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

@oobabooga Another performance update following the previous comparison.

The latest changes further improve initial scrolling, main-thread responsiveness, and streaming update efficiency, building on the improvements already measured in 08b77dfa47.

This update compares:

  • 08b77dfa47 → 9b0cd6eef7 for scrolling and streaming performance.
  • 9b0cd6eef7 → 1776ef78a7 for the additional code-fence rendering cleanup.

These are improvements on top of the previous PR results, not another comparison against the suggested guard.

Desktop App Showcase - mid streaming!

prdesktop_.mp4

Summary

Area Previous Updated Result
Initial scrolling, expanded, 1× 233.69 FPS 239.04 FPS Near 240 Hz
Initial scrolling, expanded, 4× 93.92 FPS 119.81 FPS +28%
Initial scrolling, answer-only, 4× 119.46 FPS 232.24 FPS +94%
Longest scrolling task, expanded, 1× 75.13 ms 5.68 ms 69.45 ms shorter
Longest scrolling task, answer-only, 4× 164.36 ms 87.94 ms 76.42 ms shorter
Source-only streaming update 0.470 ms 0.010 ms 0.460 ms less
Plain Thinking append 0.642 ms 0.118 ms 0.524 ms less
Body renders across 160 streaming updates 160 80 50% fewer
FenceLines render passes (latest cleanup) 99 50 49.5% fewer

The most important improvement is more consistent initial scrolling with substantially shorter main-thread tasks, particularly under CPU throttling.


1. Initial scrolling — Faster and more consistent

Three-run averages, comparing 08b77dfa47 → 9b0cd6eef7.

Presentation rate and frame intervals

Workload CPU FPS before FPS after Mean frame before Mean frame after
Expanded conversation 1× 233.69 239.04 4.28 ms 4.18 ms
Expanded conversation 4× 93.92 119.81 10.66 ms 8.35 ms
Answer-only proxy 1× 231.73 239.95 4.31 ms 4.17 ms
Answer-only proxy 4× 119.46 232.24 8.38 ms 4.30 ms

At native CPU speed, both workloads now approach the display's 240 Hz refresh rate during initial scrolling.

Under 4× CPU throttling, the improvements are more pronounced:

  • Expanded conversation: 93.92 → 119.81 FPS
  • Answer-only: 119.46 → 232.24 FPS

The answer-only workload now approaches the 240 Hz refresh rate even under 4× throttling in this particular test.

Frame consistency

Lower intervals are better.

Workload CPU p99 before p99 after Worst before¹ Worst after¹
Expanded 1× 4.20 ms 4.20 ms 93.04 ms 12.53 ms
Expanded 4× 70.84 ms 62.50 ms 518.03 ms 143.05 ms
Answer-only 1× 4.21 ms 4.20 ms 37.51 ms 5.61 ms
Answer-only 4× 109.74 ms 4.22 ms 208.34 ms 101.42 ms

¹ Worst interval is the average of each run's single worst recorded frame interval, not the p99 value.

Notable improvements:

  • Expanded, 1×: Worst interval drops from 93 ms to 13 ms.
  • Expanded, 4×: Worst interval drops from 518 ms to 143 ms, eliminating approximately 375 ms from the average worst-frame measurement.
  • Answer-only, 1×: Worst interval drops from 38 ms to 6 ms.
  • Answer-only, 4×: p99 drops from 110 ms to 4.22 ms, while the worst individual interval drops from 208 ms to 101 ms.

The remaining worst-frame intervals under throttling are still measurable, but they occur much less prominently in the frame distribution, especially for the answer-only workload.

Important: These measurements cover initial scrolling while some syntax highlighting is deferred. They do not measure how long it takes for all deferred highlighting to finish.


2. Main-thread responsiveness — Substantially shorter tasks

These measurements show how much renderer work occurs during initial scrolling.

Longest renderer task

Workload CPU Before After Time removed
Expanded 1× 75.13 ms 5.68 ms 69.45 ms
Expanded 4× 445.82 ms 118.29 ms 327.53 ms
Answer-only 1× 30.27 ms 4.02 ms 26.25 ms
Answer-only 4× 164.36 ms 87.94 ms 76.42 ms

At native CPU speed, the longest renderer tasks during initial scrolling are now approximately 4–6 ms, compared with 30–75 ms previously.

This is particularly relevant to responsiveness because long main-thread tasks can delay input handling and contribute to visible stalls.

Under 4× CPU throttling, the longest tasks are also considerably shorter, although some still exceed 50 ms.

Accumulated renderer work and long tasks

Workload CPU Total before Total after Tasks >50 ms before Tasks >50 ms after
Expanded 1× 1.626 s 1.309 s 1 0
Expanded 4× 9.386 s 8.003 s 13 9
Answer-only 1× 1.279 s 0.647 s 0 0
Answer-only 4× 5.655 s 2.666 s 8 0.33

The current changes reduce accumulated renderer task time by:

  • Expanded, 1×: 317 ms less.
  • Expanded, 4×: 1.383 s less.
  • Answer-only, 1×: 632 ms less.
  • Answer-only, 4×: 2.989 s less.

The number of tasks exceeding 50 ms is also reduced. At native CPU speed, neither workload records any >50 ms renderer tasks in these runs.

The fractional value of 0.33 represents an average across three runs, not a fractional task within a single run.


3. Streaming updates — Less unnecessary React work

Separate measurements using production React components in Linux Chromium, unthrottled, with precomputed tokens.

Comparison: 08b77dfa47 → 9b0cd6eef7.

Operation Before After Improvement
Source-only update 0.470 ms 0.010 ms 0.460 ms less
Highlighted-token update 0.952 ms 0.541 ms 0.411 ms less
Plain Thinking append 0.642 ms 0.118 ms 0.524 ms less
Body renders across 80 source + 80 token updates 160 80 50% fewer

The main improvement here is avoiding unnecessary React rendering work during streaming updates.

In the measured sequence of 80 source updates and 80 highlighted-token updates, body renders drop from 160 to 80.

Individual update costs are also lower:

  • Source-only updates: 0.470 → 0.010 ms
  • Highlighted-token updates: 0.952 → 0.541 ms
  • Plain Thinking appends: 0.642 → 0.118 ms

These are small absolute durations per update, so the significance is primarily their repeated occurrence during streaming, rather than any individual update taking a noticeable amount of time.

These measurements isolate component update costs. They are not end-to-end live inference streaming benchmarks.


4. Additional cleanup in 1776ef78a7

The latest commit includes another improvement to code-fence rendering.

Measurement 9b0cd6eef7 1776ef78a7 Improvement
FenceLines render passes, 3,200-line fixture 99 50 49.5% fewer

This nearly halves the number of FenceLines render passes for the same large code-fence fixture.

This is a render-count improvement, not a direct measurement of elapsed time or FPS.

The scrolling and streaming measurements above were taken at 9b0cd6eef7; they should not be interpreted as fresh full-suite benchmark results for 1776ef78a7.


Conclusion

These changes build on the previous performance improvements and further reduce unnecessary renderer work.

The key results are:

  • Initial scrolling: Both workloads now approach 240 FPS at native CPU speed, with the answer-only workload also reaching 232 FPS under 4× throttling.
  • Frame consistency: Large improvements to worst-frame intervals, especially during initial scrolling.
  • Main-thread responsiveness: Longest native-speed renderer tasks fall from 30–75 ms to approximately 4–6 ms.
  • Streaming efficiency: Fewer unnecessary React renders and lower per-update costs.
  • Latest cleanup: Almost 50% fewer FenceLines render passes for the 3,200-line fixture.

As discussed in the previous comment, manual testing remains important because automated traces do not capture every intermittent stall or mixed browsing interaction.

Overall, this update further improves scrolling consistency and reduces main-thread work, while also making the streaming render path more efficient.

The results here are incremental comparisons against the previous PR revision, not new measurements against the guard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 1776ef78a7

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

@danielhanchen danielhanchen self-assigned this Oct 19, 2026
Main moved the type check to TypeScript 7, whose package has no compiler
API, and the other tests read it from @typescript/typescript6. Also follow
the grammar warm gate in the WebKit path test: it now waits for a held
pointer and recent input on every engine.
The default no longer moves line windows, which is what stopped the
scrollbar stall, so Thinking code can keep the worker-coloured rendering
it had before this branch (unslothai#13415). Restores the settled colour path and
its tests, and drops the plain-Thinking action test that only covered the
removed path.
A thumb press targets the scroller, an ancestor of the fence body, so the
window guard read it as no pointer on the fence and moved the window on
every frame of the drag. Track the held scrollbar and treat it as a drag on
that scroller's fences, so the window override no longer stalls either.
Guard as proposed in review by oobabooga.
@unslothai unslothai deleted a comment from Sneakr Oct 19, 2026
@unslothai unslothai deleted a comment from Sneakr Oct 19, 2026
@unslothai unslothai deleted a comment from Sneakr Oct 19, 2026
@unslothai unslothai deleted a comment from Sneakr Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

Any non-empty selection on the page blocked the highlight queue, so after
selecting a sentence in prose and leaving it, every fence reached later
stayed a plain shell until the selection was cleared. Highlighting only
swaps a fence's own line nodes, so only a selection ending inside a fence
needs protecting.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 19, 2026
A cancelled dragstart starts no drag, so no dragend or drop ever clears the
flag, and every fence's highlighting, grammar warm-up and speculation waited
until the next real drag or a window blur. The model picker's pinned rows
and the hub carousel both cancel it.
With the scrollbar guard the window no longer moves during a thumb drag, so
the stall this branch set out to fix is gone under the window too. Measured
in the real app on a thread with ten fences of 280 to 3,200 lines, the
deferred default kept the colour of every line the reader had passed: after
a slow read of the thread it held 111K elements against 28K with the
window, a theme change took 2.6 s instead of 0.3 s (8.1 s against 1.3 s at
4x CPU throttle), and a thumb drag over the large fence was back to 2.5 s
of long frames at 4x. The window keeps that bounded, and the chunked lines,
hoisted line colour and highlight queue from this branch still apply to it.
`defer` stays reachable as an override.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 19, 2026
@danielhanchen danielhanchen changed the title Fix chat scrollbar freezes by disabling code line windowing by default Studio: fix chat scrollbar freezes on long code fences Oct 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 8aa213ab30

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

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
@danielhanchen
danielhanchen merged commit 6c3a9e9 into unslothai:main Oct 19, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
## Summary

Follow-up to unslothai#13919. Since that merge, dragging the chat scrollbar over
a long code block turns the code into plain text until the thumb is
released. This goes back to the default @Sneakr proposed in unslothai#13919, so
code that has been coloured stays coloured while scrolling.

## Cause

unslothai#13919 shipped with the line window as the default and a guard that
holds the window still during a scrollbar thumb drag. With the line
window, every line of a large fence outside the window renders as plain
text. While the thumb was held, the window did not follow it, so the
code being read showed as raw text until release.

## Change

- `SHIP_DEFAULT` goes back to `defer`: once a fence is coloured it keeps
its colour while you scroll, and nothing is swapped during a drag, so
the drag stays smooth.
- The scrollbar guard is removed. It only applied to the line window,
which stays reachable as an override
(`window.__UNSLOTH_DEFER_FENCE_HIGHLIGHT__ = "window"`).
- Everything else from unslothai#13919 stays: chunked fence rendering, hoisted
line colour, the progressive highlight queue, Thinking code colour, and
the selection and cancelled-drag fixes.

## Measurements

Real Studio, production builds, a thread of ten Python fences of 280 to
3,200 lines. The middle of the 3,200-line fence was coloured first, then
the scrollbar thumb was dragged back over it and held:

| | main | this PR |
|---|---|---|
| visible lines coloured while the thumb moves | 0 of 52 | 52 of 52 |
| visible lines coloured while held still | 0 of 52 | 52 of 52 |
| visible lines coloured after release | 52 of 52 | 52 of 52 |

Measured with this default in unslothai#13919: a thumb drag over the large fence
had 0 to 350 ms of long frames at 4x CPU throttle, against 4.2 s with
the line window and no guard.

Trade-off: with `defer`, every line already coloured keeps its spans, so
a very long chat read end to end holds more DOM, and a theme change
after such a read is slower (about 2 s at 1x on the test thread) than
with the line window.

## Testing

- Frontend: 12,791 tests pass, typecheck, production build, bundle
check.

## Before and after

Same thread on main (BEFORE) and this PR (AFTER), each from its own
production build, with the scrollbar thumb held still in the middle of
the 3,200-line fence after the region had been coloured.

![Before and after: with the thumb held, main shows the code as plain
text and this PR keeps its
colour](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14242/pr14242_held_drag-c5e637319995.png)
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
unslothai#14585)

## Summary

Every time the composer changes height (each new line of a multi-line
draft), the composer dock's `ResizeObserver` looked up the thread footer
with `viewport.querySelector(":scope > .aui-thread-viewport-footer")`.
In Chromium (Unsloth Web in Chrome/Edge, Unsloth Desktop on Windows)
that query visits every element in the thread, so its cost grows with
the chat. This PR walks the viewport's direct children instead, which
returns the same element.

This removes thread-sized work from multi-line typing in long chats.
Per-keystroke latency is unchanged within measurement noise, so this is
a CPU saving.

## What changes

- `thread.tsx`: a small `childWithClass(parent, className)` helper
replaces the two `:scope >` lookups in `ThreadComposerDock` (the thread
viewport next to the dock, and the footer inside it).
- `tests/composer-dock-column-lookup.test.ts`: four tests. The helper
returns the first direct child with the class, skips non-HTML children,
never matches a nested descendant, and the dock uses it instead of a
selector.
- Startup bundle: +88 B raw / +53 B transfer, inside the current budget,
so the budget is unchanged.

## Measurements

**Typing in a long live chat.** A code-heavy chat of about 62K elements,
typing ten composer-growing lines (130 keys). Playwright Chromium 148,
headless Linux, 4 sessions × 2 rounds per arm.

| | main | this PR |
|---|---:|---:|
| Script, 1× CPU | 739 ms | **539 ms (−27%)** |
| Total task, 1× CPU | 1,754 ms | 1,536 ms (−12%) |
| Script, 4× CPU | 2,338 ms | **1,914 ms (−18%)** |
| Total task, 4× CPU | 5,198 ms | 4,901 ms (−6%) |
| Plain typing (43 keys), script 1× / 4× | 114 / 457 ms | 116 / 450 ms |

The lookup was 196 ms of self time in the 1× probe on main. Plain typing
never reaches this code. Per-keystroke latency from trace `EventTiming`
is within the rig's noise: multi-line p98 at 1× is 32.0 vs 30.6 ms.

**unslothai#13919 benchmark harness.** Windows Chrome 155, 240 Hz display, saved
conversation and answer-only proxy, 1× and 4× CPU, 3 runs per cell.
Every table is within run-to-run noise of main. Whole-session renderer
time, main vs this PR:

| Workload | CPU | main | this PR |
|---|---|---:|---:|
| Saved conversation | 1× | 14.60 s | 14.53 s |
| Saved conversation | 4× | 54.13 s | 53.57 s |
| Answer-only | 1× | 9.55 s | 9.46 s |
| Answer-only | 4× | 38.27 s | 38.38 s |

## Testing

- `npm test`: 13,396 pass, 0 fail.
- `npm run typecheck` passes.
- ESLint: `thread.tsx` findings are identical to main; the new test file
is clean.
- `npm run bundle:check` is within budget.
- The new lookup returns the same element as the old selectors in
Chromium, Firefox and WebKit.

## Follow-up: walk from the last child

The helper now walks back from `lastElementChild`. The footer follows
every message row, so a forward walk costs one check per row, and in
current Chromium and Firefox that was slower than the `:scope >`
selector it replaced. Walking back reaches the footer on the first check
and the viewport in two. Per lookup on a 62K-element thread (200 rows,
median of 21 samples x 200 calls, headless Linux):

| Engine | `:scope >` (main) | forward walk | walk from the end |
|---|---:|---:|---:|
| Chromium 156 | 1.5 us | 36.5 us | ~0 us |
| Firefox 157 | ~0 us | 20 us | ~0 us |
| WebKit 27.2 | 1945 us | 15 us | ~0 us |

All three lookups return the same element in all three engines,
including when a nested descendant carries the footer class. A new test
asserts that finding the footer after 500 rows checks a single child.

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants