Skip to content

Studio: defer off-screen code fence highlighting, one way only - #9462

Merged
danielhanchen merged 19 commits into
mainfrom
coal-mono
Aug 22, 2026
Merged

danielhanchen merged 19 commits into
mainfrom
coal-mono

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

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 carries defer. 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_px confirmed 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:

metric defer null null spread floor verdict
scroll_after.gesture_ms -1.2% -1.0% 1.4% 1.4% VOID
scroll_after.per_step_ms -1.2% -1.0% 1.4% 1.4% VOID
max_frame_ms -0.8% +0.3% 7.9% 7.9% VOID
select_all_copy.total_ms -0.7% -0.7% 3.0% 3.0% VOID
select_all_copy.copy_ms -1.2% 0.0% 5.3% 5.3% VOID
copy_markdown.copy_ms -0.1% -0.2% 0.4% 0.4% VOID
jank_index -36.3% -24.2% 11.4% 24.2% faster
time_in_jank_pct -21.2% -16.8% 11.4% 16.8% faster
reasoning_toggle.open_ms -40.5% -17.7% 7.1% 17.7% faster

The 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_ms and 57% on reasoning_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:

off on delta
LayoutObjects 112,171 31,699 -71.7%
Nodes 116,512 78,646 -32.5%
elements 61,736 22,783 -63.1%
pre span 41,410 2,458 -94.1%
deferred fences 0 53
selection.toString() 9.7 ms 2.9 ms -70.1%
selected characters 189,318 189,318 0
select_all 0.1 ms 0.1 ms 0

Text-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

standard tier, 100K only, --reps 4 --shards 2, with two concurrent in-band null controls: a flag-off build against itself, and the driver's default base_main. Three gates: a per-metric floor of max(|null delta|, null spread), sign consistency, and the effect must exceed its own scatter.

metric n defer base_main floor own null own floor scatter clears
jank_index 4 -71.0% 10.3% +15.9% 45.4% 5.6% both
delete_message.delete_ms 4 -59.4% 9.1% -0.9% 25.2% 4.0% both
select_all_copy.copy_ms 4 -57.8% 6.9% -2.7% 8.2% 5.3% both
select_all_copy.total_ms 4 -57.3% 7.3% -2.3% 7.7% 4.4% both
select_all_copy.select_all_ms 4 -54.6% 22.3% -5.7% 23.9% 11.6% both
time_in_jank_pct 4 -45.5% 11.9% +8.2% 13.6% 4.7% both
max_frame_ms 4 -44.7% 4.8% +9.0% 38.6% 6.1% both
thread_reopen.close_ms 4 -42.4% 10.2% +0.7% 22.6% 16.9% both
reasoning_toggle.close_ms 4 -48.5% 3.4% +18.3% 52.0% 25.3% base_main only
reasoning_toggle.open_ms 4 -40.5% 15.3% +13.8% 52.4% 11.0% base_main only
thread_reopen.reopen_ms 4 -9.8% 8.8% -18.4% 75.4% 8.4% base_main only

Eight rows clear both nulls. The three reasoning_toggle and thread_reopen.reopen_ms rows clear the base_main floor 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-visibility on code blocks costs +28.8% on select_all_ms, because skipped content must be rendered before it can be selected. This goes the other way, -54.6%, and selected_chars is 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. useFenceReached latches, 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:

Where reasoning_toggle.open_ms goes

A third build makes the split reproducible from the tree. VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT=tokenize renders the deferred shell but still runs the tokenizer, so the document cost and the tokenizer cost can be told apart:

open_ms delta from off
off 1,213.0 ms
tokenize 1,023.5 ms -15.6%
defer 807.6 ms -33.4%

and 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_ms as 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.mjs reproduces 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-auto pane nested at 4,000 px inside an 800 px scroller, reported reached, Chromium and WebKit identical:

case inner root alone fence against both roots pane against outer root
observer built while capped, cap then dropped, pane out of view 10 0 0
pane capped, scrolled away 4 0 0
pane capped, in view 4 2 4
cap dropped, in view 10 10 10

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. 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.py reproduces all of it.

What this does not do

  • The win is a function of how much of the thread the reader visits. The standard film's scroll is 5,880 px against a 56,455 px thread, so 53 of 56 fences are never reached. That is a fair model of "open a long thread and work near the bottom", which is the reported complaint. It is not a claim about a reader who scrolls their whole history; that case is the worst-case section above, and it is neutral.
  • Printing is a stated limitation. There was a beforeprint path 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> and code.highlight runs from an effect, so no warm-up or extra flushSync produces 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.
  • A fence on screen at first mount renders plain for 2 frames, about 50 ms. An already-laid-out fence latches before paint, but on a fresh navigation the first frames are 60 to 160 ms apart while the thread loads and the observer's first delivery is asynchronous. Measured 0 frames flag off, 2 frames flag on.
  • Only unindented triple-backtick fences defer. CODE_FENCE_RE accepts 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.
  • One IntersectionObserver per unreached fence, and a second plus a ResizeObserver only 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

  • Native find-in-page over deferred fences: 15 of 15 needles found with 71 deferred fences on the page, against 15 of 15 flag off.
  • UI parity: 64 action pairs agreed on every stable action, on both films.
  • npm test 4,295 pass, 0 fail. Typecheck clean. Lint adds no error over origin/main's own copy of the same files.
  • The select_all_copy rows 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

python3 -m tests.studio.studiobench --tier standard --rungs 100K --reps 4

with a concurrent in-band null control, scored through tests/studio/studiobench/sweep/floor_table.py. GRID_COLLAPSE_REASONING_ENABLED is false on main, so #9423 is inert and the base here is main with that flag off.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…eting stream, and scope the print upgrade to mounted fences
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: bed93f8bef

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 62702d231c

ℹ️ 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 merged commit 015bdef into main Aug 22, 2026
36 checks passed
@danielhanchen
danielhanchen deleted the coal-mono branch August 22, 2026 16:03
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Aug 23, 2026
…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>
pull Bot pushed a commit to pirica/unsloth that referenced this pull request Sep 23, 2026
…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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants