Repository navigation
Studio: defer off-screen code fence highlighting, one way only - #9462
Conversation
…eting stream, and scope the print upgrade to mounted fences
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58faeded45
ℹ️ 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".
| // How far outside the viewport a fence counts as "reached". One viewport of | ||
| // slack in each direction, so the upgrade has a frame or two to land before the | ||
| // block is actually on screen and the reader never sees the swap. | ||
| const REACH_MARGIN = "100% 0px"; |
There was a problem hiding this comment.
Base the reach margin on the scroller height
On tall or portrait viewports, this does not provide the documented one-viewport lookahead: IntersectionObserver resolves percentage rootMargin values against the root rectangle's width, including for the top and bottom margins. For example, a 400×800 thread viewport starts an upgrade only 400 px ahead, while the layout-effect path uses the full 800 px height, so fences reached by scrolling can remain deferred much closer to the visible area and expose the shell when highlighting is slow. Compute the vertical margin from the scroller height in pixels so both reach paths use the same distance.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible: the premise does not hold in either engine Studio ships against. I measured it rather than reasoning about it, with a 400x800 root and rootMargin: "100% 0px", reading entry.rootBounds back:
| engine | root | rootBounds | vertical expansion per side |
|---|---|---|---|
| Chromium | 402 x 802 | 400 x 2400 | 799 px |
| WebKit | 402 x 802 | 400 x 2400 | 799 px |
The vertical margin resolves against the root's HEIGHT, not its width. On the 400x800 example in the item the upgrade starts 800 px ahead, not 400 px, so the layout-effect path and the observer path already use the same distance and there is nothing to reconcile.
The item is a reasonable reading of the spec text, which is why I checked instead of dismissing it: w3c/IntersectionObserver#391 records that section 2.2 says percentages resolve against the width while implementations resolve top and bottom against the height, and MDN documents the per-axis behaviour. Both engines here follow the implementations, not the prose.
Leaving it as a percentage. Switching to a pixel value computed from the scroller height would be equivalent today and would need its own resize handling to stay correct, which is cost for no behavioural change.
…the lookahead works inside the reasoning pane
The `beforeprint` path did not work, and the measurement is the reason. Dispatch and read back in one synchronous task, 100K rung, cold open: delay after open flag off: blocks on the raw fallback flag on 1.5 s 56 of 56 56 of 56 3 s and beyond 0 53 of 56 Streamdown renders `<Suspense>` around a lazily imported highlighter body and `code.highlight` runs from an effect, so no amount of grammar warm-up or extra `flushSync` produces tokens inside the synchronous print task. The shipped build has a real window of about three seconds and is fully highlighted after it; with the flag on, 53 of 56 blocks stayed on the raw fallback out to twenty seconds. The earlier reading that suggested otherwise waited 500 ms before snapshotting, so it measured the asynchronous path completing rather than the synchronous one, and a later probe used a zero-span discriminator that never fires because the fallback still emits one token span per line. Removed: the module-level listener set, the `beforeprint` and print-media listeners, the double `flushSync`, the chunk-warm claim and the per-language grammar warm-up. In their place is a block comment carrying the table, so the limitation is written down where the decision was taken. With the flag on, printing a long thread prints unreached fences without syntax colour; the text itself is a live text node and prints complete, in order and correctly laid out.
Two things, both of which changed what a number means. `getCodeFence` captures the whole info string, so a fence opened with metadata such as ```python startLine=10 arrived as "python startLine=10". Markdown treats everything past the first word as metadata and Streamdown highlights the block as `python`, so the raw string was labelling the deferred shell with the metadata attached, and handing the measurement arm a language no grammar matches. That arm exists to put the tokenizer work back while holding the DOM at the deferred size; tokenizing as plain text instead makes it measure nothing and quietly corrupts the open_ms split it supports. The info string is now split once and both the shell and the arm use the token. Adjacent-token coalescing comes out. It was measured at exactly 0.0% over the 100K rung's 99 real fences in all three theme modes, because Shiki already emits maximally coalesced tokens, and a mechanism that removes no spans cannot make anything faster. Keeping the implementation meant carrying a runtime-flippable flag through the fence cache, where a cached result can disagree with the flag that produced it: an exact cache hit never reaches the merge, and a growing fence keeps lines committed under the old setting, so flipping the flag off mid-session can go on serving merged tokens and contaminate the very baseline the override exists to measure. The census stays in the file as a comment with its numbers, and `scripts/coal_span_census.mjs` reproduces it standalone. Both are pinned by tests.
Observing the FENCE against the outermost root clips it at the reasoning pane on the way, so the outer gate went false exactly where the inner lookahead was supposed to be doing its work. Fences reached out of ten, both engines: case inner both gated observer built capped, cap then drops 10 0 0 pane capped, scrolled away 4 0 0 pane capped, in view 4 2 4 cap dropped, scrolled away 0 0 0 cap dropped, in view 10 10 10 `both` is the fence watched against both roots: the pre-warm inside the pane drops from 4 to 2, which is the plain shell showing while a fence scrolls into the pane. `gated` is the pane watched against the outer root and the fence against the inner one: every out-of-view case still reports 0, and the in-pane lookahead is back to 4. So the two gates watch two different elements. The fence against the nearest scroller answers "the reader is about to reach it inside the pane"; the pane against the outermost scroller answers "the pane is somewhere the reader can see". When the two scrollers are the same element, which is every fence outside a nested scroller, there is one observer and this costs nothing. The pre-paint door asks the same two questions of the same two elements.
The comment recording the coalescing null cited a script that only existed on the machine the census was run on, which makes the citation worth nothing. `studio/frontend/scripts/coal-span-census.mjs` is that script, taking any markdown and extracting the fences itself, and a test asserts the file the comment names actually exists. Run over the whole studiobench corpus rather than one rung, it is a stronger null than the one quoted: 728 fences, 1,335,897 code characters, 537,013 tokens, 0.0% merged in dual and 535,981 tokens 0.0% merged dark only. Not one adjacent pair in half a million shares a rendered style. The extraction is a line scanner, not one regex. The regex version treated every CLOSING delimiter as a fresh opener and reported 1,456 fences of one line each where there are 728. Separately, which fences this covers is now written down where the decision is made. `CODE_FENCE_RE` accepts exactly three backticks, unindented, so tildes, four or more backticks and indented fences never reach the deferral path and render exactly as they do today. That is unrealised benefit rather than a wrong result, and it is left alone deliberately: `getCodeFence` also decides whether a block is an SVG or a full HTML document to be shown as an artifact, and a fence that does not match it renders a bare Block with no wrapper and no copy button, so widening the regex would add an artifact path and a copy overlay to blocks that do not have them today. It moves no number here either: over the frozen corpus, 2,467,069 characters, all 1,456 fence delimiters are unindented triple backticks.
…ling The conjunction was not enough on its own, and the earlier probe could not show it because it held the pane 4,000 px out of view, where the outer gate is false and covers for the stale inner root. Scroll the expanded pane so much as partly on screen and the outer gate is true, so the stale root decides alone. On a 4,080 px trace against a 900 px viewport, fences reported reached: stale inner root, pane on screen 10 of 10 after re-resolving 4 of 10 where about 3 is the honest answer. Chromium and WebKit agree. reasoning.tsx drops max-h-64 when a stream ends and keeps overflow-y-auto, so the pane stops being a scroller and its box becomes the whole trace. A ResizeObserver on the pane now rebuilds the gates when that happens, which collapses the fence back to the single-gate case with the outermost scroller as the root, where nothing can be stale. Watched rather than re-resolved per frame, and only for fences that actually have a nested scroller. The callback reads one overflow-y on one element, so a pane resizing every frame while it streams costs one computed-style read per fence per frame and rebinds nothing until the cap comes off. Still one-way: the rebind can withhold a latch, never clear one, and a test refuses setGeneration(0) and setLatched(false) by name.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7d92c550d8
ℹ️ 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".
| data-streamdown="code-block-body" | ||
| > | ||
| <pre> | ||
| <code>{trimTrailingNewlines(source)}</code> |
There was a problem hiding this comment.
Preserve the real renderer's empty line
When deferral is enabled for a settled empty fence (or one containing only trailing newlines), this expression renders an empty <code> element with no line box. Streamdown's fallback/highlighted renderer instead represents an empty token line with a newline inside a block span, so the fence gains one line of height when it is reached and upgraded. Preserve that empty line in the shell to avoid a layout and scroll-position jump for these fences.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and confirmed against streamdown's own renderer rather than reasoned about. bed93f8b.
From chunk-BO2N2NFS.js:
children: c.length === 0 || (c.length === 1 && c[0].content === "") ? `\n` : c.map(...)and the same file trims trailing newlines off the source first with the identical loop this shell uses. So a fence whose body is empty, or is nothing but newlines, tokenizes to a single empty line and renders as one line box. A <code> holding an empty text node has no line box at all, so the shell was one line shorter than the block it stands in for, and the fence grew by a line the moment it upgraded, moving everything below it.
Fixed by mirroring the rule:
const shellBody = (source: string): string => {
const trimmed = trimTrailingNewlines(source);
return trimmed === "" ? "\n" : trimmed;
};Worth saying which way this cuts for the numbers, since it is the kind of thing that could look like it invalidates them. It does not: the frozen corpus contains no empty fence, so the mechanism table reporting scrollHeight identical to the pixel is unaffected in either direction. This is a correctness fix for real threads, not a correction to a measurement.
A test carries streamdown's expression as a comment, runs the rule over "", "\n\n\n" and "x", and refuses <code>{trimTrailingNewlines(source)}</code> being rendered directly, which is the shape that loses the case.
Streamdown special-cases the empty token line, from its own renderer:
children: c.length === 0 || (c.length === 1 && c[0].content === "")
? `\n` : c.map(...)
and it trims trailing newlines off the source first, with the same trim this
file uses. So a fence whose body is empty, or is nothing but newlines,
tokenizes to a single empty line and renders as one line box of height. A
`<code>` holding an empty text node has no line box at all, so the shell was a
line shorter than the block it stands in for and the fence grew by a line when
it upgraded, moving everything below it.
The corpus has no such fence, so no measurement here moves; the mechanism table
reporting scrollHeight identical to the pixel is unaffected either way. A test
reproduces streamdown's rule and refuses the raw trim being rendered directly.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0b1f5d89b5
ℹ️ 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".
| // eslint-disable-next-line react-hooks/set-state-in-effect | ||
| setLatched(true); | ||
| } | ||
| }, [reached, host]); |
There was a problem hiding this comment.
Re-run the prepaint gate when rebinding roots
When the nested reasoning pane loses max-h-64, the ResizeObserver increments generation to re-resolve the scrolling root, but this layout effect does not depend on that generation. If expanding the pane exposes an unreached fence inside the outer viewport, the render triggered by the rebind therefore leaves the plain shell in place; the replacement observer is created only in the passive effect and delivers asynchronously, so the shell can be painted for one or more frames. Include the rebind generation in the prepaint check so newly visible fences latch during the same commit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 62702d2.
The ResizeObserver bumped generation and the passive effect rebuilt its observers off it, but the pre-paint effect's dependency list was still [reached, host]. So bringing a fence inside the outer viewport for the first time left the plain shell in place for the rebind's own render, and the replacement observer delivers asynchronously. generation is now in that dependency list, with the reason recorded beside it.
Taking this as genuine on a slightly different basis than the strict bar. This change's whole case is that its differences are off screen, so a newly visible fence painting as an unhighlighted shell is on screen and belongs in the same accounting as the reopen flash already documented here.
The regression test slices the pre-paint effect out of the source by its own comment and asserts the slice really is the effect that latches, so it cannot silently start pinning a different effect, then requires generation in the dependency list. It fails before the fix and passes after: 16 pass 1 fail, then 17 pass 0 fail. Full suite 4,296 pass, typecheck clean.
The ResizeObserver bumps `generation` when the reasoning pane stops scrolling, and the passive effect rebuilds its observers off that, but the pre-paint effect did not depend on it. So if expanding the pane brings a fence inside the outer viewport for the first time, the render the rebind causes leaves the plain shell in place, and the replacement observer is created in a passive effect and delivers asynchronously, so the shell is painted for one or more frames. That is an on-screen difference, which is the one kind this change is not allowed to have. It is the same family as the 2 frame reopen flash already disclosed in the body, and it belongs in the same accounting rather than being left to be found later. The fix is the dependency. A test slices the pre-paint effect out by its own comment, checks it is the effect that latches, and requires the generation in its dependency list; it fails on the previous commit and passes on this one.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…i#9567) * Studio: defer off-screen code fence highlighting by default Turns on the mechanism merged in unslothai#9462, which has been inert behind a flag because turning it on caused two things a reader could see. Both are fixed here rather than accepted, so the default moves with neither of them. A DISCONTINUOUS SCROLL PAINTED PLAIN CODE. A scrollbar drag, Ctrl+End or an anchor jump can move the viewport further than the observers' one-viewport lookahead, with no React render in between, and an IntersectionObserver record arrives after the browser has painted. Measured in Chromium at the 100K rung: 29 of 274 painted frames on 8 of 16 jumps, median 92 ms. A capturing scroll listener now latches the fences the jump landed on inside the same task, so the swap is part of the frame the reader is about to see. The test for "is this a jump" is derived from the observer margin rather than picked: a scroll of at most one root height can only reveal fences the observers had already reached, so the pass runs when, and only when, the lookahead provably did not cover the movement. A continuous scroll pays one subtraction per event, and the listener is removed when the last fence latches. PRINT LOST COLOUR ON ONE OR TWO FENCES PER PAGE. A print lays the document out at paper width while the scroll offset carries across as a raw pixel count, so the printed page lands several fences away from the reader's window. The whole document is on the page, so the whole document is now highlighted, through both doors: beforeprint for Ctrl+P and the print menu, and the print media query for page.pdf and PDF export. An earlier attempt at this was removed after it was measured to leave 53 of 56 blocks on streamdown's raw fallback. The reason was not the latch. Streamdown's highlighted body asks the plugin for tokens from a passive effect and shows a plain fallback until it answers, and the plugin answers null while a grammar is still loading, so latching alone renders the block UNHIGHLIGHTED. Three things close it, all of them needed: the tokens are warmed first so the render is a cache hit; grammars are loaded at idle, empty-string tokenizations that mount no span, so a loading grammar can never be what is missing; and the flush is nested, because react-dom only runs pending passive effects when it has sync work, and it restores the update priority before it flushes. Measured on this commit, Chromium, 100K rung, against current main served concurrently on the same machine, with the pre-fix build served alongside as an in-run control: painted frames showing plain code main 0/822 this 0/821 pre-fix 81/817 jumps affected main 0/45 this 0/45 pre-fix 24/45 printed page vs main, Letter 6.5628% -> 0.0034% differing pixels deferred fences on a printed page 1 to 2 per page -> none Idempotency is unchanged: 160 of 160 viewports byte-identical at matched scroll positions with the null also identical, 0 reverse edges within a mount against a mutant scoring 152, and 0 settled positions showing a plain fence. At the 100K rung the thread mounts 22,808 elements instead of 61,760 and 2,458 highlight spans instead of 41,410, with 53 of 56 fences deferred at rest, which is what the flag was for and is unchanged by the two fixes above. * Studio: ask the heavy-thread fixture check something deferral cannot move The heavy-thread smoke asserts every kind of content its fixture claims to build is really on the page, so that a thread which quietly stopped rendering code cannot pass as a heavy thread. It asked that question in highlighted tokens, and with off-screen fences deferred a token count is partly a measurement of where the viewport is: the same untouched fixture renders 1,322 tokens for one cycle where it rendered 3,216 before, and the check failed. The number was doing two jobs, and deferral separates them. IS THIS THE HEAVY THREAD IT CLAIMS TO BE. Asked in characters of code, which the deferred shell carries because it holds the same text node the highlighted block holds. Measured at 12,660 for one cycle and 51,081 for four, with 2 of 5 and 15 of 20 fences deferred, and identical to the character on Chromium, Firefox and WebKit. One cycle is seven code blocks averaging about 1,800 characters, so the 660 of slack under the floor is well short of the smallest thing that could go missing. HAS THIS THREAD FINISHED BUILDING ITSELF. Asked per block rather than in total: every fence is either a deferred shell, which is a state with an attribute, or it is highlighted. The third state, mounted and showing streamdown's own unhighlighted fallback, lasts a frame on any build and a settled thread holds none. That is stricter than the floor it replaces, which one block stuck on the fallback passed as long as the others made the count up. The census also prints fence blocks, deferred fences and code characters beside the token count, so a reader can see how much of the thread the viewport had reached rather than inferring it from a total that now means two things. Proved to still bite by breaking the fixture for real rather than by argument: stopping the python fence from growing, with highlighted tokens untouched, fails with "rendered 19595 codeChars, short of the 24000 its 2 content cycles should produce". The three offline cases are pinned as tests, including one asserting that a deferred thread is NOT a failure. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: a print upgrades the page it printed, not the rest of the session * Studio: write down that a percentage rootMargin follows the engines, not the spec text * Studio: tighten the comments around deferred fence highlighting Compress the prose in and around the defer-by-default change without losing any of the measurements it records: the IntersectionObserver percentage-versus-height discrepancy and its per-engine rows, the print latch scoping and its span and element counts, the engine-invariant code-character figures, and the stated limitations. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…nslothai#11741) * studiobench: compare a code fence one arm scrolled past on its text The UI parity gate failed on backend-only pull requests (unslothai#11724, unslothai#11727, and others on 2026-09-23) with differences like msg15(assistant):1847269->2150610c on model_change, reasoning_toggle, select_all_copy, settings and image_upload at r100K. Those are not rendering differences. code-fence-defer.tsx (unslothai#9462, the default since unslothai#9567) renders a fence as a plain shell until it first comes within a viewport of the reader, then highlights it for the rest of the mount. After reasoning_toggle the r100K film leaves the viewport either near the tail (scrollTop ~50,740) or about 20,000px higher, at random per cell on one build (78 of 172 cells across 43 recorded payloads), and the higher landing latches the fences of msg11/13/15 until thread_reopen remounts them. A null control whose cells all landed low measured those actions stable, so the result's latch noise was scored as a regression. The same noise also made a null that did see it excuse settings and model_change outright, which hid real changes there. scene/parity.js now reads, in the same walk that produces the unchanged per-message digest, each fence's latch state, full digest and text digest (whitespace dropped, since streamdown emits one span per line and the shell one text node), plus the message with every fence replaced by a marker. analysis/parity.fence_latch_residue treats a message as differing only by latch when everything outside its fences matches, every fence latched on both arms or neither matches in full, and every fence latched on one arm only matches on its text. Nothing is excused when one arm latched no fence anywhere, which is what a build whose fences never upgrade looks like. A latch-only pair is a MATCH, counted and printed, so it costs no coverage; payloads recorded before this carry no fence fields and score exactly as before. The selftest replays both failing runs from their recorded CI payloads, shows they fail as recorded and pass once the latch is recorded, and injects genuine differences (a message with no fences, a change outside a latched message's fences, a highlighting change on a fence both arms latched, fences that never upgrade) that must still fail. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studiobench: keep a fence's spacing and language in the latch comparison The one-sided fence comparison dropped every whitespace character, so `x = 1` and `x=1`, an indentation change or a space inside a string read as the same fence, and it never looked at the language, so a fence that changed language but kept its body read as latch-only too. Drop line breaks only, the one thing that differs between the shell and the highlighted form, keep the rest of the text as it is, and record and compare each fence's data-language. * studiobench: read a fence's text as lines, not a run of characters Dropping every newline made a line break moved within the code, `a\nbc` against `ab\nc`, read as the same fence. Read both forms as lines: the shell's text split on newlines, and the highlighted fence one line per element directly inside its <code>, a blank line's lone newline dropped. Join them with one newline and drop trailing blank lines, which the shell trims. * studiobench: compare a fence's text as written, without prose placeholders The time and id placeholders are there for UI prose. Applied to a one-sided fence's source they made `"295ms"` against `"310ms"`, or two different timestamp or id literals, read as the same code. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…nslothai#11741) * studiobench: compare a code fence one arm scrolled past on its text The UI parity gate failed on backend-only pull requests (unslothai#11724, unslothai#11727, and others on 2026-09-23) with differences like msg15(assistant):1847269->2150610c on model_change, reasoning_toggle, select_all_copy, settings and image_upload at r100K. Those are not rendering differences. code-fence-defer.tsx (unslothai#9462, the default since unslothai#9567) renders a fence as a plain shell until it first comes within a viewport of the reader, then highlights it for the rest of the mount. After reasoning_toggle the r100K film leaves the viewport either near the tail (scrollTop ~50,740) or about 20,000px higher, at random per cell on one build (78 of 172 cells across 43 recorded payloads), and the higher landing latches the fences of msg11/13/15 until thread_reopen remounts them. A null control whose cells all landed low measured those actions stable, so the result's latch noise was scored as a regression. The same noise also made a null that did see it excuse settings and model_change outright, which hid real changes there. scene/parity.js now reads, in the same walk that produces the unchanged per-message digest, each fence's latch state, full digest and text digest (whitespace dropped, since streamdown emits one span per line and the shell one text node), plus the message with every fence replaced by a marker. analysis/parity.fence_latch_residue treats a message as differing only by latch when everything outside its fences matches, every fence latched on both arms or neither matches in full, and every fence latched on one arm only matches on its text. Nothing is excused when one arm latched no fence anywhere, which is what a build whose fences never upgrade looks like. A latch-only pair is a MATCH, counted and printed, so it costs no coverage; payloads recorded before this carry no fence fields and score exactly as before. The selftest replays both failing runs from their recorded CI payloads, shows they fail as recorded and pass once the latch is recorded, and injects genuine differences (a message with no fences, a change outside a latched message's fences, a highlighting change on a fence both arms latched, fences that never upgrade) that must still fail. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studiobench: keep a fence's spacing and language in the latch comparison The one-sided fence comparison dropped every whitespace character, so `x = 1` and `x=1`, an indentation change or a space inside a string read as the same fence, and it never looked at the language, so a fence that changed language but kept its body read as latch-only too. Drop line breaks only, the one thing that differs between the shell and the highlighted form, keep the rest of the text as it is, and record and compare each fence's data-language. * studiobench: read a fence's text as lines, not a run of characters Dropping every newline made a line break moved within the code, `a\nbc` against `ab\nc`, read as the same fence. Read both forms as lines: the shell's text split on newlines, and the highlighted fence one line per element directly inside its <code>, a blank line's lone newline dropped. Join them with one newline and drop trailing blank lines, which the shell trims. * studiobench: compare a fence's text as written, without prose placeholders The time and id placeholders are there for UI prose. Applied to a one-sided fence's source they made `"295ms"` against `"310ms"`, or two different timestamp or id literals, read as the same code. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Off-screen code fences render as plain text and upgrade to highlighted once, on first viewport entry. The latch is never released, so a fence goes plain to highlighted exactly once and never back. Behind
VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT, default off.Merging this changes nothing anybody sees.
fenceMode()returns"off"when the variable is unset, and the build verifies it by reading the inlined literal back out of the emitted bundle rather than trusting the environment: the default build carries an empty string, the treatment build carriesdefer. So what the measurements below decide is not whether to merge, it is whether the flag is ever worth turning on.Every number here is from bundles built at
bed93f8b, the head of this branch, and the commit is stamped into each dist and read back after the copy.The worst case first, because it is the one that could sink this
A reader who scrolls their whole history reaches every fence, so the deferral buys nothing and the observers are pure overhead. That case was measured, not argued: a second film whose scroll traverses 58,441 px against the 56,455 px thread, with
commanded_px == travelled_pxconfirmed in the payload before anything was read out of it.Nothing is slower past its floor. The traversal itself, scored against a concurrent in-band null built from byte-identical bundles:
scroll_after.gesture_msscroll_after.per_step_msmax_frame_msselect_all_copy.total_msselect_all_copy.copy_mscopy_markdown.copy_msjank_indextime_in_jank_pctreasoning_toggle.open_msThe honest reading of the worst case is the absence of a regression, not the presence of a win: in that film the in-band null itself moves 51% on
delete_message.delete_msand 57% onreasoning_toggle.close_ms, so those rows resolve nothing at all and are excluded. What does hold is the top of the table. Scrolling the whole thread costs the same as it does today, to within a floor of 1.4%, and the select and copy rows converge on base as expected once everything has upgraded.Mechanism, before any timing
Median of 3, CDP
Performance.getMetrics, 100K rung, flag off versus on:pre spanselection.toString()select_allText-neutral to the character. For the record, since a larger figure has been circulating: the resting document at 100K is 61,736 elements, 41,410
pre span, 112,171 LayoutObjects.Scored, standard film, 100K rung
standardtier, 100K only,--reps 4 --shards 2, with two concurrent in-band null controls: a flag-off build against itself, and the driver's defaultbase_main. Three gates: a per-metric floor ofmax(|null delta|, null spread), sign consistency, and the effect must exceed its own scatter.base_mainfloorjank_indexdelete_message.delete_msselect_all_copy.copy_msselect_all_copy.total_msselect_all_copy.select_all_mstime_in_jank_pctmax_frame_msthread_reopen.close_msreasoning_toggle.close_msbase_mainonlyreasoning_toggle.open_msbase_mainonlythread_reopen.reopen_msbase_mainonlyEight rows clear both nulls. The three
reasoning_toggleandthread_reopen.reopen_msrows clear thebase_mainfloor but not the own-build one, because the own-build null was itself moving 52% on those metrics in this run. They are reported rather than dropped, and they should not be quoted as established. The own-build null returned NO CHANGE overall: every one of its 35 metrics landed inside the floor.On select and copy specifically.
content-visibilityon code blocks costs +28.8% onselect_all_ms, because skipped content must be rendered before it can be selected. This goes the other way, -54.6%, andselected_charsis identical on both arms. The deferred text is a live text node, not skipped content, so there is nothing for the browser to render first.On stream cost. That instrument carries a systematic bias on the treatment side, independently measured at +17% to +19% under byte-identical bundles, so it has to be read against the null's own delta and never against zero. Here the own-build null reads +36.5% on cost per 1,000 reply characters and +7.4% on
busy_pct. Against that, defer reads +27.9% and +5.0%: below the artefact on both, so no stream-cost regression, and if anything a small reduction. Quoted against zero the same numbers would read as a 28% regression, which is why they are printed side by side.Why this is not #9386 again
#9386 had the same idea and measured 12.7% slower on
reasoning_toggle.close_ms. It gated on viewport entry and exit, so the work was bidirectional: closing a reasoning pane pushed blocks out of view and created gating and re-highlight work. Here the transition is one way.useFenceReachedlatches, every effect early-returns once reached, and the observers are disconnected forever. Nothing in the change can clear a latch; the extra gate and the rebind described below can only withhold one.Two other differences that matter:
code-plugin.ts, which only receives{code, language, themes}, so every block was highlighted once before it could be downgraded. Here a fence that is never reached never callshighlight()at all.relative isolatedivmarkdown-text.tsxalready renders.Where
reasoning_toggle.open_msgoesA third build makes the split reproducible from the tree.
VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT=tokenizerenders the deferred shell but still runs the tokenizer, so the document cost and the tokenizer cost can be told apart:open_msand in the scored sweep, -16.9% and -40.5% on the same axis. CDP brackets the open: script 938.0 -> 853.4 -> 641.9 ms, style recalc 486.8 -> 220.0 -> 226.3 ms, spans mounted 57,781 -> 4,317 -> 4,317. So roughly 40% of the win is not mounting the pane's spans and the rest is not tokenizing them, which is consistent with the earlier dose ablation reading
open_msas a null: that ablation moved RESTING spans, and this moves the first-mount cost of the pane's own fences. The arm is reachable only by the explicit string and is pinned by a test.Read against the own-build null this row does not clear its floor in this run, so the mechanism is identified but the effect size is not established. Both statements belong here.
A null worth recording, so nobody repeats it
The obvious cheaper idea is to merge adjacent Shiki tokens that share a rendered style. It buys exactly nothing. Over the whole corpus, 728 fences and 1,335,897 code characters, through Studio's own Shiki configuration: 537,013 tokens -> 537,013 merged in dual mode, 535,981 -> 535,981 dark only. Over the 100K rung's 99 assembled fences: 72,550 -> 72,550, 72,408 -> 72,408, 62,098 -> 62,098.
Not one adjacent pair in half a million shares a rendered style, in any theme mode. Shiki already emits maximally coalesced tokens. No timing was run on it, because a mechanism that removes no spans cannot make anything faster. The implementation is not shipped: carrying a runtime-flippable flag through the fence cache for a measured-zero benefit only creates ways for a cached result to disagree with the flag that produced it.
studio/frontend/scripts/coal-span-census.mjsreproduces the census on any markdown, and a test asserts the file the comment cites actually exists.Nested scrollers, which took three measurements to get right
An explicit IntersectionObserver root is clipped by the ancestors between the target and the root and by nothing above it. Rooting at the streaming reasoning pane therefore asks only "is this fence inside the pane's window". Ten fences in a 256 px
overflow-y-autopane nested at 4,000 px inside an 800 px scroller, reported reached, Chromium and WebKit identical:reasoning.tsxdropsmax-h-64when a stream ends and keepsoverflow-y-auto, so the pane stops being a scroller and its box becomes the whole trace. Three separate defects fell out of that and all three are fixed: the fence must be gated on the outermost scroller as well; the outer gate must watch the pane, not the fence through it, or it clips twice and cancels the lookahead it was rooted at the pane to get; and the gates must be rebuilt when the pane stops scrolling, because with the pane partly on screen the outer gate is true and a stale inner root reports the whole trace, measured at 10 of 10 on a 4,080 px trace where 3 is the honest answer, against 4 of 10 after re-resolving.scripts/coalmono_stale_root_probe.pyreproduces all of it.What this does not do
beforeprintpath that latched every mounted fence, warmed grammars at idle and flushed twice. It was removed because it was measured and it did not work: synchronous dispatch and read in one task, 53 of 56 blocks stayed on streamdown's raw fallback at every delay out to twenty seconds, where the shipped build has a window of about three seconds and is fully highlighted after it. Streamdown wraps a lazily imported highlighter body in<Suspense>andcode.highlightruns from an effect, so no warm-up or extraflushSyncproduces tokens inside the synchronous print task. With the flag on, printing a long thread prints unreached fences without syntax colour. The text is a live text node, so it prints complete, in order and correctly laid out.CODE_FENCE_REaccepts exactly that form, so tildes, four or more backticks and indented fences render as they do today. Widening it would also widen the SVG and HTML artifact path and add a copy overlay to blocks that do not have one, which is a rendering change that does not belong in a performance PR. Over the frozen corpus, 2,467,069 characters, all 1,456 fence delimiters are unindented triple backticks, so no measurement here is inflated by the gap.IntersectionObserverper unreached fence, and a second plus aResizeObserveronly for fences inside a nested scroller. Over a full 133-step traversal the observers cost 4,516 ms against 4,433 ms with every observer disconnected, and nothing at all once a fence has upgraded.Behaviour checks
npm test4,295 pass, 0 fail. Typecheck clean. Lint adds no error overorigin/main's own copy of the same files.select_all_copyrows are Chromium only. Playwright WebKit does not copy on Ctrl+C at all, so any WebKit row on that action measures the harness's own wait.Reproducing
with a concurrent in-band null control, scored through
tests/studio/studiobench/sweep/floor_table.py.GRID_COLLAPSE_REASONING_ENABLEDisfalseon main, so #9423 is inert and the base here is main with that flag off.