Skip to content

fix(studio): stop re-tokenizing the whole code block on every frame while streaming - #7537

Merged
danielhanchen merged 5 commits into
mainfrom
fix/studio-streaming-code-highlight
Jul 28, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix/studio-streaming-code-highlight

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

Problem

Reported in #7522. The chat UI gets progressively laggy while a model is generating, and it is much worse once the answer contains a large block of code. The video in that thread shows the reasoning text streaming smoothly and then the code arriving in lumps.

The cause is in the Shiki code plugin. While a fence is still streaming, highlight() is called on every animation frame with the entire block, and Shiki re-tokenizes it from scratch each time. That is O(length) per frame and O(length^2) over the message.

Instrumenting one generation:

highlight() calls:  808        (~50/sec, i.e. every frame)
chars tokenized:    5,504,216
rendered block:     13,561 chars

5.5MB of tokenization to render a 13.5KB block. A CPU profile of 8.2s mid-stream put about 4s, roughly half the renderer main thread, inside the TextMate tokenizer (findNextMatchSync 2.78s, plus _pushAttributed and the grammar matchers).

Worth noting for the issue thread: this is not specific to HTML and not caused by the canvas preview. A Python block of the same size degrades identically. "write a html flappy bird game" is simply a prompt that reliably produces a big code block very quickly.

Fix

Blocks under 2000 chars are unchanged, since a full re-tokenize is cheap there. Above that, a growing fence reuses the tokens from the last real tokenization for the lines it already covered and appends the newly arrived tail as unstyled lines, so text still lands every frame. A full re-tokenize runs at most every 250ms, which colours the tail and fixes up any construct spanning the boundary.

Shiki always returns null synchronously and resolves through the callback, so throttling the dispatch is what actually removes the per-frame work.

Results

Measured against the real UI by replaying a stream at 230 tok/s, the generation rate from the reporter's log, so rendering is isolated from inference.

emitted chars frame p50 before dropped before frame p50 after dropped after
0 to 8k 16.7ms 0 16.7ms 0
16k 26.3ms 2 16.6ms 4
22k 8.0ms 110 16.7ms 9
26k 8.8ms 112 16.7ms 9

Total dropped frames over the generation: 460 to 63 for the HTML block, 567 to 50 for the Python one. Frame p50 stays pinned at 16.7ms instead of collapsing into lumps (the low p50 values before the fix are frames bunching together, not frames being fast).

Tokenizer time went from about 4s to about 280ms per 8s of streaming, and the main thread went from roughly 50% busy to 57% idle.

Verification

The finished block renders byte identical to before the change (28,320 chars in, 28,320 out) and fully highlighted (9,078 spans, 8,181 coloured). Typecheck and build pass.

Not covered here

While measuring I found two more streaming render costs that are separate from this one:

  • Large markdown tables are worse than this was. A 600 row table spent 40.5s of a 72s stream in long tasks, dominated by micromark's GFM table resolver. Fine under about 200 rows, degrades sharply past 400.
  • Inline code heavy text is slowed by a character scan inside Streamdown.

Both sit upstream of us rather than in this plugin, so they are not touched here.

Closes #7522

…ocks

A streaming fence re-enters highlight() every animation frame with the whole
block, so Shiki re-tokenizes it from scratch each time: O(length) per frame and
O(length^2) over the message. One generation made 808 highlight() calls and
tokenized 5.5MB of text to render a 13.5KB block, putting ~50% of the renderer
main thread in the TextMate tokenizer.

Blocks under 2000 chars are unchanged. Above that, a growing fence reuses the
tokens from the last real tokenization and appends the new tail unstyled, with
a full re-tokenize at most every 250ms.

@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: fde50f8f7b

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

return inner.highlight({ ...opts, language }, callback);
}

const key = `${language} ${JSON.stringify(opts.themes)}`;

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 Key the cache by code fence identity

When one streamed message contains multiple code fences over 2,000 characters with the same language and themes, every fence shares this single cache entry. Streamdown revisits the earlier fences while rendering each update, so each fence overwrites the entry before the growing fence is reached; startsWith(cached.code) then fails and both fences are fully tokenized again every frame. This leaves the reported lag essentially unfixed for multi-block answers, so the cache needs to distinguish fences or retain multiple prefix candidates.

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.

This one is addressed as of a4d111a. The cache is no longer a single entry per language and themes: it is a list of slots, and a call is matched to its own slot by longest prefix, so sibling fences no longer evict each other.

