Repository navigation
Studio: fix chat scrollbar freezes on long code fences - #13919
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.
|
Flipping Root cause
Chrome dispatches The whole change, against Patch (two files, applies with
|
| 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.
|
@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. Below a video showcasing that #10769 can not be reproduced at all. 2026-10-16.13-20-15.mp4Additionally, 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:
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. |
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.
|
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.
|
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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. |
|
Two corrections to my earlier comment, then measurements re-run against the current head. Corrections
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. SetupThree builds from this PR's merge base Drag over the big fence, 8 seconds, 4x CPU throttle
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
Renderer main thread, whole traced drag session, 4x throttle
What each arm puts on the 3,200-line fence
NotesThe 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 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.
|
@oobabooga Updated performance comparison for SummaryThe 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 PRI manually tested both versions under normal browsing conditions, including scrolling, typing, searching, and navigating large conversations. Guard (base + suggested guard):
Current PR (
Side-by-side video recordingsI've attached two manually recorded comparisons demonstrating the difference: ** Guard (base + suggested guard)** guard_compressed.mp4guard_2_compressed.mp4** Current PR ( after_compressed.mp4after_2_compressed.mp4These 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 resultsTest environment: Windows, Chrome 155, 240 Hz display, three traced runs per comparison.
Workloads:
Results are averages across three automated runs. CPU 1× represents unthrottled execution; 4× represents CPU throttling. 1. Full-thread scrolling — Current PR substantially fasterCompositor presentation rate (higher is better)
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
The p99 values are particularly relevant: they represent the slow end of the recorded frame-interval distribution. For example, under 4× CPU throttling:
This demonstrates substantially fewer long frame intervals during automated traversal with the current PR. 2. Renderer work during scrolling — Current PR winsAccumulated renderer task time during unthrottled full-thread traversal:
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 resultsFast native scrollbar dragging was measured separately from full-thread traversal.
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:
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 resolvedThe previous PR revision had noticeably slower resize measurements. The current revision brings resizing back to approximately guard-level performance. Answer-only proxy:
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 costsThese are individual restyling operations, not continuous scrolling performance. Absolute times are shown rather than potentially misleading percentage increases. Answer-only proxy
Expanded conversation, native CPU
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-offsAnswer-only proxy:
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 workloadThis measures accumulated renderer task wall time across the complete automated sequence: loading, expansion, traversal, dragging, resizing, theme/font changes, and measurement overhead.
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
ConclusionThe 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. |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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.
|
@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 This update compares:
These are improvements on top of the previous PR results, not another comparison against the suggested guard. Desktop App Showcase - mid streaming!prdesktop_.mp4Summary
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 consistentThree-run averages, comparing Presentation rate and frame intervals
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:
The answer-only workload now approaches the 240 Hz refresh rate even under 4× throttling in this particular test. Frame consistencyLower intervals are better.
¹ Worst interval is the average of each run's single worst recorded frame interval, not the p99 value. Notable improvements:
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 tasksThese measurements show how much renderer work occurs during initial scrolling. Longest renderer task
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
The current changes reduce accumulated renderer task time by:
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 workSeparate measurements using production React components in Linux Chromium, unthrottled, with precomputed tokens. Comparison:
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:
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
|
| 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
FenceLinesrender 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.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.
|
@codex review |
1 similar comment
|
@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.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
## 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. 
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>
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
code-fence-defer.tsx,onScrollbarincode-fence-window.ts).window.deferis still reachable through__UNSLOTH_DEFER_FENCE_HIGHLIGHT__/VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT. See the slow read numbers below for why.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.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):
defer)The same drag on a Windows 11 runner in Microsoft Edge at 4x: main 3,940 ms of long frames, main + guard 67 ms,
defer0 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):
deferdefaultWith
deferevery 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), anddefer4.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
dragstart, each failing without its fix.Not covered
__UNSLOTH_DEFER_FENCE_HIGHLIGHT__ = "defer".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.