Repository navigation
Studio: keep a streaming code fence highlighted, and window its spans - #11423
Conversation
Fixes the lag in #10769 without giving up syntax highlighting, which is what closed #10779. The cost was never Shiki. #10779 kept calling the highlighter and only stopped rendering the tokens, and still took a 140K-character stream from 29 fps to 59 fps. Tokenization has been incremental since code-plugin.ts started caching committed lines with a carried GrammarState: past MIN_INCREMENTAL_CHARS only the live tail is tokenized. What was not incremental was the rendering. Streamdown's CodeBlockBody maps the whole token array to elements on every render and memoizes on the identity of the result object, and the plugin returns a fresh one on every call, including the approximateResult path that runs on every streamed frame. So a large fence rebuilt every line and every token in itself about sixty times a second. Two changes, in one new body that replaces Block for fences. One memoized component per line. A committed line's token array is already stable, so a fence growing by a character now reconciles its last line instead of all of them. A line window, past a 2,000 line cap. A line outside the window renders its text as one node instead of its token spans. The swap is the children of a line, never the line, so the block box and its height are unchanged, and the characters never leave the document: selection, copy, find-in-page and print are untouched and only off-screen colour is given up. Under the cap nothing happens at all, so every fence in the benchmark corpus renders what main renders. Selection lives in code-fence-window.ts, a JSX-free module, so the arithmetic is run by a test rather than described by a regex. Windowing is behind the new "window" fence mode and is not yet the ship default; the ladder that would justify moving it has not been run. Measured in Chromium at 4x CPU throttle, 45 s of streaming per arm, one run each, on a synthetic 6,000 line TypeScript fence: arm fps median >33ms spans lines in 45 s streamdown-shaped 43.9 21.2ms 336 37,112 1,448 per-line memo 48.6 16.8ms 210 71,402 2,782 per-line memo + window 50.1 16.6ms 175 1,170 2,928 Twice the lines rendered in the same wall clock, the median frame back on the vsync floor, and 98% fewer mounted spans with the visible code still coloured. Not the studiobench ladder: one machine, one run per arm, no null control, and a synthetic body rather than the corpus. Separately verified in the browser that the windowed and unwindowed arms of the same 4,000 line fence agree exactly on code height (75,000 px), thread scrollHeight (75,704 px), textContent (172,594 chars) and innerText, and that index.css still wins content-visibility on the block.
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. |
…ence body Both found by diffing the rendered DOM of the new body against the merge base through the real markdown route, on the same scene, in Chromium. `remark-rehype` puts `language-<info>` on a fenced block's `<code>`, and streamdown passes that className through to both the code-block-body div and the `<pre>`. The new body dropped it. Nothing in the tree selects on it, which is exactly why it would have gone unnoticed: it is a published rendering contract that user stylesheets and future probes reach for, and `math-block-marker.ts` already depends on the same `language-` convention one layer up. The token is the first word of the info string, so ```python startLine=10 is `language-python`, which is what `languageToken` already holds. Streamdown also puts `data-incomplete` on the wrapper while a fence is open. The new streaming route dropped that too. Its only mention in the tree is `studiobench/scene/parity.js`, explaining why an in-flight message is elided from the parity digest, so no oracle reads it today either. Measured before: settled_code, settled_meta and settled_crlf disagreed with the base arm on the structural fingerprint, and streaming_svg, streaming_html, streaming_tilde, streaming_quad, streaming_indented, streaming_crlf and streaming_meta each differed on one key. Measured after: all nineteen scenes report shape_identical=True and zero differing keys except the ones the change is for.
A print puts the whole document on the page, so the whole fence has to be coloured. `upgradeEverythingForPrint` already makes that argument for a deferred fence; the line window reintroduced the same defect one level down. Measured: a 3,000 line fence printed with 342 spans against the 23,139 the merge base printed, so all but a screenful of a printed listing came out uncoloured. Colour is the only thing a window costs, and a printed page is the one place the reader keeps it. Both doors, as with the latch: `beforeprint` covers Ctrl+P and the print menu, the print media query covers headless `page.pdf()` and devtools emulation. Synchronous, inside `flushSync`, because there is no next paint before the print snapshot. This one reverts on `afterprint` and the latch does not, which is a real difference rather than an inconsistency. Re-latching a fence would mean re-tokenizing it; re-windowing costs element creation and nothing else, because the tokens are already in `fence.lines`. And not reverting would mean one Ctrl+P un-windows every huge fence for the life of the tab, which is precisely the cost the window exists to avoid. `code-fence-defer.test.ts` banned the string `afterprint` outright, which said the right thing about the only mechanism that existed when it was written. Narrowed rather than dropped: an afterprint handler may end the print and nothing else, and no route anywhere may clear a latch. Re-measured after the fix: on screen 342 spans and `data-unsloth-fence-windowed` still set; under print emulation 23,139 spans, the same count as the merge base, with textContent identical at 128,693 characters in both states.
Found by the staging cross-platform pass, not by the frontend suite: `tests/studio/test_ui_font_scale_contract.py` reads 12 passed on the merge base and 1 failed on this branch. The line class here was copied verbatim from streamdown, and streamdown writes a raw pixel text utility for the line-number pseudo-element. That spelling is banned anywhere in frontend source, comments included, because a fixed pixel size ignores the UI font size preference. `text-ui-13` is `calc(0.8125rem * var(--ui-font-scale, 1))`, so it renders at the same size at the default scale and follows the preference above and below it. Nothing moves in the thread either way: `index.css` gives `.aui-thread-root [data-streamdown="code-block"] code > span::before` `content: none` and `display: none`, so no pseudo-element box is generated there at all and its font size is dead. This is the one deliberate difference from streamdown's own class list, and it is now the only one. Re-measured across four scenes: every metric identical to the merge base, including code height, thread scrollHeight, textContent, innerText, the text checksum, data-incomplete, data-language, computed display and computed content-visibility. The single differing class token is `before:text-ui-13` against streamdown's pixel spelling. `tests/studio/test_ui_font_scale_contract.py`: 12 passed. Frontend suite: 8190 passed, 0 failed.
Simulation reportRan the full before/after/what-else-changed pass on this branch: base arm at the merge base Verdict: issue REAL, PR as submitted DEFECTIVE with 4 defects fixed here, merge YES. It found four real defects in my own first commit. All four are fixed on this branch and each one What it measured
Null control, base build against base build, same scenes, 3 repetitions: detection floor 9.4% on A 600 line fence that closes reads 51.2 fps base against 49.5 fps head, a 3.3% delta against a Defects it found, and the fixes
What else changed, which is the half worth readingEvery changed predicate enumerated over its full input space with the real helpers: 7 opener Nothing leaves the mermaid, svg, canvas, artifact or fence-block branches, confirmed separately in On the shipped default the window machinery costs nothing, measured rather than reasoned: 0 Cross-engine, 15 scenes by 3 engines by 2 arms, each with a five-stable-reads settle gate: Frontend suite 8,190 passed 0 failed on head, 8,165 passed 0 failed on base. 9 of the 23 new tests What I could not prove
|
`CODE_FENCE_RE` closed a fence with exactly three backticks. CommonMark requires the closing run to be *at least* as many as the opening one, so a model closing a three-backtick fence whose body contains a backtick run writes four. The lazy body matched such a line by its last three backticks and handed the surplus delimiter to `source`: `` ```python / x = 1 / ```` `` parsed as the code `` x = 1\n` ``. Only the completed block takes this path -- the streaming route went through `markdownBlockFallback`, which already applied the "at least as many" rule -- so the two classifiers disagreed about the same reply, and the reader watched the block grow a stray backtick line at the moment the closing delimiter landed. Left lazy, the run is consumed by the close. The opener is fixed at three, so every run of three or more closes it. Measured against `micromark` over 384 opener/body/closer/length combinations: the fixed-length close disagreed with CommonMark on 304 of them, this one on none outside a body that is itself a closing run, where a block-level regex cannot tell a delimiter from code. `tests/code-fence-close-run.test.ts` runs that differential, the body's own trailing backticks, and the unchanged language tag and block-level shapes.
|
Ran this against a real build, not just the unit tests: Studio installed from the branch head on an isolated home, a local Qwen3.8-27B GGUF loaded into it, and the app driven in a browser through its own API and DOM. One bug found and fixed —
The fix is
Injecting the same fixture through the app's own
The PR's own claim holds live. A real streamed reply produced a 30-line TypeScript fence with 266 spans in 7 distinct token colours, Mount cost and span census (one fixture, 24 fences x 150 lines, 22 of them off screen when the thread opens):
4.7x faster to first paint and 91.6% fewer spans, with line counts, Gate: the repo's own One honest gap: I could not reproduce the fps ladder from the PR body on this box — my synthetic scene is too small to separate the arms there — so treat those numbers as the author's, not mine. |
The lazy `+?` close I pushed in the previous commit was half the rule. It fixed
the surplus-delimiter case but also accepted a ONE- or TWO-backtick run as a
delimiter, which a stream that had just written its first backtick would have
swallowed, and an aborted reply ending in a short run would be read as a closed
fence with the run deleted.
The opener is fixed at three, so "at least as many" is `{3,}`.
Measured against micromark over 540 opener/body/closer/tail/indent shapes:
`{3}` (original) 54 disagreements on the shapes it claims (the surplus delimiter)
`+?` (previous) 54 disagreements (the short-run rows)
`{3,}` (this) 0
tests/code-fence-close-run.test.ts gains the short-run rows; 5/5 pass.
|
Short clip of the shipped Full quality (same 14 s clip, 720 px, original quality): pr11423-fence-stream.mp4 What to look at, in the order it happens:
Recorded at native speed, no speed-up. The clip is hosted on a media-only branch of my fork ( |
… state Two review findings, both on the fence path. 1. A tilde, four-or-more-backtick or indented fence is recognised by `markdownBlockFallback` while it streams, but `getCodeFence` does not match those forms, so once it completed it fell through to streamdown's whole-token `Block` and remounted every span -- the final-frame freeze this PR exists to remove. A stopped reply did the same and never settled. The completed form now stays on the per-line body. Deliberately not routed through `FenceBlock`: that branch also owns the reach latch, the action bar and the fence-mode switch, which are wired to `getCodeFence`'s narrower form on purpose, and widening them would add controls and artifact paths to blocks that do not have them today. 2. `setPrinting` returned early when no window was registered, so a print begun while a fence still showed its shell never recorded the state; the tokens could then arrive during the preview and window the fence normally, leaving most printed pages uncoloured. The global state now changes even when there is nothing to remeasure. tests/code-fence-body.test.ts gains the completed-fence rows; 90/90 pass in the fence and routing suites and `tsc --noEmit` is clean.
Comment-only; no code changes. The fence-close rationale, the completed-fence route, the print-state guard and the new test headers all said the same thing at four times the length.
…l diagrams Two review findings, both on the fence-close work. 1. The close now requires a line break before it unless the body is empty. The previous `\r?\n?` let a body ending in a run of backticks have that run eaten: ```\nfoo```` returned `foo` where CommonMark keeps `foo```` `. The alternation is outside the body group so the no-newline branch really is an empty body. Against micromark over 300 shapes: 0 disagreements. 2. A tilde mermaid fence is a diagram. `MERMAID_SOURCE_RE` and the `hasMermaidFence` probe only recognised backticks, so `~~~mermaid` fell through to a highlighted code block while streamdown renders mermaid wherever the language tag says so. Both now accept either marker, and the completed-fence route does not swallow a diagram.
… mermaid close Two review findings. 1. kept the previous render when returned null after catching a tokenization error, so a streamed fence went on showing an older, shorter body instead of the current source. The state is cleared for the request; the callback still restores a late result. 2. The mermaid matcher accepted any run as the close, so a body holding its own `~~~` truncated the diagram the copy button reads. It now requires a line-level close of the opener's own character, at least as long.
Three review findings, all one root cause: a hand-rolled matcher next to a scanner that already gets this right. - `~~~ mermaid` (whitespace before the info string) was rejected, so a completed diagram fell to the code renderer and never rendered. - A fence still streaming has no close, so the complete matcher never matched and the loading state was skipped. - The close's trailing run accepted the opposite marker, so a body line like ```~~~ truncated the diagram the copy button reads. `getMermaidSource` now reads `markdownBlockFallback`, which handles every fence form CommonMark allows, and the streaming branch keys on an opener-only probe.
…ttled incomplete flag Two review findings. 1. A block that continues past a mermaid fence -- a reply containing a footnote is one block -- is not `fenced` as a whole, so `getMermaidSource` returned null and the copy button was skipped even though the diagram rendered. It now falls back to reading the fence's own slice with the same opener/close rules. 2. A completed tilde/4-backtick/indented fence renders through the streaming component, which passed `isIncomplete` unconditionally, so a finished fence kept `data-incomplete="true"`. The parameter now defaults to true for the streaming branch and the settled branch passes false.
|
@codex security review |
CommonMark closes a fenced block at the FIRST bare delimiter run on its own line. The
multi-fence guard only rejected a body whose bare close was followed by another opener, so a
block whose close is followed by prose still matched, and the body ran past the real close.
Checked against micromark:
```md / A: / ``` / B / ``` is a fence holding "A:", the paragraph "B", and an empty
fence. getCodeFence returned the body "A:\n```\nB".
```js / code / ``` / ``` is a fence holding "code" and an empty fence.
getCodeFence returned "code\n```".
This is reachable on ordinary input: a model explaining how to write a code block produces
exactly that shape. It was latent while the fence body came from streamdown's own re-parse,
and this branch makes it visible, because FenceBody renders the source getCodeFence reports.
markdownBlockFallback already reported these blocks as not fenced, so the two classifiers
disagreed about the same reply.
A delimiter line carrying an info string is still ordinary code, so a tutorial quoting ```js
inline keeps working.
|
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". |
|
Correction to my earlier comment, and it goes the other way: the content-loss claim does not hold. In #11423 (comment) I wrote that on main a four-backtick fence containing a nested mermaid example "silently drops five lines of the reader's code", and gave a 3-lines-versus-8-lines table. That came out of my own probe harness, which renders I have now driven the same reply through two real Studio installs, built from this PR's merge base and from its head, with the model response replaced by fixed scripted bytes so both sides render identical input. At the merge base Studio renders the block correctly and completely: one typescript block containing So the defect I described is an artefact of my harness, not behaviour of the application, and I withdraw it. I do not yet have a full account of why the harness and Studio disagree on that block; the honest statement is that the harness reading was wrong about the product and the screenshot is what counts. What this does not change:
I am re-running the before/after as a parity pair, since the correct claim for this shape is that the two builds render it identically, and will post the pair. |
|
Codex Review: Didn't find any major issues. 🎉 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". |
Comment-only. Collapses the multi-line rationales added by this branch to one line each and deletes restatements, measured figures that belong in the PR description, and pointers. Every surviving comment states something the code does not: an invariant, a citation, or why an alternative is wrong. One was stale rather than merely long: the note in markdown-text.tsx said tilde, four-backtick and indented fences 'render exactly as they do today and get no deferral', which stopped being true when the settled-fence rung landed. Pre-existing comments in the files this branch touches are left alone.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d658aa6602
ℹ️ 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".
| rest.replace(/[\t ]*\r?$/, "") === "" && marker.length >= 3; | ||
| if (enclosing === null) { | ||
| if (marker[0] === "`" && rest.includes("`")) continue; // an info string may not hold a backtick | ||
| if (/^[\t ]*mermaid\b/i.test(rest)) { |
There was a problem hiding this comment.
Decode fence info before classifying Mermaid
For a valid CommonMark fence such as ```mermaid, the Markdown parser decodes the character reference and produces the language mermaid, but this test examines the raw info string and misses it. The closed block then reaches the new parser-free FenceBlock path and is displayed as highlighted source instead of the Mermaid diagram that the previous <Block> rendered. Decode the info string according to Markdown rules, or classify using parsed metadata, before testing the language.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right about the spec, and I checked it rather than assuming: micromark renders both mermaid and mermaid as language-mermaid, so CommonMark does decode character references in the info string and this classifier does miss the encoded form.
Declining it anyway, on reachability. A model writing a diagram emits the literal tag; an info string carrying a numeric character reference is not something a real session produces, and the consequence is a diagram rendering as highlighted source rather than lost content, a wrong tool call or a crash. That puts it in the exotic-input class this repo rejects rather than backlogs.
Worth recording that the blind spot is not new either: on the merge base getMermaidSource matched the raw ```mermaid substring with no decoding, so the same input was misclassified there too. What this branch changes is only what happens afterwards.
Two pieces of redundant work on the per-frame path this branch exists to shorten. `findMermaidFence` splits a block and regex-scans every line. Asking it whether the fence is open and what its source is went through two separate wrappers, so the walk ran twice on every render of every block. Measured on a 3,000 line fence: 0.118 ms per walk, so the redundant one cost 0.092 ms per render, about 5.5 ms per second while streaming at 60 fps. Both answers now come off one walk, and the wrappers that only existed to start a second one are gone rather than left unused. `useFenceTokens` ran a passive effect and a layout effect with the same inputs and the same deps, each calling `code.highlight`. The plugin's throttled `approximateResult` returns a fresh object per call, so both setters were observable and every source change scheduled a second render of the whole body. One layout effect does both jobs: it gets the before-paint colour the layout effect was added for, and keeps the asynchronous callback the passive one carried. Both are pinned by tests that fail on the code before this commit.
…haracter CommonMark removes the opening fence's indentation from each content line by COLUMN, and a tab expands to a four-column tab stop. A tab opening a line inside a one-space indented fence therefore spans columns 1 to 4 and loses only its first column, leaving three spaces. stripIndent took characters, so the tab survived whole and the body came out a tab too deep. Checked against micromark: " ```js / \tx / ```" CommonMark " x", this gave "\tx" " ```js / \tx / ```" CommonMark " x", this gave "\tx" " ```js / \tx / ```" CommonMark " x", this gave "\tx" Latent until this branch, because an indented fence used to reach streamdown's parser; the settled-fence rung renders this text directly, so it now reaches the screen and the clipboard, where wrong indentation is wrong code rather than a cosmetic difference. A tab that straddles the boundary is consumed whole and the columns past the indent come back as spaces, which is what expanding it and re-cutting would give. Verified over a 36-block matrix of indents and tab positions against micromark: 0 disagreements.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8025ea0d83
ℹ️ 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".
| (late) => { | ||
| if (wanted.current === body) setTokens(late); |
There was a problem hiding this comment.
Include the language in the stale-result guard
When an already-mounted fence changes only its language tag while its body remains unchanged, the callback from the previous grammar still passes this body-only guard. Because grammar chunks load independently, the older request can resolve last and permanently replace the current result with tokens from the wrong grammar. Track both body and languageToken (or a request generation) before accepting the callback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right that the guard keys on the body alone, so an out-of-order callback from a previous grammar would pass it. I went looking for the case where that is visible and could not reach one.
The language can only change while the body is EMPTY. The info string precedes the newline and a streamed block is append-only, so once any body text exists the opener line is already fixed. Replaying ```python\nprint(1)\nprint(2)` one character at a time through markdownBlockFallback:
null -> "p" body "" -> ""
"p" -> "py" body "" -> ""
"py" -> "pyt" body "" -> ""
"pyt" -> "pyth" body "" -> ""
"pyth" -> "pytho" body "" -> ""
"pytho" -> "python" body "" -> ""
Six language changes, every one with an empty body, and zero with a non-empty body that stayed the same. A late callback therefore races only over the tokens for the empty string, which are the same under any grammar. A settled fence does not change its language at all, and the streaming and completed routes are separate component instances, so they do not share this ref.
Declining on that basis rather than on the one-line change being expensive. If there is a path where the language moves while a non-empty body stays identical, that is the missing piece and I will take the fix.
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
Confirmed the streaming path in markdown-block-fallback.ts now keeps an open fence on the same body, so highlighting survives while the block grows and the shape does not jump when the closing delimiter lands; will get this reviewed. |
…unslothai#11423) * Studio: keep a streaming code fence highlighted, and window its spans Fixes the lag in unslothai#10769 without giving up syntax highlighting, which is what closed unslothai#10779. The cost was never Shiki. unslothai#10779 kept calling the highlighter and only stopped rendering the tokens, and still took a 140K-character stream from 29 fps to 59 fps. Tokenization has been incremental since code-plugin.ts started caching committed lines with a carried GrammarState: past MIN_INCREMENTAL_CHARS only the live tail is tokenized. What was not incremental was the rendering. Streamdown's CodeBlockBody maps the whole token array to elements on every render and memoizes on the identity of the result object, and the plugin returns a fresh one on every call, including the approximateResult path that runs on every streamed frame. So a large fence rebuilt every line and every token in itself about sixty times a second. Two changes, in one new body that replaces Block for fences. One memoized component per line. A committed line's token array is already stable, so a fence growing by a character now reconciles its last line instead of all of them. A line window, past a 2,000 line cap. A line outside the window renders its text as one node instead of its token spans. The swap is the children of a line, never the line, so the block box and its height are unchanged, and the characters never leave the document: selection, copy, find-in-page and print are untouched and only off-screen colour is given up. Under the cap nothing happens at all, so every fence in the benchmark corpus renders what main renders. Selection lives in code-fence-window.ts, a JSX-free module, so the arithmetic is run by a test rather than described by a regex. Windowing is behind the new "window" fence mode and is not yet the ship default; the ladder that would justify moving it has not been run. Measured in Chromium at 4x CPU throttle, 45 s of streaming per arm, one run each, on a synthetic 6,000 line TypeScript fence: arm fps median >33ms spans lines in 45 s streamdown-shaped 43.9 21.2ms 336 37,112 1,448 per-line memo 48.6 16.8ms 210 71,402 2,782 per-line memo + window 50.1 16.6ms 175 1,170 2,928 Twice the lines rendered in the same wall clock, the median frame back on the vsync floor, and 98% fewer mounted spans with the visible code still coloured. Not the studiobench ladder: one machine, one run per arm, no null control, and a synthetic body rather than the corpus. Separately verified in the browser that the windowed and unwindowed arms of the same 4,000 line fence agree exactly on code height (75,000 px), thread scrollHeight (75,704 px), textContent (172,594 chars) and innerText, and that index.css still wins content-visibility on the block. * Studio: keep streamdown's language class and incomplete flag on the fence body Both found by diffing the rendered DOM of the new body against the merge base through the real markdown route, on the same scene, in Chromium. `remark-rehype` puts `language-<info>` on a fenced block's `<code>`, and streamdown passes that className through to both the code-block-body div and the `<pre>`. The new body dropped it. Nothing in the tree selects on it, which is exactly why it would have gone unnoticed: it is a published rendering contract that user stylesheets and future probes reach for, and `math-block-marker.ts` already depends on the same `language-` convention one layer up. The token is the first word of the info string, so ```python startLine=10 is `language-python`, which is what `languageToken` already holds. Streamdown also puts `data-incomplete` on the wrapper while a fence is open. The new streaming route dropped that too. Its only mention in the tree is `studiobench/scene/parity.js`, explaining why an in-flight message is elided from the parity digest, so no oracle reads it today either. Measured before: settled_code, settled_meta and settled_crlf disagreed with the base arm on the structural fingerprint, and streaming_svg, streaming_html, streaming_tilde, streaming_quad, streaming_indented, streaming_crlf and streaming_meta each differed on one key. Measured after: all nineteen scenes report shape_identical=True and zero differing keys except the ones the change is for. * Studio: colour the whole fence for a print, then window it again A print puts the whole document on the page, so the whole fence has to be coloured. `upgradeEverythingForPrint` already makes that argument for a deferred fence; the line window reintroduced the same defect one level down. Measured: a 3,000 line fence printed with 342 spans against the 23,139 the merge base printed, so all but a screenful of a printed listing came out uncoloured. Colour is the only thing a window costs, and a printed page is the one place the reader keeps it. Both doors, as with the latch: `beforeprint` covers Ctrl+P and the print menu, the print media query covers headless `page.pdf()` and devtools emulation. Synchronous, inside `flushSync`, because there is no next paint before the print snapshot. This one reverts on `afterprint` and the latch does not, which is a real difference rather than an inconsistency. Re-latching a fence would mean re-tokenizing it; re-windowing costs element creation and nothing else, because the tokens are already in `fence.lines`. And not reverting would mean one Ctrl+P un-windows every huge fence for the life of the tab, which is precisely the cost the window exists to avoid. `code-fence-defer.test.ts` banned the string `afterprint` outright, which said the right thing about the only mechanism that existed when it was written. Narrowed rather than dropped: an afterprint handler may end the print and nothing else, and no route anywhere may clear a latch. Re-measured after the fix: on screen 342 spans and `data-unsloth-fence-windowed` still set; under print emulation 23,139 spans, the same count as the merge base, with textContent identical at 128,693 characters in both states. * Studio: size the fence's line-number gutter with the UI font token Found by the staging cross-platform pass, not by the frontend suite: `tests/studio/test_ui_font_scale_contract.py` reads 12 passed on the merge base and 1 failed on this branch. The line class here was copied verbatim from streamdown, and streamdown writes a raw pixel text utility for the line-number pseudo-element. That spelling is banned anywhere in frontend source, comments included, because a fixed pixel size ignores the UI font size preference. `text-ui-13` is `calc(0.8125rem * var(--ui-font-scale, 1))`, so it renders at the same size at the default scale and follows the preference above and below it. Nothing moves in the thread either way: `index.css` gives `.aui-thread-root [data-streamdown="code-block"] code > span::before` `content: none` and `display: none`, so no pseudo-element box is generated there at all and its font size is dead. This is the one deliberate difference from streamdown's own class list, and it is now the only one. Re-measured across four scenes: every metric identical to the merge base, including code height, thread scrollHeight, textContent, innerText, the text checksum, data-incomplete, data-language, computed display and computed content-visibility. The single differing class token is `before:text-ui-13` against streamdown's pixel spelling. `tests/studio/test_ui_font_scale_contract.py`: 12 passed. Frontend suite: 8190 passed, 0 failed. * Studio: let a closing fence run be at least as long as the opener `CODE_FENCE_RE` closed a fence with exactly three backticks. CommonMark requires the closing run to be *at least* as many as the opening one, so a model closing a three-backtick fence whose body contains a backtick run writes four. The lazy body matched such a line by its last three backticks and handed the surplus delimiter to `source`: `` ```python / x = 1 / ```` `` parsed as the code `` x = 1\n` ``. Only the completed block takes this path -- the streaming route went through `markdownBlockFallback`, which already applied the "at least as many" rule -- so the two classifiers disagreed about the same reply, and the reader watched the block grow a stray backtick line at the moment the closing delimiter landed. Left lazy, the run is consumed by the close. The opener is fixed at three, so every run of three or more closes it. Measured against `micromark` over 384 opener/body/closer/length combinations: the fixed-length close disagreed with CommonMark on 304 of them, this one on none outside a body that is itself a closing run, where a block-level regex cannot tell a delimiter from code. `tests/code-fence-close-run.test.ts` runs that differential, the body's own trailing backticks, and the unchanged language tag and block-level shapes. * Studio: require three closing backticks, not one or two The lazy `+?` close I pushed in the previous commit was half the rule. It fixed the surplus-delimiter case but also accepted a ONE- or TWO-backtick run as a delimiter, which a stream that had just written its first backtick would have swallowed, and an aborted reply ending in a short run would be read as a closed fence with the run deleted. The opener is fixed at three, so "at least as many" is `{3,}`. Measured against micromark over 540 opener/body/closer/tail/indent shapes: `{3}` (original) 54 disagreements on the shapes it claims (the surplus delimiter) `+?` (previous) 54 disagreements (the short-run rows) `{3,}` (this) 0 tests/code-fence-close-run.test.ts gains the short-run rows; 5/5 pass. * Studio: keep non-``` fences on the bounded renderer, and record print state Two review findings, both on the fence path. 1. A tilde, four-or-more-backtick or indented fence is recognised by `markdownBlockFallback` while it streams, but `getCodeFence` does not match those forms, so once it completed it fell through to streamdown's whole-token `Block` and remounted every span -- the final-frame freeze this PR exists to remove. A stopped reply did the same and never settled. The completed form now stays on the per-line body. Deliberately not routed through `FenceBlock`: that branch also owns the reach latch, the action bar and the fence-mode switch, which are wired to `getCodeFence`'s narrower form on purpose, and widening them would add controls and artifact paths to blocks that do not have them today. 2. `setPrinting` returned early when no window was registered, so a print begun while a fence still showed its shell never recorded the state; the tokens could then arrive during the preview and window the fence normally, leaving most printed pages uncoloured. The global state now changes even when there is nothing to remeasure. tests/code-fence-body.test.ts gains the completed-fence rows; 90/90 pass in the fence and routing suites and `tsc --noEmit` is clean. * Studio: trim the added comments to the rules they explain Comment-only; no code changes. The fence-close rationale, the completed-fence route, the print-state guard and the new test headers all said the same thing at four times the length. * Studio: a close needs a line break, and tilde mermaid fences are still diagrams Two review findings, both on the fence-close work. 1. The close now requires a line break before it unless the body is empty. The previous `\r?\n?` let a body ending in a run of backticks have that run eaten: ```\nfoo```` returned `foo` where CommonMark keeps `foo```` `. The alternation is outside the body group so the no-newline branch really is an empty body. Against micromark over 300 shapes: 0 disagreements. 2. A tilde mermaid fence is a diagram. `MERMAID_SOURCE_RE` and the `hasMermaidFence` probe only recognised backticks, so `~~~mermaid` fell through to a highlighted code block while streamdown renders mermaid wherever the language tag says so. Both now accept either marker, and the completed-fence route does not swallow a diagram. * Studio: clear stale fence tokens on a failed highlight, and bound the mermaid close Two review findings. 1. kept the previous render when returned null after catching a tokenization error, so a streamed fence went on showing an older, shorter body instead of the current source. The state is cleared for the request; the callback still restores a late result. 2. The mermaid matcher accepted any run as the close, so a body holding its own `~~~` truncated the diagram the copy button reads. It now requires a line-level close of the opener's own character, at least as long. * Studio: take the mermaid source from the shared fence scanner Three review findings, all one root cause: a hand-rolled matcher next to a scanner that already gets this right. - `~~~ mermaid` (whitespace before the info string) was rejected, so a completed diagram fell to the code renderer and never rendered. - A fence still streaming has no close, so the complete matcher never matched and the loading state was skipped. - The close's trailing run accepted the opposite marker, so a body line like ```~~~ truncated the diagram the copy button reads. `getMermaidSource` now reads `markdownBlockFallback`, which handles every fence form CommonMark allows, and the streaming branch keys on an opener-only probe. * Studio: keep an embedded mermaid fence's copy button, and drop the settled incomplete flag Two review findings. 1. A block that continues past a mermaid fence -- a reply containing a footnote is one block -- is not `fenced` as a whole, so `getMermaidSource` returned null and the copy button was skipped even though the diagram rendered. It now falls back to reading the fence's own slice with the same opener/close rules. 2. A completed tilde/4-backtick/indented fence renders through the streaming component, which passed `isIncomplete` unconditionally, so a finished fence kept `data-incomplete="true"`. The parameter now defaults to true for the streaming branch and the settled branch passes false. * Studio: match an embedded mermaid close by the opener's rule, and strip its indentation Two review findings on the embedded-fence fallback. 1. The close was matched at exactly the opener's length. CommonMark wants "at least as many", so a four-backtick close on a three-backtick opener was not recognised and the source ran past the fence. 2. The opener's indentation was not removed from the body, so an indented mermaid fence copied with leading spaces CommonMark says it does not have. Up to N spaces come off each line, as `stripIndent` does for the fenced case. The final trim was also `trim()`, which ate the body's own leading indentation; it now removes trailing whitespace only. * Studio: find a mermaid fence that follows prose in the same block When a footnote coalesces a reply into one block, the mermaid fence can sit after prose rather than starting the block. The `^` anchor made both the opener probe and the embedded-fence fallback miss it, so the copy control disappeared and an incomplete diagram skipped the loading state. The matcher now searches line by line with the `m` flag. * Studio: pin the two fence classifiers against each other A code block is owned by `markdownBlockFallback` while it is still arriving and by `getCodeFence` the instant its closing delimiter lands, because only the second can see a close. `FenceBody` renders the body text each one reports rather than re-parsing the block the way streamdown's `Block` did, so a disagreement between the two is a block whose contents change under a reader at the moment the model finishes writing it. That is the defect the closing-run commits fixed. `CODE_FENCE_RE` matched a longer closing run by its last three backticks and handed the surplus to `source`, while the streaming scanner already applied CommonMark's "at least as many" rule. Measured on a built tree, a three-backtick fence closed with five rendered four lines with a trailing `` line against three on the merge base. `code-fence-close-run.test.ts` pins each classifier against CommonMark separately. Neither that nor anything else in the tree pins them against EACH OTHER, which is the invariant the rendering now depends on. Reverting the closing-run widening fails two of the four tests here; it fails none of the rendering tests. * Studio: keep a multi-fence block parsed, seed completed tokens, skip sub-cap measurement Three review findings. 1. A coalesced block can hold two fences (a reply with a footnote is one block), and `getCodeFence` matched from the first opener to the last closer, so `FenceBody` rendered both fences and the prose as one block. It now declines content that holds a second fence, leaving it to `<Block>`. 2. A completed fence mounts `FenceBlock`, whose hook starts at `null`, so a fence that was already highlighted while streaming painted plain for a frame. The hook now takes the synchronous cache hit before paint. 3. Under `WINDOW_CAP_LINES` a window can never apply, yet every reached fence registered a measure that read layout on each scroll frame. It returns before the reads; a fence growing past the cap re-registers via its ResizeObserver. * Studio: seed the fence token cache before the first paint The cache read sat in the passive effect, and a passive effect lands after the frame it was meant to colour: a fence that was already cached, whether from the stream that just finished or a static fence on a settled reply, painted the plain shell first. The read is now a layout effect, which runs before paint. * Studio: narrow the multi-fence guard, and scan mermaid openers with fence context Two review findings. 1. The multi-fence guard rejected any delimiter-shaped body line, so a fence holding `~~~template` as example text lost its copy and download controls, SVG preview and HTML artifact collapsing. It now rejects only a real close followed by another opener. 2. The mermaid opener probe matched a line inside an already-open fence, so an outer fence holding `~~~mermaid` as example text was replaced by the loading card while streaming and given a diagram copy action once settled. It now walks the block tracking which fence is open. * Studio: find the mermaid fence with fence context, not a context-free search `getMermaidSource` still ran its own context-free match after the opener probe was fixed, so an outer fence holding a literal `~~~mermaid` example was still extracted as a diagram: the block rendered through Streamdown, lost its copy/download and bounded rendering, and gained a diagram copy action. Both questions now come from one walk over the block's lines, which tracks which fence is open and only treats a mermaid opener inside no enclosing fence as a diagram. That walk answers the streaming question and yields the body in one pass, so there is no second parser left to disagree with it. * Studio: catch bare follow-on openers, and keep an unclosed mermaid fence loading Two review findings. 1. A bare follow-on opener carries no info string, and the multi-fence guard required a character after the marker, so ```` ``` ```` on its own line was read as the first fence's CLOSE. `FenceBody` then rendered the first close, the prose and the second fence as one code snippet. 2. `markdownBlockFallback` reports an UNCLOSED fence as `fenced` (it treats a fence that never closes as the whole block), so consulting it first handed an incomplete mermaid body back as copyable source and skipped the loading card. The shared walk decides first now: open means no source yet. * Studio: consult the walk first, and read a bare top-level run as an opener Two review findings on the mermaid walk. 1. `isMermaidFenceOpener` consulted `markdownBlockFallback` first, and that reports an UNCLOSED fence as `fenced`, so a streaming mermaid block was treated as settled and rendered as code instead of the loading card. The walk decides now. 2. At TOP level a bare run is an opener, not a close: skipping it meant a four-backtick outer fence holding a nested mermaid example looked like a real diagram. It is recorded as the enclosing fence instead. * Studio: close a fence at the first bare run, not the last CommonMark closes a fenced block at the FIRST bare delimiter run on its own line. The multi-fence guard only rejected a body whose bare close was followed by another opener, so a block whose close is followed by prose still matched, and the body ran past the real close. Checked against micromark: ```md / A: / ``` / B / ``` is a fence holding "A:", the paragraph "B", and an empty fence. getCodeFence returned the body "A:\n```\nB". ```js / code / ``` / ``` is a fence holding "code" and an empty fence. getCodeFence returned "code\n```". This is reachable on ordinary input: a model explaining how to write a code block produces exactly that shape. It was latent while the fence body came from streamdown's own re-parse, and this branch makes it visible, because FenceBody renders the source getCodeFence reports. markdownBlockFallback already reported these blocks as not fenced, so the two classifiers disagreed about the same reply. A delimiter line carrying an info string is still ordinary code, so a tutorial quoting ```js inline keeps working. * Studio: cut the fence comments to the rules they carry Comment-only. Collapses the multi-line rationales added by this branch to one line each and deletes restatements, measured figures that belong in the PR description, and pointers. Every surviving comment states something the code does not: an invariant, a citation, or why an alternative is wrong. One was stale rather than merely long: the note in markdown-text.tsx said tilde, four-backtick and indented fences 'render exactly as they do today and get no deferral', which stopped being true when the settled-fence rung landed. Pre-existing comments in the files this branch touches are left alone. * Studio: walk a block once, and highlight a revision once Two pieces of redundant work on the per-frame path this branch exists to shorten. `findMermaidFence` splits a block and regex-scans every line. Asking it whether the fence is open and what its source is went through two separate wrappers, so the walk ran twice on every render of every block. Measured on a 3,000 line fence: 0.118 ms per walk, so the redundant one cost 0.092 ms per render, about 5.5 ms per second while streaming at 60 fps. Both answers now come off one walk, and the wrappers that only existed to start a second one are gone rather than left unused. `useFenceTokens` ran a passive effect and a layout effect with the same inputs and the same deps, each calling `code.highlight`. The plugin's throttled `approximateResult` returns a fresh object per call, so both setters were observable and every source change scheduled a second render of the whole body. One layout effect does both jobs: it gets the before-paint colour the layout effect was added for, and keeps the asynchronous callback the passive one carried. Both are pinned by tests that fail on the code before this commit. * Studio: strip a fence's indentation by columns, so a tab is not one character CommonMark removes the opening fence's indentation from each content line by COLUMN, and a tab expands to a four-column tab stop. A tab opening a line inside a one-space indented fence therefore spans columns 1 to 4 and loses only its first column, leaving three spaces. stripIndent took characters, so the tab survived whole and the body came out a tab too deep. Checked against micromark: " ```js / \tx / ```" CommonMark " x", this gave "\tx" " ```js / \tx / ```" CommonMark " x", this gave "\tx" " ```js / \tx / ```" CommonMark " x", this gave "\tx" Latent until this branch, because an indented fence used to reach streamdown's parser; the settled-fence rung renders this text directly, so it now reaches the screen and the clipboard, where wrong indentation is wrong code rather than a cosmetic difference. A tab that straddles the boundary is consumed whole and the columns past the indent come back as spaces, which is what expanding it and re-cutting would give. Verified over a 36-block matrix of indents and tab positions against micromark: 0 disagreements. --------- Co-authored-by: wasimysaid <[email protected]>

Summary
Fixes the lag in #10769 without giving up syntax highlighting, which is what closed #10779.
The cost was never Shiki. #10779 kept calling the highlighter and only stopped rendering the tokens, and it still took a 140K-character stream from 29 fps to 59 fps. Tokenization has been incremental since
code-plugin.tsstarted caching committed lines with a carriedGrammarState: pastMIN_INCREMENTAL_CHARSonly the live tail is tokenized. What was not incremental was the rendering.Streamdown's
CodeBlockBodymaps the whole token array to elements on every render and memoizes onprev.result === next.result, reference equality. Our plugin returns a fresh result object on every call, including theapproximateResultpath that runs on every streamed frame between the 250 ms refreshes. So a large fence rebuilt every line and every token in itself about sixty times a second.scripts/coal-span-census.mjshad already closed the other door: Shiki emits maximally coalesced tokens (537013 to 537013 over the whole corpus), so the span count cannot be reduced by merging. It can only be reduced by not mounting spans for code nobody is looking at.What changed
A new
FenceBodyreplacesBlockfor fences, and does two thingsBlockcannot.One memoized component per line.
code-plugin.tspushes each completed line intofence.linesexactly once and never rebuilds it, so a committed line's array identity is already stable across refreshes andmemobails out on it. A growing fence now reconciles the live tail line and whatever was just committed, instead of all of it.A line window, past a 2,000 line cap. A line outside the window renders its text as one node instead of its token spans. The swap is the children of a line, never the line, so the block box and its height are unchanged, and the characters never leave the document. Selection, copy, find-in-page and print are untouched, and the only thing a line outside the window gives up is its colour, off screen by construction. That is deliberately not virtualization, which
progressive-mount-controller.tsrejects on those grounds, and deliberately notcontent-visibility: auto, whichindex.cssalready bans on code blocks because WebKit before Safari 26 cannot find-in-page skipped content.Under the cap nothing happens at all, so every fence in the benchmark corpus, mean 1,800 characters, renders the DOM main renders. The selection itself lives in a new JSX-free
code-fence-window.ts, the same splitcode-fence-mode.tsmade out ofcode-fence-defer.tsx, so the arithmetic is run by a test rather than described by a regex over a file nothing can import.A streaming fence keeps its colours.
getCodeFenceneeds the closing delimiter, so an open fence had nocodeFenceand fell through to the bareBlock; it now renders the same body a completed fence gets, so the block does not change shape when its closing delimiter lands.markdownBlockFallbackrecognises the open fence rather thangetCodeFence, so tildes, four or more backticks and indented fences take this route too.Windowing is behind a new
windowfence mode and is not the ship default. The default staysdefer, soplaywright_heavy_thread.pyand everything else that countspre code spansees exactly what it sees today. MovingSHIP_DEFAULTis a one-line change once the ladder justifies it.Measurements
Chromium, 4x CPU throttle, 45 s of streaming per arm, one run each, on a synthetic 6,000 line TypeScript fence:
Twice the lines rendered in the same wall clock, the median frame back on the vsync floor, and 98% fewer mounted spans with the visible code still coloured.
Separately, the windowed and unwindowed arms of the same 4,000 line fence agree exactly:
textContentinnerTextcontent-visibilityTwo bugs that check caught and that are fixed here: the window only engaged after a scroll, because a passive effect keyed on the mode alone never re-ran once the grammar chunk landed and the body replaced the shell; and
ResizeObserversilently never fires on a<code>, which isdisplay: inlineand has no principal box, so a fence streamed past 3,000 lines and 23,139 spans with the window never once engaging. It observes the wrapper now.What this does not answer
TOKENIZE_LIMITS.tokenizeMaxLineLength.OversizedReasoningCodepath still drops highlighting entirely. It renders an arbitrary slice of a fence, with no language tag, starting mid-grammar, and it wraps, so none of the geometry here holds for it. Fixing it needs per-line grammar checkpoints, which is a separate change.Test plan
cd studio/frontend && npm run typecheck && npm test: 8,188 pass, 0 fail.npm run buildandnpm run bundle:check: clean, within budget.tests/code-fence-window.test.tsruns the window arithmetic: the cap, overscan, clamping at both ends, hysteresis holding an ordinary scroll and releasing on a jump, the cap binding the window itself, and untrustworthy geometry degrading to highlighting everything.tests/code-fence-body.test.tsruns the line-text invariant, that a line shows the same characters inside the window and outside it, and pins the rendering decisions that live in the.tsx.code-plugin-incremental.test.ts,code-plugin-tokenization-work.test.ts,code-plugin-embedded-grammars.test.ts,code-plugin-engine-and-cache.test.ts,markdown-block-boundary.test.ts,code-fence-defer.test.ts,code-fence-mode.test.ts.Worth running before merge:
playwright_code_block_flicker.pyas the height-stability gate,playwright_find_in_page.pyincluding its three degraded-engine modes, andplaywright_heavy_thread.py.Before and after
Rendered evidence, from two isolated Studio installs built from this PR's merge base (
b32e63e9c) and its head (864eb6b93). The model response is replaced by fixed scripted bytes, so both sides render byte-identical input and any difference would be the rendering change alone.The reply is a four-backtick fence that quotes a ```mermaid fence as an example, which is what a model writes when asked how to draw a diagram, and it is the shape this PR moves off streamdown's whole-token
Blockand onto `FenceBody`.This is a parity pair: the halves matching is the claim, not a failed run. Both render one typescript block holding all eight lines in order (
Example:, the quoted ```mermaid opener,graph TD, ` A --> B`, the quoted closing run, then the three `const value_N` lines), with the quoted mermaid fence shown as text inside the block rather than becoming a diagram, syntax-highlighted on both.Measured off the live DOM on each side:
code_line_count8,code_first_lineExample:,code_textequal,highlighted_token_count30, on both. Zero scene facts moved between the two sides.