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: cap chat code blocks at a scrollable height and keep them coloured while scrolling (#16865)
Michael Han7e2297328be4
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 456288b75be..70d318c264c 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -3,6 +3,8 @@"use client";+import { CodeXmlIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";import type { HighlightResult } from "@streamdown/code";import {memo,@@ -43,6 +45,7 @@ import {advanceHighlightProgress,EMPTY_HIGHLIGHT_PROGRESS,EMPTY_HIGHLIGHT_COUNTS,+ highlightLineCount,HIGHLIGHT_BATCH_TOKENS,type HighlightProgress,needsHighlightBatches,@@ -66,9 +69,15 @@ import { planPrintTokenization } from "./code-fence-print";import { ROW_DISTANT_ATTRIBUTE } from "./distant-rows";import { createFenceSpeculator } from "./fence-speculation";import { highlightWorkerState, streamActive } from "./use-reasoning-highlight";-import { inputQuietIn, scheduleQuietIdleTask } from "@/lib/schedule-idle-task";+import {+ inputQuietIn,+ nonScrollInputQuietIn,+ scheduleIdleTask,+ scheduleQuietIdleTask,+} from "@/lib/schedule-idle-task";import { inputPointerHeld } from "@/lib/input-pointer-state";import {+ languageDisplayName,MAX_CACHED_CHARACTERS,MAX_FENCES,normalizeLanguage,@@ -91,7 +100,10 @@ const subscribeCodeWrap = (listener: () => void): (() => void) => {wrapObserver = new MutationObserver(() => {for (const notify of wrapListeners) notify();});- wrapObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-code-wrap"] });+ // data-wrap: a block's own word wrap button (CodeBlockActions) overrides the setting for that block.+ wrapObserver.observe(document.documentElement, {+ attributes: true, subtree: true, attributeFilter: ["data-code-wrap", "data-wrap"],+ });}return () => {wrapListeners.delete(listener);@@ -101,8 +113,12 @@ const subscribeCodeWrap = (listener: () => void): (() => void) => {}};};-const codeWrapOn = (): boolean => document.documentElement.hasAttribute("data-code-wrap");-const useCodeWrap = (): boolean => useSyncExternalStore(subscribeCodeWrap, codeWrapOn, () => false);+const codeWrapOn = (node: Element | null): boolean => {+ const own = node?.closest("[data-wrap]")?.getAttribute("data-wrap");+ return own ? own === "on" : document.documentElement.hasAttribute("data-code-wrap");+};+const useCodeWrap = (node: RefObject<Element | null>): boolean =>+ useSyncExternalStore(subscribeCodeWrap, () => codeWrapOn(node.current), () => false);/* One viewport of lookahead. The percentage resolves against the root's HEIGHT in all engines* (spec says width, w3c/IntersectionObserver#391); pf9462_parity.py guards it. */@@ -157,6 +173,16 @@ function PlainFenceText({ source }: { source: string }) {))}</>;}+function CodeBlockLanguage({ language }: { language: string | null }) {+ if (!language) return null;+ return (+ <span className="ml-1 flex items-center gap-1.5" data-code-block-language="">+ <HugeiconsIcon icon={CodeXmlIcon} strokeWidth={1.75} className="size-3.5 shrink-0" />+ {languageDisplayName(language)}+ </span>+ );+}+function FenceShell({language,source,@@ -178,7 +204,7 @@ function FenceShell({data-language={language ?? undefined}data-streamdown="code-block-header">- <span className="ml-1 font-mono lowercase">{language}</span>+ <CodeBlockLanguage language={language} /></div><divclassName="overflow-x-auto rounded-md border border-border bg-background p-4 text-sm"@@ -434,6 +460,18 @@ const fenceSpeculator = createFenceSpeculator<FenceGate>({maxInFlight: SPECULATION_IN_FLIGHT,});+// One capturing listener flags a code body scrolled off its first line, for the fade under its header.+const flagScrolledBody = (event: Event): void => {+ const target = event.target;+ if (!(target instanceof HTMLElement) || target.dataset.streamdown !== "code-block-body") return;+ const scrolled = target.scrollTop > 0;+ if (scrolled !== target.hasAttribute("data-scrolled")) target.toggleAttribute("data-scrolled", scrolled);+};++if (typeof document !== "undefined" && typeof document.addEventListener === "function") {+ document.addEventListener("scroll", flagScrolledBody, { capture: true, passive: true });+}+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {window.addEventListener("beforeprint", () => {upgradeEverythingForPrint();@@ -1060,25 +1098,30 @@ const highlightResize = (): void => {highlightResizedAt = performance.now();};-const highlightQuietIn = (): number =>- Math.max(inputQuietIn(), 300 - (performance.now() - highlightResizedAt));+// Bounded entries ignore wheel and touch scrolling; the rest still wait for the reader to stop.+const highlightQuietIn = (duringScroll: boolean): number =>+ Math.max(+ duringScroll ? nonScrollInputQuietIn() : inputQuietIn(),+ 300 - (performance.now() - highlightResizedAt),+ );const highlightQueue = createFenceHighlightQueue({- schedule: (run) => {+ schedule: (run, duringScroll) => {let frame = 0;let cancelIdle: (() => void) | undefined;const timer = setTimeout(() => {frame = requestAnimationFrame(() => {- cancelIdle = scheduleQuietIdleTask(run, 100);+ cancelIdle = (duringScroll ? scheduleIdleTask : scheduleQuietIdleTask)(run, 100);});- }, Math.max(0, highlightQuietIn(), inputPointerHeld() || selectionInFence(liveSelection()) ? 80 : 0));+ }, Math.max(0, highlightQuietIn(duringScroll), inputPointerHeld() || selectionInFence(liveSelection()) ? 80 : 0));return () => {clearTimeout(timer);cancelAnimationFrame(frame);cancelIdle?.();};},- blocked: () => inputPointerHeld() || highlightQuietIn() > 0 || selectionInFence(liveSelection()),+ blocked: (duringScroll) =>+ inputPointerHeld() || highlightQuietIn(duringScroll) > 0 || selectionInFence(liveSelection()),commit: (run) => flushSync(run),});@@ -1123,7 +1166,7 @@ export function queueFenceWork(work: () => void): () => void {const remove = highlightQueue.add(() => {finish();return true;- }, finish);+ }, finish, true);cancel = () => {remove();unwatchHighlighting();@@ -1148,6 +1191,46 @@ const visibleHighlightLine = (code: HTMLElement | null, frame: HTMLElement | nulreturn Math.max(0, Math.floor((top - line.top) / line.height));};+/** Lines in and one view either side of a block that scrolls on its own, or null when it does not. */+const innerLineWindow = (+ code: HTMLElement | null,+ body: HTMLElement | null,+): { first: number; last: number } | null => {+ if (!code || !body || body.scrollHeight <= body.clientHeight + 1) return null;+ const lines = code.children;+ if (lines.length === 0) return null;+ const view = body.getBoundingClientRect();+ const top = view.top + body.clientTop;+ const lineAt = (y: number): number => {+ let low = 0;+ let high = lines.length - 1;+ while (low < high) {+ const middle = (low + high) >> 1;+ if (lines[middle].getBoundingClientRect().bottom <= y) low = middle + 1;+ else high = middle;+ }+ return low;+ };+ return {+ first: lineAt(top - body.clientHeight),+ last: lineAt(top + 2 * body.clientHeight),+ };+};++// Paused capped fences are not in the highlight queue; printing still has to finish them.+const pausedFences = new Set<() => void>();++const lineWindowColoured = (+ tokens: FenceTokens["tokens"],+ progress: HighlightProgress,+ range: { first: number; last: number },+): boolean => {+ for (let line = range.first; line <= range.last && line < tokens.length; line += 1) {+ if (highlightLineCount(progress, line) < tokens[line].length) return false;+ }+ return true;+};+function useFenceHighlightLimit(tokens: FenceTokens["tokens"] | null,isIncomplete: boolean | undefined,@@ -1156,6 +1239,7 @@ function useFenceHighlightLimit(source: string,code: RefObject<HTMLElement | null>,frame: RefObject<HTMLElement | null>,+ surface: RefObject<HTMLElement | null>,parked = false,): { progress: HighlightProgress | null; staged: boolean } {const eligible = !(typeof window === "undefined" || windowing || isIncomplete@@ -1190,19 +1274,53 @@ function useFenceHighlightLimit(}if (current !== previous) setPrevious(current);const progress = immediate ? null : current.progress;+ const [scrolled, setScrolled] = useState(0);useLayoutEffect(() => {if (progress === null || tokens === null || parked) return;+ const body = surface.current;+ // A capped block colours what is in view and stops; scrolling inside it asks for the rest.+ const capped = innerLineWindow(code.current, body);+ if (capped !== null && body !== null && lineWindowColoured(tokens, progress, capped)) {+ let frameId = 0;+ // Expand code lifts the cap without a scroll: a resize rechecks too.+ const recheck = (): void => {+ if (frameId !== 0) return;+ frameId = requestAnimationFrame(() => {+ frameId = 0;+ const next = innerLineWindow(code.current, body);+ if (next === null || !lineWindowColoured(tokens, progress, next)) setScrolled((n) => n + 1);+ });+ };+ const resized = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(recheck);+ resized?.observe(body);+ body.addEventListener("scroll", recheck, { passive: true });+ const finish = (): void => setPrevious({ tokens, parked, progress: null });+ pausedFences.add(finish);+ return () => {+ pausedFences.delete(finish);+ resized?.disconnect();+ body.removeEventListener("scroll", recheck);+ cancelAnimationFrame(frameId);+ };+ }watchHighlighting();const cancel = highlightQueue.add(() => {- const visible = progress.located ? 0 : visibleHighlightLine(code.current, frame.current);- setPrevious({ tokens, parked, progress: advanceHighlightProgress(tokens, progress, visible) });+ const inView = innerLineWindow(code.current, surface.current);+ const next = inView !== null+ ? advanceHighlightProgress(tokens, { ...progress, located: false }, inView.first)+ : advanceHighlightProgress(+ tokens,+ progress,+ progress.located ? 0 : visibleHighlightLine(code.current, frame.current),+ );+ setPrevious({ tokens, parked, progress: next });return true;- }, () => setPrevious({ tokens, parked, progress: null }));+ }, () => setPrevious({ tokens, parked, progress: null }), capped !== null);return () => {cancel();unwatchHighlighting();};- }, [tokens, progress, parked, code, frame]);+ }, [tokens, progress, parked, code, frame, surface, scrolled]);return { progress, staged };}@@ -1218,6 +1336,9 @@ const setPrinting = (value: boolean): void => {cancelAnimationFrame(windowFrame);windowFrame = 0;}+ if (value && pausedFences.size > 0) flushSync(() => {+ for (const finish of [...pausedFences]) finish();+ });if (value) highlightQueue.flush();if (value) tokenizeForPrint();if (value) highlightQueue.flush();@@ -1593,6 +1714,75 @@ function useLineWindow(const NO_WINDOW = { window: null, pins: null, measured: false } as const;const EMPTY_WINDOW = { window: EMPTY_LINE_WINDOW, pins: null, measured: false } as const;+const READER_SCROLL_EVENTS = ["wheel", "touchmove", "keydown", "pointerdown"] as const;+type BodyScroll = { top: number; atBottom: boolean; at: number };+// A finished stream's remount takes the streamed body's place once, soon after; same-text blocks never share one.+const bodyScrolls = new Map<string, BodyScroll>();+const BODY_SCROLLS_KEPT = 16;++const rememberBodyScroll = (key: string, body: HTMLElement): void => {+ if (body.scrollHeight <= body.clientHeight) return;+ bodyScrolls.delete(key);+ bodyScrolls.set(key, {+ top: body.scrollTop,+ atBottom: body.scrollHeight - body.scrollTop - body.clientHeight < 24,+ at: performance.now(),+ });+ if (bodyScrolls.size > BODY_SCROLLS_KEPT) bodyScrolls.delete(bodyScrolls.keys().next().value as string);+};++const takeBodyScroll = (key: string): BodyScroll | undefined => {+ const saved = bodyScrolls.get(key);+ bodyScrolls.delete(key);+ return saved !== undefined && performance.now() - saved.at < JUST_STREAMED_MS ? saved : undefined;+};++function usePinnedWhileStreaming(+ surface: RefObject<HTMLElement | null>,+ isIncomplete: boolean | undefined,+ tokens: FenceTokens["tokens"] | null,+ language: string | null,+ source: string,+): void {+ const following = useRef(true);+ const mounted = tokens !== null && tokens.length > 0;+ const key = `${language ?? ""}\n${source.slice(0, 200)}`;+ const keyRef = useRef(key);+ keyRef.current = key;+ const streamedRef = useRef(isIncomplete === true);+ if (isIncomplete) streamedRef.current = true;+ useLayoutEffect(() => {+ const body = surface.current;+ if (!(mounted && body)) return;+ const saved = streamedRef.current ? undefined : takeBodyScroll(keyRef.current);+ if (saved) {+ following.current = saved.atBottom;+ body.scrollTop = saved.atBottom ? body.scrollHeight : saved.top;+ }+ // Only the reader's own scroll stops the follow: lines settling above shift scrollTop too.+ let readerAt = Number.NEGATIVE_INFINITY;+ const onReader = (): void => {+ readerAt = performance.now();+ };+ const onScroll = (): void => {+ const atBottom = body.scrollHeight - body.scrollTop - body.clientHeight < 24;+ if (atBottom || performance.now() - readerAt < 250) following.current = atBottom;+ };+ body.addEventListener("scroll", onScroll, { passive: true });+ for (const type of READER_SCROLL_EVENTS) body.addEventListener(type, onReader, { passive: true });+ return () => {+ if (streamedRef.current) rememberBodyScroll(keyRef.current, body);+ body.removeEventListener("scroll", onScroll);+ for (const type of READER_SCROLL_EVENTS) body.removeEventListener(type, onReader);+ };+ }, [surface, mounted]);+ useLayoutEffect(() => {+ const body = surface.current;+ if (!(isIncomplete && following.current && body)) return;+ if (body.scrollHeight > body.clientHeight) body.scrollTop = body.scrollHeight;+ }, [surface, isIncomplete, tokens]);+}+// Keep settled, offscreen fences as text instead of retaining every highlighted span.// Plain text has the same height only without wrapping or line-number gutters.// Reuse the windowing listeners to restore markup for find, print and selection.@@ -1660,16 +1850,16 @@ export const FenceBody = memo(function FenceBody({source: string;windowing: boolean;}) {- const codeWrap = useCodeWrap();+ const code = useRef<HTMLElement | null>(null);+ const surface = useRef<HTMLDivElement | null>(null);+ const wrapper = useRef<HTMLDivElement | null>(null);+ const frame = useRef<HTMLDivElement | null>(null);+ const codeWrap = useCodeWrap(frame);const tokens = result?.tokens ?? null;// Only fences over the cap get a line window; below it the batched highlight path stays on,// so a dense line (minified JSON) still renders in quiet-work batches.windowing ||= WINDOW_SETTLED_FENCES && !isIncomplete && !codeWrap&& (tokens?.length ?? 0) > WINDOW_CAP_LINES;- const code = useRef<HTMLElement | null>(null);- const surface = useRef<HTMLDivElement | null>(null);- const wrapper = useRef<HTMLDivElement | null>(null);- const frame = useRef<HTMLDivElement | null>(null);const { window: lineWindow, pins, measured } = useLineWindow(code,surface,@@ -1684,8 +1874,9 @@ export const FenceBody = memo(function FenceBody({WINDOW_SETTLED_FENCES && !!tokens?.length && !isIncomplete,);const highlight = useFenceHighlightLimit(- tokens, isIncomplete, windowing, language, source, code, frame, offscreenPlain,+ tokens, isIncomplete, windowing, language, source, code, frame, surface, offscreenPlain,);+ usePinnedWhileStreaming(surface, isIncomplete, tokens, language, source);const languageClass = language === null ? null : `language-${language}`;const rootStyle = useMemo(() => {@@ -1717,7 +1908,7 @@ export const FenceBody = memo(function FenceBody({data-language={language ?? undefined}data-streamdown="code-block-header">- <span className="ml-1 font-mono lowercase">{language}</span>+ <CodeBlockLanguage language={language} /></div><divdata-unsloth-fence-paint={diff --git a/studio/frontend/src/components/assistant-ui/code-plugin.ts b/studio/frontend/src/components/assistant-ui/code-plugin.tsindex ecb0622731b..4693ecdcfc4 100644--- a/studio/frontend/src/components/assistant-ui/code-plugin.ts+++ b/studio/frontend/src/components/assistant-ui/code-plugin.ts@@ -77,6 +77,26 @@ const SUPPORTED_LANGUAGE_LIST = Array.from() as BundledLanguage[];const PLAIN_TEXT = "text" as BundledLanguage;+// Shiki names shells by grammar ("Shell" for bash and zsh); readers name them by the tag they typed.+const DISPLAY_NAME_OVERRIDES: Record<string, string> = {+ bash: "Bash",+ zsh: "Zsh",+ text: "Text",+ plaintext: "Text",+ txt: "Text",+ cuda: "CUDA",+};+const DISPLAY_NAMES = new Map(+ bundledLanguagesInfo.flatMap((info) =>+ [info.id, ...(info.aliases ?? [])].map((name) => [name.toLowerCase(), info.name] as const),+ ),+);++export const languageDisplayName = (language: string): string => {+ const key = language.trim().toLowerCase();+ return DISPLAY_NAME_OVERRIDES[key] ?? DISPLAY_NAMES.get(key) ?? key.charAt(0).toUpperCase() + key.slice(1);+};+export const normalizeLanguage = (language: string): BundledLanguage => {const key = language.trim().toLowerCase();const alias = LANGUAGE_ALIAS_OVERRIDES[key] ?? SHIKI_LANGUAGE_ALIASES[key];diff --git a/studio/frontend/src/components/assistant-ui/fence-highlight-queue.ts b/studio/frontend/src/components/assistant-ui/fence-highlight-queue.tsindex bd2b58e552e..552b236dcc5 100644--- a/studio/frontend/src/components/assistant-ui/fence-highlight-queue.ts+++ b/studio/frontend/src/components/assistant-ui/fence-highlight-queue.ts@@ -16,16 +16,18 @@ export const selectionInFence = (type HighlightEntry = {step: () => boolean;finish: () => void;+ /** Bounded work (a reach, or the lines on screen in a capped block) that may run mid-scroll. */+ duringScroll: boolean;};export type FenceHighlightQueueOptions = {- schedule: (callback: () => void) => () => void;- blocked: () => boolean;+ schedule: (callback: () => void, duringScroll: boolean) => () => void;+ blocked: (duringScroll: boolean) => boolean;commit: (callback: () => void) => void;};export function createFenceHighlightQueue(options: FenceHighlightQueueOptions): {- add: (step: () => boolean, finish: () => void) => () => void;+ add: (step: () => boolean, finish: () => void, duringScroll?: boolean) => () => void;flush: () => void;pending: () => number;} {@@ -49,7 +51,7 @@ export function createFenceHighlightQueue(options: FenceHighlightQueueOptions):if (scheduled !== ticket) return;scheduled = null;run();- });+ }, [...entries].some((entry) => entry.duringScroll));} catch (error) {if (scheduled === ticket) scheduled = null;entries.clear();@@ -61,8 +63,12 @@ export function createFenceHighlightQueue(options: FenceHighlightQueueOptions):running = true;let entry: HighlightEntry | undefined;try {- if (options.blocked()) return;- entry = entries.values().next().value;+ for (const candidate of entries) {+ if (!options.blocked(candidate.duringScroll)) {+ entry = candidate;+ break;+ }+ }if (!entry) return;const current = entry;let complete = false;@@ -112,8 +118,8 @@ export function createFenceHighlightQueue(options: FenceHighlightQueueOptions):};return {- add: (step, finish) => {- const entry = { step, finish };+ add: (step, finish, duringScroll = false) => {+ const entry = { step, finish, duringScroll };entries.add(entry);schedule();return () => {diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 4661ce973ca..9f690760f0c 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -51,7 +51,12 @@ import {useAui,useAuiState,} from "@assistant-ui/react";-import { Download01Icon } from "@hugeicons/core-free-icons";+import {+ ArrowExpand01Icon,+ ArrowShrink01Icon,+ Download01Icon,+} from "@hugeicons/core-free-icons";+import { LineWrapDisableIcon, LineWrapIcon } from "@/lib/hugeicons-derived";import { Copy01Icon } from "@/lib/copy-icon";import { HugeiconsIcon } from "@hugeicons/react";import { createMathPlugin } from "@streamdown/math";@@ -636,16 +641,94 @@ export function CodeBlockActions({disabled,language,source,+ wrappable = true,}: {disabled: boolean;language: string | null;source: string | (() => string);+ /** False where the code is not one streamdown block (reasoning fragments): wrap and expand would reach nothing. */+ wrappable?: boolean;}) {const { copied, showCopied } = useCopiedState();+ const actionsRef = useRef<HTMLDivElement>(null);+ // Starts from Appearance > Code > Word wrap; the toggle overrides it for this block only.+ const [wrapped, setWrapped] = useState(+ () => typeof document !== "undefined" && document.documentElement.hasAttribute("data-code-wrap"),+ );+ const wrapLabel = wrapped ? "Disable word wrap" : "Enable word wrap";+ const [expanded, setExpanded] = useState(false);+ const [overflowing, setOverflowing] = useState(false);+ useEffect(() => {+ const wrapper = actionsRef.current?.parentElement;+ if (!wrappable || !wrapper || typeof ResizeObserver === "undefined") return;+ const check = () => {+ const body = wrapper.querySelector<HTMLElement>('[data-streamdown="code-block-body"]');+ wrapper.toggleAttribute("data-scrolls-x", body !== null && body.scrollWidth > body.clientWidth + 1);+ if (wrapper.hasAttribute("data-code-expanded")) return;+ setOverflowing(body !== null && body.scrollHeight > body.clientHeight + 1);+ };+ // A capped body's code can change without the wrapper resizing (a remount, a wrap toggle): recheck on hover.+ const observer = new ResizeObserver(check);+ observer.observe(wrapper);+ wrapper.addEventListener("pointerenter", check);+ check();+ return () => {+ observer.disconnect();+ wrapper.removeEventListener("pointerenter", check);+ };+ }, [wrappable]);+ const expandLabel = expanded ? "Collapse code" : "Expand code";return (- <div className="pointer-events-none absolute top-3 right-3 z-20 flex items-center justify-end">+ <div+ className="pointer-events-none absolute top-3 right-3 z-20 flex items-center justify-end"+ data-code-block-actions=""+ ref={actionsRef}+ ><div className={ACTION_PANEL_CLASS}>+ {wrappable && <button+ type="button"+ className={ACTION_BUTTON_CLASS}+ title={wrapLabel}+ aria-label={wrapLabel}+ aria-pressed={wrapped}+ onClick={() => {+ const next = !wrapped;+ // The block is this bar's sibling; index.css keys the per-block wrap on the shared wrapper.+ actionsRef.current?.parentElement?.setAttribute("data-wrap", next ? "on" : "off");+ setWrapped(next);+ }}+ >+ <HugeiconsIcon icon={wrapped ? LineWrapDisableIcon : LineWrapIcon} strokeWidth={1.75} className="size-icon" />+ </button>}+ {wrappable && (overflowing || expanded) && <button+ type="button"+ className={ACTION_BUTTON_CLASS}+ title={expandLabel}+ aria-label={expandLabel}+ aria-expanded={expanded}+ onClick={() => {+ const next = !expanded;+ actionsRef.current?.parentElement?.toggleAttribute("data-code-expanded", next);+ setExpanded(next);+ }}+ >+ <HugeiconsIcon icon={expanded ? ArrowShrink01Icon : ArrowExpand01Icon} strokeWidth={1.75} className="size-icon" />+ </button>}+ <button+ type="button"+ className={ACTION_BUTTON_CLASS}+ title="Download file"+ disabled={disabled}+ onClick={() => {+ downloadTextFile(+ getCodeFilename(language),+ typeof source === "function" ? source() : source,+ );+ }}+ >+ <HugeiconsIcon icon={Download01Icon} className="size-icon" />+ </button><buttontype="button"className={ACTION_BUTTON_CLASS}@@ -665,20 +748,6 @@ export function CodeBlockActions({className="size-icon"/></button>- <button- type="button"- className={ACTION_BUTTON_CLASS}- title="Download file"- disabled={disabled}- onClick={() => {- downloadTextFile(- getCodeFilename(language),- typeof source === "function" ? source() : source,- );- }}- >- <HugeiconsIcon icon={Download01Icon} className="size-icon" />- </button></div></div>);diff --git a/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsxindex 1c34654824c..a9c3b3ecd0c 100644--- a/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx@@ -361,6 +361,7 @@ function CodeGroup({disabled={streaming}language={code.language}source={() => code.source}+ wrappable={false}/>)}{first.first && (diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsxindex 67d0ad033f4..55af6bbedf9 100644--- a/studio/frontend/src/features/browser/browser-panel.tsx+++ b/studio/frontend/src/features/browser/browser-panel.tsx@@ -60,13 +60,20 @@ import { isTauri } from "@/lib/api-base";import { ChevronDownStandardIcon, ChevronRightStandardIcon } from "@/lib/chevron-icons";import { asPng, copyToClipboard, copyToClipboardFrom } from "@/lib/copy-to-clipboard";import { openExternalLink } from "@/lib/open-link";-import { Settings01Icon, SiteInfoIcon, TrashIcon } from "@/lib/hugeicons-derived";+import {+ LineWrapDisableIcon,+ LineWrapIcon,+ Settings01Icon,+ SiteInfoIcon,+ TrashIcon,+} from "@/lib/hugeicons-derived";import { ShieldAlertGlyph } from "@/lib/shield-alert-icon";import { SquareDashedMousePointerIcon } from "@/lib/annotate-icon";import { Tick02Icon } from "@/lib/tick-icon";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";import {+ CodeXmlIcon,Refresh01Icon,Search01Icon,ArrowUpRight01Icon,@@ -84,10 +91,8 @@ import {PictureInPictureOnIcon,PlusSignIcon,SmartPhone01Icon,- SourceCodeIcon,StarIcon,Tablet01Icon,- TextWrapIcon,UndoIcon,ViewIcon,VolumeMute02Icon,@@ -1759,7 +1764,7 @@ function BrowserFileToolbar({)}><HugeiconsIcon- icon={mode === "preview" ? ViewIcon : SourceCodeIcon}+ icon={mode === "preview" ? ViewIcon : CodeXmlIcon}strokeWidth={1.75}className="size-4"/>@@ -1883,7 +1888,7 @@ function BrowserFileToolbar({onCheckedChange={(wrap) => setView({ wrap })}onSelect={(event) => event.preventDefault()}>- <HugeiconsIcon icon={TextWrapIcon} strokeWidth={1.75} className="size-4" />+ <HugeiconsIcon icon={view.wrap || kind === "text" ? LineWrapDisableIcon : LineWrapIcon} strokeWidth={1.75} className="size-4" />{t("browser.file.wrap")}</DropdownMenuCheckboxItem>) : null}@@ -1990,7 +1995,7 @@ function FloatingFileToolbar({onSelect={(event) => event.preventDefault()}><HugeiconsIcon- icon={TextWrapIcon}+ icon={view.wrap || kind === "text" ? LineWrapDisableIcon : LineWrapIcon}strokeWidth={1.75}className="size-4"/>@@ -2063,7 +2068,7 @@ function FloatingFileToolbar({)}><HugeiconsIcon- icon={mode === "preview" ? ViewIcon : SourceCodeIcon}+ icon={mode === "preview" ? ViewIcon : CodeXmlIcon}strokeWidth={1.75}className="size-4"/>diff --git a/studio/frontend/src/features/chat/artifacts/artifact-card.tsx b/studio/frontend/src/features/chat/artifacts/artifact-card.tsxindex 1db7765b16b..6a3f6bb488d 100644--- a/studio/frontend/src/features/chat/artifacts/artifact-card.tsx+++ b/studio/frontend/src/features/chat/artifacts/artifact-card.tsx@@ -27,10 +27,10 @@ import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";import { useAuiState } from "@assistant-ui/react";import {+ CodeXmlIcon,Download01Icon,InternetIcon,LinkSquare02Icon,- SourceCodeIcon,} from "@hugeicons/core-free-icons";import { Copy01Icon } from "@/lib/copy-icon";import { HugeiconsIcon } from "@hugeicons/react";@@ -272,7 +272,7 @@ export function ArtifactCard({className="pointer-events-none relative flex size-[calc(48px*var(--ui-space-scale,1))] shrink-0 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] dark:bg-[color-mix(in_oklab,var(--foreground)_calc(11%*var(--contrast-wash-gain,1)),transparent)]"><HugeiconsIcon- icon={isReact ? SourceCodeIcon : InternetIcon}+ icon={isReact ? CodeXmlIcon : InternetIcon}strokeWidth={1.75}className="size-6 text-control-accent"/>@@ -336,7 +336,7 @@ export function ArtifactCard({</DropdownMenuItem><DropdownMenuItem onSelect={() => open("source")}>{/* </> draws small, so one size up. */}- <MenuGlyph icon={SourceCodeIcon} className="size-4.5" />+ <MenuGlyph icon={CodeXmlIcon} className="size-4.5" />Code view</DropdownMenuItem><DropdownMenuSeparator />diff --git a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts b/studio/frontend/src/features/chat/lib/attachment-file-kind.tsindex 9e814ebf46d..7aaa41d33a4 100644--- a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts+++ b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts@@ -4,13 +4,13 @@// Name and MIME only: this runs on every tile and row.import {+ CodeXmlIcon,Doc01Icon,FileEmpty02Icon,FlimSlateIcon,ImageIcon,Pdf01Icon,Presentation01Icon,- SourceCodeIcon,Zip02Icon,} from "@hugeicons/core-free-icons";// Relative so the node tests can load this file.@@ -105,8 +105,8 @@ export const ATTACHMENT_KIND_ICONS = {document: FileEmpty02Icon,spreadsheet: SheetIcon,presentation: Presentation01Icon,- web: SourceCodeIcon,- code: SourceCodeIcon,+ web: CodeXmlIcon,+ code: CodeXmlIcon,text: FileEmpty02Icon,archive: Zip02Icon,file: FileEmpty02Icon,diff --git a/studio/frontend/src/features/library/file-kind.ts b/studio/frontend/src/features/library/file-kind.tsindex 2da6393b4f5..71b469b8d4f 100644--- a/studio/frontend/src/features/library/file-kind.ts+++ b/studio/frontend/src/features/library/file-kind.ts@@ -2,13 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import {+ CodeXmlIcon,Doc01Icon,FileEmpty02Icon,FlimSlateIcon,ImageIcon,Pdf01Icon,Presentation01Icon,- SourceCodeIcon,} from "@hugeicons/core-free-icons";import { AiSpeechIcon, SheetIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";import type { IconSvgElement } from "@hugeicons/react";@@ -167,13 +167,13 @@ export const TYPE_FILTER_KINDS: Record<LibraryTypeFilter, LibraryFileKind[]> = {export const KIND_ICONS: Record<LibraryFileKind, IconSvgElement> = {image: ImageIcon,- web: SourceCodeIcon,+ web: CodeXmlIcon,word: Doc01Icon,document: FileEmpty02Icon,spreadsheet: SheetIcon,presentation: Presentation01Icon,pdf: Pdf01Icon,- code: SourceCodeIcon,+ code: CodeXmlIcon,audio: AiSpeechIcon,video: FlimSlateIcon,model: TestTubeOutlineIcon,diff --git a/studio/frontend/src/features/security/components/remote-code-consent-dialog.tsx b/studio/frontend/src/features/security/components/remote-code-consent-dialog.tsxindex d16b32ba302..68f23e3541a 100644--- a/studio/frontend/src/features/security/components/remote-code-consent-dialog.tsx+++ b/studio/frontend/src/features/security/components/remote-code-consent-dialog.tsx@@ -15,9 +15,9 @@ import { Badge } from "@/components/ui/badge";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import {+ CodeXmlIcon,SecurityWarningIcon,ShieldBanIcon,- SourceCodeSquareIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Fragment, type ReactNode } from "react";@@ -121,7 +121,7 @@ function UnsafeFileCard({ file }: { file: UnsafeFile }) {{file.level}</Badge><span className="flex min-w-0 items-center gap-1 font-mono text-xs text-muted-foreground">- <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-3.5 shrink-0" />+ <HugeiconsIcon icon={CodeXmlIcon} className="size-3.5 shrink-0" /><span className="truncate">{file.path}</span></span></div>@@ -145,7 +145,7 @@ function FindingCard({ finding }: { finding: RemoteCodeFinding }) {</Badge><span className="text-sm font-medium">{finding.check}</span><span className="ml-auto flex shrink-0 items-center gap-1 font-mono text-xs text-muted-foreground">- <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-3.5" />+ <HugeiconsIcon icon={CodeXmlIcon} className="size-3.5" />{fileLabel}</span></div>diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsxindex 5aac4981446..97098b8c4b6 100644--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx@@ -36,8 +36,8 @@ import {Refresh01Icon,Search01Icon,Shield01Icon,- TextWrapIcon,} from "@hugeicons/core-free-icons";+import { LineWrapDisableIcon, LineWrapIcon } from "@/lib/hugeicons-derived";import { FolderOpenIcon } from "@/lib/folder-icons";import { Copy01Icon } from "@/lib/copy-icon";import { HugeiconsIcon } from "@hugeicons/react";@@ -850,7 +850,7 @@ export function DebuggingTab() {wrap ? "text-foreground" : "text-muted-foreground",)}>- <HugeiconsIcon strokeWidth={1.75} icon={TextWrapIcon} />+ <HugeiconsIcon strokeWidth={1.75} icon={wrap ? LineWrapDisableIcon : LineWrapIcon} /></Button></TooltipTrigger><TooltipContent>{t("settings.debugging.wrapLines")}</TooltipContent>diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 57dce91c698..a451ce8b7c4 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -1727,6 +1727,26 @@ html[data-code-wrap]:not([data-code-line-numbers]) :is(.aui-thread-root, [data-cpadding-inline-start: 0;text-indent: 0;}+/* A block's own word wrap button (CodeBlockActions) overrides the setting above either way. */+[data-wrap="on"] [data-streamdown="code-block"] :is(pre, code) {+ white-space: pre-wrap !important;+ overflow-wrap: anywhere;+}+html[data-code-line-numbers] [data-wrap="on"] [data-streamdown="code-block"] code > span {+ padding-inline-start: 2.5rem;+ text-indent: -2.5rem;+}+html[data-code-line-numbers] [data-wrap="on"] [data-streamdown="code-block"] code > span::before {+ text-indent: 0;+}+html[data-code-wrap] [data-wrap="off"] [data-streamdown="code-block"] :is(pre, code) {+ white-space: pre !important;+ overflow-wrap: normal;+}+html[data-code-wrap] [data-wrap="off"] [data-streamdown="code-block"] code > span {+ padding-inline-start: 0;+ text-indent: 0;+}/* Capped Thinking box: fades only an edge with more past it; the second layer keeps the scrollbar unfaded. */[data-slot="reasoning-tail"][data-capped] {--trace-fade-top: 0px;@@ -4152,7 +4172,54 @@ html[data-chat-font] .aui-root {.aui-thread-root [data-streamdown="code-block-body"] {/* Keep overlay scrollbars below one-line code. */- padding-bottom: calc(0.625rem * var(--ui-space-scale, 1)) !important;+ padding-bottom: calc(0.75rem * var(--ui-space-scale, 1)) !important;+ max-height: var(--unsloth-code-block-max-height, min(30rem, 55vh));+ overflow-y: auto;+ padding-left: var(--spacing) !important;+ /* Bleeds into the block's padding so the scrollbar hugs its edge. */+ margin-inline-end: calc(-0.75rem * var(--ui-space-scale, 1));+ padding-inline-end: calc(0.75rem * var(--ui-space-scale, 1)) !important;+ scrollbar-gutter: stable;+ }++ /* Fades scrolled code under the header; the second layer keeps the scrollbar's strip unfaded. */+ .aui-thread-root [data-streamdown="code-block-body"][data-scrolled] {+ mask-image:+ linear-gradient(to bottom, transparent, #000 calc(1.25rem * var(--ui-space-scale, 1))),+ linear-gradient(#000, #000);+ mask-size: 100% 100%, calc(1rem * var(--ui-space-scale, 1)) 100%;+ mask-position: 0 0, right;+ mask-repeat: no-repeat;+ }++ .aui-thread-root [data-code-expanded] [data-streamdown="code-block-body"] {+ max-height: none;+ mask-image: none;+ }++ .aui-thread-root [data-streamdown="code-block"] {+ padding-top: calc(0.25rem * var(--ui-space-scale, 1));+ padding-bottom: 0;+ }++ /* The half pixel centres the icons on the label. */+ .aui-thread-root [data-code-block-actions] {+ top: calc(0.25rem * var(--ui-space-scale, 1) + 0.5px);+ }++ /* The scrollbar sits in the bottom padding over the code's last gap, so a wide block is no taller. */+ @supports selector(::-webkit-scrollbar) {+ .aui-thread-root [data-scrolls-x] [data-streamdown="code-block-body"] {+ padding-bottom: calc(0.75rem * var(--ui-space-scale, 1) - 6px) !important;+ }+ }++ @media print {+ .aui-thread-root [data-streamdown="code-block-body"] {+ max-height: none;+ overflow-y: visible;+ mask-image: none;+ }}[data-streamdown="code-block"] {@@ -4485,14 +4552,28 @@ html[data-chat-font] .aui-root {contain: paint;}+ /* Paint containment clips at this box, so it takes the body's bleed and the scrollbar stays inside it. */+ .aui-thread-root [data-unsloth-fence-paint] {+ margin-inline-end: calc(-0.75rem * var(--ui-space-scale, 1));+ }++ .aui-thread-root [data-unsloth-fence-paint] > [data-streamdown="code-block-body"] {+ margin-inline-end: 0;+ }+.aui-thread-root [data-unsloth-fence-paint] pre {width: max-content;}- html[data-code-wrap] .aui-thread-root [data-unsloth-fence-paint] pre {+ html[data-code-wrap] .aui-thread-root [data-unsloth-fence-paint] pre,+ .aui-thread-root [data-wrap="on"] [data-unsloth-fence-paint] pre {width: auto;}+ html[data-code-wrap] .aui-thread-root [data-wrap="off"] [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);@@ -4886,6 +4967,30 @@ html.force-reduced-motion .sidebar-section-drop-line {background: oklch(0.67 0 0 / 0.5);}+/* Chromium ignores ::-webkit-scrollbar while scrollbar-width/color are set. */+@supports selector(::-webkit-scrollbar) {+ .aui-thread-root [data-streamdown="code-block-body"] {+ scrollbar-width: auto;+ scrollbar-color: auto;+ }+}++.aui-thread-root [data-streamdown="code-block-body"]::-webkit-scrollbar {+ height: 6px;+}++.aui-thread-root [data-streamdown="code-block-body"]::-webkit-scrollbar-thumb:horizontal {+ background: transparent;+}++.aui-thread-root [data-streamdown="code-block"]:hover [data-streamdown="code-block-body"]::-webkit-scrollbar-thumb:horizontal {+ background: oklch(0.5 0 0 / 0.4);+}++.dark .aui-thread-root [data-streamdown="code-block"]:hover [data-streamdown="code-block-body"]::-webkit-scrollbar-thumb:horizontal {+ background: oklch(0.72 0 0 / 0.4);+}+/* Classic, not overlay: a wide chat table shows it scrolls before it is touched. */@supports selector(::-webkit-scrollbar) {.aui-md-table-scroll,@@ -5669,6 +5774,11 @@ html.force-reduced-motion .sidebar-section-drop-line {height: round(var(--icon-size), 2px);}+.aui-root.aui-thread-root [data-code-block-actions] .aui-chat-icon-btn svg {+ width: round(var(--icon-size) - 2px, 2px);+ height: round(var(--icon-size) - 2px, 2px);+}+/* Sonner injects fixed 13px toast text and 12px action labels at runtime;text follows the preference at full rate. Line heights are unitless sothey track automatically. */diff --git a/studio/frontend/src/lib/hugeicons-derived.ts b/studio/frontend/src/lib/hugeicons-derived.tsindex 362b06c0a98..d6ab5f9a08b 100644--- a/studio/frontend/src/lib/hugeicons-derived.ts+++ b/studio/frontend/src/lib/hugeicons-derived.ts@@ -122,3 +122,23 @@ export {SheetIcon,TrashIcon,} from "@hugeicons/core-free-icons";++const wrapStroke = {+ stroke: "currentColor",+ strokeLinecap: "round",+ strokeLinejoin: "round",+ strokeWidth: "1.5",+} as const;++// Hugeicons line-wrap / line-wrap-disable (MIT), traced until @hugeicons/core-free-icons ships them (not in 4.4.0).+export const LineWrapIcon: IconSvgElement = [+ ["path", { d: "M5 3V21", ...wrapStroke, key: "0" }],+ ["path", { d: "M9 12H20", ...wrapStroke, key: "1" }],+ ["path", { d: "M15 7.5C15 7.5 20 10.81 20 12C20 13.19 15 16.5 15 16.5", ...wrapStroke, key: "2" }],+];++export const LineWrapDisableIcon: IconSvgElement = [+ ["path", { d: "M20 3V21", ...wrapStroke, key: "0" }],+ ["path", { d: "M9.5 8H13.5C15.433 8 17 9.567 17 11.5C17 13.433 15.433 15 13.5 15H4", ...wrapStroke, key: "1" }],+ ["path", { d: "M7.5 11.5C7.5 11.5 4 14.08 4 15C4 15.92 7.5 18.5 7.5 18.5", ...wrapStroke, key: "2" }],+];diff --git a/studio/frontend/src/lib/schedule-idle-task.ts b/studio/frontend/src/lib/schedule-idle-task.tsindex 88321de8ac5..80c7196ec53 100644--- a/studio/frontend/src/lib/schedule-idle-task.ts+++ b/studio/frontend/src/lib/schedule-idle-task.ts@@ -10,10 +10,13 @@ const INPUT_EVENTS = ["touchstart","touchmove",] as const;+const SCROLL_EVENTS: ReadonlySet<string> = new Set(["wheel", "scroll", "touchmove"]);let lastInputAt = Number.NEGATIVE_INFINITY;+let lastNonScrollInputAt = Number.NEGATIVE_INFINITY;let watchingInput = false;-const noteInput = (): void => {+const noteInput = (event?: Event): void => {lastInputAt = performance.now();+ if (!(event && SCROLL_EVENTS.has(event.type))) lastNonScrollInputAt = lastInputAt;};const watchInput = (): void => {if (watchingInput || typeof document === "undefined") return;@@ -28,6 +31,12 @@ export const inputQuietIn = (): number => {return INPUT_QUIET_MS - (performance.now() - lastInputAt);};+/** Like inputQuietIn, but wheel and touch scrolling do not count: work sliced per frame can run under them. */+export const nonScrollInputQuietIn = (): number => {+ watchInput();+ return INPUT_QUIET_MS - (performance.now() - lastNonScrollInputAt);+};+/*** Run `callback` once the main thread is idle, or after `timeout` at the latest; returns a* canceller. Falls back to setTimeout without requestIdleCallback (Safari, the WebKitGTK webviewdiff --git a/studio/frontend/tests/appearance-code-display.test.ts b/studio/frontend/tests/appearance-code-display.test.tsindex 8c10debf784..5b2a52f4416 100644--- a/studio/frontend/tests/appearance-code-display.test.ts+++ b/studio/frontend/tests/appearance-code-display.test.ts@@ -43,7 +43,7 @@ test("each code setting drives one root attribute the stylesheet keys on", () =>const css = readSrc("index.css");assert.match(css, /html\[data-code-wrap\] \[data-streamdown="code-block"\] :is\(pre, code\)/);assert.match(css, /html\[data-code-no-ligatures\] :is\(pre, code, kbd, samp\)/);- assert.match(css, /html\[data-code-wrap\] \.aui-thread-root \[data-unsloth-fence-paint\] pre \{\s*width: auto;/);+ assert.match(css, /html\[data-code-wrap\] \.aui-thread-root \[data-unsloth-fence-paint\] pre,\s*\.aui-thread-root \[data-wrap="on"\] \[data-unsloth-fence-paint\] pre \{\s*width: auto;/);assert.match(css, /html:not\(\[data-code-line-numbers\]\) :is\(\.aui-thread-root, \[data-code-preview\]\)/);});@@ -55,3 +55,24 @@ test("API examples drop their no-wrap overrides while Word wrap is on", () => {for (const use of uses) assert.ok(use.startsWith("[html:not([data-code-wrap])_&"), use);}});++test("a block's own wrap button overrides the setting in both directions", () => {+ const css = readSrc("index.css");+ assert.match(css, /\[data-wrap="on"\] \[data-streamdown="code-block"\] :is\(pre, code\) \{\s*white-space: pre-wrap !important;/);+ assert.match(css, /html\[data-code-wrap\] \[data-wrap="off"\] \[data-streamdown="code-block"\] :is\(pre, code\) \{\s*white-space: pre !important;/);+ const actions = readSrc("components/assistant-ui/markdown-text.tsx");+ assert.match(actions, /parentElement\?\.setAttribute\("data-wrap", next \? "on" : "off"\)/);+ assert.match(actions, /wrapped \? "Disable word wrap" : "Enable word wrap"/);+ assert.match(readSrc("components/assistant-ui/reasoning-transcript.tsx"), /wrappable=\{false\}/);+});++test("Expand code lifts one block's cap and is offered only while the block overflows", () => {+ const actions = readSrc("components/assistant-ui/markdown-text.tsx");+ assert.match(actions, /\{wrappable && \(overflowing \|\| expanded\) && <button/);+ assert.match(actions, /parentElement\?\.toggleAttribute\("data-code-expanded", next\)/);+ assert.match(actions, /expanded \? "Collapse code" : "Expand code"/);+ const css = readSrc("index.css");+ assert.match(css, /\[data-code-expanded\] \[data-streamdown="code-block-body"\] \{\s*max-height: none;\s*mask-image: none;/);+ assert.match(css, /scrollbar-gutter: stable;/);+ assert.match(css, /linear-gradient\(#000, #000\);\s*mask-size: 100% 100%, calc\(1rem \* var\(--ui-space-scale, 1\)\) 100%;/);+});diff --git a/studio/frontend/tests/code-fence-body.test.ts b/studio/frontend/tests/code-fence-body.test.tsindex 03f67aea985..20f95e506a6 100644--- a/studio/frontend/tests/code-fence-body.test.ts+++ b/studio/frontend/tests/code-fence-body.test.ts@@ -351,6 +351,8 @@ test("paint containment is limited to large completed full-token bodies", () =>sameFenceBodyProps,updateFenceChunks,useLineWindow: () => ({ window: null, pins: null, measured: false }),+ usePinnedWhileStreaming: () => {},+ CodeBlockLanguage: () => null,lineRendered,WINDOW_CAP_LINES,joinClasses: (...parts: (string | null)[]) => parts.filter(Boolean).join(" "),@@ -392,3 +394,72 @@ test("paint containment is limited to large completed full-token bodies", () =>}}});++test("chat code blocks cap their height and scroll inside, except on paper", () => {+ const css = readSrc("index.css");+ const at = css.indexOf('.aui-thread-root [data-streamdown="code-block-body"] {');+ const rule = css.slice(at, css.indexOf("}", at));+ assert.match(rule, /max-height: var\(--unsloth-code-block-max-height, min\(30rem, 55vh\)\);/);+ assert.match(rule, /overflow-y: auto;/);+ assert.match(css, /@media print \{\s+\.aui-thread-root \[data-streamdown="code-block-body"\] \{\s+max-height: none;/);+});++test("a capped block colours only what is in view and a streaming one follows its last line", () => {+ const hook = DEFER.slice(DEFER.indexOf("function useFenceHighlightLimit("), DEFER.indexOf("const READER_SCROLL_EVENTS"));+ assert.match(hook, /const capped = innerLineWindow\(code\.current, body\);/);+ assert.match(hook, /lineWindowColoured\(tokens, progress, capped\)/);+ assert.match(hook, /\}, \(\) => setPrevious\(\{ tokens, parked, progress: null \}\), capped !== null\);/);+ const pin = DEFER.slice(DEFER.indexOf("function usePinnedWhileStreaming("), DEFER.indexOf("export const FenceBody = memo("));+ assert.match(pin, /if \(atBottom \|\| performance\.now\(\) - readerAt < 250\) following\.current = atBottom;/);+ assert.match(pin, /body\.scrollTop = body\.scrollHeight;/);+ assert.match(pin, /body\.scrollTop = saved\.atBottom \? body\.scrollHeight : saved\.top;/);+ assert.match(DEFER, /const READER_SCROLL_EVENTS = \["wheel", "touchmove", "keydown", "pointerdown"\] as const;/);+});++test("Expand code resumes colouring a capped block that had stopped at its view", () => {+ const hook = DEFER.slice(DEFER.indexOf("function useFenceHighlightLimit("), DEFER.indexOf("const READER_SCROLL_EVENTS"));+ assert.match(hook, /if \(next === null \|\| !lineWindowColoured\(tokens, progress, next\)\) setScrolled/);+ assert.match(hook, /new ResizeObserver\(recheck\)/);+ assert.match(hook, /resized\?\.observe\(body\);/);+});++test("printing colours capped blocks that paused at their view", () => {+ const hook = DEFER.slice(DEFER.indexOf("function useFenceHighlightLimit("), DEFER.indexOf("const READER_SCROLL_EVENTS"));+ assert.match(hook, /const finish = \(\): void => setPrevious\(\{ tokens, parked, progress: null \}\);\s*pausedFences\.add\(finish\);/);+ assert.match(hook, /pausedFences\.delete\(finish\);/);+ const print = DEFER.slice(DEFER.indexOf("const setPrinting = "), DEFER.indexOf("const scheduleRemeasure"));+ assert.match(print, /if \(value && pausedFences\.size > 0\) flushSync\(\(\) => \{\s*for \(const finish of \[\.\.\.pausedFences\]\) finish\(\);/);+});++test("only a finished body mounting right after a stream takes its scroll place, once", () => {+ const pin = DEFER.slice(DEFER.indexOf("type BodyScroll"), DEFER.indexOf("export const FenceBody = memo("));+ assert.match(pin, /if \(streamedRef\.current\) rememberBodyScroll\(keyRef\.current, body\);/);+ assert.match(pin, /const saved = streamedRef\.current \? undefined : takeBodyScroll\(keyRef\.current\);/);+ assert.match(pin, /bodyScrolls\.delete\(key\);\s*return saved !== undefined && performance\.now\(\) - saved\.at < JUST_STREAMED_MS/);+ assert.equal(pin.match(/rememberBodyScroll\(/g)?.length, 1);+});++test("a block's own word wrap turns off line windowing for that block only", async () => {+ const { readFileSync } = await import("node:fs");+ const { runInNewContext } = await import("node:vm");+ const ts = (await import("@typescript/typescript6")).default;+ const src = readFileSync(new URL("../src/components/assistant-ui/code-fence-defer.tsx", import.meta.url), "utf8");+ const start = src.indexOf("const codeWrapOn = ");+ const end = src.indexOf("const useCodeWrap = ", start);+ const js = ts.transpileModule(src.slice(start, end), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const html = { attrs: new Set<string>(), hasAttribute(name: string) { return this.attrs.has(name); } };+ const block = (wrap: string | null) => ({+ closest: (selector: string) => selector === "[data-wrap]" && wrap !== null+ ? { getAttribute: () => wrap } : null,+ });+ const context: Record<string, unknown> = { document: { documentElement: html } };+ runInNewContext(`${js}\nthis.codeWrapOn = codeWrapOn;`, context);+ const codeWrapOn = context.codeWrapOn as (node: unknown) => boolean;+ assert.equal(codeWrapOn(block(null)), false, "setting off, no override");+ assert.equal(codeWrapOn(block("on")), true, "the block's wrap button wins over the setting");+ html.attrs.add("data-code-wrap");+ assert.equal(codeWrapOn(block(null)), true, "setting on");+ assert.equal(codeWrapOn(block("off")), false, "the block's unwrap wins too");+ assert.equal(codeWrapOn(null), true, "before mount: the setting");+ assert.match(src, /attributeFilter: \["data-code-wrap", "data-wrap"\]/, "a toggle re-reads the guard");+});diff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.tsindex f4997d698cb..6d74feee637 100644--- a/studio/frontend/tests/code-fence-defer.test.ts+++ b/studio/frontend/tests/code-fence-defer.test.ts@@ -522,3 +522,16 @@ test("the warm dedupes on the grammar, not on the spelling", async () => {"one definition, exported, so the two keyings cannot drift apart",);});++test("code block headers name the language the way the language does, behind a code icon", async () => {+ const { languageDisplayName } = await import("../src/components/assistant-ui/code-plugin.ts");+ assert.equal(languageDisplayName("python"), "Python");+ assert.equal(languageDisplayName("HTML"), "HTML");+ assert.equal(languageDisplayName("ts"), "TypeScript");+ assert.equal(languageDisplayName("bash"), "Bash");+ assert.equal(languageDisplayName("text"), "Text");+ assert.equal(languageDisplayName("mylang"), "Mylang");+ const source = readFileSync(new URL("../src/components/assistant-ui/code-fence-defer.tsx", import.meta.url), "utf8");+ assert.equal(source.match(/<CodeBlockLanguage language=\{language\} \/>/g)?.length, 2);+ assert.match(source, /icon=\{CodeXmlIcon\}/);+});diff --git a/studio/frontend/tests/code-fence-offscreen-restore.test.ts b/studio/frontend/tests/code-fence-offscreen-restore.test.tsindex 72d1a031f5b..80fe2c115e7 100644--- a/studio/frontend/tests/code-fence-offscreen-restore.test.ts+++ b/studio/frontend/tests/code-fence-offscreen-restore.test.ts@@ -113,6 +113,7 @@ test("a fully highlighted fence parked as plain text comes back in quiet-work basource: string,code: { current: null },frame: { current: null },+ surface: { current: null },parked: boolean,) => { progress: HighlightProgress | null; staged: boolean };const queue: { run: () => boolean; flush: () => void; cancelled: boolean }[] = [];@@ -134,6 +135,10 @@ test("a fully highlighted fence parked as plain text comes back in quiet-work bawatchHighlighting: () => {},unwatchHighlighting: () => {},visibleHighlightLine: () => 0,+ // An uncapped block: no inner line window, so the batched path runs.+ innerLineWindow: () => null,+ lineWindowColoured: () => false,+ pausedFences: new Set(),highlightQueue: {add(run: () => boolean, flush: () => void) {const entry = { run, flush, cancelled: false };@@ -156,7 +161,7 @@ test("a fully highlighted fence parked as plain text comes back in quiet-work baassert.ok(needsHighlightBatches(tokens, WINDOW_CAP_LINES));const refs = { current: null };const props = (parked: boolean): Parameters<Hook> =>- [tokens, false, false, "text", "source", refs, refs, parked];+ [tokens, false, false, "text", "source", refs, refs, refs, parked];const live = () => queue.filter((entry) => !entry.cancelled);const highlighted = (progress: HighlightProgress | null) =>progress === null ? Number.POSITIVE_INFINITYdiff --git a/studio/frontend/tests/debug-log-export.test.ts b/studio/frontend/tests/debug-log-export.test.tsindex 11323f65919..16f7bf533e6 100644--- a/studio/frontend/tests/debug-log-export.test.ts+++ b/studio/frontend/tests/debug-log-export.test.ts@@ -197,6 +197,7 @@ function makeWorld(options: {},"@hugeicons/core-free-icons": new Proxy({}, { get: () => ({}) }),"@/lib/folder-icons": new Proxy({}, { get: () => ({}) }),+ "@/lib/hugeicons-derived": { LineWrapDisableIcon: {}, LineWrapIcon: {} },"@hugeicons/react": { HugeiconsIcon: () => null },"@/lib/tick-icon": { Tick02Icon: {} },"@/lib/copy-icon": { Copy01Icon: {} },diff --git a/studio/frontend/tests/desktop-webkit-paths.test.ts b/studio/frontend/tests/desktop-webkit-paths.test.tsindex a118bbc0b38..1a2fb0a99c8 100644--- a/studio/frontend/tests/desktop-webkit-paths.test.ts+++ b/studio/frontend/tests/desktop-webkit-paths.test.ts@@ -108,6 +108,7 @@ test("settled WebKitGTK fences only line-window themselves while code wrapping i"line windows map offsets with one unwrapped row per source line; wrapped lines would highlight a window ahead of the reader, "+ "and a fence under the cap has no line window, so forcing windowing there would only drop the batched highlight path",);- assert.match(defer, /const useCodeWrap = \(\): boolean => useSyncExternalStore\(subscribeCodeWrap, codeWrapOn, \(\) => false\);/);- assert.match(defer, /attributeFilter: \["data-code-wrap"\]/);+ // A block's own wrap button counts too (data-wrap on its wrapper), not only the global setting.+ assert.match(defer, /const useCodeWrap = \(node: RefObject<Element \| null>\): boolean =>\s*useSyncExternalStore\(subscribeCodeWrap, \(\) => codeWrapOn\(node\.current\), \(\) => false\);/);+ assert.match(defer, /attributeFilter: \["data-code-wrap", "data-wrap"\]/);});diff --git a/studio/frontend/tests/fence-highlight-queue.test.ts b/studio/frontend/tests/fence-highlight-queue.test.tsindex d52d273811e..889ff6ee082 100644--- a/studio/frontend/tests/fence-highlight-queue.test.ts+++ b/studio/frontend/tests/fence-highlight-queue.test.ts@@ -237,5 +237,27 @@ test("only a selection that ends inside a fence holds the highlight queue", () =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\(\)\),/);+ assert.match(defer, /blocked: \(duringScroll\) =>\s+inputPointerHeld\(\) \|\| highlightQuietIn\(duringScroll\) > 0 \|\| selectionInFence\(liveSelection\(\)\),/);+});++test("mid-scroll only entries marked for it run, ahead of older ones that wait for quiet", () => {+ let scrolling = true;+ const flags: boolean[] = [];+ const h = harness({+ schedule: (callback, duringScroll) => {+ flags.push(duringScroll);+ h.callbacks.add(callback);+ return () => { h.callbacks.delete(callback); };+ },+ blocked: (duringScroll) => scrolling && !duringScroll,+ });+ const ran: string[] = [];+ h.queue.add(() => { ran.push("rest of a long fence"); return true; }, () => {});+ h.queue.add(() => { ran.push("lines in view"); return true; }, () => {}, true);+ h.run();+ assert.deepEqual(ran, ["lines in view"]);+ assert.equal(flags.at(-1), false, "with only waiting work left, the next slot waits for quiet");+ scrolling = false;+ h.run();+ assert.deepEqual(ran, ["lines in view", "rest of a long fence"]);});