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: keep a streaming code fence highlighted, and window its spans (#11423)
Daniel Han40ade0f6ae13
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 864034cbbdb..094f4f3d860 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -3,11 +3,13 @@"use client";+import type { HighlightResult } from "@streamdown/code";import {memo,type RefObject,useEffect,useLayoutEffect,+ useMemo,useRef,useState,} from "react";@@ -15,7 +17,15 @@ import { flushSync } from "react-dom";import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";import { type FenceMode, resolveFenceMode } from "./code-fence-mode";+import {+ isBlankLine,+ type LineWindow,+ lineIsWindowed,+ plainLineText,+ selectLineWindow,+} from "./code-fence-window";import { normalizeLanguage } from "./code-plugin";+import { WINDOW_CAP_LINES } from "./code-fence-window";/** MONOTONIC fence highlighting: a fence renders as a plain shell until the first time it comes near@@ -348,9 +358,18 @@ const scheduleGrammarWarm = (): void => {};if (typeof window !== "undefined" && typeof window.addEventListener === "function") {- window.addEventListener("beforeprint", upgradeEverythingForPrint);+ window.addEventListener("beforeprint", () => {+ upgradeEverythingForPrint();+ setPrinting(true);+ });+ window.addEventListener("afterprint", () => setPrinting(false));window.matchMedia?.("print")?.addEventListener?.("change", (event) => {- if (event.matches) upgradeEverythingForPrint();+ if (event.matches) {+ upgradeEverythingForPrint();+ setPrinting(true);+ } else {+ setPrinting(false);+ }});}@@ -571,3 +590,419 @@ export function useFenceReached(}export const DeferredFenceShell = memo(FenceShell);++/*+ * The highlighted body, rendered here rather than by streamdown.+ *+ * Streamdown's `CodeBlockBody` maps the whole token array every render and memoizes on+ * `prev.result === next.result`, reference equality, while `code-plugin.ts` returns a fresh object+ * every call, so the memo never hits and every line and token rebuilds each frame. The spans are+ * the cost, not the tokenizer: #10779 kept calling the highlighter, stopped rendering the tokens+ * and still doubled the frame rate, and `scripts/coal-span-census.mjs` shows Shiki's tokens are+ * already maximally coalesced, so merging cannot help.+ *+ * So: one memoized component per line (a committed line's identity is stable, so `memo` bails),+ * plus a line window past `WINDOW_CAP_LINES` (see `code-fence-window.ts`).+ *+ * The DOM is streamdown's element for element and class for class, because+ * `playwright_code_block_flicker.py` reads computed styles off this subtree and a perf change that+ * also moved the rendering could not be attributed.+ */++export type FenceTokens = HighlightResult;+type TokenLine = HighlightResult["tokens"][number];+type FenceToken = TokenLine[number];++/* Streamdown's own class lists, copied verbatim. The `bg-[var(--sdm-bg,inherit]` spellings are+ * unbalanced in streamdown 2.5's build and therefore generate no rule at all; they are reproduced+ * as they are because the goal is the same DOM, not a tidier one. */+/*+ * The one deliberate difference from streamdown's line class: it writes a raw pixel text utility,+ * which `tests/studio/test_ui_font_scale_contract.py` forbids anywhere in frontend source, comments+ * included, because a fixed size ignores the UI font preference. `text-ui-13` scales with it.+ * Moot in the thread either way: `index.css` gives that pseudo-element `display: none`.+ */+const LINE_CLASS =+ "block before:content-[counter(line)] before:inline-block before:[counter-increment:line] before:w-6 before:mr-4 before:text-ui-13 before:text-right before:text-muted-foreground/50 before:font-mono before:select-none";+const CODE_CLASS = "[counter-increment:line_0] [counter-reset:line]";+const PRE_CLASS =+ "bg-[var(--sdm-bg,inherit] dark:bg-[var(--shiki-dark-bg,var(--sdm-bg,inherit)]";+const TOKEN_CLASS =+ "text-[var(--sdm-c,inherit)] dark:text-[var(--shiki-dark,var(--sdm-c,inherit))]";+const TOKEN_BG_CLASS =+ "bg-[var(--sdm-tbg)] dark:bg-[var(--shiki-dark-bg,var(--sdm-tbg))]";++/*+ * THE `language-x` CLASS, WHICH IS NOT DECORATION. `remark-rehype` puts `language-<info>` on the+ * `<code>` of a fenced block, streamdown passes that `className` straight through to BOTH the body+ * div and the `<pre>`, and dropping it was measured as the only DOM difference between this body+ * and the one it replaces. Nothing in the tree selects on it today, which is exactly why it would+ * have gone unnoticed: it is a published rendering contract, user stylesheets and future probes+ * reach for it, and `math-block-marker.ts` already relies on the same `language-` convention one+ * layer up. The token is the FIRST word of the info string, so ```python startLine=10 is+ * `language-python`, which is what `languageToken` already holds.+ */+const joinClasses = (...parts: (string | null)[]): string =>+ parts.filter((part): part is string => Boolean(part)).join(" ");++/* `rootStyle` arrives as a CSS declaration string. Parsed the way streamdown parses it, splitting+ * on the FIRST colon only, so a `url(data:...)` value survives. */+const parseDeclarations = (text: string): Record<string, string> => {+ const style: Record<string, string> = {};+ for (const declaration of text.split(";")) {+ const colon = declaration.indexOf(":");+ if (colon <= 0) continue;+ const property = declaration.slice(0, colon).trim();+ const value = declaration.slice(colon + 1).trim();+ if (property && value) style[property] = value;+ }+ return style;+};++const tokenStyle = (+ token: FenceToken,+): { style: Record<string, string>; hasBackground: boolean } => {+ const style: Record<string, string> = {};+ let hasBackground = Boolean(token.bgColor);+ if (token.color) style["--sdm-c"] = token.color;+ if (token.bgColor) style["--sdm-tbg"] = token.bgColor;+ if (token.htmlStyle) {+ for (const [property, value] of Object.entries(token.htmlStyle)) {+ if (property === "color") style["--sdm-c"] = value;+ else if (property === "background-color") {+ style["--sdm-tbg"] = value;+ hasBackground = true;+ } else style[property] = value;+ }+ }+ return { style, hasBackground };+};++/**+ * One line of a fence.+ *+ * Memoized on the default shallow comparison, which is all it needs: `line` is the array+ * `code-plugin.ts` committed and never touches again, and `windowed` only changes when the reader+ * moves far enough for the window to move. A fence growing by a character re-renders its last line+ * and nothing else.+ */+const FenceLine = memo(function FenceLine({+ line,+ windowed,+}: {+ line: TokenLine;+ windowed: boolean;+}) {+ if (isBlankLine(line)) {+ return <span className={LINE_CLASS}>{"\n"}</span>;+ }+ if (!windowed) {+ // One text node for the whole line. Same characters, same block box, same height: the only+ // thing this line has given up is its colour, and it is off screen.+ return <span className={LINE_CLASS}>{plainLineText(line)}</span>;+ }+ return (+ <span className={LINE_CLASS}>+ {line.map((token, index) => {+ const { style, hasBackground } = tokenStyle(token);+ return (+ <span+ className={+ hasBackground ? `${TOKEN_CLASS} ${TOKEN_BG_CLASS}` : TOKEN_CLASS+ }+ key={index}+ style={style}+ {...token.htmlAttrs}+ >+ {token.content}+ </span>+ );+ })}+ </span>+ );+});++// One scroll listener and one frame for every windowed fence: each measurement reads layout, so a+// listener per fence makes scrolling cost more than the rendering the window avoids. Same shape+// `watchScrolling` uses for the reach latch, coalesced into a frame.+const windowedFences = new Set<() => void>();+let windowFrame = 0;+let windowWatched = false;++/*+ * A print puts the whole document on the page, so the whole fence is coloured;+ * `upgradeEverythingForPrint` makes the same argument for a deferred fence.+ *+ * This one REVERTS where the latch does not: the tokens are already in `fence.lines`, so+ * re-windowing costs element creation only, and not reverting would let one Ctrl+P un-window every+ * huge fence for the life of the tab. Both doors, as above: `beforeprint` for Ctrl+P, the media+ * query for `page.pdf()` and devtools emulation, which do not fire it.+ */+let printing = false;++const remeasureWindows = (): void => {+ windowFrame = 0;+ for (const measure of windowedFences) measure();+};++/** Is a print in progress? While it is, every fence renders every line highlighted. */+export const fencePrinting = (): boolean => printing;++/*+ * Synchronous, and inside `flushSync`, for the same reason `latchNow` is: a normally scheduled+ * update lands after the next paint, and there is no next paint before the print snapshot.+ */+const setPrinting = (value: boolean): void => {+ // BEFORE the window check: a print that starts while a fence still shows its shell has no window+ // to remeasure, but the state must still be recorded or the tokens arrive mid-preview and window+ // it. Only the flush is skipped when there is nothing to remeasure.+ if (printing === value) return;+ printing = value;+ if (windowFrame !== 0) {+ cancelAnimationFrame(windowFrame);+ windowFrame = 0;+ }+ if (windowedFences.size === 0) return;+ flushSync(remeasureWindows);+};++const scheduleRemeasure = (): void => {+ if (windowFrame !== 0 || windowedFences.size === 0) return;+ windowFrame = requestAnimationFrame(remeasureWindows);+};++const watchWindows = (): void => {+ if (windowWatched || typeof document === "undefined") return;+ windowWatched = true;+ // Capturing, because scroll does not bubble but does capture, so this one listener sees the+ // thread scroller AND the nested reasoning pane.+ document.addEventListener("scroll", scheduleRemeasure, {+ capture: true,+ passive: true,+ });+ window.addEventListener("resize", scheduleRemeasure, { passive: true });+};++const unwatchWindows = (): void => {+ if (!windowWatched || windowedFences.size > 0 || typeof document === "undefined") {+ return;+ }+ windowWatched = false;+ document.removeEventListener("scroll", scheduleRemeasure, { capture: true });+ window.removeEventListener("resize", scheduleRemeasure);+ if (windowFrame !== 0) {+ cancelAnimationFrame(windowFrame);+ windowFrame = 0;+ }+};++/**+ * Which lines of this fence carry token spans, or `null` for all of them.+ *+ * The geometry is read here and the decision is made in `code-fence-window.ts`, which is a+ * JSX-free module so that a test can RUN the arithmetic rather than regex this file.+ */+function useLineWindow(+ code: RefObject<HTMLElement | null>,+ /*+ * The fence's outermost element, and the ONLY thing it is used for is finding the scrolling+ * ancestor. `scrollerOf` starts at `parentElement` and tests `overflow-y`, and a code block+ * carries `overflow-x: auto`, which makes `overflow-y` compute to `auto` as well+ * (css-overflow-3: a non-visible value on one axis forces the other off `visible`). Walking up+ * from the `<code>` would therefore be one `scrollHeight` away from rooting the whole window+ * calculation inside the fence's own horizontal scroller. Starting outside the block skips+ * both of them, and it is the element the reach latch already measures against.+ */+ frame: RefObject<HTMLElement | null>,+ lineCount: number,+ enabled: boolean,+): LineWindow | null {+ const [lineWindow, setLineWindow] = useState<LineWindow | null>(null);+ // The rendered window, read by `measure` without making it an effect dependency: the effect+ // registers a listener, and rebuilding that on every window move would defeat the coalescing.+ const current = useRef<LineWindow | null>(null);+ const lines = useRef(lineCount);+ lines.current = lineCount;+ const hasBody = lineCount > 0;+ const measure = useRef<() => void>(() => {});++ measure.current = () => {+ const node = code.current;+ const outer = frame.current;+ if (!node || !outer) return;+ // Under the cap a window can never apply, so no layout read is needed. A streaming fence that+ // grows past the cap re-registers through the ResizeObserver.+ if (lines.current <= WINDOW_CAP_LINES && current.current === null) return;+ // See `setPrinting`: the whole document is on the page, so the whole fence is coloured.+ if (printing) {+ if (current.current === null) return;+ current.current = null;+ setLineWindow(null);+ return;+ }+ const scroller = scrollerOf(outer);+ const bounds = scroller?.getBoundingClientRect();+ const rect = node.getBoundingClientRect();+ const count = lines.current;+ const next = selectLineWindow({+ lineCount: count,+ // MEASURED, never assumed. `index.css` pins `line-height: 1.55` on the code block, but the+ // font size is a `--ui-font-scale` multiple inside a container query, so the pixel height is+ // not knowable from here. Every line is rendered, so the mean IS the line height.+ lineHeight: count > 0 ? rect.height / count : 0,+ contentTop: rect.top,+ viewportTop: bounds ? bounds.top : 0,+ viewportHeight: bounds ? bounds.height : window.innerHeight,+ previous: current.current,+ });+ // `selectLineWindow` hands the previous object straight back when nothing moved, so this is an+ // identity check and an ordinary scroll costs no render at all.+ if (next === current.current) return;+ current.current = next;+ setLineWindow(next);+ };++ /*+ * IN A LAYOUT EFFECT, AND KEYED ON THE BODY EXISTING.+ * Two things go wrong with a passive effect keyed on `enabled` alone, and the browser probe+ * caught both. A fence renders the plain shell until its grammar chunk lands, so at mount there+ * is no `<code>` to measure and no element for the ResizeObserver to watch; keyed only on+ * `enabled` the effect never runs again once the tokens arrive, and the window stayed off until+ * the reader happened to scroll (measured: 30,861 spans still mounted). And a passive effect+ * lands after the paint, so the frame that introduces a 20,000 line fence paints every span in+ * it before the window takes them away. Layout effects run after mutation and before paint, so+ * the first painted frame is already windowed.+ */+ useLayoutEffect(() => {+ if (!enabled) {+ current.current = null;+ // eslint-disable-next-line react-hooks/set-state-in-effect+ setLineWindow(null);+ return;+ }+ const run = () => measure.current();+ windowedFences.add(run);+ watchWindows();+ run();+ /*+ * The fence's own growth moves nothing the scroll listener would notice: a streamed line+ * lands below the viewport and the reader has not moved. A ResizeObserver on the code+ * element is what sees it, and it also covers the font finishing loading, the thread column+ * changing width, and the reasoning pane expanding.+ */+ /*+ * OBSERVED ON THE WRAPPER, NOT ON THE `<code>`.+ * A `<code>` is `display: inline`, and ResizeObserver does not observe an element with no+ * principal box: the callback simply never fires. Measured, not read off the spec -- with the+ * observer on the `<code>` a fence streamed past 3,000 lines and 23,139 spans and the window+ * never once engaged, because the only thing that ever called `measure` was the one call this+ * effect makes, back when the fence was one line long. The wrapper is a flex container, it+ * grows by exactly what the code grows by, and it is already resolved here.+ */+ let resize: ResizeObserver | undefined;+ const box = frame.current;+ if (box && typeof ResizeObserver !== "undefined") {+ resize = new ResizeObserver(scheduleRemeasure);+ resize.observe(box);+ }+ return () => {+ resize?.disconnect();+ windowedFences.delete(run);+ unwatchWindows();+ };+ // `hasBody` and not `lineCount`: the count changes on every streamed line and re-registering+ // per line would throw away the coalescing this exists for. The transition that matters is the+ // shell becoming a real body, and it happens once.+ }, [enabled, hasBody, code, frame]);++ return enabled ? lineWindow : null;+}++/**+ * A fence's body, highlighted, with the spans bounded to what is on screen.+ *+ * Falls back to the plain shell whenever there are no tokens to render, which is the window+ * between a fence appearing and its grammar chunk arriving. That is the same markup the deferred+ * shell uses and the same markup streamdown's own unhighlighted fallback uses, so the fence does+ * not change shape when the colours land.+ */+export const FenceBody = memo(function FenceBody({+ isIncomplete,+ language,+ result,+ source,+ windowing,+}: {+ /** Streamdown's unclosed-fence flag, reproduced as `data-incomplete` on the wrapper. */+ isIncomplete: boolean | undefined;+ language: string | null;+ result: FenceTokens | null;+ source: string;+ /** False keeps every line highlighted however long the fence is, which is what main does. */+ windowing: boolean;+}) {+ const code = useRef<HTMLElement | null>(null);+ const frame = useRef<HTMLDivElement | null>(null);+ const tokens = result?.tokens ?? null;+ const lineWindow = useLineWindow(code, frame, tokens?.length ?? 0, windowing);+ const languageClass = language === null ? null : `language-${language}`;++ const rootStyle = useMemo(() => {+ const style: Record<string, string> = {};+ if (!result) return style;+ if (result.bg) style["--sdm-bg"] = result.bg;+ if (result.fg) style["--sdm-fg"] = result.fg;+ if (result.rootStyle) Object.assign(style, parseDeclarations(result.rootStyle));+ return style;+ }, [result]);++ // No tokens yet, or a result carrying no lines at all. Both fall back to the plain shell, which+ // is one line tall for an empty body where a `<code>` with no children is nothing at all.+ if (!tokens || tokens.length === 0) {+ return <FenceShell language={language} source={source} />;+ }++ return (+ <div+ className="my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2"+ data-incomplete={isIncomplete || undefined}+ data-language={language ?? undefined}+ data-streamdown="code-block"+ ref={frame}+ // Streamdown declares both inline. `index.css` then forces `content-visibility: visible`+ // back on for code blocks, because WebKit before Safari 26 cannot find-in-page skipped+ // content, but the declaration is reproduced so the computed cascade is identical to the one+ // `playwright_code_block_flicker.py` reads.+ style={{ containIntrinsicSize: "auto 200px", contentVisibility: "auto" }}+ >+ <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={joinClasses(+ languageClass,+ "overflow-x-auto rounded-md border border-border bg-background p-4 text-sm",+ )}+ data-language={language ?? undefined}+ data-streamdown="code-block-body"+ data-unsloth-fence-windowed={lineWindow === null ? undefined : "true"}+ >+ <pre className={joinClasses(languageClass, PRE_CLASS)} style={rootStyle}>+ <code className={CODE_CLASS} ref={code}>+ {tokens.map((line, index) => (+ <FenceLine+ key={index}+ line={line}+ windowed={lineIsWindowed(lineWindow, index)}+ />+ ))}+ </code>+ </pre>+ </div>+ </div>+ );+});diff --git a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts b/studio/frontend/src/components/assistant-ui/code-fence-mode.tsindex 4b23e1c6596..f47a577093e 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts+++ b/studio/frontend/src/components/assistant-ui/code-fence-mode.ts@@ -10,6 +10,11 @@* "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.+ * "window" "defer", plus a LINE WINDOW inside a fence past `WINDOW_CAP_LINES`: off-screen+ * lines render their text as one node instead of their token spans. Not yet the+ * ship default, because the ladder that would justify moving it has not been run.+ * It is a superset of "defer": under the cap the two render the same DOM, so an+ * A/B between them isolates the window and nothing else.* `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@@ -17,7 +22,7 @@* "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";+export type FenceMode = "off" | "defer" | "tokenize" | "window";/** Moving this line is the whole of "turn deferral on by default"; every override still works. */export const SHIP_DEFAULT: FenceMode = "defer";@@ -49,7 +54,9 @@ export const resolveFenceMode = (? "defer": raw === "tokenize"? "tokenize"- : raw === ""- ? SHIP_DEFAULT- : "off";+ : raw === "window"+ ? "window"+ : raw === ""+ ? SHIP_DEFAULT+ : "off";};diff --git a/studio/frontend/src/components/assistant-ui/code-fence-window.ts b/studio/frontend/src/components/assistant-ui/code-fence-window.tsnew file mode 100644index 00000000000..09a89622fc2--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/code-fence-window.ts@@ -0,0 +1,134 @@+// 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 lines of a fence carry token spans. JSX-free so the tests can RUN it.+ *+ * A line outside the window loses its COLOUR and nothing else: every character stays in the+ * document, which is what separates this from virtualization (rejected in+ * `progressive-mount-controller.ts`) and from `content-visibility: auto` (banned on code blocks in+ * `index.css`; WebKit before Safari 26 cannot find-in-page skipped content).+ *+ * The swap replaces a line's CHILDREN, never the element, so heights cannot move. That matters:+ * `use-intent-aware-autoscroll.tsx` absorbs only 64px of sub-frame shrink and+ * `progressive-messages.tsx` has scroll anchoring off.+ */++/** An inclusive line range. `null` means "no window": every line renders its token spans. */+export type LineWindow = { first: number; last: number };++// Below the cap a fence is highlighted end to end and produces main's DOM byte for byte; the+// mechanism exists for the 140K-character fence in #10769. Lines, not characters: the bounded cost+// is mounted elements, which track lines.+export const WINDOW_CAP_LINES = 2_000;++// Viewports of lookahead each way, matching `REACH_MARGIN`: the reader crosses into already+// coloured code rather than watching it arrive.+export const OVERSCAN_VIEWPORTS = 1;++// Slack before the window moves, in viewports. Without it one line of scroll re-renders both+// boundaries, the thrash that killed the earlier bidirectional gate.+export const HYSTERESIS_VIEWPORTS = 0.5;++export type WindowGeometry = {+ lineCount: number;+ /** MEASURED from the rendered block, never assumed. */+ lineHeight: number;+ contentTop: number;+ /** The fence's nearest scrolling ancestor, or the window. */+ viewportTop: number;+ viewportHeight: number;+ /** The window currently rendered, so an ordinary scroll can keep it. */+ previous: LineWindow | null;+ cap?: number;+};++const clamp = (value: number, low: number, high: number): number =>+ value < low ? low : value > high ? high : value;++// Arithmetic, not a measurement per line: reading 20,000 line boxes would cost more than the+// rendering this avoids.+const visibleRange = (geometry: WindowGeometry): LineWindow => {+ const { lineCount, lineHeight, contentTop, viewportTop, viewportHeight } = geometry;+ const top = (viewportTop - contentTop) / lineHeight;+ const bottom = (viewportTop + viewportHeight - contentTop) / lineHeight;+ return {+ first: clamp(Math.floor(top), 0, lineCount - 1),+ last: clamp(Math.ceil(bottom) - 1, 0, lineCount - 1),+ };+};++/**+ * Which lines carry token spans. `null` (every line) is both the small-fence answer and the answer+ * for untrustworthy geometry, so a zero line height degrades to today's rendering, never to an+ * arbitrary range. A wrong answer costs colour, never text.+ */+export const selectLineWindow = (geometry: WindowGeometry): LineWindow | null => {+ const cap = geometry.cap ?? WINDOW_CAP_LINES;+ const { lineCount, lineHeight, viewportHeight } = geometry;+ if (lineCount <= cap) return null;+ if (!(lineHeight > 0) || !(viewportHeight > 0)) return null;+ if (!Number.isFinite(geometry.contentTop) || !Number.isFinite(geometry.viewportTop)) {+ return null;+ }++ const visible = visibleRange(geometry);+ const linesPerViewport = Math.ceil(viewportHeight / lineHeight);++ // Checked against the VISIBLE range, not the overscanned one: overscan is a rendering margin,+ // and testing it would move the window on every scroll.+ const slack = Math.ceil(linesPerViewport * HYSTERESIS_VIEWPORTS);+ const previous = geometry.previous;+ if (+ previous !== null+ && previous.first <= Math.max(0, visible.first - slack)+ && previous.last >= Math.min(lineCount - 1, visible.last + slack)+ ) {+ return previous;+ }++ const overscan = linesPerViewport * OVERSCAN_VIEWPORTS;+ let first = clamp(visible.first - overscan, 0, lineCount - 1);+ let last = clamp(visible.last + overscan, 0, lineCount - 1);++ // The cap binds the window itself, or a zoomed-out print layout restores the cost it bounds.+ // Shrink from the END so lines the reader is heading towards outlive ones they passed.+ if (last - first + 1 > cap) {+ last = first + cap - 1;+ if (last < visible.last) {+ last = clamp(visible.last, 0, lineCount - 1);+ first = Math.max(0, last - cap + 1);+ }+ }++ return { first, last };+};++/** Is line `index` inside `window`? A `null` window highlights everything. */+export const lineIsWindowed = (window: LineWindow | null, index: number): boolean =>+ window === null || (index >= window.first && index <= window.last);++// Structurally typed rather than importing Shiki's `ThemedToken`, so a bundler-less test runner+// can load this module.+type LineToken = { content: string };++/**+ * A blank line is one line tall, not nothing: a `<span>` holding an empty text node has no line box,+ * so the fence would close up and everything below it would move. Streamdown special-cases the same+ * two shapes to a bare newline.+ */+export const isBlankLine = (line: readonly LineToken[]): boolean =>+ line.length === 0 || (line.length === 1 && line[0].content === "");++/**+ * A line's text from its TOKENS, never a source slice. The invariant the window rests on is that a+ * line shows the same characters on both sides of it; reading it back out of the tokens makes that+ * true by construction. A slice would not: Shiki drops the CR of a CRLF pair, so a line leaving the+ * window would gain a character (`code-plugin.ts` `completedEnd`, and the CRLF cases in+ * `code-plugin-incremental.test.ts`).+ */+export const plainLineText = (line: readonly LineToken[]): string => {+ let text = "";+ for (const token of line) text += token.content;+ return text;+};diff --git a/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.tsindex 01990b89c6b..e77066fe502 100644--- a/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts+++ b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts@@ -75,14 +75,43 @@ function openingFence(content: string): OpeningFence | null {* structure. Recognising the indent when opening the fence and then not removing it is the half of* the rule that shows: the reader copies the degraded block into a file and gets an* IndentationError from text their model never wrote. `extractHtmlFences` applies the same rule.+ *+ * REMOVED BY COLUMNS, NOT BY CHARACTERS, because a tab is not one column. CommonMark expands tabs+ * to a four-column tab stop when measuring indentation, so a tab opening a line of a one-space+ * indented fence spans columns 1 to 4 and loses only its first column: the line keeps three+ * spaces. Taking characters instead left the tab whole, so the body of an indented fence whose+ * code is tab-indented came out one tab too deep, and a settled fence now renders this text+ * directly rather than going through streamdown's parser. Checked against `micromark`: for+ * " ```js\\n\\tx\\n ```" it gives " x", for two spaces " x", for three " x".*/+const TAB_STOP = 4;+function stripIndent(body: string, indent: number): string {if (indent === 0 || body === "") return body;const lines = body.split("\n");for (let n = 0; n < lines.length; n += 1) {- let take = 0;- while (take < indent && lines[n][take] === " ") take += 1;- lines[n] = lines[n].slice(take);+ const line = lines[n];+ let column = 0;+ let at = 0;+ let carry = "";+ while (column < indent && at < line.length) {+ const ch = line[at];+ if (ch === " ") {+ column += 1;+ at += 1;+ continue;+ }+ if (ch !== "\t") break;+ column += TAB_STOP - (column % TAB_STOP);+ at += 1;+ if (column > indent) {+ // The tab straddles the boundary, so it is consumed whole and the columns beyond the+ // indent come back as spaces: the same result as expanding it and re-cutting.+ carry = " ".repeat(column - indent);+ break;+ }+ }+ lines[n] = carry + line.slice(at);}return lines.join("\n");}diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 09397f8b326..04651964f50 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -57,6 +57,7 @@ import {useCallback,useContext,useEffect,+ useLayoutEffect,useMemo,useRef,useState,@@ -69,11 +70,14 @@ import {} from "streamdown";import {DeferredFenceShell,+ FenceBody,+ type FenceTokens,fenceMode,trimmedLength,trimTrailingNewlines,useFenceReached,} from "./code-fence-defer";+import { markdownBlockFallback } from "./markdown-block-fallback";import { createCodePlugin } from "./code-plugin";import { withMathBlockMarker } from "./math-block-marker";import {@@ -309,15 +313,71 @@ const STREAMDOWN_ALLOWED_TAGS = {} satisfies NonNullable<StreamdownProps["allowedTags"]>;const COPY_RESET_MS = 2000;-const MERMAID_SOURCE_RE = /```mermaid\s*([\s\S]*?)```/i;const ACTION_PANEL_CLASS ="pointer-events-auto flex shrink-0 items-center gap-1";const ACTION_BUTTON_CLASS ="flex size-8 cursor-pointer items-center justify-center rounded-[10px] text-chat-icon-fg transition-all hover:bg-chat-icon-bg-hover hover:text-chat-icon-fg-hover disabled:cursor-not-allowed disabled:opacity-50";-function getMermaidSource(blockContent: string): string | null {- const source = blockContent.match(MERMAID_SOURCE_RE)?.[1]?.trim();- return source && source.length > 0 ? source : null;+/**+ * THE MERMAID FENCE IN THIS BLOCK, found with fence context.+ *+ * One walk answers both questions the renderer asks: whether a mermaid fence is still open (so an+ * incomplete reply shows the loading card), and where its body starts. Scanning lines with no+ * context made a `~~~mermaid` shown as EXAMPLE inside an outer fence look like a diagram, which+ * replaced the whole block with the loading card and gave ordinary code a diagram copy action.+ */+type MermaidFence =+ | { open: true }+ | { open: false; indent: string; body: string };++function findMermaidFence(blockContent: string): MermaidFence {+ const lines = blockContent.split("\n");+ let enclosing: { char: string; run: number } | null = null;+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index];+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);+ if (!match) continue;+ const [, marker, rest] = match;+ const isClose =+ rest.replace(/[\t ]*\r?$/, "") === "" && marker.length >= 3;+ if (enclosing === null) {+ if (marker[0] === "`" && rest.includes("`")) continue; // an info string may not hold a backtick+ if (/^[\t ]*mermaid\b/i.test(rest)) {+ const indent = /^( *)/.exec(line)?.[1] ?? "";+ const body = lines.slice(index + 1).join("\n");+ // The close is "at least as many" of the opener's own character, on its own line.+ const closeRe = new RegExp(`^ {0,3}${marker[0]}{${marker.length},}[\\t ]*\\r?$`, "m");+ const close = closeRe.exec(body);+ if (close === null) return { open: true };+ const raw = body.slice(0, close.index);+ const stripped = indent+ ? raw+ .split("\n")+ .map((l) => l.slice(Math.min(indent.length, /^ */.exec(l)?.[0].length ?? 0)))+ .join("\n")+ : raw;+ return { open: false, indent, body: stripped.replace(/[\t ]*\r?\n?$/, "") };+ }+ // A bare run at top level is an OPENER (an info string may be empty). Reading it as a close+ // made a four-backtick outer fence holding a nested mermaid example look like a diagram.+ enclosing = { char: marker[0], run: marker.length };+ } else if (marker[0] === enclosing.char && marker.length >= enclosing.run && isClose) {+ enclosing = null;+ }+ }+ return { open: false, indent: "", body: "" };+}++/** The diagram source for a walk already performed, so the block is not scanned twice. */+function mermaidSourceOf(blockContent: string, found: MermaidFence): string | null {+ if (found.open) return null;+ if (found.body.trim().length > 0) return found.body.trim();+ const fence = markdownBlockFallback(blockContent);+ if (fence.fenced && fence.language === "mermaid") {+ const source = fence.text.trim();+ return source.length > 0 ? source : null;+ }+ return null;}function getCodeFilename(language: string | null) {@@ -529,8 +589,13 @@ function StreamdownBlockContent(props: BlockProps) {const messageHasRenderableRenderHtmlTool = useContext(RenderHtmlToolPresenceContext,);- const hasMermaidFence = props.content.includes("```mermaid");- const mermaidSource = getMermaidSource(props.content);+ // ONE walk, both answers. `findMermaidFence` splits the block and scans every line, and asking+ // the two questions separately walked it twice on every render of every block. Measured on a+ // 3,000 line fence: 0.118 ms per walk, so the redundant one cost 0.092 ms per render, about+ // 5.5 ms per second while streaming at 60 fps.+ const mermaidFence = findMermaidFence(props.content);+ const hasMermaidFence = mermaidFence.open;+ const mermaidSource = mermaidSourceOf(props.content, mermaidFence);const codeFence = getCodeFence(props.content);if (props.isIncomplete && hasMermaidFence) {@@ -613,7 +678,6 @@ function StreamdownBlockContent(props: BlockProps) {return (<><FenceBlock- blockProps={blockProps}isIncomplete={props.isIncomplete}language={codeFence.language}source={codeFence.source}@@ -633,6 +697,43 @@ function StreamdownBlockContent(props: BlockProps) {* boundary existed, 0 copy and 0 download buttons on both. Guarding it keeps the failure inside the renderer* boundary, so the completed block mounts `FenceBlock` normally and keeps its controls.*/+ /*+ * The streaming fence, which used to fall through to the bare `Block`: `getCodeFence` needs a+ * close, so an arriving fence never reached `FenceBlock`. That is the route #10769 measured as+ * unusable and #10779 fixed by giving up the colours. `FenceBody` is the same per-line rendering+ * the completed fence gets, so the block does not change shape when its delimiter lands.+ * `markdownBlockFallback`, not `getCodeFence`, because it recognises every CommonMark fence.+ */+ /*+ * RECOGNISED FORMS STAY ON THE BOUNDED RENDERER AT COMPLETION TOO. `getCodeFence` does not match+ * tildes, four or more backticks or up to three spaces of indent, so a completed fence on those+ * forms used to fall to streamdown's whole-token `Block` and remount every span -- and a stopped+ * reply never settles. NOT routed through `FenceBlock`: that branch also owns the reach latch,+ * the action bar and the mode switch, which are wired to the narrower form on purpose.+ */+ const settledFence = props.isIncomplete ? null : markdownBlockFallback(props.content);+ if (settledFence?.fenced && !(settledFence.language === "mermaid" && mermaidSource)) {+ return (+ <StreamingFenceBlock+ isIncomplete={false}+ language={settledFence.language}+ source={settledFence.text}+ />+ );+ }++ if (props.isIncomplete) {+ const openFence = markdownBlockFallback(props.content);+ if (openFence.fenced) {+ return (+ <StreamingFenceBlock+ language={openFence.language}+ source={openFence.text}+ />+ );+ }+ }+return (<MarkdownRendererBoundaryfallback={<MarkdownBlockFallbackView content={props.content} />}@@ -642,19 +743,105 @@ function StreamdownBlockContent(props: BlockProps) {);}+/**+ * This fence's tokens, or `null` while its grammar chunk is still loading.+ *+ * The same shape streamdown's own `HighlightedCodeBlockBody` uses -- ask the plugin, take the+ * synchronous answer when the grammar is already in hand, take the callback's when it is not --+ * because `latchNow` in `code-fence-defer.tsx` is built around exactly that shape. Its nested+ * `flushSync` exists to make React run this passive effect inside the task that latched the fence,+ * so a jump or a print swaps straight to a COLOURED block rather than painting a plain one first.+ *+ * The guard on `wanted` is what a streamed fence needs and a settled one does not: the callback for+ * chunk N can arrive after chunk N+1 has already been rendered, and letting it through would walk+ * the fence backwards by a frame.+ */+function useFenceTokens(+ source: string,+ languageToken: string | null,+ enabled: boolean,+): FenceTokens | null {+ const [tokens, setTokens] = useState<FenceTokens | null>(null);+ const wanted = useRef("");+ /*+ * ONE effect, and a layout one. This was two -- a passive effect for the result and the+ * callback, plus a layout effect so an already-cached fence is coloured before its first paint.+ * Both called `code.highlight` with the same inputs on the same deps, and the plugin's+ * throttled `approximateResult` returns a FRESH object each call, so both `setTokens` were+ * observable and every source change scheduled a second render of the whole body: exactly the+ * work this branch exists to remove. A layout effect gets the before-paint colour on its own,+ * so the passive one bought nothing.+ */+ useLayoutEffect(() => {+ if (!enabled) return;+ const body = trimTrailingNewlines(source);+ wanted.current = body;+ const settled = code.highlight(+ {+ code: body,+ language: (languageToken ?? "text") as never,+ themes: STREAMDOWN_SHIKI_THEME,+ },+ (late) => {+ if (wanted.current === body) setTokens(late);+ },+ );+ // `settled === null` means the plugin caught a tokenization error; keeping the previous+ // tokens would show an older, shorter body. The callback restores them if it succeeds later.+ setTokens(settled ?? null);+ }, [enabled, source, languageToken]);+ return tokens;+}++/**+ * A fence that is still being written.+ *+ * No reach latch and no deferral: the block being written is the one the reader is looking at, so+ * it is highlighted from its first character, which is the rule `useFenceReached` already spells+ * for a streaming fence. No action bar either, because the bare `Block` this replaces never had+ * one and a performance change is the wrong place to add controls.+ */+function StreamingFenceBlock({+ language,+ source,+ isIncomplete = true,+}: {+ language: string | null;+ source: string;+ isIncomplete?: boolean;+}) {+ const languageToken = language?.trim().split(/\s+/)[0] || null;+ const tokens = useFenceTokens(source, languageToken, true);+ return (+ <MarkdownRendererBoundary+ fallback={<DeferredFenceShell language={languageToken} source={source} />}+ >+ <FenceBody+ isIncomplete={isIncomplete}+ language={languageToken}+ result={tokens}+ source={source}+ windowing={fenceMode() === "window"}+ />+ </MarkdownRendererBoundary>+ );+}+/** 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.+ * branch rendered before: the same `relative isolate` wrapper, the same action bar, and inside them a body+ * whose elements and classes are streamdown's own. 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.+ * `<Block>` is gone from this branch. It maps the WHOLE token array on every render and memoizes on the+ * identity of a result object the plugin rebuilds every frame, so the fence re-rendered end to end sixty+ * times a second. See `FenceBody` in `code-fence-defer.tsx` for what replaced it and why.*/function FenceBlock({- blockProps,isIncomplete,language,source,}: {- blockProps: BlockProps;isIncomplete: boolean | undefined;language: string | null;source: string;@@ -663,18 +850,11 @@ function FenceBlock({const mode = fenceMode();/*- * 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.- */+ * `CODE_FENCE_RE` claims only unindented triple-backtick fences. Tildes, four or more backticks+ * and indented fences do not reach THIS branch; they are picked up by the settled-fence rung+ * below. The regex is deliberately not widened: it also decides the SVG and HTML-artifact paths,+ * so widening it would add an artifact path and a copy overlay to blocks that lack them today.+ */// `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@@ -714,6 +894,11 @@ function FenceBlock({// 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.+ // Asked for only once the fence is reached, so a deferred fence still tokenizes nothing. The+ // latch calls `warm(true)` synchronously on the way in, so this is a cache hit rather than the+ // first tokenization of the body.+ const tokens = useFenceTokens(source, languageToken, reached);+const pretokenize = mode === "tokenize" && !reached;useEffect(() => {if (!pretokenize) return;@@ -744,7 +929,13 @@ function FenceBlock({}>{reached ? (- <Block {...blockProps} />+ <FenceBody+ isIncomplete={isIncomplete}+ language={languageToken}+ result={tokens}+ source={source}+ windowing={mode === "window"}+ />) : (<DeferredFenceShell language={languageToken} source={source} />)}diff --git a/studio/frontend/src/features/chat/artifacts/html-fences.ts b/studio/frontend/src/features/chat/artifacts/html-fences.tsindex 38fdee9fd10..3cf18901e11 100644--- a/studio/frontend/src/features/chat/artifacts/html-fences.ts+++ b/studio/frontend/src/features/chat/artifacts/html-fences.ts@@ -11,7 +11,19 @@ export type CodeFence = {};// Matches one fenced block spanning the whole string (one pre-split block).-export const CODE_FENCE_RE = /^```([^\r\n`]*)\r?\n([\s\S]*?)\r?\n?```$/;+//+// THE CLOSE IS THREE OR MORE, NOT EXACTLY THREE. CommonMark wants the closing run to be "at least+// as many" as the opener, and a model closing a fence whose body holds three backticks writes four.+// `{3}` matched such a line by its LAST three and handed the surplus to `source` (`x = 1\n\``); a+// bare lazy `+?` is the other half of the rule and accepts a one- or two-backtick run as a close.+// The close needs a LINE BREAK before it unless the body is empty, so the alternation is outside+// the body group: without that, `` ```\nfoo```` `` matched with the run eaten and gave `foo` where+// CommonMark gives `foo```` `. A fence that closes on the same line it opens has no body at all.+//+// Against `micromark`: `{3}` and `+?` each disagreed on 54 of 540 shapes; the shape above was this+// rule's one regression, found by review and now a row in the test.+export const CODE_FENCE_RE =+ /^```([^\r\n`]*)\r?\n(?:([\s\S]*?)\r?\n`{3,}|`{3,})$/;export type ToolCallPartLike = {type?: string;@@ -47,10 +59,21 @@ export function getCodeFence(blockContent: string): CodeFence | null {if (!match) {return null;}+ // A block can hold MORE than one fence (a reply with a footnote is one block) and the greedy body+ // would then span both, prose included. CommonMark closes a fence at the FIRST bare run on its+ // own line, so a body that still contains one means the real close came earlier and this match+ // ran past it: `` ```md / A: / ``` / B / ``` `` is a fence holding `A:`, the paragraph `B` and an+ // empty fence, not one fence holding ``A:\n```\nB``. Requiring a following OPENER missed that,+ // and `B` is prose. A delimiter-shaped line that is NOT bare (it carries an info string) is+ // ordinary code and still allowed, which is what lets a tutorial quote ```` ```js ```` inline.+ if (/^ {0,3}`{3,}[\t ]*\r?$/m.test(match[2])) {+ return null;+ }return {language: match[1]?.trim() || null,- source: match[2],+ // Absent only for a fence that closes on the line after it opens.+ source: match[2] ?? "",};}diff --git a/studio/frontend/tests/code-fence-body.test.ts b/studio/frontend/tests/code-fence-body.test.tsnew file mode 100644index 00000000000..501664626f8--- /dev/null+++ b/studio/frontend/tests/code-fence-body.test.ts@@ -0,0 +1,286 @@+// 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 test from "node:test";++import {+ isBlankLine,+ plainLineText,+} from "../src/components/assistant-ui/code-fence-window.ts";++import { readSrc } from "./helpers/kit.ts";++/**+ * The fence body that replaced streamdown's `Block`. What is RUN is the part deciding what+ * characters a line shows; the `.tsx` side is pinned by regex over source, since the runner cannot+ * load JSX.+ */++const DEFER = readSrc("components/assistant-ui/code-fence-defer.tsx");+const MARKDOWN_TEXT = readSrc("components/assistant-ui/markdown-text.tsx");++test("a line shows the same characters inside the window and outside it", () => {+ const line = [+ { content: "const " },+ { content: "x" },+ { content: " = " },+ { content: "1;" },+ ];+ assert.equal(plainLineText(line), "const x = 1;");+});++test("the plain form is the tokens, never a slice of the source", () => {+ // Shiki drops the CR of a CRLF pair, so a source slice would make a line gain a character on+ // leaving the window.+ assert.equal(plainLineText([{ content: "x = 1" }]), "x = 1");+ assert.ok(+ !/source\.slice|split\(["'`]\\n["'`]\)/.test(+ DEFER.slice(DEFER.indexOf("const FenceLine = memo")),+ ),+ "the line renderer must not reach for the source",+ );+});++test("a blank line is one line tall, not nothing", () => {+ // An empty text node has no line box, so the fence would close up and everything below it moves.+ assert.equal(isBlankLine([]), true);+ assert.equal(isBlankLine([{ content: "" }]), true);+ assert.equal(isBlankLine([{ content: " " }]), false);+ assert.equal(isBlankLine([{ content: "" }, { content: "" }]), false);+ assert.ok(+ /if \(isBlankLine\(line\)\) \{\s*return <span className=\{LINE_CLASS\}>\{"\\n"\}<\/span>;/+ .test(DEFER),+ "a blank line must render the newline streamdown renders for it",+ );+});++test("the line component is memoized, which is the whole point of it", () => {+ // A committed line's identity is already stable, so without `memo` a one-character growth still+ // reconciles every line: the cost this change removes.+ assert.ok(+ /const FenceLine = memo\(function FenceLine\(/.test(DEFER),+ "FenceLine must be memoized",+ );+ assert.ok(+ !/memo\(\s*function FenceLine[\s\S]*?\},\s*\(/.test(DEFER),+ "and on the default shallow comparison: a custom comparator here would have to know that a " ++ "committed line is immutable, which is a second place for that to stop being true",+ );+});++test("the fence branch no longer renders streamdown's Block", () => {+ const from = MARKDOWN_TEXT.indexOf("function FenceBlock(");+ const to = MARKDOWN_TEXT.indexOf("const StreamdownBlock = memo(", from);+ assert.ok(from > 0 && to > from, "FenceBlock still bounds a branch of its own");+ const body = MARKDOWN_TEXT.slice(from, to);+ // Comment lines stripped: this branch still EXPLAINS `<Block>` at length, and should.+ const code = body.replace(/^\s*(?:\/\/|\/?\*).*$/gm, "");+ assert.ok(+ !/<Block\b/.test(code),+ "the reached fence must render FenceBody, not Block",+ );+ assert.ok(+ /<FenceBody[\s\S]{0,80}language=\{languageToken\}/.test(code),+ "and it must be handed the parsed language token, not the raw info string",+ );+});++test("a streaming open fence is highlighted rather than shown plain", () => {+ assert.ok(+ /if \(props\.isIncomplete\) \{\s*const openFence = markdownBlockFallback\(props\.content\);\s*if \(openFence\.fenced\) \{\s*return \(\s*<StreamingFenceBlock/m+ .test(MARKDOWN_TEXT),+ "an open fence must leave the bare Block route",+ );+ const streaming = MARKDOWN_TEXT.slice(+ MARKDOWN_TEXT.indexOf("function StreamingFenceBlock("),+ );+ assert.ok(+ /<FenceBody[\s\S]{0,200}result=\{tokens\}/.test(streaming),+ "and it must render the tokens, not a plain shell: keeping the highlighting while it streams " ++ "is the difference between this and the change that was rejected",+ );+});++test("a completed fence on a non-``` form keeps the bounded renderer", () => {+ // A completed tilde / four-backtick / indented fence used to fall to `Block` and remount every+ // span; a stopped reply takes the same route.+ assert.ok(+ /const settledFence = props\.isIncomplete \? null : markdownBlockFallback\(props\.content\);\s*if \(settledFence\?\.fenced/.test(+ MARKDOWN_TEXT,+ ),+ "a completed fence must be recognised by the CommonMark-complete scanner",+ );+ const settled = MARKDOWN_TEXT.slice(MARKDOWN_TEXT.indexOf("const settledFence ="));+ const branch = settled.slice(0, settled.indexOf("if (props.isIncomplete)"));+ assert.ok(+ /<StreamingFenceBlock[\s\S]{0,120}isIncomplete=\{false\}[\s\S]{0,120}settledFence\.language/.test(+ branch,+ ),+ "and it must render the per-line body rather than Block, or the spans remount",+ );+ // Not `FenceBlock`: that branch also owns the reach latch, the action bar and the mode switch.+ assert.ok(+ !/<FenceBlock[\s\S]{0,200}settledFence/.test(MARKDOWN_TEXT),+ "widening FenceBlock would add controls and artifact paths to blocks that do not have them",+ );+});++test("markdownBlockFallback is what recognises the open fence, not getCodeFence", () => {+ // `getCodeFence` claims only unindented triple backticks; a fence this route misses goes back to+ // the renderer that cannot afford it.+ assert.ok(+ MARKDOWN_TEXT.includes(+ 'import { markdownBlockFallback } from "./markdown-block-fallback";',+ ),+ "the streaming route must use the CommonMark-complete scanner",+ );+});++test("the window decision is not reimplemented in the component", () => {+ assert.ok(+ /import \{[\s\S]*?selectLineWindow,[\s\S]*?\} from "\.\/code-fence-window";/.test(DEFER),+ "the component must consume the decision",+ );+ assert.ok(+ !/WINDOW_CAP_LINES\s*=|OVERSCAN_VIEWPORTS\s*=|HYSTERESIS_VIEWPORTS\s*=/.test(DEFER),+ "no copy of the window constants may live here as well",+ );+});++test("the text is never removed from the document, only its colour", () => {+ // Why this is not virtualization: the text never leaves the document, so find-in-page, copy and+ // print are untouched (`progressive-mount-controller.ts`, and the `content-visibility` ban).+ const body = DEFER.slice(DEFER.indexOf("export const FenceBody = memo("));+ assert.ok(+ /tokens\.map\(\(line, index\) => \(/.test(body),+ "every line must still be rendered; only what is INSIDE a line changes",+ );+ assert.ok(+ !/contentVisibility:\s*"hidden"|display:\s*"none"/.test(body),+ "no line may be hidden from the engine",+ );+});++test("one scroll listener serves every windowed fence on the page", () => {+ // A listener per fence reads layout per fence per scroll, costing more than it saves.+ assert.ok(+ /const windowedFences = new Set<\(\) => void>\(\);/.test(DEFER),+ "the registry must be shared",+ );+ assert.ok(+ /document\.addEventListener\("scroll", scheduleRemeasure, \{\s*capture: true,\s*passive: true,\s*\}\);/+ .test(DEFER),+ "capturing, so the nested reasoning pane's scroller is seen too, and passive",+ );+ assert.ok(+ /windowFrame = requestAnimationFrame\(remeasureWindows\);/.test(DEFER),+ "and coalesced into a frame: scroll fires faster than the screen updates",+ );+});++test("the scrolling ancestor is resolved from outside the code block", () => {+ // A code block carries `overflow-x: auto`, which makes `overflow-y` compute to `auto` as well,+ // so walking up from the <code> is one scrollHeight away from rooting the whole calculation+ // inside the fence's own horizontal scroller.+ assert.ok(+ /const scroller = scrollerOf\(outer\);/.test(DEFER),+ "resolve from the fence's outermost element, not from the code element",+ );+});++test("the body reproduces streamdown's language class and incomplete flag", () => {+ // Both were MEASURED missing against the merge base, on the same scene, and neither has a+ // reader in the tree today. That is what makes them worth pinning rather than shrugging at: a+ // published rendering contract with no current consumer is exactly the kind of thing that goes+ // quietly and is found by a user stylesheet months later.+ const body = DEFER.slice(DEFER.indexOf("export const FenceBody = memo("));+ assert.ok(+ /const languageClass = language === null \? null : `language-\$\{language\}`;/.test(DEFER),+ "the first word of the info string, which is what remark-rehype emits",+ );+ assert.ok(+ /className=\{joinClasses\(\s*languageClass,/.test(body),+ "the body div carries it, as streamdown's does",+ );+ assert.ok(+ /<pre className=\{joinClasses\(languageClass, PRE_CLASS\)\}/.test(body),+ "and so does the pre",+ );+ assert.ok(+ /data-incomplete=\{isIncomplete \|\| undefined\}/.test(body),+ "an open fence carries data-incomplete, and a settled one carries no attribute at all",+ );+});++test("a print colours the whole fence, and the window comes back afterwards", () => {+ // MEASURED: a 3,000 line fence printed with 342 spans against the 23,139 the merge base+ // printed. `upgradeEverythingForPrint` makes this argument for a deferred fence already; the+ // line window reintroduced the same defect one level down.+ assert.ok(+ /let printing = false;/.test(DEFER),+ "the print state has to be module-global: a print is a document-wide event",+ );+ assert.ok(+ /window\.addEventListener\("afterprint", \(\) => setPrinting\(false\)\);/.test(DEFER),+ "and it must revert, or one Ctrl+P un-windows every huge fence for the life of the tab. " ++ "Unlike the reach latch this costs nothing to undo, because the tokens are already cached",+ );+ assert.ok(+ /if \(event\.matches\) \{\s*upgradeEverythingForPrint\(\);\s*setPrinting\(true\);\s*\} else \{\s*setPrinting\(false\);\s*\}/+ .test(DEFER),+ "both doors: beforeprint for Ctrl+P, the media query for page.pdf() and devtools emulation",+ );+ assert.ok(+ /flushSync\(remeasureWindows\);/.test(DEFER),+ "synchronously, because there is no next paint before the print snapshot",+ );+ assert.ok(+ /if \(printing\) \{\s*if \(current\.current === null\) return;/.test(DEFER),+ "and the measurement has to honour it",+ );+});++test("a block is scanned for a mermaid fence once per render, not twice", () => {+ // `findMermaidFence` splits the block and regex-scans every line. Asking "is it open" and "what+ // is the source" as two calls walked it twice on every render of every block, on the hot path+ // this change exists to shorten. Measured on a 3,000 line fence: 0.118 ms per walk, so the+ // redundant one cost 0.092 ms per render, about 5.5 ms per second at 60 fps.+ const body = MARKDOWN_TEXT.slice(MARKDOWN_TEXT.indexOf("function StreamdownBlockContent("));+ const walks = body.match(/findMermaidFence\(props\.content\)/g) ?? [];+ assert.equal(walks.length, 1, "the walk must happen once and both answers come off it");+ assert.ok(+ !/isMermaidFenceOpener\(/.test(MARKDOWN_TEXT),+ "the second walk's wrapper must be gone, not merely unused",+ );+ assert.ok(+ /const mermaidSource = mermaidSourceOf\(props\.content, mermaidFence\);/.test(body),+ "the source must be derived from the walk that already ran",+ );+});++test("a fence source is highlighted once per revision, not twice", () => {+ // This was a passive effect and a layout effect, same inputs and same deps. `code.highlight`+ // caches, but the plugin's throttled `approximateResult` hands back a FRESH object each call, so+ // both setters were observable and every source change scheduled a second render of the body.+ const hook = MARKDOWN_TEXT.slice(+ MARKDOWN_TEXT.indexOf("function useFenceTokens("),+ MARKDOWN_TEXT.indexOf("function StreamingFenceBlock("),+ );+ assert.ok(hook.length > 0, "useFenceTokens still bounds a hook of its own");+ assert.equal(+ (hook.match(/code\.highlight\(/g) ?? []).length,+ 1,+ "one highlight call per revision",+ );+ assert.equal(+ (hook.match(/useLayoutEffect\(|useEffect\(/g) ?? []).length,+ 1,+ "and one effect, which must be the LAYOUT one so an already-cached fence is coloured before " ++ "its first paint",+ );+ assert.ok(+ /useLayoutEffect\(\(\) => \{/.test(hook),+ "the surviving effect runs before paint",+ );+});diff --git a/studio/frontend/tests/code-fence-classifier-agreement.test.ts b/studio/frontend/tests/code-fence-classifier-agreement.test.tsnew file mode 100644index 00000000000..902bf1cbe24--- /dev/null+++ b/studio/frontend/tests/code-fence-classifier-agreement.test.ts@@ -0,0 +1,188 @@+// 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 test from "node:test";++import { getCodeFence } from "../src/features/chat/artifacts/html-fences.ts";+import { markdownBlockFallback } from "../src/components/assistant-ui/markdown-block-fallback.ts";++/**+ * The two classifiers have to agree about the same reply.+ *+ * A block is owned by `markdownBlockFallback` while it arrives and by `getCodeFence` the instant it+ * closes. Since `FenceBody` renders the body text each reports, rather than re-parsing the block as+ * streamdown's `Block` did, a disagreement is a block whose contents change under the reader at+ * that moment. `code-fence-close-run.test.ts` pins each against CommonMark; this pins them against+ * EACH OTHER, which neither file catches alone.+ *+ * Fences `getCodeFence` declines by design are skipped: there is no second opinion to compare.+ */++const BODIES = [+ "x = 1",+ "a\nb",+ "",+ "foo `",+ "foo ``",+ "const a = `x`;",+ " indented",+ "}\n",+];+const LANGS = ["", "ts", "typescript", "python startLine=10"];+const CLOSE_RUNS = [3, 4, 5, 6];++/** The first word, which is what both routes hand to the highlighter as the grammar. */+const grammarOf = (info: string | null): string | null =>+ info?.trim().split(/\s+/)[0] || null;++test("a fence's body is the same text while it streams and once it closes", () => {+ let checked = 0;+ for (const lang of LANGS) {+ for (const body of BODIES) {+ for (const closeRun of CLOSE_RUNS) {+ const opening = "```" + lang + "\n";+ // Exactly the two strings one growing block passes through.+ const streaming = opening + body;+ const closed = `${opening}${body}\n${"`".repeat(closeRun)}`;++ const before = markdownBlockFallback(streaming);+ const after = getCodeFence(closed);+ assert.ok(+ before.fenced,+ `${JSON.stringify(streaming)} must be recognised as a fence while it streams, or the ` ++ "block falls back to the renderer this change exists to keep it away from",+ );+ if (after === null) continue;+ checked++;+ assert.equal(+ before.text,+ after.source,+ "the body a reader is watching must not change when the closing delimiter lands " ++ `(${JSON.stringify(closed)})`,+ );+ }+ }+ }+ assert.ok(checked > 50, `expected the table to exercise the handover, got ${checked}`);+});++test("the grammar does not change when the closing delimiter lands", () => {+ // `getCodeFence` hands back the WHOLE info string and `markdownBlockFallback` hands back the+ // first word, so these two are not equal and are not supposed to be. What must match is what+ // each route actually highlights with, which is the first word of either.+ for (const info of ["", "ts", "python startLine=10", "typescript extra bits"]) {+ const streaming = "```" + info + "\nx = 1";+ const closed = "```" + info + "\nx = 1\n```";+ const before = markdownBlockFallback(streaming);+ const after = getCodeFence(closed);+ assert.ok(after, "closed fence must parse");+ assert.equal(+ grammarOf(before.language),+ grammarOf(after.language),+ `the highlighter's grammar must survive the handover (info ${JSON.stringify(info)})`,+ );+ }+});++test("a closing run longer than the opener agrees across the handover", () => {+ // The specific shape that was broken, kept as its own row so a regression names itself rather+ // than arriving as one failure among a hundred table entries.+ for (const closeRun of [4, 5, 6]) {+ const closed = "```python\nx = 1\n" + "`".repeat(closeRun);+ const after = getCodeFence(closed);+ assert.equal(after?.source, "x = 1", `a ${closeRun}-backtick close must not leak delimiters`);+ assert.equal(+ markdownBlockFallback("```python\nx = 1").text,+ after?.source,+ "and the streaming scanner must already have said the same thing",+ );+ }+});++test("a block holding more than one fence is claimed by neither classifier", () => {+ /*+ * CommonMark closes a fence at the FIRST bare run on its own line; a match running past one has+ * swallowed the close, the prose after it and the next opener, and `FenceBody` renders all of+ * that as the reader's code. Expectations read off `micromark`'s HTML, not off this file: it+ * makes "```md\nA:\n```\nB\n```" a fence holding `A:`, a paragraph `B`, and an empty fence.+ */+ for (const block of [+ "```md\nA:\n```\nB\n```",+ "```js\ncode\n```\n```",+ "```md\nUse this:\n```js\nx\n```\nDone.\n```",+ "```js\ncode\n```\n\nprose\n\n```py\nmore\n```",+ ]) {+ assert.equal(+ getCodeFence(block),+ null,+ `a multi-fence block is not one fence: ${JSON.stringify(block)}`,+ );+ assert.equal(+ markdownBlockFallback(block).fenced,+ false,+ `and the streaming scanner must say the same: ${JSON.stringify(block)}`,+ );+ }+});++test("a delimiter line that carries an info string is still code", () => {+ // The other side of the rule: an info-carrying run is not a close, so these stay single fences.+ assert.equal(+ getCodeFence("```js\nconst s = `x`;\n```")?.source,+ "const s = `x`;",+ );+ assert.equal(getCodeFence("```\nfoo `\n```")?.source, "foo `");+ assert.equal(getCodeFence("```\nfoo ``\n```")?.source, "foo ``");+ // A closing run longer than the opener still closes, and the body keeps its own backticks.+ assert.equal(getCodeFence("```python\nx = 1\n`````")?.source, "x = 1");+});++test("a run too short to close leaves the block streaming on both routes", () => {+ // A stream that has written only its first delimiter backtick must not read as closed.+ for (const short of ["`", "``"]) {+ const text = `\`\`\`python\nx = 1\n${short}`;+ assert.equal(+ getCodeFence(text),+ null,+ `${JSON.stringify(short)} is code, not a closing delimiter`,+ );+ assert.equal(+ markdownBlockFallback(text).fenced,+ true,+ "and the block is still an open fence, so it keeps streaming",+ );+ }+});++test("an indented fence loses its indentation by COLUMNS, so a tab is not one character", () => {+ /*+ * CommonMark removes the opener's indentation from each content line by COLUMN, expanding tabs+ * to a four-column tab stop. A tab opening a line of a one-space indented fence therefore spans+ * columns 1 to 4 and loses only its first column, leaving three spaces. Stripping characters+ * left the tab whole and the code came out a tab too deep, and the settled-fence rung renders+ * this text directly instead of going through streamdown's parser, so it reaches the screen and+ * the clipboard.+ *+ * Every expectation is `micromark`'s, read off its HTML.+ */+ const rows: [string, string][] = [+ [" ```js\n\tx\n ```", " x"],+ [" ```js\n\tx\n ```", " x"],+ [" ```js\n\tx\n ```", " x"],+ // Unindented: nothing is removed, so the tab survives whole.+ ["```js\n\tx\n```", "\tx"],+ // A tab that does NOT straddle the boundary is consumed with no spaces handed back.+ [" ```js\n \tx\n ```", " x"],+ // Spaces behave as before.+ [" ```js\n x\n ```", " x"],+ [" ```js\n x\n ```", "x"],+ ];+ for (const [block, expected] of rows) {+ assert.equal(+ markdownBlockFallback(block).text,+ expected,+ `indentation must match CommonMark for ${JSON.stringify(block)}`,+ );+ }+});diff --git a/studio/frontend/tests/code-fence-close-run.test.ts b/studio/frontend/tests/code-fence-close-run.test.tsnew file mode 100644index 00000000000..47523882e5c--- /dev/null+++ b/studio/frontend/tests/code-fence-close-run.test.ts@@ -0,0 +1,145 @@+// 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 test from "node:test";++import { getCodeFence } from "../src/features/chat/artifacts/html-fences.ts";++/**+ * WHAT A CLOSING FENCE IS ALLOWED TO LOOK LIKE.+ *+ * CommonMark 0.31.2: the close uses the same character and "at least as many" of it as the opener,+ * so a model closing a fence whose body holds three backticks writes four. `{3}` matched that by+ * its LAST three and handed the surplus to `source`; a bare lazy `+?` is the other half of the rule+ * and accepts a one- or two-backtick run as a close, deleting real code. The opener is fixed at+ * three, so the close is `{3,}`.+ *+ * Each row names the answer `micromark` gives, so the expectation is CommonMark's and not this+ * file's.+ */++/** The code text `micromark` produces for a whole-block fence, with its trailing break removed. */+const commonmarkSource = (markdown: string): string => {+ // Read out of `micromark(markdown)` directly: the runner has no HTML parser, and a second parser+ // would be a second thing to disagree.+ const expected: Record<string, string> = {+ "```python\nx = 1\n```\n": "x = 1",+ "```python\nx = 1\n````\n": "x = 1",+ "```python\nx = 1\n`````\n": "x = 1",+ "```python\nx = 1\n``````\n": "x = 1",+ "```python\nx = 1\n```": "x = 1",+ "```python\nx = 1\n````": "x = 1",+ "```python\na = 1\nb = 2\n````\n": "a = 1\nb = 2",+ "```python\n\n\n````\n": "\n",+ "```python\n````\n": "",+ "```python\n```\n": "",+ "```python startLine=10\nx = 1\n````\n": "x = 1",+ "```\nfoo `\n```\n": "foo `",+ "```\nfoo ``\n```\n": "foo ``",+ "```python\r\nx = 1\r\n````\r\n": "x = 1",+ };+ return expected[markdown];+};++test("every closing run a model writes yields the body CommonMark gives it", () => {+ for (const [markdown, expected] of Object.entries({+ "```python\nx = 1\n```\n": "x = 1",+ "```python\nx = 1\n````\n": "x = 1",+ "```python\nx = 1\n`````\n": "x = 1",+ "```python\nx = 1\n``````\n": "x = 1",+ "```python\nx = 1\n```": "x = 1",+ "```python\nx = 1\n````": "x = 1",+ "```python\na = 1\nb = 2\n````\n": "a = 1\nb = 2",+ "```python\n\n\n````\n": "\n",+ "```python\n````\n": "",+ "```python\n```\n": "",+ "```python startLine=10\nx = 1\n````\n": "x = 1",+ "```\nfoo `\n```\n": "foo `",+ "```\nfoo ``\n```\n": "foo ``",+ "```python\r\nx = 1\r\n````\r\n": "x = 1",+ })) {+ const fence = getCodeFence(markdown);+ assert.ok(fence, `${JSON.stringify(markdown)} must still parse as a fence`);+ assert.equal(+ fence.source,+ expected,+ `the surplus delimiter of a longer closing run must not reach source (${JSON.stringify(markdown)})`,+ );+ assert.equal(+ fence.source,+ commonmarkSource(markdown),+ `source must be what CommonMark says it is (${JSON.stringify(markdown)})`,+ );+ }+});++test("a body's OWN trailing backticks survive", () => {+ // A run the BODY owns is code, not a delimiter, at both fence lengths.+ assert.equal(getCodeFence("```\nfoo `\n```\n")?.source, "foo `");+ assert.equal(getCodeFence("```\nfoo ``\n```\n")?.source, "foo ``");+ // Only the close's own run is eaten; anything shorter before it is the body's.+ assert.equal(+ getCodeFence("```\nfoo `````\n`````\n")?.source,+ "foo `````",+ "a body line of backticks is code when the closing run is longer",+ );+});++test("the language tag and the block-level shapes are unchanged", () => {+ assert.equal(getCodeFence("```python\nx = 1\n```\n")?.language, "python");+ assert.equal(+ getCodeFence("```python startLine=10\nx = 1\n````\n")?.language,+ "python startLine=10",+ "the whole info string is still handed back; the caller takes its first word",+ );+ assert.equal(getCodeFence("~~~python\nx = 1\n~~~\n"), null, "tildes are not this regex's form");+ assert.equal(getCodeFence(" ```python\n x = 1\n ```\n"), null, "nor is an indented fence");+ assert.equal(+ getCodeFence("```python\nx = 1"),+ null,+ "an open fence has no close, which is what routes it to the streaming branch",+ );+ assert.equal(getCodeFence("plain prose"), null);+});++test("the close is at least three, not exactly three", () => {+ // The regression in one row: `{3}` matched the last three of a four-backtick close.+ const four = getCodeFence("```python\nx = 1\n````\n");+ assert.equal(four?.source, "x = 1");+ assert.ok(+ !/```$/m.test(four?.source ?? ""),+ "no delimiter may be left inside the body",+ );+ const five = getCodeFence("```python\nx = 1\n`````\n");+ assert.equal(five?.source, "x = 1");+});++test("a run with no line break before it does not close the fence", () => {+ // A close needs a LINE BREAK before it unless the body is empty. Without one, a body ending in a+ // run of backticks had that run eaten: `` ```\nfoo```` `` returned `foo` where CommonMark keeps+ // `foo```` `. Such a block is not closed, so it must be declined and left to the streaming route.+ assert.equal(getCodeFence("```\nfoo````"), null);+ assert.equal(getCodeFence("```\nfoo```"), null);+ assert.equal(getCodeFence("```python\n````")?.source, "", "an empty fence still closes");+});++test("a run shorter than three does not close the fence", () => {+ // A short run is code, so the block is still open and the collapse must decline it.+ for (const short of ["`", "``"]) {+ const markdown = `\`\`\`python\nx = 1\n${short}`;+ assert.equal(+ getCodeFence(markdown),+ null,+ `${JSON.stringify(markdown)} is not a closed fence; the short run is code, not a delimiter`,+ );+ }+ assert.equal(+ getCodeFence("```python\nx = 1\n`\n`"),+ null,+ "two separate one-backtick lines are still not a close",+ );+ // The same run one line higher is a body line, and must survive both a short and a long close.+ assert.equal(getCodeFence("```\nfoo `\n```\n")?.source, "foo `");+ assert.equal(getCodeFence("```\nfoo ``\n```\n")?.source, "foo ``");+});diff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.tsindex e30680e75a2..ee95db8bfe4 100644--- a/studio/frontend/tests/code-fence-defer.test.ts+++ b/studio/frontend/tests/code-fence-defer.test.ts@@ -5,6 +5,7 @@ import assert from "node:assert/strict";import { existsSync, readFileSync } from "node:fs";import test from "node:test";+import { markdownBlockFallback } from "../src/components/assistant-ui/markdown-block-fallback.ts";import { readSrc } from "./helpers/kit.ts";/**@@ -324,9 +325,27 @@ test("a print upgrades the whole document, and never puts it back", () => {`${door} is one of the two ways a document reaches a printer, and both must be covered`,);}+ /*+ * THE LATCH NEVER REVERTS. This used to ban the string `afterprint` outright, which said the+ * right thing about the only mechanism that existed when it was written. The line window is a+ * second one and it MUST revert: not reverting would mean one Ctrl+P un-windows every huge fence+ * for the life of the tab, which is the cost the window exists to avoid, and unlike a latch it+ * costs nothing to undo because the tokens are already in `fence.lines`.+ * So the ban is narrowed to what it protects rather than dropped: an `afterprint` handler may+ * clear the PRINT flag and nothing else, and no route may clear a latch.+ */+ const afterPrint = SOURCE.match(/addEventListener\("afterprint", (.*?)\);/);+ if (afterPrint) {+ assert.equal(+ afterPrint[1],+ "() => setPrinting(false)",+ "an afterprint handler may do one thing: end the print. Anything else here is the " ++ "bidirectional edge this design removes",+ );+ }assert.ok(- !/addEventListener\(\s*"afterprint"/.test(SOURCE),- "reverting on afterprint would be exactly the bidirectional edge this design removes",+ !/setLatched\(false\)|latched = false/.test(SOURCE),+ "nothing anywhere may hand a reached fence back its plain shell",);// 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,@@ -396,6 +415,53 @@ test("nothing is watched once there is nothing left to defer", () => {const CODE_PLUGIN = readSrc("components/assistant-ui/code-plugin.ts");+test("mermaid detection walks the block with fence context", () => {+ // A context-free search was the root cause of three findings: a `~~~mermaid` shown as EXAMPLE+ // inside an outer fence was treated as a diagram, so the block was replaced by the loading card+ // while streaming and given a diagram copy action once settled.+ assert.match(+ MARKDOWN_TEXT,+ /function findMermaidFence\(blockContent: string\): MermaidFence \{/,+ "one walk must answer both the opener and the source question",+ );+ assert.match(MARKDOWN_TEXT, /let enclosing: \{ char: string; run: number \} \| null = null;/);+ assert.match(MARKDOWN_TEXT, /enclosing = \{ char: marker\[0\], run: marker\.length \};/);+ // And the close still has to be the opener's own character, at least as long.+ assert.match(MARKDOWN_TEXT, /marker\.length >= enclosing\.run/);+ // The old context-free regex must be gone, not merely unused.+ assert.ok(!MARKDOWN_TEXT.includes("MERMAID_INFO_RE"), "the context-free matcher is gone");+});++test("a settled alternative fence is not marked incomplete", () => {+ // The completed form renders through the streaming component, which used to pass isIncomplete+ // unconditionally and left data-incomplete="true" on a finished fence.+ assert.match(+ MARKDOWN_TEXT,+ /<StreamingFenceBlock[\s\S]{0,160}isIncomplete=\{false\}/,+ "the settled branch must pass isIncomplete={false}",+ );+ assert.match(+ MARKDOWN_TEXT,+ /function StreamingFenceBlock\(\{[\s\S]{0,120}isIncomplete = true,/,+ "and the parameter must default to true for the streaming branch",+ );+});++test("a settled alternative fence is not marked incomplete", () => {+ // The completed form renders through the streaming component, which used to pass isIncomplete+ // unconditionally and left data-incomplete="true" on a finished fence.+ assert.match(+ MARKDOWN_TEXT,+ /<StreamingFenceBlock[\s\S]{0,160}isIncomplete=\{false\}/,+ "the settled branch must pass isIncomplete={false}",+ );+ assert.match(+ MARKDOWN_TEXT,+ /function StreamingFenceBlock\(\{[\s\S]{0,120}isIncomplete = true,/,+ "and the parameter must default to true for the streaming branch",+ );+});+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 anddiff --git a/studio/frontend/tests/code-fence-window.test.ts b/studio/frontend/tests/code-fence-window.test.tsnew file mode 100644index 00000000000..644af2e671a--- /dev/null+++ b/studio/frontend/tests/code-fence-window.test.ts@@ -0,0 +1,172 @@+// 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 test from "node:test";++import {+ HYSTERESIS_VIEWPORTS,+ lineIsWindowed,+ OVERSCAN_VIEWPORTS,+ selectLineWindow,+ WINDOW_CAP_LINES,+ type LineWindow,+ type WindowGeometry,+} from "../src/components/assistant-ui/code-fence-window.ts";++import { readSrc } from "./helpers/kit.ts";++/**+ * The line-window selection, RUN rather than described.+ *+ * Everything this decides is arithmetic over four numbers, and the thing it protects -- that a+ * fence small enough to be ordinary is NEVER windowed, and that an ordinary scroll inside a huge+ * one does not move the window -- is exactly the kind of claim a regex over the source cannot+ * make. The React side stays in `.tsx` and stays regex-tested, as `code-fence-defer.test.ts` does.+ */++/** 20px lines, a 600px viewport sitting at the top of the fence: 30 lines visible, 30 overscan. */+const geometry = (over: Partial<WindowGeometry> = {}): WindowGeometry => ({+ lineCount: 20_000,+ lineHeight: 20,+ contentTop: 0,+ viewportTop: 0,+ viewportHeight: 600,+ previous: null,+ ...over,+});++test("a fence at or under the cap is never windowed", () => {+ // The whole point of the cap: every fence in the benchmark corpus, and every fence anybody has+ // ever complained about except the one in #10769, renders what main renders.+ assert.equal(selectLineWindow(geometry({ lineCount: 1 })), null);+ assert.equal(selectLineWindow(geometry({ lineCount: WINDOW_CAP_LINES })), null);+ assert.equal(selectLineWindow(geometry({ lineCount: WINDOW_CAP_LINES - 1 })), null);+ // And an empty fence has no lines to window.+ assert.equal(selectLineWindow(geometry({ lineCount: 0 })), null);+});++test("past the cap the window covers the viewport plus one viewport each way", () => {+ const window = selectLineWindow(geometry({ viewportTop: 10_000 }));+ assert.ok(window, "a 20,000 line fence is windowed");+ // 10,000px down at 20px a line is line 500; 600px of viewport is 30 lines; overscan is another+ // 30 each way.+ const perViewport = 600 / 20;+ assert.equal(window.first, 500 - perViewport * OVERSCAN_VIEWPORTS);+ assert.equal(window.last, 500 + perViewport - 1 + perViewport * OVERSCAN_VIEWPORTS);+});++test("the window is clamped to the fence at both ends", () => {+ const top = selectLineWindow(geometry({ viewportTop: 0 }));+ assert.ok(top);+ assert.equal(top.first, 0, "no negative first line");++ const bottom = selectLineWindow(+ geometry({ viewportTop: 20_000 * 20 - 600 }),+ );+ assert.ok(bottom);+ assert.equal(bottom.last, 19_999, "no line past the end");+});++test("the window is read against the viewport, not the fence, when the fence starts off screen", () => {+ // The fence begins 5,000px ABOVE the viewport, which is what a fence part-way up a long reply+ // looks like. Line 250 is the first on screen.+ const window = selectLineWindow(geometry({ contentTop: -5_000 }));+ assert.ok(window);+ assert.equal(window.first, 250 - 30);+ assert.equal(window.last, 250 + 30 - 1 + 30);+});++test("an ordinary scroll inside the window does not move it", () => {+ const previous: LineWindow = { first: 470, last: 559 };+ // Scrolled by two lines. The visible range is still a long way inside `previous`.+ const kept = selectLineWindow(+ geometry({ viewportTop: 10_040, previous }),+ );+ assert.equal(kept, previous, "the same object, so React keeps every line element");+});++test("crossing the hysteresis band does move it", () => {+ const previous: LineWindow = { first: 470, last: 559 };+ const slack = Math.ceil((600 / 20) * HYSTERESIS_VIEWPORTS);+ // Put the visible top exactly `slack` lines above `previous.first`, so the guard fails.+ const viewportTop = (previous.first - slack - 1) * 20;+ const moved = selectLineWindow(geometry({ viewportTop, previous }));+ assert.ok(moved);+ assert.notEqual(moved, previous, "the window moved");+ assert.ok(moved.first < previous.first, "and it moved towards the reader");+});++test("hysteresis cannot pin a window that no longer covers the reader", () => {+ // A jump: Ctrl+End, a scrollbar drag, a find-in-page hit thousands of lines away. The old window+ // is nowhere near, so keeping it would leave the reader looking at uncoloured code indefinitely.+ const previous: LineWindow = { first: 0, last: 89 };+ const jumped = selectLineWindow(geometry({ viewportTop: 300_000, previous }));+ assert.ok(jumped);+ assert.notEqual(jumped, previous);+ assert.ok(jumped.first > 14_000, "the window followed the jump");+});++test("the window itself never exceeds the cap", () => {+ // A viewport taller than the cap: the ranges would otherwise add up to three times it.+ const window = selectLineWindow(+ geometry({+ lineCount: 40_000,+ viewportHeight: WINDOW_CAP_LINES * 20,+ viewportTop: 100_000,+ cap: WINDOW_CAP_LINES,+ }),+ );+ assert.ok(window);+ assert.ok(+ window.last - window.first + 1 <= WINDOW_CAP_LINES,+ `window held ${window.last - window.first + 1} lines`,+ );+ // And it still covers where the reader actually is, which is the half worth keeping.+ assert.ok(window.first <= 5_000 && window.last >= 5_000);+});++test("geometry that cannot be trusted degrades to highlighting everything", () => {+ // Fonts still loading, a detached node, a display:none ancestor. Every one of these has to land+ // on today's rendering: this mechanism may cost colour off screen, never on it.+ for (const broken of [+ { lineHeight: 0 },+ { lineHeight: -20 },+ { lineHeight: Number.NaN },+ { viewportHeight: 0 },+ { contentTop: Number.NaN },+ { viewportTop: Number.POSITIVE_INFINITY },+ ]) {+ assert.equal(+ selectLineWindow(geometry(broken)),+ null,+ `geometry ${JSON.stringify(broken)} must not produce a window`,+ );+ }+});++test("a null window highlights every line", () => {+ assert.equal(lineIsWindowed(null, 0), true);+ assert.equal(lineIsWindowed(null, 19_999), true);+});++test("membership is inclusive at both ends", () => {+ const window: LineWindow = { first: 10, last: 20 };+ assert.equal(lineIsWindowed(window, 9), false);+ assert.equal(lineIsWindowed(window, 10), true);+ assert.equal(lineIsWindowed(window, 20), true);+ assert.equal(lineIsWindowed(window, 21), false);+});++/** JSX in the window module makes this file unloadable and every assertion above a comment. */+test("the window module is plain TypeScript", () => {+ const source = readSrc("components/assistant-ui/code-fence-window.ts");+ assert.ok(+ !/<[A-Za-z]/.test(source.replace(/^\s*[/*].*$/gm, "")),+ "no JSX in the window module",+ );+ assert.ok(+ !/\bfrom\s+["']react["']/.test(source),+ "and no react import: this module has to load under --experimental-strip-types",+ );+});