Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han015bdef0d94a
diff --git a/studio/frontend/scripts/coal-span-census.mjs b/studio/frontend/scripts/coal-span-census.mjs
new file mode 100644
index 00000000000..a550bec81f4
--- /dev/null
+++ b/studio/frontend/scripts/coal-span-census.mjs
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Would merging adjacent same-styled Shiki tokens remove any spans?
+ *
+ * WHY THIS EXISTS. The renderer emits one <span> per themed token, so a thread's span census is
+ * its token census, and Shiki splits on GRAMMAR boundaries rather than on rendered appearance:
+ * `foo`, `.`, `bar` in a member expression look like three tokens carrying one identical colour.
+ * Merging runs whose rendered style is byte-identical therefore looks like a pure reduction with
+ * no viewport gating, no state machine and nothing a reader can do to undo it.
+ *
+ * It removes nothing. Over the whole studiobench corpus, 728 fences and 1,335,897 code
+ * characters in typescript, go, rust, python and c:
+ *
+ * dual tokens 537013 -> merged 537013 0.0% fewer
+ * darkonly tokens 535981 -> merged 535981 0.0% fewer
+ *
+ * and over the 100K rung's 99 assembled fences, 180,902 characters, 72,550 -> 72,550 dual,
+ * 72,408 -> 72,408 dark only, 62,098 -> 62,098 light only. Not one adjacent pair in half a million
+ * shares a rendered style, in any theme mode. Shiki already emits maximally coalesced tokens.
+ *
+ * This script is kept so the result is checkable rather than quoted, and so the next person to
+ * have the idea can spend a minute on it instead of a day.
+ *
+ * USAGE. Point it at any markdown that contains fenced code; a saved thread export, a docs page,
+ * a scratch file. It extracts the fences itself.
+ *
+ * node studio/frontend/scripts/coal-span-census.mjs thread.md [more.md ...]
+ * node studio/frontend/scripts/coal-span-census.mjs --theme dark thread.md
+ *
+ * The configuration below is the one `code-plugin.ts` uses: the JavaScript regex engine, one-light
+ * and one-dark-pro with transparent backgrounds, dual-theme `themes:` mode.
+ */
+
+import { readFileSync } from "node:fs";
+import oneDarkPro from "@shikijs/themes/one-dark-pro";
+import oneLight from "@shikijs/themes/one-light";
+import { createHighlighter } from "shiki";
+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+
+const withTransparentBg = (t) => ({
+ ...t,
+ bg: "transparent",
+ colors: { ...t.colors, "editor.background": "transparent" },
+});
+const light = { ...withTransparentBg(oneLight), name: "unsloth-light" };
+const dark = { ...withTransparentBg(oneDarkPro), name: "unsloth-dark" };
+
+// The merge predicate. `htmlAttrs` blocks a merge outright rather than being reconciled: it can
+// carry ids, titles or data attributes something downstream depends on, and two spans that differ
+// there are not interchangeable however identical they look.
+const sameHtmlStyle = (a, b) => {
+ if (a === b) return true;
+ const ka = a ? Object.keys(a) : [];
+ const kb = b ? Object.keys(b) : [];
+ if (ka.length !== kb.length) return false;
+ for (const k of ka) if (a?.[k] !== b?.[k]) return false;
+ return true;
+};
+const hasAttrs = (t) => t.htmlAttrs !== undefined && Object.keys(t.htmlAttrs).length > 0;
+const mergeable = (a, b) =>
+ a.color === b.color &&
+ a.bgColor === b.bgColor &&
+ a.fontStyle === b.fontStyle &&
+ !hasAttrs(a) &&
+ !hasAttrs(b) &&
+ sameHtmlStyle(a.htmlStyle, b.htmlStyle);
+
+const coalesceLine = (line) => {
+ if (line.length < 2) return line;
+ const out = [];
+ for (const tok of line) {
+ const last = out.length ? out[out.length - 1] : null;
+ if (last !== null && mergeable(last, tok)) {
+ out[out.length - 1] = { ...last, content: last.content + tok.content };
+ continue;
+ }
+ out.push(tok);
+ }
+ return out;
+};
+
+// Every fence form CommonMark allows, not just the unindented triple backtick: three or more
+// backticks or tildes, up to three spaces of indent, closed by at least as many of the same
+// character. Scanned line by line rather than by one regex, because a regex that treats the
+// closing delimiter as optional will also match every CLOSING line as a fresh opener and double
+// the fence count, which is what the first version of this did.
+const OPEN_RE = /^ {0,3}(`{3,}|~{3,})([^\n]*)$/;
+
+const readFences = (paths) => {
+ const out = [];
+ for (const path of paths) {
+ const lines = readFileSync(path, "utf8").split("\n");
+ let open = null;
+ let body = [];
+ for (const line of lines) {
+ const m = OPEN_RE.exec(line);
+ if (open === null) {
+ if (m && !(m[1][0] === "`" && m[2].includes("`"))) {
+ open = { marker: m[1], lang: m[2].trim().split(/\s+/)[0] || "text" };
+ body = [];
+ }
+ continue;
+ }
+ // A closer is the same character, at least as long, and carries nothing else.
+ if (m && m[1][0] === open.marker[0] && m[1].length >= open.marker.length
+ && m[2].trim() === "") {
+ out.push({ lang: open.lang, code: body.join("\n") });
+ open = null;
+ continue;
+ }
+ body.push(line);
+ }
+ // Markdown leaves an unterminated fence open to the end of the document, and so does a
+ // thread that was still streaming when it was saved.
+ if (open !== null) out.push({ lang: open.lang, code: body.join("\n") });
+ }
+ return out;
+};
+
+const ALIAS = {
+ py: "python", js: "javascript", ts: "typescript", rs: "rust", rb: "ruby",
+ sh: "shellscript", bash: "shellscript", zsh: "shellscript", shell: "shellscript",
+ yml: "yaml", golang: "go", "c++": "cpp", "c#": "csharp", kt: "kotlin",
+};
+
+const argv = process.argv.slice(2);
+const themeAt = argv.indexOf("--theme");
+const mode = themeAt === -1 ? "dual" : argv[themeAt + 1];
+const paths = argv.filter((a, i) => i !== themeAt && (themeAt === -1 || i !== themeAt + 1));
+if (paths.length === 0) {
+ console.error("usage: coal-span-census.mjs [--theme dual|dark|light] <markdown> [...]");
+ process.exit(2);
+}
+
+const fences = readFences(paths);
+if (fences.length === 0) {
+ console.error("no fenced code found in those files");
+ process.exit(1);
+}
+
+const engine = createJavaScriptRegexEngine({ forgiving: true });
+const themeArg =
+ mode === "dark" ? { theme: "unsloth-dark" }
+ : mode === "light" ? { theme: "unsloth-light" }
+ : { themes: { light: "unsloth-light", dark: "unsloth-dark" } };
+
+let before = 0;
+let after = 0;
+let lines = 0;
+let chars = 0;
+const perLang = {};
+const highlighters = new Map();
+
+for (const f of fences) {
+ const lang = ALIAS[f.lang.toLowerCase()] ?? f.lang.toLowerCase();
+ let hl = highlighters.get(lang);
+ if (!hl) {
+ try {
+ hl = await createHighlighter({ themes: [light, dark], langs: [lang], engine });
+ } catch {
+ hl = await createHighlighter({ themes: [light, dark], langs: ["text"], engine });
+ }
+ highlighters.set(lang, hl);
+ }
+ const use = hl.getLoadedLanguages().includes(lang) ? lang : "text";
+ const res = hl.codeToTokens(f.code, { lang: use, ...themeArg });
+ let b = 0;
+ let a = 0;
+ for (const line of res.tokens) {
+ b += line.length;
+ const c = coalesceLine(line);
+ a += c.length;
+ // The whole point is that the text is untouched. If it ever is not, the census is meaningless
+ // and the run should stop rather than print a number.
+ if (line.map((t) => t.content).join("") !== c.map((t) => t.content).join("")) {
+ throw new Error(`TEXT CHANGED in a ${use} fence`);
+ }
+ }
+ lines += res.tokens.length;
+ chars += f.code.length;
+ before += b;
+ after += a;
+ const k = perLang[use] ?? (perLang[use] = { fences: 0, before: 0, after: 0 });
+ k.fences += 1;
+ k.before += b;
+ k.after += a;
+}
+
+const pct = (from, to) => `${(100 * (1 - to / from)).toFixed(1)}%`;
+console.log(`theme mode ${mode}`);
+console.log(`fences ${fences.length}`);
+console.log(`code characters ${chars}`);
+console.log(`fence lines ${lines} (one <span> each, unchanged by the merge)`);
+console.log(`token spans ${before} -> ${after} ${pct(before, after)} fewer`);
+console.log(`total spans ${before + lines} -> ${after + lines} ${pct(before + lines, after + lines)} fewer`);
+console.log("\nper language:");
+for (const [k, v] of Object.entries(perLang).sort((x, y) => y[1].before - x[1].before)) {
+ console.log(
+ ` ${k.padEnd(14)} fences ${String(v.fences).padStart(3)} ` +
+ `${String(v.before).padStart(7)} -> ${String(v.after).padStart(7)} ${pct(v.before, v.after)}`,
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
new file mode 100644
index 00000000000..5861c7935d8
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
@@ -0,0 +1,435 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"use client";
+
+import {
+ memo,
+ type RefObject,
+ useEffect,
+ useLayoutEffect,
+ useState,
+} from "react";
+
+/*
+ * MONOTONIC fence highlighting: a fence is rendered as a plain shell until the
+ * first time it comes near the viewport, and from that moment it is highlighted
+ * for the rest of its mount. There is no reverse edge.
+ *
+ * WHY THE DIRECTION MATTERS. The previous attempt at this gated on viewport
+ * entry AND on viewport EXIT, so scrolling away from a fence, or collapsing the
+ * pane holding it, tore the highlighted subtree down and scrolling back built
+ * it again. That makes the gate BIDIRECTIONAL: a user gesture that ought to
+ * cost nothing instead schedules a full re-tokenize and a re-mount of every
+ * span in the block. It was predicted to save 55% and measured slower.
+ *
+ * Here the only transition is cheap -> expensive, taken at most once per mount.
+ * Scrolling away costs nothing, because there is nothing to undo; the observer
+ * has already been disconnected and the component has no effect left running.
+ * The worst case is therefore exactly today's cost (every fence looked at), and
+ * every fence the reader never reaches is saved outright.
+ *
+ * WHAT THE SHELL IS. The same text, in the same elements streamdown's own
+ * unhighlighted fallback would use, carrying the same `data-streamdown`
+ * attributes so every rule in index.css that sizes a code block applies to it
+ * unchanged. The text is present in the DOM and selectable, which is the
+ * property `content-visibility: auto` does not have: skipped content has to be
+ * rendered before it can be selected, and that was measured at +28.8% on
+ * `select_all_copy.select_all_ms`. Selection, clipboard and native find-in-page
+ * see the same characters here whether the fence has upgraded or not.
+ *
+ * A STREAMING fence never defers. The block being written is by definition the
+ * one the reader is looking at, and deferring it would change what streaming
+ * renders rather than what a settled thread costs.
+ */
+
+// How far outside the viewport a fence counts as "reached". One viewport of
+// slack in each direction, so the upgrade has a frame or two to land before the
+// block is actually on screen and the reader never sees the swap.
+const REACH_MARGIN = "100% 0px";
+
+/*
+ * Three states, not two.
+ *
+ * "off" ship default. Every fence is highlighted at mount, as today.
+ * "defer" the change: an unreached fence is a plain shell and is never tokenized.
+ * "tokenize" MEASUREMENT ONLY. An unreached fence is the same plain shell, but the
+ * highlighter is still driven over its source and the result thrown away.
+ *
+ * `tokenize` exists to answer one question and is not a shipping mode. `defer` removes two
+ * things at once: the spans from the document, and the tokenizer work that produces them. An
+ * improvement seen under `defer` alone cannot say which of the two paid for it. `tokenize`
+ * holds the DOM at `defer`'s size and puts only the tokenizer work back, so the gap between
+ * `tokenize` and `defer` is the tokenizer's contribution and the gap between `off` and
+ * `tokenize` is the document's.
+ */
+export type FenceMode = "off" | "defer" | "tokenize";
+
+export const fenceMode = (): FenceMode => {
+ const runtime = (globalThis as Record<string, unknown>)
+ .__UNSLOTH_DEFER_FENCE_HIGHLIGHT__;
+ const raw =
+ typeof runtime === "string"
+ ? runtime
+ : runtime === true
+ ? "defer"
+ : runtime === false
+ ? "off"
+ : readBuildFlag();
+ return raw === "1" || raw === "defer"
+ ? "defer"
+ : raw === "tokenize"
+ ? "tokenize"
+ : "off";
+};
+
+const readBuildFlag = (): string => {
+ try {
+ return import.meta.env.VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT ?? "";
+ } catch {
+ return "";
+ }
+};
+
+// Streamdown trims trailing newlines off a fence body before rendering it, so
+// the shell has to as well or the two differ by a blank line of height.
+export const trimTrailingNewlines = (text: string): string => {
+ let end = text.length;
+ while (end > 0 && text[end - 1] === "\n") end -= 1;
+ return text.slice(0, end);
+};
+
+/*
+ * AN EMPTY FENCE IS ONE LINE TALL, not nothing.
+ *
+ * Streamdown renders a code block as one span per token line, and it special-cases the empty line:
+ *
+ * children: c.length === 0 || (c.length === 1 && c[0].content === "") ? `\n` : c.map(...)
+ *
+ * It also trims trailing newlines off the source first, exactly as `trimTrailingNewlines` does
+ * here, so a fence whose body is empty or is nothing but newlines tokenizes to a single empty line
+ * and renders as one newline: one line box of height. A `<code>` holding an empty text node has no
+ * line box at all, so without this the shell is one line shorter than the block it stands in for
+ * and the fence grows by a line when it upgrades, moving everything below it.
+ */
+const shellBody = (source: string): string => {
+ const trimmed = trimTrailingNewlines(source);
+ return trimmed === "" ? "\n" : trimmed;
+};
+
+function FenceShell({
+ language,
+ source,
+}: {
+ language: string | null;
+ source: string;
+}) {
+ return (
+ <div
+ className="my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2"
+ data-language={language ?? undefined}
+ data-streamdown="code-block"
+ data-unsloth-fence-deferred="true"
+ >
+ <div
+ className="flex h-8 items-center text-muted-foreground text-xs"
+ data-language={language ?? undefined}
+ data-streamdown="code-block-header"
+ >
+ <span className="ml-1 font-mono lowercase">{language}</span>
+ </div>
+ <div
+ className="overflow-x-auto rounded-md border border-border bg-background p-4 text-sm"
+ data-language={language ?? undefined}
+ data-streamdown="code-block-body"
+ >
+ <pre>
+ <code>{shellBody(source)}</code>
+ </pre>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Has this fence been reached yet? Latches true and never returns false again.
+ *
+ * Takes a ref to an element the CALLER already renders rather than mounting a
+ * wrapper of its own. An extra div here would sit between a list item and its
+ * code block and break `[data-streamdown="list-item"] > [data-streamdown=
+ * "code-block"]`, and would push the block one level deeper than the
+ * `:last-child` margin chain in index.css walks -- a layout change smuggled in
+ * by a performance change, which is the one thing an A/B must not carry.
+ */
+// No IntersectionObserver, no gate. Read once at module scope so the decision
+// is part of the rendered value rather than a state write from inside an
+// effect, which would cost a cascading render on every fence in the thread.
+const CAN_OBSERVE =
+ typeof IntersectionObserver !== "undefined" &&
+ typeof globalThis !== "undefined";
+
+/*
+ * PRINT: NOT HANDLED, and measured rather than assumed.
+ *
+ * A print renders the whole document, so every deferred fence is on the page whether or not the
+ * reader reached it. Colour is the only thing deferral costs there: the text is a live text node,
+ * so it prints complete, in order, correctly laid out and in the right font.
+ *
+ * There WAS a `beforeprint` path here that latched every mounted fence, warmed each language's
+ * grammar at idle and flushed twice. It has been removed because it did not work, and the
+ * measurement is the reason. Synchronous dispatch and read in one task, 100K rung, cold open:
+ *
+ * delay after open flag off: blocks on the raw fallback flag on
+ * 1.5 s 56 of 56 56 of 56
+ * 3 s and beyond 0 53 of 56
+ *
+ * The shipped build has a real window of about three seconds and is fully highlighted after it.
+ * With the flag on, 53 of 56 blocks stayed on streamdown's raw fallback at every delay out to
+ * twenty seconds. Neither a warm grammar nor a second `flushSync` makes a lazily imported,
+ * effect-driven highlighter produce tokens inside the synchronous print task, because
+ * `beforeprint` returns and the browser snapshots before any of that can land.
+ *
+ * So the honest position is that this is a stated limitation, not a solved problem: with the flag
+ * on, printing a long thread prints unreached fences without syntax colour. Keeping the machinery
+ * would have meant maintaining a module-global claim, two bookkeeping sets and an idle scheduler
+ * for a benefit that was measured at zero.
+ */
+
+/*
+ * THE NEAREST SCROLLING ANCESTOR, found rather than named.
+ *
+ * This used to match two known selectors, `[data-slot='thread-viewport']` and
+ * `.aui-thread-viewport`, and `closest()` walks straight past anything that matches neither. The
+ * one that matters is the reasoning pane: while a reply streams, `reasoning.tsx` gives its trace
+ * `overflow-y-auto` and `max-h-64` and pins it to the bottom, so the reader is looking at an
+ * arbitrarily long trace through a 256 px window nested inside the thread scroller.
+ *
+ * What this is NOT. It is not a correctness fix. Intermediate scrollers clip, so intersection was
+ * always computed correctly and fences inside that pane were always deferred properly; measured in
+ * Chromium with ten fences in a 256 px inner scroller inside a 400 px outer one, 3 of 10 reported
+ * intersecting either way. It is a LOOKAHEAD fix. `rootMargin` expands the ROOT's rectangle, so
+ * rooting at the thread viewport expanded a rectangle the reader is not looking through and the
+ * one-viewport warning was worth nothing inside the pane: the "100% 0px" column and the no-margin
+ * column were identical at 3 of 10, while rooting at the inner scroller gave 5 of 10. The
+ * user-visible consequence of getting it wrong is narrow and real: a fence scrolling into the
+ * 256 px window gets no pre-warm and shows the plain shell for the frames the upgrade takes.
+ *
+ * `null` is deliberately still possible and is deliberately NOT the default: a fence with no
+ * scrolling ancestor really is clipped by the document viewport, but assuming that when a scroller
+ * exists is the bug the review caught.
+ */
+const isScrollable = (el: HTMLElement): boolean => {
+ const overflowY = getComputedStyle(el).overflowY;
+ return (
+ (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay")
+ && el.scrollHeight > el.clientHeight
+ );
+};
+
+const scrollerOf = (node: HTMLElement): HTMLElement | null => {
+ for (let el = node.parentElement; el !== null; el = el.parentElement) {
+ if (isScrollable(el)) return el;
+ }
+ return null;
+};
+
+/*
+ * THE OUTERMOST ONE TOO, and why the nearest is not enough on its own.
+ *
+ * An explicit root is clipped by the ancestors BETWEEN the target and the root, and by NOTHING
+ * above it. Rooting at the reasoning pane therefore asks "is this fence inside the pane's own
+ * window" and never "is the pane itself anywhere near the reader". Two ways that goes wrong, and
+ * the second one undoes the whole change on the pane most likely to hold the spans:
+ *
+ * 1. A pane scrolled far out of the thread still reports the two or three fences inside its
+ * 256 px window as intersecting, so they upgrade where nobody can see them.
+ * 2. `reasoning.tsx` drops `max-h-64` when the stream ends but KEEPS `overflow-y-auto`, so the
+ * pane stops being scrollable and its box becomes the whole trace. An observer still rooted
+ * at it from the streaming frames then reports EVERY fence in that trace as intersecting at
+ * once.
+ *
+ * Rooting at the outermost scroller instead would fix both and cost the lookahead that rooting at
+ * the nearest one bought: measured in Chromium with ten fences in a 256 px inner scroller inside a
+ * 400 px outer one, the inner root reports 5 of 10 with a one-window margin against 3 of 10 for
+ * the outer root, and the difference is exactly the pre-warm that keeps a fence from showing its
+ * plain shell as it scrolls into the pane.
+ *
+ * So when the two differ there are two gates, watching two different elements, and the latch needs
+ * both: the FENCE against the nearest scroller answers "the reader is about to reach it inside the
+ * pane", and the PANE against the outermost scroller answers "the pane is somewhere the reader can
+ * see". Watching the fence through the outer root instead would clip it at the pane on the way and
+ * go false exactly where the inner lookahead was doing its work -- 2 of 10 against 4, measured with
+ * the pane fully in view. When the two scrollers are the same element, which is every fence outside
+ * a nested scroller, there is exactly one observer and this costs nothing.
+ *
+ * THE CONJUNCTION IS NOT ENOUGH ON ITS OWN, which took a measurement to see. A stale inner root
+ * is too permissive, and the outer gate only covers that while the pane is out of view. Scroll the
+ * expanded pane so much as partly on screen and the outer gate is true, so the stale inner root
+ * decides alone and reports the WHOLE trace: 10 of 10 in both engines, on a 4,080 px trace against
+ * a 900 px viewport where the right answer is about 3. So the inner root is re-resolved when the
+ * pane stops scrolling, which collapses the fence back to the single-gate case where the outermost
+ * scroller is the root and nothing can be stale.
+ *
+ * Watched with a ResizeObserver on the pane rather than by re-resolving on every frame, and only
+ * for fences that actually have a nested scroller. The callback reads one `overflow-y` on one
+ * element, so a streaming pane resizing every frame costs one computed-style read per fence per
+ * frame and rebinds nothing until the cap actually comes off.
+ *
+ * Still one-way. Nothing here can clear a latch; the extra gate and the rebind can only withhold
+ * one.
+ */
+const outermostScrollerOf = (node: HTMLElement): HTMLElement | null => {
+ let found: HTMLElement | null = null;
+ for (let el = node.parentElement; el !== null; el = el.parentElement) {
+ if (isScrollable(el)) found = el;
+ }
+ return found;
+};
+
+/** Is `node` inside `scroller`'s box grown by one of its own heights, the observer's margin? */
+const inBand = (node: HTMLElement, scroller: HTMLElement | null): boolean => {
+ const bounds = scroller?.getBoundingClientRect();
+ const top = bounds ? bounds.top : 0;
+ const height = bounds ? bounds.height : window.innerHeight;
+ const rect = node.getBoundingClientRect();
+ return rect.bottom > top - height && rect.top < top + height * 2;
+};
+
+/**
+ * @param enabled false on the shipped default, where this hook must cost nothing at all: no
+ * state is ever written, no observer is built and no layout is read.
+ * @param streaming the fence is still being written. It is highlighted while it streams AND it
+ * latches, so that finishing cannot take the highlighting back.
+ */
+export function useFenceReached(
+ host: RefObject<HTMLElement | null>,
+ enabled: boolean,
+ streaming: boolean,
+): boolean {
+ const [latched, setLatched] = useState(false);
+ // Bumped when the resolved scrolling ancestor stops being one, which rebuilds the gates below
+ // against the element that clips this fence now. Never read for anything else.
+ const [generation, setGeneration] = useState(0);
+ const reached = !enabled || !CAN_OBSERVE || streaming || latched;
+
+ /*
+ * A COMPLETING STREAM MUST NOT DOWNGRADE.
+ *
+ * `streaming` goes true -> FALSE when streamdown recognises the closing delimiter. Deriving
+ * `reached` from it alone therefore takes a fence that was highlighted all through its stream
+ * and hands it back the plain shell the moment it finishes: highlighted -> plain, on a block the
+ * reader is watching, which is precisely the reverse edge this design exists to remove. The
+ * fence was reached; that has to be recorded, not recomputed.
+ *
+ * In a layout effect so the downgrade is never painted even for one frame.
+ */
+ useLayoutEffect(() => {
+ if (!enabled || latched || !streaming) return;
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setLatched(true);
+ }, [enabled, latched, streaming]);
+
+ /*
+ * THE FIRST FRAME, which the observer cannot cover.
+ *
+ * An IntersectionObserver delivers its first record asynchronously, one or more frames after
+ * `observe()`. For a fence that is ALREADY on screen when the thread mounts, those frames are
+ * plain code inside the viewport: measured at 2 to 3 frames, 30 to 190 ms. That is a visible
+ * difference, not an off-screen one, so it is closed here rather than argued about.
+ *
+ * `useLayoutEffect` runs after mutation and BEFORE paint, so a fence that is on screen latches
+ * and re-renders within the same frame and the plain shell is never painted. One
+ * `getBoundingClientRect` per unreached fence, all of them inside a single commit with no DOM
+ * mutation in between, so the layout is forced once for the whole thread rather than once per
+ * fence.
+ *
+ * RE-RUN ON A REBIND. `generation` is a dependency because the ResizeObserver below bumps it
+ * when the reasoning pane stops scrolling, and expanding that pane can bring a fence inside the
+ * outer viewport for the first time. Without it the rebind's own render leaves the plain shell
+ * in place, and the replacement observer is built in a passive effect and delivers
+ * asynchronously, so the shell is PAINTED. That is an on-screen difference, which is the one
+ * kind this change is not allowed to have.
+ *
+ * Still one-way: this can only ever latch true.
+ */
+ useLayoutEffect(() => {
+ if (reached) return;
+ const node = host.current;
+ if (!node) return;
+ // The same two questions the observers below ask, of the same two elements: is the FENCE in
+ // the window the reader is looking through, and is that WINDOW itself on screen.
+ const near = scrollerOf(node);
+ const outer = outermostScrollerOf(node);
+ if (inBand(node, near) && (near === outer || inBand(near as HTMLElement, outer))) {
+ // The cascading render this warns about is the POINT: it is what keeps the plain shell off
+ // the screen. It happens at most once per fence, only for the one or two fences that are
+ // already on screen at mount, and the alternative is the 2 to 3 painted frames of
+ // unhighlighted code this replaced.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setLatched(true);
+ }
+ }, [reached, host, generation]);
+
+ // The one-way edge. Once `reached` is true this effect re-runs, takes the
+ // early return, and never observes anything again, so a fence that has been
+ // read carries no residual per-scroll cost at all.
+ useEffect(() => {
+ if (reached) return;
+ const node = host.current;
+ if (!node) return;
+ // ROOTED AT THE THREAD'S SCROLLER, not at the document.
+ //
+ // The chat scrolls inside a nested overflow container. With `root` unset the root is the
+ // document viewport, and `rootMargin` expands THAT rectangle -- while the intersection is
+ // still clipped by the scroller's own edges, which no margin can widen. The lookahead would
+ // then be worth nothing: a fence would report intersecting only once it was already inside
+ // the visible band, and the reader would get the plain shell for the frames it takes the
+ // observer to deliver and the upgrade to render. Rooting at the scroller is what makes the
+ // margin mean one viewport of warning.
+ //
+ // See `outermostScrollerOf`: when a nested scroller is in the way, the outermost one is
+ // observed as well and the latch needs both. One observer, not two, whenever they agree.
+ const near = scrollerOf(node);
+ const outer = outermostScrollerOf(node);
+ // WHAT EACH GATE WATCHES, which is not the same element.
+ //
+ // Observing the FENCE against the outer root clips it at the pane on the way, so the outer
+ // gate goes false exactly where the inner lookahead was supposed to be doing its work: 2 of 10
+ // against the inner root's 4, measured, with the pane fully in view. Observing the PANE
+ // against the outer root asks the question the outer gate is for -- is the pane anywhere the
+ // reader can see -- and the inner gate keeps its lookahead untouched at 4 of 10.
+ const gates: [Element, Element | null][] = near === outer
+ ? [[node, near]]
+ : [[node, near], [near as HTMLElement, outer]];
+ const seen = gates.map(() => false);
+ const observers = gates.map(([, root], i) => new IntersectionObserver(
+ (entries) => {
+ seen[i] = entries.some((entry) => entry.isIntersecting);
+ if (!seen.every(Boolean)) return;
+ for (const each of observers) each.disconnect();
+ setLatched(true);
+ },
+ { root, rootMargin: REACH_MARGIN },
+ ));
+ gates.forEach(([target], i) => observers[i].observe(target));
+
+ // `reasoning.tsx` drops `max-h-64` when a stream ends and keeps `overflow-y-auto`, so the pane
+ // stops being a scroller and its box becomes the whole trace. Watch for that and rebuild.
+ let resize: ResizeObserver | undefined;
+ if (near !== null && near !== outer && typeof ResizeObserver !== "undefined") {
+ resize = new ResizeObserver(() => {
+ if (!isScrollable(near)) setGeneration((n) => n + 1);
+ });
+ resize.observe(near);
+ }
+
+ return () => {
+ for (const observer of observers) observer.disconnect();
+ resize?.disconnect();
+ };
+ }, [reached, host, generation]);
+
+ return reached;
+}
+
+export const DeferredFenceShell = memo(FenceShell);
diff --git a/studio/frontend/src/components/assistant-ui/code-plugin.ts b/studio/frontend/src/components/assistant-ui/code-plugin.ts
index 18206c30ee4..441a229386f 100644
--- a/studio/frontend/src/components/assistant-ui/code-plugin.ts
+++ b/studio/frontend/src/components/assistant-ui/code-plugin.ts
@@ -148,6 +148,33 @@ const shiftLine = (line: TokenLine, offset: number): TokenLine =>
? line
: line.map((token) => ({ ...token, offset: token.offset + offset }));
+// ADJACENT-TOKEN COALESCING: TRIED, MEASURED AT ZERO, REMOVED.
+//
+// The renderer emits one <span> per themed token, so a fence's span census is
+// its token census, and Shiki splits on GRAMMAR boundaries rather than on
+// rendered appearance. Merging runs of adjacent tokens whose rendered style is
+// byte-identical looked like a pure reduction with no gating at all: no
+// viewport state machine, nothing a reader could do to push a fence back into a
+// more expensive shape.
+//
+// It buys exactly nothing. Running the whole studiobench corpus, 728 fences and
+// 1,335,897 code characters, through this component's own Shiki configuration:
+//
+// dual tokens 537013 -> merged 537013 0.0% fewer
+// darkonly tokens 535981 -> merged 535981 0.0% fewer
+//
+// and the 100K rung's 99 assembled fences, 180,902 characters, 72550 -> 72550
+// dual, 72408 -> 72408 dark only, 62098 -> 62098 light only. Not one adjacent
+// pair in half a million shares a rendered style, in any theme mode. Shiki
+// already emits maximally coalesced tokens. No timing was run on it, because a
+// mechanism that removes no spans cannot make anything faster.
+//
+// The implementation is not kept. Carrying a runtime-flippable flag through the
+// fence cache for a measured-zero benefit only adds a way for a cached result
+// to disagree with the flag that produced it. Run
+// `node scripts/coal-span-census.mjs <markdown>` from studio/frontend to check
+// the census on any thread rather than taking these numbers on trust.
+
// Markdown reports a closing fence as body until it recognizes it, so that
// line is all a fence can lose: up to three spaces, one run of backticks or
// tildes, then spaces. It also starts a line, so the body it leaves behind ends
@@ -314,6 +341,9 @@ export function createCodePlugin(
const completed = tokenizeFrom(
code.slice(fence.committedLength, completedEnd),
);
+ // Coalesced ONCE, here, as the line is committed. A committed line is
+ // never re-tokenized, so this is paid once per line for the life of the
+ // fence and every later render of it reads the reduced array.
for (const line of completed.tokens) {
fence.lines.push(shiftLine(line, fence.committedLength));
}
@@ -327,7 +357,7 @@ export function createCodePlugin(
const liveResult = tokenizeFrom(live);
fence.meta = stripTokens(liveResult);
fence.liveTokens = shiftLine(
- liveResult.tokens[0] ?? [],
+ liveResult.tokens[0] ?? ([] as unknown as TokenLine),
fence.committedLength,
);
fence.lastTokenizedAt = monotonicNow();
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 9a6618c8ae1..ad2859e0fd3 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -40,6 +40,12 @@ import {
Streamdown,
type StreamdownProps,
} from "streamdown";
+import {
+ DeferredFenceShell,
+ fenceMode,
+ trimTrailingNewlines,
+ useFenceReached,
+} from "./code-fence-defer";
import { createCodePlugin } from "./code-plugin";
import "katex/dist/katex.min.css";
import { AudioPlayer } from "./audio-player";
@@ -394,14 +400,12 @@ function StreamdownBlockContent(props: BlockProps) {
return (
<>
- <div className="relative isolate">
- <Block {...blockProps} />
- <CodeBlockActions
- disabled={props.isIncomplete}
- language={codeFence.language}
- source={codeFence.source}
- />
- </div>
+ <FenceBlock
+ blockProps={blockProps}
+ isIncomplete={props.isIncomplete}
+ language={codeFence.language}
+ source={codeFence.source}
+ />
{svgSource && <SvgPreview source={svgSource} />}
</>
);
@@ -409,6 +413,89 @@ function StreamdownBlockContent(props: BlockProps) {
return <Block {...blockProps} />;
}
+
+/*
+ * The fence branch, extracted so the reach latch can be a hook.
+ *
+ * With the flag off this renders exactly what the branch rendered before: the
+ * same `relative isolate` wrapper, the same `<Block>`, the same action bar. The
+ * wrapper is reused as the intersection target rather than a new one being
+ * introduced, so the DOM the off arm produces is byte-for-byte what main
+ * produces and the on arm differs only in what is INSIDE the wrapper.
+ */
+function FenceBlock({
+ blockProps,
+ isIncomplete,
+ language,
+ source,
+}: {
+ blockProps: BlockProps;
+ isIncomplete: boolean | undefined;
+ language: string | null;
+ source: string;
+}) {
+ const host = useRef<HTMLDivElement | null>(null);
+ const mode = fenceMode();
+ // A streaming fence is the one the reader is watching, so it never defers, and the hook latches
+ // it so that finishing the stream cannot hand it back the plain shell.
+ const reached = useFenceReached(host, mode !== "off", Boolean(isIncomplete));
+
+ /*
+ * WHICH FENCES THIS COVERS, and which it does not.
+ *
+ * `CODE_FENCE_RE` accepts exactly three backticks, unindented. CommonMark also allows tildes,
+ * four or more backticks (which is how a model writes a fence whose body contains one), and up
+ * to three spaces of indent. Those forms never reach here, so they render exactly as they do
+ * today and get no deferral: unrealised benefit, not a wrong result.
+ *
+ * Left alone deliberately rather than overlooked. `getCodeFence` is also what decides whether a
+ * block is an SVG or a full HTML document to be shown as an artifact, and a fence that does not
+ * match it renders a bare `<Block>` with no `relative isolate` wrapper and no copy button.
+ * Widening the regex would therefore add an artifact path and a copy overlay to blocks that do
+ * not have them today, which is a rendering change, and a performance PR is the wrong place to
+ * smuggle one in.
+ *
+ * It also does not move any number here: over the frozen corpus, 2,467,069 characters, all
+ * 1,456 fence delimiters are unindented triple backticks. Not one tilde, not one four-backtick
+ * fence, not one indented one.
+ */
+ // `getCodeFence` hands back the WHOLE info string, so a fence opened with metadata such as
+ // ```python startLine=10 arrives here as "python startLine=10". Markdown treats everything
+ // after the first word as metadata and Streamdown highlights it as `python`, so passing the
+ // raw string on would label the shell with the metadata attached and, in the measurement arm,
+ // tokenize an unknown language as plain text -- which is exactly the grammar work the arm
+ // exists to put back.
+ const languageToken = language?.trim().split(/\s+/)[0] || null;
+
+ // MEASUREMENT ARM ONLY. See `FenceMode`: this puts the tokenizer work back while leaving the
+ // document at the deferred size, so the two costs can be told apart. `code.highlight` caches
+ // on the source string, so the work happens exactly once and the discarded result is the same
+ // object the real path would have used.
+ const pretokenize = mode === "tokenize" && !reached;
+ useEffect(() => {
+ if (!pretokenize) return;
+ code.highlight({
+ code: trimTrailingNewlines(source),
+ language: (languageToken ?? "text") as never,
+ themes: STREAMDOWN_SHIKI_THEME,
+ }, () => {});
+ }, [pretokenize, source, languageToken]);
+
+ return (
+ <div className="relative isolate" ref={host}>
+ {reached ? (
+ <Block {...blockProps} />
+ ) : (
+ <DeferredFenceShell language={languageToken} source={source} />
+ )}
+ <CodeBlockActions
+ disabled={Boolean(isIncomplete)}
+ language={language}
+ source={source}
+ />
+ </div>
+ );
+}
const StreamdownBlock = memo(StreamdownBlockContent);
const AUDIO_PLAYER_RE = /<audio-player\s+src="([^"]+)"\s*\/>/;
diff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.ts
new file mode 100644
index 00000000000..85ef2272936
--- /dev/null
+++ b/studio/frontend/tests/code-fence-defer.test.ts
@@ -0,0 +1,409 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { existsSync, readFileSync } from "node:fs";
+import test from "node:test";
+
+/**
+ * The one property that makes this change different from the viewport gate that came before it,
+ * pinned as source facts.
+ *
+ * The earlier attempt gated a fence on viewport entry AND on viewport exit. Because the gate ran
+ * both ways, collapsing a reasoning pane pushed fences out of view and generated re-highlight
+ * work instead of saving it: predicted -55% on `reasoning_toggle.close_ms`, measured +12.7%
+ * slower, and closed on that number.
+ *
+ * Everything below exists so that reintroducing a downgrade edge fails a test rather than a
+ * benchmark two days later. These are deliberately source-level assertions: the module is a React
+ * hook over IntersectionObserver, so a behavioural test would need a DOM, and the invariant worth
+ * protecting is structural anyway -- "no code path sets this back to false".
+ */
+
+const SOURCE = readFileSync(
+ new URL("../src/components/assistant-ui/code-fence-defer.tsx", import.meta.url),
+ "utf8",
+);
+
+const MARKDOWN_TEXT = readFileSync(
+ new URL("../src/components/assistant-ui/markdown-text.tsx", import.meta.url),
+ "utf8",
+);
+
+test("the latch is only ever set to true", () => {
+ const writes = SOURCE.match(/setLatched\([^)]*\)/g) ?? [];
+ assert.ok(writes.length > 0, "expected at least one write to the latch");
+ for (const write of writes) {
+ assert.equal(
+ write,
+ "setLatched(true)",
+ `the latch must never be cleared; found ${write}. A downgrade edge is what made the ` +
+ "previous viewport gate measure slower than doing nothing.",
+ );
+ }
+});
+
+
+
+
+
+test("a completing stream cannot downgrade a fence that was highlighted while it streamed", () => {
+ // `streaming` goes true -> FALSE at the closing delimiter. Deriving `reached` from it alone
+ // hands a finished fence back the plain shell, which is the reverse edge in miniature.
+ assert.ok(
+ /if\s*\(!enabled\s*\|\|\s*latched\s*\|\|\s*!streaming\)\s*return;/.test(SOURCE),
+ "a streaming fence must LATCH, not merely read as reached while the flag is live",
+ );
+ const derived = SOURCE.match(/const reached = [^;]+;/)?.[0] ?? "";
+ assert.ok(
+ derived.includes("latched"),
+ `the derived value must include the latch; found ${derived}`,
+ );
+});
+
+test("the observer is rooted at the nearest SCROLLING ancestor, found not named", () => {
+ // Two failures this pins, and they are different from each other.
+ //
+ // `root: null` is the document viewport, so `rootMargin` expands a rectangle that is not the
+ // one clipping and the lookahead is worth nothing. That was the review item.
+ //
+ // Matching two known selectors walks past the reasoning pane, which while streaming is an
+ // `overflow-y-auto` `max-h-64` window holding an arbitrarily long trace. Intersection was still
+ // correct there, because intermediate scrollers clip, but the one-viewport lookahead was not:
+ // measured 3 of 10 fences intersecting with and without the margin when rooted at the thread
+ // viewport, against 5 of 10 rooted at the 256px pane.
+ assert.ok(
+ /const near = scrollerOf\(node\);/.test(SOURCE) && /\{ root, rootMargin: REACH_MARGIN \}/.test(SOURCE),
+ "the observer root must be the fence's own scrolling ancestor",
+ );
+ assert.ok(
+ !/closest<HTMLElement>\("\[data-slot='thread-viewport'\]"\)/.test(SOURCE),
+ "a named-selector lookup walks past the reasoning pane's scroller, which matches neither name",
+ );
+ const fn = SOURCE.slice(SOURCE.indexOf("const scrollerOf"), SOURCE.indexOf("const scrollerOf") + 320);
+ assert.ok(
+ fn.includes("el.parentElement") && fn.includes("isScrollable(el)"),
+ "it must WALK to the nearest scrollable ancestor rather than matching known names",
+ );
+ const pred = SOURCE.slice(SOURCE.indexOf("const isScrollable"), SOURCE.indexOf("const scrollerOf"));
+ for (const token of ['"auto"', '"scroll"', '"overlay"', "scrollHeight > el.clientHeight"]) {
+ assert.ok(pred.includes(token), `the scrollable test must consider ${token}`);
+ }
+});
+
+test("the pre-paint gate re-runs when the roots are rebound", () => {
+ // The ResizeObserver bumps `generation` when the reasoning pane stops scrolling, and the
+ // passive effect rebuilds its observers off that. The PRE-PAINT effect has to re-run on the
+ // same bump, or a fence that the expanding pane has just brought inside the outer viewport
+ // stays on its plain shell through the commit the rebind causes, and the replacement observer
+ // delivers asynchronously, so the shell is painted.
+ //
+ // That is an ON SCREEN difference, which is the one kind this change is not allowed to have.
+ const prepaint = SOURCE.slice(
+ SOURCE.indexOf("THE FIRST FRAME, which the observer cannot cover"),
+ SOURCE.indexOf("// The one-way edge."),
+ );
+ assert.ok(prepaint.length > 200, "the pre-paint effect must still be findable by its comment");
+ assert.ok(
+ /\}, \[reached, host, generation\]\);/.test(prepaint),
+ "the pre-paint gate must depend on the rebind generation, not just on reached and host",
+ );
+ // And it has to be the gate that actually latches, not some other effect in the slice.
+ assert.ok(
+ prepaint.includes("setLatched(true)") && prepaint.includes("useLayoutEffect"),
+ "the effect this pins must be the pre-paint latch itself",
+ );
+});
+
+test("with the flag off the hook writes no state, builds no observer and reads no layout", () => {
+ const hook = SOURCE.slice(SOURCE.indexOf("export function useFenceReached"));
+ for (const guard of ["if (!enabled || latched || !streaming) return;", "if (reached) return;"]) {
+ assert.ok(hook.includes(guard), `expected the early return ${guard}`);
+ }
+ assert.ok(
+ /const reached = !enabled \|\|/.test(hook),
+ "the disabled path must short-circuit to reached, so every effect below takes its early return",
+ );
+});
+
+test("the observer disconnects itself on the upgrade", () => {
+ const callback = SOURCE.slice(
+ SOURCE.indexOf("new IntersectionObserver"),
+ SOURCE.indexOf("for (const observer of observers) observer.observe(node)"),
+ );
+ assert.ok(
+ callback.indexOf("each.disconnect()") < callback.indexOf("setLatched(true)"),
+ "every observer must disconnect before the state write, so an upgraded fence carries no " +
+ "residual per-scroll cost",
+ );
+});
+
+test("a nested scroller is gated by the outermost one as well", () => {
+ // An explicit root is clipped by the ancestors BETWEEN the target and the root and by nothing
+ // above it, so rooting at the reasoning pane asks only "is this fence inside the pane's window".
+ // Two ways that upgrades fences nobody can see: a pane scrolled out of the thread still reports
+ // the fences inside its 256 px window as intersecting, and `reasoning.tsx` drops `max-h-64` at
+ // the end of a stream while KEEPING `overflow-y-auto`, so the pane stops being scrollable, its
+ // box becomes the whole trace, and an observer still rooted at it reports every fence in that
+ // trace at once.
+ //
+ // The outermost scroller answers the question the inner root cannot, and it cannot go stale the
+ // same way: a pane below it ceasing to scroll does not change which element is outermost.
+ const walk = SOURCE.slice(SOURCE.indexOf("const outermostScrollerOf"));
+ assert.ok(
+ walk.slice(0, 260).includes("found = el") && !walk.slice(0, 260).includes("return el;"),
+ "outermostScrollerOf must keep walking rather than returning the first match",
+ );
+ assert.ok(
+ SOURCE.includes("? [[node, near]]")
+ && SOURCE.includes("[[node, near], [near as HTMLElement, outer]]"),
+ "one gate when the two scrollers agree; otherwise the FENCE against the nearest and the "
+ + "PANE against the outermost",
+ );
+ assert.ok(
+ SOURCE.includes("if (!seen.every(Boolean)) return;"),
+ "the latch must need EVERY gate, not any of them",
+ );
+ assert.ok(
+ /inBand\(node, near\) && \(near === outer \|\| inBand\(near as HTMLElement, outer\)\)/
+ .test(SOURCE),
+ "the pre-paint door must ask the same two questions of the same two elements",
+ );
+ assert.ok(
+ !/\[\[node, near\], \[node, outer\]\]/.test(SOURCE),
+ "watching the FENCE through the outer root clips it at the pane and cancels the lookahead "
+ + "it was rooted at the pane to get: measured 2 of 10 against 4 with the pane in view",
+ );
+
+ // The rebind. The conjunction alone is not enough: scroll an expanded pane partly on screen and
+ // the outer gate is true, so a stale inner root decides alone and reports the whole trace,
+ // measured at 10 of 10 on a 4,080 px trace against a 900 px viewport where the right answer is
+ // about 3, and 4 of 10 once the inner root is re-resolved. Both engines.
+ assert.ok(
+ /resize = new ResizeObserver\(\(\) => \{\s*if \(!isScrollable\(near\)\) setGeneration/
+ .test(SOURCE),
+ "the gates must be rebuilt when the nested scroller stops being one",
+ );
+ assert.ok(
+ /\}, \[reached, host, generation\]\);/.test(SOURCE),
+ "and the rebind has to be a dependency of the effect that builds them",
+ );
+ assert.ok(
+ /if \(near !== null && near !== outer && typeof ResizeObserver !== "undefined"\)/.test(SOURCE),
+ "watched only for fences that actually have a nested scroller, and only one element",
+ );
+ assert.ok(
+ !/setGeneration\(0\)|setLatched\(false\)/.test(SOURCE),
+ "the rebind must stay one-way: it can withhold a latch, never clear one",
+ );
+
+ // The conjunction, run rather than described: a fence inside a pane's window while the pane is
+ // far outside the thread viewport must NOT be reached.
+ const band = (rect: {top: number; bottom: number}, root: {top: number; height: number}) =>
+ rect.bottom > root.top - root.height && rect.top < root.top + root.height * 2;
+ const pane = { top: 4000, height: 256, bottom: 4256 };
+ const viewport = { top: 0, height: 800 };
+ const fence = { top: 4100, bottom: 4200 };
+ assert.equal(band(fence, pane), true, "inside the pane's own window");
+ assert.equal(band(pane, viewport), false, "but the pane is nowhere the reader can see");
+
+ // And the lookahead survives when the pane IS in view: the outer gate asks about the pane, so
+ // it cannot clip the fence a second time.
+ const onScreen = { top: 100, height: 256, bottom: 356 };
+ const ahead = { top: 500, bottom: 620 };
+ assert.equal(band(onScreen, viewport), true, "the pane is on screen");
+ assert.equal(band(ahead, onScreen), true, "so a fence one window below it still pre-warms");
+});
+
+test("the flag defaults off, and off means today's behaviour", () => {
+ assert.ok(
+ SOURCE.includes('return raw === "1" || raw === "defer"'),
+ "the mode is decided from the flag value",
+ );
+ assert.ok(
+ /:\s*"off";/.test(SOURCE),
+ "any value that is not an understood mode must fall through to off",
+ );
+ assert.ok(
+ MARKDOWN_TEXT.includes('useFenceReached(host, mode !== "off", Boolean(isIncomplete))'),
+ "with the flag off every fence must render immediately, exactly as it does today",
+ );
+});
+
+test("a streaming fence never defers", () => {
+ assert.ok(
+ MARKDOWN_TEXT.includes("Boolean(isIncomplete)"),
+ "an incomplete (streaming) fence must be immediate: deferring it would change what " +
+ "streaming renders rather than what a settled thread costs",
+ );
+});
+
+test("the shell carries the same streamdown hooks the real block does", () => {
+ for (const attribute of [
+ 'data-streamdown="code-block"',
+ 'data-streamdown="code-block-header"',
+ 'data-streamdown="code-block-body"',
+ ]) {
+ assert.ok(
+ SOURCE.includes(attribute),
+ `the shell must carry ${attribute} or the stylesheet rules that size a code block do ` +
+ "not apply to it and the two arms lay out differently",
+ );
+ }
+});
+
+test("the shell trims trailing newlines the way streamdown does", () => {
+ const trim = (text: string): string => {
+ let end = text.length;
+ while (end > 0 && text[end - 1] === "\n") end -= 1;
+ return text.slice(0, end);
+ };
+ assert.equal(trim("a\nb\n\n\n"), "a\nb");
+ assert.equal(trim("a\nb"), "a\nb");
+ assert.equal(trim("\n\n"), "");
+ assert.ok(
+ SOURCE.includes("trimTrailingNewlines"),
+ "an untrimmed shell is one blank line taller than the block it stands in for",
+ );
+
+ // ...and an EMPTY one is one line SHORTER, in the other direction. Streamdown special-cases the
+ // empty token line, from its own renderer:
+ //
+ // children: c.length === 0 || (c.length === 1 && c[0].content === "") ? `\n` : c.map(...)
+ //
+ // so a fence whose body is empty, or nothing but newlines, is one line box tall. A <code> with
+ // an empty text node has no line box, so the fence would grow by a line on upgrade and move
+ // everything below it.
+ const body = (source: string): string => (trim(source) === "" ? "\n" : trim(source));
+ assert.equal(body(""), "\n");
+ assert.equal(body("\n\n\n"), "\n");
+ assert.equal(body("x"), "x");
+ assert.ok(
+ /const trimmed = trimTrailingNewlines\(source\);\s*return trimmed === "" \? "\\n" : trimmed;/
+ .test(SOURCE),
+ "the shell must reproduce streamdown's empty line rather than collapse to no line at all",
+ );
+ assert.ok(
+ !/<code>\{trimTrailingNewlines\(source\)\}<\/code>/.test(SOURCE),
+ "the raw trim must not be rendered directly; it loses the empty-line case",
+ );
+});
+
+test("the gate does not mount a wrapper element of its own", () => {
+ assert.ok(
+ !SOURCE.includes("<div ref={host}>"),
+ "an extra div between a list item and its code block breaks the direct-child selector in " +
+ "index.css and pushes the block a level deeper than the :last-child margin chain walks",
+ );
+ assert.ok(
+ MARKDOWN_TEXT.includes('<div className="relative isolate" ref={host}>'),
+ "the intersection target must be the wrapper markdown-text already rendered",
+ );
+});
+
+test("the tokenize arm is measurement only and is not reachable from a boolean flag", () => {
+ assert.ok(
+ SOURCE.includes('raw === "tokenize"'),
+ "the tokenize arm is selected by an explicit string, never by a truthy flag",
+ );
+ assert.ok(
+ MARKDOWN_TEXT.includes('const pretokenize = mode === "tokenize" && !reached'),
+ "pretokenizing must be confined to the tokenize arm",
+ );
+});
+
+test("there is no print machinery left to leak", () => {
+ // A `beforeprint` path that latched every mounted fence, warmed grammars at idle and flushed
+ // twice was removed after it was measured: synchronous dispatch and read in one task, 53 of 56
+ // blocks still printed on streamdown's raw fallback at every delay out to twenty seconds. The
+ // shipped build is fully highlighted after about three seconds. Neither a warm grammar nor a
+ // second flushSync makes an effect-driven, lazily imported highlighter produce tokens inside
+ // the synchronous print task.
+ //
+ // Three review rounds went on leaks inside that machinery. This test exists so it does not come
+ // back without a measurement showing it works.
+ for (const gone of ["flushSync", "printListeners", "claimChunkWarm", "beforeprint"]) {
+ assert.ok(
+ !new RegExp(`(addEventListener|const|let)[^\\n]*${gone}`).test(SOURCE),
+ `${gone} was removed because it did not work; re-adding it needs a measurement first`,
+ );
+ }
+ assert.ok(
+ !/warmedGrammars|pendingGrammars/.test(MARKDOWN_TEXT),
+ "the grammar warm-up was removed with the rest of the print path",
+ );
+});
+
+test("the print limitation is written down where it is decided", () => {
+ assert.ok(
+ SOURCE.includes("PRINT: NOT HANDLED") && SOURCE.includes("53 of 56"),
+ "the measured limitation belongs next to the code that causes it, with its number",
+ );
+});
+
+const CODE_PLUGIN = readFileSync(
+ new URL("../src/components/assistant-ui/code-plugin.ts", import.meta.url),
+ "utf8",
+);
+
+test("the fence language is a language, not the whole info string", () => {
+ // `getCodeFence` captures everything after the backticks, so ```python startLine=10 arrives as
+ // "python startLine=10". Markdown treats everything past the first word as metadata and
+ // Streamdown highlights the block as `python`. Passing the raw string through would label the
+ // deferred shell with the metadata attached, and would hand the measurement arm a language no
+ // grammar matches -- so it would tokenize as plain text and silently stop measuring the
+ // tokenizer work it exists to measure.
+ assert.ok(
+ /const languageToken = language\?\.trim\(\)\.split\(\/\\s\+\/\)\[0\] \|\| null;/
+ .test(MARKDOWN_TEXT),
+ "the info string must be split before it is used as a language",
+ );
+ for (const use of [
+ "language: (languageToken ?? \"text\") as never",
+ "<DeferredFenceShell language={languageToken}",
+ ]) {
+ assert.ok(
+ MARKDOWN_TEXT.includes(use),
+ `both the shell and the measurement arm must use the parsed token: ${use}`,
+ );
+ }
+ assert.ok(
+ !/language: \(language \?\? "text"\)/.test(MARKDOWN_TEXT),
+ "no path may pass the unparsed info string to the highlighter",
+ );
+
+ // The parse itself, run rather than described.
+ const token = (info: string | null) => info?.trim().split(/\s+/)[0] || null;
+ assert.equal(token("python startLine=10"), "python");
+ assert.equal(token(" ts "), "ts");
+ assert.equal(token(""), null);
+ assert.equal(token(null), null);
+});
+
+test("token coalescing was measured at zero and is not carried as code", () => {
+ // Shiki already emits maximally coalesced tokens: 72,550 -> 72,550 over the 100K rung's 99 real
+ // fences, in every theme mode. An implementation that removes no spans cannot make anything
+ // faster, and carrying a runtime-flippable flag through the fence cache for it only creates
+ // ways for a cached result to disagree with the flag that produced it.
+ for (const gone of ["coalesceTokens", "coalesceLine", "mergeable", "__UNSLOTH_COALESCE_TOKENS__",
+ "VITE_UNSLOTH_COALESCE_TOKENS"]) {
+ assert.ok(
+ !CODE_PLUGIN.includes(gone),
+ `${gone} was removed after measuring 0.0%; re-adding it needs a number first`,
+ );
+ }
+ assert.ok(
+ CODE_PLUGIN.includes("537013 -> merged 537013"),
+ "the null belongs in the file it was measured on, so nobody repeats it",
+ );
+ assert.ok(
+ CODE_PLUGIN.includes("scripts/coal-span-census.mjs"),
+ "and it must name a reproducer, so the number can be checked rather than trusted",
+ );
+ // The reproducer has to BE here. The first version of that comment pointed at a script that
+ // only existed on the machine the census was run on, which makes the citation worth nothing.
+ assert.ok(
+ existsSync(new URL("../scripts/coal-span-census.mjs", import.meta.url)),
+ "the cited reproducer must exist in this repository",
+ );
+});