Reproduced the original problem first so the fix had something to prove. Driving the real plugin against a stubbed @streamdown/code, two same-language fences revisited on every render:

before: 30 inner dispatches for 30 renders
after:   2 inner dispatches for 30 renders

Against the real renderer with ten fences the same change takes inner dispatches from 376 to 20, with output byte-identical to source and the same 6900 of 8730 coloured spans on both sides.


// Shiki returns null synchronously and resolves via callback, so
// throttling the dispatch is what removes the per-frame work.
if (grewFrom && now - grewFrom.dispatchedAt < REFRESH_MS) {

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 Schedule a full highlight after returning cached tokens

When generation finishes less than 250 ms after the latest real dispatch, the final status render can take this branch and return the synthetic cached result. The branch neither invokes the callback nor schedules a refresh after the throttle window, and no later text or status render is guaranteed, so the completed block can permanently retain an incorrectly styled tail. Schedule the deferred full highlight, or otherwise force one when streaming completes.

Useful? React with 👍 / 👎.

Two defects found while property-testing the reuse path:

- plainLine() spread the template token, so newly streamed lines inherited the
  first token's colour instead of the default foreground. Emit a bare token.
- A reused result could be the final one if the caller stopped re-rendering,
  leaving the tail permanently unstyled. Schedule a trailing re-tokenize so a
  reused run always converges.

@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: fbb35402e5

ℹ️ 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 +124 to +125
if (!canReuse) {
return dispatch(entry, { opts, language, callback });

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 Cancel stale trailing refreshes before direct dispatch

If main-thread work delays the trailing timer until after REFRESH_MS and a newer render reaches this branch first, the newer code is dispatched while the old timer and entry.latest remain pending. When that timer subsequently runs, it dispatches the older code and invokes its callback, which can replace the completed highlight with a stale or truncated block when no further render occurs. Clear the pending timer/latest value before this direct dispatch, or version-check the timer payload.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. Reproduced with a fake clock: arm the trailing refresh, let the timer run late (a backgrounded tab clamps timers to 1s while stream-driven commits keep arriving), and have a newer render dispatch first past REFRESH_MS. The late timer then re-dispatched the older code and its callback replaced the finished block, leaving 2805 of 2851 characters on screen. Fixed in a4d111a by clearTrailing() before every direct dispatch.

Comment on lines +118 to +121
const canReuse =
entry.result != null &&
opts.code.length > entry.code.length &&
opts.code.startsWith(entry.code) &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reuse completed blocks on identical renders

When streaming continues after a block over 2,000 characters has closed, such as when prose follows the fence, Streamdown revisits that fence with byte-identical opts.code; the strict growth check rejects this exact cache hit and dispatches Shiki again on every subsequent render. This preserves the frame-by-frame full-tokenization cost for completed large blocks during the rest of the stream, even when there is only one fence and no cache-key collision. Track which code produced entry.result and return that result when the input is identical.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Marking this one down: both premises measured false against the real renderer. I streamed a 6k python fence to completion and then kept 400 paragraphs of prose streaming for another 60 seconds, counting every highlight() call whose code was byte-identical to a previous one: 0 on the merge base and 0 on the PR. Streamdown's Block memo gates on content and HighlightedCodeBlockBody's effect deps are [code, language, shikiTheme, plugin, raw], all frozen once the fence closes, so the effect does not re-run. And when an identical call does occur, @streamdown/code returns from its own fingerprint cache synchronously with zero tokenizations, so there is no full re-tokenization to preserve. The fast path added in a4d111a is harmless, just not load-bearing.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed two defects found while property testing this, plus the test setup used.

Defects found and fixed in fbb3540

  1. plainLine() spread the template token, which carries color and variants. Newly streamed lines therefore inherited the first token's colour, so the tail of a growing block was painted in the keyword colour rather than the default foreground. It now emits a bare token.
  2. A reused result could end up being the final one if the caller stopped re-rendering, leaving the tail permanently unstyled. A reused run now schedules a trailing re-tokenize, so it always converges to a real highlight.

Tests

Unit, driving the real plugin against a mock highlighter that mirrors shiki's contract (returns null synchronously, resolves via callback). 28 assertions, all passing:

  • text integrity across streaming sequences for plain source, no trailing newline, CRLF, a 12k single line, blank line heavy, unicode and emoji, empty lines only, tabs
  • shrink, replace and branch switch must not reuse
  • two blocks of the same language where one is a strict prefix of the other
  • tail colour must not inherit the template token
  • trailing dispatch fires after the stream goes silent
  • blocks under the threshold are never throttled
  • stale callbacks still reach the caller

LaTeX PR (#7538) differential, old implementation vs new over 20,120 inputs including every prefix of a streaming document: identical output, zero mismatches.

Cross engine, Playwright against a live Studio at 230 tok/s, eight payloads each on Chromium 149 (Chrome and Edge), Firefox 151 and WebKit 26.5 (Safari). Colour coverage of the last 15% of lines matches the first 15% on every engine and payload, which is the check a stale tail would fail.

Every remaining flag in that matrix reproduces identically on main with these changes reverted, so none of them are regressions from this PR. Two are pre existing and worth separate issues:

  • a single long line with many tokens stalls the render. Minified JS at 8.8k chars and a 16k CSV header row both stop progressing around 3 to 4k chars and never finish. Long strings and base64 are fine, so it looks like tokenizer backtracking rather than length alone. Unchanged by this PR, and base64 actually got faster, 24.2s to 13.5s.
  • WebKit logs access control page errors against /api/health and /api/auth/status on every page load, on main too.

Verified on macOS. Both files are plain TypeScript with no platform specific APIs, and CRLF is covered above.

@shimmyshimmer

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: fbb35402e5

ℹ️ 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 +108 to +112
const key = `${language} ${JSON.stringify(opts.themes)}`;
let entry = cache.get(key);
if (!entry) {
entry = { code: "", result: null, dispatchedAt: 0, trailing: null, latest: null };
cache.set(key, entry);

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 Keep separate throttle entries for simultaneous fences

When one streamed response contains multiple code fences using the same language and themes, they all share this single cache entry—the code plugin is a singleton in markdown-text.tsx. As Streamdown revisits the fences, each block overwrites entry.code; because the next block is generally not its prefix, canReuse is false and both blocks are fully dispatched again on every render. This restores the quadratic tokenization cost that this change is intended to remove for multi-block answers, so the throttle state needs to distinguish individual fences rather than only language/theme.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed as a real design gap and fixed in a4d111a by the per-fence slots, but one magnitude correction for the record: the claim that both blocks are fully dispatched again on every render did not hold when measured. On fbb3540, a message with a finished 3k python fence plus a streaming 20k one took 82 inner dispatches against 177 on the merge base, so the throttle was still doing most of its job. The visible damage in that fixture came from the code/result misalignment in 3665058291, not from the shared key.

Comment on lines +124 to +125
if (!canReuse) {
return dispatch(entry, { opts, language, callback });

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 Cancel obsolete trailing refreshes before dispatching new content

When a reused block schedules entry.trailing and the same cache entry then receives non-prefix content before that timeout runs—for example, after switching or replacing a large artifact—the non-reuse path dispatches the new content but leaves the old latest request and timer intact. The timeout subsequently dispatches the obsolete code, overwrites entry.code, and invokes its stale callback after the newer request, which can temporarily restore the previous block's tokens and leaves the cache tracking the wrong content. Clear the pending timer/request whenever this path supersedes it.

Useful? React with 👍 / 👎.

Comment on lines +85 to +90
const dispatch = (entry: CacheEntry, { opts, language, callback }: Dispatch) => {
entry.code = opts.code;
entry.dispatchedAt = Date.now();
return inner.highlight({ ...opts, language }, (result) => {
// Ignore stale results from a superseded dispatch.
if (entry.code === opts.code) entry.result = result;

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 Keep cached code aligned with its token result

When a refresh is dispatched, these assignments immediately advance entry.code but leave entry.result holding tokens for the previous, shorter code until the asynchronous callback finishes. If another highlight occurs in that interval—for example while a grammar chunk is loading or when highlights are batched in one render—the prefix check treats the old result as though it belongs to the new entry.code; the reuse path then slices the old token array using the new code's line count, which can omit newly appended text on the prior final line or misalign the rendered tail. Track the code associated with result separately from the in-flight dispatch code, or disable reuse until they match.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed, and this was the one that actually reached the screen. Reproduced against fbb3540 with @streamdown/code stubbed: a tokenized run that ended mid-line, then a refresh dispatch that advanced entry.code while entry.result still described the older string, made the reuse path render C059 partial where the source said C059 partial-line-continues (15 characters silently dropped). In a real browser it also collapsed a re-render of a two-fence message from 4710 coloured spans to 1267. Fixed in a4d111a: slot.code is now written only alongside slot.result, and both canReuse and the slice read it.

… with code

Review found four real defects in the previous approach:

- entry.code advanced at dispatch time while entry.result still held the older
  tokens, so a reuse could slice one against the other and drop text from the
  cached run's final line.
- A finished fence re-rendered with identical code re-dispatched every frame,
  keeping the per-frame cost for the rest of the stream.
- All fences of one language shared a single entry, so sibling fences evicted
  each other and both were fully tokenized on every render.
- An overdue trailing timer could dispatch stale code after a newer dispatch.

Cache is now one slot per fence, matched by longest prefix. code and result
only ever move together, an exact match is served straight from cache, and a
direct dispatch or a slot eviction cancels any pending trailing refresh.
@shimmyshimmer

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: a4d111a938

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

if (!slot) {
slot = { code: "", result: null, inFlight: null, lastDispatchAt: 0, trailing: null, pending: null };
slots.unshift(slot);
for (const dropped of slots.splice(MAX_SLOTS_PER_KEY)) clearTrailing(dropped);

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 Avoid cache thrashing after the eighth code fence

When a message contains nine or more code fences over 2,000 characters with the same language and themes, this fixed-size eviction policy causes every fence to miss on every subsequent render: processing the first missing fence evicts the next fence before Streamdown reaches it, and the cycle continues through the message. During streaming, all of those fences are therefore fully re-tokenized on every frame, recreating—and amplifying—the performance problem this change is intended to solve.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Measured against the real renderer and could not reproduce it. Fixture: ten python fences in one message, each just over 2000 characters, streamed at 900 tok/s through real streamdown 2.5.0 and shiki 3.23.0, with a counter on every highlight() call whose code was byte-identical to one already seen.

merge base a4d111a
highlight() calls 273 280
byte-identical repeat calls 0 0
inner Shiki dispatches 273 236
dropped frames 43 41
main thread blocked 717 ms 683 ms

All ten blocks rendered, 5020 of 5020 coloured spans, text byte-identical to source.

The eviction cycle needs Streamdown to revisit each earlier fence on every render, and it does not: Block is memoized on content, and HighlightedCodeBlockBody's effect deps are [code, language, shikiTheme, plugin, raw], all frozen once a fence closes, so the effect never re-runs for it. That is why the repeat-call count is 0 rather than large. Even if a revisit did happen, @streamdown/code answers byte-identical code from its own fingerprint cache synchronously with zero tokenizations, so there is no full re-tokenization to amplify. At ten fences the PR is still ahead of the base rather than behind it.

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.

Independently measured and I could not reach it either, though I want to record why rather than just the result.

The premise is that several fences call highlight() in the same render. They do not. Streamdown only calls it for the fence whose content changed, so a closed fence never comes back. Instrumenting every call with a hash of its code, ten fences of ~2.7k chars each streamed at 900 tok/s:

merge base 47c624e
highlight() calls 376 375
distinct code strings 376 375
byte-identical repeat calls 0 0
inner Shiki dispatches 376 20
coloured spans 6900 / 8730 6900 / 8730

Ten fences against eight slots is past the eviction threshold, and the dispatch count went down 18x rather than up. If the cascade were real, inner dispatches would track highlight() calls at 375.

The zero repeat count is also the honest answer to the earlier "reuse completed blocks on identical renders" suggestion: that fast path is correct but never load bearing, because Streamdown does not re-ask for a fence it has already closed.

@danielhanchen

Copy link
Copy Markdown
Member

Independent verification of a4d111a, since I had already built a rig for this.

Method. Two layers. A deterministic Node harness that imports code-plugin.ts verbatim with only the @streamdown/code import specifier redirected to a controllable stub (fake wall clock plus a separate monotonic clock, manual callback resolution, synchronous-cache-hit support, provenance-tagged tokens), and a browser harness that mounts the real streamdown 2.5.0 with real shiki 3.23.0 and the real Unsloth themes, replays a message at 230 tok/s off requestAnimationFrame, and compares the finished DOM against a fresh static render of the same text.

Where the head stands. Seven of my ten checks pass on a4d111a, up from two on fbb3540. The two P2 items that reached the screen are gone:

fixture merge base fbb3540 a4d111a
two same-language fences, coloured spans after a re-render 9246 9198 9246
finished 3k fence + streaming 20k fence, re-render 4710 1267 4710
CRLF fence, coloured spans at end of stream 2835 2807 2835

The speedup holds after the correctness work, on Chromium 149, Firefox 151 and WebKit 26.5 (which between them are every engine Studio ships on: WebView2 on Windows, WKWebView on macOS, WebKitGTK on Linux, plus the browser path). Inner dispatches, merge base to a4d111a, at 900 tok/s on Chromium: 28k HTML fence 98 to 42, two HTML fences 147 to 74, CRLF fence 62 to 27, sibling python 177 to 82. Dropped frames on the 28k fence 59 to 36. Rendered text was byte-identical to the source in every run, on every engine, with no page errors.

Two things still open, neither blocking:

  1. Date.now() is wall clock. A backward step (NTP correction, resume from sleep) makes elapsed negative, which pins the reuse branch on and schedules the trailing refresh by the size of the step, so a one hour step arms a one hour timer. In my harness no refresh happened in 12.5 seconds of wall clock after a step back. performance.now() is monotonic and is a drop-in here. MDN: "the timestamps returned by performance.now() are not subject to clock adjustments".
  2. Cold start is unthrottled: while shiki is still loading, slot.result is null so every frame dispatches a full tokenize (61 over 61 frames in the harness). This is identical to the pre-PR behaviour, so it is not a regression, just the one case the throttle does not yet cover.

Separately, JSON.stringify(opts.themes) in the cache key serializes both full theme registrations, about 59 KB at roughly 87 microseconds, once per call. It does not defeat the win, but keying on theme.name would be free.

The red Repo tests (CPU) check is pre-existing and unrelated: test_shipping_code_names_an_encoding fails on studio/install_llama_prebuilt.py:5647,5656 from 7917c78, and fails identically on a clean main.

@danielhanchen

Copy link
Copy Markdown
Member

@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: a4d111a938

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

target.trailing = null;
const next = target.pending;
target.pending = null;
if (next) dispatch(target, next);

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 Handle cached results from the trailing refresh

When the pending snapshot has already been highlighted by another plugin instance or earlier render, the pinned @streamdown/code implementation returns its cached HighlightResult synchronously and does not invoke the callback. This timer discards that return value, so dispatch leaves the slot pointing at the older result and React never receives the fully highlighted snapshot; if streaming ends here, the synthetic unstyled tail remains visible until an unrelated remount or code change.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 47c624e. Reproduced with the inner plugin stubbed: pre-seed @streamdown/code's fingerprint cache with the fence's final snapshot (another plugin instance or an earlier render having tokenized it), let the trailing timer fire, and the fence ends with 3 of 62 rows permanently unstyled, because dispatch() discarded the synchronous return and the callback is never invoked on that path. dispatch() now adopts a synchronous result into the slot, and the timer hands it to the pending callback.

Comment on lines +159 to +166
slot.pending = { opts, language, callback };
if (slot.trailing === null) {
const target = slot;
target.trailing = setTimeout(() => {
target.trailing = null;
const next = target.pending;
target.pending = null;
if (next) dispatch(target, next);

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 Cancel trailing work after a non-append update

When a large block schedules this trailing refresh and the same Streamdown code component is then changed to code that does not extend the cached prefix, such as an artifact/version replacement or edited response, the next highlight call allocates a different slot without clearing this pending timer. The old timer subsequently dispatches its captured opts and invokes the same React state setter after the newer result, overwriting the rendered block with tokens and text from the previous code indefinitely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Marking this down because I could not reach it, not because the mechanism is imaginary. The code-level point is right: allocating a new slot does not clear an older slot's timer, and in a unit model with one shared state setter the old block does come back.

What I could not show is any difference from the merge base. Driving a real streamdown 2.5.0 component in Chromium, streaming a 90-line python block and then replacing it with a different one 120 ms later, the merge base and this head render identically, so the trailing timer is not what causes the old content to persist there. streamdown's own useEffect has no cleanup, so an in-flight callback for the previous code already lands on setResult without any of this.

I also did not want to fix it blind. The obvious remedy, clearing sibling slots' timers when a new slot is allocated, would regress a case I did measure as load-bearing: with two same-language fences, the trailing refresh is exactly what takes the finished first fence from 9198 to 9246 coloured spans. Since the plugin API exposes no fence identity, a completed fence and a swapped-out fence are indistinguishable at that point, and the stale timer's window is bounded by REFRESH_MS.

If you have a repro where this is visible and the base is not affected, I will take it and the fix is a one-liner.

@streamdown/code answers out of its own cache synchronously and never invokes
the callback in that case. dispatch() ignored that return value, so the slot
kept pointing at the older tokens. On the trailing refresh, where nothing else
consumes the return, that left the fence showing its unstyled tail until an
unrelated remount. Adopt the synchronous result on both paths and hand it to
the pending callback.

Drive the throttle off performance.now(). Date.now() is wall clock, so a
backward step from an NTP correction or a resume from sleep makes elapsed
negative, which pins the reuse branch on and schedules the trailing refresh by
the size of the step.
@danielhanchen

Copy link
Copy Markdown
Member

@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: 47c624e9b4

ℹ️ 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 +183 to +188
target.trailing = setTimeout(() => {
target.trailing = null;
const next = target.pending;
target.pending = null;
if (!next) return;
const immediate = dispatch(target, next);

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 Cancel trailing refreshes after code is replaced

When a large fence schedules this trailing refresh and, within 250 ms, its code is shortened, replaced, or its language/theme changes, the next highlight call selects a different slot and never cancels this timer. The newer highlight can therefore complete first, after which this callback delivers tokens for the obsolete code and permanently replaces the displayed source until another update occurs; invalidate outstanding trailing work when a fence stops matching its previous slot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Third pass on this one, and I now have a direct measurement rather than an argument.

I built a probe that streams an 80-line python fence past the 2000-char threshold so the throttle arms a trailing refresh, then replaces the entire message with a different fence at 60 ms, 100 ms and 200 ms, and samples the DOM three times: right after A finishes, 60 ms after the swap, and 3 s after it settles. Chromium 149, real streamdown 2.5.0 and shiki 3.23.0.

delay variant after A just after swap settled
60 ms base old old old
60 ms this head old old old
100 ms base old old old
100 ms this head old old old
200 ms base old old old
200 ms this head old old old

The replacement never reaches the DOM at all, on the merge base either. Streamdown in mode="streaming" commits blocks and does not revise them, so "the same Streamdown code component is then changed to code that does not extend the cached prefix" is not a state the renderer produces. That is why I cannot reach this, and why base and head are indistinguishable.

On the theme half of the trigger: Studio passes a fixed dual-theme tuple and switches light and dark through CSS variables, so shikiTheme never changes identity and the key never moves.

Not changing code for it, for the reason I gave last round: the only obvious remedy, cancelling sibling slots' timers, would regress the two-fence case where the trailing refresh is exactly what takes the finished first fence from 9198 to 9246 coloured spans, and the plugin API exposes no way to tell a finished fence from a swapped-out one.

Worth splitting out separately: that probe does suggest the artifact source view keeps showing the previous artifact's source after a switch, since its Streamdown has no key and streaming mode will not revise the block. That reproduces on the merge base, so it is a pre-existing Studio issue rather than anything this PR touches.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 47c624e9b4

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

@codex review

@danielhanchen
danielhanchen merged commit 9e568c1 into main Jul 28, 2026
39 of 40 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-streaming-code-highlight branch July 28, 2026 13:30

@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: 4160c5cea8

ℹ️ 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 +133 to +134
if (opts.code.length < MIN_INCREMENTAL_CHARS) {
return inner.highlight({ ...opts, language }, callback);

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 Cancel stale trailing refreshes when bypassing the cache

When a fence above 2 KB has a trailing refresh queued and its content is then truncated below this threshold within 250 ms, this early return leaves the old timer and its callback active. The current short-code highlight can resolve first, after which the timer invokes the previous callback and makes Streamdown display the obsolete long code indefinitely if no further render occurs; cancel or invalidate pending incremental work before delegating here.

Useful? React with 👍 / 👎.

Comment on lines +164 to +168
const elapsed = monotonicNow() - slot.lastDispatchAt;
const grew = slot.result !== null && opts.code.length > slot.code.length;
if (!grew || elapsed >= REFRESH_MS) {
clearTrailing(slot);
return dispatch(slot, { opts, language, callback });

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 Throttle growth while the initial highlight is pending

When a fence first enters this path above 2 KB and its Shiki highlighter or language is still loading, slot.result remains null, so every subsequent growing frame sets grew to false and dispatches another full snapshot. The inner plugin queues each distinct request behind the same asynchronous highlighter load and then runs codeToTokens for every queued snapshot, recreating the burst of whole-block tokenization this change is intended to prevent; use inFlight to queue only the latest growth even before the first result exists.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Extremely laggy/slow webUI

2 participants