Skip to content

Studio: keep a streaming code fence highlighted, and window its spans - #11423

Merged
danielhanchen merged 25 commits into
mainfrom
studio/windowed-fence-highlighting
Sep 22, 2026
Merged

danielhanchen merged 25 commits into
mainfrom
studio/windowed-fence-highlighting

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

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.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 prev.result === next.result, reference equality. Our plugin returns a fresh result object on every call, including the approximateResult path 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.mjs had 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 FenceBody replaces Block for fences, and does two things Block cannot.

One memoized component per line. code-plugin.ts pushes each completed line into fence.lines exactly once and never rebuilds it, so a committed line's array identity is already stable across refreshes and memo bails 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.ts rejects on those grounds, and deliberately not content-visibility: auto, which index.css already 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 split code-fence-mode.ts made out of code-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. getCodeFence needs the closing delimiter, so an open fence had no codeFence and fell through to the bare Block; it now renders the same body a completed fence gets, so the block does not change shape when its closing delimiter lands. markdownBlockFallback recognises the open fence rather than getCodeFence, so tildes, four or more backticks and indented fences take this route too.

Windowing is behind a new window fence mode and is not the ship default. The default stays defer, so playwright_heavy_thread.py and everything else that counts pre code span sees exactly what it sees today. Moving SHIP_DEFAULT is 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:

arm fps mean median frame frames over 33 ms spans at end lines in 45 s
streamdown-shaped (what main renders) 43.9 21.2 ms 336 37,112 1,448
per-line memo 48.6 16.8 ms 210 71,402 2,782
per-line memo plus window 50.1 16.6 ms 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.

Separately, the windowed and unwindowed arms of the same 4,000 line fence agree exactly:

unwindowed windowed
code height 75,000 px 75,000 px
thread scrollHeight 75,704 px 75,704 px
textContent 172,594 chars 172,594 chars
innerText 176,593 chars 176,593 chars
mounted token spans 30,861 351
computed content-visibility visible visible

Two 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 ResizeObserver silently never fires on a <code>, which is display: inline and 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

  • A single 140K-character line. Line windowing does nothing for it, and it stays bounded only by TOKENIZE_LIMITS.tokenizeMaxLineLength.
  • The numbers above are not the studiobench ladder: one machine, one run per arm, no null control, and a synthetic body rather than the corpus, which tops out at 1,800-character fences and so cannot show this workload at all. A single-growing-fence fixture and the pre-boot arms to go with it are the follow-up, and nothing here proposes moving the ship default before that runs.
  • The reasoning trace's OversizedReasoningCode path 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 build and npm run bundle:check: clean, within budget.
  • New tests/code-fence-window.test.ts runs 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.
  • New tests/code-fence-body.test.ts runs 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.
  • Unchanged and still green: 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.py as the height-stability gate, playwright_find_in_page.py including its three degraded-engine modes, and playwright_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 Block and onto `FenceBody`.

Before and after: a four-backtick code fence quoting a mermaid fence, rendered identically by both builds

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_count 8, code_first_line Example:, code_text equal, highlighted_token_count 30, on both. Zero scene facts moved between the two sides.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T17:27:32.867503Z 8025ea0 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
…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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation report

Ran the full before/after/what-else-changed pass on this branch: base arm at the merge base
b32e63e, head arm, same harness, driven through MarkdownTextSource so the markdown takes the
real route (Streamdown to StreamdownBlock to StreamdownBlockContent to the fence branches) rather
than reaching into anything the change added.

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
was re-measured after the fix rather than assumed.

What it measured

base head
3,000 line fence streaming, 4x CPU throttle, 3 runs 20.8 fps mean, median frame 37-38 ms, 1023-1071 frames over 33 ms, 1325-1353 lines in 90 s, never finished 42.0 fps mean, median frame 17.9-18.1 ms, 585-628 frames over 33 ms, 2,999 lines, finished every run
same, with the window on 21.1 fps, 33,780 spans, never finished 46.3 fps, 1,140 spans, finished every run
settled 3,000 line fence, window on 23,139 token spans 342 token spans
code height / thread scrollHeight / textContent 56,231.25 px / 75,704 px / 128,693 chars identical, windowed and not, in Chromium, Firefox and WebKit
window.find over a line the window has downgraded to plain text true true
select-all inside the fence 131,263 chars 131,263 chars

Null control, base build against base build, same scenes, 3 repetitions: detection floor 9.4% on
the streaming scene. The effect is +102% and +119%, sign consistent across every paired ratio, and
far larger than its own scatter. All three verdict gates clear.

