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: let maths-bearing blocks take containment, behind a flag (#9731)
Daniel Han1b384308a12c
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 1e677571965..40ff39f1f74 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -65,6 +65,7 @@ import {useFenceReached,} from "./code-fence-defer";import { createCodePlugin } from "./code-plugin";+import { withMathBlockMarker } from "./math-block-marker";import {MarkdownBlockBoundary,MarkdownBlockFallbackView,@@ -80,7 +81,15 @@ import {withoutStreamdownAnimationPlugin,} from "./streaming-render-schedule";-const math = createMathPlugin({ singleDollarTextMath: true });+const baseMath = createMathPlugin({ singleDollarTextMath: true });+// Mark the block that holds each inline maths root, on the way past, so `index.css` has something+// that can take containment. Composed onto the maths plugin's own rehype pass because that is the+// only hook here that runs after Streamdown's sanitizer, which strips class names it does not+// recognise. See `math-block-marker.ts` for why neither plugin prop works.+const math = {+ ...baseMath,+ rehypePlugin: withMathBlockMarker(baseMath.rehypePlugin),+} satisfies typeof baseMath;const code = createCodePlugin({themes: [unslothLightTheme, unslothDarkTheme],});diff --git a/studio/frontend/src/components/assistant-ui/math-block-containment.ts b/studio/frontend/src/components/assistant-ui/math-block-containment.tsnew file mode 100644index 00000000000..a7766494037--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/math-block-containment.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/*+ * READING THE FLAG, AND PUTTING IT WHERE THE STYLESHEET CAN SEE IT.+ *+ * Split from `math-block-mode.ts` for the same reason `code-fence-defer.tsx` is split from+ * `code-fence-mode.ts`: this file touches `import.meta.env` and `document`, neither of which the+ * frontend's `node --experimental-strip-types` test runner can evaluate, and the decision itself+ * has to stay testable.+ */++import {+ FIND_IN_PAGE_PROBE,+ MATH_BLOCK_CONTAINMENT_ATTRIBUTE,+ MATH_BLOCK_CONTAINMENT_ON,+ type MathBlockMode,+ gateOnEngine,+ installOverrideWatcher,+ isRuntimeForced,+ resolveMathBlockMode,+} from "./math-block-mode";++const readBuildFlag = (): string => {+ try {+ return import.meta.env.VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT ?? "";+ } catch {+ return "";+ }+};++/**+ * Does this engine's find-in-page reach skipped `content-visibility` content? Answered by proxy;+ * `FIND_IN_PAGE_PROBE` carries the reasoning. Absent `CSS.supports`, the answer is NO, because an+ * engine too old to have that is certainly too old to have the fix.+ */+export const engineFindsSkippedContent = (): boolean => {+ try {+ return typeof CSS !== "undefined" && typeof CSS.supports === "function"+ ? CSS.supports(FIND_IN_PAGE_PROBE)+ : false;+ } catch {+ return false;+ }+};++const runtimeFlag = (): unknown =>+ (globalThis as Record<string, unknown>).__UNSLOTH_MATH_BLOCK_CONTAINMENT__;++export const mathBlockMode = (): MathBlockMode => {+ const runtime = runtimeFlag();+ return gateOnEngine(+ resolveMathBlockMode(runtime, readBuildFlag()),+ engineFindsSkippedContent(),+ isRuntimeForced(runtime),+ );+};++/**+ * Put the resolved mode on `document.documentElement`, following the `html[data-panel-resizing]`+ * precedent already in `index.css`. Called once at startup. Returns the mode so a caller can log+ * it; nothing in the app branches on the return value.+ *+ * The attribute is REMOVED rather than set to a falsy value when the mode is off, so an install+ * that never heard of this feature and one that has it turned off present the same DOM.+ */+export const applyMathBlockContainment = (+ root: Element | null = typeof document === "undefined"+ ? null+ : document.documentElement,+): MathBlockMode => {+ const mode = mathBlockMode();+ if (!root) return mode;+ if (mode === "contain") {+ root.setAttribute(+ MATH_BLOCK_CONTAINMENT_ATTRIBUTE,+ MATH_BLOCK_CONTAINMENT_ON,+ );+ } else {+ root.removeAttribute(MATH_BLOCK_CONTAINMENT_ATTRIBUTE);+ }+ return mode;+};++/**+ * Bind `installOverrideWatcher` to the real global and the real apply. The logic is in+ * `math-block-mode.ts`, where the test runner can reach it.+ */+export const watchMathBlockContainmentOverride = (+ scope: Record<string, unknown> = globalThis as Record<string, unknown>,+ apply: () => MathBlockMode = applyMathBlockContainment,+): boolean => installOverrideWatcher(scope, apply);diff --git a/studio/frontend/src/components/assistant-ui/math-block-marker.ts b/studio/frontend/src/components/assistant-ui/math-block-marker.tsnew file mode 100644index 00000000000..a23499965ac--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/math-block-marker.ts@@ -0,0 +1,333 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/*+ * MARK THE BLOCK THAT HOLDS INLINE MATHS, so a stylesheet has something it can contain.+ *+ * WHY THIS EXISTS. On WebKitGTK, which is what Studio and Desktop render through on Linux,+ * `RenderLayerScrollableArea::scrollTo` reaches+ * `RenderLayer::recursiveUpdateLayerPositionsAfterScroll`, which recurses over every descendant+ * RenderLayer once per scroll EVENT with no dirty-bit pruning and exactly one early out,+ * `!m_hasVisibleDescendant && !m_hasVisibleContent`. `RenderBoxModelObject::requiresLayer()` is+ * true for `isPositioned()`, and `isPositioned()` is `position != static`, so `position: relative`+ * alone buys a layer. KaTeX sets `position: relative` on `.katex`, `.base` and `.vlist`, and+ * `position: absolute` on `.katex-mathml` and `.vlist > span`. A 500K-character maths-bearing+ * thread measures 21,713 positioned boxes, about 20,700 of them under KaTeX, and 287.6 ms of+ * blocked main thread to move that scroller by ONE PIXEL.+ *+ * `content-visibility: auto` reaches that same early out for content the user cannot see: a+ * skipped subtree is `isSkippedContent()` and `RenderLayer::computeHasVisibleContent()` returns+ * false for it, so the walk stops at the skipped root instead of descending.+ *+ * WHY THE MATHS ROOT ITSELF IS NOT THE PLACE TO PUT IT. `content-visibility` needs SIZE+ * CONTAINMENT to take effect, and size containment does not apply to a non-atomic inline-level box+ * (css-contain-2 #containment-size; WebKit implements the check in+ * `Style::ContainmentChecker::shouldApplySizeContainment`). Shipped `katex.css` gives `.katex` no+ * `display`, so inline maths computes to `display: inline` and the declaration is silently inert+ * on it. That was measured rather than reasoned about: a rule naming `.katex` had the engine act+ * on 0 of 146 sampled inline roots. In the same corpus only about 4,919 of the positioned boxes+ * under maths sit under DISPLAY maths against about 15,291 under INLINE maths, so a rule that can+ * only reach display maths leaves three quarters of the cost behind, and measured as such: minus+ * 27 percent on the mean and plus 13 percent on p50, under the bar either way.+ *+ * SO THE DECLARATION IS HOISTED TO THE BLOCK THAT CONTAINS THE MATHS. For inline maths that block+ * is the paragraph, list item or heading it sits in, and nothing in CSS can select "an element+ * that contains maths" except `:has()`, which is itself the measured owner of the 500K scroll cost+ * on Chromium. So the renderer marks it, here.+ *+ * DISPLAY MATHS NEEDS NO MARKER and deliberately gets none. `remark-math` emits it as+ * `<pre><code class="language-math math-display">`, `rehype-katex` replaces that whole `pre` with+ * `<span class="katex-display">`, and `katex.css` gives that span `display: block`. It is already+ * a block-level element with a stable class, so `index.css` names it directly. Marking it here+ * would put a class on a node that is about to be thrown away.+ *+ * WHERE THIS RUNS, AND WHY IT IS NOT A `remarkPlugins` OR `rehypePlugins` PROP. Both were tried+ * and both are wrong here:+ *+ * - Passing `rehypePlugins` to `<Streamdown>` replaces its default list, and Streamdown only+ * installs the `allowedTags` sanitizer schema when that list is still the default one+ * (`rehypePlugins === defaultRehypePlugins`). Supplying our own would silently drop the+ * sanitize pass this renderer depends on. That is a security regression to buy a class name.+ * - Marking on the mdast side, through `data.hProperties`, lands the class BEFORE+ * `rehype-sanitize`, whose `defaultSchema` permits `className` on `a`, `code`, `h2`, `li`,+ * `ol`, `section` and `ul` and NOWHERE ELSE. A class on a `<p>` would be stripped, and+ * stripped silently, which is exactly the shape of a change that measures as doing nothing.+ *+ * So the marker is composed onto the MATHS plugin's own rehype pass, which Streamdown appends+ * after `raw`, `sanitize` and `harden`. It is the only hook in this pipeline that runs on hast,+ * after the sanitizer, without displacing anything.+ *+ * WHAT IT SEES THERE. The sanitizer strips `math-inline` and `math-display` for the same reason it+ * would strip ours: `defaultSchema` allows only `['className', /^language-./]` on `code`. So by+ * this point both kinds of maths carry `language-math` and nothing else, and inline is told from+ * display exactly the way `rehype-katex` itself tells them apart one plugin later: display maths+ * is a `code` whose parent is a `pre`.+ *+ * THE CLASS IS EMITTED WHETHER OR NOT THE FEATURE IS ON. It is inert without the stylesheet rule,+ * and emitting it unconditionally is what lets a measurement compare a window with the feature on+ * against a window with it off WITHOUT the two windows holding different DOM. An arm that mutates+ * the DOM inside its own measured window is billing itself for someone else's work.+ */++interface HastProperties {+ className?: unknown;+ [key: string]: unknown;+}++interface HastNode {+ type: string;+ tagName?: string;+ properties?: HastProperties;+ children?: HastNode[];+}++/** The marker. Read by `index.css`, and by nothing else. */+export const MATH_BLOCK_CLASS = "aui-math-block";++/*+ * The class the stylesheet contains DISPLAY maths by, added AFTER KaTeX has run and only to+ * displays that carry no equation number. `katex.css` resets `katexEqnNo` on `body` and increments+ * it in `.katex .eqn-num::before`, and style containment, which `content-visibility: auto` applies+ * unconditionally, scopes that increment to each contained display. Measured on Chromium: three+ * numbered displays read (1) (2) (3) with the feature off and (1) (1) (1) with it on. The same+ * fixture on WebKitGTK 2.50.4 does NOT reproduce it, 0 differing pixels, so this is engine+ * dependent and Chromium is the engine most of the web UI runs in.+ *+ * A `:has()` rule would express this in CSS alone and is exactly what must not be used: two+ * `:has()` rules were the measured owner of the whole 500K scroll cost on Chromium, fixed in #9669.+ * So the renderer decides, and the stylesheet names a plain class.+ */+export const MATH_DISPLAY_CLASS = "aui-math-display";++/** KaTeX's two equation-number markers, from `katex.css`. */+const EQN_NUM_CLASSES = new Set(["eqn-num", "mml-eqn-num"]);++/** What survives `rehype-sanitize` on a maths `code` element. See the header. */+const MATH_CLASS = "language-math";++/*+ * Elements that can take size containment AND that a run of prose carrying inline maths can be+ * sitting in. `pre` is absent because a `code.language-math` inside one is DISPLAY maths, which+ * this module does not touch.+ */+const BLOCK_TAGS = new Set([+ "p",+ "div",+ "blockquote",+ "dd",+ "figcaption",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+]);++/*+ * Size containment does NOT apply to internal table elements (css-contain-2 #containment-size), so+ * a `td` or `th` cannot be the target, and neither can anything above it short of the whole table,+ * which would be far too coarse a thing to collapse. Maths inside a table cell is therefore+ * ABANDONED rather than hoisted past. Recorded as a known limit rather than hidden: the corpus+ * this was measured on has no maths in tables.+ *+ * LIST ITEMS ARE HERE FOR A DIFFERENT AND MEASURED REASON. `content-visibility: auto` applies+ * STYLE containment, which scopes the automatic `list-item` counter, and a contained `li` can then+ * no longer resolve `counter(list-item)` for its own `::marker`. The observed result is not a+ * renumbering, it is that the number DISAPPEARS: photographed on WebKitGTK 2.50.4 with a five item+ * ordered list where only items 2 and 4 carried the class, the marker column differed by 61 and 59+ * pixels at full channel swing on exactly those two items and by 0 pixels on the other three, so+ * the list read 1, nothing, 3, nothing, 5. Siblings still observe the increment; what breaks is the+ * contained item's own marker.+ *+ * An earlier revision marked the `li` DELIBERATELY, because Streamdown gives a list item's+ * paragraph `[&>p]:inline` and an inline box cannot take size containment, which leaves the `li` as+ * the only containable ancestor. There is no third option there, so maths inside a list item is+ * abandoned like maths inside a table cell. `ol` and `ul` are listed too, so the walk cannot hoist+ * PAST an item and contain the whole list, which would lose every marker in it instead of one.+ *+ * The cost of this exemption was censused rather than assumed: of the 595 marked blocks in the 500K+ * corpus, 595 are `p` and 0 are `li`, so it gives up nothing that the +92% measurement was+ * counting. A thread that does put maths in lists loses the optimisation for those items and keeps+ * its numbering, which is the right way round.+ */+const UNCONTAINABLE_TAGS = new Set([+ "li",+ "ol",+ "ul",+ "td",+ "th",+ "table",+ "thead",+ "tbody",+ "tfoot",+ "tr",+]);++/*+ * The same bound the measurement harness used when it walked the rendered DOM for the equivalent+ * arm. Maths buried more than twelve elements deep inside inline wrappers is not a shape this+ * renderer produces, and an unbounded walk over a malformed tree is worse than marking nothing.+ */+const MAX_HOPS = 12;++const classListOf = (node: HastNode): string[] => {+ const raw = node.properties?.className;+ if (Array.isArray(raw)) return raw.map(String);+ if (typeof raw === "string") return raw.split(/\s+/).filter(Boolean);+ return [];+};++const addClass = (node: HastNode): void => {+ const properties: HastProperties = node.properties ?? {};+ node.properties = properties;+ const current = classListOf(node);+ if (current.includes(MATH_BLOCK_CLASS)) return;+ properties.className = [...current, MATH_BLOCK_CLASS];+};++/** Inline maths is a maths `code` element whose parent is not a `pre`. Display maths is the rest. */+const isInlineMath = (node: HastNode, parent: HastNode | undefined): boolean =>+ node.type === "element" &&+ node.tagName === "code" &&+ classListOf(node).includes(MATH_CLASS) &&+ parent?.tagName !== "pre";++/**+ * Walk up `stack` (outermost first) and mark the nearest element that can take containment.+ *+ * Returns the element marked, or `null` when there is nothing markable, which happens for maths+ * inside a table cell, maths deeper than `MAX_HOPS` inside inline wrappers, and maths with no+ * block ancestor at all.+ */+export const markNearestBlock = (stack: HastNode[]): HastNode | null => {+ let hops = 0;+ for (let i = stack.length - 1; i >= 0 && hops < MAX_HOPS; i -= 1, hops += 1) {+ const candidate = stack[i];+ const tagName = candidate.tagName ?? "";+ if (UNCONTAINABLE_TAGS.has(tagName)) return null;+ if (!BLOCK_TAGS.has(tagName)) continue;+ /*+ * Streamdown renders a list item with `[&>p]:inline`, so the paragraph a list item wraps its+ * text in computes to `display: inline` and cannot take size containment. Neither can the list+ * item, for the counter reason recorded on `UNCONTAINABLE_TAGS`, so there is nothing markable+ * here and the maths is abandoned rather than hoisted to something that would break numbering.+ * `tests/math-block-marker.test.ts` reads the `[&>p]:inline` class out of the installed+ * Streamdown build, so the day Streamdown stops doing it this stops being justified loudly+ * rather than quietly.+ */+ if (tagName === "p" && i > 0 && stack[i - 1].tagName === "li") return null;+ addClass(candidate);+ return candidate;+ }+ return null;+};++/**+ * Mark every block that holds inline maths. Returns how many blocks were marked, which is what+ * makes the transform testable without a DOM and without a browser.+ */+export const markMathBlocks = (tree: HastNode): number => {+ const stack: HastNode[] = [];+ let marked = 0;++ const visit = (node: HastNode, parent: HastNode | undefined): void => {+ if (isInlineMath(node, parent)) {+ // A maths root's own subtree holds nothing else of interest.+ if (markNearestBlock(stack)) marked += 1;+ return;+ }+ const children = node.children;+ if (!children || children.length === 0) return;+ const isElement = node.type === "element";+ if (isElement) stack.push(node);+ for (const child of children) visit(child, node);+ if (isElement) stack.pop();+ };++ visit(tree, undefined);+ return marked;+};++type Transformer = (tree: HastNode, file: unknown) => unknown;+type Attacher = (+ this: unknown,+ ...options: unknown[]+) => Transformer | undefined;++/**+ * Compose the marker in front of the maths renderer, preserving whatever options the maths plugin+ * was configured with.+ *+ * Takes the `rehypePlugin` off a Streamdown maths plugin, which is either an attacher or an+ * `[attacher, options]` tuple, and returns a single attacher that marks the tree and then hands it+ * to the original. Returning ONE attacher matters: Streamdown appends this value to its rehype+ * list as a single entry, where an array would be read as an `[attacher, options]` tuple.+ */+/** Does this subtree carry a KaTeX equation number? */+const hasEquationNumber = (node: HastNode): boolean => {+ if (node.type === "element" && classListOf(node).some((c) => EQN_NUM_CLASSES.has(c))) {+ return true;+ }+ for (const child of node.children ?? []) {+ if (hasEquationNumber(child)) return true;+ }+ return false;+};++/**+ * Run AFTER KaTeX. Two jobs, both about the equation counter:+ *+ * 1. Give every `.katex-display` WITHOUT an equation number the class the stylesheet contains by.+ * A numbered one is left alone and simply does not take containment.+ * 2. Take `MATH_BLOCK_CLASS` back off any block that turned out to contain a numbered display.+ * `markMathBlocks` runs before KaTeX, when a display is still+ * `<pre><code class="language-math">` and no `.eqn-num` exists to see, so a blockquote or div+ * holding both inline maths and a numbered display would otherwise scope the counter from+ * above and break the numbering just as effectively.+ *+ * Returns how many displays were marked and how many blocks were unmarked, which is what makes+ * this testable without a browser.+ */+export const guardEquationNumbers = (tree: HastNode): { marked: number; unmarked: number } => {+ let marked = 0;+ let unmarked = 0;+ const visit = (node: HastNode): void => {+ if (node.type === "element") {+ const classes = classListOf(node);+ if (classes.includes("katex-display") && !hasEquationNumber(node)) {+ const properties: HastProperties = node.properties ?? {};+ node.properties = properties;+ if (!classes.includes(MATH_DISPLAY_CLASS)) {+ properties.className = [...classes, MATH_DISPLAY_CLASS];+ marked += 1;+ }+ }+ if (classes.includes(MATH_BLOCK_CLASS) && hasEquationNumber(node)) {+ const properties: HastProperties = node.properties ?? {};+ node.properties = properties;+ properties.className = classes.filter((c) => c !== MATH_BLOCK_CLASS);+ unmarked += 1;+ }+ }+ for (const child of node.children ?? []) visit(child);+ };+ visit(tree);+ return { marked, unmarked };+};++export const withMathBlockMarker = (mathRehypePlugin: unknown): Attacher => {+ const [attacher, options] = (+ Array.isArray(mathRehypePlugin) ? mathRehypePlugin : [mathRehypePlugin]+ ) as [Attacher, unknown?];+ return function markThenRenderMaths(this: unknown) {+ const renderMaths = attacher.call(this, options);+ return (tree: HastNode, file: unknown) => {+ markMathBlocks(tree);+ const rendered = renderMaths ? renderMaths(tree, file) : undefined;+ // After KaTeX, because equation numbers do not exist until it has run.+ guardEquationNumbers(tree);+ return rendered;+ };+ };+};diff --git a/studio/frontend/src/components/assistant-ui/math-block-mode.ts b/studio/frontend/src/components/assistant-ui/math-block-mode.tsnew file mode 100644index 00000000000..9f930418ac7--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/math-block-mode.ts@@ -0,0 +1,192 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/*+ * WHETHER MATHS-BEARING BLOCKS TAKE CONTAINMENT, decided in one pure function.+ *+ * Kept out of any `.tsx` and free of `import.meta`, exactly as `code-fence-mode.ts` is, because+ * the frontend's tests run under `node --experimental-strip-types` and can neither load JSX nor+ * evaluate `import.meta.env`. Every row below is RUN by `tests/math-block-mode.test.ts` rather+ * than checked by regexes over the source.+ *+ * "off" The marker class is still emitted, the stylesheet rule that reads it is not armed,+ * and nothing about rendering changes.+ * "contain" SHIP DEFAULT, subject to the engine gate below. `content-visibility: auto` applies+ * to maths-bearing blocks, so off-screen maths generates no boxes and no RenderLayers+ * until it is scrolled to. See the comment on `SHIP_DEFAULT` for what that buys and+ * for the two costs that are accepted rather than solved.+ *+ * TWO STATES, NOT THREE. `code-fence-mode.ts` distinguishes an unset flag from a mistyped one; this+ * file does not, and the reason has CHANGED now that the default is "contain". It used to be that+ * unset and unrecognised both resolved to "off" and there was no distinction to draw. They no+ * longer land in the same place: unset resolves to the ship default, which is ON, while an+ * unrecognised value resolves to "off". That asymmetry is deliberate and is the safe direction. An+ * operator who mistypes `VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT=conatin` was reaching for the flag,+ * and the only reason to reach for a flag that is already on is to turn it off, so a typo turning+ * it off does what they were trying to do. The opposite rule, resolving a typo to the default,+ * would ignore them.+ */+export type MathBlockMode = "off" | "contain";++/*+ * SHIP DEFAULT, and the evidence for it.+ *+ * WHAT IT BUYS. At the 500K rung on a real GPU (AMD gfx1151, production bundle, two repetitions per+ * rung, each arm scored against its own two neighbouring baselines, runs 32902943628 and+ * 32906688232) a one pixel scroll costs 285 ms of blocked main thread and the interface runs at+ * 3.2 fps. With this on it costs 18 to 19.5 ms and runs at 35.6 to 38.2 fps: +92% on the mean and+ * +88% on the median rAF gap, in all four sessions. At 100K it is +80 to +85% at 62 fps. At 0K the+ * selector matches nothing, so the rule cannot cost anything there for a structural reason rather+ * than a statistical one.+ *+ * RENDERING IS UNCHANGED. Two production bundles, feature off against on, photographed at seven+ * maths blocks after one full walk of the thread: 10 differing pixels over seven frames, four of+ * them bit-identical, `scrollHeight` matching exactly at 307,915.+ *+ * THE THREE THINGS THAT COULD HAVE STOPPED IT, each measured rather than argued.+ *+ * 1. FIND-IN-PAGE. Handled by `gateOnEngine` below, not by this constant: an engine that cannot+ * find skipped content does not get containment at all. Verified once by driving the real+ * `WebKitFindController` over four states on WebKitGTK 2.50.4 (plain 1 match, contained 1,+ * `visibility: hidden` 0, absent 0; the two controls are what make the middle row mean+ * something). Studio Desktop wires no find-in-page on any platform, so the exposed surface is+ * the web UI in a browser older than Safari 26, which is exactly what the gate switches off.+ * 2. LIST NUMBERING. Fixed by making `li`, `ol` and `ul` uncontainable; see+ * `math-block-marker.ts`. Censused at zero cost: 595 of 595 marked blocks in the 500K corpus+ * are paragraphs.+ * 3. A REMEMBERED HEIGHT GOING STALE ACROSS A RESIZE. Accepted, at a measured size. Narrowing the+ * window from 1440 to 1008 px on the 500K corpus leaves `scrollHeight` 6,350 px short of the+ * truth, 2.0%, against 0.0% for the same thread with the feature off. It converges as blocks+ * are scrolled past. A synthetic fixture in which EVERY block is contained reads 100%, which+ * is an upper bound and not what a real thread does.+ *+ * WHAT IS ACCEPTED RATHER THAN SOLVED. The 2.0% above, and clipping: paint containment clips an+ * inline formula wider than the chat column instead of letting it overflow, confirmed by hit+ * testing. Zero blocks overflow in the 500K corpus. `overflow-x: auto` is NOT the remedy, because+ * it would make 595 marked blocks into 595 scroll containers, which is the RenderLayer population+ * this whole change exists to remove.+ *+ * Moving this line is the whole of "turn block containment off again".+ */+export const SHIP_DEFAULT: MathBlockMode = "contain";++/*+ * THE FIND-IN-PAGE GATE, and why it is a proxy rather than a direct test.+ *+ * WebKit below Safari 26 cannot find SKIPPED `content-visibility` content with native find-in-page+ * (webkit.org/b/283846). `index.css` already refuses to use `content-visibility: auto` on code+ * blocks for exactly this reason and says so in a comment, noting that Studio has no in-thread+ * search to fall back on. Containment on maths-bearing blocks reintroduces the same hazard, and it+ * reaches further: the marked element is a whole paragraph or heading, so ordinary PROSE in a+ * maths-bearing block would stop being findable too, not just the formula.+ *+ * Nothing on the platform exposes "can find-in-page reach skipped content", so this gates on a CSS+ * feature that shipped in the SAME release as the fix and is therefore absent on exactly the builds+ * that are affected. Anchor positioning is that feature. This is a PROXY: it asserts a release+ * train, not the bug, and if some engine ever ships one without the other this gate is wrong in+ * whichever direction that engine chose. That is a deliberate trade against the alternative, which+ * is parsing a user-agent string that WebKitGTK freezes at `AppleWebKit/605.1.15` on every version+ * it has ever shipped.+ *+ * Measured on the venue the performance numbers came from, WebKitGTK 2.50.4: `anchor-name` is+ * supported, and that build does find skipped content. The point of the gate is the builds that are+ * not that one, which Studio absolutely ships against, since Linux uses whatever WebKitGTK the host+ * provides and macOS uses whatever the OS provides.+ */+export const FIND_IN_PAGE_PROBE = "anchor-name: --unsloth-probe";++/**+ * Whether the engine may take containment at all, given the outcome of the probe above.+ *+ * An EXPLICIT RUNTIME override wins, because that global exists so a measurement or a bug report+ * can force an arm from the devtools console, and a gate that silently refused would make the+ * console flip look like it had worked while measuring the other arm. A build flag does NOT win:+ * a build is shipped to machines whose engines the builder cannot see.+ */+export const gateOnEngine = (+ mode: MathBlockMode,+ engineFindsSkippedContent: boolean,+ forcedByRuntime: boolean,+): MathBlockMode =>+ mode !== "contain" || engineFindsSkippedContent || forcedByRuntime ? mode : "off";++/** Whether `runtime` is an explicit instruction rather than an absent global. */+export const isRuntimeForced = (runtime: unknown): boolean =>+ runtime === true || runtime === "1" || runtime === "contain";++/**+ * @param runtime `__UNSLOTH_MATH_BLOCK_CONTAINMENT__`: string, boolean or absent. The boolean is+ * the devtools-console form and has to work in BOTH directions, so that a session+ * can be flipped without a rebuild.+ * @param build `VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT`, `""` when never set.+ */+export const resolveMathBlockMode = (+ runtime: unknown,+ build: string,+): MathBlockMode => {+ const raw =+ typeof runtime === "string"+ ? runtime+ : runtime === true+ ? "contain"+ : runtime === false+ ? "off"+ : build;+ return raw === "1" || raw === "contain"+ ? "contain"+ : raw === ""+ ? SHIP_DEFAULT+ : "off";+};++/**+ * The attribute the stylesheet reads, on `document.documentElement`, following the+ * `html[data-panel-resizing]` precedent already in `index.css`. An attribute rather than a class+ * on the thread root because it has to be reachable before any thread has mounted, and because a+ * measurement can flip it without provoking a React render, which keeps the DOM identical between+ * a measured window with the feature on and one with it off.+ */+export const MATH_BLOCK_CONTAINMENT_ATTRIBUTE = "data-math-block-containment";+export const MATH_BLOCK_CONTAINMENT_ON = "on";++/*+ * REAPPLY WHEN THE CONSOLE FLIPS THE GLOBAL.+ *+ * `applyMathBlockContainment()` is called once, before the first render. Without this, a tester who+ * set `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` from devtools AFTER load changed nothing: the attribute+ * kept its old value and the session went on measuring the arm it was already in, silently. That is+ * the worst failure mode an escape hatch can have, because the number it produces looks like an+ * answer.+ *+ * The global is redefined as an accessor so that ASSIGNING it reapplies. The value is held in a+ * closure rather than on the scope object, so reading the property still returns what was written+ * and nothing else on the page sees a different shape than before.+ *+ * It lives HERE, in the module with no `import.meta` and no `document`, for the reason this file's+ * header gives: the frontend's `node --experimental-strip-types` runner cannot load the other one,+ * and an escape hatch whose failure mode is silence is exactly the thing that needs rows run+ * against it rather than a comment.+ */+export const installOverrideWatcher = (+ scope: Record<string, unknown>,+ apply: () => MathBlockMode,+): boolean => {+ try {+ let held = scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__;+ Object.defineProperty(scope, "__UNSLOTH_MATH_BLOCK_CONTAINMENT__", {+ configurable: true,+ enumerable: true,+ get: () => held,+ set: (next: unknown) => {+ held = next;+ apply();+ },+ });+ return true;+ } catch {+ // A frozen or otherwise hostile global is not worth failing startup over: this runs before the+ // first render, so throwing here is a white screen. The flag still works when set BEFORE load,+ // which is how the build flag and the measurement harness use it.+ return false;+ }+};diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex f02a11978a2..183ebae828c 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -2577,6 +2577,150 @@ html[data-chat-font] .aui-root {.aui-thread-root [data-streamdown="code-block"] [data-sd-animate] {animation: none !important;}++ /* Off-screen maths costs a full RenderLayer walk on every scroll event.+ *+ * ON BY DEFAULT, AND ENGINE-GATED. `main.tsx` sets this attribute only when+ * `resolveMathBlockMode` says "contain", and `SHIP_DEFAULT` in+ * `math-block-mode.ts` is now "contain", so an ordinary install DOES arm this+ * rule -- but only where `engineFindsSkippedContent()` passes, which feature+ * detects `anchor-name` as a proxy for the WebKit release carrying the+ * find-in-page fix (webkit.org/b/283846). On an engine below that bar the+ * gate returns "off" and these rules never apply.+ * `VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT` and+ * `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` override both ways at build and at+ * runtime, so it is still revertible by configuration rather than by a+ * revert.+ *+ * THE MECHANISM. On WebKitGTK, which is what Studio and Desktop render+ * through on Linux, `RenderLayerScrollableArea::scrollTo` reaches+ * `RenderLayer::recursiveUpdateLayerPositionsAfterScroll`, which recurses+ * over every descendant RenderLayer once per scroll EVENT with no dirty-bit+ * pruning and exactly one early out,+ * `!m_hasVisibleDescendant && !m_hasVisibleContent`.+ * `RenderBoxModelObject::requiresLayer()` is true for `isPositioned()`, and+ * `isPositioned()` is `position != static`, so `position: relative` alone+ * buys a layer. KaTeX sets it on `.katex`, `.base` and `.vlist`, and+ * `position: absolute` on `.katex-mathml` and `.vlist > span`. A+ * 500K-character maths-bearing thread measures 21,713 positioned boxes, about+ * 20,700 of them under KaTeX, and 287.6 ms of blocked main thread to move the+ * scroller by ONE PIXEL, which is 3.2 fps.+ *+ * `content-visibility: auto` reaches that same early out for content the user+ * cannot see: a skipped subtree is `isSkippedContent()` and+ * `RenderLayer::computeHasVisibleContent()` returns false for it.+ *+ * WHY THE BLOCK AND NOT THE MATHS. `content-visibility` needs size+ * containment, and size containment does not apply to a non-atomic+ * inline-level box (css-contain-2 #containment-size; WebKit checks it in+ * `Style::ContainmentChecker::shouldApplySizeContainment`). Shipped+ * `katex.css` gives `.katex` no `display`, so inline maths is `display:+ * inline` and the declaration is inert on it: measured at 0 of 146 sampled+ * inline roots. Only about 4,919 of the positioned boxes under maths in that+ * corpus sit under DISPLAY maths against about 15,291 under INLINE maths, and+ * a `.katex-display`-only rule measured minus 27 percent on the mean and plus+ * 13 percent on p50, under the bar either way. `.aui-math-block` is the+ * paragraph, list item or heading that HOLDS the inline maths, marked by the+ * renderer in `math-block-marker.ts` because no CSS selector can ask that+ * question except `:has()`, which is itself the measured owner of the 500K+ * scroll cost on Chromium.+ *+ * THE PLACEHOLDER IS MEASURED, NOT GUESSED, IT IS A FALLBACK, AND THERE ARE+ * TWO OF THEM. The mean rendered height over the 500K corpus is 138.04px for a+ * marked block and 49.13px for a display formula: a marked block is a+ * PARAGRAPH of prose that happens to contain a formula, and a display formula+ * is one line of maths, so the two populations are nothing like each other.+ * The mean rather than the median because the scrollHeight error a placeholder+ * introduces is the SUM of (placeholder minus actual) over the blocks not yet+ * rendered, and the mean is the value that makes that sum zero.+ *+ * One shared 7.5rem was tried first and measured: 18px short on every+ * paragraph and 71px too tall on every formula. Those errors do not cancel,+ * they queue up under the user, and on a first traversal of a 500K thread they+ * showed up as a 3,995px scrollbar excursion over 470 rescales. Two values+ * cut the per-block error to about 2px and 1px.+ *+ * The `auto` keyword makes the engine remember each block's real size once it+ * has been rendered, so either fallback only ever applies to a block the user+ * has not reached yet, and only until they reach it. A second traversal of the+ * same thread measured zero excursion and zero drift.+ *+ * WHAT IT COSTS, corrected. An earlier revision of this comment said 39+ * sub-structures move by one device pixel across seven formulae, blamed paint+ * containment re-parenting KaTeX's absolutely positioned `.vlist` boxes, and+ * gave that as the reason to ship off. Both halves were wrong. `contain: paint`+ * ALONE moves 192 pixels over the same seven frames, two of them bit-identical,+ * against 7,611 for the whole change, so it is about 2.5% of the effect. And+ * the effect is a FIRST-TRAVERSAL TRANSIENT rather than a rendering difference:+ * photographed after one full walk of the thread, so that every block has+ * rendered once and `contain-intrinsic-size: auto` holds its real height, the+ * two built bundles differ by TEN pixels over seven frames, four of them+ * bit-identical, with `scrollHeight` matching exactly. What the earlier+ * measurement caught was blocks still showing their placeholder.+ *+ * What it does cost is recorded on `SHIP_DEFAULT` in `math-block-mode.ts`: a+ * remembered height goes stale across a resize, 2.0% of `scrollHeight` on the+ * 500K corpus against 0.0% with the feature off, converging as blocks are+ * scrolled past; and paint containment clips an inline formula wider than the+ * column, which no block in that corpus is. This ships ON, gated on the+ * engine. */+ html[data-math-block-containment="on"] .aui-thread-root .aui-math-block {+ content-visibility: auto;+ contain-intrinsic-size: auto 8.5rem;+ }+ /* `.aui-math-display`, not `.katex-display`, because a display carrying an equation number must+ NOT take containment: style containment scopes `katexEqnNo` and Chromium then renders every+ numbered equation as (1). The renderer adds this class after KaTeX has run, to the displays+ that have no number. A `:has()` rule would say the same thing in CSS and is precisely what+ must not be used here, since two `:has()` rules were the measured owner of the 500K scroll+ cost on Chromium (#9669). */+ html[data-math-block-containment="on"] .aui-thread-root .aui-math-display {+ content-visibility: auto;+ contain-intrinsic-size: auto 3rem;+ }++ /* A PRINT IS NOT A VIEWPORT, and on WebKit that loses the equations.+ *+ * Skipped content is not painted, and the box keeps the placeholder height above, so a block+ * that is skipped when the print is taken comes out as an EMPTY 8.5rem or 3rem rectangle on the+ * page. Nothing about the printed copy tells the reader it happened; they keep a PDF whose+ * formulae, and whose maths-bearing paragraphs of prose, are blank boxes. That is the one+ * failure mode this whole feature must not have.+ *+ * WHY THE ENGINE DOES NOT SAVE US. `content-visibility: auto` skips whatever is not "relevant to+ * the user", and css-contain-2 defines that as on-screen, focused, selected or in the top layer+ * -- there is no print carve-out in the prose, under `#relevant-to-the-user` in+ * drafts.csswg.org/css-contain-2. The CSSWG resolved on 2024-06-13 to add one, "when printing a+ * document, also treat content-visibility:auto as visible" (w3c/csswg-drafts#10347), and the+ * spec still has not been edited. So each engine is on its own: Chromium unlocks for print+ * (`DisplayLockContext::SetShouldUnlockAutoForPrint`, 2020), Gecko resolves `auto` to `visible`+ * in print context (bugzilla 1907081, Firefox 130), and WebKit does NEITHER -- its+ * `ContentRelevancy` enum is `OnScreen | Focused | IsInTopLayer | Selected` and its+ * `ContentVisibilityDocumentState` never mentions printing, so relevancy stays whatever an+ * IntersectionObserver against the on-screen viewport last said. WebKit is exactly what Studio+ * renders through on Linux and what a macOS reader reaches this app with, and it is the engine+ * the gate ARMS: Safari 26 and WebKitGTK 2.50.4 both carry `anchor-name`, which is what+ * `FIND_IN_PAGE_PROBE` tests, and neither carries a print fix. The Gecko report reads exactly+ * like the defect this rule prevents: "the contents are not visible in the print preview.+ * However, the height is reserved, resulting in a few empty pages."+ *+ * WHY CSS AND NOT `beforeprint`. `code-fence-defer.tsx` needs a script for its print upgrade+ * because what it defers is not in the DOM to begin with. Here the maths IS in the DOM and only+ * its RENDERING is skipped, so switching the declaration off is the whole fix, and a media query+ * covers both doors that file has to hook separately: WebKit re-evaluates media queries inside+ * `LocalFrame::setPrinting` before it lays out the pages, and a headless `page.pdf()` or DevTools+ * print emulation changes the media without ever firing `beforeprint`.+ *+ * `!important` because the gated rules above are more specific than anything unprefixed, and+ * `none` rather than a length so the box is sized by its contents, matching the code-block rule+ * earlier in this file. */+ @media print {+ .aui-thread-root .aui-math-block,+ .aui-thread-root .aui-math-display {+ content-visibility: visible !important;+ contain-intrinsic-size: none !important;+ }+ }}/* No border line; same drop shadow as the composer (.unsloth-composer-surface).diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsxindex 18630b372e7..e752871fe90 100644--- a/studio/frontend/src/main.tsx+++ b/studio/frontend/src/main.tsx@@ -6,6 +6,10 @@ import { createRoot } from "react-dom/client";import "./index.css";import { App } from "./app/app";+import {+ applyMathBlockContainment,+ watchMathBlockContainmentOverride,+} from "./components/assistant-ui/math-block-containment";import { fetchDeviceType } from "./config/env";import { initializeLocale } from "./i18n";import { isTauri } from "./lib/api-base";@@ -28,6 +32,16 @@ if (uaLower.includes("linux") && !uaLower.includes("android")) {document.documentElement.classList.add("render-linux");}+// Whether off-screen maths takes containment. ON by default, subject to a feature detect for the+// engine's find-in-page, so on a recent engine this normally SETS the attribute and arms the rule;+// on an older one it removes an attribute that was never there. Before the first render, because+// the rule it arms is a rendering rule and arming it late would relayout the first thread that+// mounts.+applyMathBlockContainment();+// And keep watching, so a devtools flip of `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` reapplies instead of+// leaving the session measuring the arm it was already in.+watchMathBlockContainmentOverride();+// Keep right-edge controls clear of overlay scrollbars.watchOverlayScrollbarGutter(window);diff --git a/studio/frontend/tests/math-block-containment-wiring.test.ts b/studio/frontend/tests/math-block-containment-wiring.test.tsnew file mode 100644index 00000000000..24cf91ad225--- /dev/null+++ b/studio/frontend/tests/math-block-containment-wiring.test.ts@@ -0,0 +1,351 @@+// 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 {+ MATH_BLOCK_CLASS,+ MATH_DISPLAY_CLASS,+} from "../src/components/assistant-ui/math-block-marker.ts";+import {+ MATH_BLOCK_CONTAINMENT_ATTRIBUTE,+ MATH_BLOCK_CONTAINMENT_ON,+} from "../src/components/assistant-ui/math-block-mode.ts";++/*+ * THE THREE PIECES ONLY WORK TOGETHER, and nothing in the type system joins them:+ *+ * 1. the marker has to be composed onto the MATHS plugin, not passed as a `rehypePlugins` prop,+ * because that prop switches off Streamdown's `allowedTags` sanitizer;+ * 2. the stylesheet has to name the class the marker writes and the attribute the resolver sets;+ * 3. `main.tsx` has to set that attribute before the first render.+ *+ * Each is checked against the real source. Where a check is a string search it says what it is+ * defending, so a rename that breaks the join fails here by name rather than by measuring as a+ * change that does nothing.+ */++const read = (relative: string): string =>+ readFileSync(new URL(relative, import.meta.url), "utf8");++const MARKDOWN_TEXT = read("../src/components/assistant-ui/markdown-text.tsx");+const INDEX_CSS = read("../src/index.css");+const MAIN_TSX = read("../src/main.tsx");+const MATH_BLOCK_MODE = read(+ "../src/components/assistant-ui/math-block-mode.ts",+);+const CONTAINMENT = read(+ "../src/components/assistant-ui/math-block-containment.ts",+);++test("the marker is composed onto the maths plugin", () => {+ assert.ok(+ MARKDOWN_TEXT.includes("createMathPlugin({ singleDollarTextMath: true })"),+ "PRECONDITION: the chat renderer still builds its own maths plugin",+ );+ assert.ok(+ MARKDOWN_TEXT.includes(+ "rehypePlugin: withMathBlockMarker(baseMath.rehypePlugin)",+ ),+ "the marker wraps the maths plugin's own rehype pass",+ );+});++test("the chat renderer does NOT pass a rehypePlugins prop", () => {+ // Passing one makes Streamdown skip its `allowedTags` sanitizer schema, because it only installs+ // that schema while `rehypePlugins === defaultRehypePlugins`. This is the reason the marker is+ // composed rather than appended, and it is worth more than the class it buys.+ assert.ok(+ MARKDOWN_TEXT.includes("allowedTags={STREAMDOWN_ALLOWED_TAGS}"),+ "PRECONDITION: the chat renderer relies on the allowedTags sanitizer",+ );+ assert.ok(+ !/\brehypePlugins=\{/.test(MARKDOWN_TEXT),+ "no rehypePlugins prop, or the sanitizer schema above is silently dropped",+ );+});++test("the stylesheet rule names the class, the attribute and both declarations", () => {+ const gate = `html[${MATH_BLOCK_CONTAINMENT_ATTRIBUTE}="${MATH_BLOCK_CONTAINMENT_ON}"]`;+ const rules = INDEX_CSS.split(gate)+ .slice(1)+ .map((part) => part.slice(0, 220));+ assert.equal(+ rules.length,+ 2,+ "PRECONDITION: two gated rules, one per population, because their heights differ 3x",+ );++ const [marked, display] = rules;+ for (const rule of rules) {+ assert.ok(rule.includes(".aui-thread-root"), "scoped to the chat thread");+ assert.ok(+ rule.includes("content-visibility: auto"),+ "the declaration under test",+ );+ }++ assert.ok(marked.includes(`.${MATH_BLOCK_CLASS}`), "names the marker class");+ assert.ok(+ display.includes(`.${MATH_DISPLAY_CLASS}`),+ "names the display class the renderer adds after KaTeX has run",+ );+ assert.equal(+ display.includes(".katex-display"),+ false,+ "and NOT `.katex-display` itself: a display carrying an equation number must not take " ++ "containment, because style containment scopes `katexEqnNo` and Chromium then renders " ++ "every numbered equation as (1). Measured, and engine dependent: the same fixture on " ++ "WebKitGTK 2.50.4 does not reproduce it.",+ );+ for (const rule of rules) {+ // Scoped to THESE rules rather than to the file, which carries other `:has()` rules that #9669+ // deliberately narrowed to direct children rather than removing.+ assert.equal(+ rule.includes(":has("),+ false,+ "the exemption is NOT expressed with `:has()` here, which was the measured owner of the " ++ "whole 500K scroll cost on Chromium (#9669); the renderer decides instead",+ );+ }++ /*+ * THE TWO PLACEHOLDERS ARE DIFFERENT, AND THAT IS THE POINT. A marked block is a PARAGRAPH of+ * prose holding a formula and measured a 138.04px mean; a display formula is one line of maths+ * and measured 49.13px. One shared value was tried and was 18px short on every paragraph and+ * 71px too tall on every formula, which queued up under a first-time scroller as a 3,995px+ * scrollbar excursion. If these two ever become equal again, that regression is back.+ */+ assert.ok(+ marked.includes("contain-intrinsic-size: auto 8.5rem"),+ "the paragraph placeholder, near the measured 138px mean",+ );+ assert.ok(+ display.includes("contain-intrinsic-size: auto 3rem"),+ "the formula placeholder, near the measured 49px mean",+ );+ assert.notEqual(+ marked.match(/contain-intrinsic-size: auto [\d.]+rem/)?.[0],+ display.match(/contain-intrinsic-size: auto [\d.]+rem/)?.[0],+ "one shared placeholder is the thing this pair replaced",+ );+});++test("the rule is armed by nothing except that attribute", () => {+ // PRECONDITION: the stylesheet already carries an UNGATED `content-visibility: visible` on code+ // blocks, put there to stop a flicker. So "no content-visibility anywhere else" would be false+ // and this test has to be specific about which declaration it is defending.+ assert.ok(+ INDEX_CSS.includes("content-visibility: visible !important"),+ "the code-block flicker rule is still there",+ );++ // Two gated copies of `auto`, one per population. A third, ungated one would turn the flag+ // into decoration.+ const declarations = INDEX_CSS.split("content-visibility: auto;").length - 1;+ assert.equal(+ declarations,+ 2,+ "exactly two `content-visibility: auto` declarations in the whole stylesheet",+ );+ const gateAt = INDEX_CSS.indexOf(`html[${MATH_BLOCK_CONTAINMENT_ATTRIBUTE}=`);+ assert.ok(gateAt >= 0, "PRECONDITION: the gate is present");+ assert.ok(+ INDEX_CSS.indexOf("content-visibility: auto;") > gateAt,+ "and the first of them sits after the gate",+ );+});++test("a print turns the containment off, for both populations", () => {+ /*+ * WHAT IS AT STAKE. Skipped content is not painted and the box keeps its placeholder height, so a+ * block still skipped when the reader prints comes out as an EMPTY 8.5rem or 3rem rectangle. The+ * Gecko report that got printing fixed there describes precisely that: "the contents are not+ * visible in the print preview. However, the height is reserved, resulting in a few empty pages."+ * (bugzilla.mozilla.org/show_bug.cgi?id=1907081, fixed in Firefox 130.)+ *+ * AND THE ENGINE DOES NOT DO IT FOR US. css-contain-2 lists on-screen, focused, selected and top+ * layer as the ways to be "relevant to the user" and says nothing about printing; the CSSWG+ * resolved to add a print carve-out on 2024-06-13 (w3c/csswg-drafts#10347) and the spec is still+ * unedited. Chromium and Gecko each fixed it themselves. WebKit has not: `ContentRelevancy` is+ * `OnScreen | Focused | IsInTopLayer | Selected` and nothing in its+ * `ContentVisibilityDocumentState` mentions printing. WebKit is what Studio renders through on+ * Linux, and it is an engine this feature ARMS on, since the `anchor-name` probe passes on Safari+ * 26 and on WebKitGTK 2.50.4. So this rule, not the engine, is what keeps the equations on the+ * page -- which makes it worth a test rather than a comment.+ *+ * NOT a `beforeprint` hook, unlike `code-fence-defer.tsx`, which has to script its print upgrade+ * because what it defers is not in the DOM. Here the maths is in the DOM and only its rendering+ * is skipped, so a media query is the whole fix and it covers `page.pdf()` too.+ */+ // Balanced-brace slices, so the assertions below are about a print block and not about whatever+ // the next 200 characters of the file happen to be, and every `@media print` in the file is a+ // candidate rather than just the first one.+ const printBlocks: string[] = [];+ for (+ let start = INDEX_CSS.indexOf("@media print");+ start >= 0;+ start = INDEX_CSS.indexOf("@media print", start + 1)+ ) {+ let depth = 0;+ for (let i = INDEX_CSS.indexOf("{", start); i < INDEX_CSS.length; i += 1) {+ if (INDEX_CSS[i] === "{") depth += 1;+ else if (INDEX_CSS[i] === "}") {+ depth -= 1;+ if (depth === 0) {+ printBlocks.push(INDEX_CSS.slice(start, i + 1));+ break;+ }+ }+ }+ }+ const printBlock =+ printBlocks.find((block) => block.includes(`.${MATH_BLOCK_CLASS}`)) ?? "";+ assert.notEqual(+ printBlock,+ "",+ "no `@media print` block in the stylesheet mentions the marked-block class, so a thread " ++ "printed before the reader has scrolled every formula into view loses them",+ );++ for (const cls of [MATH_BLOCK_CLASS, MATH_DISPLAY_CLASS]) {+ assert.ok(+ printBlock.includes(`.${cls}`),+ `the print override names .${cls}; a paragraph of prose holding a formula is lost by the ` ++ "same mechanism as the formula itself, so both populations need it",+ );+ }+ assert.ok(+ printBlock.includes("content-visibility: visible !important"),+ "`visible`, and important: the gated rules above are more specific than any unprefixed selector",+ );+ assert.ok(+ printBlock.includes("contain-intrinsic-size: none !important"),+ "and the placeholder height cleared, or a rendered block still prints at its fallback size",+ );++ // ANTI-VACUITY: the two gated `auto` rules really are the thing being overridden, and they are+ // still there to override. Without this the block above could be defending nothing.+ assert.equal(+ INDEX_CSS.split("content-visibility: auto;").length - 1,+ 2,+ "PRECONDITION: the two gated declarations this print block exists to switch off",+ );+});++test("no comment anywhere claims this feature ships off", () => {+ // THIS HAS NOW GONE WRONG THREE TIMES. Flipping `SHIP_DEFAULT` to "contain" left prose in+ // `math-block-mode.ts`, `main.tsx` and `index.css` still saying the feature defaults to off;+ // fixing "all three" then missed a SECOND block in `index.css`, because the fix was a grep for+ // the passage already known about rather than for every statement of the default. A comment+ // that documents the opposite of the shipped behaviour is what someone diagnosing a rendering+ // problem or attempting a rollback will read and believe, so it is worth a test rather than+ // another round of care.+ //+ // Deliberately a search of the WHOLE text of each file, comments included, rather than of the+ // one block a previous fix touched.+ const STALE = [+ /OFF BY DEFAULT/i,+ /never arms this rule/i,+ /which is why this ships off/i,+ /`SHIP_DEFAULT`[^.]{0,80}is\s+"off"/i,+ ];+ for (const [name, text] of [+ ["index.css", INDEX_CSS],+ ["main.tsx", MAIN_TSX],+ ["math-block-mode.ts", MATH_BLOCK_MODE],+ ] as const) {+ for (const pattern of STALE) {+ assert.ok(+ !pattern.test(text),+ `${name} still documents the old off-by-default behaviour (${pattern})`,+ );+ }+ }++ // ANTI-VACUITY. The four patterns above are only meaningful if this file's text is actually+ // being searched; a bad path would make every assertion above pass on an empty string.+ for (const [name, text] of [+ ["index.css", INDEX_CSS],+ ["main.tsx", MAIN_TSX],+ ["math-block-mode.ts", MATH_BLOCK_MODE],+ ] as const) {+ assert.ok(text.length > 500, `PRECONDITION: ${name} was actually read`);+ }+ assert.ok(+ /SHIP_DEFAULT[^\n]*=[^\n]*"contain"/.test(MATH_BLOCK_MODE),+ "PRECONDITION: the shipped default really is `contain`, or this test is defending the wrong claim",+ );+});++test("every override name a comment advertises is one the code actually reads", () => {+ // Same failure family as the test above, and it cost a review round of its own: `index.css`+ // documented the rollback switches as `VITE_UNSLOTH_MATH_BLOCK` and `__UNSLOTH_MATH_BLOCK__`,+ // but the resolver reads the `_CONTAINMENT`-suffixed names. Vite substitutes the LITERAL+ // property name at build time (vite.dev/guide/env-and-mode), so the shorter build flag is never+ // consulted, and the shorter global is never read either. An operator rolling the feature back+ // by the documented names would set them, see containment stay on, and have no signal why.+ //+ // So: gather every override-looking token out of the prose and require each to be the real one.+ // A truncated or renamed variant fails by name.+ const BUILD = "VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT";+ const RUNTIME = "__UNSLOTH_MATH_BLOCK_CONTAINMENT__";+ assert.ok(+ CONTAINMENT.includes(`import.meta.env.${BUILD}`),+ "PRECONDITION: the build flag really is read under this name",+ );+ assert.ok(+ CONTAINMENT.includes(RUNTIME),+ "PRECONDITION: the runtime flag really is read under this name",+ );++ for (const [name, text] of [+ ["index.css", INDEX_CSS],+ ["main.tsx", MAIN_TSX],+ ["math-block-mode.ts", MATH_BLOCK_MODE],+ ] as const) {+ for (const token of text.match(/\bVITE_UNSLOTH_MATH_BLOCK\w*/g) ?? []) {+ assert.equal(+ token,+ BUILD,+ `${name} advertises a build flag the code never reads`,+ );+ }+ for (const token of text.match(/\b__UNSLOTH_MATH_BLOCK\w*?__/g) ?? []) {+ assert.equal(+ token,+ RUNTIME,+ `${name} advertises a runtime flag the code never reads`,+ );+ }+ }++ // ANTI-VACUITY. The loops above pass trivially if nothing matched, which is also what a bad+ // path or a wholesale rename looks like.+ assert.ok(+ INDEX_CSS.includes(BUILD) && INDEX_CSS.includes(RUNTIME),+ "PRECONDITION: the stylesheet still documents both overrides",+ );+});++test("startup applies the mode before the first render", () => {+ // A LINE, not a substring. `includes` is satisfied by a commented-out call, which is exactly the+ // shape of the mutation that first slipped past this test.+ const lines = MAIN_TSX.split("\n");+ const callLine = lines.findIndex(+ (line) => line.trim() === "applyMathBlockContainment();",+ );+ assert.ok(+ callLine >= 0,+ "the attribute is applied at startup, on a line of its own and not in a comment",+ );+ const applyAt = MAIN_TSX.indexOf("\napplyMathBlockContainment();");+ const renderAt = MAIN_TSX.indexOf("function renderApp");+ assert.ok(renderAt > 0, "PRECONDITION: main.tsx still defines renderApp");+ assert.ok(+ applyAt < renderAt,+ "before the render, or the first thread that mounts relayouts when it is armed",+ );+});diff --git a/studio/frontend/tests/math-block-marker-pipeline.test.ts b/studio/frontend/tests/math-block-marker-pipeline.test.tsnew file mode 100644index 00000000000..07d4bb99c4b--- /dev/null+++ b/studio/frontend/tests/math-block-marker-pipeline.test.ts@@ -0,0 +1,229 @@+// 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 { createMathPlugin } from "@streamdown/math";+import rehypeRaw from "rehype-raw";+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";+import { unified } from "unified";++import { withMathBlockMarker } from "../src/components/assistant-ui/math-block-marker.ts";++/*+ * THE MARKER, RUN THROUGH THE PIPELINE IT ACTUALLY RUNS IN, rather than over a tree this file+ * built to suit itself.+ *+ * `tests/math-block-marker.test.ts` feeds the transform hast trees it constructs. That cannot+ * catch the failure this change was one refactor away from shipping: the class landing somewhere+ * the SANITIZER strips it. `rehype-sanitize`'s `defaultSchema` permits `className` on `a`, `code`,+ * `h2`, `li`, `ol`, `section` and `ul` and nowhere else, so a class put on a `<p>` before the+ * sanitize pass disappears without a word, and the whole change measures as doing nothing.+ *+ * So this reproduces Streamdown's real plugin order -- parse, gfm, remark-math, remark-rehype,+ * raw, sanitize, and only then the maths plugin's rehype pass with the marker composed in front of+ * it -- and asserts on the tree that comes out.+ */++const MARKDOWN = [+ "Energy is $E=mc^2$ in prose and $p=mv$ too.",+ "",+ "$$",+ "\\frac{a^3}{b}",+ "$$",+ "",+ // A LOOSE list, with the blank line that makes it one. A TIGHT list is unwrapped by+ // `mdast-util-to-hast`, so its item holds the maths directly and the hoist past an inline+ // paragraph never runs. A fixture built on a tight list leaves that hoist untested while+ // looking as though it covers it.+ "- loose item with $x_i$ inline",+ "",+ "- a second item, which is what makes the list loose",+ "",+ // Inside a blockquote, so that hoisting PAST the cell would have somewhere to land. A+ // root-level table has no containable ancestor at all, so it cannot tell the abandon apart+ // from the walk simply running out of tree.+ "> | h |",+ "> |---|",+ "> | $y$ |",+ "",+ // Same reasoning for display maths: inside a blockquote, so treating it as inline would put a+ // class somewhere visible to this test.+ "> $$",+ "> \\frac{c}{d}",+ "> $$",+ "",+ "# heading with $z$",+ "",+ "> quoted $q$ here",+ "",+].join("\n");++type Node = {+ type: string;+ tagName?: string;+ properties?: { className?: unknown };+ children?: Node[];+};++const render = async (markdown: string) => {+ const baseMath = createMathPlugin({ singleDollarTextMath: true });+ const [remarkMath, remarkMathOptions] = baseMath.remarkPlugin as [+ // biome-ignore lint/suspicious/noExplicitAny: a unified attacher, typed loosely on purpose+ any,+ unknown,+ ];+ const processor = unified()+ .use(remarkParse)+ .use(remarkGfm)+ .use(remarkMath, remarkMathOptions)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(rehypeRaw)+ .use(rehypeSanitize, defaultSchema)+ // unified's `Plugin` generics cannot describe an attacher composed at runtime. This is the+ // same value Streamdown takes as `MathPlugin["rehypePlugin"]`, where it typechecks.+ .use(withMathBlockMarker(baseMath.rehypePlugin) as never);+ return (await processor.run(processor.parse(markdown))) as unknown as Node;+};++const collect = (tree: Node) => {+ const marked: string[] = [];+ let displayRoots = 0;+ let mathRoots = 0;+ const walk = (node: Node) => {+ if (node.type === "element") {+ const classes = Array.isArray(node.properties?.className)+ ? node.properties.className.map(String)+ : [];+ if (classes.includes("aui-math-block")) marked.push(node.tagName ?? "?");+ if (classes.includes("katex-display")) displayRoots += 1;+ if (classes.includes("katex")) mathRoots += 1;+ }+ for (const child of node.children ?? []) walk(child);+ };+ walk(tree);+ return { marked, displayRoots, mathRoots };+};++test("the class survives the sanitizer and lands on the right blocks", async () => {+ const tree = await render(MARKDOWN);+ const { marked, displayRoots, mathRoots } = collect(tree);++ // PRECONDITION: the pipeline really rendered maths. If KaTeX silently did nothing, every+ // assertion below would be about an empty document and would still be capable of passing.+ assert.ok(+ mathRoots >= 6,+ `PRECONDITION: KaTeX rendered maths, saw ${mathRoots} roots`,+ );+ assert.equal(+ displayRoots,+ 2,+ "PRECONDITION: both display formulae rendered as such",+ );++ assert.deepEqual(+ marked,+ ["p", "h1", "p"],+ "the prose paragraph, the heading and the blockquote's paragraph",+ );+ assert.equal(+ marked.includes("li"),+ false,+ "the list item is NOT among them: containing it would cost the item its number, see " ++ "UNCONTAINABLE_TAGS in math-block-marker.ts",+ );+});++test("the list item in the fixture really does carry maths, so its absence means something", async () => {+ // Without this the assertion above passes just as well on a fixture whose list item never had a+ // formula in it, which is the shape of a test that stops testing when the fixture drifts.+ const tree = await render(MARKDOWN);+ const items: Node[] = [];+ const walk = (node: Node): void => {+ if (node.tagName === "li") items.push(node);+ for (const child of node.children ?? []) walk(child);+ };+ walk(tree);+ assert.ok(items.length >= 1, "PRECONDITION: the fixture has a list item");+ const text = JSON.stringify(items);+ assert.ok(+ text.includes("katex"),+ "PRECONDITION: that list item rendered maths, so declining to mark it is a choice",+ );+});++test("two inline formulae in one paragraph mark it once", async () => {+ // The fixture's first paragraph deliberately carries two.+ const tree = await render(MARKDOWN);+ const paragraphs = collect(tree).marked.filter((tag) => tag === "p");+ assert.equal(+ paragraphs.length,+ 2,+ "one for the prose paragraph, one for the blockquote's",+ );+});++/*+ * The two fixtures below are wrapped in a blockquote, and that is the whole point of them.+ *+ * At the root of a document there is no containable ancestor above a `pre` or above a `table`, so+ * a marker that WRONGLY treated display maths as inline, or that WRONGLY hoisted past a table+ * cell, would still mark nothing and the test would still pass. Both properties would be+ * non-load-bearing while looking covered. The blockquote gives the wrong behaviour somewhere to+ * land, so these assertions discriminate. Each one asserts that ancestor is there first.+ */++const containableAncestors = (tree: Node): string[] => {+ const found: string[] = [];+ const walk = (node: Node) => {+ if (node.type === "element" && node.tagName === "blockquote") {+ found.push(node.tagName);+ }+ for (const child of node.children ?? []) walk(child);+ };+ walk(tree);+ return found;+};++test("display maths is not marked, because `.katex-display` already is a block", async () => {+ const tree = await render("> $$\n> \\frac{a}{b}\n> $$\n");+ const { marked, displayRoots } = collect(tree);+ assert.equal(+ displayRoots,+ 1,+ "PRECONDITION: the fixture rendered display maths",+ );+ assert.deepEqual(+ containableAncestors(tree),+ ["blockquote"],+ "PRECONDITION: there is a containable ancestor a wrong answer could land on",+ );+ assert.deepEqual(marked, [], "nothing else needed marking");+});++test("maths in a table cell is left alone", async () => {+ const tree = await render("> | h |\n> |---|\n> | $y$ |\n");+ const { marked, mathRoots } = collect(tree);+ assert.ok(mathRoots >= 1, "PRECONDITION: the cell's maths rendered");+ assert.deepEqual(+ containableAncestors(tree),+ ["blockquote"],+ "PRECONDITION: there is a containable ancestor a wrong hoist could land on",+ );+ assert.deepEqual(+ marked,+ [],+ "size containment does not apply to internal table elements, so nothing is marked",+ );+});++test("a document with no maths gets no class", async () => {+ const tree = await render(+ "Just prose, and `code`, and a [link](https://example.com).\n",+ );+ assert.deepEqual(collect(tree).marked, []);+});diff --git a/studio/frontend/tests/math-block-marker.test.ts b/studio/frontend/tests/math-block-marker.test.tsnew file mode 100644index 00000000000..9395a9523ad--- /dev/null+++ b/studio/frontend/tests/math-block-marker.test.ts@@ -0,0 +1,382 @@+// 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, readdirSync } from "node:fs";+import test from "node:test";++import {+ MATH_BLOCK_CLASS,+ MATH_DISPLAY_CLASS,+ guardEquationNumbers,+ markMathBlocks,+ withMathBlockMarker,+} from "../src/components/assistant-ui/math-block-marker.ts";++/*+ * The marker, RUN over hast trees shaped the way Streamdown's pipeline actually shapes them.+ *+ * THE FIXTURE'S OWN PRECONDITIONS ARE ASSERTED FIRST, and two of them live in dependencies rather+ * than in this repo, which is the case that reading our own source would never reveal:+ *+ * - `rehype-sanitize`'s `defaultSchema` decides whether a class on a `<p>` survives at all. If it+ * ever started allowing `className` everywhere, the whole reason this marker runs where it runs+ * would evaporate, and every test below would still pass while the code became needlessly+ * convoluted. So the schema is read and asserted.+ * - Streamdown renders a list item with `[&>p]:inline`. That is the entire justification for+ * hoisting past a paragraph inside a list item. If Streamdown drops it, the hoist becomes wrong+ * and this test says so by name.+ */++type HastNode = {+ type: string;+ tagName?: string;+ properties?: { className?: unknown; [key: string]: unknown };+ children?: HastNode[];+};++const el = (+ tagName: string,+ children: HastNode[] = [],+ properties: Record<string, unknown> = {},+): HastNode => ({ type: "element", tagName, properties, children });++const text = (value: string): HastNode =>+ ({ type: "text", value }) as unknown as HastNode;++/** What `remark-math` emits for inline maths AFTER the sanitizer has been over it. */+const inlineMath = (): HastNode =>+ el("code", [text("x^2")], { className: ["language-math"] });++/** What it emits for display maths: the same `code`, wrapped in a `pre`. */+const displayMath = (): HastNode =>+ el("pre", [el("code", [text("x^2")], { className: ["language-math"] })]);++const root = (children: HastNode[]): HastNode => ({ type: "root", children });++const classesOf = (node: HastNode): string[] => {+ const raw = node.properties?.className;+ return Array.isArray(raw) ? raw.map(String) : [];+};++const marked = (node: HastNode): boolean =>+ classesOf(node).includes(MATH_BLOCK_CLASS);++const countMarked = (node: HastNode): number => {+ let n = marked(node) ? 1 : 0;+ for (const child of node.children ?? []) n += countMarked(child);+ return n;+};++test("PRECONDITION: the sanitizer would strip this class from a paragraph", async () => {+ const { defaultSchema } = (await import("hast-util-sanitize")) as {+ defaultSchema: {+ attributes?: Record<string, ReadonlyArray<unknown>>;+ };+ };+ const attributes = defaultSchema.attributes ?? {};+ const flat = (name: string): string[] =>+ (attributes[name] ?? []).map((entry) =>+ Array.isArray(entry) ? String(entry[0]) : String(entry),+ );++ assert.ok(+ !flat("*").includes("className"),+ "the wildcard schema does not permit className, so a class must be added after the sanitizer",+ );+ assert.ok(+ !flat("p").includes("className"),+ "the paragraph schema does not permit className either",+ );+ assert.ok(+ flat("code").includes("className"),+ "PRECONDITION: `code` does keep a className, which is how `language-math` survives at all",+ );+});++test("PRECONDITION: Streamdown still renders a list item's paragraph inline", () => {+ // The chunk name carries a content hash, so the directory is scanned rather than a file named.+ // A rename must not turn this precondition into a silent pass.+ const dist = new URL("../node_modules/streamdown/dist/", import.meta.url);+ const files = readdirSync(dist).filter((name) => name.endsWith(".js"));+ assert.ok(+ files.length > 0,+ "PRECONDITION: the installed Streamdown build was found",+ );+ const found = files.some((name) =>+ readFileSync(new URL(name, dist), "utf8").includes("[&>p]:inline"),+ );+ assert.ok(+ found,+ "the hoist past a paragraph inside a list item is justified by this Streamdown class",+ );+});++test("inline maths marks the paragraph that holds it", () => {+ const paragraph = el("p", [text("so "), inlineMath(), text(" grows")]);+ const tree = root([paragraph]);+ assert.equal(marked(paragraph), false, "PRECONDITION: nothing is marked yet");++ assert.equal(markMathBlocks(tree), 1);+ assert.deepEqual(classesOf(paragraph), [MATH_BLOCK_CLASS]);+ assert.equal(+ countMarked(tree),+ 1,+ "exactly one block, and it is the paragraph",+ );+});++test("an existing class list is preserved rather than replaced", () => {+ const paragraph = el("p", [inlineMath()], { className: ["prose"] });+ markMathBlocks(root([paragraph]));+ assert.deepEqual(classesOf(paragraph), ["prose", MATH_BLOCK_CLASS]);+});++test("two maths roots in one paragraph mark it once", () => {+ const paragraph = el("p", [inlineMath(), text(" and "), inlineMath()]);+ const tree = root([paragraph]);+ // The count is per maths root; the class is idempotent.+ assert.equal(markMathBlocks(tree), 2);+ assert.deepEqual(classesOf(paragraph), [MATH_BLOCK_CLASS]);+ assert.equal(countMarked(tree), 1);+});++test("inline wrappers are walked through to the block", () => {+ const paragraph = el("p", [el("em", [el("strong", [inlineMath()])])]);+ const tree = root([paragraph]);+ assert.equal(markMathBlocks(tree), 1);+ assert.ok(marked(paragraph));+ assert.equal(countMarked(tree), 1, "the em and the strong are not marked");+});++test("maths inside a list item is abandoned, so the item keeps its number", () => {+ // An earlier revision marked the `li`, because Streamdown gives its paragraph `[&>p]:inline` and+ // an inline box cannot take size containment, which leaves the item as the only containable+ // ancestor. Containing it costs the item its `::marker`: `content-visibility: auto` applies style+ // containment, style containment scopes the automatic `list-item` counter, and the item can no+ // longer resolve `counter(list-item)` for its own marker. Photographed on WebKitGTK 2.50.4 the+ // number simply vanishes on the contained items. So there is no containable ancestor here at all+ // and the maths is abandoned, as it is inside a table cell.+ const paragraph = el("p", [inlineMath()]);+ const item = el("li", [paragraph]);+ const tree = root([el("ul", [item])]);++ assert.equal(markMathBlocks(tree), 0, "nothing is marked");+ assert.equal(marked(item), false, "the list item does NOT take the class");+ assert.equal(marked(paragraph), false, "nor does its inline paragraph");+});++test("maths directly inside a list item is abandoned too, not just via a paragraph", () => {+ // The `p` inside `li` shape has its own branch. This one reaches the `li` through the ordinary+ // tag walk, so it proves the exemption is in the tag sets rather than only in that branch.+ const item = el("li", [inlineMath()]);+ const tree = root([el("ol", [item])]);++ assert.equal(markMathBlocks(tree), 0);+ assert.equal(marked(item), false);+});++test("the walk does not hoist PAST a list item and contain the whole list", () => {+ // Containing the `ol` would lose every marker in it rather than one, so `ol` and `ul` are+ // uncontainable and stop the walk instead of being skipped over.+ const item = el("li", [el("p", [inlineMath()])]);+ const list = el("ol", [item]);+ const tree = root([el("div", [list])]);++ assert.equal(markMathBlocks(tree), 0);+ assert.equal(marked(list), false, "the list itself is not marked");+ assert.equal(countMarked(tree), 0, "and nothing above it is either");+});++test("a heading and a blockquote paragraph are markable", () => {+ const heading = el("h2", [inlineMath()]);+ const quoted = el("p", [inlineMath()]);+ const tree = root([heading, el("blockquote", [quoted])]);++ assert.equal(markMathBlocks(tree), 2);+ assert.ok(marked(heading));+ assert.ok(marked(quoted), "a blockquote's paragraph is a normal block");+ assert.equal(countMarked(tree), 2, "the blockquote itself is not marked");+});++test("display maths is left alone, because `.katex-display` is already a block", () => {+ const tree = root([displayMath()]);+ assert.equal(+ (tree.children ?? []).length,+ 1,+ "PRECONDITION: the fixture is a pre-wrapped maths code element",+ );+ assert.equal(markMathBlocks(tree), 0);+ assert.equal(countMarked(tree), 0);+});++test("maths in a table cell is abandoned, not hoisted to the table", () => {+ const cell = el("td", [inlineMath()]);+ const tree = root([el("table", [el("tbody", [el("tr", [cell])])])]);+ assert.equal(+ markMathBlocks(tree),+ 0,+ "size containment does not apply to internal table elements",+ );+ assert.equal(countMarked(tree), 0);+});++test("a maths root buried deeper than the hop bound marks nothing", () => {+ let node = inlineMath();+ const depth = 13;+ for (let i = 0; i < depth; i += 1) node = el("span", [node]);+ const paragraph = el("p", [node]);+ const tree = root([paragraph]);++ assert.ok(+ depth > 12,+ "PRECONDITION: the fixture is past the twelve-hop bound",+ );+ assert.equal(markMathBlocks(tree), 0);+ assert.equal(marked(paragraph), false);+});++test("a document with no maths is untouched", () => {+ const paragraph = el("p", [text("no maths here"), el("code", [text("x")])]);+ const tree = root([paragraph]);+ assert.equal(markMathBlocks(tree), 0);+ assert.equal(countMarked(tree), 0);+});++test("the composed attacher marks the tree and then runs the maths renderer", () => {+ const seen: string[] = [];+ let optionsSeen: unknown = "not called";+ const fakeMathAttacher = (options: unknown) => {+ optionsSeen = options;+ return (tree: HastNode) => {+ // PRECONDITION for this test: the marker must already have run by the time the maths+ // renderer sees the tree, which is the whole point of composing rather than appending.+ seen.push(marked(tree.children?.[0] as HastNode) ? "marked" : "unmarked");+ };+ };++ const attacher = withMathBlockMarker([+ fakeMathAttacher,+ { errorColor: "red" },+ ]);+ const transform = attacher.call(undefined) as (+ tree: HastNode,+ file: unknown,+ ) => unknown;++ assert.deepEqual(+ optionsSeen,+ { errorColor: "red" },+ "the maths options are preserved",+ );++ const paragraph = el("p", [inlineMath()]);+ transform(root([paragraph]), {});+ assert.deepEqual(seen, ["marked"]);+ assert.ok(marked(paragraph));+});++test("the composed attacher also accepts a bare attacher with no options", () => {+ let ran = 0;+ const attacher = withMathBlockMarker(() => () => {+ ran += 1;+ });+ const transform = attacher.call(undefined) as (+ tree: HastNode,+ file: unknown,+ ) => unknown;+ const paragraph = el("p", [inlineMath()]);+ transform(root([paragraph]), {});+ assert.equal(ran, 1);+ assert.ok(marked(paragraph));+});++/*+ * EQUATION NUMBERS. `katex.css` resets `katexEqnNo` on `body` and increments it in+ * `.katex .eqn-num::before`. Style containment, which `content-visibility: auto` applies+ * unconditionally, scopes that increment per contained display. Measured on Chromium: three+ * numbered displays read (1) (2) (3) off and (1) (1) (1) on. The same fixture on WebKitGTK 2.50.4+ * does NOT reproduce it, 0 differing pixels against 120 for the list-marker case photographed in+ * the same frame, so the probe could see counter breakage and this engine simply does not do it.+ * Chromium is the engine most of the web UI runs in, so it decides.+ *+ * `guardEquationNumbers` runs AFTER KaTeX, because none of this markup exists before it.+ */++const withClass = (tag: string, className: string, children: HastNode[] = []): HastNode => {+ const node = el(tag, children);+ node.properties = { className: [className] };+ return node;+};++test("a display with no equation number gets the display class", () => {+ const display = withClass("span", "katex-display", [withClass("span", "katex")]);+ const tree = root([display]);++ assert.deepEqual(guardEquationNumbers(tree), { marked: 1, unmarked: 0 });+ assert.ok(classesOf(display).includes(MATH_DISPLAY_CLASS));+ assert.ok(classesOf(display).includes("katex-display"), "and keeps its own class");+});++test("a display WITH an equation number does not", () => {+ const numbered = withClass("span", "katex-display", [+ withClass("span", "katex", [withClass("span", "eqn-num")]),+ ]);+ const tree = root([numbered]);++ assert.deepEqual(guardEquationNumbers(tree), { marked: 0, unmarked: 0 });+ assert.equal(classesOf(numbered).includes(MATH_DISPLAY_CLASS), false);+});++test("the MathML equation number counts too", () => {+ // `katex.css` has two counters, `katexEqnNo` and `mmlEqnNo`, and only one of them appears in a+ // given output mode. Missing either would leave half the configurations broken.+ const numbered = withClass("span", "katex-display", [+ withClass("span", "katex", [withClass("span", "mml-eqn-num")]),+ ]);+ assert.deepEqual(guardEquationNumbers(root([numbered])), { marked: 0, unmarked: 0 });+ assert.equal(classesOf(numbered).includes(MATH_DISPLAY_CLASS), false);+});++test("a marked block holding a numbered display is UNMARKED", () => {+ // `markMathBlocks` runs before KaTeX, when a display is still `<pre><code>` and no `.eqn-num`+ // exists to see. A blockquote holding both inline maths and a numbered display would otherwise+ // scope the counter from above and break the numbering just as effectively as containing the+ // display itself would.+ const numbered = withClass("span", "katex-display", [+ withClass("span", "katex", [withClass("span", "eqn-num")]),+ ]);+ const quote = el("blockquote", [numbered]);+ quote.properties = { className: [MATH_BLOCK_CLASS] };+ const tree = root([quote]);++ const counts = guardEquationNumbers(tree);+ assert.equal(counts.unmarked, 1);+ assert.equal(classesOf(quote).includes(MATH_BLOCK_CLASS), false, "the block loses containment");+});++test("a marked block holding an UNNUMBERED display keeps its class", () => {+ // The control for the row above: without this, an implementation that unmarked every block+ // holding any display at all would pass and would give up containment it did not need to.+ const plain = withClass("span", "katex-display", [withClass("span", "katex")]);+ const quote = el("blockquote", [plain]);+ quote.properties = { className: [MATH_BLOCK_CLASS] };++ const counts = guardEquationNumbers(root([quote]));+ assert.equal(counts.unmarked, 0);+ assert.ok(classesOf(quote).includes(MATH_BLOCK_CLASS));+ assert.ok(classesOf(plain).includes(MATH_DISPLAY_CLASS), "and the display is still contained");+});++test("running the guard twice adds nothing the second time", () => {+ // Streamdown re-renders a settled body on every mount, so the pass has to be idempotent or the+ // class list grows without bound.+ const display = withClass("span", "katex-display", [withClass("span", "katex")]);+ const tree = root([display]);+ guardEquationNumbers(tree);+ assert.deepEqual(guardEquationNumbers(tree), { marked: 0, unmarked: 0 });+ assert.equal(+ classesOf(display).filter((c) => c === MATH_DISPLAY_CLASS).length,+ 1,+ );+});diff --git a/studio/frontend/tests/math-block-mode.test.ts b/studio/frontend/tests/math-block-mode.test.tsnew file mode 100644index 00000000000..f5f10b6f7a4--- /dev/null+++ b/studio/frontend/tests/math-block-mode.test.ts@@ -0,0 +1,135 @@+// 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 {+ FIND_IN_PAGE_PROBE,+ MATH_BLOCK_CONTAINMENT_ATTRIBUTE,+ MATH_BLOCK_CONTAINMENT_ON,+ SHIP_DEFAULT,+ gateOnEngine,+ isRuntimeForced,+ resolveMathBlockMode,+} from "../src/components/assistant-ui/math-block-mode.ts";++/**+ * The maths-block containment decision table, RUN rather than described.+ *+ * This feature changes what is on screen by one device pixel on KaTeX's vlist sub-structures, so+ * the thing that has to hold is that it is OFF unless somebody deliberately turned it on, in every+ * way it can be addressed. 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,+ "contain",+ "PRECONDITION: this feature ships ON, gated on the engine. It is +92% at 500K, 3.2 to " ++ "37 fps, with 10 differing pixels across seven screenshots. See the comment on SHIP_DEFAULT " ++ "for what is accepted rather than solved.",+ );+ // Expressed through the constant rather than through its current value, so this row keeps+ // testing "unset means the ship default" when the default next moves.+ assert.equal(resolveMathBlockMode(undefined, ""), SHIP_DEFAULT);+ assert.equal(resolveMathBlockMode(null, ""), SHIP_DEFAULT);+});++test("a mistyped build flag turns it OFF, and does not fall back to the ship default", () => {+ // The asymmetry matters now that the default is on. Someone who reaches for a flag that is+ // already enabled is reaching for it in order to disable it, so a typo landing on "off" does+ // what they meant. Resolving a typo to the default would ignore them silently, which is the+ // hazard `code-fence-mode.ts` invented a third state to avoid.+ assert.equal(SHIP_DEFAULT, "contain", "PRECONDITION: this row is about an ON default");+ assert.equal(resolveMathBlockMode(undefined, "conatin"), "off");+ assert.equal(resolveMathBlockMode(undefined, "true"), "off");+ assert.notEqual(resolveMathBlockMode(undefined, "conatin"), SHIP_DEFAULT);+});++test("the build flag turns it on, and only on the values that mean on", () => {+ assert.equal(resolveMathBlockMode(undefined, "contain"), "contain");+ assert.equal(resolveMathBlockMode(undefined, "1"), "contain");+ assert.equal(resolveMathBlockMode(undefined, "off"), "off");+ assert.equal(resolveMathBlockMode(undefined, "0"), "off");+ // A mistyped value must not land on "contain". It lands on "off", which is no longer the same+ // thing as the ship default; the row below this test is where that asymmetry is asserted.+ assert.equal(resolveMathBlockMode(undefined, "conatin"), "off");+ assert.equal(resolveMathBlockMode(undefined, "true"), "off");+});++test("the runtime global overrides the build flag in BOTH directions", () => {+ // PRECONDITION: without the runtime value these two builds disagree, so the assertions below+ // are about the override and not about the build flag being ignored.+ assert.equal(resolveMathBlockMode(undefined, "contain"), "contain");+ assert.equal(resolveMathBlockMode(undefined, "off"), "off");++ assert.equal(resolveMathBlockMode("off", "contain"), "off");+ assert.equal(resolveMathBlockMode(false, "contain"), "off");+ assert.equal(resolveMathBlockMode("contain", ""), "contain");+ assert.equal(resolveMathBlockMode(true, ""), "contain");+ assert.equal(resolveMathBlockMode("1", ""), "contain");+});++test("a non-string, non-boolean runtime value falls through to the build flag", () => {+ assert.equal(resolveMathBlockMode({}, "contain"), "contain");+ assert.equal(resolveMathBlockMode(0, "off"), "off");+ assert.equal(resolveMathBlockMode(0, ""), SHIP_DEFAULT);+});++test("the attribute the stylesheet reads is the one the stylesheet reads", () => {+ // Pinned here because `index.css` cannot import it, so the two are joined only by this pair of+ // literals and by `tests/math-block-containment-wiring.test.ts`, which reads the stylesheet.+ assert.equal(MATH_BLOCK_CONTAINMENT_ATTRIBUTE, "data-math-block-containment");+ assert.equal(MATH_BLOCK_CONTAINMENT_ON, "on");+});++/*+ * THE ENGINE GATE. WebKit below Safari 26 cannot find SKIPPED `content-visibility` content with+ * native find-in-page (webkit.org/b/283846), which `index.css` already refuses to accept for code+ * blocks. These rows run the decision rather than describing it.+ */++test("an engine that cannot find skipped content does not get containment", () => {+ assert.equal(gateOnEngine("contain", false, false), "off");+});++test("an engine that can, does", () => {+ assert.equal(gateOnEngine("contain", true, false), "contain");+});++test("the gate never turns anything ON that was already off", () => {+ assert.equal(gateOnEngine("off", true, false), "off");+ assert.equal(gateOnEngine("off", false, true), "off");+});++test("an explicit runtime override beats the gate, because that is what it is for", () => {+ // The console global exists so a measurement or a bug report can force an arm. A gate that+ // silently refused would make the flip look like it worked while measuring the other arm, which+ // is the failure mode that produces a confident wrong number.+ assert.equal(gateOnEngine("contain", false, true), "contain");+});++test("a BUILD flag does not beat the gate", () => {+ // A build ships to machines whose engines the builder cannot see, so `forcedByRuntime` is false+ // for it and the gate stands.+ assert.equal(gateOnEngine(resolveMathBlockMode(undefined, "1"), false, false), "off");+ assert.equal(gateOnEngine(resolveMathBlockMode(undefined, "1"), true, false), "contain");+});++test("only an explicit ON counts as a runtime force", () => {+ for (const value of [true, "1", "contain"]) {+ assert.equal(isRuntimeForced(value), true, `${String(value)} forces`);+ }+ for (const value of [undefined, null, false, "", "off", "0", "yes", 1]) {+ assert.equal(isRuntimeForced(value), false, `${String(value)} does not force`);+ }+});++test("the probe names a property, so CSS.supports can be handed it directly", () => {+ assert.match(+ FIND_IN_PAGE_PROBE,+ /^[a-z-]+:\s*\S/,+ "a `property: value` string is what CSS.supports takes in its one-argument form",+ );+});diff --git a/studio/frontend/tests/math-block-override-reapply.test.ts b/studio/frontend/tests/math-block-override-reapply.test.tsnew file mode 100644index 00000000000..0e30f1aa822--- /dev/null+++ b/studio/frontend/tests/math-block-override-reapply.test.ts@@ -0,0 +1,85 @@+// 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 { installOverrideWatcher } from "../src/components/assistant-ui/math-block-mode.ts";++/*+ * `applyMathBlockContainment()` is called once, before the first render. Before the watcher below,+ * a tester who set `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` from the devtools console AFTER load+ * changed nothing at all: the attribute kept its previous value and the session went on measuring+ * the arm it was already in. That is the worst thing an escape hatch can do, because the number it+ * produces looks like an answer, and it is what these rows exist to stop.+ *+ * The watcher is exercised against a plain object rather than the real global, so the tests do not+ * have to mutate `globalThis` and cannot leak into each other.+ */++const scopeWithSpy = () => {+ const scope: Record<string, unknown> = {};+ const calls: number[] = [];+ const ok = installOverrideWatcher(scope, () => {+ calls.push(1);+ return "off";+ });+ return { scope, calls, ok };+};++test("assigning the override reapplies the mode", () => {+ const { scope, calls } = scopeWithSpy();+ assert.equal(calls.length, 0, "installing the watcher does not itself apply");+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = "contain";+ assert.equal(calls.length, 1, "the assignment reapplied");+});++test("reading it back returns what was written", () => {+ // Anything that made the property write-only, or that stored somewhere else, would break the+ // documented console workflow in a different way than the bug it is fixing.+ const { scope } = scopeWithSpy();+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = "contain";+ assert.equal(scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__, "contain");+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = false;+ assert.equal(scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__, false);+});++test("a value set BEFORE the watcher is installed is preserved", () => {+ // The build flag and the measurement harness both set the global before load. Installing the+ // watcher must not discard that, or the harness would silently fall back to the ship default.+ const scope: Record<string, unknown> = {+ __UNSLOTH_MATH_BLOCK_CONTAINMENT__: "contain",+ };+ installOverrideWatcher(scope, () => "contain");+ assert.equal(scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__, "contain");+});++test("every assignment reapplies, not just the first", () => {+ const { scope, calls } = scopeWithSpy();+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = "contain";+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = "off";+ scope.__UNSLOTH_MATH_BLOCK_CONTAINMENT__ = true;+ assert.equal(calls.length, 3);+});++test("the property stays enumerable and configurable, so a later redefine is possible", () => {+ const { scope } = scopeWithSpy();+ const descriptor = Object.getOwnPropertyDescriptor(+ scope,+ "__UNSLOTH_MATH_BLOCK_CONTAINMENT__",+ );+ assert.ok(descriptor, "the property exists");+ assert.equal(descriptor.configurable, true);+ assert.equal(descriptor.enumerable, true);+});++test("a frozen scope is reported rather than throwing through startup", () => {+ // This runs from `main.tsx` before the first render. An exception there is a white screen, and+ // the flag still works when set before load, so refusing quietly is the right failure.+ const frozen = Object.freeze({} as Record<string, unknown>);+ let installed: boolean | null = null;+ assert.doesNotThrow(() => {+ installed = installOverrideWatcher(frozen, () => "off");+ });+ assert.equal(installed, false, "and it says so rather than reporting success");+});