Repository navigation
Studio: fix lag when streaming large code blocks - #10779
Souravrajvi0 wants to merge 5 commits into
Conversation
While a fenced block is still arriving, Streamdown routed the growing body through Block and re-tokenized it on every frame. Render the same plain shell deferral uses until the closing delimiter lands, then highlight once in FenceBlock when the fence completes. Fixes unslothai#10769
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4c0d93d9c2
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const openFence = markdownBlockFallback(props.content); | ||
| if (openFence.fenced) { |
There was a problem hiding this comment.
Distinguish closed fences before bypassing Block
When the currently streaming block is a valid closed fence that getCodeFence does not recognize—such as a tilde fence, a four-backtick fence, or a fence indented by up to three spaces—markdownBlockFallback(...).fenced is still true, because that field means “the entire block is fenced,” not “the fence is open.” This therefore routes an already-complete fence through the plain shell and suppresses its normal Streamdown rendering until another block arrives or streaming ends; gate this path on an explicit unclosed-fence result instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This branch cannot receive a closed fence. Streamdown 2.5 computes isIncomplete as isAnimating && lastBlock && hasIncompleteCodeFence(block) (packages/streamdown/index.tsx, lib/incomplete-code-utils.ts), and hasIncompleteCodeFence already recognizes tilde fences, runs of four or more backticks, and up to three spaces of indentation, with a close that uses the same character and at least the same length. A closed tilde, four-backtick, or indented fence therefore has isIncomplete === false and still renders through Block. I ran the bundled predicate against markdownBlockFallback for all three forms and each reported isIncomplete: false.
|
Confirmed this hits the streaming route in studio/frontend/src/components/assistant-ui/markdown-text.tsx, where an unclosed fence has no codeFence and falls through to the bare Block that re-tokenizes on every frame, and highlighting still lands once via FenceBlock when the fence closes. Will get this reviewed. |
|
@codex security review |
|
To use Codex here, create a Codex account and connect to github. |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 27a00007de
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const openFence = markdownBlockFallback(props.content); | ||
| if (openFence.fenced) { |
There was a problem hiding this comment.
Handle open fences inside document-scoped blocks
When a reply contains a reference-style link and definition before a large open fence, parseMarkdownIntoRenderableBlocks deliberately returns the entire reply as one block (streaming-render-schedule.ts:142-145). In that case props.isIncomplete is true, but props.content begins with prose, so markdownBlockFallback reports fenced: false and this path falls through to <Block>, reproducing the per-update rendering lag this change is intended to eliminate. Detect the incomplete trailing fence rather than requiring the whole block to begin with its opener.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This shape renders exactly as it does on main, so it is not a regression. Document scope only applies when a reference definition or footnote appears before the open fence. In that case the whole reply is one block, and it still goes through Block as it always has. A reply whose definition comes after the code, which is the usual order, is split into blocks while the fence streams, so it does get the shell. Moving a trailing fence out of a document-scoped block would mean splitting a block that was kept whole on purpose so its references resolve. It would also need to know when an opener sits inside a list item or other container. That is a wider rendering change than this PR makes.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
I have confirmed the performance gain after this PR is significant (streaming a 140K-character code block in Chromium went from 29 fps to 59 fps), but so is the cost (disabling syntax highlighting during streaming). An optimization that avoids this functionality loss would be preferable. |
|
This fixes the lag, but disables syntax highlighting |
|
Picked this back up, and the answer to @oobabooga's point is in this PR's own numbers: the highlighting was never what cost the frames.
That is consistent with the rest of the tree. So the optimization that avoids the functionality loss is to stop rebuilding the spans, not to stop making them. #11423 does that: one memoized component per line, plus a line window past a 2,000 line cap where an off-screen line renders its text as one node instead of its token spans. The swap is the children of a line rather than the line, so heights are unchanged and the characters never leave the document, which keeps selection, copy, find-in-page and print exactly as they are. Measured in Chromium at 4x CPU throttle, 45 s of streaming per arm:
Twice the lines in the same wall clock with the visible code still coloured. Thanks @Souravrajvi0 for the original diagnosis, and @oobabooga for holding the line on the regression. Closing this one in favour of #11423. |
…#11423) * Studio: keep a streaming code fence highlighted, and window its spans 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. * 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]>
…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 #10769.
While a code fence is still streaming (no closing delimiter yet), the chat renderer was routing the growing body through Streamdown's
Blockcomponent, which runs Shiki syntax highlighting on every frame. For large outputs like a full HTML game, that made the UI nearly unusable.This change detects an open fence during streaming and renders the same plain
DeferredFenceShellused for off-screen deferral instead. Highlighting still runs once when the fence completes, via the existingFenceBlockpath.Root cause
getCodeFence()requires a closing fence, so streaming blocks fall through to the bareBlockfallback inStreamdownBlockContent. That path loads the highlighter immediately and re-renders thousands of tokens as the model streams more characters.Test plan
node --experimental-strip-types --test tests/markdown-block-boundary.test.ts tests/code-fence-defer.test.tsBlockand useDeferredFenceShell