A 600 line fence that closes reads 51.2 fps base against 49.5 fps head, a 3.3% delta against a
3.3% floor. That is on the floor, not above it, so it is not distinguishable from the null control
and I am not claiming it either way. The frame-time distribution on the same runs points the other
way: 17-19 frames over 33 ms on head against 24-30 on base.

Defects it found, and the fixes

  1. The body dropped streamdown's language-<info> class from the code-block-body div and the
    <pre>. Nothing in the tree selects on it, which is exactly why it would have gone unnoticed.
    Fixed in de388d9. Three scenes went from shape-different to identical.
  2. The streaming route dropped data-incomplete on the wrapper. Fixed in the same commit.
    Seven scenes went from one differing key to zero.
  3. A print kept the window, so a printed listing came out almost entirely uncoloured: 342 spans
    against the 23,139 the merge base printed. That is the defect upgradeEverythingForPrint exists
    to prevent, reintroduced one level down. Fixed in 5bbea49, both doors, synchronous inside
    flushSync, reverting on afterprint. After: 342 spans on screen, 23,139 under print
    emulation, textContent 128,693 in both states. code-fence-defer.test.ts banned the string
    afterprint outright; narrowed rather than dropped, so an afterprint handler may end the print
    and nothing else and no route may clear a latch.
  4. A raw pixel text utility in the line class. tests/studio/test_ui_font_scale_contract.py
    reads 12 passed on the merge base and 1 failed on this branch: the line class was copied
    verbatim from streamdown, which writes a fixed pixel size for the line-number pseudo-element,
    and that spelling is banned anywhere in frontend source. Found by the staging cross-platform
    pass, not by the frontend suite. Fixed in 3ee2942 with text-ui-13, same size at the default
    scale, follows the preference.

What else changed, which is the half worth reading

Every changed predicate enumerated over its full input space with the real helpers: 7 opener
shapes by 7 info strings by 10 bodies by open/closed by the two store flags, plus prose blocks.

cells       3968
identical   2448
moved       1520
violations     0
transitions  bare-block -> streaming-fence-body: 1520
moved cells that are NOT streaming: 0
prose cells 48, moved 0

Nothing leaves the mermaid, svg, canvas, artifact or fence-block branches, confirmed separately in
the browser on all three engines.

On the shipped default the window machinery costs nothing, measured rather than reasoned: 0
document scroll listeners and 0 getBoundingClientRect calls across a 60-frame scroll, the same as
the merge base. With the window on it is 1 listener and about 2 rect reads per frame, the listener
drains on unmount, and a 60-frame scroll takes 994 ms against the base arm's 997 ms.

Cross-engine, 15 scenes by 3 engines by 2 arms, each with a five-stable-reads settle gate:
Chromium, Firefox and WebKit all report 0 unexpected differences and 0 unsettled cells. A first
WebKit pass reported 4 differences; they were a measurement race (the base arm was being read at
2,571 spans where Chromium read 23,139), so the gate was added and the run repeated rather than
either number being reported.

Frontend suite 8,190 passed 0 failed on head, 8,165 passed 0 failed on base. 9 of the 23 new tests
fail on the merge base with the functional hunk reverted and the tests kept.

What I could not prove

  • The studiobench ladder did not run. It needs a Studio install, and the frozen corpus tops out at
    1,800 character fences so it cannot carry this workload without a new fixture. Everything above
    is my own harness with a null control and three repetitions on one machine.
  • Per-frame work is still linear in the number of lines, not in the viewport. A React element is
    created per line on every render even when every one memo-bails, so the window removes a constant
    factor of roughly ten rather than the asymptote. Going further means virtualization, which
    progressive-mount-controller.ts rejects on find-in-page, selection, copy and print grounds.
  • A single enormous line is unaffected.
  • The live app was not driven end to end: the harness renders MarkdownTextSource with two
    assistant-ui hooks stubbed identically on both arms, so the thread viewport, the autoscroll
    observer and the SSE path are outside the measurement.
  • windows-11-arm, ubuntu-24.04-arm and macos-26 did not run, and native Safari is not
    automatable here.
  • Of the staging failures: one was defect 4 above; test_chat_response_details_ui_contract (2
    failed) and test_desktop_reliability_frontend_contract (1 failed) fail identically on the merge
    base and are drift against current main, not this PR; workflow-trigger lint flags
    staging-11423-playwright.yml, a file staging generates and which does not exist here; and the
    ubuntu Composer leg failed to launch a browser after an apt timeout while the same matrix passed
    twice on macOS.

