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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: defer off-screen code fence highlighting by default (#9567)
Daniel Hanc5808de346ac
diff --git a/studio/frontend/smoke-heavy-thread-main.tsx b/studio/frontend/smoke-heavy-thread-main.tsxindex 621ea203a1e..a58ea3849cc 100644--- a/studio/frontend/smoke-heavy-thread-main.tsx+++ b/studio/frontend/smoke-heavy-thread-main.tsx@@ -585,11 +585,20 @@ const EXPECTED_PER_CYCLE: Record<string, number> = {artifactCards: 2,// python, typescript, json, svg, the html document, and the two tool result panes.codeBlocks: 7,- // Shiki is async and per block, so a <pre> exists long before it is highlighted. A floor under- // the token count is what tells a finished thread apart from one still building itself; a- // settled-looking count of 577 against the 3216 a whole cycle produces is a real measured- // failure of the naive "it stopped moving" gate.- highlightedTokens: 2500,+ /*+ * THE CODE ITSELF, in characters: the one size measure deferral cannot move.+ *+ * This was a floor of 2,500 highlighted tokens, doing two jobs at once. Off-screen fences now+ * render as a plain shell, so tokens partly measure where the viewport is: the same fixture+ * renders 1,322 per cycle where it rendered 3,216. Characters do not move, because the shell+ * carries the same text node: 12,660 for one cycle and 51,081 for four (2 of 5 and 15 of 20+ * fences deferred), and Chromium, Firefox and WebKit each report 12,660 to the character.+ *+ * Floor 12,000 against 12,660; a cycle is seven blocks averaging ~1,800 chars, so losing any one+ * block still fails. The other job, telling a settled thread from one still building itself, is+ * now `unhighlightedMountedFences`, asked per block.+ */+ codeChars: 12000,};/**@@ -781,6 +790,33 @@ function HeavyThreadApi({domNodes: document.getElementsByTagName("*").length,codeBlocks: document.querySelectorAll("pre").length,highlightedTokens: document.querySelectorAll("pre code span").length,+ /*+ * HOW MUCH CODE IS ON THE PAGE. `highlightedTokens` cannot answer that any more: a+ * deferred fence renders as a plain shell, so tokens measure where the reader is+ * looking. The shell holds the same text node the highlighted block holds (which is+ * also why selection, clipboard and find-in-page are identical across the two states),+ * so characters read the same either way and still drop if the fixture loses code.+ */+ codeChars: Array.from(document.querySelectorAll("pre code")).reduce(+ (total, node) => total + (node.textContent?.length ?? 0),+ 0,+ ),+ fenceBlocks: document.querySelectorAll('[data-streamdown="code-block"]').length,+ deferredFences: document.querySelectorAll("[data-unsloth-fence-deferred]").length,+ /*+ * A fence that is NEITHER deferred NOR highlighted, at rest: the settlement half of the+ * old token floor, asked per block. Streamdown mounts a code block on its own+ * unhighlighted fallback and colours it from a passive effect, so this state exists for+ * a frame on any build and a settled thread must hold none. Stronger than a floor on+ * the total, which one stuck block passes as long as the others make up the count.+ */+ unhighlightedMountedFences: Array.from(+ document.querySelectorAll('[data-streamdown="code-block"]'),+ ).filter(+ (block) =>+ !block.hasAttribute("data-unsloth-fence-deferred") &&+ block.querySelector("pre code span") === null,+ ).length,toolParts: document.querySelectorAll(".aui-tool-fallback-root").length,// The collapsible CONTENT ELEMENT, which Radix keeps in the tree for its collapse// animation. It is present whether the card is open or shut, so it counts cards, notdiff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 5861c7935d8..19b654ba810 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -8,8 +8,12 @@ import {type RefObject,useEffect,useLayoutEffect,+ useRef,useState,} from "react";+import { flushSync } from "react-dom";++import { type FenceMode, resolveFenceMode } from "./code-fence-mode";/** MONOTONIC fence highlighting: a fence is rendered as a plain shell until the@@ -43,45 +47,37 @@ import {* 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.+/*+ * How far outside the viewport a fence counts as "reached": one viewport of slack each way, so the+ * upgrade lands a frame or two before the block is on screen and the reader never sees the swap.+ *+ * THE PERCENTAGE RESOLVES AGAINST THE ROOT'S HEIGHT, and the spec says otherwise. Intersection+ * Observer 2.2 says percentages "are resolved relative to the width of the undilated rectangle"+ * for all four sides; no engine does that for top and bottom, and w3c/IntersectionObserver#391 is+ * open on exactly that. Measured on a synthetic scroller, with `0px 0px` and `300px 0px` alongside+ * as controls that must come back 0 and 300:+ *+ * root 300x800 -> 800 px root 1600x600 -> 600 px root 600x1400 -> 1400 px+ *+ * on Chromium, Firefox and WebKit alike, nine rows, every control reproduced. So it is the HEIGHT,+ * which `inBand` and the jump test below both assume. That is today's engines against a spec that+ * reads otherwise, so it is guarded rather than trusted: `pf9462_parity.py` re-measures two+ * geometries every run and fails if the observer's lookahead and the pre-paint band stop agreeing,+ * which is what an engine moving to the spec's reading would look like.+ */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.+ * The mode decision lives in `code-fence-mode.ts`, a JSX-free `.ts` so a test can RUN the table+ * rather than regex this file. Re-exported here because consumers already import this module.*/-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";-};+export { type FenceMode, resolveFenceMode, SHIP_DEFAULT } from "./code-fence-mode";++export const fenceMode = (): FenceMode =>+ resolveFenceMode(+ (globalThis as Record<string, unknown>).__UNSLOTH_DEFER_FENCE_HIGHLIGHT__,+ readBuildFlag(),+ );const readBuildFlag = (): string => {try {@@ -169,31 +165,209 @@ const CAN_OBSERVE =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 REGISTER OF FENCES THAT HAVE NOT BEEN REACHED YET, for the two things that must reach across+ * all of them at once without waiting for a React render: a discontinuous scroll, and a print,+ * which puts the WHOLE document on the page. Both go through `latchNow` below.+ *+ * A gate carries the two elements its observers were built against, resolved at the same moment+ * and rebuilt with them, so nothing here re-walks the ancestor chain or re-reads a computed style.+ * `warm` comes from the caller because the highlighter instance lives with the block's component.+ */+type FenceGate = {+ node: HTMLElement;+ near: HTMLElement | null;+ outer: HTMLElement | null;+ language: string | null;+ /** `true` tokenizes this fence's source now; `false` only loads its grammar. */+ warm: (tokens: boolean) => void;+ latch: () => void;+ /** A state write that changes nothing, whose only job is to give React sync work to do. */+ poke: () => void;+};++const unreached = new Set<FenceGate>();++/** Is this gate's fence where the observers would call it reached? */+const gateOpen = (gate: FenceGate): boolean =>+ inBand(gate.node, gate.near)+ && (gate.near === gate.outer || inBand(gate.near as HTMLElement, gate.outer));++/*+ * UPGRADE THESE FENCES INSIDE THIS TASK, so the browser paints them highlighted instead of+ * painting the plain shell and correcting it a few frames later. Dropping any of the three steps+ * was measured to put a painted plain frame back:+ *+ * 1. `warm(true)`. Streamdown's highlighted body renders its own plain fallback whenever the+ * plugin answers `null`, which it does only while a grammar is loading; with the grammar in+ * hand it tokenizes in the same call. Warming makes the render below a cache hit.+ * 2. The inner `flushSync(latch)`. A normally scheduled update lands after the next paint, which+ * is the whole defect. This commits the shell-to-block swap in this task.+ * 3. The inner `flushSync(poke)`, INSIDE an outer `flushSync`. Step 2 does not produce the+ * COLOURED commit: `HighlightedCodeBlockBody` starts at `useState(raw)` and asks for tokens+ * from a PASSIVE effect, so every newly mounted block renders unhighlighted once. Off screen+ * at thread mount that is invisible; deferred, it is a plain frame on the reader's screen.+ *+ * WHY THE POKE AND THE NESTING, since an empty `flushSync(() => {})` does neither:+ *+ * - React runs pending passive effects from `performSyncWorkOnRoot`, reached only when sync work+ * is waiting, so a flush with nothing to do never runs the effect that colours the block.+ * `poke` is that work: a state write on an already-latched fence whose own effects all+ * early-return.+ * - `flushSync` restores React's update priority BEFORE performing the flush, so the passive+ * effect's update resolves against the ambient priority, and a scroll is continuous rather+ * than discrete, so it is not flushed and lands next frame after all. The outer call holds the+ * priority discrete across its whole body, so the inner flushes carry the effect's update too.+ *+ * One way only. Nothing here can clear a latch.*/+const latchNow = (arrived: readonly FenceGate[]): void => {+ if (arrived.length === 0) return;+ for (const gate of arrived) {+ unreached.delete(gate);+ gate.warm(true);+ }+ flushSync(() => {+ flushSync(() => {+ for (const gate of arrived) gate.latch();+ });+ flushSync(() => {+ for (const gate of arrived) gate.poke();+ });+ });+};++/*+ * A DISCONTINUOUS SCROLL: a scrollbar drag, Ctrl+End, an anchor jump, a restored position.+ *+ * Neither the observers' one root height of lookahead (`REACH_MARGIN`) nor the render-time+ * pre-paint gate covers a jump: the viewport can move further than the lookahead in one step with+ * no React render in between, and an IntersectionObserver record is delivered one or more frames+ * AFTER the paint. Chromium at the 100K rung, 16 seeded jumps: 8 painted 3 to 4 frames of plain+ * code, 50 to 190 ms.+ *+ * A SCROLL LISTENER IS ENOUGH AND IS IN TIME: scroll events are dispatched in the "run the scroll+ * steps" of the same update-the-rendering pass that will paint the new position, before+ * animation-frame callbacks and before style, layout and paint, so a `flushSync` from here is part+ * of the frame the reader is about to see. `scrollTo`, wheel, drag and keyboard all arrive here.+ *+ * THE THRESHOLD IS DERIVED, NOT TUNED. The band is one root height `h` bigger each way, so after a+ * scroll of `d` the newly visible strip `[d, d + h]` is inside the old band exactly when `d <= h`.+ * The pass therefore runs only when the lookahead provably did not cover the movement, and a+ * continuous scroll pays one subtraction per event.+ *+ * ONE LISTENER, NOT ONE PER FENCE. Scroll does not bubble but does capture, so one capturing+ * document listener sees every element including nested reasoning panes. Attached when the first+ * fence registers and removed when the last latches, so nothing left to defer costs nothing.+ */+const lastScrollTop = new WeakMap<EventTarget, number>();+let scrollWatched = false;++const onScroll = (event: Event): void => {+ if (unreached.size === 0) return;+ const target = event.target;+ if (target === null) return;+ const element = target === document ? null : (target as HTMLElement);+ const top = element ? element.scrollTop : window.scrollY;+ const height = element ? element.clientHeight : window.innerHeight;+ const before = lastScrollTop.get(target);+ lastScrollTop.set(target, top);+ // An unseen scroller has no previous position, so its first event counts as a jump: one pass per+ // scroller, and never an assumption that the movement was small.+ if (before !== undefined && Math.abs(top - before) <= height) return;+ const arrived: FenceGate[] = [];+ for (const gate of unreached) {+ if (gateOpen(gate)) arrived.push(gate);+ }+ latchNow(arrived);+};++const watchScrolling = (): void => {+ if (scrollWatched || typeof document === "undefined") return;+ scrollWatched = true;+ document.addEventListener("scroll", onScroll, { capture: true, passive: true });+};++const unwatchScrolling = (): void => {+ if (!scrollWatched || unreached.size > 0 || typeof document === "undefined") return;+ scrollWatched = false;+ document.removeEventListener("scroll", onScroll, { capture: true });+};++/*+ * PRINT, the one gesture that puts every deferred fence on the page at once.+ *+ * Colour is all deferral costs a printed page -- the shell holds a live text node, so it prints+ * complete, in order and in the right font -- but a page that lost the colour on fences the reader+ * never scrolled past is a defect they can see and keep. Nor does the printed window match the+ * reader's: a print lays out at PAPER width while the scroll offset carries across as raw pixels,+ * so the page lands several fences away. Letter against a 1280 px window: 1 to 2 deferred fences+ * on every sampled page, 6.6% pixel difference against the same page with the flag off; matching+ * paper to window removes it, which identifies the cause and is why chasing the window is the+ * wrong fix. The whole document is on the page, so the whole document has to be highlighted.+ *+ * WHY AN EARLIER ATTEMPT FAILED and was reported as impossible: it latched every fence from+ * `beforeprint` with `flushSync`, the blocks swapped, and 53 of 56 still printed on streamdown's+ * raw fallback, because the swap alone renders UNHIGHLIGHTED while the passive effect waits on a+ * grammar. `latchNow` closes both halves (warm, then flush the colouring render as well as the+ * swap) and `warmGrammars` below keeps a loading grammar from being what is missing at snapshot.+ *+ * BOTH DOORS: `beforeprint` covers Ctrl+P and the print menu; headless `page.pdf()` and DevTools+ * print emulation change the media query without firing it, and a PDF export is how a reader keeps+ * a copy.+ *+ * A PRINT UPGRADES THE DOCUMENT THAT WAS PRINTED, AND NOTHING ELSE. This was a module-global+ * `printed` folded into every future fence's `reached`, a session-wide latch rather than a+ * monotonic one: at the 100K rung a thread with 53 of 56 fences deferred, 2,458 spans and 22,794+ * elements printed once, then after navigating away inside the app and back remounted with 0+ * deferred, 41,410 spans and 61,747 elements. One Ctrl+P turned the default off for the tab's+ * life, including threads never on the printed page. So a print latches what is on the page WHEN+ * IT HAPPENS and a fence mounted afterwards defers again; every print does it again, so print,+ * scroll, print gives a second page as complete as the first. Still one way only: `latchNow` can+ * only latch, and reverting on `afterprint` would be the bidirectional edge this design avoids.+ */+const upgradeEverythingForPrint = (): void => {+ latchNow([...unreached]);+};++/*+ * GRAMMARS, WARMED AT IDLE. NOT TOKENS.+ *+ * `warm(false)` highlights an EMPTY string in the fence's language: the grammar loads, nothing is+ * tokenized, no span is mounted, the document stays the size deferral made it. It buys that+ * `latchNow`'s synchronous path cannot be defeated by a still-loading grammar -- on a jump into a+ * language the reader has not met, and on a print, where there is no later frame to correct in.+ * Deduplicated by language and scheduled at idle: one load per language, nothing when nothing is+ * deferred.+ */+const grammarsWarmed = new Set<string>();+let warmScheduled = false;++const warmGrammars = (): void => {+ warmScheduled = false;+ for (const gate of unreached) {+ const language = gate.language ?? "text";+ if (grammarsWarmed.has(language)) continue;+ grammarsWarmed.add(language);+ gate.warm(false);+ }+};++const scheduleGrammarWarm = (): void => {+ if (warmScheduled || typeof globalThis === "undefined") return;+ warmScheduled = true;+ const idle = (globalThis as Record<string, unknown>).requestIdleCallback as+ | ((cb: () => void, options?: { timeout: number }) => number)+ | undefined;+ if (typeof idle === "function") idle(warmGrammars, { timeout: 2000 });+ else setTimeout(warmGrammars, 500);+};++if (typeof window !== "undefined" && typeof window.addEventListener === "function") {+ window.addEventListener("beforeprint", upgradeEverythingForPrint);+ window.matchMedia?.("print")?.addEventListener?.("change", (event) => {+ if (event.matches) upgradeEverythingForPrint();+ });+}/** THE NEAREST SCROLLING ANCESTOR, found rather than named.@@ -300,17 +474,28 @@ const inBand = (node: HTMLElement, scroller: HTMLElement | null): boolean => {* 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.+ * @param language used only to load one grammar per language rather than one per fence; `null`+ * warms plain text.+ * @param warm drive the highlighter over this fence: `true` for tokens, `false` for the grammar+ * alone. See `latchNow`. Held in a ref, not an effect dependency, so an+ * unmemoized caller cannot rebuild every observer in the thread on every render.*/export function useFenceReached(host: RefObject<HTMLElement | null>,enabled: boolean,streaming: boolean,+ language: string | null,+ warm: (tokens: boolean) => void,): 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;+ const warmRef = useRef(warm);+ useEffect(() => {+ warmRef.current = warm;+ }, [warm]);/** A COMPLETING STREAM MUST NOT DOWNGRADE.@@ -413,6 +598,23 @@ export function useFenceReached());gates.forEach(([target], i) => observers[i].observe(target));+ // The same two elements, so a jump and a print can ask the same questions without a render or+ // another ancestor walk. Rebuilt with the observers, so a rebind cannot leave a stale root.+ const registered: FenceGate = {+ node,+ near,+ outer,+ language,+ warm: (tokens) => warmRef.current(tokens),+ latch: () => setLatched(true),+ // Reuses `generation`: this fence has just latched, so every effect keyed on it+ // early-returns and the bump costs one render. See `latchNow` for why React needs the work.+ poke: () => setGeneration((n) => n + 1),+ };+ unreached.add(registered);+ watchScrolling();+ scheduleGrammarWarm();+// `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;@@ -426,6 +628,8 @@ export function useFenceReached(return () => {for (const observer of observers) observer.disconnect();resize?.disconnect();+ unreached.delete(registered);+ unwatchScrolling();};}, [reached, host, generation]);diff --git a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts b/studio/frontend/src/components/assistant-ui/code-fence-mode.tsnew file mode 100644index 00000000000..8ed68027d5e--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/code-fence-mode.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/*+ * WHICH FENCE MODE IS IN FORCE, decided in one pure function.+ *+ * Kept out of `code-fence-defer.tsx` because that is a `.tsx` and the frontend's tests run under+ * `node --experimental-strip-types`, which cannot load JSX. Every row below is RUN by+ * `tests/code-fence-mode.test.ts` rather than checked by regexes over the source.+ *+ * "off" every fence is highlighted at mount. What shipped before `defer` became default.+ * "defer" SHIP DEFAULT. An unreached fence is a plain shell and is never tokenized.+ * "tokenize" MEASUREMENT ONLY. Same plain shell, but the highlighter is still driven over the+ * source and the result thrown away.+ *+ * `tokenize` is not a shipping mode. `defer` removes the spans AND the tokenizer work that makes+ * them, so an improvement under `defer` alone cannot say which paid for it; `tokenize` holds the+ * DOM at `defer`'s size with only the tokenizer work back, so tokenize-minus-defer is the+ * tokenizer's share and off-minus-tokenize the document's. Reachable ONLY by the exact string+ * "tokenize" -- no boolean, empty value or default lands there, which keeps a measurement arm out+ * of a shipped install.+ */+export type FenceMode = "off" | "defer" | "tokenize";++/** Moving this line is the whole of "turn deferral on by default"; every override still works. */+export const SHIP_DEFAULT: FenceMode = "defer";++/**+ * AN UNSET FLAG AND AN UNRECOGNISED ONE DO NOT RESOLVE TO THE SAME MODE. Unset means an install+ * that never heard of this flag, and takes `SHIP_DEFAULT`. An unrecognised non-empty value means+ * somebody tried to configure it and mistyped: resolving that to the default would silently ignore+ * the attempt, so it degrades to `off`, which is never wrong-looking and is what this flag gave+ * before the default moved. Same rule for the env var and the runtime global.+ *+ * @param runtime `__UNSLOTH_DEFER_FENCE_HIGHLIGHT__`: string, boolean or absent. The boolean is+ * the devtools-console form and has to work in BOTH directions.+ * @param build `VITE_UNSLOTH_DEFER_FENCE_HIGHLIGHT`, `""` when never set.+ */+export const resolveFenceMode = (+ runtime: unknown,+ build: string,+): FenceMode => {+ const raw =+ typeof runtime === "string"+ ? runtime+ : runtime === true+ ? "defer"+ : runtime === false+ ? "off"+ : build;+ return raw === "1" || raw === "defer"+ ? "defer"+ : raw === "tokenize"+ ? "tokenize"+ : raw === ""+ ? SHIP_DEFAULT+ : "off";+};diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 8f701b2b0f2..c6200aa2ffe 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -498,9 +498,6 @@ function FenceBlock({}) {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.@@ -529,6 +526,36 @@ function FenceBlock({// exists to put back.const languageToken = language?.trim().split(/\s+/)[0] || null;+ /*+ * DRIVE THE HIGHLIGHTER OVER THIS FENCE ON DEMAND. The latch owns WHEN; this owns WHAT, because+ * the plugin instance lives here with the component that renders the block.+ *+ * `tokens: true`: `code.highlight` returns synchronously once the grammar is loaded and caches+ * on the source string, so this is the same object the block's own render is about to ask for,+ * which is what lets a jump or a print swap straight to a COLOURED block rather than to+ * streamdown's plain fallback. `tokens: false` highlights "", loading the grammar only.+ */+ const warm = useCallback(+ (tokens: boolean) => {+ code.highlight({+ code: tokens ? trimTrailingNewlines(source) : "",+ language: (languageToken ?? "text") as never,+ themes: STREAMDOWN_SHIKI_THEME,+ }, () => {});+ },+ [source, languageToken],+ );++ // 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),+ languageToken,+ warm,+ );+// 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 samediff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.tsindex 85ef2272936..9130823025e 100644--- a/studio/frontend/tests/code-fence-defer.test.ts+++ b/studio/frontend/tests/code-fence-defer.test.ts@@ -215,18 +215,21 @@ test("a nested scroller is gated by the outermost one as well", () => {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", () => {+test("the mode is decided in one place, and `off` still means the pre-default behaviour", () => {+ // The table itself is RUN row by row in `tests/code-fence-mode.test.ts`. What this file pins is+ // that this module grows no second opinion, and that `off` still switches the whole hook out.assert.ok(- SOURCE.includes('return raw === "1" || raw === "defer"'),- "the mode is decided from the flag value",+ SOURCE.includes('export { type FenceMode, resolveFenceMode, SHIP_DEFAULT } from "./code-fence-mode";'),+ "the mode module is the single source of the decision",);assert.ok(- /:\s*"off";/.test(SOURCE),- "any value that is not an understood mode must fall through to off",+ !/raw === "defer"|SHIP_DEFAULT: FenceMode|const raw =/.test(SOURCE),+ "no copy of the decision table may live here as well",);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",+ /useFenceReached\(\s*host,\s*mode !== "off",\s*Boolean\(isIncomplete\),/.test(MARKDOWN_TEXT),+ "with the mode off every fence must render immediately, exactly as it did before the default " ++ "moved",);});@@ -302,9 +305,11 @@ test("the gate does not mount a wrapper element of its own", () => {});test("the tokenize arm is measurement only and is not reachable from a boolean flag", () => {+ // The selection rule, and every shape that must NOT reach it, is exercised in+ // `tests/code-fence-mode.test.ts`. Here: no route into the arm except that resolved mode.assert.ok(- SOURCE.includes('raw === "tokenize"'),- "the tokenize arm is selected by an explicit string, never by a truthy flag",+ !/"tokenize"/.test(SOURCE),+ "this module must not name the measurement arm at all; it only consumes a resolved mode",);assert.ok(MARKDOWN_TEXT.includes('const pretokenize = mode === "tokenize" && !reached'),@@ -312,32 +317,84 @@ test("the tokenize arm is measurement only and is not reachable from a boolean f);});-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"]) {+test("a print upgrades the whole document, and never puts it back", () => {+ // An earlier `beforeprint` path was removed after 53 of 56 blocks still printed on streamdown's+ // raw fallback out to twenty seconds. The latch was not the problem: what it renders is, since+ // the highlighted body asks for tokens from a PASSIVE effect and the plugin answers `null` while+ // a grammar loads. `latchNow` closes both halves, warming then flushing twice. Keep both.+ for (const door of ["beforeprint", 'matchMedia?.("print")']) {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`,+ SOURCE.includes(door),+ `${door} is one of the two ways a document reaches a printer, and both must be covered`,);}assert.ok(- !/warmedGrammars|pendingGrammars/.test(MARKDOWN_TEXT),- "the grammar warm-up was removed with the rest of the print path",+ !/addEventListener\(\s*"afterprint"/.test(SOURCE),+ "reverting on afterprint would be exactly the bidirectional edge this design removes",+ );+ // A PRINT IS NOT A SESSION-WIDE SWITCH. As a module-global `printed` folded into every future+ // fence's `reached` it measured, at the 100K rung: print once, navigate away in-app and back,+ // and the thread remounts with 0 of 56 fences deferred, 41,410 spans and 61,747 elements instead+ // of 53, 2,458 and 22,794. One Ctrl+P turned the default off for the rest of the tab.+ assert.ok(+ /const reached = !enabled \|\| !CAN_OBSERVE \|\| streaming \|\| latched;/.test(SOURCE),+ "no print state may be folded into a fence's reached: a fence mounted after a print was not " ++ "on the printed page and has nothing to latch for",+ );+ assert.ok(+ /const upgradeEverythingForPrint = \(\): void => \{\s*latchNow\(\[\.\.\.unreached\]\);\s*\};/+ .test(SOURCE),+ "a print latches exactly what is unreached when it happens, and every print does it again",);});-test("the print limitation is written down where it is decided", () => {+test("an upgrade taken inside one task warms, flushes, and flushes again", () => {+ // Dropping any one of the three puts a plain frame back on a jump, or a colourless fence on a+ // printed page.+ const latchNow = SOURCE.slice(SOURCE.indexOf("const latchNow"));+ const body = latchNow.slice(0, latchNow.indexOf("\n};"));+ assert.ok(body.includes("gate.warm(true)"), "the tokens have to exist before the swap renders");+ assert.ok(+ body.indexOf("gate.warm(true)") < body.indexOf("flushSync"),+ "warming after the flush is warming after the paint",+ );+ assert.equal(+ body.split("flushSync").length - 1,+ 3,+ "an outer flush holds the update priority discrete; one inner flush commits the swap and the "+ + "second runs the passive effect that colours it",+ );+ assert.ok(+ body.includes("gate.poke()"),+ "react only runs pending passive effects when it has sync work, so the second flush needs some",+ );+});++test("a jump is recognised from the lookahead, not from a tuned number", () => {+ // `REACH_MARGIN` grows the band by one root height, so a scroll of at most one height can only+ // reveal fences already reached: the pass runs exactly when the movement beat the lookahead. A+ // literal pixel threshold would be a number nobody could derive or maintain.+ assert.ok(+ /Math\.abs\(top - before\) <= height/.test(SOURCE),+ "the jump test compares the movement against the root height the margin is one of",+ );+ assert.ok(+ !/[^a-zA-Z_]\d{2,}\s*(?:px)?\s*[;)]/.test(SOURCE.slice(SOURCE.indexOf("const onScroll"), SOURCE.indexOf("const watchScrolling"))),+ "no pixel constant may appear in the jump test",+ );+});++test("nothing is watched once there is nothing left to defer", () => {+ // This change claims a reached fence carries no residual per-scroll cost. The one shared+ // capturing listener must therefore be removed when the last fence latches.+ assert.ok(+ /document\.addEventListener\("scroll", onScroll, \{ capture: true, passive: true \}\)/.test(SOURCE),+ "one capturing, passive listener sees scrolling on nested panes as well as on the thread",+ );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",+ /unreached\.size > 0/.test(SOURCE) &&+ /document\.removeEventListener\("scroll", onScroll/.test(SOURCE),+ "the listener is removed when the register empties",);});diff --git a/studio/frontend/tests/code-fence-mode.test.ts b/studio/frontend/tests/code-fence-mode.test.tsnew file mode 100644index 00000000000..67b8e0b0cef--- /dev/null+++ b/studio/frontend/tests/code-fence-mode.test.ts@@ -0,0 +1,124 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import {+ SHIP_DEFAULT,+ resolveFenceMode,+} from "../src/components/assistant-ui/code-fence-mode.ts";++/**+ * The fence mode decision table, RUN rather than described.+ *+ * The other tests around this change are regexes over source, because what they protect is a React+ * hook over IntersectionObserver and would need a DOM. This is a pure function of two values, and+ * the point of the default moving from "off" to "defer" is that every existing override keeps+ * working in BOTH directions. A truth table nobody executes is not evidence of that.+ */++test("an install that has never set the flag gets the ship default", () => {+ assert.equal(SHIP_DEFAULT, "defer", "the ship default is deferral");+ assert.equal(resolveFenceMode(undefined, ""), "defer");+});++test("the build flag overrides the default in both directions", () => {+ // DOWN: an install that wants exactly the old rendering says so and gets it.+ assert.equal(resolveFenceMode(undefined, "off"), "off");+ assert.equal(resolveFenceMode(undefined, "0"), "off");+ // UP: still selects deferral explicitly, which is what every measurement arm passes.+ assert.equal(resolveFenceMode(undefined, "defer"), "defer");+ assert.equal(resolveFenceMode(undefined, "1"), "defer");+});++test("the runtime global overrides the default in both directions", () => {+ assert.equal(resolveFenceMode("off", ""), "off");+ assert.equal(resolveFenceMode("defer", ""), "defer");+ // The boolean forms a devtools console types. `false` must turn it OFF against a now-ON default,+ // the direction that did not previously have to work.+ assert.equal(resolveFenceMode(false, ""), "off");+ assert.equal(resolveFenceMode(true, ""), "defer");+});++test("the runtime global beats the build flag, both ways round", () => {+ assert.equal(+ resolveFenceMode(false, "defer"),+ "off",+ "global off beats a build that said on",+ );+ assert.equal(resolveFenceMode("off", "defer"), "off");+ assert.equal(+ resolveFenceMode(true, "off"),+ "defer",+ "global on beats a build that said off",+ );+ assert.equal(resolveFenceMode("defer", "off"), "defer");+});++test("a typo degrades to the old behaviour, never to the new default", () => {+ // Falling through to the DEFAULT would silently ignore the attempt. `off` highlights every fence+ // at mount, which is never wrong-looking, and is what this flag did before the default moved.+ for (const typo of [+ "defr",+ "DEFER",+ "true",+ "yes",+ "on",+ "2",+ " defer",+ "tokenise",+ ]) {+ assert.equal(+ resolveFenceMode(undefined, typo),+ "off",+ `build flag ${typo}`,+ );+ assert.equal(resolveFenceMode(typo, ""), "off", `runtime global ${typo}`);+ }+});++test("tokenize is measurement only and no default or boolean can reach it", () => {+ assert.equal(+ resolveFenceMode(undefined, "tokenize"),+ "tokenize",+ "explicit string only",+ );+ assert.equal(resolveFenceMode("tokenize", ""), "tokenize");+ // Nothing else may land there, least of all the shapes carrying no opinion: absent global, unset+ // build flag.+ assert.notEqual(resolveFenceMode(undefined, ""), "tokenize");+ assert.notEqual(resolveFenceMode(true, ""), "tokenize");+ assert.notEqual(resolveFenceMode(false, ""), "tokenize");+ assert.notEqual(resolveFenceMode(1 as unknown, ""), "tokenize");+ assert.notEqual(resolveFenceMode({} as unknown, ""), "tokenize");+});++test("a non-string non-boolean global is ignored rather than coerced", () => {+ // `__UNSLOTH_DEFER_FENCE_HIGHLIGHT__ = 1` is a plausible console typo. Coercing it would add two+ // more undocumented spellings, so it falls through to the build flag instead.+ assert.equal(resolveFenceMode(1 as unknown, "off"), "off");+ assert.equal(resolveFenceMode(0 as unknown, "defer"), "defer");+ assert.equal(resolveFenceMode(null, ""), SHIP_DEFAULT);+ assert.equal(resolveFenceMode({} as unknown, ""), SHIP_DEFAULT);+});++/** JSX in the mode module makes this file unloadable and every assertion above a comment. */+test("the mode module is plain TypeScript", () => {+ const source = readFileSync(+ new URL(+ "../src/components/assistant-ui/code-fence-mode.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.ok(+ !/<[A-Za-z]/.test(source.replace(/^\s*[/*].*$/gm, "")),+ "no JSX in the mode module",+ );+ assert.ok(+ !/\bfrom\s+["']react["']/.test(source),+ "and no react import: this module has to load under --experimental-strip-types",+ );+});diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.pyindex 550b9fed311..e7afb10500b 100644--- a/tests/studio/playwright_heavy_thread.py+++ b/tests/studio/playwright_heavy_thread.py@@ -1199,7 +1199,17 @@ TABLE_ROWS = (("messages rendered", lambda r: r["counts"]["messages"]),("dom nodes", lambda r: r["counts"]["domNodes"]),("code blocks", lambda r: r["counts"]["codeBlocks"]),+ # Side by side deliberately: `code chars` is what the fixture built and does not move when a+ # fence defers, while `highlighted tokens` and `deferred fences` are how much of it the+ # viewport reached. Only the first is a statement about the fixture.+ ("code chars", lambda r: r["counts"].get("codeChars", 0)),("highlighted tokens", lambda r: r["counts"]["highlightedTokens"]),+ ("fence blocks", lambda r: r["counts"].get("fenceBlocks", 0)),+ ("deferred fences", lambda r: r["counts"].get("deferredFences", 0)),+ (+ "mounted but unhighlighted fences",+ lambda r: r["counts"].get("unhighlightedMountedFences", 0),+ ),("tool parts", lambda r: r["counts"]["toolParts"]),("collapsible tool outputs", lambda r: r["counts"]["collapsibleOutputs"]),("code execution panes", lambda r: r["counts"]["codeExecutionPanes"]),@@ -1757,6 +1767,21 @@ def harness_failures(results: dict, report: dict) -> list[str]:)if counts.get("highlightedTokens", 0) <= 0:failures.append(f"{where} highlighted nothing; Shiki never ran")+ # DEFERRAL IS EXPECTED. AN UNHIGHLIGHTED MOUNTED FENCE IS NOT.+ #+ # A floor on total tokens no longer separates "settled" from "the reader is not looking+ # at most of the code", so ask per block: a fence is either a deferred shell, which is+ # a named state with an attribute, or highlighted. The third state -- mounted, not+ # deferred, still on streamdown's fallback -- lasts a frame while the highlighter's+ # passive effect runs, and a settled thread must hold none. Stricter than the total it+ # replaces, which one stuck block passed as long as the others made the count up.+ stuck = counts.get("unhighlightedMountedFences", 0)+ if stuck:+ failures.append(+ f"{where} left {stuck} of {counts.get('fenceBlocks', 0)} code fences mounted "+ f"but unhighlighted after settling, neither deferred nor coloured; the "+ "thread had not finished building itself when it was measured"+ )viewport = row["viewport"]if viewport["scrollHeight"] <= viewport["clientHeight"]:failures.append(diff --git a/tests/studio/test_heavy_thread_harness_contract.py b/tests/studio/test_heavy_thread_harness_contract.pyindex 3d9ada92ece..dbc0cc7aeb7 100644--- a/tests/studio/test_heavy_thread_harness_contract.py+++ b/tests/studio/test_heavy_thread_harness_contract.py@@ -126,6 +126,26 @@ def test_the_verdict_asserts_the_fixture_and_not_just_its_size() -> None:assert 'counts.get("highlightedTokens", 0)' in decision+def test_the_fixture_assertion_survives_deferred_fence_highlighting() -> None:+ # A floor on the TOKEN count partly measures where the viewport is: the same unchanged fixture+ # dropped from 3,216 tokens per cycle to 1,322. Lowering it to fit would leave the check unable+ # to tell a deferred thread from one that stopped rendering code, which is all it is for. So+ # the size assertion is on characters, which the deferred shell carries too.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ head = page.index("const EXPECTED_PER_CYCLE")+ expected = page[head : page.index("};", head)]+ assert "codeChars: 12000" in expected, "the floor has to be on something deferral cannot move"+ assert "highlightedTokens:" not in expected, "the token floor was the thing deferral broke"+++def test_a_fence_may_be_deferred_or_highlighted_but_not_neither() -> None:+ # The SETTLEMENT half of the old token floor, asked per block. One block stuck on streamdown's+ # unhighlighted fallback used to pass as long as the others made the count up.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ assert "unhighlightedMountedFences" in page+ assert 'counts.get("unhighlightedMountedFences", 0)' in verdict()++def test_the_verdict_asserts_the_keystroke_reached_the_runtime() -> None:# The DOM value is what the harness itself wrote. A keystroke that reached nothing still# reports the ~33ms paint floor, which reads as a plausible timing.diff --git a/tests/studio/test_heavy_thread_measurement_integrity.py b/tests/studio/test_heavy_thread_measurement_integrity.pyindex aa35990a639..fcf31f0331c 100644--- a/tests/studio/test_heavy_thread_measurement_integrity.py+++ b/tests/studio/test_heavy_thread_measurement_integrity.py@@ -538,12 +538,16 @@ def test_the_median_of_three_good_repetitions_is_unchanged() -> None:def clean_cell() -> dict:"""One (engine, size) cell that harness_failures() has nothing to say about."""- per_cycle = {"images": 3, "codeBlocks": 7}+ per_cycle = {"images": 3, "codeBlocks": 7, "codeChars": 12000}counts = {"messages": 20,"domNodes": 4000,"codeBlocks": 7,+ "codeChars": 12660,"highlightedTokens": 3000,+ "fenceBlocks": 5,+ "deferredFences": 2,+ "unhighlightedMountedFences": 0,"images": 3,"actionBars": 10,"tooltipTriggers": 30,@@ -619,6 +623,36 @@ def test_a_clean_cell_produces_no_harness_failure() -> None:assert HARNESS.harness_failures(results_with(clean_cell()), discriminating_report()) == []+def test_deferred_fences_are_not_a_harness_failure() -> None:+ # THE POINT OF MEASURING CHARACTERS. A real, complete thread now holds far fewer highlighted+ # tokens than before the default moved: 1,322 against 3,216 for one cycle, measured, with the+ # fixture untouched. The harness must not call that broken.+ cell = copy.deepcopy(clean_cell())+ cell["counts"]["deferredFences"] = 4+ cell["counts"]["highlightedTokens"] = 300+ assert HARNESS.harness_failures(results_with(cell), discriminating_report()) == []+++def test_a_fixture_that_lost_its_code_is_still_a_harness_failure() -> None:+ # The replaced check caught a fixture that is not the heavy thread it claims to be, and this+ # still does. Tokens are left HIGH so only the character floor can fail: a thread whose code+ # blocks quietly emptied still renders, still scrolls and still curves, of something else.+ cell = copy.deepcopy(clean_cell())+ cell["counts"]["codeChars"] = 6000+ cell["counts"]["highlightedTokens"] = 99999+ failures = HARNESS.harness_failures(results_with(cell), discriminating_report())+ assert any("6000 codeChars, short of the 12000" in f for f in failures), failures+++def test_a_fence_that_is_neither_deferred_nor_highlighted_is_a_harness_failure() -> None:+ # The other half of the old token floor, per block: one block stuck on streamdown's+ # unhighlighted fallback passed the total as long as the rest made it up.+ cell = copy.deepcopy(clean_cell())+ cell["counts"]["unhighlightedMountedFences"] = 1+ failures = HARNESS.harness_failures(results_with(cell), discriminating_report())+ assert any("mounted but unhighlighted" in f for f in failures), failures++def test_a_scroll_that_never_settled_is_a_harness_failure() -> None:cell = copy.deepcopy(clean_cell())cell["actions"]["scroll"]["settleMs"] = None