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: fix chat scrollbar freezes on long code fences (#13919)
Eyera6c3a9e9b34b6
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex e72d00cbb3f..d463b301a98 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -252,8 +252,13 @@ export const BUDGET = {// raw, 2,054,190 -> 2,054,583 B transfer against a33463fb16, one machine and build, Node 24, chunk count// unchanged at 96): the refresh retry and outcome live in features/auth/api.ts, which every authFetch imports.// Raised by that growth, to the measured build plus the same 160 B raw / 189 B transfer margin.- transferBytes: 2_054_772,- rawBytes: 6_827_079,+ // Chunked fence lines, hoisted line colour, the progressive highlight queue, pointer state and the+ // scrollbar guard for the line window (#13919) add 11,012 B raw / 3,984 B transfer (6,826,518 ->+ // 6,837,530 B raw, 2,054,604 -> 2,058,588 B transfer against ffd6c3033, one machine and build, Node 24,+ // chunk count unchanged at 96), all in the eager chat chunk the fences render from. Raised to that+ // build plus the same 160 B raw / 189 B transfer margin.+ transferBytes: 2_058_777,+ rawBytes: 6_837_690,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/components/assistant-ui/code-fence-chunks.ts b/studio/frontend/src/components/assistant-ui/code-fence-chunks.tsnew file mode 100644index 00000000000..23e86d9b061--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/code-fence-chunks.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export const FENCE_CHUNK_LINES = 32;++export type FenceLineChunks<T> = readonly (readonly T[])[];++export function updateFenceChunks<T>(+ previous: FenceLineChunks<T> | null,+ lines: readonly T[],+): FenceLineChunks<T> {+ const count = Math.ceil(lines.length / FENCE_CHUNK_LINES);+ let next: (readonly T[])[] | null =+ previous?.length === count ? null : new Array(count);+ for (let index = 0; index < count; index += 1) {+ const start = index * FENCE_CHUNK_LINES;+ const length = Math.min(FENCE_CHUNK_LINES, lines.length - start);+ const old = previous?.[index];+ let unchanged = old?.length === length;+ if (unchanged) {+ for (let offset = 0; offset < length; offset += 1) {+ if (old![offset] !== lines[start + offset]) {+ unchanged = false;+ break;+ }+ }+ }+ if (!unchanged && next === null) next = previous!.slice();+ if (next !== null) {+ next[index] = unchanged ? old! : lines.slice(start, start + length);+ }+ }+ return next ?? previous!;+}++export type FenceBodyMemoProps<Result extends { tokens: readonly unknown[] }> = {+ isIncomplete: boolean | undefined;+ language: string | null;+ result: Result | null;+ source: string;+ windowing: boolean;+};++export function sameFenceBodyProps<Result extends { tokens: readonly unknown[] }>(+ previous: FenceBodyMemoProps<Result>,+ next: FenceBodyMemoProps<Result>,+): boolean {+ return (+ previous.result === next.result &&+ previous.language === next.language &&+ previous.isIncomplete === next.isIncomplete &&+ previous.windowing === next.windowing &&+ (previous.source === next.source ||+ (previous.result !== null && previous.result.tokens.length > 0))+ );+}diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex d601acb5b48..3b4320a8995 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -6,6 +6,7 @@import type { HighlightResult } from "@streamdown/code";import {memo,+ type CSSProperties,type RefObject,startTransition,useEffect,@@ -19,6 +20,32 @@ import { flushSync } from "react-dom";import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";import { FENCE_HEIGHT_PROPERTY } from "./code-block-containment-mode";import { type FenceMode, resolveFenceMode } from "./code-fence-mode";+import { fenceLineForeground } from "./code-fence-foreground";+import {+ FENCE_CHUNK_LINES,+ type FenceLineChunks,+ sameFenceBodyProps,+ updateFenceChunks,+} from "./code-fence-chunks";+import {+ type PlainFenceChunk,+ type PlainFenceChunks,+ updatePlainFenceChunks,+} from "./plain-fence-chunks";+import {+ createFenceHighlightQueue,+ selectionInFence,+} from "./fence-highlight-queue";+import {+ initialHighlightProgress,+ advanceHighlightProgress,+ EMPTY_HIGHLIGHT_PROGRESS,+ EMPTY_HIGHLIGHT_COUNTS,+ HIGHLIGHT_BATCH_TOKENS,+ type HighlightProgress,+ needsHighlightBatches,+ retainHighlightProgress,+} from "./fence-highlight-progress";import {EMPTY_LINE_WINDOW,HYSTERESIS_VIEWPORTS,@@ -28,6 +55,7 @@ import {lineRendered,pinBoundaryLines,samePins,+ onScrollbar,OVERSCAN_VIEWPORTS,plainLineText,selectLineWindow,@@ -37,6 +65,7 @@ import { planPrintTokenization } from "./code-fence-print";import { createFenceSpeculator } from "./fence-speculation";import { highlightWorkerState, streamActive } from "./use-reasoning-highlight";import { inputQuietIn, scheduleQuietIdleTask } from "@/lib/schedule-idle-task";+import { inputPointerHeld } from "@/lib/input-pointer-state";import {MAX_CACHED_CHARACTERS,MAX_FENCES,@@ -114,14 +143,22 @@ const shellBody = (source: string): string => {return trimmed === "" ? "\n" : trimmed;};-const shellLines = (source: string): string[] => {- const nodes: string[] = [];- for (const [index, line] of shellBody(source).split("\n").entries()) {- if (index > 0) nodes.push("\n");- if (line !== "") nodes.push(line);- }- return nodes;-};+const PlainFenceTextChunk = memo(function PlainFenceTextChunk({+ nodes,+}: {+ nodes: PlainFenceChunk;+}) {+ return <>{nodes}</>;+});++function PlainFenceText({ source }: { source: string }) {+ const [previous, setPrevious] = useState<PlainFenceChunks>(() => updatePlainFenceChunks(null, source));+ const current = previous.source === source ? previous : updatePlainFenceChunks(previous, source);+ if (current !== previous) setPrevious(current);+ return <>{current.chunks.map((nodes, index) => (+ <PlainFenceTextChunk key={index} nodes={nodes} />+ ))}</>;+}function FenceShell({language,@@ -152,7 +189,7 @@ function FenceShell({data-streamdown="code-block-body"><pre>- <code>{plain ? shellLines(source) : shellBody(source)}</code>+ <code>{plain ? <PlainFenceText source={source} /> : shellBody(source)}</code></pre></div></div>@@ -199,6 +236,19 @@ type FenceGate = {};const unreached = new Set<FenceGate>();+const pendingReaches = new Map<FenceGate, () => void>();++const deferReaches = (): boolean =>+ fenceMode() === "defer" && !printing && !findBarOpen();++const queueReach = (gate: FenceGate): void => {+ if (pendingReaches.has(gate)) return;+ const cancel = queueFenceWork(() => {+ pendingReaches.delete(gate);+ if (unreached.has(gate) && gateOpen(gate)) latchNow([gate]);+ });+ pendingReaches.set(gate, cancel);+};/** Is this gate's fence where the observers would call it reached? */const gateOpen = (gate: FenceGate): boolean =>@@ -226,6 +276,8 @@ const gateOpen = (gate: FenceGate): boolean =>const latchNow = (arrived: readonly FenceGate[]): void => {if (arrived.length === 0) return;for (const gate of arrived) {+ pendingReaches.get(gate)?.();+ pendingReaches.delete(gate);unreached.delete(gate);fenceSpeculator.remove(gate);gate.warm(true);@@ -261,6 +313,10 @@ let scrollWatched = false;const onScroll = (event: Event): void => {if (unreached.size === 0) return;+ if (deferReaches()) {+ fenceSpeculator.rerank();+ return;+ }const target = event.target;if (target === null) return;const element = target === document ? null : (target as HTMLElement);@@ -354,11 +410,17 @@ const grammarOf = (gate: FenceGate): string =>normalizeLanguage(gate.language ?? "text");const warmMustWait = (): boolean =>- typeof (globalThis as Record<string, unknown>).requestIdleCallback !== "function"- && (streamActive() || inputQuietIn() > 0);+ inputPointerHeld() || inputQuietIn() > 0+ || (typeof (globalThis as Record<string, unknown>).requestIdleCallback !== "function"+ && streamActive());const warmGrammars = (): void => {warmScheduled = false;+ if (unreached.size === 0) return;+ if (warmMustWait()) {+ scheduleGrammarWarm();+ return;+ }// EVERY GRAMMAR STARTS LOADING IN THE FIRST TASK. A load is cheap and asynchronous, and it is// what `latchNow` needs already present; only the tokenizations below are worth yielding for.for (const gate of unreached) {@@ -391,6 +453,11 @@ const warmGrammars = (): void => {const scheduleGrammarWarm = (): void => {if (warmScheduled || typeof globalThis === "undefined") return;warmScheduled = true;+ const quiet = inputQuietIn();+ if (inputPointerHeld() || quiet > 0) {+ setTimeout(warmGrammars, Math.max(80, quiet));+ return;+ }const idle = (globalThis as Record<string, unknown>).requestIdleCallback as| ((cb: () => void, options?: { timeout: number }) => number)| undefined;@@ -425,7 +492,8 @@ const fenceSpeculator = createFenceSpeculator<FenceGate>({},enabled: () =>fenceMode() !== "off" && highlightWorkerState() !== "unavailable",- busy: () => streamActive() || highlightWorkerState() === "stalled",+ busy: () => streamActive() || highlightWorkerState() === "stalled"+ || inputPointerHeld() || inputQuietIn() > 0,eligible: (gate) => grammarsWarmed.has(grammarOf(gate)),rank: rankGates,maxChars: MAX_HIGHLIGHT_CHARS,@@ -637,6 +705,7 @@ export function useFenceReached(*/useLayoutEffect(() => {if (reached) return;+ if (deferReaches()) return;const node = host.current;if (!node) return;// The same two questions the observers below ask, of the same two elements: is the FENCE in@@ -677,6 +746,10 @@ export function useFenceReached((entries) => {seen[i] = entries.some((entry) => entry.isIntersecting);if (!seen.every(Boolean)) return;+ if (deferReaches()) {+ queueReach(registered);+ return;+ }for (const each of observers) each.disconnect();setLatched(true);},@@ -717,6 +790,8 @@ export function useFenceReached(return () => {for (const observer of observers) observer.disconnect();resize?.disconnect();+ pendingReaches.get(registered)?.();+ pendingReaches.delete(registered);fenceSpeculator.remove(registered);unreached.delete(registered);unwatchScrolling();@@ -837,11 +912,14 @@ export const FenceLine = memo(function FenceLine({line,windowed,inline = false,+ highlighted = Number.POSITIVE_INFINITY,}: {line: TokenLine;windowed: boolean;inline?: boolean;+ highlighted?: number;}) {+ const lineClass = inline ? "inline" : LINE_CLASS;if (!inline && isBlankLine(line)) {return <span className={LINE_CLASS}>{"\n"}</span>;}@@ -849,14 +927,23 @@ export const FenceLine = memo(function FenceLine({// 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={inline ? "inline" : LINE_CLASS}>+ <span className={lineClass}>{plainLineText(line)}</span>);}+ const foreground = fenceLineForeground(line);return (- <span className={inline ? "inline" : LINE_CLASS}>- {line.map((token, index) => {+ <span+ className={foreground ? `${lineClass} ${TOKEN_CLASS}` : lineClass}+ style={+ foreground+ ? { "--sdm-c": foreground.light, "--shiki-dark": foreground.dark } as CSSProperties+ : undefined+ }+ >+ {(highlighted >= line.length ? line : line.slice(0, highlighted)).map((token, index) => {+ if (foreground?.inherited[index]) return token.content;const { style, hasBackground } = tokenStyle(token);return (<span@@ -870,11 +957,101 @@ export const FenceLine = memo(function FenceLine({{token.content}</span>);- })}+ })}{highlighted < line.length ? line.slice(highlighted).map((token) => token.content).join("") : null}</span>);});+const FenceTokenChunk = memo(function FenceTokenChunk({+ tokens,+ foreground,+ start,+ highlighted,+}: {+ tokens: readonly FenceToken[];+ foreground: ReturnType<typeof fenceLineForeground>;+ start: number;+ highlighted: number;+}) {+ return <>{(highlighted >= tokens.length ? tokens : tokens.slice(0, highlighted)).map((token, index) => {+ if (foreground?.inherited[start + index]) return token.content;+ 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>;+ })}{highlighted < tokens.length ? tokens.slice(highlighted).map((token) => token.content).join("") : null}</>;+});++const DenseFenceLine = memo(function DenseFenceLine({+ line,+ highlighted,+}: {+ line: TokenLine;+ highlighted: number;+}) {+ const chunks = useMemo(() => updateFenceChunks(null, line), [line]);+ const foreground = useMemo(() => fenceLineForeground(line), [line]);+ return <span+ className={foreground ? `${LINE_CLASS} ${TOKEN_CLASS}` : LINE_CLASS}+ style={foreground+ ? { "--sdm-c": foreground.light, "--shiki-dark": foreground.dark } as CSSProperties+ : undefined}+ >{chunks.map((tokens, index) => <FenceTokenChunk+ key={index}+ tokens={tokens}+ foreground={foreground}+ start={index * FENCE_CHUNK_LINES}+ highlighted={Math.max(0, Math.min(tokens.length, highlighted - index * FENCE_CHUNK_LINES))}+ />)}</span>;+});++const FenceLineChunk = memo(function FenceLineChunk({+ lines,+ limits,+ dense,+}: {+ lines: readonly TokenLine[];+ limits: readonly number[] | null;+ dense: boolean;+}) {+ return <>{lines.map((line, index) => {+ const count = limits === null ? Number.POSITIVE_INFINITY : limits[index] ?? 0;+ return dense && line.length > HIGHLIGHT_BATCH_TOKENS+ ? <DenseFenceLine key={index} line={line} highlighted={count} />+ : <FenceLine key={index} line={line} windowed={count > 0}+ highlighted={count >= line.length ? Number.POSITIVE_INFINITY : count} />;+ })}</>;+});++const FenceLines = memo(function FenceLines({+ tokens,+ highlighted,+ staged = false,+}: {+ tokens: TokenLine[];+ highlighted: HighlightProgress | null;+ staged?: boolean;+}) {+ const [dense] = useState(staged);+ const [previous, setPrevious] = useState<{+ tokens: TokenLine[];+ chunks: FenceLineChunks<TokenLine>;+ }>(() => ({ tokens, chunks: updateFenceChunks(null, tokens) }));+ const current = previous.tokens === tokens+ ? previous+ : { tokens, chunks: updateFenceChunks(previous.chunks, tokens) };+ if (current !== previous) setPrevious(current);+ return <>{current.chunks.map((lines, index) => <FenceLineChunk+ key={index}+ lines={lines}+ limits={highlighted === null ? null : highlighted.counts[index] ?? EMPTY_HIGHLIGHT_COUNTS}+ dense={dense}+ />)}</>;+});+// 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.@@ -886,6 +1063,7 @@ let frameRects: Map<Element, DOMRect> | null = null;let frameFlying: Map<Element | null, boolean> | null = null;let frameSettle = false;let pointerHeld: Node | null = null;+let barHeld: HTMLElement | null = null;let heldLastFrame = false;let frameSelection: { read: boolean; value: Selection | null } | null = null;const scrollerMotion = new WeakMap<Element, { top: number; at: number }>();@@ -917,8 +1095,27 @@ const selectionDuringFrame = (): Selection | null => {return frameSelection.value;};-const draggingDuringFrame = (body: HTMLElement): boolean => {- const held = pointerHeld !== null && body.contains(pointerHeld);+// A thumb press targets the scroller, an ancestor of the fence body, so `pointerHeld` misses it and+// the window would move on every frame of the drag; hold it until release instead.+const scrollbarOf = (event: PointerEvent): HTMLElement | null => {+ const target = event.target;+ if (!(target instanceof HTMLElement)) return null;+ const spot = {+ offsetX: event.offsetX,+ offsetY: event.offsetY,+ clientWidth: target.clientWidth,+ clientHeight: target.clientHeight,+ };+ return onScrollbar(spot) && isScrollable(target) ? target : null;+};++const draggingDuringFrame = (+ body: HTMLElement,+ scroller: HTMLElement | null,+): boolean => {+ const held =+ (pointerHeld !== null && body.contains(pointerHeld))+ || (barHeld !== null && barHeld === scroller);if (held) heldLastFrame = true;return held;};@@ -1035,6 +1232,160 @@ const findBarOpen = (): boolean =>typeof document !== "undefined"&& document.documentElement.hasAttribute(FIND_BAR_FLAG);+export const fenceNeedsQuietWork = (+ language: string | null,+ source: string,+ streaming = false,+): boolean =>+ !streaming && typeof window !== "undefined" && deferReaches()+ && !justStreamed(language, source.slice(0, FENCE_HEAD_CHARS), trimmedLength(source));++let highlightWatching = false;+let highlightFindObserver: MutationObserver | null = null;+let highlightResizedAt = Number.NEGATIVE_INFINITY;++const highlightResize = (): void => {+ highlightResizedAt = performance.now();+};++const highlightQuietIn = (): number =>+ Math.max(inputQuietIn(), 300 - (performance.now() - highlightResizedAt));++const highlightQueue = createFenceHighlightQueue({+ schedule: (run) => {+ let frame = 0;+ let cancelIdle: (() => void) | undefined;+ const timer = setTimeout(() => {+ frame = requestAnimationFrame(() => {+ cancelIdle = scheduleQuietIdleTask(run, 100);+ });+ }, Math.max(0, highlightQuietIn(), inputPointerHeld() || selectionInFence(liveSelection()) ? 80 : 0));+ return () => {+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ cancelIdle?.();+ };+ },+ blocked: () => inputPointerHeld() || highlightQuietIn() > 0 || selectionInFence(liveSelection()),+ commit: (run) => flushSync(run),+});++const watchHighlighting = (): void => {+ if (highlightWatching) return;+ highlightWatching = true;+ window.addEventListener("resize", highlightResize, { passive: true });+ highlightFindObserver = new MutationObserver(() => {+ if (findBarOpen()) highlightQueue.flush();+ });+ highlightFindObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: [FIND_BAR_FLAG],+ });+};++let highlightTeardownPending = false;+const unwatchHighlighting = (): void => {+ if (!highlightWatching || highlightTeardownPending) return;+ highlightTeardownPending = true;+ queueMicrotask(() => {+ highlightTeardownPending = false;+ if (!highlightWatching || highlightQueue.pending() > 0) return;+ highlightWatching = false;+ window.removeEventListener("resize", highlightResize);+ highlightFindObserver?.disconnect();+ highlightFindObserver = null;+ });+};++export function queueFenceWork(work: () => void): () => void {+ if (typeof window === "undefined" || printing || findBarOpen()) {+ work();+ return () => {};+ }+ watchHighlighting();+ let cancel = () => {};+ const finish = (): void => {+ cancel();+ work();+ };+ const remove = highlightQueue.add(() => {+ finish();+ return true;+ }, finish);+ cancel = () => {+ remove();+ unwatchHighlighting();+ };+ return cancel;+}++const visibleHighlightLine = (code: HTMLElement | null, frame: HTMLElement | null): number => {+ const first = code?.firstElementChild;+ if (!first || !frame) return 0;+ const line = first.getBoundingClientRect();+ if (line.height <= 0) return 0;+ let top = 0;+ let bottom = window.innerHeight;+ for (let ancestor = frame.parentElement; ancestor !== null; ancestor = ancestor.parentElement) {+ if (!isScrollable(ancestor)) continue;+ const rect = ancestor.getBoundingClientRect();+ top = Math.max(top, rect.top + ancestor.clientTop);+ bottom = Math.min(bottom, rect.top + ancestor.clientTop + ancestor.clientHeight);+ }+ if (top >= bottom || line.top >= bottom) return 0;+ return Math.max(0, Math.floor((top - line.top) / line.height));+};++function useFenceHighlightLimit(+ tokens: FenceTokens["tokens"] | null,+ isIncomplete: boolean | undefined,+ windowing: boolean,+ language: string | null,+ source: string,+ code: RefObject<HTMLElement | null>,+ frame: RefObject<HTMLElement | null>,+): { progress: HighlightProgress | null; staged: boolean } {+ const eligible = !(typeof window === "undefined" || windowing || isIncomplete+ || fenceMode() !== "defer"+ || justStreamed(language, source.slice(0, FENCE_HEAD_CHARS), trimmedLength(source)));+ const [eager, setEager] = useState(!eligible);+ if (!eligible && !eager) setEager(true);+ const staged = eligible && !eager;+ const large = useMemo(+ () => staged && tokens !== null && needsHighlightBatches(tokens, WINDOW_CAP_LINES),+ [staged, tokens],+ );+ const immediate = !staged || printing || findBarOpen() || (tokens !== null && !large);+ const [previous, setPrevious] = useState<{+ tokens: typeof tokens;+ progress: HighlightProgress | null;+ }>(() => ({ tokens, progress: immediate ? null : tokens === null+ ? EMPTY_HIGHLIGHT_PROGRESS : initialHighlightProgress(tokens) }));+ let current = previous;+ if (staged && previous.tokens !== tokens) {+ current = { tokens, progress: immediate || tokens === null+ ? null : retainHighlightProgress(previous.tokens, tokens, previous.progress) };+ } else if (immediate && previous.progress !== null) {+ current = { tokens, progress: null };+ }+ if (current !== previous) setPrevious(current);+ const progress = immediate ? null : current.progress;+ useLayoutEffect(() => {+ if (progress === null || tokens === null) return;+ watchHighlighting();+ const cancel = highlightQueue.add(() => {+ const visible = progress.located ? 0 : visibleHighlightLine(code.current, frame.current);+ setPrevious({ tokens, progress: advanceHighlightProgress(tokens, progress, visible) });+ return true;+ }, () => setPrevious({ tokens, progress: null }));+ return () => {+ cancel();+ unwatchHighlighting();+ };+ }, [tokens, progress, code, frame]);+ return { progress, staged };+}+/** 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.@@ -1049,7 +1400,9 @@ const setPrinting = (value: boolean): void => {cancelAnimationFrame(windowFrame);windowFrame = 0;}+ if (value) highlightQueue.flush();if (value) tokenizeForPrint();+ if (value) highlightQueue.flush();if (windowedFences.size === 0) return;flushSync(remeasureWindows);};@@ -1062,11 +1415,13 @@ const scheduleRemeasure = (): void => {const onPointerDown = (event: PointerEvent): void => {if (event.pointerType === "touch" || event.button !== 0) return;pointerHeld = event.target instanceof Node ? event.target : null;+ barHeld = scrollbarOf(event);};const releasePointer = (): void => {- if (pointerHeld === null) return;+ if (pointerHeld === null && barHeld === null) return;pointerHeld = null;+ barHeld = null;if (heldLastFrame) scheduleRemeasure();};@@ -1141,6 +1496,7 @@ const unwatchWindows = (): void => {findBarObserver?.disconnect();findBarObserver = null;pointerHeld = null;+ barHeld = null;heldLastFrame = false;if (windowFrame !== 0) {cancelAnimationFrame(windowFrame);@@ -1356,7 +1712,7 @@ function useLineWindow(return;}if (current.current !== null && flyingDuringFrame(known.scroller, viewportHeight)) return;- if (current.current !== null && draggingDuringFrame(body)) return;+ if (current.current !== null && draggingDuringFrame(body, known.scroller)) return;const next = selectLineWindow({lineCount: lines.current,lineHeight: known.lineHeight,@@ -1447,6 +1803,7 @@ export const FenceBody = memo(function FenceBody({const wrapper = useRef<HTMLDivElement | null>(null);const frame = useRef<HTMLDivElement | null>(null);const tokens = result?.tokens ?? null;+ const highlight = useFenceHighlightLimit(tokens, isIncomplete, windowing, language, source, code, frame);const { window: lineWindow, pins, measured } = useLineWindow(code,surface,@@ -1494,6 +1851,11 @@ export const FenceBody = memo(function FenceBody({<span className="ml-1 font-mono lowercase">{language}</span></div><div+ data-unsloth-fence-paint={+ !isIncomplete && !windowing && tokens.length > WINDOW_CAP_LINES+ ? "true"+ : undefined+ }data-unsloth-fence-windowed={lineWindow === null || !measured ? undefined : "true"}ref={wrapper}>@@ -1508,17 +1870,17 @@ export const FenceBody = memo(function FenceBody({><pre className={joinClasses(languageClass, PRE_CLASS)} style={rootStyle}><code className={CODE_CLASS} ref={code}>- {tokens.map((line, index) => (+ {windowing ? tokens.map((line, index) => (<FenceLinekey={index}line={line}windowed={lineRendered(lineWindow, pins, index)}/>- ))}+ )) : <FenceLines tokens={tokens} highlighted={highlight.progress} staged={highlight.staged} />}</code></pre></div></div></div>);-});+}, sameFenceBodyProps);diff --git a/studio/frontend/src/components/assistant-ui/code-fence-foreground.ts b/studio/frontend/src/components/assistant-ui/code-fence-foreground.tsnew file mode 100644index 00000000000..a018d7f9423--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/code-fence-foreground.ts@@ -0,0 +1,54 @@+// 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 type { HighlightResult } from "@streamdown/code";++type TokenLine = HighlightResult["tokens"][number];++const COLOR = /^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;+const EXTRA_STYLES = new Set([+ "background-color",+ "font-style",+ "font-weight",+ "text-decoration",+ "--shiki-dark-bg",+ "--shiki-dark-font-style",+ "--shiki-dark-font-weight",+ "--shiki-dark-text-decoration",+]);++export function fenceLineForeground(line: TokenLine): {+ light: string;+ dark: string;+ inherited: boolean[];+} | null {+ const candidates: (string | null)[] = [];+ let chosen = "";+ for (const token of line) {+ const style = token.htmlStyle ?? {};+ const light = style.color ?? token.color;+ const dark = style["--shiki-dark"];+ if (+ !light ||+ !dark ||+ !COLOR.test(light) ||+ !COLOR.test(dark) ||+ (token.htmlAttrs && Object.keys(token.htmlAttrs).length > 0)+ )+ return null;+ const extra = Object.keys(style).filter(+ (key) => key !== "color" && key !== "--shiki-dark",+ );+ if (extra.some((key) => !EXTRA_STYLES.has(key))) return null;+ if (token.bgColor || token.fontStyle || extra.length > 0) {+ candidates.push(null);+ continue;+ }+ const key = `${light.toLowerCase()}|${dark.toLowerCase()}`;+ candidates.push(key);+ if (!chosen) chosen = key;+ }+ if (!chosen) return null;+ const [light, dark] = chosen.split("|");+ return { light, dark, inherited: candidates.map((key) => key === chosen) };+}diff --git a/studio/frontend/src/components/assistant-ui/code-fence-window.ts b/studio/frontend/src/components/assistant-ui/code-fence-window.tsindex bc45bf9f157..2fe31709280 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-window.ts+++ b/studio/frontend/src/components/assistant-ui/code-fence-window.ts@@ -32,6 +32,18 @@ export const OVERSCAN_VIEWPORTS = 1;// boundaries, the thrash that killed the earlier bidirectional gate.export const HYSTERESIS_VIEWPORTS = 0.5;+// `offsetX`/`offsetY` are from the padding box, so only a scrollbar press lands at or past the+// client size.+export type PointerSpot = {+ offsetX: number;+ offsetY: number;+ clientWidth: number;+ clientHeight: number;+};++export const onScrollbar = (spot: PointerSpot): boolean =>+ spot.offsetX >= spot.clientWidth || spot.offsetY >= spot.clientHeight;+export type WindowGeometry = {lineCount: number;/** MEASURED from the rendered block, never assumed. */diff --git a/studio/frontend/src/components/assistant-ui/fence-highlight-progress.ts b/studio/frontend/src/components/assistant-ui/fence-highlight-progress.tsnew file mode 100644index 00000000000..689f29eb485--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/fence-highlight-progress.ts@@ -0,0 +1,122 @@+// 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 { FENCE_CHUNK_LINES, type FenceLineChunks } from "./code-fence-chunks.ts";++export const HIGHLIGHT_BATCH_TOKENS = 512;+export const HIGHLIGHT_BATCH_LINES = 64;+export const HIGHLIGHT_TOKEN_CAP = 4096;++export type HighlightProgress = {+ counts: FenceLineChunks<number>;+ cursor: number;+ located: boolean;+};++type Lines = readonly { length: number }[];++export const EMPTY_HIGHLIGHT_COUNTS: readonly number[] = [];++export const EMPTY_HIGHLIGHT_PROGRESS: HighlightProgress = {+ counts: [], cursor: 0, located: false,+};++export const highlightLineCount = (progress: HighlightProgress, line: number): number =>+ progress.counts[Math.floor(line / FENCE_CHUNK_LINES)]?.[line % FENCE_CHUNK_LINES] ?? 0;++export function needsHighlightBatches(lines: Lines, lineCap: number): boolean {+ if (lines.length > lineCap) return true;+ let tokens = 0;+ for (const line of lines) {+ tokens += line.length;+ if (tokens > HIGHLIGHT_TOKEN_CAP) return true;+ }+ return false;+}++export function advanceHighlightProgress(+ lines: Lines,+ progress: HighlightProgress,+ visibleLine = 0,+): HighlightProgress | null {+ const requested = progress.located ? progress.cursor : visibleLine;+ let cursor = Number.isFinite(requested) && requested >= 0 && requested < lines.length+ ? Math.trunc(requested) : 0;+ let counts: (readonly number[])[] | null = null;+ const changed = new Map<number, number[]>();+ let remaining = HIGHLIGHT_BATCH_TOKENS;+ let touched = 0;+ let scanned = 0;+ while (scanned < lines.length) {+ const length = lines[cursor].length;+ const groupIndex = Math.floor(cursor / FENCE_CHUNK_LINES);+ const offset = cursor % FENCE_CHUNK_LINES;+ const before = counts?.[groupIndex]?.[offset] ?? highlightLineCount(progress, cursor);+ const missing = length - before;+ if (missing > 0) {+ if (remaining === 0 || touched === HIGHLIGHT_BATCH_LINES+ || (length <= HIGHLIGHT_BATCH_TOKENS && missing > remaining)) break;+ const groupCount = Math.ceil(lines.length / FENCE_CHUNK_LINES);+ counts ??= progress.counts.length === groupCount+ ? progress.counts.slice()+ : Array.from({ length: groupCount }, (_, index) => progress.counts[index] ?? EMPTY_HIGHLIGHT_COUNTS);+ let group = changed.get(groupIndex);+ if (!group) {+ const length = Math.min(FENCE_CHUNK_LINES, lines.length - groupIndex * FENCE_CHUNK_LINES);+ const previous = progress.counts[groupIndex];+ group = previous?.length === length+ ? previous.slice()+ : Array.from({ length }, (_, index) => previous?.[index] ?? 0);+ changed.set(groupIndex, group);+ counts[groupIndex] = group;+ }+ const added = Math.min(missing, remaining);+ group[offset] = before + added;+ remaining -= added;+ touched += 1;+ if (added < missing) break;+ }+ cursor = (cursor + 1) % lines.length;+ scanned += 1;+ }+ return scanned === lines.length+ ? null+ : { counts: counts ?? progress.counts, cursor, located: true };+}++export function initialHighlightProgress(lines: Lines): HighlightProgress | null {+ const progress = advanceHighlightProgress(lines, EMPTY_HIGHLIGHT_PROGRESS);+ return progress === null ? null : { ...progress, located: false };+}++export function retainHighlightProgress(+ previous: Lines | null,+ next: Lines,+ progress: HighlightProgress | null,+): HighlightProgress | null {+ let complete = true;+ const counts: (readonly number[])[] = [];+ for (let start = 0; start < next.length; start += FENCE_CHUNK_LINES) {+ const length = Math.min(FENCE_CHUNK_LINES, next.length - start);+ const oldGroup = progress?.counts[start / FENCE_CHUNK_LINES];+ let group: number[] | null = null;+ for (let offset = 0; offset < length; offset += 1) {+ const index = start + offset;+ const old = progress === null ? previous?.[index]?.length ?? 0 : oldGroup?.[offset] ?? 0;+ const count = Math.min(old, next[index].length);+ if (count < next[index].length) complete = false;+ if (count !== (oldGroup?.[offset] ?? 0)) {+ group ??= Array.from({ length }, (_, index) => oldGroup?.[index] ?? 0);+ group[offset] = count;+ }+ }+ counts.push(group ?? (oldGroup && oldGroup.length <= length ? oldGroup+ : oldGroup?.slice(0, length) ?? EMPTY_HIGHLIGHT_COUNTS));+ }+ if (complete) return null;+ return {+ counts,+ cursor: Math.min(progress?.cursor ?? 0, Math.max(0, next.length - 1)),+ located: progress?.located ?? false,+ };+}diff --git a/studio/frontend/src/components/assistant-ui/fence-highlight-queue.ts b/studio/frontend/src/components/assistant-ui/fence-highlight-queue.tsnew file mode 100644index 00000000000..bd2b58e552e--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/fence-highlight-queue.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Highlighting swaps only a fence's own line nodes, so only a selection ending inside a fence+// needs holding.+export const selectionInFence = (+ selection: Pick<Selection, "anchorNode" | "focusNode"> | null,+): boolean => {+ const inFence = (node: Node | null): boolean => {+ const element = node !== null && node.nodeType === 1 ? node as Element : node?.parentElement ?? null;+ return element?.closest('[data-streamdown="code-block"]') != null;+ };+ return selection !== null && (inFence(selection.anchorNode) || inFence(selection.focusNode));+};++type HighlightEntry = {+ step: () => boolean;+ finish: () => void;+};++export type FenceHighlightQueueOptions = {+ schedule: (callback: () => void) => () => void;+ blocked: () => boolean;+ commit: (callback: () => void) => void;+};++export function createFenceHighlightQueue(options: FenceHighlightQueueOptions): {+ add: (step: () => boolean, finish: () => void) => () => void;+ flush: () => void;+ pending: () => number;+} {+ const entries = new Set<HighlightEntry>();+ let scheduled: { cancel: (() => void) | null } | null = null;+ let running = false;+ let flushing = false;++ const cancelScheduled = (): void => {+ const previous = scheduled;+ scheduled = null;+ previous?.cancel?.();+ };++ const schedule = (): void => {+ if (scheduled || running || flushing || entries.size === 0) return;+ const ticket = { cancel: null as (() => void) | null };+ scheduled = ticket;+ try {+ ticket.cancel = options.schedule(() => {+ if (scheduled !== ticket) return;+ scheduled = null;+ run();+ });+ } catch (error) {+ if (scheduled === ticket) scheduled = null;+ entries.clear();+ throw error;+ }+ };++ const run = (): void => {+ running = true;+ let entry: HighlightEntry | undefined;+ try {+ if (options.blocked()) return;+ entry = entries.values().next().value;+ if (!entry) return;+ const current = entry;+ let complete = false;+ options.commit(() => {+ if (entries.has(current)) complete = current.step();+ });+ if (entries.delete(current) && !complete) entries.add(current);+ } catch (error) {+ if (entry) entries.delete(entry);+ else entries.clear();+ throw error;+ } finally {+ running = false;+ schedule();+ }+ };++ const flush = (): void => {+ if (flushing) return;+ cancelScheduled();+ flushing = true;+ let failure: { error: unknown } | null = null;+ try {+ while (entries.size > 0) {+ try {+ options.commit(() => {+ while (entries.size > 0) {+ const entry = entries.values().next().value as HighlightEntry;+ entries.delete(entry);+ try {+ entry.finish();+ } catch (error) {+ failure ??= { error };+ }+ }+ });+ } catch (error) {+ entries.clear();+ failure ??= { error };+ }+ }+ } finally {+ flushing = false;+ schedule();+ }+ if (failure) throw failure.error;+ };++ return {+ add: (step, finish) => {+ const entry = { step, finish };+ entries.add(entry);+ schedule();+ return () => {+ entries.delete(entry);+ if (entries.size === 0) cancelScheduled();+ };+ },+ flush,+ pending: () => entries.size,+ };+}diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex c7e10945f68..9b379692940 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -78,8 +78,10 @@ import {FenceBody,type FenceTokens,fenceMode,+ fenceNeedsQuietWork,noteStreamingFence,PlainFenceShell,+ queueFenceWork,trimmedLength,trimTrailingNewlines,useFenceReached,@@ -977,6 +979,8 @@ function useFenceTokens(enabled: boolean,streaming: boolean,): FenceTokens | null {+ const [eager, setEager] = useState(() => !fenceNeedsQuietWork(languageToken, source, streaming));+ if (!eager && !fenceNeedsQuietWork(languageToken, source, streaming)) setEager(true);const highlight = useCallback((body: string, late: (result: FenceTokens) => void) =>streaming@@ -985,7 +989,7 @@ function useFenceTokens([languageToken, streaming],);const [seed] = useState<{ body: string; tokens: FenceTokens } | null>(() => {- if (!enabled) return null;+ if (!enabled || !eager) return null;const body = trimTrailingNewlines(source);const options = fenceHighlightOptions(body, languageToken);const settled = settlesOffThread(body, streaming, options)@@ -998,15 +1002,7 @@ function useFenceTokens();const wanted = useRef("");const seedConsumed = useRef(false);- /*- * 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.- */+ const displayed = useRef(seed ? { body: seed.body, language: languageToken } : null);useLayoutEffect(() => {if (!enabled) return;const body = trimTrailingNewlines(source);@@ -1015,67 +1011,112 @@ function useFenceTokens(seedConsumed.current = true;if (seed?.body === body) return;}- const late = (result: FenceTokens) => {- if (wanted.current === body) setTokens(result);- };+ let active = true;let cancel: (() => void) | null = null;let release: (() => void) | null = null;- let settled: FenceTokens | null = null;+ let cancelStart: (() => void) | null = null;+ let cancelPublish: (() => void) | null = null;+ let cancelFallback: (() => void) | null = null;const options = fenceHighlightOptions(body, languageToken);- if (settlesOffThread(body, streaming, options)) {- const failover = !tokenizesOffThread(body, streaming);- settled = code.cached(options);- if (settled === null) {- cancel = requestFullHighlight(- body,- languageToken,- (result) => {- if (result === null) {- if (failover && wanted.current === body) {- setTokens(highlight(body, late));+ const current = (): boolean => active && wanted.current === body;+ const defer = (): boolean => !eager && fenceNeedsQuietWork(languageToken, source, streaming);+ const show = (result: FenceTokens | null): void => {+ if (!current()) return;+ displayed.current = result === null ? null : { body, language: languageToken };+ setTokens(result);+ };+ const publish = (work: () => void): void => {+ if (!current()) return;+ cancelPublish?.();+ cancelPublish = null;+ if (defer()) {+ cancelPublish = queueFenceWork(() => {+ cancelPublish = null;+ if (current()) work();+ });+ } else work();+ };+ const late = (result: FenceTokens) => publish(() => show(result));+ const tokenizeNow = (): boolean => {+ if (!current() || highlight("", () => {}) === null) return false;+ const result = code.highlightExact(options, late);+ if (result === null) return false;+ cancel?.();+ cancelPublish?.();+ cancelPublish = null;+ show(result);+ release?.();+ release = null;+ return true;+ };+ const start = (): void => {+ cancelStart = null;+ if (!current()) return;+ let settled: FenceTokens | null = null;+ if (settlesOffThread(body, streaming, options)) {+ const failover = !tokenizesOffThread(body, streaming);+ settled = code.cached(options);+ if (settled === null) {+ cancel = requestFullHighlight(+ body,+ languageToken,+ (result) => {+ if (!current()) return;+ if (result === null) {+ if (failover) publish(() => show(highlight(body, late)));+ return;}- return;+ cancelFallback?.();+ cancelFallback = null;+ release?.();+ release = null;+ publish(() => {+ code.seed(options, result);+ show(result);+ });+ },+ false,+ !failover,+ );+ if (cancel === null && failover) {+ settled = highlight(body, late);+ } else {+ highlight("", () => {});+ settled = code.cover(options).result;+ }+ release = awaitWorker(body.length, () => {+ if (!current()) return false;+ if (!defer()) return tokenizeNow();+ if (cancelFallback === null) {+ cancelFallback = queueFenceWork(() => {+ cancelFallback = null;+ tokenizeNow();+ });}- release?.();- release = null;- if (wanted.current !== body) return;- code.seed(options, result);- setTokens(result);- },- false,- !failover,- );- if (cancel === null && failover) {- settled = highlight(body, late);- } else {- highlight("", () => {});- settled = code.cover(options).result;+ return false;+ });}- release = awaitWorker(body.length, () => {- if (highlight("", () => {}) === null) return false;- const result = code.highlightExact(- fenceHighlightOptions(body, languageToken),- late,- );- if (result === null) return false;- cancel?.();- setTokens(result);- release?.();- release = null;- return true;- });+ } else {+ settled = highlight(body, late);}- } else {- settled = highlight(body, 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);+ show(settled);+ };+ if (defer()) {+ if (displayed.current !== null+ && (displayed.current.body !== body || displayed.current.language !== languageToken)) {+ show(null);+ }+ cancelStart = queueFenceWork(start);+ } else start();return () => {+ active = false;+ cancelStart?.();+ cancelPublish?.();+ cancelFallback?.();release?.();cancel?.();};- }, [enabled, source, highlight, seed, streaming, languageToken]);+ }, [enabled, source, highlight, seed, streaming, languageToken, eager]);return tokens;}diff --git a/studio/frontend/src/components/assistant-ui/plain-fence-chunks.ts b/studio/frontend/src/components/assistant-ui/plain-fence-chunks.tsnew file mode 100644index 00000000000..a837b636e07--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/plain-fence-chunks.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export const PLAIN_FENCE_CHUNK_LINES = 64;++export type PlainFenceChunk = readonly string[];++export type PlainFenceChunks = {+ readonly source: string;+ readonly chunks: readonly PlainFenceChunk[];+ readonly trimmedEnd: number;+ readonly tailStart: number;+};++const sameNodes = (a: PlainFenceChunk, b: PlainFenceChunk): boolean =>+ a.length === b.length && a.every((node, index) => node === b[index]);++function readChunks(+ previous: PlainFenceChunks | null | undefined,+ source: string,+ trimmedEnd: number,+ appended: boolean,+): Pick<PlainFenceChunks, "chunks" | "tailStart"> {+ const chunks: PlainFenceChunk[] =+ appended && previous ? previous.chunks.slice(0, -1) : [];+ let offset = appended && previous ? previous.tailStart : 0;+ let chunkStart = offset;+ let tailStart = offset;+ let lineIndex = chunks.length * PLAIN_FENCE_CHUNK_LINES;+ let nodes: string[] = [];++ while (offset <= trimmedEnd) {+ const newline = source.indexOf("\n", offset);+ const end = newline < 0 || newline >= trimmedEnd ? trimmedEnd : newline;+ if (lineIndex > 0) {+ nodes.push("\n");+ }+ if (end > offset) {+ nodes.push(source.slice(offset, end));+ }+ lineIndex += 1;++ if (lineIndex % PLAIN_FENCE_CHUNK_LINES === 0 || end === trimmedEnd) {+ const oldNodes = previous?.chunks[chunks.length];+ chunks.push(oldNodes && sameNodes(oldNodes, nodes) ? oldNodes : nodes);+ tailStart = chunkStart;+ chunkStart = end + 1;+ nodes = [];+ }+ if (end === trimmedEnd) {+ break;+ }+ offset = end + 1;+ }++ return { chunks, tailStart };+}++export function updatePlainFenceChunks(+ previous: PlainFenceChunks | null | undefined,+ source: string,+): PlainFenceChunks {+ if (previous?.source === source) {+ return previous;+ }++ let trimmedEnd = source.length;+ while (trimmedEnd > 0 && source[trimmedEnd - 1] === "\n") {+ trimmedEnd -= 1;+ }++ const appended =+ previous !== null &&+ previous !== undefined &&+ source.slice(0, previous.source.length) === previous.source;+ if (appended && trimmedEnd === previous.trimmedEnd) {+ return { ...previous, source };+ }+ if (trimmedEnd === 0) {+ return { source, chunks: [["\n"]], trimmedEnd, tailStart: 0 };+ }++ return {+ source,+ trimmedEnd,+ ...readChunks(+ previous,+ source,+ trimmedEnd,+ appended && previous.trimmedEnd > 0,+ ),+ };+}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex f6e1caf582a..4ebde4f3a8c 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -40,6 +40,7 @@ import {} from "@/components/assistant-ui/grammar-prewarm";import { streamActive } from "@/components/assistant-ui/use-reasoning-highlight";import { scheduleQuietIdleTask } from "@/lib/schedule-idle-task";+import { inputPointerHeld } from "@/lib/input-pointer-state";import { MessageHtmlArtifacts } from "@/components/assistant-ui/message-html-artifacts";import {MessageResponseDetailsSheet,@@ -2040,6 +2041,7 @@ const startGrammarPrewarm = (): void => {},quiet: () =>!streamActive()+ && !inputPointerHeld()&& performance.now() - lastInputAt >= PREWARM_INPUT_QUIET_MS,skip: grammarWarmed,},diff --git a/studio/frontend/src/components/ui/sidebar.tsx b/studio/frontend/src/components/ui/sidebar.tsxindex 17bbe234484..6c8fbd3c0c4 100644--- a/studio/frontend/src/components/ui/sidebar.tsx+++ b/studio/frontend/src/components/ui/sidebar.tsx@@ -334,7 +334,7 @@ function Sidebar({return (<divclassName={cn(- "group peer text-sidebar-foreground relative shrink-0",+ "group sidebar-peer text-sidebar-foreground relative shrink-0",hasPinMode && pinned && "w-(--sidebar-width)",hasPinMode && !pinned && (collapseToZero ? "w-0" : "w-(--sidebar-width-icon)"),)}@@ -587,7 +587,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {<maindata-slot="sidebar-inset"className={cn(- "bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 relative flex min-h-0 w-full flex-1 flex-col",+ "bg-background md:[:where(.sidebar-peer)[data-variant=inset]~&]:m-2 md:[:where(.sidebar-peer)[data-variant=inset]~&]:ml-0 md:[:where(.sidebar-peer)[data-variant=inset]~&]:rounded-xl md:[:where(.sidebar-peer)[data-variant=inset]~&]:shadow-sm md:[:where(.sidebar-peer)[data-variant=inset]~&]:[:where(.sidebar-peer)[data-state=collapsed]~&]:ml-2 relative flex min-h-0 w-full flex-1 flex-col",className)}{...props}@@ -841,6 +841,8 @@ function SidebarMenuButton({)}+const sidebarMenuPeerActiveClass = String.raw`[:where(.peer\/menu-button):where([data-state=active],[data-active]:not([data-active=false]))~&]:text-sidebar-accent-foreground`+function SidebarMenuAction({className,asChild = false,@@ -858,8 +860,10 @@ function SidebarMenuAction({data-sidebar="menu-action"className={cn("text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 aspect-square w-5 rounded-md p-0 peer-data-[size=default]/menu-button:top-2 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 focus-visible:ring-1 [&>svg]:size-4 flex items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0",- showOnHover &&- "peer-data-active/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-open:opacity-100 md:opacity-0",+ showOnHover && [+ sidebarMenuPeerActiveClass,+ "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-open:opacity-100 md:opacity-0",+ ],className)}{...props}@@ -876,7 +880,8 @@ function SidebarMenuBadge({data-slot="sidebar-menu-badge"data-sidebar="menu-badge"className={cn(- "text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground peer-data-active/menu-button:text-sidebar-accent-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 rounded-md px-1 text-xs font-medium peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 flex items-center justify-center tabular-nums select-none group-data-[collapsible=icon]:hidden",+ "text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 rounded-md px-1 text-xs font-medium peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 flex items-center justify-center tabular-nums select-none group-data-[collapsible=icon]:hidden",+ sidebarMenuPeerActiveClass,className)}{...props}diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 8272129bb66..88fe7920c11 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -4863,6 +4863,14 @@ html[data-chat-font] .aui-root {}}+ html[data-code-block-containment="on"] .aui-thread-root [data-unsloth-fence-paint] {+ contain: paint;+ }++ .aui-thread-root [data-unsloth-fence-paint] pre {+ width: max-content;+ }+html[data-code-block-containment="on"] .aui-thread-root [data-streamdown="code-block"]:not([data-incomplete]) > [data-unsloth-fence-windowed] {content-visibility: auto;contain-intrinsic-size: auto var(--unsloth-fence-height);@@ -4876,6 +4884,14 @@ html[data-chat-font] .aui-root {}@media print {+ .aui-thread-root [data-unsloth-fence-paint] {+ contain: none !important;+ }++ .aui-thread-root [data-unsloth-fence-paint] pre {+ width: auto;+ }+.aui-thread-root [data-unsloth-fence-windowed] {content-visibility: visible !important;contain-intrinsic-size: none !important;diff --git a/studio/frontend/src/lib/input-pointer-state.ts b/studio/frontend/src/lib/input-pointer-state.tsnew file mode 100644index 00000000000..e4c89ba700c--- /dev/null+++ b/studio/frontend/src/lib/input-pointer-state.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export function createInputPointerState(target: Window, document: Document): {+ held: () => boolean;+ dispose: () => void;+} {+ const pointers = new Set<number>();+ const cleanups: (() => void)[] = [];+ let mouseHeld = false;+ let touchHeld = false;+ let dragging = false;++ const listen = (node: EventTarget, type: string, listener: EventListener): void => {+ node.addEventListener(type, listener, { capture: true, passive: true });+ cleanups.push(() => node.removeEventListener(type, listener, { capture: true }));+ };+ const release = (): void => {+ pointers.clear();+ mouseHeld = false;+ touchHeld = false;+ dragging = false;+ };++ if (typeof (target as Window & { PointerEvent?: unknown }).PointerEvent === "function") {+ listen(target, "pointerdown", ((event: PointerEvent) => {+ if (event.button === 0 || event.pointerType === "touch") pointers.add(event.pointerId);+ }) as EventListener);+ listen(target, "pointermove", ((event: PointerEvent) => {+ if (event.pointerType === "touch") return;+ if ((event.buttons & 1) !== 0) pointers.add(event.pointerId);+ else pointers.delete(event.pointerId);+ }) as EventListener);+ const pointerReleased = ((event: PointerEvent) => {+ pointers.delete(event.pointerId);+ }) as EventListener;+ listen(target, "pointerup", pointerReleased);+ listen(target, "pointercancel", pointerReleased);+ } else {+ listen(target, "mousedown", ((event: MouseEvent) => {+ mouseHeld = event.button === 0 || (event.buttons & 1) !== 0;+ }) as EventListener);+ const mouseChanged = ((event: MouseEvent) => {+ mouseHeld = (event.buttons & 1) !== 0;+ }) as EventListener;+ listen(target, "mousemove", mouseChanged);+ listen(target, "mouseup", mouseChanged);+ const touchesChanged = ((event: TouchEvent) => {+ touchHeld = event.touches.length > 0;+ }) as EventListener;+ for (const type of ["touchstart", "touchmove", "touchend", "touchcancel"]) {+ listen(target, type, touchesChanged);+ }+ }++ // A cancelled dragstart is never followed by dragend or drop.+ listen(target, "dragstart", (event) => {+ dragging = true;+ setTimeout(() => {+ if (event.defaultPrevented) dragging = false;+ }, 0);+ });+ listen(target, "dragend", release);+ listen(target, "drop", release);+ listen(target, "blur", (event) => {+ if (event.target === target) release();+ });+ listen(target, "pagehide", release);+ listen(document, "visibilitychange", () => {+ if (document.hidden) release();+ });++ return {+ held: () => pointers.size > 0 || mouseHeld || touchHeld || dragging,+ dispose: () => {+ for (const cleanup of cleanups.splice(0)) cleanup();+ release();+ },+ };+}++const inputPointerState = typeof window === "undefined" || typeof document === "undefined"+ ? null+ : createInputPointerState(window, document);++export const inputPointerHeld = (): boolean => inputPointerState?.held() ?? false;diff --git a/studio/frontend/tests/code-block-containment-wiring.test.ts b/studio/frontend/tests/code-block-containment-wiring.test.tsindex 0a3739d7716..f5471dd1412 100644--- a/studio/frontend/tests/code-block-containment-wiring.test.ts+++ b/studio/frontend/tests/code-block-containment-wiring.test.ts@@ -52,13 +52,15 @@ const printBlocks = (css: string): string[] => {return blocks;};-test("one rule, gated on the html attribute, inside the utilities layer", () => {- const rules = INDEX_CSS.split(GATE).slice(1);- assert.equal(rules.length, 1, "exactly one gated rule");- const at = INDEX_CSS.indexOf(GATE);+test("the windowed rule stays gated inside the utilities layer", () => {+ const rules = INDEX_CSS.split(GATE).slice(1)+ .map((rule) => rule.slice(0, rule.indexOf("}")))+ .filter((rule) => rule.includes("[data-unsloth-fence-windowed]"));+ assert.equal(rules.length, 1, "exactly one gated windowed rule");+ const at = INDEX_CSS.indexOf(GATE + rules[0]);const [open, close] = layerBounds(INDEX_CSS, "utilities");assert.ok(at > open && at < close, "inside @layer utilities, where the visible override lives");- const rule = rules[0].slice(0, rules[0].indexOf("}"));+ const rule = rules[0];assert.ok(rule.includes(".aui-thread-root"), "scoped to the chat thread");assert.ok(rule.includes('[data-streamdown="code-block"]:not([data-incomplete])'), "settled fences only");assert.ok(rule.includes(':not([data-incomplete]) > [data-unsloth-fence-windowed] {'), "the box around the windowed body: a skipped scroller drops its scrollbar in Chromium and its padding in Firefox, so the body itself would come back taller than it was skipped");@@ -74,7 +76,7 @@ test("the wrapper keeps the visible override and the body keeps the DOM contract"the flicker rule on the wrapper stays",);const body = DEFER.slice(DEFER.indexOf("export const FenceBody = memo("));- assert.ok(/<div\s*data-unsloth-fence-windowed=\{lineWindow === null \|\| !measured \? undefined : "true"\}\s*ref=\{wrapper\}\s*>\s*<div\s*className=\{joinClasses\([\s\S]*?\)\}\s*data-language=\{language \?\? undefined\}\s*data-streamdown="code-block-body"\s*ref=\{surface\}/.test(body), "the window hook sits on a box that does not scroll, around a body that keeps streamdown's markup and the measuring ref");+ assert.ok(/data-unsloth-fence-windowed=\{lineWindow === null \|\| !measured \? undefined : "true"\}\s*ref=\{wrapper\}\s*>\s*<div\s*className=\{joinClasses\([\s\S]*?\)\}\s*data-language=\{language \?\? undefined\}\s*data-streamdown="code-block-body"\s*ref=\{surface\}/.test(body), "the window hook sits on a box that does not scroll, around a body that keeps streamdown's markup and the measuring ref");assert.ok(!/contentVisibility:\s*"hidden"|display:\s*"none"/.test(body), "no line may be hidden from the engine");});@@ -145,3 +147,33 @@ test("the widening anchor stops at a skipped subtree instead of forcing it to reassert.ok(loop.indexOf("child.checkVisibility({ contentVisibilityAuto: true })") < loop.indexOf("child.getBoundingClientRect()"), "the child is asked before its rect is read, because the skipping element itself passes the check");assert.match(loop, /if \(child\.checkVisibility\(\)\) return anchor;\s*continue;/, "a skipped child makes its parent the anchor; a boxless child is skipped");});++test("full-token paint containment reserves no substitute height and clears for print", () => {+ const selector = `${GATE} .aui-thread-root [data-unsloth-fence-paint]`;+ const at = INDEX_CSS.indexOf(selector);+ assert.ok(at >= 0);+ const [open, close] = layerBounds(INDEX_CSS, "utilities");+ assert.ok(at > open && at < close);+ const rule = INDEX_CSS.slice(at + selector.length, INDEX_CSS.indexOf("}", at) + 1);+ assert.match(rule, /^\s*\{\s*contain: paint;\s*\}$/);+ const print = printBlocks(INDEX_CSS).find((block) => block.includes("[data-unsloth-fence-paint]"));+ assert.ok(print);+ assert.match(print, /\[data-unsloth-fence-paint\]\s*\{\s*contain: none !important;\s*\}/);+});++test("full-token fences retain intrinsic width without viewport-driven containment", () => {+ assert.doesNotMatch(DEFER, /data-unsloth-fence-contained/);+ assert.doesNotMatch(INDEX_CSS, /data-unsloth-fence-contained/);+ const selector = ".aui-thread-root [data-unsloth-fence-paint] pre";+ const at = INDEX_CSS.indexOf(selector);+ assert.ok(at >= 0);+ const [open, close] = layerBounds(INDEX_CSS, "utilities");+ assert.ok(at > open && at < close);+ const rule = INDEX_CSS.slice(at + selector.length, INDEX_CSS.indexOf("}", at) + 1);+ assert.match(rule, /^\s*\{\s*width: max-content;\s*\}$/);+ const print = printBlocks(INDEX_CSS).find((block) => block.includes(selector));+ assert.ok(print);+ const printAt = print.indexOf(selector);+ const printRule = print.slice(printAt + selector.length, print.indexOf("}", printAt) + 1);+ assert.match(printRule, /^\s*\{\s*width: auto;\s*\}$/);+});diff --git a/studio/frontend/tests/code-fence-body.test.ts b/studio/frontend/tests/code-fence-body.test.tsindex 822e21f0d98..fbc8ac0cf74 100644--- a/studio/frontend/tests/code-fence-body.test.ts+++ b/studio/frontend/tests/code-fence-body.test.ts@@ -3,10 +3,21 @@import assert from "node:assert/strict";import test from "node:test";+import { runInNewContext } from "node:vm";+import * as React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import ts from "@typescript/typescript6";+import {+ FENCE_CHUNK_LINES,+ sameFenceBodyProps,+ updateFenceChunks,+} from "../src/components/assistant-ui/code-fence-chunks.ts";import {isBlankLine,+ lineRendered,plainLineText,+ WINDOW_CAP_LINES,} from "../src/components/assistant-ui/code-fence-window.ts";import { readSrc } from "./helpers/kit.ts";@@ -19,6 +30,7 @@ import { readSrc } from "./helpers/kit.ts";const DEFER = readSrc("components/assistant-ui/code-fence-defer.tsx");const MARKDOWN_TEXT = readSrc("components/assistant-ui/markdown-text.tsx");+const LINE_SOURCE = DEFER.slice(DEFER.indexOf("const FenceLine = memo"), DEFER.indexOf("const FenceLineChunk = memo"));test("a line shows the same characters inside the window and outside it", () => {const line = [@@ -36,7 +48,7 @@ test("the plain form is the tokens, never a slice of the source", () => {assert.equal(plainLineText([{ content: "x = 1" }]), "x = 1");assert.ok(!/source\.slice|split\(["'`]\\n["'`]\)/.test(- DEFER.slice(DEFER.indexOf("const FenceLine = memo")),+ LINE_SOURCE,),"the line renderer must not reach for the source",);@@ -63,7 +75,7 @@ test("the line component is memoized, which is the whole point of it", () => {"FenceLine must be memoized",);assert.ok(- !/memo\(\s*function FenceLine[\s\S]*?\},\s*\(/.test(DEFER),+ !/memo\(\s*function FenceLine[\s\S]*?\},\s*\(/.test(LINE_SOURCE),"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",);@@ -118,8 +130,8 @@ test("a fence in the thinking box is coloured off the main thread, while it growconst plain = MARKDOWN_TEXT.slice(start, MARKDOWN_TEXT.indexOf("\n}\n", start));assert.equal(/useFenceTokens|requestFullHighlight|code\.highlight|noteStreamingFence/.test(plain), false);assert.match(plain, /<PlainFenceShell language=\{languageToken\} source=\{source\} \/>/);- assert.match(DEFER, /<code>\{plain \? shellLines\(source\) : shellBody\(source\)\}<\/code>/);- assert.match(DEFER, /if \(index > 0\) nodes\.push\("\\n"\);\s*if \(line !== ""\) nodes\.push\(line\);/, "one text node per line and per line break, so a streamed append rewrites only the growing line and a selection above it survives");+ assert.match(DEFER, /<code>\{plain \? <PlainFenceText source=\{source\} \/> : shellBody\(source\)\}<\/code>/);+ assert.match(DEFER, /<PlainFenceTextChunk key=\{index\} nodes=\{nodes\} \/>/);assert.match(DEFER, /data-unsloth-fence-deferred=\{plain \? undefined : "true"\}/, "a plain fence is never upgraded, so it does not carry the deferred marker");});@@ -339,3 +351,74 @@ test("no positional pseudo-class sits above .relative or button in a selector",);});+test("paint containment is limited to large completed full-token bodies", () => {+ const parsed = ts.createSourceFile("code-fence-defer.tsx", DEFER, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const declaration = parsed.statements+ .filter(ts.isVariableStatement)+ .flatMap((statement) => [...statement.declarationList.declarations])+ .find((node) => ts.isIdentifier(node.name) && node.name.text === "FenceBody");+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(+ `const ${declaration.getText(parsed)}; exports.render = FenceBody;`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } },+ );+ type Token = { content: string };+ type BodyProps = {+ isIncomplete: boolean | undefined;+ language: string | null;+ result: { tokens: Token[][] } | null;+ source: string;+ windowing: boolean;+ };+ const context = {+ exports: {} as { render: React.ComponentType<BodyProps> },+ React,+ memo: React.memo,+ useMemo: React.useMemo,+ useRef: React.useRef,+ useFenceHighlightLimit: () => ({ progress: null, staged: false }),+ FENCE_CHUNK_LINES,+ sameFenceBodyProps,+ updateFenceChunks,+ useLineWindow: () => ({ window: null, pins: null, measured: false }),+ lineRendered,+ WINDOW_CAP_LINES,+ joinClasses: (...parts: (string | null)[]) => parts.filter(Boolean).join(" "),+ CODE_CLASS: "",+ PRE_CLASS: "",+ FenceShell: ({ source }: { source: string }) => React.createElement("pre", null, source),+ FenceLine: ({ line, windowed }: { line: Token[]; windowed: boolean }) =>+ React.createElement("span", { "data-highlighted": String(windowed) }, plainLineText(line)),+ FenceLines: ({ tokens }: { tokens: Token[][] }) =>+ React.createElement(React.Fragment, null, tokens.map((line, index) =>+ React.createElement("span", { key: index, "data-highlighted": "true" }, plainLineText(line)))),+ };+ runInNewContext(outputText, context);+ const count = WINDOW_CAP_LINES + 1;+ for (const [lines, incomplete, windowing, missing, contained] of [+ [WINDOW_CAP_LINES, false, false, false, false],+ [count, false, false, false, true],+ [count, undefined, false, false, true],+ [count, true, false, false, false],+ [count, false, true, false, false],+ [count, false, false, true, false],+ [0, false, false, false, false],+ ] as const) {+ const tokens = Array.from({ length: lines }, (_, i) => [{ content: `line_${i};` }]);+ const html = renderToStaticMarkup(React.createElement(context.exports.render, {+ isIncomplete: incomplete,+ language: "text",+ result: missing ? null : { tokens },+ source: "fallback",+ windowing,+ }));+ assert.equal(html.includes('data-unsloth-fence-paint="true"'), contained,+ JSON.stringify({ lines, incomplete, windowing, missing }));+ if (!missing && lines > 0) {+ assert.equal((html.match(/data-highlighted="true"/g) ?? []).length, lines);+ for (const [token] of tokens) assert.ok(html.includes(`>${token.content}</span>`));+ } else {+ assert.match(html, /<pre>fallback<\/pre>/);+ }+ }+});diff --git a/studio/frontend/tests/code-fence-chunks.test.ts b/studio/frontend/tests/code-fence-chunks.test.tsnew file mode 100644index 00000000000..675c8acdf76--- /dev/null+++ b/studio/frontend/tests/code-fence-chunks.test.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++import assert from "node:assert/strict";+import test from "node:test";++import {+ FENCE_CHUNK_LINES,+ type FenceBodyMemoProps,+ sameFenceBodyProps,+ updateFenceChunks,+} from "../src/components/assistant-ui/code-fence-chunks.ts";++const makeLines = (count: number) =>+ Array.from({ length: count }, (_, index) => [{ content: `line ${index}` }]);++test("groups preserve token line order and use bounded immutable slices", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2 + 3);+ const chunks = updateFenceChunks(null, lines);+ assert.deepEqual(chunks.map((chunk) => chunk.length), [FENCE_CHUNK_LINES, FENCE_CHUNK_LINES, 3]);+ assert.deepEqual(chunks.flat(), lines);+ assert.notEqual(chunks[0], lines);+ for (const [index, line] of chunks.flat().entries()) {+ assert.equal(line, lines[index]);+ }+});++test("identical line references reuse every chunk and the chunk list", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2 + 3);+ const previous = updateFenceChunks(null, lines);+ assert.equal(updateFenceChunks(previous, lines), previous);+ assert.equal(updateFenceChunks(previous, [...lines]), previous);+});++test("a growing live tail only replaces its own chunk", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2 + 3);+ const previous = updateFenceChunks(null, lines);+ Object.freeze(previous);+ for (const chunk of previous) Object.freeze(chunk);+ const nextLines = [...lines];+ nextLines[nextLines.length - 1] = [{ content: "live tail grows" }];+ const next = updateFenceChunks(previous, nextLines);+ assert.notEqual(next, previous);+ assert.equal(next[0], previous[0]);+ assert.equal(next[1], previous[1]);+ assert.notEqual(next[2], previous[2]);+ assert.equal(previous[2][2], lines[lines.length - 1]);+ assert.deepEqual(next.flat(), nextLines);+});++test("middle line changes are detected when both edge references are unchanged", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 3);+ const previous = updateFenceChunks(null, lines);+ const nextLines = [...lines];+ nextLines[FENCE_CHUNK_LINES + 11] = [{ content: "retokenized middle" }];+ const next = updateFenceChunks(previous, nextLines);+ assert.equal(next[0], previous[0]);+ assert.notEqual(next[1], previous[1]);+ assert.equal(next[2], previous[2]);+ assert.deepEqual(next.flat(), nextLines);+});++test("appending across a boundary reuses completed groups", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2 - 1);+ const previous = updateFenceChunks(null, lines);+ const nextLines = [...lines, ...makeLines(3)];+ const next = updateFenceChunks(previous, nextLines);+ assert.deepEqual(next.map((chunk) => chunk.length), [FENCE_CHUNK_LINES, FENCE_CHUNK_LINES, 2]);+ assert.equal(next[0], previous[0]);+ assert.notEqual(next[1], previous[1]);+ assert.equal(previous[1].length, FENCE_CHUNK_LINES - 1);+ assert.deepEqual(next.flat(), nextLines);+ const appended = updateFenceChunks(next, [...nextLines, ...makeLines(1)]);+ assert.equal(appended[0], next[0]);+ assert.equal(appended[1], next[1]);+ assert.notEqual(appended[2], next[2]);+});++test("a full previous tail remains stable when a new group starts", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2);+ const previous = updateFenceChunks(null, lines);+ const next = updateFenceChunks(previous, [...lines, ...makeLines(1)]);+ assert.equal(next[0], previous[0]);+ assert.equal(next[1], previous[1]);+ assert.equal(next[2].length, 1);+});++test("truncation drops later groups and replaces only a shortened group", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 3);+ const previous = updateFenceChunks(null, lines);+ const nextLines = lines.slice(0, FENCE_CHUNK_LINES + 7);+ const next = updateFenceChunks(previous, nextLines);+ assert.equal(next.length, 2);+ assert.equal(next[0], previous[0]);+ assert.notEqual(next[1], previous[1]);+ assert.equal(next[1].length, 7);+ assert.deepEqual(next.flat(), nextLines);+ const boundary = updateFenceChunks(next, lines.slice(0, FENCE_CHUNK_LINES));+ assert.equal(boundary.length, 1);+ assert.equal(boundary[0], previous[0]);+});++test("resetting the source and empty transitions retain no stale lines", () => {+ const lines = makeLines(FENCE_CHUNK_LINES * 2);+ const previous = updateFenceChunks(null, lines);+ const replacement = makeLines(lines.length);+ const next = updateFenceChunks(previous, replacement);+ assert.notEqual(next[0], previous[0]);+ assert.notEqual(next[1], previous[1]);+ assert.deepEqual(next.flat(), replacement);+ const empty = updateFenceChunks(next, []);+ assert.deepEqual(empty, []);+ assert.equal(updateFenceChunks(empty, []), empty);+ assert.deepEqual(updateFenceChunks(null, []), []);+ assert.deepEqual(updateFenceChunks(empty, lines).flat(), lines);+});++type TestResult = { tokens: ReturnType<typeof makeLines>; fg?: string };+const bodyProps = (+ result: TestResult | null = { tokens: makeLines(1) },+): FenceBodyMemoProps<TestResult> => ({+ result,+ source: "line 0",+ language: "python",+ isIncomplete: true,+ windowing: false,+});++test("source growth skips a body render only with the same nonempty tokens result", () => {+ const previous = bodyProps();+ assert.equal(sameFenceBodyProps(previous, { ...previous }), true);+ assert.equal(+ sameFenceBodyProps(previous, { ...previous, source: "line 0 grows" }),+ true,+ );+ const nextResult = { tokens: previous.result!.tokens };+ assert.equal(+ sameFenceBodyProps(previous, { ...previous, result: nextResult }),+ false,+ );+ assert.equal(+ sameFenceBodyProps(previous, {+ ...previous,+ result: { ...nextResult, fg: "#eee" },+ }),+ false,+ );+});++test("null and empty results still render source changes in the plain fallback", () => {+ for (const result of [null, { tokens: [] }]) {+ const previous = bodyProps(result);+ assert.equal(sameFenceBodyProps(previous, { ...previous }), true);+ assert.equal(+ sameFenceBodyProps(previous, { ...previous, source: "replacement" }),+ false,+ );+ }+ const previous = bodyProps();+ assert.equal(+ sameFenceBodyProps(previous, { ...previous, result: null }),+ false,+ );+});++test("source equality does not inspect tokens", () => {+ const previous = bodyProps({+ get tokens(): ReturnType<typeof makeLines> {+ throw new Error("tokens were unnecessarily inspected");+ },+ });+ assert.equal(sameFenceBodyProps(previous, { ...previous }), true);+});++test("completion, language and window changes always update the body", () => {+ const previous = bodyProps();+ for (const update of [+ { isIncomplete: false },+ { isIncomplete: undefined },+ { language: "javascript" },+ { language: null },+ { windowing: true },+ ]) {+ assert.equal(sameFenceBodyProps(previous, { ...previous, ...update }), false);+ }+ const completed = { ...previous, isIncomplete: false };+ assert.equal(sameFenceBodyProps(completed, previous), false);+ assert.equal(+ sameFenceBodyProps(completed, { ...completed, source: "unchanged tokens" }),+ true,+ );+});diff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.tsindex ee95db8bfe4..d5227aad538 100644--- a/studio/frontend/tests/code-fence-defer.test.ts+++ b/studio/frontend/tests/code-fence-defer.test.ts@@ -614,7 +614,7 @@ test("the idle warm yields between languages", () => {"one tokenization per task: warm, re-schedule, and leave the rest to the next idle slot",);// Everything before the second loop, which is the one that tokenizes.- const loadPass = body.slice(0, body.indexOf("grammarsWarmed.has"));+ const loadPass = body.slice(body.indexOf("for (const gate of unreached)"), body.indexOf("grammarsWarmed.has"));assert.ok(!loadPass.includes("scheduleGrammarWarm") && !loadPass.includes("return;"),"the grammar loads all start in the first pass; yielding them costs the jump and the print",diff --git a/studio/frontend/tests/code-fence-foreground.test.ts b/studio/frontend/tests/code-fence-foreground.test.tsnew file mode 100644index 00000000000..720364baaa9--- /dev/null+++ b/studio/frontend/tests/code-fence-foreground.test.ts@@ -0,0 +1,228 @@+// 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 { runInNewContext } from "node:vm";+import type { HighlightResult } from "@streamdown/code";+import * as React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import ts from "@typescript/typescript6";+import { fenceLineForeground } from "../src/components/assistant-ui/code-fence-foreground.ts";+import {+ isBlankLine,+ plainLineText,+} from "../src/components/assistant-ui/code-fence-window.ts";+import { readSrc } from "./helpers/kit.ts";++type Token = HighlightResult["tokens"][number][number];+const token = (+ content: string,+ light = "#383A42",+ dark = "#ABB2BF",+ rest: Partial<Token> = {},+): Token => ({+ content,+ offset: 0,+ htmlStyle: { color: light, "--shiki-dark": dark },+ ...rest,+});++const source = readSrc("components/assistant-ui/code-fence-defer.tsx");+const parsed = ts.createSourceFile(+ "code-fence-defer.tsx",+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);+const wanted = new Set([+ "LINE_CLASS",+ "TOKEN_CLASS",+ "TOKEN_BG_CLASS",+ "tokenStyle",+ "FenceLine",+]);+const declarations = parsed.statements+ .filter(ts.isVariableStatement)+ .flatMap((statement) =>+ [...statement.declarationList.declarations]+ .filter(+ (declaration) =>+ ts.isIdentifier(declaration.name) &&+ wanted.has(declaration.name.text),+ )+ .map((declaration) => `const ${declaration.getText(parsed)};`),+ );+assert.equal(declarations.length, wanted.size);+const { outputText } = ts.transpileModule(+ `${declarations.join("\n")}\nexports.FenceLine = FenceLine;`,+ {+ compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },+ },+);+const scope = {+ exports: {} as {+ FenceLine: React.ComponentType<{ line: Token[]; windowed: boolean }>;+ },+ React,+ memo: React.memo,+ isBlankLine,+ plainLineText,+ fenceLineForeground,+};+runInNewContext(outputText, scope);+const render = (line: Token[], windowed = true) =>+ renderToStaticMarkup(+ React.createElement(scope.exports.FenceLine, { line, windowed }),+ );+const spanCount = (html: string) => (html.match(/<span\b/g) ?? []).length;++test("a line inherits its first eligible color pair and keeps different light or dark colors", () => {+ const line = [+ token("a"),+ token("b", "#e45649"),+ token("c"),+ token("d", "#383a42", "#e06c75"),+ ];+ assert.deepEqual(fenceLineForeground(line), {+ light: "#383a42",+ dark: "#abb2bf",+ inherited: [true, false, true, false],+ });+ const html = render(line);+ assert.equal(spanCount(html), 3);+ assert.match(html, /style="--sdm-c:#383a42;--shiki-dark:#abb2bf"/);+ assert.match(html, /--sdm-c:#e45649/);+ assert.match(html, /--shiki-dark:#e06c75/);+});++test("font styles and token backgrounds retain their spans", () => {+ const line = [+ token("a"),+ token("b"),+ token("italic", undefined, undefined, { fontStyle: 1 }),+ token("bold", undefined, undefined, {+ htmlStyle: {+ color: "#383A42",+ "--shiki-dark": "#ABB2BF",+ "font-weight": "bold",+ },+ }),+ token("background", undefined, undefined, { bgColor: "#ff0000" }),+ token("dark-background", undefined, undefined, {+ htmlStyle: {+ color: "#383A42",+ "--shiki-dark": "#ABB2BF",+ "--shiki-dark-bg": "#ff0000",+ },+ }),+ ];+ assert.deepEqual(fenceLineForeground(line)?.inherited, [+ true,+ true,+ false,+ false,+ false,+ false,+ ]);+ const html = render(line);+ assert.equal(spanCount(html), 5);+ assert.match(html, /font-weight:bold/);+ assert.match(html, /--sdm-tbg:#ff0000/);+ assert.match(html, /--shiki-dark-bg:#ff0000/);+});++test("attributes and unrecognized styles leave line inheritance unchanged", () => {+ for (const special of [+ token("attributed", undefined, undefined, {+ htmlAttrs: { "data-marker": "retained" },+ }),+ token("custom", undefined, undefined, {+ htmlStyle: {+ color: "#383A42",+ "--shiki-dark": "#ABB2BF",+ all: "inherit",+ },+ }),+ ]) {+ const line = [token("a"), special, token("b")];+ assert.equal(fenceLineForeground(line), null);+ assert.equal(spanCount(render(line)), 4);+ }+ assert.match(+ render([+ token("x", undefined, undefined, {+ htmlAttrs: { "data-marker": "retained" },+ }),+ ]),+ /data-marker="retained"/,+ );+});++test("approximate, uncolored, empty and nonliteral colors never gain a new foreground", () => {+ for (const special of [+ { content: "tail", offset: 0 },+ token("one-theme", undefined, undefined, {+ htmlStyle: { color: "#383A42" },+ }),+ token("empty", ""),+ token("inherited", "inherit"),+ token("custom", "var(--custom)"),+ token("invalid", "#12345"),+ ] as Token[]) {+ const line = [token("colored"), special];+ assert.equal(fenceLineForeground(line), null);+ assert.equal(spanCount(render(line)), 3);+ }+ assert.equal(fenceLineForeground([]), null);+});++test("raw text preserves characters and windowed-out and blank lines keep their existing form", () => {+ const line = [token("<&>"), token(" \tπ"), token("tail")];+ const html = render(line);+ assert.equal(spanCount(html), 1);+ assert.ok(html.endsWith("<&> \tπtail</span>"));+ const plain = render(line, false);+ assert.equal(spanCount(plain), 1);+ assert.equal(plain.includes("style="), false);+ assert.ok(plain.endsWith("<&> \tπtail</span>"));+ for (const blank of [[], [{ content: "", offset: 0 }]] as Token[][]) {+ assert.equal(spanCount(render(blank)), 1);+ assert.ok(render(blank).endsWith("\n</span>"));+ }+});++test("legacy color fields are honored without mutating committed tokens", () => {+ const line = [+ Object.freeze(+ token("x", undefined, undefined, {+ color: "#383A42",+ htmlStyle: Object.freeze({ "--shiki-dark": "#ABB2BF" }),+ }),+ ),+ ];+ assert.deepEqual(fenceLineForeground(line), {+ light: "#383a42",+ dark: "#abb2bf",+ inherited: [true],+ });+ assert.equal(spanCount(render(line)), 1);+});++test("appending a different color cannot replace unchanged prefix token spans", () => {+ const prefix = [token("a"), token("b", "#e45649", "#e06c75"), token("c")];+ const grown = [+ ...prefix,+ token("d", "#e45649", "#e06c75"),+ token("e", "#e45649", "#e06c75"),+ ];+ const before = fenceLineForeground(prefix)!;+ const after = fenceLineForeground(grown)!;+ assert.equal(after.light, before.light);+ assert.equal(after.dark, before.dark);+ assert.deepEqual(after.inherited.slice(0, prefix.length), before.inherited);+ assert.deepEqual(after.inherited, [true, false, true, false, false]);+ const prefixMarkup = render(prefix).slice(0, -"</span>".length);+ assert.ok(render(grown).startsWith(prefixMarkup));+});diff --git a/studio/frontend/tests/code-fence-mode.test.ts b/studio/frontend/tests/code-fence-mode.test.tsindex f597a9db654..d4158ce5e23 100644--- a/studio/frontend/tests/code-fence-mode.test.ts+++ b/studio/frontend/tests/code-fence-mode.test.ts@@ -72,6 +72,8 @@ test("the runtime global beats the build flag, both ways round", () => {"global on beats a build that said off",);assert.equal(resolveFenceMode("defer", "off"), "defer");+ assert.equal(resolveFenceMode("defer", "window"), "defer");+ assert.equal(resolveFenceMode("window", "defer"), "window");});test("a typo degrades to the old behaviour, never to the new default", () => {diff --git a/studio/frontend/tests/code-fence-print.test.ts b/studio/frontend/tests/code-fence-print.test.tsindex 643c20925a5..97d8316eda5 100644--- a/studio/frontend/tests/code-fence-print.test.ts+++ b/studio/frontend/tests/code-fence-print.test.ts@@ -38,7 +38,7 @@ test("a print tokenizes what the worker still owes, synchronously and within a bconst hook = markdown.slice(markdown.indexOf("function useFenceTokens("), markdown.indexOf("function StreamingFenceBlock("));assert.equal((hook.match(/awaitWorker\(/g) ?? []).length, 1);assert.ok(hook.indexOf("requestFullHighlight(") < hook.indexOf("awaitWorker("));- assert.match(hook, /requestFullHighlight\(\s*body,\s*languageToken,\s*\(result\) => \{\s*if \(result === null\) \{[^}]*\}\s*return;\s*\}\s*release\?\.\(\);\s*release = null;/, "the worker's tokens end what the print entry stands for; a failed reply keeps it, so a print still colours the fence");+ assert.match(hook, /requestFullHighlight\(\s*body,\s*languageToken,\s*\(result\) => \{\s*if \(!current\(\)\) return;\s*if \(result === null\) \{[^}]*return;\s*\}\s*cancelFallback\?\.\(\);\s*cancelFallback = null;\s*release\?\.\(\);\s*release = null;/, "the worker's tokens end what the print entry stands for; a failed reply keeps it, so a print still colours the fence");const probes = [...hook.matchAll(/highlight\("", /g)];assert.ok(probes.length >= 2);for (const probe of probes) {@@ -50,7 +50,7 @@ test("a drag freezes the line window, and a selection pins only the lines holdinconst defer = readSrc("components/assistant-ui/code-fence-defer.tsx");const measure = defer.slice(defer.indexOf("measure.current = () => {"), defer.indexOf("useLayoutEffect(() => {", defer.indexOf("measure.current = () => {")));const flying = measure.indexOf("flyingDuringFrame(");- const dragging = measure.indexOf("if (current.current !== null && draggingDuringFrame(body)) return;");+ const dragging = measure.indexOf("if (current.current !== null && draggingDuringFrame(body, known.scroller)) return;");assert.ok(flying >= 0 && dragging > flying && dragging < measure.indexOf("selectLineWindow({"));assert.ok(measure.indexOf("pinBoundaryLines(") > measure.indexOf("selectLineWindow({"), "the window keeps following the reader while the boundary lines stay as they were");assert.match(measure, /if \(next === current\.current && samePins\(pins, pinned\.current\)\) return;/);diff --git a/studio/frontend/tests/code-fence-window.test.ts b/studio/frontend/tests/code-fence-window.test.tsindex 05f22428440..05969be74f4 100644--- a/studio/frontend/tests/code-fence-window.test.ts+++ b/studio/frontend/tests/code-fence-window.test.ts@@ -9,6 +9,7 @@ import {HYSTERESIS_VIEWPORTS,lineIsWindowed,lineRendered,+ onScrollbar,pinBoundaryLines,samePins,OVERSCAN_VIEWPORTS,@@ -204,3 +205,14 @@ test("a selection boundary line keeps its rendering while the window moves on",assert.equal(samePins(kept, null), false);});+test("a press on a scrollbar holds the line window, a press on content does not", () => {+ const box = { clientWidth: 800, clientHeight: 600 };+ assert.equal(onScrollbar({ ...box, offsetX: 799, offsetY: 300 }), false, "the last content column");+ assert.equal(onScrollbar({ ...box, offsetX: 800, offsetY: 300 }), true, "the vertical gutter a thumb drag uses");+ assert.equal(onScrollbar({ ...box, offsetX: 400, offsetY: 600 }), true, "the horizontal bar of a wide fence");+ assert.equal(onScrollbar({ ...box, offsetX: 0, offsetY: 0 }), false);+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");+ assert.match(defer, /\|\| \(barHeld !== null && barHeld === scroller\)/, "a held scrollbar counts as a drag on its own scroller's fences");+ assert.match(defer, /barHeld = scrollbarOf\(event\);/);+ assert.match(defer, /if \(pointerHeld === null && barHeld === null\) return;\s*pointerHeld = null;\s*barHeld = null;/, "releasing either remeasures");+});diff --git a/studio/frontend/tests/desktop-webkit-paths.test.ts b/studio/frontend/tests/desktop-webkit-paths.test.tsindex b8f581e2795..314f7373cce 100644--- a/studio/frontend/tests/desktop-webkit-paths.test.ts+++ b/studio/frontend/tests/desktop-webkit-paths.test.ts@@ -60,9 +60,9 @@ test("below 1.5x device scale the Windows thread scrolls on the compositor and kassert.match(provider, /<AppearanceCustomizationEffect \/>\s*<LowDeviceScaleEffect \/>/);});-test("without requestIdleCallback, main-thread grammar work waits for the reader and the stream", () => {+test("grammar work waits for a held pointer and the reader, and without requestIdleCallback for the stream", () => {const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");- assert.match(defer, /const warmMustWait = \(\): boolean =>\s*typeof \(globalThis as Record<string, unknown>\)\.requestIdleCallback !== "function"\s*&& \(streamActive\(\) \|\| inputQuietIn\(\) > 0\);/);+ assert.match(defer, /const warmMustWait = \(\): boolean =>\s*inputPointerHeld\(\) \|\| inputQuietIn\(\) > 0\s*\|\| \(typeof \(globalThis as Record<string, unknown>\)\.requestIdleCallback !== "function"\s*&& streamActive\(\)\);/);assert.ok(defer.indexOf("if (warmMustWait()) {") < defer.indexOf("grammarsWarmed.add(language);"), "a warm that has to wait does not mark its grammar warmed");});diff --git a/studio/frontend/tests/fence-highlight-lifecycle.test.ts b/studio/frontend/tests/fence-highlight-lifecycle.test.tsnew file mode 100644index 00000000000..dc71558f957--- /dev/null+++ b/studio/frontend/tests/fence-highlight-lifecycle.test.ts@@ -0,0 +1,228 @@+// 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 ts from "@typescript/typescript6";++import { createFenceHighlightQueue } from "../src/components/assistant-ui/fence-highlight-queue.ts";+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("components/assistant-ui/code-fence-defer.tsx");+const declarations = source.slice(source.indexOf("let highlightWatching ="), source.indexOf("const highlightQuietIn ="));+const lifecycle = source.slice(source.indexOf("const watchHighlighting ="), source.indexOf("const visibleHighlightLine ="));+const compiled = ts.transpileModule(declarations + lifecycle.replace("export function queueFenceWork", "function queueFenceWork"), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },+}).outputText;++function harness() {+ const scheduled = new Set<() => void>();+ const microtasks: (() => void)[] = [];+ const resizeListeners = new Set<() => void>();+ const observers: Observer[] = [];+ const element = {};+ let blocked = false;+ let find = false;+ let clock = 0;+ let removals = 0;+ const queue = createFenceHighlightQueue({+ schedule: (callback) => {+ scheduled.add(callback);+ return () => { scheduled.delete(callback); };+ },+ blocked: () => blocked,+ commit: (callback) => { callback(); },+ });+ class Observer {+ connected = false;+ disconnects = 0;+ callback: () => void;+ constructor(callback: () => void) {+ this.callback = callback;+ observers.push(this);+ }+ observe(target: unknown, options: unknown) {+ assert.equal(target, element);+ assert.deepEqual(options, { attributes: true, attributeFilter: ["data-find-bar-open"] });+ this.connected = true;+ }+ disconnect() {+ this.connected = false;+ this.disconnects += 1;+ }+ }+ const context = {+ window: {+ addEventListener(type: string, callback: () => void) {+ assert.equal(type, "resize");+ resizeListeners.add(callback);+ },+ removeEventListener(type: string, callback: () => void) {+ assert.equal(type, "resize");+ assert.ok(resizeListeners.delete(callback));+ removals += 1;+ },+ },+ document: { documentElement: element },+ performance: { now: () => clock },+ MutationObserver: Observer,+ FIND_BAR_FLAG: "data-find-bar-open",+ findBarOpen: () => find,+ highlightQueue: queue,+ printing: false,+ queueMicrotask: (callback: () => void) => { microtasks.push(callback); },+ };+ const api = new Function(...Object.keys(context), compiled + `+ return {+ queue: queueFenceWork,+ resizedAt: () => highlightResizedAt,+ setPrinting: value => { printing = value; },+ };+ `)(...Object.values(context)) as {+ queue: (work: () => void) => () => void;+ resizedAt: () => number;+ setPrinting: (value: boolean) => void;+ };+ const flushMicrotasks = () => {+ let count = 0;+ while (microtasks.length > 0) {+ assert.ok(++count < 100);+ microtasks.shift()!();+ }+ };+ return {+ ...api,+ observers,+ scheduled,+ microtasks,+ resizeListeners,+ pending: queue.pending,+ removals: () => removals,+ block: (value: boolean) => { blocked = value; },+ resize: (at: number) => {+ clock = at;+ for (const callback of resizeListeners) callback();+ },+ setFind: (value: boolean) => {+ find = value;+ microtasks.push(() => {+ for (const observer of observers) if (observer.connected) observer.callback();+ });+ },+ flushMicrotasks,+ run: () => {+ const callback = scheduled.values().next().value;+ assert.ok(callback);+ scheduled.delete(callback);+ callback();+ },+ };+}++test("replacement work survives the last-entry teardown and remains findable", () => {+ const h = harness();+ const cancel = h.queue(() => assert.fail("canceled work must not run"));+ const observer = h.observers[0];+ cancel();+ assert.equal(h.microtasks.length, 1);+ let finished = false;+ h.queue(() => { finished = true; });+ h.resize(123);+ assert.equal(h.resizedAt(), 123);+ assert.equal(h.observers.length, 1);+ h.block(true);+ h.setFind(true);+ h.flushMicrotasks();+ assert.equal(finished, true);+ assert.equal(h.pending(), 0);+ assert.equal(h.scheduled.size, 0);+ assert.equal(observer.disconnects, 1);+ assert.equal(h.removals(), 1);+ assert.equal(h.resizeListeners.size, 0);+});++test("a commit registering its successor keeps the existing observers alive", () => {+ const h = harness();+ const finished: string[] = [];+ h.queue(() => {+ finished.push("first");+ h.queue(() => { finished.push("second"); });+ h.block(true);+ });+ h.run();+ h.flushMicrotasks();+ assert.deepEqual(finished, ["first"]);+ assert.equal(h.pending(), 1);+ assert.equal(h.observers.length, 1);+ assert.equal(h.observers[0].disconnects, 0);+ assert.equal(h.resizeListeners.size, 1);+ h.block(false);+ h.run();+ h.flushMicrotasks();+ assert.deepEqual(finished, ["first", "second"]);+ assert.equal(h.observers[0].disconnects, 1);+ assert.equal(h.resizeListeners.size, 0);+});++test("repeated cancellation coalesces teardown and a later subscription starts cleanly", () => {+ const h = harness();+ const first = h.queue(() => assert.fail());+ const second = h.queue(() => assert.fail());+ first();+ first();+ second();+ assert.equal(h.microtasks.length, 1);+ assert.equal(h.removals(), 0);+ h.flushMicrotasks();+ assert.equal(h.removals(), 1);+ assert.equal(h.observers[0].disconnects, 1);+ let finished = false;+ h.queue(() => { finished = true; });+ assert.equal(h.observers.length, 2);+ h.run();+ h.flushMicrotasks();+ assert.equal(finished, true);+ assert.equal(h.observers[1].disconnects, 1);+ assert.equal(h.removals(), 2);+ assert.equal(h.scheduled.size, 0);+});++test("closing find keeps blocked work pending and opening it flushes nested work", () => {+ const h = harness();+ const finished: string[] = [];+ h.block(true);+ h.queue(() => {+ finished.push("first");+ h.queue(() => { finished.push("nested"); });+ });+ h.setFind(false);+ h.flushMicrotasks();+ assert.deepEqual(finished, []);+ assert.equal(h.pending(), 1);+ assert.equal(h.observers[0].disconnects, 0);+ h.setFind(true);+ h.flushMicrotasks();+ assert.deepEqual(finished, ["first", "nested"]);+ assert.equal(h.pending(), 0);+ assert.equal(h.scheduled.size, 0);+ assert.equal(h.observers.length, 1);+ assert.equal(h.observers[0].disconnects, 1);+});++test("print and an already open find bypass subscriptions and run work synchronously", () => {+ for (const force of ["print", "find"]) {+ const h = harness();+ h.block(true);+ if (force === "print") h.setPrinting(true);+ else h.setFind(true);+ let finished = false;+ const cancel = h.queue(() => { finished = true; });+ assert.equal(finished, true);+ cancel();+ h.flushMicrotasks();+ assert.equal(h.pending(), 0);+ assert.equal(h.observers.length, 0);+ assert.equal(h.scheduled.size, 0);+ assert.equal(h.resizeListeners.size, 0);+ }+});diff --git a/studio/frontend/tests/fence-highlight-progress.test.ts b/studio/frontend/tests/fence-highlight-progress.test.tsnew file mode 100644index 00000000000..16dd411f5ff--- /dev/null+++ b/studio/frontend/tests/fence-highlight-progress.test.ts@@ -0,0 +1,264 @@+// 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 { updateFenceChunks } from "../src/components/assistant-ui/code-fence-chunks.ts";+import {+ advanceHighlightProgress,+ EMPTY_HIGHLIGHT_COUNTS,+ EMPTY_HIGHLIGHT_PROGRESS,+ HIGHLIGHT_BATCH_LINES,+ HIGHLIGHT_BATCH_TOKENS,+ type HighlightProgress,+ highlightLineCount,+ initialHighlightProgress,+ needsHighlightBatches,+ retainHighlightProgress,+} from "../src/components/assistant-ui/fence-highlight-progress.ts";++const linesOf = (...lengths: number[]) => lengths.map((length) => ({ length }));+const coverage = (lines: readonly { length: number }[], progress: HighlightProgress | null): number[] =>+ lines.map((line, index) => progress === null ? line.length : highlightLineCount(progress, index));++function assertBoundedStep(before: readonly number[], after: readonly number[]): number {+ let tokens = 0;+ let touched = 0;+ for (let index = 0; index < after.length; index += 1) {+ const added = after[index] - before[index];+ assert.ok(added >= 0, `line ${index} retains its highlighted tokens`);+ if (added > 0) touched += 1;+ tokens += added;+ }+ assert.ok(tokens <= HIGHLIGHT_BATCH_TOKENS);+ assert.ok(touched <= HIGHLIGHT_BATCH_LINES);+ return tokens;+}++test("batching activates above either the line cap or the token cap", () => {+ assert.equal(needsHighlightBatches([], 240), false);+ assert.equal(needsHighlightBatches(linesOf(4096), 240), false);+ assert.equal(needsHighlightBatches(linesOf(4097), 240), true);+ assert.equal(needsHighlightBatches(linesOf(2048, 2048), 240), false);+ assert.equal(needsHighlightBatches(linesOf(2048, 2049), 240), true);+ assert.equal(needsHighlightBatches(Array.from({ length: 240 }, () => ({ length: 1 })), 240), false);+ assert.equal(needsHighlightBatches(Array.from({ length: 241 }, () => ({ length: 0 })), 240), true);+});++test("the first batch is bounded and leaves visible prioritization available", () => {+ const lines = linesOf(10_000, 10);+ const initial = initialHighlightProgress(lines);+ assert.deepEqual(initial, { counts: [[512, 0]], cursor: 0, located: false });+ assert.equal(initialHighlightProgress([]), null);+ assert.equal(initialHighlightProgress(linesOf(0, 0)), null);+ assert.equal(initialHighlightProgress(linesOf(512)), null);+});++test("a 10000-token line is partitioned into strict 512-token batches without gaps", () => {+ const lines = linesOf(10_000, 3);+ let progress: HighlightProgress | null = EMPTY_HIGHLIGHT_PROGRESS;+ let before = coverage(lines, progress);+ let batches = 0;+ let visited = 0;+ while (progress !== null) {+ progress = advanceHighlightProgress(lines, progress);+ const after = coverage(lines, progress);+ const added = assertBoundedStep(before, after);+ assert.ok(added > 0);+ visited += added;+ before = after;+ assert.ok(++batches < 30);+ }+ assert.deepEqual(before, [10_000, 3]);+ assert.equal(visited, 10_003);+ assert.equal(batches, 20);+});++test("ordinary lines remain whole and each batch touches at most 64 incomplete lines", () => {+ assert.deepEqual(advanceHighlightProgress(linesOf(300, 300), EMPTY_HIGHLIGHT_PROGRESS), {+ counts: [[300, 0]], cursor: 1, located: true,+ });+ const lines = Array.from({ length: 200 }, () => ({ length: 1 }));+ const result = advanceHighlightProgress(lines, EMPTY_HIGHLIGHT_PROGRESS);+ assert.ok(result);+ assert.deepEqual(coverage(lines, result), [...Array<number>(64).fill(1), ...Array<number>(136).fill(0)]);+ assert.equal(result.cursor, 64);+});++test("completed lines do not consume the batch line budget", () => {+ const lines = Array.from({ length: 200 }, () => ({ length: 1 }));+ const counts = Array.from({ length: 200 }, (_, index) => index % 2);+ const result = advanceHighlightProgress(lines, { counts: updateFenceChunks(null, counts), cursor: 0, located: true });+ assert.ok(result);+ assert.equal(assertBoundedStep(counts, coverage(lines, result)), 64);+ assert.equal(result.cursor, 128);+});++test("mixed sparse and dense lines complete monotonically within both budgets", () => {+ const lines = Array.from({ length: 2000 }, (_, index) => ({+ length: index % 97 === 0 ? 10_000 : (index * 17) % 41,+ }));+ let progress: HighlightProgress | null = EMPTY_HIGHLIGHT_PROGRESS;+ let before = coverage(lines, progress);+ let visited = 0;+ let batches = 0;+ while (progress !== null) {+ progress = advanceHighlightProgress(lines, progress);+ const after = coverage(lines, progress);+ const added = assertBoundedStep(before, after);+ assert.ok(added > 0);+ visited += added;+ before = after;+ assert.ok(++batches < 2000);+ }+ assert.deepEqual(before, lines.map((line) => line.length));+ assert.equal(visited, lines.reduce((sum, line) => sum + line.length, 0));+});++test("visible prioritization happens once and wraps to finish earlier lines without decoloring", () => {+ const lines = Array.from({ length: 400 }, (_, index) => ({ length: index === 320 ? 10_000 : 12 }));+ let progress = initialHighlightProgress(lines);+ assert.ok(progress);+ let before = coverage(lines, progress);+ const initial = before.slice();+ let steps = 0;+ while (progress !== null) {+ const next = advanceHighlightProgress(lines, progress, steps === 0 ? 300 : 200);+ const after = coverage(lines, next);+ assert.ok(assertBoundedStep(before, after) > 0);+ if (steps === 0) {+ assert.deepEqual(after.slice(0, 300), initial.slice(0, 300));+ assert.equal(after[300], lines[300].length);+ assert.equal(after[320], 272);+ }+ if (steps === 1) {+ assert.equal(after[200], 0);+ assert.equal(after[320], 784);+ }+ before = after;+ progress = next;+ assert.ok(++steps < 100);+ }+ assert.deepEqual(before, lines.map((line) => line.length));+});++test("batch advancement never mutates previously rendered progress", () => {+ const counts = Object.freeze([Object.freeze([10, 0, 0])]);+ const previous = Object.freeze({ counts, cursor: 1, located: true });+ const result = advanceHighlightProgress(linesOf(10, 10_000, 10), previous);+ assert.ok(result);+ assert.notEqual(result.counts, counts);+ assert.deepEqual(previous.counts, [[10, 0, 0]]);+ assert.deepEqual(result.counts, [[10, 512, 0]]);+});++test("replacement of an early line preserves every already colored unchanged suffix line", () => {+ const previous = [[1, 2], [3, 4], [5, 6]];+ const next = [Array.from({ length: 10_000 }, (_, index) => index), previous[1], previous[2]];+ const retained = retainHighlightProgress(previous, next, null);+ assert.deepEqual(retained, { counts: [[2, 2, 2]], cursor: 0, located: false });+ assert.equal(next[2], previous[2]);+ assert.equal(highlightLineCount(retained!, 2), next[2].length);+ const advanced = advanceHighlightProgress(next, retained!);+ assert.deepEqual(advanced?.counts, [[514, 2, 2]]);+});++test("several changed middle lines preserve disjoint colored islands and partial dense lines", () => {+ const previous = Array.from({ length: 6 }, () => Array<number>(1000).fill(0));+ const next = previous.slice();+ next[1] = Array<number>(1100).fill(1);+ next[3] = Array<number>(1200).fill(2);+ const progress = { counts: [[1000, 1000, 512, 1000, 0, 1000]], cursor: 2, located: true };+ const retained = retainHighlightProgress(previous, next, progress);+ assert.deepEqual(retained, progress);+ assert.notEqual(retained?.counts, progress.counts);+ assert.equal(highlightLineCount(retained!, 2), 512);+ assert.equal(highlightLineCount(retained!, 5), 1000);+ assert.equal(retained?.counts[0], progress.counts[0]);+});++test("null tokens and small coverage upgraded to dense tokens regain bounded progress", () => {+ const dense = [Array.from({ length: 10_000 }, (_, index) => index)];+ assert.deepEqual(retainHighlightProgress(null, dense, null), { counts: [EMPTY_HIGHLIGHT_COUNTS], cursor: 0, located: false });+ const retained = retainHighlightProgress([[0]], dense, null);+ assert.deepEqual(retained, { counts: [[1]], cursor: 0, located: false });+ assert.deepEqual(advanceHighlightProgress(dense, retained!), {+ counts: [[513]], cursor: 0, located: true,+ });+});++test("append starts only new lines at zero and leaves existing completed lines intact", () => {+ const previous = [[1], [2], [3]];+ const next = [...previous, [4]];+ const progress = retainHighlightProgress(previous, next, null);+ assert.deepEqual(progress, { counts: [[1, 1, 1, 0]], cursor: 0, located: false });+ assert.equal(advanceHighlightProgress(next, progress!), null);+ assert.equal(retainHighlightProgress(previous, previous.slice(), null), null);+});++test("truncation clamps counts and cursor and recognizes entirely complete retained content", () => {+ const previous = linesOf(1000, 1000, 1000);+ const progress = { counts: [[1000, 512, 0]], cursor: 2, located: true };+ assert.deepEqual(retainHighlightProgress(previous, linesOf(1000, 800), progress), {+ counts: [[1000, 512]], cursor: 1, located: true,+ });+ assert.equal(retainHighlightProgress(previous, linesOf(10, 20), progress), null);+ assert.equal(retainHighlightProgress(previous, [], progress), null);+});++test("a batch copies only its changed groups and shares untouched empty groups", () => {+ const lines = Array.from({ length: 3200 }, () => ({ length: 12 }));+ const previous = initialHighlightProgress(lines)!;+ for (const group of previous.counts) Object.freeze(group);+ Object.freeze(previous.counts);+ Object.freeze(previous);+ const next = advanceHighlightProgress(lines, previous, 1024)!;+ assert.equal(next.counts.length, 100);+ const changed = next.counts.flatMap((group, index) => group !== previous.counts[index] ? [index] : []);+ assert.deepEqual(changed, [32, 33]);+ assert.equal(next.counts[2], EMPTY_HIGHLIGHT_COUNTS);+ assert.equal(next.counts[99], EMPTY_HIGHLIGHT_COUNTS);+ assert.equal(highlightLineCount(previous, 1024), 0);+ assert.equal(highlightLineCount(next, 1024), 12);+ assert.equal(assertBoundedStep(coverage(lines, previous), coverage(lines, next)), 504);+});++test("retaining replacement tokens reuses disjoint unchanged count groups", () => {+ const previous = Array.from({ length: 96 }, () => ({ length: 1000 }));+ const flat = previous.map((line, index) => index === 33 ? 512 : index === 95 ? 0 : line.length);+ const groups = updateFenceChunks(null, flat);+ for (const group of groups) Object.freeze(group);+ Object.freeze(groups);+ const progress = { counts: groups, cursor: 33, located: true };+ const next = previous.slice();+ next[2] = { length: 800 };+ next[34] = { length: 1100 };+ const retained = retainHighlightProgress(previous, next, progress)!;+ assert.notEqual(retained.counts[0], groups[0]);+ assert.equal(retained.counts[1], groups[1]);+ assert.equal(retained.counts[2], groups[2]);+ assert.equal(highlightLineCount(retained, 2), 800);+ assert.equal(highlightLineCount(retained, 33), 512);+ assert.equal(highlightLineCount(retained, 34), 1000);+ assert.equal(highlightLineCount(progress, 2), 1000);+});++test("appending and truncating preserve every unaffected count group", () => {+ const previous = Array.from({ length: 96 }, () => ({ length: 1000 }));+ const progress = {+ counts: updateFenceChunks(null, previous.map((line, index) => index === 64 ? 512 : line.length)),+ cursor: 64,+ located: true,+ };+ const appended = retainHighlightProgress(previous, [...previous, { length: 1 }], progress)!;+ assert.deepEqual(appended.counts.slice(0, 3), progress.counts);+ for (let index = 0; index < 3; index += 1) assert.equal(appended.counts[index], progress.counts[index]);+ assert.equal(appended.counts[3], EMPTY_HIGHLIGHT_COUNTS);+ assert.equal(highlightLineCount(appended, 96), 0);+ const truncated = retainHighlightProgress(previous, previous.slice(0, 65), progress)!;+ assert.equal(truncated.counts[0], progress.counts[0]);+ assert.equal(truncated.counts[1], progress.counts[1]);+ assert.deepEqual(truncated.counts[2], [512]);+ assert.notEqual(truncated.counts[2], progress.counts[2]);+});diff --git a/studio/frontend/tests/fence-highlight-queue.test.ts b/studio/frontend/tests/fence-highlight-queue.test.tsnew file mode 100644index 00000000000..d52d273811e--- /dev/null+++ b/studio/frontend/tests/fence-highlight-queue.test.ts@@ -0,0 +1,241 @@+// 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 {+ createFenceHighlightQueue,+ type FenceHighlightQueueOptions,+ selectionInFence,+} from "../src/components/assistant-ui/fence-highlight-queue.ts";+import { readSrc } from "./helpers/kit.ts";++const harness = (overrides: Partial<FenceHighlightQueueOptions> = {}) => {+ const callbacks = new Set<() => void>();+ const allCallbacks: (() => void)[] = [];+ let blocked = false;+ let commits = 0;+ const queue = createFenceHighlightQueue({+ schedule: (callback) => {+ callbacks.add(callback);+ allCallbacks.push(callback);+ return () => { callbacks.delete(callback); };+ },+ blocked: () => blocked,+ commit: (callback) => { commits += 1; callback(); },+ ...overrides,+ });+ return {+ queue,+ callbacks,+ allCallbacks,+ commits: () => commits,+ block: (value: boolean) => { blocked = value; },+ run: () => {+ const callback = callbacks.values().next().value;+ assert.ok(callback, "a callback is scheduled");+ callbacks.delete(callback);+ callback();+ },+ };+};++test("batches run one per task and rotate unfinished fences fairly", () => {+ const h = harness();+ const calls: string[] = [];+ let first = 0;+ h.queue.add(() => { calls.push("first"); return ++first === 2; }, () => assert.fail());+ h.queue.add(() => { calls.push("second"); return true; }, () => assert.fail());+ assert.deepEqual(calls, []);+ assert.equal(h.callbacks.size, 1);+ assert.equal(h.queue.pending(), 2);+ h.run();+ assert.deepEqual(calls, ["first"]);+ assert.equal(h.queue.pending(), 2);+ h.run();+ assert.deepEqual(calls, ["first", "second"]);+ assert.equal(h.queue.pending(), 1);+ h.run();+ assert.deepEqual(calls, ["first", "second", "first"]);+ assert.equal(h.commits(), 3);+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+});++test("blocked work reschedules without committing or advancing a fence", () => {+ const h = harness();+ let calls = 0;+ h.queue.add(() => { calls += 1; return true; }, () => assert.fail());+ h.block(true);+ h.run();+ h.run();+ assert.equal(calls, 0);+ assert.equal(h.commits(), 0);+ assert.equal(h.callbacks.size, 1);+ h.block(false);+ h.run();+ assert.equal(calls, 1);+ assert.equal(h.queue.pending(), 0);+});++test("cancellation removes only its entry and cancels the last scheduled callback", () => {+ const h = harness();+ let calls = 0;+ const cancelFirst = h.queue.add(() => assert.fail(), () => assert.fail());+ const cancelSecond = h.queue.add(() => { calls += 1; return false; }, () => assert.fail());+ cancelFirst();+ cancelFirst();+ assert.equal(h.queue.pending(), 1);+ h.run();+ assert.equal(calls, 1);+ const stale = h.allCallbacks.at(-1)!;+ cancelSecond();+ assert.equal(h.callbacks.size, 0);+ stale();+ assert.equal(calls, 1);+ assert.equal(h.queue.pending(), 0);+});++test("a stale canceled callback cannot run newly queued work", () => {+ const h = harness();+ const cancel = h.queue.add(() => assert.fail(), () => assert.fail());+ const stale = h.allCallbacks[0];+ cancel();+ let calls = 0;+ h.queue.add(() => { calls += 1; return true; }, () => assert.fail());+ stale();+ assert.equal(calls, 0);+ assert.equal(h.callbacks.size, 1);+ h.run();+ assert.equal(calls, 1);+});++test("flush bypasses blocking and finishes pending fences in one commit", () => {+ const h = harness();+ const finished: string[] = [];+ h.queue.add(() => assert.fail(), () => { finished.push("first"); });+ h.queue.add(() => assert.fail(), () => { finished.push("second"); });+ const stale = h.allCallbacks[0];+ h.block(true);+ h.queue.flush();+ assert.deepEqual(finished, ["first", "second"]);+ assert.equal(h.commits(), 1);+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+ stale();+ h.queue.flush();+ assert.equal(h.commits(), 1);+});++test("a canceled entry stays canceled when its running step returns unfinished", () => {+ const h = harness();+ let cancel = () => {};+ cancel = h.queue.add(() => { cancel(); return false; }, () => assert.fail());+ h.run();+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+});++test("a running step can flush without requeueing itself or canceled siblings", () => {+ const h = harness();+ const finished: string[] = [];+ h.queue.add(() => { h.queue.flush(); return false; }, () => { finished.push("first"); });+ h.queue.add(() => assert.fail(), () => { finished.push("second"); });+ h.run();+ assert.deepEqual(finished, ["first", "second"]);+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+});++test("flush tolerates cleanup, recursive flush and newly registered fences", () => {+ const h = harness();+ const finished: string[] = [];+ let cancelSecond = () => {};+ h.queue.add(() => assert.fail(), () => {+ finished.push("first");+ cancelSecond();+ h.queue.flush();+ h.queue.add(() => assert.fail(), () => { finished.push("third"); });+ });+ cancelSecond = h.queue.add(() => assert.fail(), () => assert.fail());+ h.queue.flush();+ assert.deepEqual(finished, ["first", "third"]);+ assert.equal(h.commits(), 1);+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+});++test("flush includes work registered by the commit lifecycle", () => {+ let added = false;+ const finished: string[] = [];+ const h = harness({ commit: (callback) => {+ callback();+ if (!added) {+ added = true;+ queue.add(() => assert.fail(), () => { finished.push("mounted"); });+ }+ } });+ const queue = h.queue;+ queue.add(() => assert.fail(), () => { finished.push("first"); });+ queue.flush();+ assert.deepEqual(finished, ["first", "mounted"]);+ assert.equal(queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+});++test("failed steps leave no failed entry and do not strand other fences", () => {+ const h = harness();+ const failure = new Error("step failed");+ h.queue.add(() => { throw failure; }, () => assert.fail());+ let completed = false;+ h.queue.add(() => { completed = true; return true; }, () => assert.fail());+ assert.throws(h.run, failure);+ assert.equal(h.queue.pending(), 1);+ assert.equal(h.callbacks.size, 1);+ h.run();+ assert.equal(completed, true);+ assert.equal(h.queue.pending(), 0);+});++test("failed finishes still flush the other fences and cancel stale work", () => {+ const h = harness();+ const failure = new Error("finish failed");+ let completed = false;+ h.queue.add(() => assert.fail(), () => { throw failure; });+ h.queue.add(() => assert.fail(), () => { completed = true; });+ assert.throws(h.queue.flush, failure);+ assert.equal(completed, true);+ assert.equal(h.queue.pending(), 0);+ assert.equal(h.callbacks.size, 0);+ for (const stale of h.allCallbacks) stale();+});++test("a failed commit or scheduler does not leak pending entries", () => {+ const failure = new Error("failed");+ const brokenCommit = harness({ commit: () => { throw failure; } });+ brokenCommit.queue.add(() => assert.fail(), () => assert.fail());+ assert.throws(brokenCommit.queue.flush, failure);+ assert.equal(brokenCommit.queue.pending(), 0);+ assert.equal(brokenCommit.callbacks.size, 0);+ const brokenSchedule = harness({ schedule: () => { throw failure; } });+ assert.throws(() => brokenSchedule.queue.add(() => assert.fail(), () => assert.fail()), failure);+ assert.equal(brokenSchedule.queue.pending(), 0);+});++test("only a selection that ends inside a fence holds the highlight queue", () => {+ const node = (inFence: boolean) => ({+ nodeType: 3,+ parentElement: { closest: (selector: string) => (inFence && selector.includes("code-block") ? {} : null) },+ }) as unknown as Node;+ const prose = node(false);+ const code = node(true);+ assert.equal(selectionInFence(null), false);+ assert.equal(selectionInFence({ anchorNode: prose, focusNode: prose }), false, "a selection in prose lets fences colour");+ assert.equal(selectionInFence({ anchorNode: prose, focusNode: code }), true, "a selection ending in code is held");+ assert.equal(selectionInFence({ anchorNode: code, focusNode: prose }), true);+ const element = { nodeType: 1, closest: () => ({}) } as unknown as Node;+ assert.equal(selectionInFence({ anchorNode: element, focusNode: null }), true, "an element endpoint is checked itself");+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");+ assert.match(defer, /blocked: \(\) => inputPointerHeld\(\) \|\| highlightQuietIn\(\) > 0 \|\| selectionInFence\(liveSelection\(\)\),/);+});diff --git a/studio/frontend/tests/fence-speculation-wiring.test.ts b/studio/frontend/tests/fence-speculation-wiring.test.tsindex f47ac2eda15..7b0ce8348fd 100644--- a/studio/frontend/tests/fence-speculation-wiring.test.ts+++ b/studio/frontend/tests/fence-speculation-wiring.test.ts@@ -14,11 +14,11 @@ const PLUGIN = readSrc("components/assistant-ui/code-plugin.ts");test("the speculator seeds the same cache key the demanded path reads, and only fences the main thread has warmed", () => {assert.match(DEFER, /eligible: \(gate\) => grammarsWarmed\.has\(grammarOf\(gate\)\),/);assert.match(DEFER, /enabled: \(\) =>\s*fenceMode\(\) !== "off" && highlightWorkerState\(\) !== "unavailable",/);- assert.match(DEFER, /busy: \(\) => streamActive\(\) \|\| highlightWorkerState\(\) === "stalled",/);+ assert.match(DEFER, /busy: \(\) => streamActive\(\) \|\| highlightWorkerState\(\) === "stalled"\s*\|\| inputPointerHeld\(\) \|\| inputQuietIn\(\) > 0,/);assert.match(DEFER, /maxChars: MAX_HIGHLIGHT_CHARS,\s*budgetChars: MAX_CACHED_CHARACTERS \/ 2,\s*budgetFences: MAX_FENCES \/ 2,/);assert.match(DEFER, /budgetFences: MAX_FENCES \/ 2,\s*maxInFlight: SPECULATION_IN_FLIGHT,/, "a few requests stay queued in the worker so speculation is not paced by main-thread idle slots");assert.match(DEFER, /const SPECULATION_IN_FLIGHT = 3;/);- assert.match(DEFER, /busy: \(\) => streamActive\(\) \|\| highlightWorkerState\(\) === "stalled",/, "a worker that is late pauses speculation instead of dropping every candidate, so it resumes on the ready message");+ assert.match(DEFER, /busy: \(\) => streamActive\(\) \|\| highlightWorkerState\(\) === "stalled"\s*\|\| inputPointerHeld\(\) \|\| inputQuietIn\(\) > 0,/, "a worker that is late pauses speculation instead of dropping every candidate, so it resumes on the ready message");assert.match(DEFER, /fenceMode\(\) !== "off" && highlightWorkerState\(\) !== "unavailable",/, "only a worker that failed turns speculation off");assert.match(DEFER, /const rect = gate\.node\.getBoundingClientRect\(\);/);assert.equal(DEFER.includes("gate.anchor"), false);@@ -41,7 +41,7 @@ test("the grammar pre-warm runs once per session from the thread root, idle andassert.match(THREAD, /let grammarPrewarm: GrammarPrewarm \| null = null;/);assert.match(THREAD, /if \(grammarPrewarm !== null\) return;/);assert.match(THREAD, /\(code, language, late\) => highlightFenceSource\(code, language, late\),/);- assert.match(THREAD, /quiet: \(\) =>\s*!streamActive\(\)\s*&& performance\.now\(\) - lastInputAt >= PREWARM_INPUT_QUIET_MS,/);+ assert.match(THREAD, /quiet: \(\) =>\s*!streamActive\(\)\s*&& !inputPointerHeld\(\)\s*&& performance\.now\(\) - lastInputAt >= PREWARM_INPUT_QUIET_MS,/);assert.match(THREAD, /skip: grammarWarmed,/);assert.match(THREAD, /useEffect\(\(\) => \{\s*startGrammarPrewarm\(\);\s*\}, \[\]\);/);assert.match(MARKDOWN, /export const highlightFenceSource = \([\s\S]*?\): FenceTokens \| null =>\s*code\.highlight\(fenceHighlightOptions\(body, language\), late\);/);diff --git a/studio/frontend/tests/fence-token-quiet-work.test.ts b/studio/frontend/tests/fence-token-quiet-work.test.tsnew file mode 100644index 00000000000..397048877f6--- /dev/null+++ b/studio/frontend/tests/fence-token-quiet-work.test.ts@@ -0,0 +1,270 @@+// 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 ts from "@typescript/typescript6";++import { readSrc } from "./helpers/kit.ts";++type Result = { source: string; language: string | null; revision?: number };+type Props = { source: string; language: string | null; enabled: boolean; streaming: boolean };+type Effect = { deps: unknown[]; cleanup?: () => void };+const source = readSrc("components/assistant-ui/markdown-text.tsx");+const hookSource = source.slice(source.indexOf("function useFenceTokens("), source.indexOf("\n/**", source.indexOf("function useFenceTokens(")));+const compiled = ts.transpileModule(hookSource, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } }).outputText;++function harness(initial: Partial<Props> = {}) {+ const slots: unknown[] = [];+ const effects = new Map<number, Effect>();+ let pending: { index: number; deps: unknown[]; effect: () => (() => void) | void }[] = [];+ let cursor = 0;+ let dirty = false;+ let mounted = true;+ let props: Props = { source: "old source", language: "javascript", enabled: true, streaming: false, ...initial };+ const jobs = new Set<() => void>();+ const workers: { callback: (result: Result | null) => void; cancelled: boolean; patient: boolean }[] = [];+ const printing = new Set<() => boolean>();+ const calls: string[] = [];+ const late: ((result: Result) => void)[] = [];+ const cache = new Map<string, Result>();+ const options = { mode: "defer", force: false, recent: false, offThread: false, long: false, grammar: true, workerAvailable: true };+ const same = (a: unknown[], b: unknown[]) => a.length === b.length && a.every((value, index) => Object.is(value, b[index]));+ const runHighlight = ({ code, language }: { code: string; language: string | null }, callback: (result: Result) => void): Result | null => {+ calls.push(code);+ if (!options.grammar) { late.push(callback); return null; }+ const result = { source: code, language };+ cache.set(`${language}:${code}`, result);+ return result;+ };+ const context = {+ useState(initialValue: unknown) {+ const index = cursor++;+ if (!(index in slots)) slots[index] = typeof initialValue === "function" ? initialValue() : initialValue;+ return [slots[index], (value: unknown) => {+ const next = typeof value === "function" ? value(slots[index]) : value;+ if (!Object.is(next, slots[index])) { slots[index] = next; dirty = true; }+ }];+ },+ useRef(initialValue: unknown) {+ const index = cursor++;+ if (!(index in slots)) slots[index] = { current: initialValue };+ return slots[index];+ },+ useCallback(callback: unknown, deps: unknown[]) {+ const index = cursor++;+ const previous = slots[index] as { callback: unknown; deps: unknown[] } | undefined;+ if (!previous || !same(previous.deps, deps)) slots[index] = { callback, deps };+ return (slots[index] as { callback: unknown }).callback;+ },+ useLayoutEffect(effect: () => (() => void) | void, deps: unknown[]) {+ const index = cursor++;+ const previous = effects.get(index);+ if (!previous || !same(previous.deps, deps)) pending.push({ index, deps, effect });+ },+ fenceNeedsQuietWork: (_language: unknown, _source: unknown, streaming: boolean) =>+ !streaming && options.mode === "defer" && !options.force && !options.recent,+ queueFenceWork: (work: () => void) => {+ if (options.force) { work(); return () => {}; }+ jobs.add(work);+ return () => { jobs.delete(work); };+ },+ trimTrailingNewlines: (body: string) => body.replace(/\n+$/, ""),+ fenceHighlightOptions: (code: string, language: string | null) => ({ code, language }),+ settlesOffThread: () => options.offThread,+ tokenizesOffThread: () => options.long,+ code: {+ highlight: runHighlight,+ highlightExact: runHighlight,+ cached: ({ code, language }: { code: string; language: string | null }) => cache.get(`${language}:${code}`) ?? null,+ cover: () => ({ result: null }),+ seed: ({ code, language }: { code: string; language: string | null }, result: Result) => {+ cache.set(`${language}:${code}`, result);+ },+ },+ requestFullHighlight: (_body: unknown, _language: unknown, callback: (result: Result | null) => void, _speculative: unknown, patient: boolean) => {+ if (!options.workerAvailable) return null;+ const worker = { callback, cancelled: false, patient };+ workers.push(worker);+ return () => { worker.cancelled = true; };+ },+ awaitWorker: (_chars: unknown, callback: () => boolean) => {+ printing.add(callback);+ return () => { printing.delete(callback); };+ },+ };+ const hook = new Function(...Object.keys(context), compiled + "\nreturn useFenceTokens;")(...Object.values(context)) as+ (source: string, language: string | null, enabled: boolean, streaming: boolean) => Result | null;+ let result: Result | null = null;+ const render = (change: Partial<Props> = {}) => {+ assert.ok(mounted);+ props = { ...props, ...change };+ let attempts = 0;+ do {+ assert.ok(++attempts < 20, "hook settles without a render loop");+ dirty = false;+ cursor = 0;+ pending = [];+ result = hook(props.source, props.language, props.enabled, props.streaming);+ if (dirty) continue;+ for (const entry of pending) {+ effects.get(entry.index)?.cleanup?.();+ const cleanup = entry.effect();+ effects.set(entry.index, { deps: entry.deps, cleanup: cleanup || undefined });+ }+ } while (dirty);+ return result;+ };+ const flushOne = () => {+ const next = jobs.values().next().value;+ assert.ok(next);+ jobs.delete(next);+ next();+ return render();+ };+ const unmount = () => {+ for (const entry of effects.values()) entry.cleanup?.();+ mounted = false;+ };+ return { render, flushOne, unmount, jobs, workers, printing, calls, late, options, result: () => result };+}++test("cold completed fences perform no tokenization before their queued turn", () => {+ const h = harness();+ assert.equal(h.render(), null);+ assert.equal(h.calls.length, 0);+ assert.equal(h.jobs.size, 1);+ assert.equal(h.flushOne()?.source, "old source");+ assert.deepEqual(h.calls, ["old source"]);+ h.unmount();+});++test("streaming, window, off and recent completions retain immediate origin", () => {+ for (const mode of ["streaming", "window", "off", "recent"]) {+ const h = harness({ streaming: mode === "streaming" });+ h.options.mode = mode === "window" || mode === "off" ? mode : "defer";+ h.options.recent = mode === "recent";+ assert.equal(h.render()?.source, "old source");+ h.options.recent = false;+ h.options.mode = "defer";+ assert.equal(h.render({ source: "next source", streaming: false })?.source, "next source");+ assert.equal(h.jobs.size, 0);+ h.unmount();+ }+});++test("worker results wait for a queued commit and stale source or language callbacks are discarded", () => {+ const h = harness();+ h.options.offThread = true;+ h.options.long = true;+ h.render();+ h.flushOne();+ const first = h.workers[0];+ first.callback({ source: "old source", language: "javascript" });+ assert.equal(h.render(), null);+ assert.equal(h.jobs.size, 1);+ h.render({ language: "python" });+ assert.equal(first.cancelled, true);+ first.callback({ source: "old source", language: "javascript" });+ assert.equal(h.jobs.size, 1);+ h.flushOne();+ h.workers[1].callback({ source: "old source", language: "python" });+ assert.equal(h.flushOne()?.language, "python");+ h.unmount();+});++test("late grammar callbacks coalesce into the latest publication", () => {+ const h = harness();+ h.options.grammar = false;+ h.render();+ h.flushOne();+ const callback = h.late[0];+ callback({ source: "old source", language: "javascript", revision: 1 });+ callback({ source: "old source", language: "javascript", revision: 2 });+ assert.equal(h.jobs.size, 1);+ assert.equal(h.render(), null);+ assert.equal(h.flushOne()?.revision, 2);+ h.unmount();+});++test("a changed completed source clears old tokens before its new queued work runs", () => {+ const h = harness();+ h.render();+ assert.equal(h.flushOne()?.source, "old source");+ assert.equal(h.render({ source: "replacement source" }), null);+ assert.deepEqual(h.calls, ["old source"]);+ assert.equal(h.flushOne()?.source, "replacement source");+ h.unmount();+});++test("disable and unmount cancel queued starts and delayed publications", () => {+ const h = harness();+ h.render();+ h.render({ enabled: false });+ assert.equal(h.jobs.size, 0);+ h.options.offThread = true;+ h.render({ enabled: true });+ h.flushOne();+ const worker = h.workers[0];+ worker.callback({ source: "old source", language: "javascript" });+ assert.equal(h.jobs.size, 1);+ h.unmount();+ assert.equal(h.jobs.size, 0);+ assert.equal(h.printing.size, 0);+ worker.callback({ source: "old source", language: "javascript" });+ assert.equal(h.jobs.size, 0);+});++test("failed short worker requests queue fallback but long requests never tokenize on failure", () => {+ for (const long of [false, true]) {+ const h = harness();+ h.options.offThread = true;+ h.options.long = long;+ h.render();+ h.flushOne();+ const before = h.calls.length;+ h.workers[0].callback(null);+ assert.equal(h.calls.length, before);+ assert.equal(h.jobs.size, long ? 0 : 1);+ if (!long) assert.equal(h.flushOne()?.source, "old source");+ assert.equal(h.workers[0].patient, long);+ h.unmount();+ }+});++test("print fallback honors quiet work normally and completes synchronously when forced", () => {+ for (const force of [false, true]) {+ const h = harness();+ h.options.offThread = true;+ h.options.long = true;+ h.render();+ h.flushOne();+ h.options.force = force;+ const callback = h.printing.values().next().value;+ assert.ok(callback);+ const before = h.calls.length;+ assert.equal(callback(), force);+ if (force) {+ assert.equal(h.jobs.size, 0);+ assert.equal(h.render()?.source, "old source");+ } else {+ assert.equal(h.calls.length, before);+ assert.equal(h.flushOne()?.source, "old source");+ }+ assert.equal(h.workers[0].cancelled, true);+ h.unmount();+ }+});++test("forcing pending startup makes its print fallback available before the snapshot", () => {+ const h = harness();+ h.options.offThread = true;+ h.options.long = true;+ h.render();+ h.options.force = true;+ h.flushOne();+ for (const fallback of h.printing) fallback();+ assert.equal(h.render()?.source, "old source");+ assert.equal(h.jobs.size, 0);+ h.unmount();+});diff --git a/studio/frontend/tests/highlight-worker-failover.test.ts b/studio/frontend/tests/highlight-worker-failover.test.tsindex 4e88c8b00fc..39e6fd06765 100644--- a/studio/frontend/tests/highlight-worker-failover.test.ts+++ b/studio/frontend/tests/highlight-worker-failover.test.ts@@ -53,13 +53,13 @@ test("a failed worker is never rebuilt and every waiting caller hears about it otest("a fence too long for the main thread stays plain without the worker", () => {const hook = MARKDOWN.slice(MARKDOWN.indexOf("function useFenceTokens("), MARKDOWN.indexOf("function StreamingFenceBlock("));assert.match(hook, /const failover = !tokenizesOffThread\(body, streaming\);/, "only a fence short enough for the main thread may fail over to it");- assert.match(hook, /cancel = requestFullHighlight\(\s*body,\s*languageToken,\s*\(result\) => \{\s*if \(result === null\) \{\s*if \(failover && wanted\.current === body\) \{\s*setTokens\(highlight\(body, late\)\);\s*\}\s*return;\s*\}/, "a failed whole-fence reply for a long fence is never failed over to the main thread");- assert.match(hook, /setTokens\(result\);\s*\},\s*false,\s*!failover,\s*\);/, "only a fence too long for the main thread waits out a late or silent worker");+ assert.match(hook, /cancel = requestFullHighlight\(\s*body,\s*languageToken,\s*\(result\) => \{\s*if \(!current\(\)\) return;\s*if \(result === null\) \{\s*if \(failover\) publish\(\(\) => show\(highlight\(body, late\)\)\);\s*return;\s*\}/, "a failed whole-fence reply for a long fence is never failed over to the main thread");+ assert.match(hook, /show\(result\);\s*\}\);\s*\},\s*false,\s*!failover,\s*\);/, "only a fence too long for the main thread waits out a late or silent worker");assert.match(hook, /if \(cancel === null && failover\) \{\s*settled = highlight\(body, late\);\s*\} else \{\s*highlight\("", \(\) => \{\}\);\s*settled = code\.cover\(options\)\.result;\s*\}\s*release = awaitWorker\(body\.length, \(\) => \{/, "with or without a worker, an uncached long fence waits for one or for a print, showing whatever the main thread already coloured");assert.equal((hook.match(/highlight\(body, late\)/g) ?? []).length, 3, "a short fence is tokenized on the main thread only without the worker's help");assert.ok(hook.lastIndexOf("highlight(body, late)") > hook.lastIndexOf("} else {"));assert.equal((hook.match(/code\.highlight\(/g) ?? []).length, 1);- assert.match(hook, /const result = code\.highlightExact\(\s*fenceHighlightOptions\(body, languageToken\),\s*late,\s*\);/, "a print tokenizes the whole fence now, never the throttled approximation with a plain tail");+ assert.match(hook, /const result = code\.highlightExact\(options, late\);/, "a print tokenizes the whole fence now, never the throttled approximation with a plain tail");assert.match(WORKER, /const result = request\.full\s*\? highlighter\.highlightExact\(options, publish\)\s*: highlighter\.highlight\(options, publish\);/, "a whole-fence reply is exact, since the main thread seeds it as a permanent cache entry");assert.match(WORKER, /if \(request\.full && result !== null\) forget\(\);/, "a finished whole-fence request leaves nothing behind in the worker");assert.match(WORKER, /if \(request\.full && result === null && current\(\)\) \{\s*guard = setTimeout\(\(\) => \{\s*guard = null;\s*if \(!current\(\)\) return;\s*self\.postMessage\(\s*reasoningHighlightFailure\(request\.client, request\.revision\),\s*\);\s*forget\(\);\s*\}, FULL_REPLY_GUARD_MS\);/, "a whole-fence request whose grammar never loads is answered with a failure, so the speculator's slot is freed and the worker can idle");diff --git a/studio/frontend/tests/input-pointer-state.test.ts b/studio/frontend/tests/input-pointer-state.test.tsnew file mode 100644index 00000000000..74291411f3c--- /dev/null+++ b/studio/frontend/tests/input-pointer-state.test.ts@@ -0,0 +1,221 @@+// 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 {+ createInputPointerState,+ inputPointerHeld,+} from "../src/lib/input-pointer-state.ts";+import { createFenceHighlightQueue } from "../src/components/assistant-ui/fence-highlight-queue.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++function environment(pointerEvents = true) {+ const target = Object.assign(new EventTarget(), {+ ...(pointerEvents ? { PointerEvent: function PointerEvent() {} } : {}),+ });+ const document = Object.assign(new EventTarget(), { hidden: false });+ const send = (type: string, fields: Record<string, unknown> = {}, node: EventTarget = target) => {+ node.dispatchEvent(Object.assign(new Event(type), fields));+ };+ const state = createInputPointerState(target as unknown as Window, document as unknown as Document);+ return { target, document, send, state };+}++const mouse = { pointerId: 1, pointerType: "mouse", button: 0, buttons: 1 };++test("pointer state is safe without a document", () => {+ assert.equal(inputPointerHeld(), false);+});++test("the module records presses before the first highlighting subscriber reads it", (t) => {+ const h = environment();+ const scope = globalThis as Record<string, unknown>;+ const saved = { window: scope.window, document: scope.document };+ scope.window = h.target;+ scope.document = h.document;+ t.after(() => {+ scope.window = saved.window;+ scope.document = saved.document;+ h.state.dispose();+ });+ const module = loadWithStubs<{ inputPointerHeld: () => boolean }>(+ new URL("../src/lib/input-pointer-state.ts", import.meta.url),+ {},+ );+ h.send("pointerdown", mouse);+ assert.equal(module.inputPointerHeld(), true);+ h.send("pointerup", { ...mouse, buttons: 0 });+ assert.equal(module.inputPointerHeld(), false);+});++test("replacing the sole queued fence cannot lose a stationary held scrollbar", () => {+ const h = environment();+ const callbacks = new Set<() => void>();+ let commits = 0;+ const queue = createFenceHighlightQueue({+ schedule: (callback) => {+ callbacks.add(callback);+ return () => { callbacks.delete(callback); };+ },+ blocked: h.state.held,+ commit: (callback) => { commits += 1; callback(); },+ });+ const cancel = queue.add(() => true, () => {});+ h.send("pointerdown", mouse);+ cancel();+ assert.equal(queue.pending(), 0);+ queue.add(() => true, () => {});+ const run = () => {+ const callback = callbacks.values().next().value;+ assert.ok(callback);+ callbacks.delete(callback);+ callback();+ };+ run();+ run();+ assert.equal(commits, 0);+ assert.equal(queue.pending(), 1);+ h.send("pointerup", { ...mouse, buttons: 0 });+ run();+ assert.equal(commits, 1);+ assert.equal(queue.pending(), 0);+ h.state.dispose();+});++test("each pointer must release independently and cancellation releases only that pointer", () => {+ const h = environment();+ h.send("pointerdown", mouse);+ h.send("pointerdown", { ...mouse, pointerId: 2, pointerType: "pen" });+ h.send("pointerup", { ...mouse, buttons: 0 });+ assert.equal(h.state.held(), true);+ h.send("pointercancel", { ...mouse, pointerId: 2 });+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("mouse and pen movement recover missed presses and releases without treating hover as a hold", () => {+ const h = environment();+ for (const pointerType of ["mouse", "pen"]) {+ h.send("pointermove", { ...mouse, pointerType, buttons: 0 });+ assert.equal(h.state.held(), false);+ h.send("pointermove", { ...mouse, pointerType });+ assert.equal(h.state.held(), true);+ h.send("pointermove", { ...mouse, pointerType, buttons: 0 });+ assert.equal(h.state.held(), false);+ }+ h.send("pointerdown", { ...mouse, button: 2, buttons: 2 });+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("touch pointers remain held through movement and until their own release or cancel", () => {+ const h = environment();+ h.send("pointerdown", { ...mouse, pointerType: "touch" });+ h.send("pointermove", { ...mouse, pointerType: "touch", buttons: 0 });+ h.send("pointerdown", { ...mouse, pointerType: "touch", pointerId: 2 });+ h.send("pointercancel", { ...mouse, pointerType: "touch" });+ assert.equal(h.state.held(), true);+ h.send("pointerup", { ...mouse, pointerType: "touch", pointerId: 2 });+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("mouse fallback tracks the primary button and recovers a release outside the window", () => {+ const h = environment(false);+ h.send("mousedown", { button: 2, buttons: 2 });+ assert.equal(h.state.held(), false);+ h.send("mousedown", { button: 0, buttons: 1 });+ assert.equal(h.state.held(), true);+ h.send("mousemove", { buttons: 0 });+ assert.equal(h.state.held(), false);+ h.send("mousemove", { buttons: 1 });+ assert.equal(h.state.held(), true);+ h.send("mouseup", { button: 0, buttons: 0 });+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("touch fallback retains other fingers through touchend and touchcancel", () => {+ const h = environment(false);+ h.send("touchstart", { touches: [{}, {}] });+ assert.equal(h.state.held(), true);+ h.send("touchmove", { touches: [{}, {}] });+ h.send("touchend", { touches: [{}] });+ assert.equal(h.state.held(), true);+ h.send("touchcancel", { touches: [] });+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("native drag remains held after pointer cancellation and releases on drop or dragend", () => {+ for (const end of ["drop", "dragend"]) {+ const h = environment();+ h.send("pointerdown", mouse);+ h.send("dragstart");+ h.send("pointercancel", mouse);+ assert.equal(h.state.held(), true);+ h.send(end);+ assert.equal(h.state.held(), false);+ h.state.dispose();+ }+});++test("blur, pagehide and hidden documents release stale state", () => {+ for (const event of ["blur", "pagehide", "visibilitychange"]) {+ const h = environment();+ h.send("pointerdown", mouse);+ if (event === "visibilitychange") {+ h.send(event, {}, h.document);+ assert.equal(h.state.held(), true);+ h.document.hidden = true;+ h.send(event, {}, h.document);+ } else {+ h.send(event);+ }+ assert.equal(h.state.held(), false);+ h.state.dispose();+ }+});++test("a focused element losing focus does not release the pointer that clicked elsewhere", () => {+ const h = environment();+ h.send("pointerdown", mouse);+ const event = new Event("blur");+ Object.defineProperty(event, "target", { value: new EventTarget() });+ h.target.dispatchEvent(event);+ assert.equal(h.state.held(), true);+ h.send("blur");+ assert.equal(h.state.held(), false);+ h.state.dispose();+});++test("disposing clears the hold and removes every listener", () => {+ const h = environment();+ h.send("pointerdown", mouse);+ h.state.dispose();+ h.state.dispose();+ assert.equal(h.state.held(), false);+ h.send("pointerdown", mouse);+ h.send("dragstart");+ assert.equal(h.state.held(), false);+});++test("a cancelled dragstart does not leave every fence held", async () => {+ const h = environment();+ h.send("pointerdown", mouse);+ const cancelled = new Event("dragstart", { cancelable: true });+ h.target.addEventListener("dragstart", (event) => event.preventDefault());+ h.target.dispatchEvent(cancelled);+ h.send("pointerup", { ...mouse, buttons: 0 });+ assert.equal(h.state.held(), true, "the outcome is only known once dispatch is over");+ await new Promise((resolve) => setTimeout(resolve, 0));+ assert.equal(h.state.held(), false, "no drag started, so nothing is held after release");+ h.send("dragstart");+ await new Promise((resolve) => setTimeout(resolve, 0));+ assert.equal(h.state.held(), true, "a drag that starts stays held until it ends");+ h.send("dragend");+ assert.equal(h.state.held(), false);+ h.state.dispose();+});diff --git a/studio/frontend/tests/plain-fence-chunks.test.ts b/studio/frontend/tests/plain-fence-chunks.test.tsnew file mode 100644index 00000000000..0e38e6a6a88--- /dev/null+++ b/studio/frontend/tests/plain-fence-chunks.test.ts@@ -0,0 +1,148 @@+// 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 {+ PLAIN_FENCE_CHUNK_LINES,+ type PlainFenceChunks,+ updatePlainFenceChunks,+} from "../src/components/assistant-ui/plain-fence-chunks.ts";++function expectedNodes(source: string): string[] {+ const nodes: string[] = [];+ const body = source.replace(/\n+$/, "") || "\n";+ for (const [index, line] of body.split("\n").entries()) {+ if (index > 0) nodes.push("\n");+ if (line !== "") nodes.push(line);+ }+ return nodes;+}++function freezeState(state: PlainFenceChunks): PlainFenceChunks {+ state.chunks.forEach(Object.freeze);+ Object.freeze(state.chunks);+ return Object.freeze(state);+}++test("plain chunks preserve every text node and trim only trailing LF", () => {+ const sources = [+ "",+ "\n",+ "\n\n",+ "a",+ "a\n",+ "\n\na\n\n",+ "a\n\nb",+ "\r\n",+ "a\r\nb\r\n",+ "a\r",+ "\t \n\t",+ "🐢\n日本語\n𝄞",+ Array.from({ length: 131 }, (_, index) =>+ index % 3 ? `line ${index}` : "",+ ).join("\n"),+ ];+ for (const source of sources) {+ const state = updatePlainFenceChunks(null, source);+ assert.deepEqual(+ state.chunks.flat(),+ expectedNodes(source),+ JSON.stringify(source),+ );+ assert.equal(state.source, source);+ }+});++test("streaming appends reuse completed chunks and replace only the growing tail", () => {+ const source = Array.from(+ { length: 140 },+ (_, index) => `line ${index}`,+ ).join("\n");+ const first = freezeState(updatePlainFenceChunks(null, source));+ const second = updatePlainFenceChunks(first, `${source} more`);+ assert.equal(second.chunks.length, 3);+ assert.equal(second.chunks[0], first.chunks[0]);+ assert.equal(second.chunks[1], first.chunks[1]);+ assert.notEqual(second.chunks[2], first.chunks[2]);+ assert.deepEqual(second.chunks.flat(), expectedNodes(second.source));+ assert.deepEqual(first.chunks.flat(), expectedNodes(source));+});++test("filling a chunk preserves its position and reuses it across the next boundary", () => {+ let source = Array.from(+ { length: PLAIN_FENCE_CHUNK_LINES - 1 },+ (_, index) => `line ${index}`,+ ).join("\n");+ const first = freezeState(updatePlainFenceChunks(null, source));+ source += "\nlast";+ const full = freezeState(updatePlainFenceChunks(first, source));+ assert.equal(full.chunks.length, 1);+ assert.notEqual(full.chunks[0], first.chunks[0]);+ const next = updatePlainFenceChunks(full, `${source}\nnext`);+ assert.equal(next.chunks.length, 2);+ assert.equal(next.chunks[0], full.chunks[0]);+ assert.deepEqual(next.chunks[1], ["\n", "next"]);+});++test("trailing newlines reuse all chunks until subsequent content makes them visible", () => {+ for (const source of [+ "",+ "a",+ Array.from({ length: 64 }, () => "x").join("\n"),+ ]) {+ const initial = freezeState(updatePlainFenceChunks(null, source));+ const trailing = freezeState(+ updatePlainFenceChunks(initial, `${source}\n\n`),+ );+ assert.equal(trailing.chunks, initial.chunks);+ const continued = updatePlainFenceChunks(trailing, `${source}\n\nend`);+ assert.deepEqual(continued.chunks.flat(), expectedNodes(continued.source));+ }+});++test("identical source returns the existing state", () => {+ const state = freezeState(updatePlainFenceChunks(null, "a\nb\n"));+ assert.equal(updatePlainFenceChunks(state, state.source), state);+});++test("replacement and truncation cannot retain stale lines", () => {+ const source = Array.from(+ { length: 140 },+ (_, index) => `line ${index}`,+ ).join("\n");+ const initial = freezeState(updatePlainFenceChunks(null, source));+ for (const replacement of [+ source.slice(0, -20),+ source.slice(0, 30),+ "replacement\ntext",+ "",+ "\n",+ source.replace("line 3", "edited"),+ ]) {+ const state = updatePlainFenceChunks(initial, replacement);+ assert.deepEqual(state.chunks.flat(), expectedNodes(replacement));+ assert.deepEqual(initial.chunks.flat(), expectedNodes(source));+ }+});++test("mixed appends, edits and truncations preserve Unicode and blank-line segmentation", () => {+ const pieces = ["a", "\n", "\r", "🐢", "", "\n\n", "\t", "日本語", " ", "𝄞"];+ let seed = 5381;+ let state: PlainFenceChunks | undefined;+ let source = "";+ for (let index = 0; index < 700; index += 1) {+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;+ if (index % 113 === 0)+ source = source.slice(0, Math.floor(source.length / 2));+ else if (index % 97 === 0) source = `edited\n${source}`;+ else source += pieces[seed % pieces.length];+ state = freezeState(updatePlainFenceChunks(state, source));+ assert.deepEqual(+ state.chunks.flat(),+ expectedNodes(source),+ `update ${index}`,+ );+ }+});diff --git a/studio/frontend/tests/sidebar-inset-selectors.test.ts b/studio/frontend/tests/sidebar-inset-selectors.test.tsnew file mode 100644index 00000000000..b8dd61cca2c--- /dev/null+++ b/studio/frontend/tests/sidebar-inset-selectors.test.ts@@ -0,0 +1,224 @@+// 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 { optimize } from "@tailwindcss/node";+import postcss from "postcss";+import selectorParser, {+ type Node as SelectorNode,+ type Selector,+} from "postcss-selector-parser";+import { compile } from "tailwindcss";+import ts from "@typescript/typescript6";+import { gateViewportMedia } from "../vite-plugin-viewport-media.ts";+import { readSrc } from "./helpers/kit.ts";++const parsed = ts.createSourceFile(+ "sidebar.tsx",+ readSrc("components/ui/sidebar.tsx"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);+const component = parsed.statements.find(+ (node) =>+ ts.isFunctionDeclaration(node) && node.name?.text === "SidebarInset",+);+assert.ok(component);+const current: string[] = [];+const visit = (node: ts.Node) => {+ if (ts.isStringLiteral(node))+ current.push(+ ...node.text.split(/\s+/).filter((value) => value.startsWith("md:")),+ );+ ts.forEachChild(node, visit);+};+visit(component);+const previous = ["m-2", "ml-0", "rounded-xl", "shadow-sm"].map((utility) =>+ ["md", "peer-data-[variant=inset]", utility].join(":"),+);+previous.push(+ [+ "md",+ "peer-data-[variant=inset]",+ "peer-data-[state=collapsed]",+ "ml-2",+ ].join(":"),+);+const activeDeclaration = parsed.statements+ .filter(ts.isVariableStatement)+ .flatMap((node) => node.declarationList.declarations)+ .find((node) => node.name.getText(parsed) === "sidebarMenuPeerActiveClass");+assert.ok(activeDeclaration?.initializer);+assert.ok(ts.isTaggedTemplateExpression(activeDeclaration.initializer));+assert.equal(activeDeclaration.initializer.tag.getText(parsed), "String.raw");+assert.ok(+ ts.isNoSubstitutionTemplateLiteral(activeDeclaration.initializer.template),+);+const currentActive = activeDeclaration.initializer.template+ .getText(parsed)+ .slice(1, -1);+const previousActive = [+ "peer-data-active/menu-button",+ "text-sidebar-accent-foreground",+].join(":");+const pairs = [+ ...previous.map((value, index) => [value, current[index]]),+ [previousActive, currentActive],+];+const candidates = [...current, currentActive];+const activeVariant = postcss+ .parse(+ readFileSync(+ new URL("tailwind.css", import.meta.resolve("shadcn")),+ "utf8",+ ),+ )+ .nodes.find(+ (node) =>+ node.type === "atrule" &&+ node.name === "custom-variant" &&+ node.params === "data-active",+ );+assert.ok(activeVariant);+const generated = (async () => {+ const compiler = await compile(+ `@theme { --spacing: .25rem; --breakpoint-md: 48rem; --radius-xl: .75rem; --shadow-sm: 0 1px 3px #0002; --color-sidebar-accent-foreground: #333; } ${activeVariant} @tailwind utilities;`,+ );+ return optimize(compiler.build(pairs.flat()), { minify: true }).code;+})();++function includesClass(node: SelectorNode, candidate: string): boolean {+ if (node.type === "class") return node.value === candidate;+ return (+ "nodes" in node &&+ Array.isArray(node.nodes) &&+ node.nodes.some((child) => includesClass(child, candidate))+ );+}++function rules(css: string, candidate: string) {+ const matches: {+ selector: Selector;+ declarations: string[];+ media: string | undefined;+ }[] = [];+ postcss.parse(css).walkRules((rule) => {+ for (const selector of selectorParser().astSync(rule.selector).nodes) {+ if (!includesClass(selector, candidate)) continue;+ const declarations = (rule.nodes ?? [])+ .filter((node) => node.type === "decl")+ .map(+ (node) =>+ `${node.prop}:${node.value}${node.important ? "!important" : ""}`,+ );+ const parent = rule.parent;+ matches.push({+ selector,+ declarations,+ media:+ parent?.type === "atrule" && parent.name === "media"+ ? parent.params+ : undefined,+ });+ }+ });+ assert.ok(matches.length > 0, candidate);+ return matches;+}++type Specificity = [number, number, number];+const add = (a: Specificity, b: Specificity): Specificity => [+ a[0] + b[0],+ a[1] + b[1],+ a[2] + b[2],+];+const compare = (a: Specificity, b: Specificity): number =>+ a[0] - b[0] || a[1] - b[1] || a[2] - b[2];+function specificity(node: SelectorNode): Specificity {+ if (node.type === "id") return [1, 0, 0];+ if (node.type === "class" || node.type === "attribute") return [0, 1, 0];+ if (node.type === "tag") return [0, 0, 1];+ if (node.type === "pseudo") {+ if (node.value === ":where") return [0, 0, 0];+ if ([":is", ":not", ":has"].includes(node.value))+ return (node.nodes ?? [])+ .map(specificity)+ .reduce((a, b) => (compare(a, b) >= 0 ? a : b), [+ 0, 0, 0,+ ] as Specificity);+ return node.value.startsWith("::") ? [0, 0, 1] : [0, 1, 0];+ }+ if ("nodes" in node && Array.isArray(node.nodes))+ return node.nodes.map(specificity).reduce(add, [0, 0, 0] as Specificity);+ return [0, 0, 0];+}++function unnamedSiblings(selector: Selector, candidate: string): string[] {+ const found: string[] = [];+ selector.walkCombinators((combinator) => {+ if (combinator.value.trim() !== "~") return;+ const nodes = combinator.parent!.nodes;+ const next = nodes.slice(nodes.indexOf(combinator) + 1);+ const end = next.findIndex((node) => node.type === "combinator");+ const compound = end === -1 ? next : next.slice(0, end);+ if (!compound.some((node) => includesClass(node, candidate)))+ found.push(String(combinator.parent));+ });+ return found;+}++test("sidebar sibling utilities keep declarations and specificity through compilation and viewport gating", async () => {+ assert.equal(current.length, previous.length);+ const raw = await generated;+ const gated = gateViewportMedia(raw);+ assert.deepEqual(+ gated.queries.map(({ query }) => query),+ ["(min-width:48rem)"],+ );+ for (const css of [raw, optimize(gated.css, { minify: true }).code]) {+ for (const [old, current] of pairs) {+ const before = rules(css, old);+ const after = rules(css, current);+ assert.equal(after.length, before.length);+ assert.deepEqual(+ after.map((rule) => rule.declarations),+ before.map((rule) => rule.declarations),+ );+ assert.deepEqual(+ after.map((rule) => rule.media),+ before.map((rule) => rule.media),+ );+ assert.deepEqual(+ after.map((rule) => specificity(rule.selector)),+ before.map((rule) => specificity(rule.selector)),+ );+ }+ }+});++test("every sidebar sibling selector names its target after final CSS generation", async () => {+ const raw = await generated;+ assert.ok(+ previous.some((candidate) =>+ rules(raw, candidate).some(+ ({ selector }) => unnamedSiblings(selector, candidate).length > 0,+ ),+ ),+ );+ for (const css of [+ raw,+ optimize(gateViewportMedia(raw).css, { minify: true }).code,+ ]) {+ for (const candidate of candidates) {+ for (const { selector } of rules(css, candidate))+ assert.deepEqual(+ unnamedSiblings(selector, candidate),+ [],+ String(selector),+ );+ }+ }+});diff --git a/studio/frontend/tests/sidebar-wrapper-children.test.ts b/studio/frontend/tests/sidebar-wrapper-children.test.tsindex 9a7cd12626b..b11f4ab1769 100644--- a/studio/frontend/tests/sidebar-wrapper-children.test.ts+++ b/studio/frontend/tests/sidebar-wrapper-children.test.ts@@ -19,9 +19,4 @@ test("pinning the desktop sidebar never adds or removes a child of the sidebar w/className="contents"[\s\S]*?\{\(!sidebarShowing \|\| holding\) && \(\s*<PanelResizeHandle/,"the container stays mounted and only its handle comes and goes",);- assert.match(- readSrc("components/ui/sidebar.tsx"),- /md:peer-data-\[variant=inset\]:m-2/,- "<main>'s peer rules flag the wrapper for sibling changes, and with KaTeX's MathML on the page Chromium restyles everything below a flagged parent when a child is inserted before another",- );});