`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.
@wasimysaid

wasimysaid commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

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 — ee4622670

CODE_FENCE_RE closed a fence with exactly three backticks, but CommonMark wants "at least as many" as the opener. A 3-backtick fence closed with 4 — normal when the body contains a backtick run — had the surplus delimiter absorbed into source. Only the completed block takes that path, so the block grew a stray backtick line exactly when the closing delimiter landed.

The fix is {3,}, and both halves of that matter: a bare lazy run also accepts a 1- or 2-backtick run as a close, which deletes real code and misreads an aborted reply. Checked against micromark over 540 opener/body/closer/tail/indent shapes:

close disagreements with CommonMark
{3} (head) 54
+? 54 (different rows)
{3,} 0

Injecting the same fixture through the app's own /api/chat/threads/{id}/messages:

input before after
```python / x = 1 / ``` 1 line, 5 spans, 19 px unchanged
```python / x = 1 / ```` 2 lines, `x = 1``, 7 spans, 38 px 1 line, x = 1, 5 spans, 19 px

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, language-ts on both the code-block body and the <pre>, plus its copy/download buttons — so a streaming fence keeps its colours and does not change shape when the closing delimiter lands.

Mount cost and span census (one fixture, 24 fences x 150 lines, 22 of them off screen when the thread opens):

mode first paint mounted spans
off (what main renders) 7136 ms 56,850
defer (ship default) 1510 ms 4,800

4.7x faster to first paint and 91.6% fewer spans, with line counts, textContent and code height byte-identical across arms. On a 4,000-line fence the line window takes 64,000 spans down to 4,960 with the same 75,000 px height and the same text.

Gate: the repo's own playwright_code_block_flicker.py passes against the branch head, and node --test tests/code-fence-close-run.test.ts is 5/5 with tsc --noEmit clean on ee4622670.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

@wasimysaid

Copy link
Copy Markdown
Collaborator

Short clip of the shipped defer mode doing the thing this PR claims, recorded on a real build of the branch head — Studio installed on an isolated home, a local Qwen3.8-27B GGUF streamed through the app, captured with Playwright.

streaming code fence keeps its highlighting

Full quality (same 14 s clip, 720 px, original quality): pr11423-fence-stream.mp4

What to look at, in the order it happens:

  1. The reply streams straight into a fence and is coloured from the first line. The header counts lines / coloured tokens / distinct colours / language-* out of Studio's own DOM every frame — 0 → 104 lines and 8 colours while the block is still being written, never a grey placeholder.
  2. The colour is per line and stays put. Lines already written keep their tokens as new ones arrive; nothing re-flashes.
  3. The block does not change shape when the closing delimiter lands. At the end the same 104 lines / 774 coloured tokens are on screen, language-* still on the code block, and the last line is still highlighted.
  4. The fence is highlighted while incomplete — the streaming path, not the completed-block path. That is the part a screenshot cannot show.

Recorded at native speed, no speed-up. The clip is hosted on a media-only branch of my fork (pr-evidence-11423), so nothing here touches this PR's files.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
… 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

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

Copy link
Copy Markdown
Member Author

@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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 189a35a174

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

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 MarkdownTextSource behind a small shim, not out of Studio.

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 Example:, the quoted ```mermaid opener, graph TD, ` A --> B`, the quoted closing run, and all three `const value_N` lines. Nothing is dropped.

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:

  • The closing-run and mermaid fixes remain correct on their own terms. Those were verified against micromark at the classifier level, which is independent of how the block is then rendered.
  • The multi-fence defect I pushed in 864eb6b stands on the same footing and is likewise verified against micromark, not against my harness. It is worth noting that it has the same latent-versus-visible character, so the same caution applies to any claim I make about what a reader sees.
  • The performance numbers are unaffected: those are frame timings from the harness comparing two builds against each other, not claims about rendered content.

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.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 864eb6b93f

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

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Decode fence info before classifying Mermaid

For a valid CommonMark fence such as ```merm&#x61;id, 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right about the spec, and I checked it rather than assuming: micromark renders both merm&#x61;id 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

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

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

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

Comment on lines +785 to +786
(late) => {
if (wanted.current === body) setTokens(late);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

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

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@danielhanchen
danielhanchen merged commit 40ade0f into main Sep 22, 2026
47 of 54 checks passed
@danielhanchen
danielhanchen deleted the studio/windowed-fence-highlighting branch September 22, 2026 06:23
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants