Skip to content

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.

Perf/scroll performance (#13255)

Eyerae36527ddcbad
diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.json
index 4f3e9ccacdc..065f948e4d9 100644
--- a/studio/frontend/package-lock.json
+++ b/studio/frontend/package-lock.json
@@ -99,6 +99,8 @@
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
+ "postcss": "^8.5.28",
+ "postcss-selector-parser": "^7.1.6",
"rolldown": "1.0.3",
"typescript": "~5.9.3",
"typescript-eslint": "^8.55.0",
diff --git a/studio/frontend/package.json b/studio/frontend/package.json
index e63023adea7..8d513e8036d 100644
--- a/studio/frontend/package.json
+++ b/studio/frontend/package.json
@@ -132,6 +132,8 @@
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
+ "postcss": "^8.5.28",
+ "postcss-selector-parser": "^7.1.6",
"rolldown": "1.0.3",
"typescript": "~5.9.3",
"typescript-eslint": "^8.55.0",
diff --git a/studio/frontend/public/reload-snapshot.js b/studio/frontend/public/reload-snapshot.js
index eff83fc3a8f..74f37f54df1 100644
--- a/studio/frontend/public/reload-snapshot.js
+++ b/studio/frontend/public/reload-snapshot.js
@@ -18,6 +18,7 @@
var overlay = null;
var retainedSnapshot = null;
var removalTimer = null;
+ var viewportObserver = null;
var accountStorageKey = "unsloth.browser-account.v1";
function readAccountMarker() {
try {
@@ -340,6 +341,23 @@
"reload-snapshot-shell " +
(typeof snapshot.rootClass === "string" ? snapshot.rootClass : "");
applyAppearanceAttributes(shellRoot, snapshot.appearance);
+ Array.prototype.forEach.call(
+ document.documentElement.attributes,
+ function (attribute) {
+ if (attribute.name.indexOf("data-mq-") === 0) {
+ shellRoot.setAttribute(attribute.name, attribute.value);
+ }
+ },
+ );
+ viewportObserver = new MutationObserver(function (records) {
+ records.forEach(function (record) {
+ var name = record.attributeName;
+ if (name.indexOf("data-mq-") === 0) {
+ shellRoot.toggleAttribute(name, document.documentElement.hasAttribute(name));
+ }
+ });
+ });
+ viewportObserver.observe(document.documentElement, { attributes: true });
var tokens = snapshot.tokens || {};
Object.keys(tokens).forEach(function (name) {
if (name.slice(0, 2) === "--" && typeof tokens[name] === "string") {
@@ -849,6 +867,10 @@
}
function removeOverlay() {
+ if (viewportObserver) {
+ viewportObserver.disconnect();
+ viewportObserver = null;
+ }
if (removalTimer !== null) {
clearTimeout(removalTimer);
removalTimer = null;
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index a69e0df9c87..ca73ba67b82 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -47,8 +47,11 @@ export const BUDGET = {
// message action bar rework (#12735) 2.9 KB raw, and the other merges in that range the rest,
// all in the eager chat, index and settings chunks. Headroom ran out, so the same margin is put
// back.
- transferBytes: 1_991_000,
- rawBytes: 6_646_000,
+ // The long-chat render work (#13255: deferred fences and reasoning rows) adds 33.3 KB raw / 13.1 KB
+ // transfer to the eager chat chunk (6,477.1 -> 6,510.4 KB raw, 1,942.6 -> 1,955.7 KB transfer at
+ // 160cb41fe, one machine and build); raised by that so main's margin stays where it was.
+ transferBytes: 2_005_000,
+ rawBytes: 6_681_000,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/app/low-device-scale.ts b/studio/frontend/src/app/low-device-scale.ts
new file mode 100644
index 00000000000..1a21a912bbd
--- /dev/null
+++ b/studio/frontend/src/app/low-device-scale.ts
@@ -0,0 +1,80 @@
+// 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 {
+ observeDevicePixelRatio,
+ type PixelRatioSource,
+} from "./window-layout-lifecycle.ts";
+
+export const LOW_DEVICE_SCALE_ATTRIBUTE = "data-low-device-scale";
+
+const COMPOSITED_SCROLLING_DEVICE_SCALE = 1.5;
+
+type FlagRoot = {
+ toggleAttribute: (name: string, force: boolean) => boolean;
+ removeAttribute: (name: string) => void;
+};
+
+export function isLowDeviceScale(
+ devicePixelRatio: number,
+ interfaceZoom: number,
+): boolean {
+ const zoom = interfaceZoom > 0 ? interfaceZoom : 1;
+ return devicePixelRatio / zoom < COMPOSITED_SCROLLING_DEVICE_SCALE;
+}
+
+export function watchLowDeviceScale(options: {
+ source: PixelRatioSource;
+ interfaceZoom: () => number;
+ subscribeInterfaceZoom: (listener: () => void) => () => void;
+ root: FlagRoot;
+}): () => void {
+ const { source, interfaceZoom, subscribeInterfaceZoom, root } = options;
+ const sync = () => {
+ root.toggleAttribute(
+ LOW_DEVICE_SCALE_ATTRIBUTE,
+ isLowDeviceScale(source.devicePixelRatio(), interfaceZoom()),
+ );
+ };
+ sync();
+ const stopRatio = observeDevicePixelRatio(source, sync);
+ const stopZoom = subscribeInterfaceZoom(sync);
+ return () => {
+ stopRatio();
+ stopZoom();
+ root.removeAttribute(LOW_DEVICE_SCALE_ATTRIBUTE);
+ };
+}
+
+export const THREAD_SCROLLBAR_GUTTER_PROPERTY = "--thread-scrollbar-gutter";
+
+export function measureThinScrollbar(): number {
+ const probe = document.createElement("div");
+ probe.setAttribute("aria-hidden", "true");
+ probe.style.cssText =
+ "position:absolute;top:0;left:0;width:100px;height:1px;overflow-y:scroll;scrollbar-width:thin;scrollbar-color:transparent transparent;visibility:hidden;pointer-events:none";
+ const content = document.createElement("div");
+ probe.append(content);
+ document.body.append(probe);
+ const width =
+ probe.getBoundingClientRect().width - content.getBoundingClientRect().width;
+ probe.remove();
+ return width;
+}
+
+export function watchThreadScrollbarGutter(options: {
+ source: PixelRatioSource;
+ measure: () => number;
+ style: Pick<CSSStyleDeclaration, "setProperty" | "removeProperty">;
+}): () => void {
+ const { source, measure, style } = options;
+ const sync = () => {
+ style.setProperty(THREAD_SCROLLBAR_GUTTER_PROPERTY, `${measure()}px`);
+ };
+ sync();
+ const stopRatio = observeDevicePixelRatio(source, sync);
+ return () => {
+ stopRatio();
+ style.removeProperty(THREAD_SCROLLBAR_GUTTER_PROPERTY);
+ };
+}
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 04b50dbe64c..8b21fe70544 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -48,15 +48,22 @@ import { useTauriUpdate } from "@/hooks/use-tauri-update";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { isTauri } from "@/lib/api-base";
import { followDesktopUpdateScreen } from "@/lib/desktop-update-activity";
+import { useDocumentFlag } from "@/lib/document-flag";
import { refreshWindowChromeTop } from "@/lib/window-chrome";
import {
CHAT_SETTINGS_INSET_VAR,
+ cornerInsetScope,
getToastOffsets,
insetPastChatSettings,
} from "@/lib/toast-offset";
import { Z_LAYER } from "@/lib/z-layers";
import { useRouterState } from "@tanstack/react-router";
import { setDesktopShellReady } from "./desktop-shell-ready";
+import {
+ measureThinScrollbar,
+ watchLowDeviceScale,
+ watchThreadScrollbarGutter,
+} from "./low-device-scale";
import { MotionConfig } from "motion/react";
import {
type CSSProperties,
@@ -114,6 +121,11 @@ const STACK_CARD_INSET_RIGHT = 16;
// Rail stays flush with the corner; only its padding grows past the open Run settings panel.
const STACK_CARD_INSET_RIGHT_PAST_PANEL = `calc(${STACK_CARD_INSET_RIGHT}px + var(${CHAT_SETTINGS_INSET_VAR}, 0px))`;
+function BlockingScreenFlag() {
+ useDocumentFlag("data-blocking-screen-open", true);
+ return null;
+}
+
// macos page zoom does not change dpr; windows already includes zoom in its dpr.
function logicalPerCssPx(monitorScale: number): number {
const zoom = Math.max(1, getAppliedInterfaceZoom());
@@ -511,6 +523,7 @@ function TauriUpdateLayer({
/>
) : (
<div
+ ref={cornerInsetScope}
// Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
className="pointer-events-none fixed bottom-0 right-0 flex max-h-[calc(100dvh-var(--studio-window-chrome-top,0px))] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain"
// Measured from the outside, per card, by tests/studio/playwright_update_banner_layout.py.
@@ -596,6 +609,7 @@ const CUSTOM_CHROME_STYLE = {
"--studio-content-top-inset": "34px",
"--studio-non-chat-content-top-inset": "34px",
"--studio-non-chat-scroller-top": "34px",
+ "--studio-chat-scroller-top": "34px",
"--studio-hidden-route-top-inset": "34px",
// Same split as the native-mac block: chat chrome scales, window chrome does not.
"--studio-chat-header-height": "calc(48px * var(--ui-space-scale, 1))",
@@ -889,6 +903,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
{/* Capped to the viewport: a long download list plus expanded notes would
push the top of the stack off screen. */}
<div
+ ref={cornerInsetScope}
// Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
className="pointer-events-none fixed bottom-0 right-0 flex max-h-[100dvh] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain"
// Measured from the outside, per card, by tests/studio/playwright_update_banner_layout.py.
@@ -957,6 +972,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
data-blocking-screen=""
className="fixed inset-0 z-40 bg-background"
>
+ <BlockingScreenFlag />
<StartupScreen
status={startupStatus}
logs={logs}
@@ -1081,6 +1097,43 @@ function AppearanceCustomizationEffect() {
return null;
}
+function LowDeviceScaleEffect() {
+ useLayoutEffect(() => {
+ const root = document.documentElement;
+ if (!root.classList.contains("client-windows")) return;
+ const source = windowPixelRatioSource();
+ if (!source) return;
+ const stopFlag = watchLowDeviceScale({
+ source,
+ interfaceZoom: getAppliedInterfaceZoom,
+ subscribeInterfaceZoom: subscribeAppliedInterfaceZoom,
+ root,
+ });
+ let gutterSheet: HTMLStyleElement | null = null;
+ let stopGutter: (() => void) | undefined;
+ if (CSS.supports("selector(::-webkit-scrollbar)")) {
+ gutterSheet = document.createElement("style");
+ gutterSheet.textContent =
+ ":is(.aui-thread-viewport, .aui-thread-composer-dock, .compare-pane-fade, [data-side-panel-inset]):not(.chat-full-view-dock *) {}";
+ document.head.append(gutterSheet);
+ const rule = gutterSheet.sheet?.cssRules[0] as CSSStyleRule | undefined;
+ if (rule) {
+ stopGutter = watchThreadScrollbarGutter({
+ source,
+ measure: measureThinScrollbar,
+ style: rule.style,
+ });
+ }
+ }
+ return () => {
+ stopFlag();
+ stopGutter?.();
+ gutterSheet?.remove();
+ };
+ }, []);
+ return null;
+}
+
const REDUCED_MOTION_MAP = {
system: "user",
on: "always",
@@ -1106,6 +1159,7 @@ export function AppProvider({ children }: AppProviderProps) {
<MotionConfig reducedMotion={REDUCED_MOTION_MAP[reduceMotion]}>
<TooltipProvider>
<AppearanceCustomizationEffect />
+ <LowDeviceScaleEffect />
<DeepLinkHandler onOpenUrls={receiveSharedRunConfigUrls} />
<TauriWrapper>{children}</TauriWrapper>
<SttDownloadPrompt />
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 333d57e5b3a..d215e6a7760 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -63,7 +63,6 @@ import { useIsMobileShell } from "@/hooks/use-mobile";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useTypeToActivate } from "@/hooks/use-type-to-activate";
import { type TranslationKey, useT } from "@/i18n";
-import { isTauri } from "@/lib/api-base";
import { createNavigationNonce } from "@/lib/navigation-nonce";
import {
Outlet,
@@ -90,7 +89,7 @@ import { AppProvider } from "../provider";
import { useDesktopShellReady } from "../desktop-shell-ready";
import { type HelpAction, helpActionAvailable, runHelpAction } from "@/components/help-actions";
import type { SettingsMenuAction } from "../app-menu-chords";
-import { useAppMenuActions } from "../use-app-menu-actions";
+import { hasAppMenus, useAppMenuActions } from "../use-app-menu-actions";
declare module "@tanstack/react-router" {
interface StaticDataRouteOption {
@@ -550,10 +549,10 @@ function RootLayout() {
const openingFolder = useOpeningFolder();
const desktopShellReady = useDesktopShellReady();
// Menu items for web shortcuts are live exactly while a mounted handler would take them.
- const sidebarMounted = useShortcutAvailable("toggleSidebar", isTauri);
- const findMounted = useShortcutAvailable("findInPage", isTauri);
- const previousChatMounted = useShortcutAvailable("previousChat", isTauri);
- const nextChatMounted = useShortcutAvailable("nextChat", isTauri);
+ const sidebarMounted = useShortcutAvailable("toggleSidebar", hasAppMenus);
+ const findMounted = useShortcutAvailable("findInPage", hasAppMenus);
+ const previousChatMounted = useShortcutAvailable("previousChat", hasAppMenus);
+ const nextChatMounted = useShortcutAvailable("nextChat", hasAppMenus);
const viaShortcut = (id: Parameters<typeof triggerShortcut>[0], mounted: boolean) =>
mounted ? () => void triggerShortcut(id) : null;
// Help opens settings or a web page, so it works anywhere past sign-in.
diff --git a/studio/frontend/src/app/use-app-menu-actions.ts b/studio/frontend/src/app/use-app-menu-actions.ts
index 45ecde91f8c..681dbc9f627 100644
--- a/studio/frontend/src/app/use-app-menu-actions.ts
+++ b/studio/frontend/src/app/use-app-menu-actions.ts
@@ -10,7 +10,7 @@ import { type AppMenuAction, menuAccelerators } from "./app-menu-chords";
export type { AppMenuAction } from "./app-menu-chords";
// Only the macOS desktop app has these menus.
-const hasAppMenus = isTauri && isMacPlatform();
+export const hasAppMenus = isTauri && isMacPlatform();
// Serialized, so the unmount disable never lands before the sync it follows.
let syncQueue: Promise<unknown> = Promise.resolve();
diff --git a/studio/frontend/src/components/assistant-ui/code-block-containment-mode.ts b/studio/frontend/src/components/assistant-ui/code-block-containment-mode.ts
new file mode 100644
index 00000000000..1be80f8d920
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/code-block-containment-mode.ts
@@ -0,0 +1,25 @@
+// 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 ContainmentMode,
+ defineContainmentFlag,
+} from "./containment-flag.ts";
+
+export type CodeBlockContainmentMode = ContainmentMode;
+
+export const CODE_BLOCK_CONTAINMENT = defineContainmentFlag({
+ attribute: "data-code-block-containment",
+ global: "__UNSLOTH_CODE_BLOCK_CONTAINMENT__",
+});
+
+export const SHIP_DEFAULT = CODE_BLOCK_CONTAINMENT.shipDefault;
+export const CODE_BLOCK_CONTAINMENT_ATTRIBUTE = CODE_BLOCK_CONTAINMENT.attribute;
+export const CODE_BLOCK_CONTAINMENT_ON = CODE_BLOCK_CONTAINMENT.on;
+export const CODE_BLOCK_CONTAINMENT_GLOBAL = CODE_BLOCK_CONTAINMENT.global;
+export const FENCE_HEIGHT_PROPERTY = "--unsloth-fence-height";
+
+export const resolveCodeBlockContainmentMode = CODE_BLOCK_CONTAINMENT.resolve;
+export const codeBlockContainmentMode = CODE_BLOCK_CONTAINMENT.mode;
+export const installCodeBlockContainmentWatcher =
+ CODE_BLOCK_CONTAINMENT.installWatcher;
diff --git a/studio/frontend/src/components/assistant-ui/code-block-containment.ts b/studio/frontend/src/components/assistant-ui/code-block-containment.ts
new file mode 100644
index 00000000000..e6765b7a499
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/code-block-containment.ts
@@ -0,0 +1,50 @@
+// 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 {
+ CODE_BLOCK_CONTAINMENT_ATTRIBUTE,
+ CODE_BLOCK_CONTAINMENT_GLOBAL,
+ CODE_BLOCK_CONTAINMENT_ON,
+ type CodeBlockContainmentMode,
+ codeBlockContainmentMode,
+ installCodeBlockContainmentWatcher,
+} from "./code-block-containment-mode";
+import { engineFindsSkippedContent } from "./math-block-containment";
+
+const readBuildFlag = (): string => {
+ try {
+ return import.meta.env.VITE_UNSLOTH_CODE_BLOCK_CONTAINMENT ?? "";
+ } catch {
+ return "";
+ }
+};
+
+const runtimeFlag = (): unknown =>
+ (globalThis as Record<string, unknown>)[CODE_BLOCK_CONTAINMENT_GLOBAL];
+
+export const applyCodeBlockContainment = (
+ root: Element | null = typeof document === "undefined"
+ ? null
+ : document.documentElement,
+): CodeBlockContainmentMode => {
+ const mode = codeBlockContainmentMode(
+ runtimeFlag(),
+ readBuildFlag(),
+ engineFindsSkippedContent(),
+ );
+ if (!root) return mode;
+ if (mode === "contain") {
+ root.setAttribute(
+ CODE_BLOCK_CONTAINMENT_ATTRIBUTE,
+ CODE_BLOCK_CONTAINMENT_ON,
+ );
+ } else {
+ root.removeAttribute(CODE_BLOCK_CONTAINMENT_ATTRIBUTE);
+ }
+ return mode;
+};
+
+export const watchCodeBlockContainmentOverride = (
+ scope: Record<string, unknown> = globalThis as Record<string, unknown>,
+ apply: () => CodeBlockContainmentMode = applyCodeBlockContainment,
+): boolean => installCodeBlockContainmentWatcher(scope, apply);
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
index 6731d6f73f3..d601acb5b48 100644
--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
@@ -7,6 +7,7 @@ import type { HighlightResult } from "@streamdown/code";
import {
memo,
type RefObject,
+ startTransition,
useEffect,
useLayoutEffect,
useMemo,
@@ -16,16 +17,31 @@ import {
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 {
+ EMPTY_LINE_WINDOW,
+ HYSTERESIS_VIEWPORTS,
isBlankLine,
type LineWindow,
- lineIsWindowed,
+ type LinePins,
+ lineRendered,
+ pinBoundaryLines,
+ samePins,
+ OVERSCAN_VIEWPORTS,
plainLineText,
selectLineWindow,
+ WINDOW_CAP_LINES,
} from "./code-fence-window";
-import { normalizeLanguage } from "./code-plugin";
-import { WINDOW_CAP_LINES } from "./code-fence-window";
+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 {
+ MAX_CACHED_CHARACTERS,
+ MAX_FENCES,
+ normalizeLanguage,
+} from "./code-plugin";
/*
* MONOTONIC fence highlighting: a fence renders as a plain shell until the first time it comes near
@@ -98,19 +114,30 @@ 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;
+};
+
function FenceShell({
language,
source,
+ plain = false,
}: {
language: string | null;
source: string;
+ plain?: boolean;
}) {
return (
<div
className="my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2"
data-language={language ?? undefined}
data-streamdown="code-block"
- data-unsloth-fence-deferred="true"
+ data-unsloth-fence-deferred={plain ? undefined : "true"}
>
<div
className="flex h-8 items-center text-muted-foreground text-xs"
@@ -125,7 +152,7 @@ function FenceShell({
data-streamdown="code-block-body"
>
<pre>
- <code>{shellBody(source)}</code>
+ <code>{plain ? shellLines(source) : shellBody(source)}</code>
</pre>
</div>
</div>
@@ -165,6 +192,7 @@ type FenceGate = {
chars: number;
/** `true` tokenizes this fence's source now; `false` only loads its grammar. */
warm: (tokens: boolean) => void;
+ speculate: (settle: (seeded: boolean) => void) => (() => void) | null;
latch: () => void;
/** A state write that changes nothing, whose only job is to give React sync work to do. */
poke: () => void;
@@ -199,6 +227,7 @@ const latchNow = (arrived: readonly FenceGate[]): void => {
if (arrived.length === 0) return;
for (const gate of arrived) {
unreached.delete(gate);
+ fenceSpeculator.remove(gate);
gate.warm(true);
}
flushSync(() => {
@@ -247,6 +276,7 @@ const onScroll = (event: Event): void => {
if (gateOpen(gate)) arrived.push(gate);
}
latchNow(arrived);
+ fenceSpeculator.rerank();
};
const watchScrolling = (): void => {
@@ -268,7 +298,7 @@ const unwatchScrolling = (): void => {
* printed window match the reader's: a print lays out at PAPER width while the scroll offset
* carries across as raw pixels, so the page lands several fences away (matching paper to window
* removes the difference, which is why chasing the window is the wrong fix). The whole document is
- * on the page, so the whole document has to be highlighted.
+ * on the page, so every fence is revealed (highlighting capped by PRINT_TOKENIZE_CHARS).
* An earlier attempt latched every fence from `beforeprint` with `flushSync` and 53 of 56 still
* printed on streamdown's raw fallback, because the swap alone renders UNHIGHLIGHTED while the
* passive effect waits on a grammar. `latchNow` closes both halves and `warmGrammars` keeps a
@@ -316,10 +346,17 @@ const grammarsWarmed = new Set<string>();
const grammarsLoaded = new Set<string>();
let warmScheduled = false;
+export const grammarWarmed = (language: string | null): boolean =>
+ grammarsWarmed.has(normalizeLanguage(language ?? "text"));
+
// Keyed the way `highlight` keys it, or `py` and `Python` are two keys for one grammar.
const grammarOf = (gate: FenceGate): string =>
normalizeLanguage(gate.language ?? "text");
+const warmMustWait = (): boolean =>
+ typeof (globalThis as Record<string, unknown>).requestIdleCallback !== "function"
+ && (streamActive() || inputQuietIn() > 0);
+
const warmGrammars = (): void => {
warmScheduled = false;
// EVERY GRAMMAR STARTS LOADING IN THE FIRST TASK. A load is cheap and asynchronous, and it is
@@ -337,6 +374,10 @@ const warmGrammars = (): void => {
// ours to tokenize speculatively. Neither marks the grammar warmed, so a later fence in the
// same language still gets its real warm.
if (gate.chars === 0 || gate.chars > MAX_HIGHLIGHT_CHARS) continue;
+ if (warmMustWait()) {
+ scheduleGrammarWarm();
+ return;
+ }
grammarsWarmed.add(language);
// TRUE, not false: real text is what takes the one-off tokenizer cost off the scroll.
gate.warm(true);
@@ -357,6 +398,42 @@ const scheduleGrammarWarm = (): void => {
else setTimeout(warmGrammars, 500);
};
+const rankGates = (gates: readonly FenceGate[]): number[] => {
+ const boxes = new Map<HTMLElement | null, DOMRect>();
+ return gates.map((gate) => {
+ let box = boxes.get(gate.outer);
+ if (box === undefined) {
+ box = gate.outer
+ ? gate.outer.getBoundingClientRect()
+ : new DOMRect(0, 0, window.innerWidth, window.innerHeight);
+ boxes.set(gate.outer, box);
+ }
+ const rect = gate.node.getBoundingClientRect();
+ if (rect.bottom < box.top) return box.top - rect.bottom;
+ if (rect.top > box.bottom) return rect.top - box.bottom;
+ return 0;
+ });
+};
+
+const SPECULATION_IN_FLIGHT = 3;
+
+const fenceSpeculator = createFenceSpeculator<FenceGate>({
+ idle: (callback, timeout) => scheduleQuietIdleTask(callback, timeout),
+ wait: (callback, ms) => {
+ const timer = setTimeout(callback, ms);
+ return () => clearTimeout(timer);
+ },
+ enabled: () =>
+ fenceMode() !== "off" && highlightWorkerState() !== "unavailable",
+ busy: () => streamActive() || highlightWorkerState() === "stalled",
+ eligible: (gate) => grammarsWarmed.has(grammarOf(gate)),
+ rank: rankGates,
+ maxChars: MAX_HIGHLIGHT_CHARS,
+ budgetChars: MAX_CACHED_CHARACTERS / 2,
+ budgetFences: MAX_FENCES / 2,
+ maxInFlight: SPECULATION_IN_FLIGHT,
+});
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("beforeprint", () => {
upgradeEverythingForPrint();
@@ -389,12 +466,25 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
* ancestor really is clipped by the document viewport, but assuming that when a scroller exists is
* the bug the review caught.
*/
+let scrollableNow: WeakMap<Element, boolean> | null = null;
+
+const forgetScrollable = (): void => {
+ scrollableNow = null;
+};
+
const isScrollable = (el: HTMLElement): boolean => {
+ if (scrollableNow === null) {
+ scrollableNow = new WeakMap();
+ queueMicrotask(forgetScrollable);
+ }
+ const known = scrollableNow.get(el);
+ if (known !== undefined) return known;
const overflowY = getComputedStyle(el).overflowY;
- return (
+ const scrollable =
(overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay")
- && el.scrollHeight > el.clientHeight
- );
+ && el.scrollHeight > el.clientHeight;
+ scrollableNow.set(el, scrollable);
+ return scrollable;
};
const scrollerOf = (node: HTMLElement): HTMLElement | null => {
@@ -458,15 +548,59 @@ const inBand = (node: HTMLElement, scroller: HTMLElement | null): boolean => {
* alone. Held in a ref, not an effect dependency, so an unmemoized caller cannot
* rebuild every observer in the thread on every render.
*/
+const FENCE_HEAD_CHARS = 64;
+const JUST_STREAMED_MS = 2000;
+
+let lastStreamingFence: {
+ language: string | null;
+ head: string;
+ chars: number;
+ at: number;
+} | null = null;
+
+export const noteStreamingFence = (
+ language: string | null,
+ source: string,
+): void => {
+ lastStreamingFence = {
+ language,
+ head: source.slice(0, FENCE_HEAD_CHARS),
+ chars: trimmedLength(source),
+ at: performance.now(),
+ };
+};
+
+const justStreamed = (
+ language: string | null,
+ head: string,
+ chars: number,
+): boolean =>
+ lastStreamingFence !== null &&
+ lastStreamingFence.language === language &&
+ lastStreamingFence.head === head &&
+ chars >= lastStreamingFence.chars &&
+ chars - lastStreamingFence.chars < 512 &&
+ performance.now() - lastStreamingFence.at < JUST_STREAMED_MS;
+
export function useFenceReached(
host: RefObject<HTMLElement | null>,
enabled: boolean,
streaming: boolean,
language: string | null,
chars: number,
+ source: string,
warm: (tokens: boolean) => void,
+ speculate: (settle: (seeded: boolean) => void) => (() => void) | null,
): boolean {
- const [latched, setLatched] = useState(false);
+ const speculateRef = useRef(speculate);
+ useEffect(() => {
+ speculateRef.current = speculate;
+ }, [speculate]);
+ const [latched, setLatched] = useState(
+ () =>
+ streaming ||
+ justStreamed(language, source.slice(0, FENCE_HEAD_CHARS), chars),
+ );
// Bumped when the resolved scrolling ancestor stops being one, which rebuilds the gates below
// against the element that clips this fence now. Never read for anything else.
const [generation, setGeneration] = useState(0);
@@ -559,6 +693,7 @@ export function useFenceReached(
language,
chars,
warm: (tokens) => warmRef.current(tokens),
+ speculate: (settle) => speculateRef.current(settle),
latch: () => setLatched(true),
// Reuses `generation`: this fence has just latched, so every effect keyed on it
// early-returns and the bump costs one render. See `latchNow` for why React needs the work.
@@ -567,6 +702,7 @@ export function useFenceReached(
unreached.add(registered);
watchScrolling();
scheduleGrammarWarm();
+ fenceSpeculator.add(registered);
// `reasoning.tsx` drops `max-h-64` when a stream ends and keeps `overflow-y-auto`, so the pane
// stops being a scroller and its box becomes the whole trace. Watch for that and rebuild.
@@ -581,6 +717,7 @@ export function useFenceReached(
return () => {
for (const observer of observers) observer.disconnect();
resize?.disconnect();
+ fenceSpeculator.remove(registered);
unreached.delete(registered);
unwatchScrolling();
};
@@ -591,6 +728,16 @@ export function useFenceReached(
export const DeferredFenceShell = memo(FenceShell);
+export const PlainFenceShell = memo(function PlainFenceShell({
+ language,
+ source,
+}: {
+ language: string | null;
+ source: string;
+}) {
+ return <FenceShell language={language} plain source={source} />;
+});
+
/*
* The highlighted body, rendered here rather than by streamdown.
*
@@ -734,9 +881,96 @@ export const FenceLine = memo(function FenceLine({
const windowedFences = new Set<() => void>();
let windowFrame = 0;
let windowWatched = false;
+let findBarObserver: MutationObserver | null = null;
+let frameRects: Map<Element, DOMRect> | null = null;
+let frameFlying: Map<Element | null, boolean> | null = null;
+let frameSettle = false;
+let pointerHeld: Node | null = null;
+let heldLastFrame = false;
+let frameSelection: { read: boolean; value: Selection | null } | null = null;
+const scrollerMotion = new WeakMap<Element, { top: number; at: number }>();
+const windowMotion = { top: 0, at: 0 };
+const FLYING_VIEWPORTS_PER_SECOND = 10;
+
+const rectDuringFrame = (element: Element): DOMRect => {
+ if (frameRects === null) return element.getBoundingClientRect();
+ const known = frameRects.get(element);
+ if (known !== undefined) return known;
+ const rect = element.getBoundingClientRect();
+ frameRects.set(element, rect);
+ return rect;
+};
+
+const liveSelection = (): Selection | null => {
+ const selection = document.getSelection();
+ return selection !== null && selection.rangeCount > 0 && !selection.isCollapsed
+ ? selection
+ : null;
+};
+
+const selectionDuringFrame = (): Selection | null => {
+ if (frameSelection === null) return liveSelection();
+ if (!frameSelection.read) {
+ frameSelection.read = true;
+ frameSelection.value = liveSelection();
+ }
+ return frameSelection.value;
+};
+
+const draggingDuringFrame = (body: HTMLElement): boolean => {
+ const held = pointerHeld !== null && body.contains(pointerHeld);
+ if (held) heldLastFrame = true;
+ return held;
+};
+
+const selectionBoundaryLines = (codeNode: HTMLElement, body: HTMLElement): number[] => {
+ const selection = selectionDuringFrame();
+ const lines: number[] = [];
+ for (let index = 0; selection !== null && index < selection.rangeCount; index += 1) {
+ const range = selection.getRangeAt(index);
+ for (const boundary of [range.startContainer, range.endContainer]) {
+ if (!body.contains(boundary)) continue;
+ let line: Node | null = boundary;
+ while (line !== null && line.parentNode !== codeNode) line = line.parentNode;
+ if (line === null) continue;
+ const at = Array.prototype.indexOf.call(codeNode.children, line);
+ if (at >= 0) lines.push(at);
+ }
+ }
+ if (lines.length > 0) heldLastFrame = true;
+ return lines;
+};
+
+const flyingDuringFrame = (
+ scroller: HTMLElement | null,
+ viewportHeight: number,
+): boolean => {
+ if (frameFlying === null) return false;
+ const known = frameFlying.get(scroller);
+ if (known !== undefined) return known;
+ const top = scroller === null ? window.scrollY : scroller.scrollTop;
+ const at = performance.now();
+ const before = scroller === null ? windowMotion : scrollerMotion.get(scroller);
+ const elapsed = before === undefined ? 0 : at - before.at;
+ const flying =
+ before !== undefined
+ && elapsed > 0
+ && viewportHeight > 0
+ && (Math.abs(top - before.top) / elapsed) * 1000
+ > viewportHeight * FLYING_VIEWPORTS_PER_SECOND;
+ if (scroller === null) {
+ windowMotion.top = top;
+ windowMotion.at = at;
+ } else {
+ scrollerMotion.set(scroller, { top, at });
+ }
+ frameFlying.set(scroller, flying);
+ if (flying) frameSettle = true;
+ return flying;
+};
/*
- * A print puts the whole document on the page, so the whole fence is coloured;
+ * A print puts every line on the page.
* `upgradeEverythingForPrint` makes the same argument for a deferred fence.
*
* This one REVERTS where the latch does not: the tokens are already in `fence.lines`, so
@@ -746,14 +980,61 @@ let windowWatched = false;
*/
let printing = false;
+type PrintTokenizer = { chars: number; tokenizeNow: () => boolean };
+const awaitingWorker = new Set<PrintTokenizer>();
+const PRINT_TOKENIZE_CHARS = 10 * MAX_HIGHLIGHT_CHARS;
+
+export const awaitWorker = (
+ chars: number,
+ tokenizeNow: () => boolean,
+): (() => void) => {
+ const entry: PrintTokenizer = { chars, tokenizeNow };
+ awaitingWorker.add(entry);
+ return () => {
+ awaitingWorker.delete(entry);
+ };
+};
+
+const tokenizeForPrint = (): void => {
+ if (awaitingWorker.size === 0) return;
+ const pending = [...awaitingWorker];
+ const order = planPrintTokenization(
+ pending.map((entry) => entry.chars),
+ PRINT_TOKENIZE_CHARS,
+ );
+ flushSync(() => {
+ for (const index of order) pending[index].tokenizeNow();
+ });
+};
+
const remeasureWindows = (): void => {
windowFrame = 0;
- for (const measure of windowedFences) measure();
+ forgetScrollable();
+ frameRects = new Map();
+ frameFlying = new Map();
+ frameSelection = { read: false, value: null };
+ frameSettle = false;
+ heldLastFrame = false;
+ try {
+ for (const measure of windowedFences) measure();
+ } finally {
+ frameRects = null;
+ frameFlying = null;
+ frameSelection = null;
+ }
+ if (frameSettle && windowedFences.size > 0 && !printing) {
+ windowFrame = requestAnimationFrame(remeasureWindows);
+ }
};
-/** Is a print in progress? While it is, every fence renders every line highlighted. */
export const fencePrinting = (): boolean => printing;
+const FIND_BAR_FLAG = "data-find-bar-open";
+
+const findBarOpen = (): boolean =>
+ typeof document !== "undefined"
+ && document.documentElement.hasAttribute(FIND_BAR_FLAG);
+
/*
* 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.
@@ -768,6 +1049,7 @@ const setPrinting = (value: boolean): void => {
cancelAnimationFrame(windowFrame);
windowFrame = 0;
}
+ if (value) tokenizeForPrint();
if (windowedFences.size === 0) return;
flushSync(remeasureWindows);
};
@@ -777,6 +1059,25 @@ const scheduleRemeasure = (): void => {
windowFrame = requestAnimationFrame(remeasureWindows);
};
+const onPointerDown = (event: PointerEvent): void => {
+ if (event.pointerType === "touch" || event.button !== 0) return;
+ pointerHeld = event.target instanceof Node ? event.target : null;
+};
+
+const releasePointer = (): void => {
+ if (pointerHeld === null) return;
+ pointerHeld = null;
+ if (heldLastFrame) scheduleRemeasure();
+};
+
+const onPointerMove = (event: PointerEvent): void => {
+ if (pointerHeld !== null && event.buttons === 0) releasePointer();
+};
+
+const onSelectionChange = (): void => {
+ if (heldLastFrame) scheduleRemeasure();
+};
+
const watchWindows = (): void => {
if (windowWatched || typeof document === "undefined") return;
windowWatched = true;
@@ -787,6 +1088,39 @@ const watchWindows = (): void => {
passive: true,
});
window.addEventListener("resize", scheduleRemeasure, { passive: true });
+ document.addEventListener("pointerdown", onPointerDown, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("pointerup", releasePointer, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("pointercancel", releasePointer, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("dragend", releasePointer, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("drop", releasePointer, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("pointermove", onPointerMove, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener("blur", releasePointer);
+ document.addEventListener("selectionchange", onSelectionChange, {
+ passive: true,
+ });
+ findBarObserver = new MutationObserver(scheduleRemeasure);
+ findBarObserver.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: [FIND_BAR_FLAG],
+ });
};
const unwatchWindows = (): void => {
@@ -796,6 +1130,18 @@ const unwatchWindows = (): void => {
windowWatched = false;
document.removeEventListener("scroll", scheduleRemeasure, { capture: true });
window.removeEventListener("resize", scheduleRemeasure);
+ document.removeEventListener("pointerdown", onPointerDown, { capture: true });
+ window.removeEventListener("pointerup", releasePointer, { capture: true });
+ window.removeEventListener("pointercancel", releasePointer, { capture: true });
+ window.removeEventListener("dragend", releasePointer, { capture: true });
+ window.removeEventListener("drop", releasePointer, { capture: true });
+ window.removeEventListener("pointermove", onPointerMove, { capture: true });
+ window.removeEventListener("blur", releasePointer);
+ document.removeEventListener("selectionchange", onSelectionChange);
+ findBarObserver?.disconnect();
+ findBarObserver = null;
+ pointerHeld = null;
+ heldLastFrame = false;
if (windowFrame !== 0) {
cancelAnimationFrame(windowFrame);
windowFrame = 0;
@@ -808,107 +1154,249 @@ const unwatchWindows = (): void => {
* The geometry is read here and the decision is made in `code-fence-window.ts`, which is a
* JSX-free module so that a test can RUN the arithmetic rather than regex this file.
*/
+type LineWindowState =
+ | { measured: false }
+ | { measured: true; window: LineWindow | null; pins: LinePins | null };
+
+const UNMEASURED: LineWindowState = { measured: false };
+
+type FenceMetrics = {
+ lineHeight: number;
+ contentInset: number;
+ insets: number;
+};
+
+type FenceGeometry = FenceMetrics & {
+ scroller: HTMLElement | null;
+};
+
+const linePitches = new Map<string, number>();
+const PITCH_PROBE_LINES = 64;
+let intrinsicScale = 0;
+if (typeof window !== "undefined") {
+ window.addEventListener("resize", () => {
+ intrinsicScale = 0;
+ });
+}
+const intrinsicSizeSupported =
+ typeof CSS !== "undefined"
+ && typeof CSS.supports === "function"
+ && CSS.supports("contain-intrinsic-size", "0 1000px");
+
+const measureIntrinsicScale = (beside: HTMLElement): number => {
+ if (!intrinsicSizeSupported) return 1;
+ if (intrinsicScale > 0) return intrinsicScale;
+ const probe = document.createElement("div");
+ probe.setAttribute("aria-hidden", "true");
+ probe.style.cssText =
+ "position:absolute;visibility:hidden;pointer-events:none;top:0;left:0;width:0;contain:size;contain-intrinsic-size:0 1000px";
+ beside.before(probe);
+ const height = probe.getBoundingClientRect().height;
+ probe.remove();
+ if (!(height > 0)) return 1;
+ intrinsicScale = Math.round(1000000 / height) / 1000;
+ return intrinsicScale;
+};
+
+const measureLinePitch = (beside: HTMLElement): number => {
+ const parent = beside.parentElement;
+ if (!parent) return 0;
+ const context = getComputedStyle(parent);
+ const key = [
+ context.fontSize,
+ context.lineHeight,
+ getComputedStyle(document.documentElement).getPropertyValue("--custom-code-font-size"),
+ window.devicePixelRatio,
+ measureIntrinsicScale(beside),
+ ].join("|");
+ const known = linePitches.get(key);
+ if (known !== undefined) return known;
+ const probe = document.createElement("pre");
+ probe.setAttribute("aria-hidden", "true");
+ probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;top:0;left:0";
+ const code = document.createElement("code");
+ const lines: HTMLElement[] = [];
+ for (let index = 0; index < PITCH_PROBE_LINES; index += 1) {
+ const line = document.createElement("span");
+ line.className = LINE_CLASS;
+ line.textContent = "x";
+ lines.push(line);
+ }
+ code.append(...lines);
+ probe.append(code);
+ beside.before(probe);
+ const pitch =
+ (lines[PITCH_PROBE_LINES - 1].getBoundingClientRect().top - lines[0].getBoundingClientRect().top)
+ / (PITCH_PROBE_LINES - 1);
+ probe.remove();
+ if (pitch > 0) linePitches.set(key, pitch);
+ return pitch;
+};
+
+const readFenceMetrics = (
+ node: HTMLElement,
+ surface: HTMLElement,
+ region: HTMLElement,
+ lineCount: number,
+ previous: FenceMetrics | null,
+): FenceMetrics => {
+ const style = getComputedStyle(surface);
+ const pitch = measureLinePitch(region);
+ const declared = Number.parseFloat(style.lineHeight);
+ const lineHeight =
+ pitch > 0
+ ? pitch
+ : declared > 0
+ ? style.lineHeight.endsWith("px")
+ ? declared
+ : declared * (Number.parseFloat(style.fontSize) || 0)
+ : previous?.lineHeight
+ ?? (lineCount > 0 ? node.getBoundingClientRect().height / lineCount : 0);
+ return {
+ lineHeight,
+ contentInset:
+ (Number.parseFloat(style.borderTopWidth) || 0)
+ + (Number.parseFloat(style.paddingTop) || 0),
+ insets: Math.max(0, surface.getBoundingClientRect().height - lineCount * lineHeight),
+ };
+};
+
+const readFenceGeometry = (
+ node: HTMLElement,
+ surface: HTMLElement,
+ region: HTMLElement,
+ outer: HTMLElement,
+ lineCount: number,
+): FenceGeometry => {
+ const scroller = scrollerOf(outer);
+ return { scroller, ...readFenceMetrics(node, surface, region, lineCount, null) };
+};
+
+const skippedByContainment = (element: HTMLElement): boolean =>
+ typeof element.checkVisibility === "function"
+ && !element.checkVisibility({ contentVisibilityAuto: true });
+
+const FAR_VIEWPORTS = OVERSCAN_VIEWPORTS + HYSTERESIS_VIEWPORTS + 1;
+const RESIZE_SETTLE_MS = 300;
+
function useLineWindow(
code: RefObject<HTMLElement | null>,
- /*
- * The fence's outermost element, and the ONLY thing it is used for is finding the scrolling
- * ancestor. `scrollerOf` starts at `parentElement` and tests `overflow-y`, and a code block
- * carries `overflow-x: auto`, which makes `overflow-y` compute to `auto` as well
- * (css-overflow-3: a non-visible value on one axis forces the other off `visible`). Walking up
- * from the `<code>` would therefore be one `scrollHeight` away from rooting the whole window
- * calculation inside the fence's own horizontal scroller. Starting outside the block skips
- * both of them, and it is the element the reach latch already measures against.
- */
+ surface: RefObject<HTMLElement | null>,
+ wrapper: RefObject<HTMLElement | null>,
frame: RefObject<HTMLElement | null>,
lineCount: number,
enabled: boolean,
-): LineWindow | null {
- const [lineWindow, setLineWindow] = useState<LineWindow | null>(null);
- // The rendered window, read by `measure` without making it an effect dependency: the effect
- // registers a listener, and rebuilding that on every window move would defeat the coalescing.
+ deferShifts: boolean,
+): { window: LineWindow | null; pins: LinePins | null; measured: boolean } {
+ const [state, setState] = useState<LineWindowState>(UNMEASURED);
+ const viewportSize = useRef("");
+ const resizedAt = useRef(Number.NEGATIVE_INFINITY);
const current = useRef<LineWindow | null>(null);
+ const pinned = useRef<LinePins | null>(null);
+ const geometry = useRef<FenceGeometry | null>(null);
+ const metricsStale = useRef(false);
const lines = useRef(lineCount);
lines.current = lineCount;
const hasBody = lineCount > 0;
+ const overCap = lineCount > WINDOW_CAP_LINES;
const measure = useRef<() => void>(() => {});
measure.current = () => {
const node = code.current;
const outer = frame.current;
- if (!node || !outer) return;
- // Under the cap a window can never apply, so no layout read is needed. A streaming fence that
- // grows past the cap re-registers through the ResizeObserver.
+ const body = surface.current;
+ const region = wrapper.current;
+ if (!node || !outer || !body || !region) return;
if (lines.current <= WINDOW_CAP_LINES && current.current === null) return;
- // See `setPrinting`: the whole document is on the page, so the whole fence is coloured.
- if (printing) {
- if (current.current === null) return;
+ if (printing || findBarOpen()) {
+ if (current.current === null && pinned.current === null) return;
current.current = null;
- setLineWindow(null);
+ pinned.current = null;
+ setState({ measured: true, window: null, pins: null });
+ return;
+ }
+ let known = geometry.current;
+ if (
+ known === null
+ || (known.scroller !== null && !isScrollable(known.scroller))
+ ) {
+ if (skippedByContainment(body)) return;
+ known = readFenceGeometry(node, body, region, outer, lines.current);
+ metricsStale.current = false;
+ } else if (metricsStale.current && !skippedByContainment(body)) {
+ known = {
+ scroller: known.scroller,
+ ...readFenceMetrics(node, body, region, lines.current, known),
+ };
+ metricsStale.current = false;
+ }
+ geometry.current = known;
+ const height =
+ Math.round(
+ (lines.current * known.lineHeight + known.insets) * measureIntrinsicScale(region) * 1000,
+ ) / 1000;
+ const declared = `${height}px`;
+ if (region.style.getPropertyValue(FENCE_HEIGHT_PROPERTY) !== declared) {
+ region.style.setProperty(FENCE_HEIGHT_PROPERTY, declared);
+ forgetScrollable();
+ }
+ const bounds = known.scroller === null ? null : rectDuringFrame(known.scroller);
+ const viewportTop = bounds ? bounds.top : 0;
+ const viewportHeight = bounds ? bounds.height : window.innerHeight;
+ const size = `${bounds ? bounds.width : window.innerWidth}x${viewportHeight}`;
+ if (size !== viewportSize.current) resizedAt.current = performance.now();
+ viewportSize.current = size;
+ const resized = performance.now() - resizedAt.current < RESIZE_SETTLE_MS;
+ const box = rectDuringFrame(region);
+ const reach = viewportHeight * FAR_VIEWPORTS;
+ if (
+ current.current !== null
+ && (box.bottom < viewportTop - reach || box.top > viewportTop + viewportHeight + reach)
+ ) {
return;
}
- const scroller = scrollerOf(outer);
- const bounds = scroller?.getBoundingClientRect();
- const rect = node.getBoundingClientRect();
- const count = lines.current;
+ if (current.current !== null && flyingDuringFrame(known.scroller, viewportHeight)) return;
+ if (current.current !== null && draggingDuringFrame(body)) return;
const next = selectLineWindow({
- lineCount: count,
- // MEASURED, never assumed. `index.css` pins `line-height: 1.55` on the code block, but the
- // font size is a `--ui-font-scale` multiple inside a container query, so the pixel height is
- // not knowable from here. Every line is rendered, so the mean IS the line height.
- lineHeight: count > 0 ? rect.height / count : 0,
- contentTop: rect.top,
- viewportTop: bounds ? bounds.top : 0,
- viewportHeight: bounds ? bounds.height : window.innerHeight,
+ lineCount: lines.current,
+ lineHeight: known.lineHeight,
+ contentTop: box.top + known.contentInset,
+ viewportTop,
+ viewportHeight,
previous: current.current,
});
- // `selectLineWindow` hands the previous object straight back when nothing moved, so this is an
- // identity check and an ordinary scroll costs no render at all.
- if (next === current.current) return;
+ const pins = pinBoundaryLines(
+ selectionBoundaryLines(node, body),
+ current.current,
+ pinned.current,
+ );
+ if (next === current.current && samePins(pins, pinned.current)) return;
+ const shifting =
+ deferShifts && current.current !== null && frameRects !== null && !resized;
current.current = next;
- setLineWindow(next);
+ pinned.current = pins;
+ const update = { measured: true, window: next, pins };
+ if (shifting) startTransition(() => setState(update));
+ else setState(update);
};
- /*
- * IN A LAYOUT EFFECT, AND KEYED ON THE BODY EXISTING.
- * Two things go wrong with a passive effect keyed on `enabled` alone, and the browser probe
- * caught both. A fence renders the plain shell until its grammar chunk lands, so at mount there
- * is no `<code>` to measure and no element for the ResizeObserver to watch; keyed only on
- * `enabled` the effect never runs again once the tokens arrive, and the window stayed off until
- * the reader happened to scroll (measured: 30,861 spans still mounted). And a passive effect
- * lands after the paint, so the frame that introduces a 20,000 line fence paints every span in
- * it before the window takes them away. Layout effects run after mutation and before paint, so
- * the first painted frame is already windowed.
- */
useLayoutEffect(() => {
if (!enabled) {
current.current = null;
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setLineWindow(null);
+ geometry.current = null;
return;
}
const run = () => measure.current();
windowedFences.add(run);
watchWindows();
run();
- /*
- * The fence's own growth moves nothing the scroll listener would notice: a streamed line
- * lands below the viewport and the reader has not moved. A ResizeObserver on the code
- * element is what sees it, and it also covers the font finishing loading, the thread column
- * changing width, and the reasoning pane expanding.
- */
- /*
- * OBSERVED ON THE WRAPPER, NOT ON THE `<code>`.
- * A `<code>` is `display: inline`, and ResizeObserver does not observe an element with no
- * principal box: the callback simply never fires. Measured, not read off the spec -- with the
- * observer on the `<code>` a fence streamed past 3,000 lines and 23,139 spans and the window
- * never once engaged, because the only thing that ever called `measure` was the one call this
- * effect makes, back when the fence was one line long. The wrapper is a flex container, it
- * grows by exactly what the code grows by, and it is already resolved here.
- */
let resize: ResizeObserver | undefined;
const box = frame.current;
if (box && typeof ResizeObserver !== "undefined") {
- resize = new ResizeObserver(scheduleRemeasure);
+ resize = new ResizeObserver(() => {
+ metricsStale.current = true;
+ scheduleRemeasure();
+ });
resize.observe(box);
}
return () => {
@@ -916,14 +1404,21 @@ function useLineWindow(
windowedFences.delete(run);
unwatchWindows();
};
- // `hasBody` and not `lineCount`: the count changes on every streamed line and re-registering
- // per line would throw away the coalescing this exists for. The transition that matters is the
- // shell becoming a real body, and it happens once.
- }, [enabled, hasBody, code, frame]);
+ }, [enabled, hasBody, code, surface, wrapper, frame]);
- return enabled ? lineWindow : null;
+ useLayoutEffect(() => {
+ if (!enabled || !overCap || state.measured) return;
+ measure.current();
+ }, [enabled, overCap, state.measured]);
+
+ if (!enabled) return NO_WINDOW;
+ if (state.measured) return state;
+ return overCap && !printing && !findBarOpen() ? EMPTY_WINDOW : NO_WINDOW;
}
+const NO_WINDOW = { window: null, pins: null, measured: false } as const;
+const EMPTY_WINDOW = { window: EMPTY_LINE_WINDOW, pins: null, measured: false } as const;
+
/**
* A fence's body, highlighted, with the spans bounded to what is on screen.
*
@@ -948,9 +1443,19 @@ export const FenceBody = memo(function FenceBody({
windowing: boolean;
}) {
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 tokens = result?.tokens ?? null;
- const lineWindow = useLineWindow(code, frame, tokens?.length ?? 0, windowing);
+ const { window: lineWindow, pins, measured } = useLineWindow(
+ code,
+ surface,
+ wrapper,
+ frame,
+ tokens?.length ?? 0,
+ windowing,
+ !isIncomplete,
+ );
const languageClass = language === null ? null : `language-${language}`;
const rootStyle = useMemo(() => {
@@ -989,25 +1494,30 @@ export const FenceBody = memo(function FenceBody({
<span className="ml-1 font-mono lowercase">{language}</span>
</div>
<div
- className={joinClasses(
- languageClass,
- "overflow-x-auto rounded-md border border-border bg-background p-4 text-sm",
- )}
- data-language={language ?? undefined}
- data-streamdown="code-block-body"
- data-unsloth-fence-windowed={lineWindow === null ? undefined : "true"}
+ data-unsloth-fence-windowed={lineWindow === null || !measured ? undefined : "true"}
+ ref={wrapper}
>
- <pre className={joinClasses(languageClass, PRE_CLASS)} style={rootStyle}>
- <code className={CODE_CLASS} ref={code}>
- {tokens.map((line, index) => (
- <FenceLine
- key={index}
- line={line}
- windowed={lineIsWindowed(lineWindow, index)}
- />
- ))}
- </code>
- </pre>
+ <div
+ className={joinClasses(
+ languageClass,
+ "overflow-x-auto rounded-md border border-border bg-background p-4 text-sm",
+ )}
+ data-language={language ?? undefined}
+ data-streamdown="code-block-body"
+ ref={surface}
+ >
+ <pre className={joinClasses(languageClass, PRE_CLASS)} style={rootStyle}>
+ <code className={CODE_CLASS} ref={code}>
+ {tokens.map((line, index) => (
+ <FenceLine
+ key={index}
+ line={line}
+ windowed={lineRendered(lineWindow, pins, index)}
+ />
+ ))}
+ </code>
+ </pre>
+ </div>
</div>
</div>
);
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts b/studio/frontend/src/components/assistant-ui/code-fence-mode.ts
index f47a577093e..d7a740c15d0 100644
--- a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts
+++ b/studio/frontend/src/components/assistant-ui/code-fence-mode.ts
@@ -7,12 +7,11 @@
* `node --experimental-strip-types`, which cannot load JSX. Every row below is RUN by
* `tests/code-fence-mode.test.ts` rather than checked by regexes over the source.
* "off" every fence is highlighted at mount. What shipped before `defer` became default.
- * "defer" SHIP DEFAULT. An unreached fence is a plain shell and is never tokenized.
+ * "defer" An unreached fence is a plain shell and is never tokenized.
* "tokenize" MEASUREMENT ONLY. Same plain shell, but the highlighter is still driven over the
* source and the result thrown away.
* "window" "defer", plus a LINE WINDOW inside a fence past `WINDOW_CAP_LINES`: off-screen
- * lines render their text as one node instead of their token spans. Not yet the
- * ship default, because the ladder that would justify moving it has not been run.
+ * lines render their text as one node instead of their token spans. SHIP DEFAULT.
* It is a superset of "defer": under the cap the two render the same DOM, so an
* A/B between them isolates the window and nothing else.
* `tokenize` is not a shipping mode. `defer` removes the spans AND the tokenizer work that makes
@@ -25,7 +24,7 @@
export type FenceMode = "off" | "defer" | "tokenize" | "window";
/** Moving this line is the whole of "turn deferral on by default"; every override still works. */
-export const SHIP_DEFAULT: FenceMode = "defer";
+export const SHIP_DEFAULT: FenceMode = "window";
/**
* AN UNSET FLAG AND AN UNRECOGNISED ONE DO NOT RESOLVE TO THE SAME MODE. Unset means an install
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-print.ts b/studio/frontend/src/components/assistant-ui/code-fence-print.ts
new file mode 100644
index 00000000000..013997b8f24
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/code-fence-print.ts
@@ -0,0 +1,19 @@
+// 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 planPrintTokenization = (
+ sizes: readonly number[],
+ budget: number,
+): number[] => {
+ const order = sizes
+ .map((_, index) => index)
+ .sort((a, b) => sizes[a] - sizes[b]);
+ const planned: number[] = [];
+ let left = budget;
+ for (const index of order) {
+ if (sizes[index] > left) break;
+ left -= sizes[index];
+ planned.push(index);
+ }
+ return planned;
+};
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-window.ts b/studio/frontend/src/components/assistant-ui/code-fence-window.ts
index 09a89622fc2..bc45bf9f157 100644
--- a/studio/frontend/src/components/assistant-ui/code-fence-window.ts
+++ b/studio/frontend/src/components/assistant-ui/code-fence-window.ts
@@ -17,10 +17,12 @@
/** An inclusive line range. `null` means "no window": every line renders its token spans. */
export type LineWindow = { first: number; last: number };
+export const EMPTY_LINE_WINDOW: LineWindow = { first: -1, last: -1 };
+
// Below the cap a fence is highlighted end to end and produces main's DOM byte for byte; the
// mechanism exists for the 140K-character fence in #10769. Lines, not characters: the bounded cost
// is mounted elements, which track lines.
-export const WINDOW_CAP_LINES = 2_000;
+export const WINDOW_CAP_LINES = 240;
// Viewports of lookahead each way, matching `REACH_MARGIN`: the reader crosses into already
// coloured code rather than watching it arrive.
@@ -81,6 +83,7 @@ export const selectLineWindow = (geometry: WindowGeometry): LineWindow | null =>
const previous = geometry.previous;
if (
previous !== null
+ && previous !== EMPTY_LINE_WINDOW
&& previous.first <= Math.max(0, visible.first - slack)
&& previous.last >= Math.min(lineCount - 1, visible.last + slack)
) {
@@ -108,6 +111,38 @@ export const selectLineWindow = (geometry: WindowGeometry): LineWindow | null =>
export const lineIsWindowed = (window: LineWindow | null, index: number): boolean =>
window === null || (index >= window.first && index <= window.last);
+export type LinePin = { readonly index: number; readonly windowed: boolean };
+export type LinePins = readonly LinePin[];
+
+const pinOf = (pins: LinePins | null, index: number): boolean | undefined => {
+ if (pins === null) return undefined;
+ for (const pin of pins) if (pin.index === index) return pin.windowed;
+ return undefined;
+};
+
+export const lineRendered = (
+ window: LineWindow | null,
+ pins: LinePins | null,
+ index: number,
+): boolean => pinOf(pins, index) ?? lineIsWindowed(window, index);
+
+export const samePins = (a: LinePins | null, b: LinePins | null): boolean => {
+ if (a === b) return true;
+ if (a === null || b === null || a.length !== b.length) return false;
+ return a.every((pin, at) => pin.index === b[at].index && pin.windowed === b[at].windowed);
+};
+
+export const pinBoundaryLines = (
+ boundaries: readonly number[],
+ window: LineWindow | null,
+ previous: LinePins | null,
+): LinePins | null => {
+ const pins: LinePin[] = [];
+ for (const index of [...new Set(boundaries)].sort((x, y) => x - y))
+ pins.push({ index, windowed: pinOf(previous, index) ?? lineIsWindowed(window, index) });
+ return pins.length === 0 ? null : pins;
+};
+
// Structurally typed rather than importing Shiki's `ThemedToken`, so a bundler-less test runner
// can load this module.
type LineToken = { content: string };
diff --git a/studio/frontend/src/components/assistant-ui/code-highlight-context.ts b/studio/frontend/src/components/assistant-ui/code-highlight-context.ts
new file mode 100644
index 00000000000..3d26d70f508
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/code-highlight-context.ts
@@ -0,0 +1,10 @@
+// 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 { createContext } from "react";
+
+// "all": answers, coloured on the main thread while they grow. "settled": thinking traces,
+// coloured on the worker (a growing fence only while on screen).
+export type CodeHighlightMode = "all" | "settled";
+
+export const CodeHighlightModeContext = createContext<CodeHighlightMode>("all");
diff --git a/studio/frontend/src/components/assistant-ui/code-plugin.ts b/studio/frontend/src/components/assistant-ui/code-plugin.ts
index dc53cf81d78..501dde01938 100644
--- a/studio/frontend/src/components/assistant-ui/code-plugin.ts
+++ b/studio/frontend/src/components/assistant-ui/code-plugin.ts
@@ -16,7 +16,10 @@ import {
type GrammarState,
type ThemedToken,
} from "shiki";
-import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+import {
+ createJavaScriptRegexEngine,
+ defaultJavaScriptRegexConstructor,
+} from "shiki/engine/javascript";
// Common fence tags shiki doesn't expose as aliases.
// Keys: lower-cased input; values: canonical shiki language ids.
@@ -77,6 +80,7 @@ export const normalizeLanguage = (language: string): BundledLanguage => {
// state so each refresh tokenizes only new text, keeping the 250 ms plain-tail cadence.
export const MIN_INCREMENTAL_CHARS = 2000;
const REFRESH_MS = 250;
+const REFRESH_SLICE_MS = 8;
// Shiki's own tokenizer guard is a wall clock: a line that takes longer than `tokenizeTimeLimit`
// (default 500 ms) is abandoned part-way and the rest of it is emitted as one uncoloured token.
// Dual themes are two passes with two separate budgets, and only the first pays to compile the
@@ -92,8 +96,8 @@ export const TOKENIZE_LIMITS = {
} as const;
// An unvirtualized thread mounts every fence. Bound both their count and source
// size; token data measured roughly 30 bytes per source character.
-const MAX_FENCES = 512;
-const MAX_CACHED_CHARACTERS = 512_000;
+export const MAX_FENCES = 512;
+export const MAX_CACHED_CHARACTERS = 512_000;
// Wall-clock Date.now() can step backwards (NTP, sleep resume) and make
// `elapsed` negative; the throttle only needs elapsed time, so stay monotonic.
@@ -123,6 +127,7 @@ type Fence = {
lastTokenizedAt: number;
trailing: ReturnType<typeof setTimeout> | null;
pending: Pending | null;
+ seeded: boolean;
};
// Tokens without colors preserve the previous plain-tail rendering.
@@ -199,14 +204,58 @@ const shedsClosingRun = (shorter: string, longer: string): boolean =>
longer.startsWith(shorter) &&
CLOSING_FENCE.test(longer.slice(shorter.length));
+export type FenceCover = {
+ uncovered: number;
+ result: HighlightResult | null;
+};
+
+export type UnslothCodePlugin = CodeHighlighterPlugin & {
+ cached: (opts: HighlightOptions) => HighlightResult | null;
+ cover: (opts: HighlightOptions) => FenceCover;
+ seed: (opts: HighlightOptions, result: HighlightResult) => void;
+ highlight: (
+ opts: HighlightOptions,
+ callback?: (result: HighlightResult) => void,
+ exact?: boolean,
+ ) => HighlightResult | null;
+ highlightExact: (
+ opts: HighlightOptions,
+ callback?: (result: HighlightResult) => void,
+ ) => HighlightResult | null;
+};
+
+const fenceKeyOf = (opts: HighlightOptions): string =>
+ `${normalizeLanguage(opts.language)} ${themeKey(opts.themes[0])} ${themeKey(opts.themes[1])}`;
+
+const javaScriptCore =
+ typeof navigator !== "undefined"
+ && navigator.userAgent.includes("AppleWebKit/")
+ && !/Chrom(?:e|ium)\//.test(navigator.userAgent);
+
export function createCodePlugin(
options: CodePluginOptions = {},
-): CodeHighlighterPlugin {
+): UnslothCodePlugin {
const defaultThemes: [ThemeInput, ThemeInput] = options.themes ?? [
"github-light",
"github-dark",
];
- const engine = createJavaScriptRegexEngine({ forgiving: true });
+ const engine = createJavaScriptRegexEngine(
+ javaScriptCore
+ ? {
+ forgiving: true,
+ regexConstructor: (pattern) => {
+ try {
+ return defaultJavaScriptRegexConstructor(pattern, {
+ target: "ES2018",
+ accuracy: "strict",
+ });
+ } catch {
+ return defaultJavaScriptRegexConstructor(pattern);
+ }
+ },
+ }
+ : { forgiving: true },
+ );
const highlighters = new Map<string, { highlighter: Highlighter | null }>();
// Most recently used first.
const fences: Fence[] = [];
@@ -272,6 +321,20 @@ export function createCodePlugin(
}
};
+ const forkFence = (fence: Fence): Fence => {
+ const fork: Fence = {
+ ...fence,
+ lines: [...fence.lines],
+ liveTokens: null,
+ trailing: null,
+ pending: null,
+ seeded: false,
+ };
+ fences.unshift(fork);
+ cachedCharacters += fence.code.length;
+ return fork;
+ };
+
const promote = (fence: Fence): Fence => {
const index = fences.indexOf(fence);
if (index > 0) {
@@ -281,6 +344,16 @@ export function createCodePlugin(
return fence;
};
+ const reachInto = (fence: Fence, code: string): number => {
+ if (fence.result === null || fence.seeded) return -1;
+ const anchor = fence.code;
+ // Lost more than its closing delimiter: a different fence, so do not share the entry.
+ const reaches =
+ code.startsWith(anchor) ||
+ (code.length >= fence.committedLength && shedsClosingRun(code, anchor));
+ return anchor && reaches ? Math.min(anchor.length, code.length) : -1;
+ };
+
/** The fence whose cached code reaches furthest into `code`. */
const findFence = (key: string, code: string): Fence => {
const exact = fencesByCode.get(codeKey(key, code));
@@ -294,14 +367,8 @@ export function createCodePlugin(
if (fence.pending?.code === code) return promote(fence);
continue;
}
- const anchor = fence.code;
- // A block that lost more than its closing delimiter is a different fence;
- // sharing this entry would cancel the refresh it has queued.
- const reaches =
- code.startsWith(anchor) ||
- (code.length >= fence.committedLength && shedsClosingRun(code, anchor));
- const reach = Math.min(anchor.length, code.length);
- if (!anchor || reach <= matchLength || !reaches) continue;
+ const reach = reachInto(fence, code);
+ if (reach <= matchLength) continue;
match = fence;
matchLength = reach;
}
@@ -318,6 +385,7 @@ export function createCodePlugin(
lastTokenizedAt: 0,
trailing: null,
pending: null,
+ seeded: false,
};
fences.unshift(fence);
return fence;
@@ -330,6 +398,7 @@ export function createCodePlugin(
code: string,
language: BundledLanguage,
themes: ThemeNames,
+ budgetMs: number,
): HighlightResult => {
const lang = highlighter.getLoadedLanguages().includes(language)
? language
@@ -344,6 +413,34 @@ export function createCodePlugin(
// Commit every newly completed line.
const lastNewline = code.lastIndexOf("\n");
+ if (lastNewline >= fence.committedLength && budgetMs < Number.POSITIVE_INFINITY) {
+ const deadline = monotonicNow() + budgetMs;
+ while (fence.committedLength <= lastNewline) {
+ const newline = code.indexOf("\n", fence.committedLength);
+ const end =
+ newline > fence.committedLength && code[newline - 1] === "\r"
+ ? newline - 1
+ : newline;
+ const completed = tokenizeFrom(code.slice(fence.committedLength, end));
+ for (const line of completed.tokens) {
+ fence.lines.push(shiftLine(line, fence.committedLength));
+ }
+ fence.state = completed.grammarState;
+ fence.committedLength = newline + 1;
+ fence.liveTokens = null;
+ fence.meta = stripTokens(completed);
+ if (monotonicNow() >= deadline) break;
+ }
+ if (fence.committedLength <= lastNewline) {
+ fence.lastTokenizedAt = monotonicNow();
+ const tail = code.slice(fence.committedLength).split("\n");
+ return {
+ ...(fence.meta as ResultMeta),
+ tokens: [...fence.lines, ...tail.map(plainLine)],
+ };
+ }
+ }
+
if (lastNewline >= fence.committedLength) {
// Shiki omits CR from CRLF token content.
const completedEnd =
@@ -399,10 +496,11 @@ export function createCodePlugin(
code: string,
language: BundledLanguage,
themes: ThemeNames,
+ budgetMs = Number.POSITIVE_INFINITY,
): HighlightResult | null => {
let result: HighlightResult;
try {
- result = tokenize(fence, highlighter, code, language, themes);
+ result = tokenize(fence, highlighter, code, language, themes, budgetMs);
} catch (error) {
console.error("[Unsloth Code] Failed to highlight code:", error);
resetFence(fence);
@@ -470,9 +568,60 @@ export function createCodePlugin(
return null;
};
- return {
+ const plugin: UnslothCodePlugin = {
name: "shiki",
type: "code-highlighter",
+ cached: (opts) => {
+ const exact = fencesByCode.get(codeKey(fenceKeyOf(opts), opts.code));
+ return exact && exact.code === opts.code && exact.result
+ ? promote(exact).result
+ : null;
+ },
+ cover: (opts) => {
+ const key = fenceKeyOf(opts);
+ const exact = fencesByCode.get(codeKey(key, opts.code));
+ if (exact && exact.code === opts.code && exact.result) {
+ return { uncovered: 0, result: exact.result };
+ }
+ let match: Fence | null = null;
+ let matchLength = -1;
+ for (const fence of fences) {
+ if (fence.key !== key) continue;
+ const reach = reachInto(fence, opts.code);
+ if (reach <= matchLength) continue;
+ match = fence;
+ matchLength = reach;
+ }
+ if (match === null) return { uncovered: opts.code.length, result: null };
+ return {
+ uncovered:
+ opts.code.length - Math.min(match.committedLength, opts.code.length),
+ result: approximateResult(match, opts.code),
+ };
+ },
+ seed: (opts, result) => {
+ const key = fenceKeyOf(opts);
+ const exact = fencesByCode.get(codeKey(key, opts.code));
+ if (exact && exact.code === opts.code && exact.result) return;
+ const fence: Fence = {
+ key,
+ code: opts.code,
+ result,
+ meta: stripTokens(result),
+ lines: result.tokens,
+ committedLength: opts.code.length,
+ state: undefined,
+ liveTokens: null,
+ lastTokenizedAt: monotonicNow(),
+ trailing: null,
+ pending: null,
+ seeded: true,
+ };
+ fences.unshift(fence);
+ cachedCharacters += opts.code.length;
+ fencesByCode.set(codeKey(key, opts.code), fence);
+ evict();
+ },
getSupportedLanguages: () => SUPPORTED_LANGUAGE_LIST,
getThemes: () => defaultThemes,
supportsLanguage: (language) =>
@@ -480,6 +629,7 @@ export function createCodePlugin(
highlight: (
opts: HighlightOptions,
callback?: (result: HighlightResult) => void,
+ exact = false,
): HighlightResult | null => {
const language = normalizeLanguage(opts.language);
const themes: ThemeNames = {
@@ -489,7 +639,8 @@ export function createCodePlugin(
const key = `${language} ${themeKey(opts.themes[0])} ${themeKey(opts.themes[1])}`;
const fence = findFence(key, opts.code);
- if (fence.result && fence.code === opts.code) {
+ const partial = fence.committedLength <= fence.code.lastIndexOf("\n");
+ if (fence.result && fence.code === opts.code && !(exact && partial)) {
const pending = fence.pending;
if (
pending !== null &&
@@ -523,6 +674,9 @@ export function createCodePlugin(
evict();
return null;
}
+ if (exact && fence.result !== null && fence.code !== opts.code) {
+ return update(forkFence(fence), highlighter, opts.code, language, themes);
+ }
const pending = fence.pending;
if (pending && shedsClosingRun(opts.code, pending.code)) {
@@ -535,29 +689,41 @@ export function createCodePlugin(
fence.result !== null &&
fence.code.length >= MIN_INCREMENTAL_CHARS &&
opts.code.length > fence.code.length;
- if (grewLargeFence && elapsed < REFRESH_MS) {
+ if (!exact && grewLargeFence && elapsed < REFRESH_MS) {
const result = approximateResult(fence, opts.code);
queuePending(fence, opts.code, callback);
+ const refresh = (): void => {
+ const pending = fence.pending;
+ fence.trailing = null;
+ fence.pending = null;
+ if (!pending) return;
+ const refreshed = update(
+ fence,
+ highlighter,
+ pending.code,
+ language,
+ themes,
+ REFRESH_SLICE_MS,
+ );
+ if (refreshed) notifyPending(pending, refreshed);
+ if (
+ refreshed
+ && fence.code === pending.code
+ && fence.committedLength <= pending.code.lastIndexOf("\n")
+ ) {
+ fence.pending = pending;
+ fence.trailing = setTimeout(refresh, 0);
+ }
+ };
fence.trailing = setTimeout(
- () => {
- const pending = fence.pending;
- fence.trailing = null;
- fence.pending = null;
- if (!pending) return;
- const refreshed = update(
- fence,
- highlighter,
- pending.code,
- language,
- themes,
- );
- if (refreshed) notifyPending(pending, refreshed);
- },
- Math.max(0, REFRESH_MS - elapsed),
+ refresh,
+ partial ? 0 : Math.max(0, REFRESH_MS - elapsed),
);
return result;
}
return update(fence, highlighter, opts.code, language, themes);
},
+ highlightExact: (opts, callback) => plugin.highlight(opts, callback, true),
};
+ return plugin;
}
diff --git a/studio/frontend/src/components/assistant-ui/containment-flag.ts b/studio/frontend/src/components/assistant-ui/containment-flag.ts
new file mode 100644
index 00000000000..dd541067a91
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/containment-flag.ts
@@ -0,0 +1,83 @@
+// 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 {
+ gateOnEngine,
+ isRuntimeForced,
+ type MathBlockMode,
+} from "./math-block-mode.ts";
+
+export type ContainmentMode = MathBlockMode;
+
+export type ContainmentFlag = {
+ attribute: string;
+ on: string;
+ global: string;
+ shipDefault: ContainmentMode;
+ resolve: (runtime: unknown, build: string) => ContainmentMode;
+ mode: (
+ runtime: unknown,
+ build: string,
+ engineFindsSkippedContent: boolean,
+ ) => ContainmentMode;
+ installWatcher: (
+ scope: Record<string, unknown>,
+ apply: () => ContainmentMode,
+ ) => boolean;
+};
+
+export function defineContainmentFlag({
+ attribute,
+ global,
+ shipDefault = "contain",
+}: {
+ attribute: string;
+ global: string;
+ shipDefault?: ContainmentMode;
+}): ContainmentFlag {
+ const resolve = (runtime: unknown, build: string): ContainmentMode => {
+ const raw =
+ typeof runtime === "string"
+ ? runtime
+ : runtime === true
+ ? "contain"
+ : runtime === false
+ ? "off"
+ : build;
+ return raw === "1" || raw === "contain"
+ ? "contain"
+ : raw === ""
+ ? shipDefault
+ : "off";
+ };
+ return {
+ attribute,
+ on: "on",
+ global,
+ shipDefault,
+ resolve,
+ mode: (runtime, build, engineFindsSkippedContent) =>
+ gateOnEngine(
+ resolve(runtime, build),
+ engineFindsSkippedContent,
+ isRuntimeForced(runtime),
+ ),
+ installWatcher: (scope, apply) => {
+ try {
+ let held = scope[global];
+ Object.defineProperty(scope, global, {
+ configurable: true,
+ enumerable: true,
+ get: () => held,
+ set: (next: unknown) => {
+ held = next;
+ apply();
+ },
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/discrete-input.ts b/studio/frontend/src/components/assistant-ui/discrete-input.ts
new file mode 100644
index 00000000000..1abc3f3f87f
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/discrete-input.ts
@@ -0,0 +1,44 @@
+// 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 DISCRETE_INPUT_EVENTS = [
+ "keydown",
+ "pointerdown",
+ "touchstart",
+] as const;
+
+export const DISCRETE_INPUT_WINDOW_MS = 50;
+
+export function discreteInputPending(
+ lastInputAt: number,
+ now: number,
+ windowMs: number = DISCRETE_INPUT_WINDOW_MS,
+): boolean {
+ return now - lastInputAt < windowMs;
+}
+
+export type DiscreteInputTracker = {
+ pending(): boolean;
+ dispose(): void;
+};
+
+export function createDiscreteInputTracker(
+ target: EventTarget,
+ now: () => number = () => performance.now(),
+): DiscreteInputTracker {
+ let lastInputAt = Number.NEGATIVE_INFINITY;
+ const record = () => {
+ lastInputAt = now();
+ };
+ for (const type of DISCRETE_INPUT_EVENTS) {
+ target.addEventListener(type, record, { capture: true, passive: true });
+ }
+ return {
+ pending: () => discreteInputPending(lastInputAt, now()),
+ dispose: () => {
+ for (const type of DISCRETE_INPUT_EVENTS) {
+ target.removeEventListener(type, record, { capture: true });
+ }
+ },
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/fence-speculation.ts b/studio/frontend/src/components/assistant-ui/fence-speculation.ts
new file mode 100644
index 00000000000..9f248d5752b
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/fence-speculation.ts
@@ -0,0 +1,169 @@
+// 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 type SpeculationGate = {
+ chars: number;
+ speculate: (settle: (seeded: boolean) => void) => (() => void) | null;
+};
+
+export type FenceSpeculatorOptions<G extends SpeculationGate> = {
+ idle: (callback: () => void, timeout: number) => () => void;
+ wait: (callback: () => void, ms: number) => () => void;
+ enabled: () => boolean;
+ busy: () => boolean;
+ eligible: (gate: G) => boolean;
+ rank: (gates: readonly G[]) => number[];
+ maxChars: number;
+ budgetChars: number;
+ budgetFences: number;
+ maxInFlight?: number;
+ rankEvery?: number;
+};
+
+export type FenceSpeculator<G> = {
+ add: (gate: G) => void;
+ remove: (gate: G) => void;
+ rerank: () => void;
+ snapshot: () => {
+ candidates: number;
+ seeded: number;
+ seededChars: number;
+ inFlight: boolean;
+ inFlightCount: number;
+ };
+};
+
+export function createFenceSpeculator<G extends SpeculationGate>(
+ options: FenceSpeculatorOptions<G>,
+): FenceSpeculator<G> {
+ const rankEvery = options.rankEvery ?? 16;
+ const maxInFlight = Math.max(1, options.maxInFlight ?? 1);
+ const candidates = new Set<G>();
+ const seeded = new Map<G, number>();
+ let seededChars = 0;
+ let ranked: G[] | null = null;
+ let picks = 0;
+ const inFlight = new Map<G, { cancel: (() => void) | null }>();
+ let inFlightChars = 0;
+ let pending: (() => void) | null = null;
+
+ const schedule = (): void => {
+ if (pending || inFlight.size >= maxInFlight || candidates.size === 0) return;
+ pending = options.idle(run, 2000);
+ };
+
+ const order = (): G[] => {
+ if (ranked) return ranked;
+ const gates = [...candidates];
+ const distances = options.rank(gates);
+ ranked = gates
+ .map((gate, index) => ({ gate, at: distances[index] ?? Infinity }))
+ .sort((a, b) => a.at - b.at)
+ .map((entry) => entry.gate);
+ picks = 0;
+ return ranked;
+ };
+
+ const pick = (): { gate: G | null; waiting: boolean } => {
+ if (seeded.size + inFlight.size >= options.budgetFences)
+ return { gate: null, waiting: false };
+ let waiting = false;
+ for (const gate of order()) {
+ if (!candidates.has(gate)) continue;
+ if (seededChars + inFlightChars + gate.chars > options.budgetChars) continue;
+ if (!options.eligible(gate)) {
+ waiting = true;
+ continue;
+ }
+ return { gate, waiting: false };
+ }
+ return { gate: null, waiting };
+ };
+
+ const finish = (gate: G): boolean => {
+ if (!inFlight.delete(gate)) return false;
+ inFlightChars -= gate.chars;
+ return true;
+ };
+
+ const settle = (gate: G, ok: boolean): void => {
+ if (!finish(gate)) return;
+ if (ok) {
+ seeded.set(gate, gate.chars);
+ seededChars += gate.chars;
+ }
+ picks += 1;
+ if (picks >= rankEvery) ranked = null;
+ schedule();
+ };
+
+ const launch = (gate: G): void => {
+ candidates.delete(gate);
+ const job = { cancel: null as (() => void) | null };
+ inFlight.set(gate, job);
+ inFlightChars += gate.chars;
+ let cancel: (() => void) | null = null;
+ try {
+ cancel = gate.speculate((ok) => settle(gate, ok));
+ } catch {
+ settle(gate, false);
+ return;
+ }
+ if (inFlight.get(gate) === job) job.cancel = cancel;
+ };
+
+ const run = (): void => {
+ pending = null;
+ if (!options.enabled()) {
+ candidates.clear();
+ ranked = null;
+ return;
+ }
+ if (options.busy()) {
+ pending = options.wait(run, 1000);
+ return;
+ }
+ while (inFlight.size < maxInFlight) {
+ const { gate, waiting } = pick();
+ if (!gate) {
+ if (waiting && inFlight.size === 0) pending = options.wait(run, 1000);
+ return;
+ }
+ launch(gate);
+ }
+ };
+
+ return {
+ add: (gate) => {
+ if (gate.chars === 0 || gate.chars > options.maxChars) return;
+ candidates.add(gate);
+ ranked = null;
+ schedule();
+ },
+ remove: (gate) => {
+ candidates.delete(gate);
+ ranked = null;
+ const share = seeded.get(gate);
+ if (share !== undefined) {
+ seeded.delete(gate);
+ seededChars -= share;
+ }
+ const job = inFlight.get(gate);
+ if (job) {
+ finish(gate);
+ job.cancel?.();
+ }
+ schedule();
+ },
+ rerank: () => {
+ ranked = null;
+ },
+ snapshot: () => ({
+ candidates: candidates.size,
+ seeded: seeded.size,
+ seededChars,
+ inFlight: inFlight.size > 0,
+ inFlightCount: inFlight.size,
+ }),
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/grammar-prewarm.ts b/studio/frontend/src/components/assistant-ui/grammar-prewarm.ts
new file mode 100644
index 00000000000..9f5fb676715
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/grammar-prewarm.ts
@@ -0,0 +1,190 @@
+// 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 type GrammarSample = { language: string; lines: string[] };
+
+export type PrewarmHighlight = (
+ code: string,
+ language: string,
+ late: () => void,
+) => unknown;
+
+export type PrewarmDeps = {
+ idle: (callback: () => void, timeout: number) => () => void;
+ wait: (callback: () => void, ms: number) => () => void;
+ quiet: () => boolean;
+ skip: (language: string) => boolean;
+};
+
+export const PREWARM_IDLE_TIMEOUT_MS = 2_000;
+export const PREWARM_RETRY_MS = 1_000;
+export const PREWARM_GUARD_MS = 5_000;
+
+export const GRAMMAR_SAMPLES: readonly GrammarSample[] = [
+ {
+ language: "python",
+ lines: [
+ "# unsloth grammar warm",
+ "import os",
+ "from typing import Optional",
+ "",
+ "class Trainer:",
+ ' """Docstring."""',
+ " def __init__(self, lr: float = 1e-3) -> None:",
+ " self.lr = lr",
+ "",
+ " def step(self, batch: list[int]) -> Optional[float]:",
+ " total = sum(x * 2 for x in batch if x > 0)",
+ " return total / len(batch) if batch else None",
+ "",
+ 'if __name__ == "__main__":',
+ ' print(f"loss={Trainer().step([1, 2, 3]):.3f}")',
+ ],
+ },
+ {
+ language: "html",
+ lines: [
+ "<!-- unsloth grammar warm -->",
+ "<!doctype html>",
+ '<html lang="en">',
+ " <head>",
+ " <style>",
+ " :root { --gap: 8px; }",
+ " .card { display: flex; gap: var(--gap); color: #333; }",
+ " @media (max-width: 600px) { .card { flex-direction: column; } }",
+ " </style>",
+ " </head>",
+ " <body>",
+ ' <div class="card" data-note="a > b">text &amp; more</div>',
+ " <script>",
+ " const items = [1, 2, 3];",
+ " const total = items.reduce((sum, n) => sum + n, 0);",
+ " function tick(dt) { if (dt > 1) { return `total ${total}`; } }",
+ " class Game { constructor() { this.state = { t: 0 }; } }",
+ ' document.querySelector(".card").addEventListener("click", () => console.log(/re+/g.test("ree")));',
+ " </script>",
+ " </body>",
+ "</html>",
+ ],
+ },
+ {
+ language: "javascript",
+ lines: [
+ "// unsloth grammar warm",
+ 'import { readFile } from "node:fs/promises";',
+ "const items = [1, 2, 3];",
+ "const total = items.reduce((sum, n) => sum + n, 0);",
+ "function tick(dt) { if (dt > 1) { return `total ${total}`; } }",
+ 'class Game { constructor() { this.state = { t: 0 }; } async load() { return await readFile("x"); } }',
+ "export default Game;",
+ ],
+ },
+ {
+ language: "typescript",
+ lines: [
+ "// unsloth grammar warm",
+ 'import type { Foo } from "./foo";',
+ "interface Props { items: string[]; onPick?: (item: string) => void }",
+ "export function pick<T extends object>(xs: T[], i: number): T | undefined { return xs[i]; }",
+ "const total: number = [1, 2, 3].reduce((sum, n) => sum + n, 0);",
+ 'enum Mode { A = "a", B = "b" }',
+ "export class Store<T> { private items = new Map<string, T>(); get(k: string) { return this.items.get(k) ?? null; } }",
+ ],
+ },
+ {
+ language: "shellscript",
+ lines: [
+ "# unsloth grammar warm",
+ "#!/usr/bin/env bash",
+ "set -euo pipefail",
+ 'for f in "$@"; do',
+ ' if [[ -f "$f" ]]; then echo "ok $f"; fi',
+ "done",
+ "cat <<END",
+ "$HOME here",
+ "END",
+ 'pip install -U unsloth && python -m unsloth.cli --model "$MODEL"',
+ ],
+ },
+ {
+ language: "json",
+ lines: [
+ '{"unsloth grammar warm": 0,',
+ ' "name": "x", "version": "1.0.0", "list": [1, 2.5, true, null], "nested": {"a": "b"}}',
+ ],
+ },
+ {
+ language: "css",
+ lines: [
+ "/* unsloth grammar warm */",
+ ":root { --gap: 8px; }",
+ ".card { display: flex; gap: var(--gap); color: #333; }",
+ "@media (max-width: 600px) { .card { flex-direction: column; } }",
+ '.card:hover > .title::before { content: "x"; }',
+ ],
+ },
+];
+
+export type GrammarPrewarm = { start: () => void; cancel: () => void };
+
+export function createGrammarPrewarm(
+ highlight: PrewarmHighlight,
+ deps: PrewarmDeps,
+ samples: readonly GrammarSample[] = GRAMMAR_SAMPLES,
+): GrammarPrewarm {
+ let sample = 0;
+ let line = 0;
+ let pending: (() => void) | null = null;
+ let guard: (() => void) | null = null;
+ let epoch = 0;
+ let started = false;
+ let done = false;
+ const step = (): void => {
+ pending = null;
+ while (sample < samples.length && deps.skip(samples[sample].language)) {
+ sample += 1;
+ line = 0;
+ }
+ if (sample >= samples.length) {
+ done = true;
+ return;
+ }
+ if (!deps.quiet()) {
+ pending = deps.wait(step, PREWARM_RETRY_MS);
+ return;
+ }
+ const { language, lines } = samples[sample];
+ line += 1;
+ const code = `${lines.slice(0, line).join("\n")}\n`;
+ const mine = epoch;
+ let advanced = false;
+ const advance = (): void => {
+ if (advanced || mine !== epoch) return;
+ advanced = true;
+ guard?.();
+ guard = null;
+ if (line >= lines.length) {
+ sample += 1;
+ line = 0;
+ }
+ pending = deps.idle(step, PREWARM_IDLE_TIMEOUT_MS);
+ };
+ guard = deps.wait(advance, PREWARM_GUARD_MS);
+ if (highlight(code, language, advance)) advance();
+ };
+ return {
+ start: () => {
+ if (started || done) return;
+ started = true;
+ pending = deps.idle(step, PREWARM_IDLE_TIMEOUT_MS);
+ },
+ cancel: () => {
+ epoch += 1;
+ guard?.();
+ guard = null;
+ pending?.();
+ pending = null;
+ started = false;
+ },
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 9eafcdbf5ae..16ac84fbd86 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -69,6 +69,7 @@ import {
useRef,
useState,
} from "react";
+import { flushSync } from "react-dom";
import {
Block,
type BlockProps,
@@ -76,16 +77,27 @@ import {
type StreamdownProps,
} from "streamdown";
import {
+ awaitWorker,
DeferredFenceShell,
FenceBody,
type FenceTokens,
fenceMode,
+ noteStreamingFence,
+ PlainFenceShell,
trimmedLength,
trimTrailingNewlines,
useFenceReached,
} from "./code-fence-defer";
+import {
+ highlightWorkerState,
+ requestFullHighlight,
+} from "./use-reasoning-highlight";
+import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
import { markdownBlockFallback } from "./markdown-block-fallback";
import { createCodePlugin } from "./code-plugin";
+import { CodeHighlightModeContext } from "./code-highlight-context";
+import { spellLines } from "./reasoning-code-colour";
+import { useThinkingCodeColour } from "./use-thinking-code-colour";
import { withMathBlockMarker } from "./math-block-marker";
import {
MarkdownBlockBoundary,
@@ -112,6 +124,10 @@ import { useSandboxImage } from "./use-sandbox-image";
import { rehypeSandboxImages } from "./rehype-sandbox-images";
import { unslothDarkTheme, unslothLightTheme } from "./code-themes";
import { stabilizeStreamingMarkdown } from "./streaming-markdown";
+import {
+ createDiscreteInputTracker,
+ type DiscreteInputTracker,
+} from "./discrete-input";
import {
IncrementalMarkdownCache,
LITERAL_LINK_REMEND,
@@ -136,6 +152,9 @@ const code = createCodePlugin({
const STREAMDOWN_PLUGINS = { code, math, mermaid } satisfies NonNullable<
StreamdownProps["plugins"]
>;
+const STREAMDOWN_PLAIN_CODE_PLUGINS = { math, mermaid } satisfies NonNullable<
+ StreamdownProps["plugins"]
+>;
const STREAMDOWN_CONTROLS = {
code: false,
mermaid: {
@@ -169,6 +188,35 @@ const STREAMDOWN_ICONS = {
} satisfies NonNullable<StreamdownProps["icons"]>;
const { withSmoothContextProvider } = INTERNAL;
+const STREAMING_RENDER_DUTY = 3;
+const STREAMING_INPUT_YIELDS = 3;
+
+type InputPendingNavigator = Navigator & {
+ scheduling?: {
+ isInputPending?: (options?: { includeContinuous?: boolean }) => boolean;
+ };
+};
+
+let discreteInput: DiscreteInputTracker | null = null;
+
+const inputPending = (): boolean => {
+ const scheduling = (navigator as InputPendingNavigator).scheduling;
+ if (scheduling?.isInputPending) {
+ return scheduling.isInputPending();
+ }
+ discreteInput ??= createDiscreteInputTracker(document);
+ return discreteInput.pending();
+};
+
+const afterFrame = (callback: () => void): void => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => {
+ channel.port1.close();
+ callback();
+ };
+ channel.port2.postMessage(null);
+};
+
// Streamdown 2.5 schedules ordinary streaming blocks in an interruptible React transition, and a continuous token
// stream can starve that transition for seconds. Its animated path commits every block update directly.
// StreamdownBlock removes the animation transformer while retaining this direct scheduling path.
@@ -630,7 +678,7 @@ export function CodeBlockActions({
}: {
disabled: boolean;
language: string | null;
- source: string;
+ source: string | (() => string);
}) {
const { copied, showCopied } = useCopiedState();
@@ -643,7 +691,8 @@ export function CodeBlockActions({
title="Copy code"
disabled={disabled}
onClick={async () => {
- if (!(await copyToClipboard(source))) {
+ const text = typeof source === "function" ? source() : source;
+ if (!(await copyToClipboard(text))) {
return;
}
showCopied();
@@ -661,7 +710,10 @@ export function CodeBlockActions({
title="Download file"
disabled={disabled}
onClick={() => {
- downloadTextFile(getCodeFilename(language), source);
+ downloadTextFile(
+ getCodeFilename(language),
+ typeof source === "function" ? source() : source,
+ );
}}
>
<HugeiconsIcon icon={Download01Icon} className="size-icon" />
@@ -715,6 +767,8 @@ function StreamdownBlockContent(props: BlockProps) {
const messageHasRenderableRenderHtmlTool = useContext(
RenderHtmlToolPresenceContext,
);
+ const highlightMode = useContext(CodeHighlightModeContext);
+ const highlightCode = highlightMode === "all";
// ONE walk, both answers. `findMermaidFence` splits the block and scans every line, and asking
// the two questions separately walked it twice on every render of every block. Measured on a
// 3,000 line fence: 0.118 ms per walk, so the redundant one cost 0.092 ms per render, about
@@ -803,11 +857,21 @@ function StreamdownBlockContent(props: BlockProps) {
return (
<>
- <FenceBlock
- isIncomplete={props.isIncomplete}
- language={codeFence.language}
- source={codeFence.source}
- />
+ {highlightCode || highlightMode === "settled" ? (
+ <FenceBlock
+ // A closed fence in a streaming trace is settled: worker route, not the main thread.
+ isIncomplete={highlightCode ? props.isIncomplete : false}
+ language={codeFence.language}
+ source={codeFence.source}
+ />
+ ) : (
+ <PlainFenceBlock
+ actions
+ isIncomplete={props.isIncomplete}
+ language={codeFence.language}
+ source={codeFence.source}
+ />
+ )}
{svgSource && <SvgPreview source={svgSource} />}
</>
);
@@ -839,23 +903,33 @@ function StreamdownBlockContent(props: BlockProps) {
*/
const settledFence = props.isIncomplete ? null : markdownBlockFallback(props.content);
if (settledFence?.fenced && !(settledFence.language === "mermaid" && mermaidSource)) {
- return (
+ return highlightCode ? (
<StreamingFenceBlock
isIncomplete={false}
language={settledFence.language}
source={settledFence.text}
/>
+ ) : (
+ <PlainFenceBlock
+ language={settledFence.language}
+ source={settledFence.text}
+ />
);
}
if (props.isIncomplete) {
const openFence = markdownBlockFallback(props.content);
if (openFence.fenced) {
- return (
+ return highlightCode ? (
<StreamingFenceBlock
language={openFence.language}
source={openFence.text}
/>
+ ) : (
+ <LiveThinkingFence
+ language={openFence.language}
+ source={openFence.text}
+ />
);
}
}
@@ -882,13 +956,67 @@ function StreamdownBlockContent(props: BlockProps) {
* chunk N can arrive after chunk N+1 has already been rendered, and letting it through would walk
* the fence backwards by a frame.
*/
+const fenceHighlightOptions = (body: string, languageToken: string | null) => ({
+ code: body,
+ language: (languageToken ?? "text") as never,
+ themes: STREAMDOWN_SHIKI_THEME,
+});
+
+const tokenizesOffThread = (body: string, streaming: boolean): boolean =>
+ !streaming && body.length > MAX_HIGHLIGHT_CHARS;
+
+const slowMainThreadRegex =
+ typeof window !== "undefined"
+ && typeof window.requestIdleCallback !== "function";
+const MAIN_THREAD_TAIL_CHARS = 512;
+
+const settlesOffThread = (
+ body: string,
+ streaming: boolean,
+ options: ReturnType<typeof fenceHighlightOptions>,
+): boolean => {
+ if (!tokenizesOffThread(body, streaming)) {
+ if (streaming || !slowMainThreadRegex) return false;
+ const state = highlightWorkerState();
+ if (state === "unavailable" || state === "stalled") return false;
+ }
+ return code.cover(options).uncovered > MAIN_THREAD_TAIL_CHARS;
+};
+
+export const highlightFenceSource = (
+ body: string,
+ language: string | null,
+ late: (result: FenceTokens) => void,
+): FenceTokens | null =>
+ code.highlight(fenceHighlightOptions(body, language), late);
+
function useFenceTokens(
source: string,
languageToken: string | null,
enabled: boolean,
+ streaming: boolean,
): FenceTokens | null {
- const [tokens, setTokens] = useState<FenceTokens | null>(null);
+ const highlight = useCallback(
+ (body: string, late: (result: FenceTokens) => void) =>
+ streaming
+ ? code.highlight(fenceHighlightOptions(body, languageToken), late)
+ : code.highlightExact(fenceHighlightOptions(body, languageToken), late),
+ [languageToken, streaming],
+ );
+ const [seed] = useState<{ body: string; tokens: FenceTokens } | null>(() => {
+ if (!enabled) return null;
+ const body = trimTrailingNewlines(source);
+ const options = fenceHighlightOptions(body, languageToken);
+ const settled = settlesOffThread(body, streaming, options)
+ ? code.cached(options)
+ : highlight(body, () => {});
+ return settled ? { body, tokens: settled } : null;
+ });
+ const [tokens, setTokens] = useState<FenceTokens | null>(
+ seed?.tokens ?? null,
+ );
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.
@@ -902,20 +1030,71 @@ function useFenceTokens(
if (!enabled) return;
const body = trimTrailingNewlines(source);
wanted.current = body;
- const settled = code.highlight(
- {
- code: body,
- language: (languageToken ?? "text") as never,
- themes: STREAMDOWN_SHIKI_THEME,
- },
- (late) => {
- if (wanted.current === body) setTokens(late);
- },
- );
+ if (!seedConsumed.current) {
+ seedConsumed.current = true;
+ if (seed?.body === body) return;
+ }
+ const late = (result: FenceTokens) => {
+ if (wanted.current === body) setTokens(result);
+ };
+ let cancel: (() => void) | null = null;
+ let release: (() => void) | null = null;
+ let settled: FenceTokens | 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));
+ }
+ return;
+ }
+ 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;
+ }
+ 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);
+ }
// `settled === null` means the plugin caught a tokenization error; keeping the previous
// tokens would show an older, shorter body. The callback restores them if it succeeds later.
setTokens(settled ?? null);
- }, [enabled, source, languageToken]);
+ return () => {
+ release?.();
+ cancel?.();
+ };
+ }, [enabled, source, highlight, seed, streaming, languageToken]);
return tokens;
}
@@ -937,7 +1116,8 @@ function StreamingFenceBlock({
isIncomplete?: boolean;
}) {
const languageToken = language?.trim().split(/\s+/)[0] || null;
- const tokens = useFenceTokens(source, languageToken, true);
+ if (isIncomplete) noteStreamingFence(languageToken, source);
+ const tokens = useFenceTokens(source, languageToken, true, isIncomplete);
return (
<MarkdownRendererBoundary
fallback={<DeferredFenceShell language={languageToken} source={source} />}
@@ -953,6 +1133,66 @@ function StreamingFenceBlock({
);
}
+function PlainFenceBlock({
+ actions = false,
+ isIncomplete,
+ language,
+ source,
+}: {
+ actions?: boolean;
+ isIncomplete?: boolean;
+ language: string | null;
+ source: string;
+}) {
+ const languageToken = language?.trim().split(/\s+/)[0] || null;
+ const shell = <PlainFenceShell language={languageToken} source={source} />;
+ if (!actions) return shell;
+ return (
+ <div className="relative isolate">
+ {shell}
+ <CodeBlockActions
+ disabled={Boolean(isIncomplete)}
+ language={language}
+ source={source}
+ />
+ </div>
+ );
+}
+
+function LiveThinkingFence({
+ language,
+ source,
+}: {
+ language: string | null;
+ source: string;
+}) {
+ const languageToken = language?.trim().split(/\s+/)[0] || null;
+ const host = useRef<HTMLDivElement | null>(null);
+ const colour = useThinkingCodeColour(host, source, languageToken, false);
+ const result = useMemo(
+ () =>
+ colour === null
+ ? null
+ : spellLines(colour, trimTrailingNewlines(source).split("\n")),
+ [colour, source],
+ );
+ return (
+ <div className="relative isolate" ref={host}>
+ {result === null ? (
+ <PlainFenceShell language={languageToken} source={source} />
+ ) : (
+ <FenceBody
+ isIncomplete
+ language={languageToken}
+ result={result}
+ source={source}
+ windowing={fenceMode() === "window"}
+ />
+ )}
+ </div>
+ );
+}
+
/*
* The fence branch, extracted so the reach latch can be a hook. With the flag off this renders exactly what the
* branch rendered before: the same `relative isolate` wrapper, the same action bar, and inside them a body
@@ -997,11 +1237,37 @@ function FenceBlock({
*/
const warm = useCallback(
(tokens: boolean) => {
- code.highlight({
- code: tokens ? trimTrailingNewlines(source) : "",
- language: (languageToken ?? "text") as never,
- themes: STREAMDOWN_SHIKI_THEME,
- }, () => {});
+ const body = trimTrailingNewlines(source);
+ const options = fenceHighlightOptions(body, languageToken);
+ const inline =
+ tokens
+ && (!settlesOffThread(body, Boolean(isIncomplete), options)
+ || code.cached(options) !== null);
+ if (inline && !isIncomplete) code.highlightExact(options, () => {});
+ else code.highlight(inline ? options : fenceHighlightOptions("", languageToken), () => {});
+ },
+ [source, languageToken, isIncomplete],
+ );
+
+ const speculate = useCallback(
+ (settle: (seeded: boolean) => void) => {
+ const body = trimTrailingNewlines(source);
+ const options = fenceHighlightOptions(body, languageToken);
+ if (code.cached(options) !== null) {
+ settle(true);
+ return null;
+ }
+ const cancel = requestFullHighlight(
+ body,
+ languageToken,
+ (result) => {
+ if (result !== null) code.seed(options, result);
+ settle(result !== null);
+ },
+ true,
+ );
+ if (cancel === null) settle(false);
+ return cancel;
},
[source, languageToken],
);
@@ -1014,7 +1280,9 @@ function FenceBlock({
Boolean(isIncomplete),
languageToken,
trimmedLength(source),
+ source,
warm,
+ speculate,
);
// MEASUREMENT ARM ONLY. See `FenceMode`: this puts the tokenizer work back while leaving the document at the
@@ -1023,7 +1291,12 @@ function FenceBlock({
// Asked for only once the fence is reached, so a deferred fence still tokenizes nothing. The
// latch calls `warm(true)` synchronously on the way in, so this is a cache hit rather than the
// first tokenization of the body.
- const tokens = useFenceTokens(source, languageToken, reached);
+ const tokens = useFenceTokens(
+ source,
+ languageToken,
+ reached,
+ Boolean(isIncomplete),
+ );
const pretokenize = mode === "tokenize" && !reached;
useEffect(() => {
@@ -1089,9 +1362,7 @@ StreamdownBlock.displayName = "StreamdownBlock";
// Only the adapter's inline wav: any other src (remote URL, WebKit-followed audio/mpegurl) fetches on render.
const AUDIO_PLAYER_RE = /<audio-player\s+src="(data:audio\/wav;base64,[A-Za-z0-9+/=]+)"\s*\/>/;
-// Coalesce only token events that arrive before the browser's next paint, as
-// textgen does. There is no time or length throttle. Incremental block parsing
-// bounds the work performed per paint, and completion returns immediately.
+// One render per paint, spaced by measured cost; incremental parsing bounds the work per paint.
function useCoalescedStreamingText(
text: string,
isStreaming: boolean,
@@ -1100,6 +1371,11 @@ function useCoalescedStreamingText(
const [displayed, setDisplayed] = useState({ messageId, text });
const pendingRef = useRef({ messageId, text });
const rafRef = useRef<number | null>(null);
+ const renderedAtRef = useRef(Number.NEGATIVE_INFINITY);
+ const frameAtRef = useRef(Number.NEGATIVE_INFINITY);
+ const frameIntervalRef = useRef(Number.POSITIVE_INFINITY);
+ const costRef = useRef(0);
+ const yieldsRef = useRef(0);
const activeMessageIdRef = useRef(messageId);
const cancelScheduledRender = useCallback(() => {
@@ -1124,10 +1400,39 @@ function useCoalescedStreamingText(
return;
}
- rafRef.current = requestAnimationFrame(() => {
+ const render = (frameTime: number) => {
rafRef.current = null;
- setDisplayed(pendingRef.current);
- });
+ if (frameTime > frameAtRef.current) {
+ frameIntervalRef.current = Math.min(
+ frameIntervalRef.current,
+ frameTime - frameAtRef.current,
+ );
+ frameAtRef.current = frameTime;
+ }
+ if (
+ frameTime - renderedAtRef.current <
+ Math.max(
+ 16 - Math.min(frameIntervalRef.current, 16) / 2,
+ STREAMING_RENDER_DUTY * costRef.current,
+ )
+ ) {
+ rafRef.current = requestAnimationFrame(render);
+ return;
+ }
+ if (yieldsRef.current < STREAMING_INPUT_YIELDS && inputPending()) {
+ yieldsRef.current += 1;
+ rafRef.current = requestAnimationFrame(render);
+ return;
+ }
+ yieldsRef.current = 0;
+ renderedAtRef.current = frameTime;
+ afterFrame(() => {
+ const startedAt = performance.now();
+ flushSync(() => setDisplayed(pendingRef.current));
+ costRef.current = performance.now() - startedAt;
+ });
+ };
+ rafRef.current = requestAnimationFrame(render);
}, [cancelScheduledRender, messageId, text, isStreaming]);
useEffect(() => {
@@ -1178,6 +1483,7 @@ function MarkdownTextRenderer({
const remoteId = useAuiState(({ threadListItem }) => threadListItem.remoteId);
const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);
const projectId = useChatProjectScope();
+ const highlightCode = useContext(CodeHighlightModeContext) === "all";
const threadId = remoteId ?? activeThreadId ?? undefined;
// Streamdown's memo comparator ignores rehypePlugins.
const sandboxScopeKey = JSON.stringify([threadId, projectId]);
@@ -1266,7 +1572,9 @@ function MarkdownTextRenderer({
}
isAnimating={isStreaming}
animated={STREAMDOWN_IMMEDIATE_UPDATES}
- plugins={STREAMDOWN_PLUGINS}
+ plugins={
+ highlightCode ? STREAMDOWN_PLUGINS : STREAMDOWN_PLAIN_CODE_PLUGINS
+ }
components={STREAMDOWN_COMPONENTS}
allowedTags={STREAMDOWN_ALLOWED_TAGS}
rehypePlugins={rehypePlugins}
@@ -1310,7 +1618,9 @@ const MarkdownTextImpl = () => {
allowSearchImages ? partsPrecedingText(message.parts, partIndex) : "",
);
const messageTextKey = useAuiState(({ message }) =>
- allowSearchImages ? partsTextKey(message.parts) : "[]",
+ allowSearchImages && partsSearchImagesSignature(message.parts) !== ""
+ ? partsTextKey(message.parts)
+ : "[]",
);
return (
diff --git a/studio/frontend/src/components/assistant-ui/message-derived.ts b/studio/frontend/src/components/assistant-ui/message-derived.ts
index ed4cbe4360f..6955b3ca49d 100644
--- a/studio/frontend/src/components/assistant-ui/message-derived.ts
+++ b/studio/frontend/src/components/assistant-ui/message-derived.ts
@@ -24,6 +24,24 @@ export function memoOnArray<A extends readonly unknown[], T>(
};
}
+const memoByArrayAndKey = new WeakMap<object, Map<unknown, unknown>>();
+
+export function memoOnArrayByKey<K, V>(
+ array: readonly unknown[],
+ key: K,
+ compute: () => V,
+): V {
+ let byKey = memoByArrayAndKey.get(array);
+ if (byKey === undefined) {
+ byKey = new Map();
+ memoByArrayAndKey.set(array, byKey);
+ }
+ if (byKey.has(key)) return byKey.get(key) as V;
+ const value = compute();
+ byKey.set(key, value);
+ return value;
+}
+
type PartLike = { readonly type: string; readonly text?: unknown };
export const partsHaveRenderableRenderHtmlTool = memoOnArray(
diff --git a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
index 2103940a890..14878cfb34c 100644
--- a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
@@ -26,7 +26,7 @@ import { cn } from "@/lib/utils";
import { useMessage, useMessageTiming } from "@assistant-ui/react";
import { InformationCircleIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import type { FC, ReactNode } from "react";
+import { type FC, type ReactNode, useEffect, useState } from "react";
type ResponseDetailsMetadata = {
modelId?: string;
@@ -339,6 +339,26 @@ export const MessageResponseModelBadge: FC<{ className?: string }> = ({
export const MessageResponseDetailsSheet: FC<{
open: boolean;
onOpenChange: (open: boolean) => void;
+}> = ({ open, onOpenChange }) => {
+ const [mounted, setMounted] = useState(open);
+ if (open && !mounted) setMounted(true);
+ useEffect(() => {
+ if (open) return;
+ const timer = window.setTimeout(() => setMounted(false), 500);
+ return () => window.clearTimeout(timer);
+ }, [open]);
+ if (!mounted && !open) return null;
+ return (
+ <MessageResponseDetailsSheetContent
+ open={open}
+ onOpenChange={onOpenChange}
+ />
+ );
+};
+
+const MessageResponseDetailsSheetContent: FC<{
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
}> = ({ open, onOpenChange }) => {
const timing = useMessageTiming();
const {
diff --git a/studio/frontend/src/components/assistant-ui/own-string.ts b/studio/frontend/src/components/assistant-ui/own-string.ts
new file mode 100644
index 00000000000..a708ea5cf34
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/own-string.ts
@@ -0,0 +1,5 @@
+// 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 ownString = (text: string): string =>
+ text.length < 16 ? text : (" " + text).slice(1);
diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
index 4f5bbbf078d..6f1566e73af 100644
--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
@@ -141,6 +141,12 @@ function pickAnchorRow(viewport: HTMLElement): Element | null {
}
}
if (!anchor) return null;
+ if (
+ typeof anchor.checkVisibility === "function"
+ && !anchor.checkVisibility({ contentVisibilityAuto: true })
+ ) {
+ return anchor;
+ }
// Then descend to the fold. A row can be taller than the viewport (a long answer with images and code usually
// is), so a reader partway through one has the row's top ABOVE them: a block earlier in that message growing
// moves everything they see while the row's top stays put, and a whole-row anchor reports zero. The first
@@ -154,6 +160,13 @@ function pickAnchorRow(viewport: HTMLElement): Element | null {
if (anchor.getBoundingClientRect().top >= fold) break;
let next: Element | null = null;
for (const child of anchor.children) {
+ if (
+ typeof child.checkVisibility === "function"
+ && !child.checkVisibility({ contentVisibilityAuto: true })
+ ) {
+ if (child.checkVisibility()) return anchor;
+ continue;
+ }
if (child.getBoundingClientRect().bottom > fold) {
next = child;
break;
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-code-colour.ts b/studio/frontend/src/components/assistant-ui/reasoning-code-colour.ts
new file mode 100644
index 00000000000..a7f4cbc67bd
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reasoning-code-colour.ts
@@ -0,0 +1,130 @@
+// 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";
+
+export type TokenLine = HighlightResult["tokens"][number];
+
+const MAX_ENTRIES = 128;
+const MAX_CHARACTERS = 1_000_000;
+const results = new Map<string, { result: HighlightResult; chars: number }>();
+let characters = 0;
+
+const keyOf = (language: string | null, source: string): string =>
+ `${language ?? ""}\u0000${source}`;
+
+export function cachedSettledColour(
+ language: string | null,
+ source: string,
+): HighlightResult | null {
+ return results.get(keyOf(language, source))?.result ?? null;
+}
+
+export function rememberSettledColour(
+ language: string | null,
+ source: string,
+ result: HighlightResult,
+): void {
+ if (source.length > MAX_CHARACTERS) return;
+ const key = keyOf(language, source);
+ const held = results.get(key);
+ if (held) {
+ characters -= held.chars;
+ results.delete(key);
+ }
+ results.set(key, { result, chars: source.length });
+ characters += source.length;
+ while (results.size > MAX_ENTRIES || characters > MAX_CHARACTERS) {
+ const oldest = results.entries().next();
+ if (oldest.done) break;
+ results.delete(oldest.value[0]);
+ characters -= oldest.value[1].chars;
+ }
+}
+
+/** The tokens of `line` covering `text` from `column`; null unless they spell it exactly. */
+export function clipLineTokens(
+ line: TokenLine | undefined,
+ column: number,
+ text: string,
+): TokenLine | null {
+ if (line === undefined) return null;
+ const clipped: TokenLine = [];
+ let offset = 0;
+ let spelled = "";
+ for (const token of line) {
+ const start = offset;
+ offset += token.content.length;
+ const content = token.content.slice(
+ Math.max(0, column - start),
+ Math.max(0, Math.min(token.content.length, column + text.length - start)),
+ );
+ if (content === "") continue;
+ spelled += content;
+ clipped.push(content === token.content ? token : { ...token, content });
+ }
+ return spelled === text ? clipped : null;
+}
+
+const spells = (line: TokenLine | undefined, text: string): boolean => {
+ if (line === undefined) return false;
+ let at = 0;
+ for (const token of line) {
+ if (!text.startsWith(token.content, at)) return false;
+ at += token.content.length;
+ }
+ return at === text.length;
+};
+
+const sameStyle = (
+ a: Record<string, string> | undefined,
+ b: Record<string, string> | undefined,
+): boolean => {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ const keys = Object.keys(a);
+ return (
+ keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key])
+ );
+};
+
+const sameLine = (a: TokenLine, b: TokenLine): boolean =>
+ a.length === b.length &&
+ a.every(
+ (token, index) =>
+ token.content === b[index].content &&
+ token.color === b[index].color &&
+ token.bgColor === b[index].bgColor &&
+ token.fontStyle === b[index].fontStyle &&
+ sameStyle(token.htmlStyle, b[index].htmlStyle),
+ );
+
+export function keepUnchangedLines(
+ previous: HighlightResult | null,
+ next: HighlightResult,
+): HighlightResult {
+ if (previous === null) return next;
+ return {
+ ...next,
+ tokens: next.tokens.map((line, index) => {
+ const old = previous.tokens[index];
+ return old !== undefined && sameLine(old, line) ? old : line;
+ }),
+ };
+}
+
+const plainLine = (content: string): TokenLine =>
+ [{ content, offset: 0 }] as unknown as TokenLine;
+
+/** Colours from an earlier, shorter source where they still spell the line; plain otherwise. */
+export function spellLines(
+ result: HighlightResult,
+ lines: readonly string[],
+): HighlightResult {
+ return {
+ ...result,
+ tokens: lines.map((text, index) =>
+ spells(result.tokens[index], text) ? result.tokens[index] : plainLine(text),
+ ),
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts b/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts
index 1adb749c961..7d9136be2de 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts
+++ b/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts
@@ -1,6 +1,7 @@
// 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 { ownString } from "./own-string.ts";
import type {
ReasoningCodeLine,
ReasoningFragment,
@@ -119,7 +120,7 @@ export class ReasoningCodeIndex {
flush(true);
continue;
}
- const part = carry + text.slice(from, stop);
+ const part = ownString(carry + text.slice(from, stop));
group.push({ line, column, text: part });
characters += part.length;
pendingSource += part;
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts b/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts
index c932d223d32..2947c69f4b5 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts
+++ b/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts
@@ -9,8 +9,16 @@ export type ReasoningHighlightRequest = {
source: string | { from: number; text: string };
language: string | null;
lines: number[];
+ full?: boolean;
+ speculative?: boolean;
};
+export type ReasoningHighlightCommand =
+ | ReasoningHighlightRequest
+ | { cancel: number };
+
+export type ReasoningHighlightReady = { ready: true };
+
/** A client sends its complete source once, then only newly appended bytes. */
export function reasoningHighlightSource(
previous: string,
@@ -24,8 +32,26 @@ export type ReasoningHighlightReply = {
client: number;
revision: number;
lines: { line: number; tokens: HighlightResult["tokens"][number] }[];
+ result?: HighlightResult | null;
+ failed?: true;
};
+export type ReasoningHighlightMessage =
+ | ReasoningHighlightReady
+ | ReasoningHighlightReply;
+
+export const reasoningHighlightFailure = (
+ client: number,
+ revision: number,
+): ReasoningHighlightReply => ({ client, revision, lines: [], failed: true });
+
+export const orderHighlightRequests = <T extends { speculative?: boolean }>(
+ requests: readonly T[],
+): T[] => [
+ ...requests.filter((request) => !request.speculative),
+ ...requests.filter((request) => request.speculative),
+];
+
/** Transfer only requested lines; the worker keeps the complete grammar context. */
export function reasoningHighlightReply(
request: ReasoningHighlightRequest,
@@ -40,5 +66,6 @@ export function reasoningHighlightReply(
return tokens ? [{ line, tokens }] : [];
})
: [],
+ ...(request.full ? { result } : {}),
};
}
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts b/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts
index 3c97b2fc47b..06906608802 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts
+++ b/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts
@@ -4,11 +4,16 @@
import { createCodePlugin, normalizeLanguage } from "./code-plugin";
import { unslothDarkTheme, unslothLightTheme } from "./code-themes";
import {
+ orderHighlightRequests,
+ reasoningHighlightFailure,
reasoningHighlightReply,
reasoningHighlightSource,
+ type ReasoningHighlightCommand,
+ type ReasoningHighlightReady,
type ReasoningHighlightRequest,
} from "./reasoning-highlight";
+const FULL_REPLY_GUARD_MS = 15_000;
const themes = [unslothLightTheme, unslothDarkTheme] as const;
const highlighter = createCodePlugin({ themes: [...themes] });
const pending = new Map<number, ReasoningHighlightRequest>();
@@ -16,9 +21,7 @@ const revisions = new Map<number, number>();
const sources = new Map<number, string>();
let scheduled = false;
-self.onmessage = ({
- data,
-}: MessageEvent<ReasoningHighlightRequest | { cancel: number }>) => {
+self.onmessage ??= ({ data }: MessageEvent<ReasoningHighlightCommand>) => {
if ("cancel" in data) {
pending.delete(data.cancel);
revisions.delete(data.cancel);
@@ -37,28 +40,62 @@ self.onmessage = ({
// If tokenization was busy, queued appends coalesce before the next pass.
setTimeout(() => {
scheduled = false;
- const requests = [...pending.values()];
+ const requests = orderHighlightRequests([...pending.values()]);
pending.clear();
for (const request of requests) {
+ const current = () =>
+ revisions.get(request.client) === request.revision;
+ let guard: ReturnType<typeof setTimeout> | null = null;
+ const forget = () => {
+ pending.delete(request.client);
+ revisions.delete(request.client);
+ sources.delete(request.client);
+ if (guard !== null) clearTimeout(guard);
+ guard = null;
+ };
const publish = (
result: Parameters<typeof reasoningHighlightReply>[1],
) => {
- if (revisions.get(request.client) === request.revision)
+ if (!current()) return;
+ try {
self.postMessage(reasoningHighlightReply(request, result));
+ if (request.full && result !== null) forget();
+ } catch {
+ self.postMessage(
+ reasoningHighlightFailure(request.client, request.revision),
+ );
+ forget();
+ }
};
try {
- const result = highlighter.highlight(
- {
- code: request.source as string,
- language: normalizeLanguage(request.language ?? "text"),
- themes: [...themes],
- },
- publish,
- );
+ const options: Parameters<typeof highlighter.highlightExact>[0] = {
+ code: request.source as string,
+ language: normalizeLanguage(request.language ?? "text"),
+ themes: [...themes],
+ };
+ const result = request.full
+ ? highlighter.highlightExact(options, publish)
+ : highlighter.highlight(options, publish);
publish(result);
+ if (request.full && result === null && current()) {
+ guard = setTimeout(() => {
+ guard = null;
+ if (!current()) return;
+ self.postMessage(
+ reasoningHighlightFailure(request.client, request.revision),
+ );
+ forget();
+ }, FULL_REPLY_GUARD_MS);
+ }
} catch {
- publish(null);
+ if (current()) {
+ self.postMessage(
+ reasoningHighlightFailure(request.client, request.revision),
+ );
+ }
}
}
}, 0);
};
+
+self.postMessage({ ready: true } satisfies ReasoningHighlightReady);
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-mount-controller.ts b/studio/frontend/src/components/assistant-ui/reasoning-mount-controller.ts
new file mode 100644
index 00000000000..34ff9441279
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reasoning-mount-controller.ts
@@ -0,0 +1,531 @@
+// 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 { ReasoningFragment } from "./reasoning-transcript-index.ts";
+
+export type FragmentGeometry = {
+ width: number;
+ lineHeight: number;
+ fontPixels: number;
+ codeLineHeight: number;
+ codeFontPixels: number;
+ codeFooter: number;
+};
+
+export const INITIAL_VIEWPORTS = 1;
+export const INITIAL_CHARACTERS = 4_096;
+export const WIDEN_CHARACTERS_PER_FRAME = 24_000;
+export const WIDEN_FRAGMENTS_PER_FRAME = 64;
+export const SETTLE_MS = 300;
+export const SETTLING_DIVISOR = 4;
+
+export const frameBudget = (
+ sinceMountMs: number,
+): { characters: number; fragments: number } =>
+ sinceMountMs < SETTLE_MS
+ ? {
+ characters: Math.ceil(WIDEN_CHARACTERS_PER_FRAME / SETTLING_DIVISOR),
+ fragments: Math.ceil(WIDEN_FRAGMENTS_PER_FRAME / SETTLING_DIVISOR),
+ }
+ : {
+ characters: WIDEN_CHARACTERS_PER_FRAME,
+ fragments: WIDEN_FRAGMENTS_PER_FRAME,
+ };
+
+type EstimatedFragment = Pick<
+ ReasoningFragment,
+ "text" | "code" | "first" | "last" | "hidden"
+>;
+
+export const estimateFragmentHeight = (
+ fragment: EstimatedFragment,
+ geometry: FragmentGeometry,
+): number => {
+ if (fragment.hidden) return 0;
+ const code = fragment.code;
+ const columns = Math.max(
+ 12,
+ Math.floor(
+ code
+ ? (geometry.width - 32) / (geometry.codeFontPixels * 0.58)
+ : geometry.width / (geometry.fontPixels * 0.48),
+ ),
+ );
+ const lines = fragment.text
+ .split("\n")
+ .reduce(
+ (sum, line) => sum + Math.max(1, Math.ceil(line.length / columns)),
+ 0,
+ );
+ return code
+ ? lines * geometry.codeLineHeight +
+ (fragment.first ? 40 : 0) +
+ (fragment.last ? geometry.codeFooter : 0)
+ : Math.max(1, lines - 2) * geometry.lineHeight +
+ (fragment.first ? 16 : 0);
+};
+
+const estimated = new WeakMap<
+ FragmentGeometry,
+ WeakMap<EstimatedFragment, number>
+>();
+
+export const estimateFragmentHeights = (
+ fragments: readonly EstimatedFragment[],
+ geometry: FragmentGeometry,
+): number[] => {
+ let known = estimated.get(geometry);
+ if (known === undefined) {
+ known = new WeakMap();
+ estimated.set(geometry, known);
+ }
+ return fragments.map((fragment) => {
+ let height = known.get(fragment);
+ if (height === undefined) {
+ height = estimateFragmentHeight(fragment, geometry);
+ known.set(fragment, height);
+ }
+ return height;
+ });
+};
+
+export const initialRows = (
+ estimates: readonly number[],
+ budgetPx: number,
+ mustInclude: number,
+ sizes?: readonly number[],
+ budgetChars: number = INITIAL_CHARACTERS,
+): number => {
+ if (estimates.length === 0) return 0;
+ let rows = Math.min(estimates.length, Math.max(0, mustInclude));
+ let covered = 0;
+ let spent = 0;
+ while (
+ rows < estimates.length
+ && (rows <= mustInclude || (covered < budgetPx && spent < budgetChars))
+ ) {
+ covered += estimates[rows];
+ spent += sizes?.[rows] ?? 0;
+ rows += 1;
+ }
+ return Math.max(1, rows);
+};
+
+export const widenBudget = (
+ sizes: readonly number[],
+ mounted: number,
+ budget: number,
+ maxRows: number = WIDEN_FRAGMENTS_PER_FRAME,
+): { rows: number; spent: number } => {
+ let rows = mounted;
+ let spent = 0;
+ while (
+ rows < sizes.length
+ && (spent === 0 || (spent + sizes[rows] <= budget && rows - mounted < maxRows))
+ ) {
+ spent += sizes[rows];
+ rows += 1;
+ }
+ return { rows, spent };
+};
+
+export const isCovered = (mounted: number, total: number): boolean =>
+ mounted >= total;
+
+export const CHUNK_CHARACTERS = 8_192;
+export const CHUNK_MAX_GROUPS = 12;
+
+export type FragmentGroup = {
+ readonly key: string;
+ readonly code: boolean;
+ readonly first: number;
+ readonly end: number;
+ readonly chars: number;
+};
+
+export type GridChunk = {
+ readonly key: string;
+ readonly groupStart: number;
+ readonly groupEnd: number;
+ readonly first: number;
+ readonly end: number;
+};
+
+export type ChunkGrid = {
+ readonly groups: readonly FragmentGroup[];
+ readonly chunks: readonly GridChunk[];
+ readonly groupOf: Int32Array;
+ readonly chunkOf: Int32Array;
+ readonly heights: Float64Array;
+};
+
+type GridFragment = Pick<ReasoningFragment, "key" | "text" | "code" | "document" | "start">;
+
+const groupKeyOf = (fragment: GridFragment): string =>
+ fragment.code ? `${fragment.document}:${fragment.start}` : fragment.key;
+
+type PlacedFragment = Pick<ReasoningFragment, "text" | "code" | "document" | "start" | "end">;
+
+const rowAtSamePlace = (
+ fragments: readonly PlacedFragment[],
+ row: PlacedFragment,
+): number => {
+ const line = row.code?.lines[0]?.line ?? 0;
+ const column = row.code?.lines[0]?.column ?? 0;
+ const same = fragments.findIndex(
+ (fragment) =>
+ fragment.document === row.document
+ && fragment.start === row.start
+ && (fragment.code?.lines[0]?.line ?? 0) === line
+ && (fragment.code?.lines[0]?.column ?? 0) === column,
+ );
+ if (same >= 0) return same;
+ const at = row.code
+ ? row.start
+ : row.start + row.text.length - row.text.trimStart().length;
+ return fragments.findIndex(
+ (fragment) =>
+ fragment.document === row.document
+ && fragment.start <= at
+ && at < fragment.end,
+ );
+};
+
+const occurrencesIn = (row: PlacedFragment, needle: string): number => {
+ if (!needle) return 0;
+ let found = 0;
+ for (const { text } of row.code?.lines ?? []) {
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1))
+ found += 1;
+ }
+ return found;
+};
+
+const fenceRows = (
+ fragments: readonly PlacedFragment[],
+ fence: PlacedFragment,
+): number[] =>
+ fragments.flatMap((fragment, index) =>
+ fragment.code
+ && fragment.document === fence.document
+ && fragment.start === fence.start
+ ? [index]
+ : [],
+ );
+
+export const anchorAtSamePlace = (
+ previous: readonly PlacedFragment[],
+ fragments: readonly PlacedFragment[],
+ row: PlacedFragment,
+ text: string,
+ occurrence: number,
+): { index: number; occurrence: number } | null => {
+ const index = rowAtSamePlace(fragments, row);
+ if (index < 0) return null;
+ if (Boolean(row.code) === Boolean(fragments[index].code))
+ return { index, occurrence };
+ if (row.code) {
+ let before = 0;
+ for (const at of fenceRows(previous, row)) {
+ if (previous[at] === row) break;
+ before += occurrencesIn(previous[at], text);
+ }
+ return { index, occurrence: occurrence + before };
+ }
+ let left = occurrence;
+ for (const at of fenceRows(fragments, fragments[index])) {
+ const here = occurrencesIn(fragments[at], text);
+ if (left < here) return { index: at, occurrence: left };
+ left -= here;
+ }
+ return { index, occurrence };
+};
+
+const startsLine = (fragment: GridFragment): boolean =>
+ (fragment.code?.lines[0]?.column ?? 0) === 0;
+
+export const buildChunkGrid = (
+ fragments: readonly GridFragment[],
+ estimates: readonly number[],
+ maxChars: number = CHUNK_CHARACTERS,
+ maxGroups: number = CHUNK_MAX_GROUPS,
+): ChunkGrid => {
+ const groups: FragmentGroup[] = [];
+ const groupOf = new Int32Array(fragments.length);
+ const heights = new Float64Array(fragments.length + 1);
+ for (let i = 0; i < fragments.length; i += 1) {
+ const fragment = fragments[i];
+ heights[i + 1] = heights[i] + (estimates[i] ?? 0);
+ const key = groupKeyOf(fragment);
+ const previous = groups[groups.length - 1];
+ const sameFence =
+ previous !== undefined
+ && previous.end === i
+ && groupKeyOf(fragments[previous.first]) === key;
+ if (sameFence && (previous.chars < maxChars || !startsLine(fragment))) {
+ groups[groups.length - 1] = {
+ ...previous,
+ end: i + 1,
+ chars: previous.chars + fragment.text.length,
+ };
+ } else {
+ groups.push({
+ key: sameFence ? fragment.key : key,
+ code: Boolean(fragment.code),
+ first: i,
+ end: i + 1,
+ chars: fragment.text.length,
+ });
+ }
+ groupOf[i] = groups.length - 1;
+ }
+ const chunks: GridChunk[] = [];
+ const chunkOf = new Int32Array(groups.length);
+ let start = 0;
+ let chars = 0;
+ for (let g = 0; g < groups.length; g += 1) {
+ if (g > start && (g - start >= maxGroups || chars >= maxChars)) {
+ chunks.push({
+ key: groups[start].key,
+ groupStart: start,
+ groupEnd: g,
+ first: groups[start].first,
+ end: groups[g - 1].end,
+ });
+ start = g;
+ chars = 0;
+ }
+ chars += groups[g].chars;
+ chunkOf[g] = chunks.length;
+ }
+ if (start < groups.length) {
+ chunks.push({
+ key: groups[start].key,
+ groupStart: start,
+ groupEnd: groups.length,
+ first: groups[start].first,
+ end: groups[groups.length - 1].end,
+ });
+ }
+ return { groups, chunks, groupOf, chunkOf, heights };
+};
+
+export const chunkEndAt = (grid: ChunkGrid, rows: number): number => {
+ if (rows <= 0) return 0;
+ if (rows >= grid.groupOf.length) return rows;
+ return grid.chunks[grid.chunkOf[grid.groupOf[rows - 1]]].end;
+};
+
+export const chunkStartAt = (grid: ChunkGrid, row: number): number => {
+ if (row <= 0) return 0;
+ if (row >= grid.groupOf.length) return row;
+ return grid.chunks[grid.chunkOf[grid.groupOf[row]]].first;
+};
+
+export type ChunkPiece = {
+ readonly key: string;
+ readonly first: number;
+ readonly end: number;
+ readonly whole: boolean;
+ readonly last: boolean;
+ readonly groups: readonly { index: number; first: number; end: number }[];
+};
+
+export const chunkPieces = (
+ grid: ChunkGrid,
+ fragmentKey: (index: number) => string,
+ from: number,
+ to: number,
+): ChunkPiece[] => {
+ const pieces: ChunkPiece[] = [];
+ for (let at = from; at < to; ) {
+ const c = grid.chunkOf[grid.groupOf[at]];
+ const chunk = grid.chunks[c];
+ const end = Math.min(to, chunk.end);
+ const groups: { index: number; first: number; end: number }[] = [];
+ for (let g = grid.groupOf[at]; g < chunk.groupEnd; g += 1) {
+ const group = grid.groups[g];
+ if (group.first >= end) break;
+ groups.push({
+ index: g,
+ first: Math.max(group.first, at),
+ end: Math.min(group.end, end),
+ });
+ }
+ pieces.push({
+ key: at === chunk.first ? chunk.key : `${chunk.key}>${fragmentKey(at)}`,
+ first: at,
+ end,
+ whole: at === chunk.first && end === chunk.end,
+ last: c === grid.chunks.length - 1,
+ groups,
+ });
+ at = end;
+ }
+ return pieces;
+};
+
+export type ChunkSlice = {
+ readonly key: string;
+ readonly code: boolean;
+ readonly first: number;
+ readonly end: number;
+ readonly streaming: boolean;
+};
+
+type ChunkRender = {
+ readonly slices: readonly ChunkSlice[];
+ readonly fragments: readonly unknown[];
+ readonly closed: boolean;
+ readonly [prop: string]: unknown;
+};
+
+const sameSlice = (a: ChunkSlice, b: ChunkSlice): boolean =>
+ a.key === b.key
+ && a.code === b.code
+ && a.first === b.first
+ && a.end === b.end
+ && a.streaming === b.streaming;
+
+export const closedChunkUnchanged = (
+ previous: ChunkRender,
+ next: ChunkRender,
+): boolean => {
+ const props = Object.keys(next);
+ if (
+ !previous.closed
+ || !next.closed
+ || Object.keys(previous).length !== props.length
+ )
+ return false;
+ for (const prop of props) {
+ if (prop === "slices" || prop === "fragments") continue;
+ if (!Object.is(previous[prop], next[prop])) return false;
+ }
+ const slices = next.slices;
+ if (
+ slices.length === 0
+ || previous.slices.length !== slices.length
+ || !slices.every((slice, at) => sameSlice(previous.slices[at], slice))
+ )
+ return false;
+ for (let at = slices[0].first; at <= slices[slices.length - 1].end; at += 1) {
+ if (previous.fragments[at] !== next.fragments[at]) return false;
+ }
+ return true;
+};
+
+export type Island = {
+ readonly id: number;
+ readonly start: number;
+ readonly end: number;
+};
+
+export const NO_ISLANDS: readonly Island[] = [];
+
+const coversRows = (
+ islands: readonly Island[],
+ start: number,
+ end: number,
+): boolean => {
+ let reach = start;
+ for (const island of islands) {
+ if (island.start > reach) break;
+ if (island.end > reach) reach = island.end;
+ if (reach >= end) return true;
+ }
+ return reach >= end;
+};
+
+export const addIsland = (
+ islands: readonly Island[],
+ add: { readonly start: number; readonly end: number },
+ prefix: number,
+): readonly Island[] => {
+ const start = Math.max(add.start, prefix);
+ if (add.end <= start || coversRows(islands, start, add.end)) return islands;
+ const at = islands.findIndex(
+ (island) => island.start <= add.end && island.end >= start,
+ );
+ const next = islands.slice();
+ if (at < 0) next.push({ id: start, start, end: add.end });
+ else
+ next[at] = {
+ id: islands[at].id,
+ start: Math.min(islands[at].start, start),
+ end: Math.max(islands[at].end, add.end),
+ };
+ return next.sort((a, b) => a.start - b.start);
+};
+
+export const mountedRanges = (
+ prefix: number,
+ islands: readonly { readonly start: number; readonly end: number }[],
+ total: number,
+): [number, number][] => {
+ const ranges: [number, number][] = [];
+ const shown = Math.min(prefix, total);
+ if (shown > 0) ranges.push([0, shown]);
+ for (const island of islands) {
+ const from = Math.max(island.start, shown);
+ const to = Math.min(island.end, total);
+ if (to <= from) continue;
+ const last = ranges[ranges.length - 1];
+ if (last !== undefined && from <= last[1]) last[1] = Math.max(last[1], to);
+ else ranges.push([from, to]);
+ }
+ return ranges;
+};
+
+export type MountItem = {
+ readonly from: number;
+ readonly to: number;
+ readonly reserve?: string;
+};
+
+export const TAIL_RESERVE = "tail";
+
+export const mountPlan = (
+ prefix: number,
+ islands: readonly Island[],
+ total: number,
+): MountItem[] => {
+ const items: MountItem[] = [];
+ const rowOf = (at: number) => Math.min(islands[at].start, total);
+ let anchor = 0;
+ let covered = 0;
+ for (const [from, to] of mountedRanges(prefix, islands, total)) {
+ while (anchor < islands.length && rowOf(anchor) <= from) {
+ const opens = rowOf(anchor) === from;
+ items.push({
+ from: covered,
+ to: opens ? from : covered,
+ reserve: String(islands[anchor].id),
+ });
+ if (opens) covered = from;
+ anchor += 1;
+ }
+ let cursor = from;
+ while (anchor < islands.length && rowOf(anchor) < to) {
+ const row = rowOf(anchor);
+ if (row > cursor) items.push({ from: cursor, to: row });
+ items.push({ from: row, to: row, reserve: String(islands[anchor].id) });
+ cursor = row;
+ anchor += 1;
+ }
+ if (to > cursor) items.push({ from: cursor, to });
+ covered = to;
+ }
+ for (; anchor < islands.length; anchor += 1)
+ items.push({
+ from: covered,
+ to: covered,
+ reserve: String(islands[anchor].id),
+ });
+ items.push({
+ from: covered,
+ to: Math.max(covered, total),
+ reserve: TAIL_RESERVE,
+ });
+ return items;
+};
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts b/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts
index 1cbd4cc0e2f..faf3cb16f16 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts
+++ b/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts
@@ -3,7 +3,8 @@
import type { ReasoningReadingAnchor } from "./reasoning-transcript-index.ts";
-const passages = "p, pre, li, h1, h2, h3, h4, h5, h6, td, th";
+const passages =
+ "p, pre, .aui-reasoning-code-lines, li, h1, h2, h3, h4, h5, h6, td, th";
function textNodes(root: Element): Text[] {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
@@ -19,6 +20,7 @@ export function reasoningTextRange(
root: Element,
text: string,
occurrence = 0,
+ range: Range = document.createRange(),
): Range | null {
const nodes = textNodes(root);
const source = nodes.map((node) => node.data).join("");
@@ -27,7 +29,6 @@ export function reasoningTextRange(
start = source.indexOf(text, start + 1);
if (start < 0) return null;
}
- const range = document.createRange();
let offset = 0;
let started = false;
for (const node of nodes) {
@@ -44,6 +45,8 @@ export function reasoningTextRange(
return null;
}
+let probe: Range | null = null;
+
/** Capture the first visible character, including when its block starts above the viewport. */
export function captureReasoningAnchor(
root: Element,
@@ -51,9 +54,9 @@ export function captureReasoningAnchor(
): ReasoningReadingAnchor | undefined {
const bounds = viewport.getBoundingClientRect();
const nodes = textNodes(root);
+ const range = (probe ??= document.createRange());
let preceding = "";
for (const node of nodes) {
- const range = document.createRange();
range.selectNodeContents(node);
const rect = range.getBoundingClientRect();
if (
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-row-containment-mode.ts b/studio/frontend/src/components/assistant-ui/reasoning-row-containment-mode.ts
new file mode 100644
index 00000000000..cea450c6227
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reasoning-row-containment-mode.ts
@@ -0,0 +1,21 @@
+// 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 ContainmentMode,
+ defineContainmentFlag,
+} from "./containment-flag.ts";
+
+export type ReasoningRowContainmentMode = ContainmentMode;
+
+export const REASONING_ROW_CONTAINMENT = defineContainmentFlag({
+ attribute: "data-reasoning-row-containment",
+ global: "__UNSLOTH_REASONING_ROW_CONTAINMENT__",
+});
+
+export const REASONING_ROW_CONTAINMENT_ATTRIBUTE =
+ REASONING_ROW_CONTAINMENT.attribute;
+export const REASONING_ROW_CONTAINMENT_ON = REASONING_ROW_CONTAINMENT.on;
+export const SHIP_DEFAULT = REASONING_ROW_CONTAINMENT.shipDefault;
+export const ROW_SETTLED_ATTRIBUTE = "data-settled";
+export const CHUNK_ESTIMATE_PROPERTY = "--unsloth-chunk-estimate";
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-row-containment.ts b/studio/frontend/src/components/assistant-ui/reasoning-row-containment.ts
new file mode 100644
index 00000000000..1ff708f3565
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reasoning-row-containment.ts
@@ -0,0 +1,46 @@
+// 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 { engineFindsSkippedContent } from "./math-block-containment";
+import {
+ REASONING_ROW_CONTAINMENT,
+ type ReasoningRowContainmentMode,
+} from "./reasoning-row-containment-mode";
+
+const readBuildFlag = (): string => {
+ try {
+ return import.meta.env.VITE_UNSLOTH_REASONING_ROW_CONTAINMENT ?? "";
+ } catch {
+ return "";
+ }
+};
+
+const runtimeFlag = (): unknown =>
+ (globalThis as Record<string, unknown>)[REASONING_ROW_CONTAINMENT.global];
+
+export const applyReasoningRowContainment = (
+ root: Element | null = typeof document === "undefined"
+ ? null
+ : document.documentElement,
+): ReasoningRowContainmentMode => {
+ const mode = REASONING_ROW_CONTAINMENT.mode(
+ runtimeFlag(),
+ readBuildFlag(),
+ engineFindsSkippedContent(),
+ );
+ if (!root) return mode;
+ if (mode === "contain") {
+ root.setAttribute(
+ REASONING_ROW_CONTAINMENT.attribute,
+ REASONING_ROW_CONTAINMENT.on,
+ );
+ } else {
+ root.removeAttribute(REASONING_ROW_CONTAINMENT.attribute);
+ }
+ return mode;
+};
+
+export const watchReasoningRowContainmentOverride = (
+ scope: Record<string, unknown> = globalThis as Record<string, unknown>,
+ apply: () => ReasoningRowContainmentMode = applyReasoningRowContainment,
+): boolean => REASONING_ROW_CONTAINMENT.installWatcher(scope, apply);
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-settle-queue.ts b/studio/frontend/src/components/assistant-ui/reasoning-settle-queue.ts
new file mode 100644
index 00000000000..1ee8218e90f
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reasoning-settle-queue.ts
@@ -0,0 +1,72 @@
+// 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 type SettleQueue<T> = {
+ add: (row: T) => void;
+ forget: (row: T) => void;
+};
+
+export const createRemeasureQueue = <T>(
+ frame: (callback: () => void) => void,
+ remeasure: (row: T) => void,
+ paused: () => boolean,
+): SettleQueue<T> => {
+ const queued = new Set<T>();
+ let scheduled = false;
+ const run = (): void => {
+ scheduled = false;
+ const next = queued.values().next();
+ if (!next.done && !paused()) {
+ queued.delete(next.value);
+ remeasure(next.value);
+ }
+ if (queued.size !== 0) schedule();
+ };
+ const schedule = (): void => {
+ if (scheduled) return;
+ scheduled = true;
+ frame(run);
+ };
+ return {
+ add: (row) => {
+ queued.add(row);
+ schedule();
+ },
+ forget: (row) => {
+ queued.delete(row);
+ },
+ };
+};
+
+export const createSettleQueue = <T>(
+ frame: (callback: () => void) => void,
+ settle: (row: T) => void,
+): SettleQueue<T> => {
+ let queued = new Set<T>();
+ let ripe = new Set<T>();
+ let scheduled = false;
+ const run = (): void => {
+ scheduled = false;
+ const due = ripe;
+ ripe = queued;
+ queued = new Set();
+ for (const row of due) settle(row);
+ if (ripe.size !== 0) schedule();
+ };
+ const schedule = (): void => {
+ if (scheduled) return;
+ scheduled = true;
+ frame(run);
+ };
+ return {
+ add: (row) => {
+ ripe.delete(row);
+ queued.add(row);
+ schedule();
+ },
+ forget: (row) => {
+ queued.delete(row);
+ ripe.delete(row);
+ },
+ };
+};
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts b/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts
index cfeeb9da66d..d969d8e532b 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts
+++ b/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts
@@ -9,7 +9,9 @@ import { math } from "micromark-extension-math";
import remend from "remend";
import type { Definition, RootContent } from "mdast";
import { markdownBlockFallback } from "./markdown-block-fallback.ts";
+import { ownString } from "./own-string.ts";
import { ReasoningCodeIndex } from "./reasoning-code-index.ts";
+import { hasPrefix } from "./streaming-render-schedule.ts";
export const REASONING_TRANSCRIPT_THRESHOLD = 16_384;
export const REASONING_FRAGMENT_CHARACTERS = 8_192;
@@ -312,7 +314,7 @@ class DocumentIndex {
update(source: string): void {
if (source === this.source) return;
- if (!source.startsWith(this.source)) {
+ if (!hasPrefix(source, this.source)) {
this.committed = [];
this.offset = 0;
this.fence = null;
@@ -359,6 +361,7 @@ class DocumentIndex {
pending.push(block);
break;
}
+ block.text = ownString(block.text);
this.committed.push(block);
this.offset = end;
this.fence = null;
@@ -398,7 +401,7 @@ class DocumentIndex {
this.committed.push({
start: this.offset,
end: this.offset + lastStart,
- text: tail.slice(0, lastStart),
+ text: ownString(tail.slice(0, lastStart)),
continued: this.continued,
prefix: this.prefix,
listContinuationDepth: this.listContinuationDepth,
@@ -420,7 +423,7 @@ class DocumentIndex {
this.committed.push({
start: this.offset + start,
end: this.offset + stop,
- text: tail.slice(start, stop),
+ text: ownString(tail.slice(start, stop)),
continued: n === 0 && this.continued,
prefix: n === 0 ? this.prefix : "",
listContinuationDepth: n === 0 ? this.listContinuationDepth : 0,
@@ -445,7 +448,7 @@ class DocumentIndex {
this.committed.push({
start: this.offset,
end: this.offset + cut,
- text: tail.slice(0, cut),
+ text: ownString(tail.slice(0, cut)),
continued: this.continued,
prefix: this.prefix,
listContinuationDepth: this.listContinuationDepth,
@@ -512,6 +515,7 @@ function fragmentsOf(
/** Stored Markdown documents never share fence or paragraph state. */
export class ReasoningTranscriptIndex {
+ generation = 0;
private documents: DocumentIndex[] = [];
private fragments = new WeakMap<
Block,
@@ -524,10 +528,13 @@ export class ReasoningTranscriptIndex {
>();
update(sources: readonly string[]): ReasoningFragment[] {
+ if (sources.length < this.documents.length) this.generation += 1;
this.documents.length = sources.length;
return sources.flatMap((source, document) => {
const index = (this.documents[document] ??= new DocumentIndex());
+ const generation = index.generation;
index.update(source);
+ if (index.generation !== generation) this.generation += 1;
return index.blocks.flatMap((block) => {
// Preview-capable fences retain the established renderer and its settings.
// Ordinary code keeps the same incremental renderer and scroll geometry.
@@ -598,3 +605,23 @@ export class ReasoningTranscriptIndex {
});
}
}
+
+const INDEX_CACHE_ENTRIES = 8;
+const indices = new Map<string, ReasoningTranscriptIndex>();
+
+export function cachedReasoningTranscriptIndex(
+ key: string,
+): ReasoningTranscriptIndex {
+ const known = indices.get(key);
+ if (known !== undefined) {
+ indices.delete(key);
+ indices.set(key, known);
+ return known;
+ }
+ const index = new ReasoningTranscriptIndex();
+ indices.set(key, index);
+ if (indices.size > INDEX_CACHE_ENTRIES) {
+ indices.delete(indices.keys().next().value as string);
+ }
+ return index;
+}
diff --git a/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx
index 6a65a868309..0130be08c22 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx
@@ -2,14 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
- defaultRangeExtractor,
- observeElementOffset,
- useVirtualizer,
- type VirtualItem,
-} from "@tanstack/react-virtual";
-import {
- Fragment as InlineFragment,
+ Component,
+ type CSSProperties,
memo,
+ startTransition,
useCallback,
useEffect,
useLayoutEffect,
@@ -23,13 +19,12 @@ import {
MarkdownTextSource,
SearchImagesEnabledContext,
} from "./markdown-text";
+import { CodeHighlightModeContext } from "./code-highlight-context";
import { FenceLine } from "./code-fence-defer";
+import { clipLineTokens, type TokenLine } from "./reasoning-code-colour";
+import { useThinkingCodeColour } from "./use-thinking-code-colour";
import {
- useReasoningHighlight,
- type ReasoningLineTokens,
-} from "./use-reasoning-highlight";
-import {
- ReasoningTranscriptIndex,
+ cachedReasoningTranscriptIndex,
resolveReasoningAnchor,
type ReasoningReadingAnchor,
type ReasoningFragment,
@@ -42,14 +37,52 @@ import {
useAdjustForContentInsertedAbove,
useDetachThreadFromBottom,
} from "./use-intent-aware-autoscroll";
+import {
+ addIsland,
+ anchorAtSamePlace,
+ buildChunkGrid,
+ chunkEndAt,
+ chunkPieces,
+ chunkStartAt,
+ type ChunkPiece,
+ type ChunkSlice,
+ closedChunkUnchanged,
+ estimateFragmentHeights,
+ type FragmentGeometry,
+ frameBudget,
+ INITIAL_VIEWPORTS,
+ initialRows,
+ isCovered,
+ type Island,
+ mountPlan,
+ NO_ISLANDS,
+ WIDEN_CHARACTERS_PER_FRAME,
+ WIDEN_FRAGMENTS_PER_FRAME,
+ widenBudget,
+} from "./reasoning-mount-controller";
+import {
+ CHUNK_ESTIMATE_PROPERTY,
+ ROW_SETTLED_ATTRIBUTE,
+} from "./reasoning-row-containment-mode";
+import { createRemeasureQueue, createSettleQueue } from "./reasoning-settle-queue";
+import { hasPendingProgressiveMounts } from "./progressive-messages";
+import { panelDragInProgress } from "@/components/ui/panel-drag-overlay";
import { cn } from "@/lib/utils";
// Twice the live box's tallest cap (18rem in reasoning.tsx).
const BOUNDED_TAIL_PX = 576;
+type Reserve = { element: HTMLDivElement; from: number; to: number };
+type Reading = ReasoningReadingAnchor & {
+ key: string;
+ row: Element;
+ offset: number;
+};
+
type Props = {
initialAnchor?: ReasoningReadingAnchor;
documents: readonly string[];
+ indexKey: string;
messageId: string;
messageHasRenderableRenderHtmlTool: boolean;
streaming: boolean;
@@ -57,90 +90,232 @@ type Props = {
bounded?: boolean;
};
-const CodeFragment = memo(
- function CodeFragment({
- fragment,
- result,
- }: { fragment: ReasoningFragment; result: ReasoningLineTokens }) {
- const code = fragment.code!;
- return (
- <>
- {code.lines.map(({ line, column, text }) => {
- const tokens = result.get(line);
- // A delayed grammar must never display the previous, shorter source.
- if (
- !tokens ||
- tokens
- .map((token) => token.content)
- .join("")
- .slice(column, column + text.length) !== text
- ) {
- return (
- <InlineFragment key={`${line}:${column}`}>
- {column === 0 && line > 0 ? "\n" : ""}
- {text}
- </InlineFragment>
- );
- }
- let offset = 0;
- const clipped = tokens.flatMap((token) => {
- const start = offset;
- offset += token.content.length;
- const content = token.content.slice(
- Math.max(0, column - start),
- Math.max(
- 0,
- Math.min(token.content.length, column + text.length - start),
- ),
- );
- return content ? [{ ...token, content }] : [];
- });
- return (
- <InlineFragment key={`${line}:${column}`}>
- {column === 0 && line > 0 ? "\n" : ""}
- <FenceLine line={clipped} windowed inline />
- </InlineFragment>
- );
- })}
- </>
- );
+const hiddenTranscripts = new WeakSet<Element>();
+const blindTranscripts = new WeakSet<Element>();
+const rowRemeasurers = new WeakMap<Element, (row: HTMLElement) => void>();
+const withoutIdleCallback =
+ typeof window !== "undefined" &&
+ typeof window.requestIdleCallback !== "function";
+
+const settleQueue = createSettleQueue<HTMLElement>(
+ (callback) => requestAnimationFrame(callback),
+ (row) => {
+ if (!row.isConnected) return;
+ row.setAttribute(ROW_SETTLED_ATTRIBUTE, "");
+ const transcript = row.parentElement;
+ if (transcript && hiddenTranscripts.has(transcript))
+ blindTranscripts.add(transcript);
},
- (previous, next) => {
- // Appending later lines cannot change this fragment's grammar or text. Keep its
- // highlighted subtree and selection alive instead of repainting it for every token.
- const a = previous.fragment;
- const b = next.fragment;
- return (
- a.key === b.key &&
- a.text === b.text &&
- a.first === b.first &&
- a.last === b.last &&
- a.code?.language === b.code?.language &&
- previous.result.get(a.code!.lines[0].line) ===
- next.result.get(b.code!.lines[0].line)
- );
+);
+
+const remeasureQueue = createRemeasureQueue<HTMLElement>(
+ (callback) => requestAnimationFrame(callback),
+ (row) => {
+ if (!row.isConnected) return;
+ if (row.parentElement) rowRemeasurers.get(row.parentElement)?.(row);
},
+ panelDragInProgress,
);
-type RowProps = {
- item: VirtualItem;
- fragment: ReasoningFragment;
- top: number;
- measure: (element: HTMLElement | null) => void;
+const resettleRows = (root: HTMLElement): void => {
+ for (const row of root.querySelectorAll<HTMLElement>(
+ `[${ROW_SETTLED_ATTRIBUTE}]`,
+ )) {
+ remeasureQueue.add(row);
+ }
+};
+
+type Spent = { characters: number; rows: number };
+type Widener = (characters: number, rows: number) => Spent | null;
+
+const NOTHING_SPENT: Spent = { characters: 0, rows: 0 };
+const wideners = new Set<Widener>();
+let widenFrame = 0;
+const WIDEN_COMMIT_TARGET_MS = 16;
+const MIN_WIDEN_SCALE = 1 / 8;
+let widenScale = 1;
+let commitStartedAt = 0;
+let widenCommitMs = 0;
+
+const widenAll = (): void => {
+ widenFrame = 0;
+ if (widenCommitMs > 0) {
+ widenScale = Math.min(
+ 1,
+ Math.max(
+ MIN_WIDEN_SCALE,
+ widenScale * Math.min(2, WIDEN_COMMIT_TARGET_MS / widenCommitMs),
+ ),
+ );
+ widenCommitMs = 0;
+ }
+ let characters = Math.ceil(WIDEN_CHARACTERS_PER_FRAME * widenScale);
+ let rows = Math.ceil(WIDEN_FRAGMENTS_PER_FRAME * widenScale);
+ const pending = [...wideners];
+ for (let at = 0; at < pending.length; at += 1) {
+ if (characters <= 0 || rows <= 0) break;
+ const remaining = pending.length - at;
+ const widen = pending[at];
+ const spent = widen(
+ Math.ceil(characters / remaining),
+ Math.ceil(rows / remaining),
+ );
+ if (spent === null) wideners.delete(widen);
+ else {
+ characters -= spent.characters;
+ rows -= spent.rows;
+ }
+ }
+ if (wideners.size > 0) widenFrame = requestAnimationFrame(widenAll);
+};
+
+const requestWiden = (widen: Widener): void => {
+ wideners.add(widen);
+ if (widenFrame === 0) widenFrame = requestAnimationFrame(widenAll);
+};
+
+const cancelWiden = (widen: Widener): void => {
+ wideners.delete(widen);
+};
+
+const RESETTLE_DELAY_MS = 150;
+const STARVED_MS = 200;
+const SHIFT_EPSILON_PX = 0.5;
+
+let passageRange: Range | null = null;
+
+const printers = new Set<() => void>();
+
+const printTranscripts = (): void => {
+ flushSync(() => {
+ for (const print of printers) print();
+ });
+};
+
+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
+ window.addEventListener("beforeprint", printTranscripts, { capture: true });
+ window.matchMedia?.("print")?.addEventListener?.(
+ "change",
+ (event) => {
+ if (event.matches) printTranscripts();
+ },
+ { capture: true },
+ );
+}
+
+class CommitBounds extends Component<{
+ before: () => void;
+ after: () => void;
children: React.ReactNode;
+}> {
+ getSnapshotBeforeUpdate() {
+ this.props.before();
+ return null;
+ }
+ componentDidUpdate() {
+ this.props.after();
+ }
+ render() {
+ return this.props.children;
+ }
+}
+
+function useSettledRow(
+ row: React.RefObject<HTMLElement | null>,
+ active: boolean,
+): void {
+ useLayoutEffect(() => {
+ const element = row.current;
+ if (!element || !active) return;
+ settleQueue.add(element);
+ const changed = new MutationObserver(() => {
+ if (!element.hasAttribute(ROW_SETTLED_ATTRIBUTE)) settleQueue.add(element);
+ });
+ changed.observe(element, {
+ subtree: true,
+ childList: true,
+ characterData: true,
+ });
+ return () => {
+ changed.disconnect();
+ remeasureQueue.forget(element);
+ settleQueue.forget(element);
+ };
+ }, [row, active]);
+}
+
+const codeRowText = (
+ fragment: ReasoningFragment,
+ leading: boolean,
+): string[] => {
+ const nodes: string[] = [];
+ for (const [at, { line, column, text }] of fragment.code!.lines.entries()) {
+ if (column === 0 && line > 0 && !(leading && at === 0)) nodes.push("\n");
+ if (text !== "") nodes.push(text);
+ }
+ return nodes;
};
-function Row({ item, fragment, top, measure, children }: RowProps) {
+const colouredRow = (
+ fragment: ReasoningFragment,
+ leading: boolean,
+ tokens: readonly TokenLine[],
+): React.ReactNode[] => {
+ const nodes: React.ReactNode[] = [];
+ for (const [at, { line, column, text }] of fragment.code!.lines.entries()) {
+ if (column === 0 && line > 0 && !(leading && at === 0)) nodes.push("\n");
+ if (text === "") continue;
+ const clipped = clipLineTokens(tokens[line], column, text);
+ nodes.push(
+ clipped === null ? (
+ text
+ ) : (
+ <FenceLine key={`${line}:${column}`} line={clipped} windowed inline />
+ ),
+ );
+ }
+ return nodes;
+};
+
+const CodeRow = memo(function CodeRow({
+ index,
+ fragment,
+ leading,
+ tokens,
+}: {
+ index: number;
+ fragment: ReasoningFragment;
+ leading: boolean;
+ tokens: readonly TokenLine[] | null;
+}) {
+ return (
+ <span
+ data-index={index}
+ data-reasoning-fragment={fragment.key}
+ data-reasoning-code-row=""
+ >
+ {tokens === null
+ ? codeRowText(fragment, leading)
+ : colouredRow(fragment, leading, tokens)}
+ </span>
+ );
+});
+
+function Row({
+ index,
+ fragment,
+ children,
+}: {
+ index: number;
+ fragment: ReasoningFragment;
+ children: React.ReactNode;
+}) {
+ if (fragment.hidden) return null;
return (
<div
- ref={measure}
- data-index={item.index}
+ data-index={index}
data-reasoning-fragment={fragment.key}
- className="absolute top-0 left-0 w-full min-w-0"
- style={{
- transform: `translateY(${item.start - top}px)`,
- contain: "layout style",
- }}
+ className="min-w-0"
>
{children}
</div>
@@ -148,62 +323,44 @@ function Row({ item, fragment, top, measure, children }: RowProps) {
}
function CodeGroup({
- items,
+ indices,
fragments,
- top,
- measure,
streaming,
}: {
- items: VirtualItem[];
- fragments: ReasoningFragment[];
- top: number;
- measure: RowProps["measure"];
+ indices: number[];
+ fragments: readonly ReasoningFragment[];
streaming: boolean;
}) {
+ const code = fragments[indices[0]].code!;
+ const first = fragments[indices[0]];
+ const last = fragments[indices[indices.length - 1]];
const surface = useRef<HTMLDivElement>(null);
- useLayoutEffect(() => {
- const element = surface.current;
- if (!element) return;
- // ResizeObserver does not report inline span geometry. Observe their shared
- // formatting surface and feed each bounded row's measured contribution back.
- const observer = new ResizeObserver(() => {
- for (const row of element.querySelectorAll<HTMLElement>(
- "[data-reasoning-code-row]",
- ))
- measure(row);
- });
- observer.observe(element);
- return () => observer.disconnect();
- }, [measure]);
- const code = fragments[items[0].index].code!;
- // One highlighter subscription per visible fence, with its complete grammar context.
- const lines = [
- ...new Set(
- items.flatMap((item) =>
- fragments[item.index].code!.lines.map((line) => line.line),
- ),
- ),
- ];
- const result = useReasoningHighlight(code.source, code.language, lines);
- const first = fragments[items[0].index];
- const last = fragments[items.at(-1)!.index];
+ const colour = useThinkingCodeColour(
+ surface,
+ code.source,
+ code.language,
+ // A trace that stopped inside a fence never closes it; it is still finished.
+ !code.incomplete || !streaming,
+ );
+ const breaksAfter =
+ !last.last &&
+ fragments[indices[indices.length - 1] + 1]?.code?.lines[0]?.column === 0;
return (
<div
ref={surface}
data-slot="reasoning-code-fragment"
data-language={code.language ?? undefined}
className={cn(
- "aui-reasoning-code-fragment absolute top-0 left-0 w-full min-w-0",
+ "aui-reasoning-code-fragment relative isolate min-w-0",
first.first && "aui-reasoning-code-first",
last.last && "aui-reasoning-code-last",
)}
- style={{ transform: `translateY(${items[0].start - top}px)` }}
>
{first.first && (
<CodeBlockActions
- disabled={streaming && code.incomplete}
+ disabled={streaming}
language={code.language}
- source={code.source}
+ source={() => code.source}
/>
)}
{first.first && (
@@ -211,33 +368,20 @@ function CodeGroup({
{code.language}
</div>
)}
- <pre className="!m-0 min-h-[1lh] whitespace-pre-wrap [overflow-wrap:anywhere] font-mono">
+ <div className="aui-reasoning-code-lines !m-0 min-h-[1lh] whitespace-pre-wrap [overflow-wrap:anywhere] font-mono">
<code>
- {items.map((item, i) => (
- <InlineFragment key={item.key}>
- {i > 0 && items[i - 1].index + 1 !== item.index && (
- <span
- aria-hidden="true"
- data-reasoning-code-gap=""
- className="block"
- style={{ height: Math.max(0, item.start - items[i - 1].end) }}
- />
- )}
- <span
- ref={measure}
- data-index={item.index}
- data-reasoning-fragment={fragments[item.index].key}
- data-reasoning-code-row=""
- >
- <CodeFragment
- fragment={fragments[item.index]}
- result={result}
- />
- </span>
- </InlineFragment>
+ {indices.map((index, at) => (
+ <CodeRow
+ key={fragments[index].key}
+ index={index}
+ fragment={fragments[index]}
+ leading={at === 0}
+ tokens={colour?.tokens ?? null}
+ />
))}
+ {breaksAfter && "\n"}
</code>
- </pre>
+ </div>
</div>
);
}
@@ -247,7 +391,7 @@ const Fragment = memo(function Fragment({
messageId,
messageHasRenderableRenderHtmlTool,
streaming,
-}: Omit<Props, "documents"> & { fragment: ReasoningFragment }) {
+}: Omit<Props, "documents" | "indexKey"> & { fragment: ReasoningFragment }) {
const root = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
// Continuation containers preserve indentation/numbering but must not paint
@@ -293,6 +437,106 @@ const Fragment = memo(function Fragment({
);
});
+type ChunkProps = {
+ slices: readonly ChunkSlice[];
+ fragments: readonly ReasoningFragment[];
+ closed: boolean;
+ estimate: number;
+ messageId: string;
+ messageHasRenderableRenderHtmlTool: boolean;
+};
+
+const Chunk = memo(function Chunk({
+ slices,
+ fragments,
+ closed,
+ estimate,
+ messageId,
+ messageHasRenderableRenderHtmlTool,
+}: ChunkProps) {
+ const box = useRef<HTMLDivElement>(null);
+ useSettledRow(box, closed);
+ return (
+ <div
+ ref={box}
+ data-reasoning-chunk=""
+ className="min-w-0"
+ style={{ [CHUNK_ESTIMATE_PROPERTY]: `${estimate}px` } as CSSProperties}
+ >
+ {slices.map(({ key, code, first, end, streaming }) => {
+ if (code) {
+ const indices: number[] = [];
+ for (let i = first; i < end; i += 1) indices.push(i);
+ return (
+ <CodeGroup
+ key={key}
+ indices={indices}
+ fragments={fragments}
+ streaming={streaming}
+ />
+ );
+ }
+ const fragment = fragments[first];
+ return (
+ <Row key={key} index={first} fragment={fragment}>
+ <Fragment
+ fragment={fragment}
+ messageId={messageId}
+ messageHasRenderableRenderHtmlTool={
+ messageHasRenderableRenderHtmlTool
+ }
+ streaming={streaming}
+ />
+ </Row>
+ );
+ })}
+ </div>
+ );
+}, closedChunkUnchanged);
+
+const DEFAULT_GEOMETRY: FragmentGeometry = {
+ width: 640,
+ lineHeight: 24,
+ fontPixels: 15,
+ codeLineHeight: 19,
+ codeFontPixels: 12,
+ codeFooter: 12,
+};
+
+const measureGeometry = (
+ element: HTMLElement,
+ codeProbe: HTMLElement | null,
+): FragmentGeometry | null => {
+ const width = element.getBoundingClientRect().width;
+ if (!width) return null;
+ const style = getComputedStyle(element);
+ const lines = codeProbe?.firstElementChild;
+ const code = lines ? getComputedStyle(lines) : null;
+ const footer = codeProbe ? getComputedStyle(codeProbe) : null;
+ return {
+ width,
+ lineHeight: Number.parseFloat(style.lineHeight) || DEFAULT_GEOMETRY.lineHeight,
+ fontPixels: Number.parseFloat(style.fontSize) || DEFAULT_GEOMETRY.fontPixels,
+ codeLineHeight:
+ Number.parseFloat(code?.lineHeight ?? "") || DEFAULT_GEOMETRY.codeLineHeight,
+ codeFontPixels:
+ Number.parseFloat(code?.fontSize ?? "") || DEFAULT_GEOMETRY.codeFontPixels,
+ codeFooter: footer
+ ? (Number.parseFloat(footer.paddingBottom) || 0) +
+ (Number.parseFloat(footer.borderBottomWidth) || 0)
+ : DEFAULT_GEOMETRY.codeFooter,
+ };
+};
+
+const keepGeometry =
+ (next: FragmentGeometry) =>
+ (old: FragmentGeometry): FragmentGeometry =>
+ (Object.keys(next) as (keyof FragmentGeometry)[]).every(
+ (key) => old[key] === next[key],
+ )
+ ? old
+ : next;
+
// IntersectionObserver reports after paint; this catches jumps past its margin before paint.
const jumpWatchers = new WeakMap<
HTMLElement,
@@ -331,221 +575,516 @@ function onViewportJump(scroll: HTMLElement, check: () => void): () => void {
export function ReasoningTranscript({
initialAnchor,
documents,
+ indexKey,
messageId,
messageHasRenderableRenderHtmlTool,
streaming,
bounded = false,
}: Props) {
const root = useRef<HTMLDivElement>(null);
+ const codeProbe = useRef<HTMLDivElement>(null);
+ const [index] = useState(() => cachedReasoningTranscriptIndex(indexKey));
// Over a screen away, a transcript stops listening to the shared viewport's scroll (#12025).
const nearby = useRef(true);
- const followOffset = useRef<((on: boolean, park?: number) => void) | null>(
- null,
- );
- const [index] = useState(() => new ReasoningTranscriptIndex());
const fragments = useMemo(() => index.update(documents), [documents, index]);
- const [anchor, setAnchor] = useState(
- () => initialAnchor && resolveReasoningAnchor(fragments, initialAnchor),
+ const fragmentsRef = useRef(fragments);
+ const [geometry, setGeometry] = useState(DEFAULT_GEOMETRY);
+ const estimates = useMemo(
+ () => estimateFragmentHeights(fragments, geometry),
+ [fragments, geometry],
+ );
+ const grid = useMemo(
+ () => buildChunkGrid(fragments, estimates),
+ [fragments, estimates],
);
- const [anchoring, setAnchoring] = useState(
- Boolean(anchor && anchor.index >= 0),
+ const [restore, setRestore] = useState(() => {
+ const anchor =
+ initialAnchor && resolveReasoningAnchor(fragments, initialAnchor);
+ return anchor && anchor.index >= 0 ? anchor : null;
+ });
+ const origin = `${index.generation}:${fragments[0]?.key ?? ""}`;
+ const originRef = useRef(origin);
+ const [mount, setMount] = useState(() => {
+ const rows = chunkEndAt(
+ grid,
+ initialRows(
+ estimates,
+ INITIAL_VIEWPORTS * (typeof window === "undefined" ? 900 : window.innerHeight),
+ restore?.index ?? -1,
+ fragments.map((fragment) => fragment.text.length),
+ ),
+ );
+ return {
+ origin,
+ limit: isCovered(rows, fragments.length) ? Number.POSITIVE_INFINITY : rows,
+ };
+ });
+ if (mount.origin !== origin) {
+ const value = chunkEndAt(
+ grid,
+ initialRows(
+ estimates,
+ INITIAL_VIEWPORTS * window.innerHeight,
+ -1,
+ fragments.map((fragment) => fragment.text.length),
+ ),
+ );
+ setMount({
+ origin,
+ limit: isCovered(value, fragments.length) ? Number.POSITIVE_INFINITY : value,
+ });
+ }
+ const limit = mount.limit;
+ const setLimit = useCallback((value: number) => {
+ setMount({ origin: originRef.current, limit: value });
+ }, []);
+ const limitRef = useRef(limit);
+ const committedRef = useRef(limit);
+ const streamingRef = useRef(streaming);
+ const estimatesRef = useRef(estimates);
+ const gridRef = useRef(grid);
+ const [islandState, setIslandState] = useState<{
+ origin: string;
+ list: readonly Island[];
+ }>(() => ({ origin, list: NO_ISLANDS }));
+ const islands = islandState.origin === origin ? islandState.list : NO_ISLANDS;
+ const setIslands = useCallback((list: readonly Island[]) => {
+ setIslandState({ origin: originRef.current, list });
+ }, []);
+ const islandsRef = useRef<readonly Island[]>(NO_ISLANDS);
+ const mountedIslands = useRef<readonly Island[]>(NO_ISLANDS);
+ const recapture = useRef<(fresh?: boolean) => void>(() => {});
+ const carry = useRef<(previous: readonly ReasoningFragment[]) => boolean>(
+ () => false,
);
- const [geometry, setGeometry] = useState({
- top: 0,
- width: 640,
- lineHeight: 24,
- fontPixels: 15,
+ const demandNow = useRef<() => void>(() => {});
+ const requestedAt = useRef(0);
+ const reserves = useRef(new Map<string, Reserve>());
+ const commitEdge = useRef({ before: () => {}, after: () => {} });
+ const beforeCommit = useCallback(() => {
+ commitStartedAt = performance.now();
+ commitEdge.current.before();
+ }, []);
+ const afterCommit = useCallback(() => commitEdge.current.after(), []);
+ const mountedAt = useRef(0);
+ useLayoutEffect(() => {
+ mountedAt.current = performance.now();
+ }, []);
+ useLayoutEffect(() => {
+ const previous = fragmentsRef.current;
+ fragmentsRef.current = fragments;
+ streamingRef.current = streaming;
+ boundedRef.current = bounded;
+ estimatesRef.current = estimates;
+ gridRef.current = grid;
+ const restarted = originRef.current !== origin;
+ if (restarted) {
+ originRef.current = origin;
+ mountedAt.current = performance.now();
+ islandsRef.current = NO_ISLANDS;
+ limitRef.current = limit;
+ }
+ const grew = committedRef.current !== limit;
+ committedRef.current = limit;
+ if (limit > limitRef.current) limitRef.current = limit;
+ const carried = restarted && carry.current(previous);
+ if (grew || mountedIslands.current !== islands) {
+ mountedIslands.current = islands;
+ if (!carried) recapture.current();
+ }
+ if (grew && withoutIdleCallback)
+ widenCommitMs = Math.max(widenCommitMs, performance.now() - commitStartedAt);
+ if (restarted && !carried) demandNow.current();
});
- const [protectedKeys, setProtectedKeys] = useState<Set<string>>(
- () => new Set(),
+ useEffect(() => {
+ const print = () => {
+ const value = Number.POSITIVE_INFINITY;
+ if (committedRef.current === value) return;
+ limitRef.current = value;
+ setLimit(value);
+ };
+ printers.add(print);
+ return () => {
+ printers.delete(print);
+ };
+ }, [setLimit]);
+ const adjustThread = useAdjustForContentInsertedAbove();
+ const boundedRef = useRef(bounded);
+ // Rows grow upward inside the live tail box: no thread correction applies.
+ const adjustAbove = useCallback(
+ (delta: number) => !boundedRef.current && adjustThread(delta),
+ [adjustThread],
);
- const adjustAbove = useAdjustForContentInsertedAbove();
const detach = useDetachThreadFromBottom();
- const viewport = useCallback(
- () => root.current?.closest<HTMLDivElement>(".aui-thread-viewport") ?? null,
- [],
- );
+ const covered = isCovered(limit, fragments.length);
- const virtualizer = useVirtualizer<HTMLDivElement, HTMLElement>({
- count: fragments.length,
- getScrollElement: viewport,
- getItemKey: (i) => fragments[i].key,
- scrollMargin: geometry.top,
- initialOffset: () => viewport()?.scrollTop ?? 0,
- observeElementOffset: (instance, callback) => {
- let stop: (() => void) | undefined;
- let generation = 0;
- const follow = (on: boolean, park?: number) => {
- stop?.();
- stop = undefined;
- // TanStack's scroll-end debounce outlives its unsubscribe: drop a stopped one's call.
- const current = ++generation;
- if (!on) {
- // A frozen offset can land mid-transcript once content above moves, mounting
- // rows a live offset never would. Park it where the live one keeps the range.
- if (park !== undefined) callback(park, false);
- return;
- }
- // Seed the live offset, else TanStack keeps its initial zero or the one from before it left.
- callback(instance.scrollElement?.scrollTop ?? 0, false);
- stop = observeElementOffset(instance, (offset, isScrolling) => {
- if (current === generation) callback(offset, isScrolling);
- });
- };
- followOffset.current = follow;
- follow(nearby.current);
- return () => {
- if (followOffset.current === follow) followOffset.current = null;
- stop?.();
- };
- },
- overscan: 2,
- measureElement: (element) => {
- if (!element.hasAttribute("data-reasoning-code-row"))
- return element.getBoundingClientRect().height;
- const surface = element.closest<HTMLElement>(
- '[data-slot="reasoning-code-fragment"]',
- )!;
- const previous = element.previousElementSibling;
- const bottom = element.nextElementSibling
- ? element.getBoundingClientRect().bottom
- : surface.getBoundingClientRect().bottom;
- const top = previous
- ? previous.getBoundingClientRect().bottom
- : surface.getBoundingClientRect().top;
- const margin = previous
- ? 0
- : Number.parseFloat(getComputedStyle(surface).marginTop) || 0;
- return Math.max(0, bottom - top + margin);
- },
- estimateSize: (i) => {
- const fragment = fragments[i];
- if (fragment.hidden) return 0;
- const code = fragment.code;
- const columns = Math.max(
- 12,
- Math.floor(
- (geometry.width - (code ? 32 : 0)) /
- (geometry.fontPixels * (code ? 0.58 : 0.48)),
- ),
- );
- const lines = fragment.text
- .split("\n")
- .reduce(
- (sum, line) => sum + Math.max(1, Math.ceil(line.length / columns)),
- 0,
- );
- return code
- ? lines * geometry.lineHeight +
- (fragment.first ? 40 : 0) +
- (fragment.last ? 16 : 0)
- : Math.max(1, lines - 2) * geometry.lineHeight +
- (fragment.first ? 16 : 0);
- },
- rangeExtractor: (range) => {
- const mounted = new Set(defaultRangeExtractor(range));
- if (anchoring && anchor) mounted.add(anchor.index);
- if (protectedKeys.size)
- fragments.forEach((fragment, i) => {
- if (protectedKeys.has(fragment.key)) mounted.add(i);
- });
- if (bounded) {
- // The box shows the end of the trace; the measured offset lags a fast-growing one.
- let height = 0;
- for (
- let i = fragments.length - 1;
- i >= 0 && height < BOUNDED_TAIL_PX;
- i -= 1
- ) {
- mounted.add(i);
- height += virtualizer.measurementsCache[i]?.size ?? 0;
- }
+ useEffect(() => {
+ if (covered) return;
+ const widen: Widener = (characters, share) => {
+ const all = fragmentsRef.current;
+ const current = limitRef.current;
+ if (committedRef.current !== current) {
+ if (performance.now() - requestedAt.current < STARVED_MS)
+ return NOTHING_SPENT;
+ requestedAt.current = performance.now();
+ setLimit(current);
+ return NOTHING_SPENT;
}
- return [...mounted].sort((a, b) => a - b);
- },
- // TanStack reports measurement corrections; the thread controller owns all scroll writes.
- // Its own initial-position writes are intentionally ignored.
- scrollToFn: (offset, { adjustments }) => {
- const element = viewport();
- if (element && adjustments !== undefined)
- adjustAbove(offset + adjustments - element.scrollTop);
- },
- });
- virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, delta) => {
- // Ref measurements run before the virtualizer observes the shared viewport.
- // Its offset is still zero then: applying that correction would send a reader
- // back to the beginning when a live trace first crosses the threshold.
- if (bounded) return false;
- if (
- virtualizer.scrollElement === null ||
- item.end >= (viewport()?.scrollTop ?? 0)
- )
- return false;
- if (nearby.current) return true;
- // A far transcript's offset froze when it stopped listening; correcting from it
- // would throw the reader back to where it left. Shift by the size change alone.
- adjustAbove(delta);
- return false;
- };
+ if (isCovered(current, all.length)) return null;
+ const allowed = frameBudget(performance.now() - mountedAt.current);
+ const budgeted = widenBudget(
+ all.map((fragment) => fragment.text.length),
+ current,
+ Math.min(characters, allowed.characters),
+ Math.min(share, allowed.fragments),
+ );
+ const spent = { characters: budgeted.spent, rows: budgeted.rows - current };
+ let rows = chunkEndAt(gridRef.current, budgeted.rows);
+ for (const skip of islandsRef.current)
+ if (rows >= skip.start && rows < skip.end) rows = skip.end;
+ requestedAt.current = performance.now();
+ limitRef.current = isCovered(rows, all.length)
+ ? Number.POSITIVE_INFINITY
+ : rows;
+ const value = limitRef.current;
+ if (streamingRef.current) setLimit(value);
+ else startTransition(() => setLimit(value));
+ return spent;
+ };
+ requestWiden(widen);
+ return () => cancelWiden(widen);
+ }, [covered, setLimit]);
useLayoutEffect(() => {
const element = root.current;
- const scroll = viewport();
+ const next = element && measureGeometry(element, codeProbe.current);
+ if (next) setGeometry(keepGeometry(next));
+ }, []);
+
+ useLayoutEffect(() => {
+ if (!bounded || covered) return;
+ let start = fragments.length;
+ for (let height = 0; start > 0 && height < BOUNDED_TAIL_PX; )
+ height += estimates[--start];
+ const next = addIsland(
+ islandsRef.current,
+ { start: chunkStartAt(grid, start), end: fragments.length },
+ committedRef.current,
+ );
+ if (next === islandsRef.current) return;
+ islandsRef.current = next;
+ setIslands(next);
+ }, [bounded, covered, fragments.length, estimates, grid, setIslands]);
+
+ useLayoutEffect(() => {
+ recapture.current(true);
+ }, [bounded]);
+
+ useLayoutEffect(() => {
+ const pending = restore;
+ const element = root.current;
+ if (!pending || !element) return;
+ const row = element.querySelector(`[data-index="${pending.index}"]`);
+ if (!row) return;
+ setRestore(null);
+ requestAnimationFrame(() => {
+ if (!row.isConnected) return;
+ const passage = reasoningTextRange(row, pending.text, pending.occurrence);
+ if (passage)
+ adjustAbove(passage.getBoundingClientRect().top - pending.top);
+ recapture.current(true);
+ });
+ }, [restore, limit, adjustAbove]);
+
+ useLayoutEffect(() => {
+ const element = root.current;
+ const scroll = element?.closest<HTMLElement>(".aui-thread-viewport");
if (!element || !scroll) return;
+ let width = element.getBoundingClientRect().width;
let frame = 0;
- let width = 0;
- let readingAnchor: (ReasoningReadingAnchor & { index: number }) | undefined;
- const measure = () => {
- frame = 0;
- const rect = element.getBoundingClientRect();
- if (!rect.width) return;
- const style = getComputedStyle(element);
- const next = {
- top: rect.top - scroll.getBoundingClientRect().top + scroll.scrollTop,
- width: rect.width,
- lineHeight: Number.parseFloat(style.lineHeight) || 24,
- fontPixels: Number.parseFloat(style.fontSize) || 15,
- };
- setGeometry((old) =>
- Object.keys(next).every(
- (key) =>
- next[key as keyof typeof next] === old[key as keyof typeof old],
- )
- ? old
- : next,
+ let reading: Reading | undefined;
+ const firstEndingBelow = (items: ArrayLike<Element>, top: number) => {
+ let low = 0;
+ let high = items.length - 1;
+ let first = items.length;
+ while (low <= high) {
+ const middle = (low + high) >> 1;
+ if (items[middle].getBoundingClientRect().bottom > top) {
+ first = middle;
+ high = middle - 1;
+ } else {
+ low = middle + 1;
+ }
+ }
+ return first;
+ };
+ const visibleAnchor = (): Reading | undefined => {
+ const chunks = element.querySelectorAll<HTMLElement>(
+ ":scope > [data-reasoning-chunk]",
);
- if (width && width !== rect.width) {
- // Capture before reflow: a long user message above us may push the whole
- // transcript offscreen at the new width before ResizeObserver runs.
- if (readingAnchor && !bounded) {
- setAnchor(readingAnchor);
- setAnchoring(true);
+ const bounds = scroll.getBoundingClientRect();
+ const rootTop = element.getBoundingClientRect().top;
+ for (
+ let at = firstEndingBelow(chunks, bounds.top);
+ at < chunks.length;
+ at += 1
+ ) {
+ const chunk = chunks[at];
+ if (chunk.getBoundingClientRect().top >= bounds.bottom) break;
+ const rows = chunk.querySelectorAll<HTMLElement>(
+ "[data-reasoning-fragment]",
+ );
+ for (let i = firstEndingBelow(rows, bounds.top); i < rows.length; i += 1) {
+ const row = rows[i];
+ if (row.getBoundingClientRect().top >= bounds.bottom) return undefined;
+ const key = row.dataset.reasoningFragment;
+ const captured = captureReasoningAnchor(row, scroll);
+ if (captured && key !== undefined)
+ return { ...captured, key, row, offset: captured.top - rootTop };
}
- virtualizer.measure();
- } else {
- readingAnchor = undefined;
- if (nearby.current)
- for (const row of element.querySelectorAll<HTMLElement>(
- "[data-index]",
- )) {
- const captured = captureReasoningAnchor(row, scroll);
- if (captured) {
- readingAnchor = { ...captured, index: Number(row.dataset.index) };
- break;
- }
- }
}
- width = rect.width;
+ return undefined;
+ };
+ const passageOf = (anchor: Reading) => {
+ const row =
+ anchor.row.isConnected
+ && element.contains(anchor.row)
+ && anchor.row.getAttribute("data-reasoning-fragment") === anchor.key
+ ? anchor.row
+ : element.querySelector(
+ `[data-reasoning-fragment="${CSS.escape(anchor.key)}"]`,
+ );
+ if (!row) return null;
+ anchor.row = row;
+ passageRange ??= document.createRange();
+ return reasoningTextRange(row, anchor.text, anchor.occurrence, passageRange);
+ };
+ let residue = 0;
+ const hold = (anchor: Reading): boolean => {
+ residue = 0;
+ const rootTop = element.getBoundingClientRect().top;
+ const was = rootTop + anchor.offset;
+ const bounds = scroll.getBoundingClientRect();
+ if (was < bounds.top - bounds.height || was > bounds.bottom + bounds.height)
+ return false;
+ const passage = passageOf(anchor);
+ if (!passage) return false;
+ const top = passage.getBoundingClientRect().top;
+ const shift = top - was;
+ if (Math.abs(shift) < SHIFT_EPSILON_PX) {
+ residue = shift;
+ return true;
+ }
+ anchor.offset = top - rootTop;
+ anchor.top = was;
+ const before = scroll.scrollTop;
+ const rounded = Math.round(shift);
+ const acted = adjustAbove(rounded);
+ const applied = scroll.scrollTop - before;
+ if (applied !== 0 || (acted && rounded !== 0)) {
+ anchor.offset -= shift - applied;
+ residue = shift - applied;
+ }
+ return true;
+ };
+ const rowAt = (from: number, to: number, offset: number): number => {
+ const sizes = estimatesRef.current;
+ let at = from;
+ for (let covered = 0; at < to && covered + sizes[at] <= offset; at += 1) {
+ covered += sizes[at];
+ }
+ return at;
+ };
+ const demand = () => {
+ const all = fragmentsRef.current.length;
+ const mounted = committedRef.current;
+ const prefix = isCovered(mounted, all) ? all : mounted;
+ if (prefix >= all) return;
+ const bounds = scroll.getBoundingClientRect();
+ const above = bounds.top - bounds.height;
+ const below = bounds.bottom + bounds.height;
+ let next = islandsRef.current;
+ for (const { element: reserve, from, to } of reserves.current.values()) {
+ if (from >= to || to > all || !reserve.isConnected) continue;
+ const rect = reserve.getBoundingClientRect();
+ if (!rect.height || rect.bottom <= above || rect.top >= below) continue;
+ const start = chunkStartAt(
+ gridRef.current,
+ rowAt(from, to, Math.max(0, above - rect.top)),
+ );
+ const end = chunkEndAt(
+ gridRef.current,
+ Math.min(to, rowAt(from, to, Math.max(0, below - rect.top)) + 1),
+ );
+ if (end > start) next = addIsland(next, { start, end }, prefix);
+ }
+ if (next === islandsRef.current) return;
+ islandsRef.current = next;
+ setIslands(next);
+ };
+ demandNow.current = () => {
+ if (element.getBoundingClientRect().width) demand();
+ };
+ const laidOut = () => {
+ const now = element.getBoundingClientRect().width;
+ return now !== 0 && now === width;
+ };
+ const capture = () => {
+ frame = 0;
+ if (!laidOut()) return;
+ const held = reading !== undefined && hold(reading);
+ demand();
+ reading = visibleAnchor();
+ if (held && reading) reading.offset -= residue;
+ };
+ recapture.current = (fresh = false) => {
+ if (!laidOut()) return;
+ if (!fresh && reading && hold(reading)) return;
+ reading = visibleAnchor();
+ };
+ let rootBefore: number | null = null;
+ let carrying = false;
+ const keepOnScreen = () => {
+ if (reading && rootBefore !== null)
+ reading.offset += rootBefore - element.getBoundingClientRect().top;
+ rootBefore = null;
+ };
+ carry.current = (previous) => {
+ keepOnScreen();
+ const anchor = reading;
+ const from = anchor && previous.find((fragment) => fragment.key === anchor.key);
+ if (!from || !laidOut()) return false;
+ const all = fragmentsRef.current;
+ const place = anchorAtSamePlace(
+ previous,
+ all,
+ from,
+ anchor.text,
+ anchor.occurrence ?? 0,
+ );
+ if (!place) return false;
+ const at = place.index;
+ anchor.key = all[at].key;
+ anchor.occurrence = place.occurrence;
+ const mounted = committedRef.current;
+ if (isCovered(mounted, all.length) || at < mounted) return false;
+ const below = 2 * scroll.getBoundingClientRect().height;
+ const next = addIsland(
+ islandsRef.current,
+ {
+ start: chunkStartAt(gridRef.current, at),
+ end: chunkEndAt(
+ gridRef.current,
+ Math.min(all.length, rowAt(at, all.length, below) + 1),
+ ),
+ },
+ mounted,
+ );
+ islandsRef.current = next;
+ setIslands(next);
+ carrying = true;
+ return true;
};
const schedule = () => {
- if (!frame) frame = requestAnimationFrame(measure);
+ if (frame === 0) frame = requestAnimationFrame(capture);
};
- const observer = new ResizeObserver(schedule);
+ let edge: number | null = null;
+ commitEdge.current = {
+ before: () => {
+ edge = null;
+ rootBefore = null;
+ if (!laidOut()) return;
+ reading ??= visibleAnchor();
+ if (reading) {
+ rootBefore = element.getBoundingClientRect().top;
+ return;
+ }
+ if (hasPendingProgressiveMounts()) return;
+ const bounds = scroll.getBoundingClientRect();
+ const box = element.getBoundingClientRect();
+ if (box.top < bounds.top && box.bottom <= bounds.bottom)
+ edge = box.bottom - bounds.top;
+ },
+ after: () => {
+ if (carrying) {
+ carrying = false;
+ keepOnScreen();
+ }
+ const was = edge;
+ edge = null;
+ if (was === null || !laidOut()) return;
+ const shift =
+ element.getBoundingClientRect().bottom -
+ scroll.getBoundingClientRect().top -
+ was;
+ if (Math.abs(shift) >= SHIFT_EPSILON_PX) adjustAbove(Math.round(shift));
+ },
+ };
+ let height = element.getBoundingClientRect().height;
+ let settleTimer = 0;
+ const resettleLater = () => {
+ settleTimer = 0;
+ if (panelDragInProgress()) {
+ settleTimer = window.setTimeout(resettleLater, RESETTLE_DELAY_MS);
+ return;
+ }
+ resettleRows(element);
+ const next = measureGeometry(element, codeProbe.current);
+ if (next) setGeometry(keepGeometry(next));
+ if (reading) hold(reading);
+ };
+ const atBottom = () =>
+ scroll.scrollTop + scroll.clientHeight >= scroll.scrollHeight - 1;
+ let remeasureResidue = 0;
+ rowRemeasurers.set(element, (row) => {
+ const bounds = scroll.getBoundingClientRect();
+ const box = element.getBoundingClientRect();
+ row.removeAttribute(ROW_SETTLED_ATTRIBUTE);
+ settleQueue.add(row);
+ if (!box.width || box.bottom > bounds.top) {
+ remeasureResidue = 0;
+ return;
+ }
+ const shift =
+ element.getBoundingClientRect().bottom -
+ scroll.getBoundingClientRect().top -
+ (box.bottom - bounds.top) +
+ remeasureResidue;
+ const before = scroll.scrollTop;
+ const acted = adjustAbove(Math.round(shift));
+ remeasureResidue = acted ? shift - (scroll.scrollTop - before) : 0;
+ });
+ const observer = new ResizeObserver(() => {
+ const box = element.getBoundingClientRect();
+ if (!box.width) {
+ hiddenTranscripts.add(element);
+ return;
+ }
+ hiddenTranscripts.delete(element);
+ const widened = box.width !== width;
+ if (blindTranscripts.delete(element) && !widened) {
+ if (settleTimer !== 0) clearTimeout(settleTimer);
+ settleTimer = window.setTimeout(resettleLater, RESETTLE_DELAY_MS);
+ }
+ const grown = box.height !== height;
+ width = box.width;
+ height = box.height;
+ if (!widened && !grown) return;
+ const anchor = reading;
+ if (!widened) {
+ if (anchor && !atBottom()) hold(anchor);
+ return;
+ }
+ if (settleTimer !== 0) clearTimeout(settleTimer);
+ settleTimer = window.setTimeout(resettleLater, RESETTLE_DELAY_MS);
+ if (!anchor) return;
+ const passage = passageOf(anchor);
+ if (!passage) return;
+ const top = passage.getBoundingClientRect().top;
+ anchor.offset = top - box.top;
+ adjustAbove(top - anchor.top);
+ });
observer.observe(element);
- observer.observe(scroll);
- if (scroll.firstElementChild) observer.observe(scroll.firstElementChild);
- if (nearby.current)
- scroll.addEventListener("scroll", schedule, { passive: true });
let stopJumpWatch: (() => void) | undefined;
const setNearby = (near: boolean, beforePaint = false) => {
if (near === nearby.current) return;
@@ -554,41 +1093,28 @@ export function ReasoningTranscript({
stopJumpWatch?.();
stopJumpWatch = undefined;
scroll.addEventListener("scroll", schedule, { passive: true });
- if (beforePaint)
- // Its top went stale while away: re-measure and render the live range before this paint.
- flushSync(() => {
- measure();
- followOffset.current?.(true);
- });
- else {
- followOffset.current?.(true);
- schedule();
- }
- } else {
- const box = element.getBoundingClientRect();
- // Far means wholly above or below the reader; a closed folded round has no box.
- followOffset.current?.(
- false,
- box.height > 0
- ? box.bottom <= scroll.getBoundingClientRect().top
- ? 1e9
- : -1e9
- : undefined,
- );
- scroll.removeEventListener("scroll", schedule);
- readingAnchor = undefined;
- stopJumpWatch = onViewportJump(scroll, () => {
- const box = element.getBoundingClientRect();
- const view = scroll.getBoundingClientRect();
- if (
- box.height > 0 &&
- box.bottom > view.top - view.height &&
- box.top < view.bottom + view.height
- )
- setNearby(true, true);
- });
+ // A jump lands before IntersectionObserver reports: mount before this paint.
+ if (beforePaint) flushSync(capture);
+ else schedule();
+ return;
}
+ scroll.removeEventListener("scroll", schedule);
+ if (frame !== 0) cancelAnimationFrame(frame);
+ frame = 0;
+ reading = undefined;
+ stopJumpWatch = onViewportJump(scroll, () => {
+ const box = element.getBoundingClientRect();
+ const view = scroll.getBoundingClientRect();
+ if (
+ box.height > 0 &&
+ box.bottom > view.top - view.height &&
+ box.top < view.bottom + view.height
+ )
+ setNearby(true, true);
+ });
};
+ if (nearby.current)
+ scroll.addEventListener("scroll", schedule, { passive: true });
const proximity =
typeof IntersectionObserver === "undefined"
? undefined
@@ -598,129 +1124,126 @@ export function ReasoningTranscript({
{ root: scroll, rootMargin: "100% 0px" },
);
proximity?.observe(element);
- measure();
return () => {
+ commitEdge.current = { before: () => {}, after: () => {} };
observer.disconnect();
proximity?.disconnect();
stopJumpWatch?.();
scroll.removeEventListener("scroll", schedule);
- cancelAnimationFrame(frame);
+ if (frame !== 0) cancelAnimationFrame(frame);
+ if (settleTimer !== 0) clearTimeout(settleTimer);
+ hiddenTranscripts.delete(element);
+ blindTranscripts.delete(element);
+ rowRemeasurers.delete(element);
};
- // Lifting the cap moves the root without resizing it: re-measure its offset.
- }, [viewport, virtualizer, bounded]);
-
- useLayoutEffect(() => {
- if (!anchoring || !anchor) return;
- // Keep this passage mounted through the initial estimates, then reconcile its
- // measured position through the thread's single scroll owner before releasing it.
- const frame = requestAnimationFrame(() => {
- const row = root.current?.querySelector(`[data-index="${anchor.index}"]`);
- const passage =
- row && reasoningTextRange(row, anchor.text, anchor.occurrence);
- if (passage && !bounded)
- adjustAbove(passage.getBoundingClientRect().top - anchor.top);
- setAnchoring(false);
- });
- return () => cancelAnimationFrame(frame);
- }, [anchor, anchoring, adjustAbove, bounded]);
+ }, [adjustAbove, setIslands]);
useEffect(() => {
const element = root.current;
if (!element) return;
const protect = () => {
+ const active = document.activeElement;
+ let touches = Boolean(active && element.contains(active));
const selection = window.getSelection();
- const keys = new Set<string>();
- for (const row of element.querySelectorAll<HTMLElement>(
- "[data-reasoning-fragment]",
- )) {
- const focused =
- document.activeElement && row.contains(document.activeElement);
- let selected = false;
- if (selection && !selection.isCollapsed) {
- for (let i = 0; i < selection.rangeCount; i += 1)
- selected ||= selection.getRangeAt(i).intersectsNode(row);
- }
- if (selected || focused) keys.add(row.dataset.reasoningFragment!);
+ if (!touches && selection && !selection.isCollapsed) {
+ for (let i = 0; i < selection.rangeCount && !touches; i += 1)
+ touches = selection.getRangeAt(i).intersectsNode(element);
}
- if (keys.size) detach();
- setProtectedKeys((old) =>
- old.size === keys.size && [...old].every((key) => keys.has(key))
- ? old
- : keys,
- );
+ if (touches) detach();
};
document.addEventListener("selectionchange", protect);
element.addEventListener("focusin", protect);
- element.addEventListener("focusout", protect);
return () => {
document.removeEventListener("selectionchange", protect);
element.removeEventListener("focusin", protect);
- element.removeEventListener("focusout", protect);
};
}, [detach]);
- const groups: {
- key: string;
- code: boolean;
- items: VirtualItem[];
- }[] = [];
- for (const item of virtualizer.getVirtualItems()) {
- const fragment = fragments[item.index];
- const key = fragment.code
- ? `${fragment.document}:${fragment.start}`
- : fragment.key;
- const previous = groups.at(-1);
- if (previous?.key === key) previous.items.push(item);
- else
- groups.push({
- key,
- code: Boolean(fragment.code),
- items: [item],
- });
+ const shown = covered ? fragments.length : limit;
+ const sealed = covered && !streaming;
+ const fragmentKey = (at: number) => fragments[at].key;
+ const sliceOf = ({
+ index,
+ first,
+ end,
+ }: ChunkPiece["groups"][number]): ChunkSlice => {
+ const group = grid.groups[index];
+ return {
+ key: group.key,
+ code: group.code,
+ first,
+ end,
+ streaming:
+ streaming &&
+ (group.code
+ ? fragments[first].code!.incomplete
+ : first === fragments.length - 1),
+ };
+ };
+ const rendered: React.ReactNode[] = [];
+ for (const { from, to, reserve } of mountPlan(
+ shown,
+ islands,
+ fragments.length,
+ )) {
+ if (reserve === undefined) {
+ for (const piece of chunkPieces(grid, fragmentKey, from, to)) {
+ rendered.push(
+ <Chunk
+ key={piece.key}
+ slices={piece.groups.map(sliceOf)}
+ fragments={fragments}
+ closed={piece.whole && (!piece.last || sealed)}
+ estimate={grid.heights[piece.end] - grid.heights[piece.first]}
+ messageId={messageId}
+ messageHasRenderableRenderHtmlTool={
+ messageHasRenderableRenderHtmlTool
+ }
+ />,
+ );
+ }
+ continue;
+ }
+ const key = `reserve:${reserve}`;
+ rendered.push(
+ <div
+ key={key}
+ ref={(element) => {
+ if (!element) return;
+ const registry = reserves.current;
+ registry.set(key, { element, from, to });
+ return () => {
+ if (registry.get(key)?.element === element) registry.delete(key);
+ };
+ }}
+ aria-hidden="true"
+ data-reasoning-reserve=""
+ style={{ height: grid.heights[to] - grid.heights[from] }}
+ />,
+ );
}
return (
<SearchImagesEnabledContext.Provider value={false}>
- <div
- ref={root}
- data-slot="reasoning-transcript"
- className="relative min-w-0"
- style={{ height: virtualizer.getTotalSize(), overflowAnchor: "none" }}
- >
- {groups.map((group) => {
- if (group.code)
- return (
- <CodeGroup
- key={group.key}
- items={group.items}
- fragments={fragments}
- top={geometry.top}
- measure={virtualizer.measureElement}
- streaming={streaming}
- />
- );
- const item = group.items[0];
- const fragment = fragments[item.index];
- return (
- <Row
- key={item.key}
- item={item}
- fragment={fragment}
- top={geometry.top}
- measure={virtualizer.measureElement}
- >
- <Fragment
- fragment={fragment}
- messageId={messageId}
- messageHasRenderableRenderHtmlTool={
- messageHasRenderableRenderHtmlTool
- }
- streaming={streaming && item.index === fragments.length - 1}
- />
- </Row>
- );
- })}
- </div>
+ <CodeHighlightModeContext.Provider value="settled">
+ <div
+ ref={root}
+ data-slot="reasoning-transcript"
+ className="relative min-w-0"
+ style={{ overflowAnchor: "none" }}
+ >
+ <div
+ ref={codeProbe}
+ aria-hidden
+ className="aui-reasoning-code-fragment aui-reasoning-code-last pointer-events-none invisible absolute"
+ >
+ <div className="aui-reasoning-code-lines" />
+ </div>
+ <CommitBounds before={beforeCommit} after={afterCommit}>
+ {rendered}
+ </CommitBounds>
+ </div>
+ </CodeHighlightModeContext.Provider>
</SearchImagesEnabledContext.Provider>
);
}
diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsx
index 6c26c288fee..f12f848e411 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx
@@ -5,6 +5,7 @@
/* eslint-disable react-refresh/only-export-components */
+import { CodeHighlightModeContext } from "@/components/assistant-ui/code-highlight-context";
import {
MarkdownText,
SearchImagesEnabledContext,
@@ -357,7 +358,9 @@ function ReasoningText({
const ReasoningImpl: ReasoningMessagePartComponent = () => (
<SearchImagesEnabledContext.Provider value={false}>
- <MarkdownText />
+ <CodeHighlightModeContext.Provider value="settled">
+ <MarkdownText />
+ </CodeHighlightModeContext.Provider>
</SearchImagesEnabledContext.Provider>
);
@@ -481,6 +484,7 @@ function useReasoningTranscriptMode({
function ReasoningBody({
transcript,
messageId,
+ roundStart,
messageHasRenderableRenderHtmlTool,
isStreaming,
bounded = false,
@@ -489,6 +493,7 @@ function ReasoningBody({
}: {
transcript: ReturnType<typeof useReasoningTranscriptMode>;
messageId: string;
+ roundStart: number;
messageHasRenderableRenderHtmlTool: boolean;
isStreaming: boolean;
bounded?: boolean;
@@ -506,6 +511,7 @@ function ReasoningBody({
key={messageId}
initialAnchor={transcript.anchor}
documents={transcript.documents}
+ indexKey={`${messageId}:${roundStart}`}
messageId={messageId}
messageHasRenderableRenderHtmlTool={
messageHasRenderableRenderHtmlTool
@@ -685,6 +691,7 @@ const FoldedReasoningRound: ReasoningGroupComponent = ({
<ReasoningBody
transcript={transcript}
messageId={messageId}
+ roundStart={startIndex}
messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}
isStreaming={isStreaming}
textClassName="pt-0"
@@ -913,6 +920,7 @@ const ReasoningGroupBlock = ({
<ReasoningBody
transcript={transcript}
messageId={messageId}
+ roundStart={startIndex}
messageHasRenderableRenderHtmlTool={
messageHasRenderableRenderHtmlTool
}
diff --git a/studio/frontend/src/components/assistant-ui/stream-activity.ts b/studio/frontend/src/components/assistant-ui/stream-activity.ts
new file mode 100644
index 00000000000..79558bdaa72
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/stream-activity.ts
@@ -0,0 +1,36 @@
+// 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 STREAM_COOLDOWN_MS = 2_000;
+
+type RunningState = { runningByThreadId: Record<string, boolean> };
+
+export type StreamActivityStore = {
+ getState(): RunningState;
+ subscribe(listener: (next: RunningState, previous: RunningState) => void): () => void;
+};
+
+export type StreamActivity = { active(): boolean };
+
+const anyRunning = (running: Record<string, boolean>): boolean =>
+ Object.values(running).some(Boolean);
+
+export function createStreamActivity(
+ store: StreamActivityStore,
+ now: () => number = () => performance.now(),
+): StreamActivity {
+ let lastRunEndedAt = Number.NEGATIVE_INFINITY;
+ store.subscribe((next, previous) => {
+ if (
+ !anyRunning(next.runningByThreadId)
+ && anyRunning(previous.runningByThreadId)
+ ) {
+ lastRunEndedAt = now();
+ }
+ });
+ return {
+ active: () =>
+ anyRunning(store.getState().runningByThreadId)
+ || now() - lastRunEndedAt < STREAM_COOLDOWN_MS,
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/streaming-markdown.ts b/studio/frontend/src/components/assistant-ui/streaming-markdown.ts
index 3f3393ea72a..9f32dfe34b0 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-markdown.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-markdown.ts
@@ -16,6 +16,7 @@ const BLOCKQUOTE_PREFIX_RE = /^(?:[ \t]*>[ \t]?)+/;
// Real prefixes are short, and parsing a long run is quadratic (100k dashes
// cost 8s), so a runaway line is left alone.
const MAX_AMBIGUOUS_LINE = 120;
+const FENCE_BLOCK_RE = /^ {0,3}(?:`{3,}|~{3,})/;
type MarkdownNode = {
readonly type: string;
@@ -104,7 +105,10 @@ export function stabilizeStreamingMarkdown(
// Run what Streamdown runs: repair, split, then read only the trailing block
// so the cost does not grow with the response.
const block = parseMarkdownIntoBlocks(remend(text)).at(-1);
- const markerIndex = block === undefined ? -1 : ambiguousMarkerIndex(block);
+ const markerIndex =
+ block === undefined || FENCE_BLOCK_RE.test(block)
+ ? -1
+ : ambiguousMarkerIndex(block);
if (
block === undefined ||
markerIndex < 0 ||
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
index 56b6a2bbc3c..18b28e8773c 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -978,6 +978,33 @@ export type IncrementalMarkdownRender = {
};
const INCOMPLETE_LINK_REPAIR = "](streamdown:incomplete-link)";
+const LINK_REPAIR_MEMO_ENTRIES = 256;
+const LINK_REPAIR_MEMO_CHARACTERS = 4_194_304;
+const linkRepairMemo = new Map<string, boolean>();
+let linkRepairMemoCharacters = 0;
+
+function addsIncompleteLinkPlaceholder(source: string, after: string): boolean {
+ return (
+ after.split(INCOMPLETE_LINK_REPAIR).length >
+ source.split(INCOMPLETE_LINK_REPAIR).length
+ );
+}
+
+function rememberLinkRepair(source: string, value: boolean): boolean {
+ if (source.length > LINK_REPAIR_MEMO_CHARACTERS) return value;
+ linkRepairMemo.set(source, value);
+ linkRepairMemoCharacters += source.length;
+ while (
+ linkRepairMemo.size > LINK_REPAIR_MEMO_ENTRIES ||
+ linkRepairMemoCharacters > LINK_REPAIR_MEMO_CHARACTERS
+ ) {
+ const oldest = linkRepairMemo.keys().next();
+ if (oldest.done) break;
+ linkRepairMemo.delete(oldest.value);
+ linkRepairMemoCharacters -= oldest.value.length;
+ }
+ return value;
+}
export function hasIncompleteLinkRepair(
source: string,
@@ -985,10 +1012,18 @@ export function hasIncompleteLinkRepair(
): boolean {
// Only an unclosed `[` gets the placeholder, so bracket-free replies skip the remend pass.
if (!source.includes("[")) return false;
- const after = repaired ?? remend(source);
- return (
- after.split(INCOMPLETE_LINK_REPAIR).length >
- source.split(INCOMPLETE_LINK_REPAIR).length
+ if (repaired !== undefined) {
+ return addsIncompleteLinkPlaceholder(source, repaired);
+ }
+ const remembered = linkRepairMemo.get(source);
+ if (remembered !== undefined) {
+ linkRepairMemo.delete(source);
+ linkRepairMemo.set(source, remembered);
+ return remembered;
+ }
+ return rememberLinkRepair(
+ source,
+ addsIncompleteLinkPlaceholder(source, remend(source)),
);
}
@@ -1639,17 +1674,43 @@ export class IncrementalMarkdownCache {
}
}
+type RehypePluginList = NonNullable<BlockProps["rehypePlugins"]>;
+
+const samePluginEntry = (
+ a: RehypePluginList[number],
+ b: RehypePluginList[number],
+): boolean =>
+ a === b
+ || (Array.isArray(a)
+ && Array.isArray(b)
+ && a.length === b.length
+ && a.every((value, index) => value === b[index]));
+
+const filteredPluginLists = new WeakMap<RehypePluginList, RehypePluginList>();
+let lastFilteredPluginList: RehypePluginList | null = null;
+
export function withoutStreamdownAnimationPlugin(
rehypePlugins: BlockProps["rehypePlugins"],
animatePlugin: BlockProps["animatePlugin"],
): BlockProps["rehypePlugins"] {
const animationPlugin = animatePlugin?.rehypePlugin;
- if (!animationPlugin) {
+ if (!animationPlugin || !rehypePlugins) {
return rehypePlugins;
}
-
- return rehypePlugins?.filter((plugin) => {
+ const known = filteredPluginLists.get(rehypePlugins);
+ if (known !== undefined) return known;
+ const filtered = rehypePlugins.filter((plugin) => {
const pluginFunction = Array.isArray(plugin) ? plugin[0] : plugin;
return pluginFunction !== animationPlugin;
});
+ const previous = lastFilteredPluginList;
+ const stable =
+ previous !== null
+ && previous.length === filtered.length
+ && previous.every((plugin, index) => samePluginEntry(plugin, filtered[index]))
+ ? previous
+ : filtered;
+ filteredPluginLists.set(rehypePlugins, stable);
+ lastFilteredPluginList = stable;
+ return stable;
}
diff --git a/studio/frontend/src/components/assistant-ui/thread-width-steps.ts b/studio/frontend/src/components/assistant-ui/thread-width-steps.ts
new file mode 100644
index 00000000000..2ce9998cdb4
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/thread-width-steps.ts
@@ -0,0 +1,36 @@
+// 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 THREAD_WIDTH_STEPS = [
+ { attribute: "data-thread-narrow", rem: 31.5, bound: "max" },
+ { attribute: "data-thread-tiny", rem: 18.75, bound: "max" },
+ { attribute: "data-thread-wide", rem: 36, bound: "min" },
+] as const;
+
+export function applyThreadWidthSteps(
+ root: Element,
+ width: number,
+ remPx: number,
+): void {
+ for (const { attribute, rem, bound } of THREAD_WIDTH_STEPS) {
+ const limit = rem * remPx;
+ root.toggleAttribute(
+ attribute,
+ bound === "max" ? width <= limit : width >= limit,
+ );
+ }
+}
+
+export function observeThreadWidthSteps(root: HTMLElement): () => void {
+ if (typeof ResizeObserver === "undefined") return () => {};
+ const observer = new ResizeObserver((entries) => {
+ const entry = entries[entries.length - 1];
+ if (!entry) return;
+ const remPx =
+ Number.parseFloat(getComputedStyle(document.documentElement).fontSize) ||
+ 16;
+ applyThreadWidthSteps(root, entry.contentRect.width, remPx);
+ });
+ observer.observe(root);
+ return () => observer.disconnect();
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index d1fd1930e31..824177b4313 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -1,6 +1,7 @@
// 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 { createPortal } from "react-dom";
import {
canQueueTextAttachment,
normalizeQueuedPrompt,
@@ -22,10 +23,23 @@ import {
} from "@/components/assistant-ui/generated-image-overlay-context";
import { AutoReadAloud } from "@/components/assistant-ui/auto-read-aloud";
import { CompactionNotice } from "@/components/assistant-ui/compaction-notice";
-import { compactionNoticeMessageIds } from "@/components/assistant-ui/message-derived";
+import {
+ compactionNoticeMessageIds,
+ memoOnArrayByKey,
+} from "@/components/assistant-ui/message-derived";
import type { ContextTruncation } from "@/features/chat/utils/context-truncation";
import { downloadImagePart } from "@/components/assistant-ui/image";
-import { MarkdownText } from "@/components/assistant-ui/markdown-text";
+import {
+ MarkdownText,
+ highlightFenceSource,
+} from "@/components/assistant-ui/markdown-text";
+import { grammarWarmed } from "@/components/assistant-ui/code-fence-defer";
+import {
+ createGrammarPrewarm,
+ type GrammarPrewarm,
+} from "@/components/assistant-ui/grammar-prewarm";
+import { streamActive } from "@/components/assistant-ui/use-reasoning-highlight";
+import { scheduleQuietIdleTask } from "@/lib/schedule-idle-task";
import { MessageHtmlArtifacts } from "@/components/assistant-ui/message-html-artifacts";
import {
MessageResponseDetailsSheet,
@@ -42,6 +56,7 @@ import { MessageTiming } from "@/components/assistant-ui/message-timing";
import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";
import { attachWheelHoverSuppression } from "@/components/assistant-ui/thread-wheel-hover";
import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";
+import { observeThreadWidthSteps } from "@/components/assistant-ui/thread-width-steps";
import { Reasoning, ReasoningGroup } from "@/components/assistant-ui/reasoning";
import { RagSourcesGroup } from "@/components/assistant-ui/rag-sources";
import { researchReplyOwners } from "@/components/assistant-ui/research-reply-owners";
@@ -1848,6 +1863,8 @@ const ThreadMessage: FC = () => {
* The walk stops at the first message the fork did not inherit, so it costs the inherited
* count rather than the thread length.
*/
+const FORK_BOUNDARY_NONE: readonly string[] = [];
+
const useTrackForkBoundaryAnchor = (threadId: string | null): void => {
const inherited = useForkBoundaryStore((s) =>
threadId === null
@@ -1855,7 +1872,9 @@ const useTrackForkBoundaryAnchor = (threadId: string | null): void => {
: s.boundaryByThreadId[threadId]?.messageIds,
);
const anchor = useAuiState(({ thread }) =>
- forkBoundaryAnchor(thread.messages, inherited),
+ memoOnArrayByKey(thread.messages, inherited ?? FORK_BOUNDARY_NONE, () =>
+ forkBoundaryAnchor(thread.messages, inherited),
+ ),
);
useEffect(() => {
setForkBoundaryAnchor(threadId, anchor);
@@ -1938,6 +1957,42 @@ const ForkContinuationRule: FC = () => {
);
};
+const PREWARM_INPUT_QUIET_MS = 1000;
+const PREWARM_INPUT_EVENTS = [
+ "scroll",
+ "wheel",
+ "pointerdown",
+ "keydown",
+ "touchmove",
+] as const;
+let grammarPrewarm: GrammarPrewarm | null = null;
+
+const startGrammarPrewarm = (): void => {
+ if (grammarPrewarm !== null) return;
+ let lastInputAt = Number.NEGATIVE_INFINITY;
+ const noteInput = () => {
+ lastInputAt = performance.now();
+ };
+ for (const type of PREWARM_INPUT_EVENTS) {
+ document.addEventListener(type, noteInput, { capture: true, passive: true });
+ }
+ grammarPrewarm = createGrammarPrewarm(
+ (code, language, late) => highlightFenceSource(code, language, late),
+ {
+ idle: scheduleQuietIdleTask,
+ wait: (callback, ms) => {
+ const timer = setTimeout(callback, ms);
+ return () => clearTimeout(timer);
+ },
+ quiet: () =>
+ !streamActive()
+ && performance.now() - lastInputAt >= PREWARM_INPUT_QUIET_MS,
+ skip: grammarWarmed,
+ },
+ );
+ grammarPrewarm.start();
+};
+
// Hoisted, so ThreadPrimitive.Messages sees the same children function on every Thread render. An
// inline arrow changes identity each time, invalidating the memo that keeps the message array from
// being rebuilt, and the bail-out below it would never get to run.
@@ -1950,11 +2005,17 @@ export const Thread: FC<{
hideWelcome?: boolean;
targetThreadId?: string;
}> = memo(({ hideComposer, hideWelcome, targetThreadId }) => {
+ useEffect(() => {
+ startGrammarPrewarm();
+ }, []);
// Intent-aware autoscroll replaces assistant-ui's built-in autoscroll to
// prevent the streaming-mutation race that snaps the viewport back to the
// bottom while the user scrolls up (see the hook for the full explanation).
- const { ref: viewportRef, context: autoScrollContext } =
- useIntentAwareAutoScroll();
+ const {
+ ref: viewportRef,
+ markerRef,
+ context: autoScrollContext,
+ } = useIntentAwareAutoScroll();
const isComposerAttachPending = useAuiState(({ threads }) =>
targetThreadId ? threads.mainThreadId !== targetThreadId : false,
@@ -1979,7 +2040,14 @@ export const Thread: FC<{
// Viewport element is owned by the autoscroll hook; mirror it locally for
// the spacer clamp math. State, not a ref: the keyed provider remounts the
// viewport on thread switches and the scroll listener must re-attach.
- const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);
+ const [viewportSlot, setViewportSlot] = useState<{
+ el: HTMLElement;
+ threadId: string;
+ } | null>(null);
+ const viewportEl =
+ viewportSlot !== null && viewportSlot.threadId === runtimeThreadId
+ ? viewportSlot.el
+ : null;
// Same element in an identity-stable ref, so ProgressiveMessages can read the viewport without a
// prop that would rebuild its row array on thread switch. A ref rather than a document-wide query
// because the Compare panes each mount their own Thread.
@@ -1987,10 +2055,10 @@ export const Thread: FC<{
const composedViewportRef = useCallback(
(node: HTMLElement | null) => {
viewportElRef.current = node;
- setViewportEl(node);
+ setViewportSlot(node ? { el: node, threadId: runtimeThreadId } : null);
viewportRef(node);
},
- [viewportRef],
+ [viewportRef, runtimeThreadId],
);
// plain-text copy skips styled data that consumes over 99% of long-thread copy time.
@@ -2053,6 +2121,7 @@ export const Thread: FC<{
desiredSpacerPxRef.current = null;
appliedSpacerPxRef.current = null;
spacerElRef.current?.style.removeProperty("height");
+ autoScrollContext.notifyContentResized();
return;
}
const desired = composerHeight + COMPOSER_SCROLL_GAP_PX;
@@ -2088,6 +2157,7 @@ export const Thread: FC<{
autoScrollContext.detachFromBottom();
}
}
+ autoScrollContext.notifyContentResized();
}, [composerHeight, hideComposer, autoScrollContext, aui, applySpacerPx, viewportEl]);
// Drop deferred spacer excess once the user has scrolled far enough above
@@ -2167,11 +2237,97 @@ export const Thread: FC<{
}
};
+ const watchWidthSteps = useCallback(
+ (root: HTMLDivElement | null) =>
+ root ? observeThreadWidthSteps(root) : undefined,
+ [],
+ );
+
return (
<GeneratedImageOverlayProvider key={runtimeThreadId} threadId={threadId}>
<PageDragContext.Provider value={pageDragging}>
+ <IntentAwareScrollProvider value={autoScrollContext}>
+ <ThreadPrimitive.Viewport
+ autoScroll={false}
+ scrollToBottomOnRunStart={false}
+ scrollToBottomOnInitialize={false}
+ scrollToBottomOnThreadSwitch={false}
+ ref={markerRef}
+ className="aui-thread-host hidden"
+ onDragEnter={onDragEnter}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ aria-hidden={true}
+ >
+ {viewportEl !== null &&
+ createPortal(
+ <>
+ {!hideWelcome && (
+ <AuiIf
+ condition={({ thread }) => thread.isEmpty && !thread.isLoading}
+ >
+ <ThreadWelcome hideComposer={hideComposer} threadId={threadId} />
+ </AuiIf>
+ )}
+
+ {/* Drop-in for ThreadPrimitive.Messages that bounds a long thread's first commit to
+ the tail and mounts the rest over the following frames. Nothing unmounts and the
+ document converges to the tree this rendered before; consumers that cannot wait call
+ completeProgressiveMounts. It takes the propless slot #9042 introduced, for the same
+ reason: React's bail-out needs one shared element per row. See
+ progressive-mount-controller.ts. */}
+ <ProgressiveMessages
+ renderMessage={renderThreadMessage}
+ resetKey={runtimeThreadId}
+ viewportRef={viewportElRef}
+ />
+
+ {/* Bottom slack so the last message has room above the sticky
+ scroll-to-bottom button (and floating composer in single mode),
+ instead of butting against the footer. */}
+ <AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
+ <div
+ ref={spacerRef}
+ className={cn(
+ "shrink-0",
+ hideComposer
+ ? "h-16"
+ : composerHeight == null
+ ? "h-40"
+ : undefined,
+ )}
+ aria-hidden={true}
+ />
+ </AuiIf>
+
+ <AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
+ <ThreadPrimitive.ViewportFooter
+ className={cn(
+ "aui-thread-viewport-footer pointer-events-none sticky z-20 flex w-full justify-center bg-transparent",
+ hideComposer
+ ? "bottom-3"
+ : footerBottomPx == null
+ ? "bottom-[calc(150px*var(--ui-space-scale,1))]"
+ : undefined,
+ )}
+ style={
+ !hideComposer && footerBottomPx != null
+ ? { bottom: footerBottomPx }
+ : undefined
+ }
+ >
+ <ThreadScrollToBottom />
+ </ThreadPrimitive.ViewportFooter>
+ </AuiIf>
+ </>,
+ viewportEl,
+ )}
+ </ThreadPrimitive.Viewport>
+ </IntentAwareScrollProvider>
<ThreadPrimitive.Root
- className="aui-root aui-thread-root @container relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
+ ref={watchWidthSteps}
+ className="aui-root aui-thread-root relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden [contain:style]"
style={{
["--thread-max-width" as string]: "var(--custom-chat-max-width, 48rem)",
["--thread-content-max-width" as string]:
@@ -2184,12 +2340,8 @@ export const Thread: FC<{
>
{!hideComposer && <AutoReadAloud />}
<IntentAwareScrollProvider value={autoScrollContext}>
- <ThreadPrimitive.Viewport
+ <div
ref={composedViewportRef}
- autoScroll={false}
- scrollToBottomOnRunStart={false}
- scrollToBottomOnInitialize={false}
- scrollToBottomOnThreadSwitch={false}
className={cn(
"aui-thread-viewport aui-stream-viewport relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-x-auto overflow-y-auto scroll-smooth px-5",
hideComposer
@@ -2197,69 +2349,9 @@ export const Thread: FC<{
: // + the chat-model notice, which is an opaque absolute bar
// directly under the header. 0px whenever it is not showing,
// so every other surface keeps the padding it had.
- "[--thread-header-offset:calc(var(--studio-content-top-inset,0px)+var(--studio-chat-header-height,48px)+var(--studio-chat-notice-height,0px))] pt-[var(--thread-header-offset)]",
- )}
- >
- {!hideWelcome && (
- <AuiIf
- condition={({ thread }) => thread.isEmpty && !thread.isLoading}
- >
- <ThreadWelcome hideComposer={hideComposer} threadId={threadId} />
- </AuiIf>
+ "[--thread-header-offset:calc(var(--studio-content-top-inset,0px)-var(--studio-chat-scroller-top,0px)+var(--studio-chat-header-height,48px)+var(--studio-chat-notice-height,0px))] mt-[var(--studio-chat-scroller-top,0px)] pt-[var(--thread-header-offset)]",
)}
-
- {/* Drop-in for ThreadPrimitive.Messages that bounds a long thread's first commit to
- the tail and mounts the rest over the following frames. Nothing unmounts and the
- document converges to the tree this rendered before; consumers that cannot wait call
- completeProgressiveMounts. It takes the propless slot #9042 introduced, for the same
- reason: React's bail-out needs one shared element per row. See
- progressive-mount-controller.ts. */}
- <ProgressiveMessages
- renderMessage={renderThreadMessage}
- resetKey={runtimeThreadId}
- viewportRef={viewportElRef}
- />
-
- {/* Bottom slack so the last message has room above the sticky
- scroll-to-bottom button (and floating composer in single mode),
- instead of butting against the footer. */}
- <AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
- <div
- ref={spacerRef}
- className={cn(
- "shrink-0",
- hideComposer
- ? "h-16"
- : composerHeight == null
- ? "h-40"
- : undefined,
- )}
- aria-hidden={true}
- />
- </AuiIf>
-
- <AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
- <ThreadPrimitive.ViewportFooter
- className={cn(
- "aui-thread-viewport-footer pointer-events-none sticky z-20 flex w-full justify-center bg-transparent",
- // 150px (was 140px) to add a small gap above the composer
- hideComposer
- ? "bottom-3"
- : footerBottomPx == null
- ? "bottom-[calc(150px*var(--ui-space-scale,1))]"
- : undefined,
- )}
- style={
- !hideComposer && footerBottomPx != null
- ? { bottom: footerBottomPx }
- : undefined
- }
- >
- <ThreadScrollToBottom />
- </ThreadPrimitive.ViewportFooter>
- </AuiIf>
- </ThreadPrimitive.Viewport>
-
+ />
<GeneratedImageViewportOverlay
hideComposer={hideComposer}
bottomOffsetPx={footerBottomPx}
@@ -7510,15 +7602,21 @@ function useContinuation() {
const partial = useAuiState(
({ message }) => readContinuationSource(message.content).partial,
);
- const reasoning = useAuiState(
- ({ message }) => readContinuationSource(message.content).reasoning,
+ const reasoning = useAuiState(({ message }) =>
+ "status" in message && message.status?.type === "running"
+ ? ""
+ : readContinuationSource(message.content).reasoning,
);
// Gemini signs answer and thought parts. A continuation runs from a sibling branch,
// so both kinds of replay metadata travel with the partial.
const thoughtSignature = useAuiState(({ message }) =>
readTextThoughtSignature(message.content),
);
- const messageContent = useAuiState(({ message }) => message.content);
+ const messageContent = useAuiState(({ message }) =>
+ "status" in message && message.status?.type === "running"
+ ? undefined
+ : message.content,
+ );
const thoughtParts = useMemo(
() => collectGeminiThoughtReplayParts(messageContent),
[messageContent],
@@ -7929,7 +8027,11 @@ const AssistantMessage: FC = () => {
const aui = useAui();
const focusReveal = useActionBarFocusReveal();
const messageId = useAuiState(({ message }) => message.id);
- const messageContent = useAuiState(({ message }) => message.content);
+ const messageContent = useAuiState(({ message }) =>
+ "status" in message && message.status?.type === "running"
+ ? null
+ : message.content,
+ );
const metadataResearchRunId = useAuiState(({ message }) =>
getResearchRunId(message.metadata),
);
@@ -8047,7 +8149,7 @@ const AssistantMessage: FC = () => {
<div className="overflow-hidden rounded-xl border-[0.5px] border-border bg-muted focus-within:border-ring">
<textarea
ref={textareaRef}
- defaultValue={extractTaggedText(messageContent)}
+ defaultValue={extractTaggedText(messageContent ?? [])}
className="block w-full p-3 bg-transparent text-foreground outline-none overflow-y-auto resize-none font-mono text-sm max-h-[70dvh]"
autoFocus
onInput={adjustHeight}
diff --git a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
index 7d4c3b23913..b18e730238e 100644
--- a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
+++ b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
@@ -46,6 +46,7 @@ const TOUCH_MOVE_THRESHOLD_PX = 4;
// per-event) so slow 1px-per-event sources (middle-click autoscroll,
// scrollbar drags, some trackpads) accumulate instead of slipping under.
const UPWARD_DETACH_THRESHOLD_PX = 2;
+const SCROLL_KEY_WINDOW_MS = 500;
// Window the viewport stays pinned through layout/content races. Extends on every resize/mutation,
// so streaming keeps it pinned; settles this long after the last change.
const FOLLOW_SETTLE_MS = 600;
@@ -82,7 +83,8 @@ type AutoScrollContextValue = {
* intent bookkeeping below. A method rather than a scrollTop write at the
* inserting commit because this hook owns scrollTop.
*/
- adjustForContentInsertedAbove: (deltaPx: number) => void;
+ adjustForContentInsertedAbove: (deltaPx: number) => boolean;
+ notifyContentResized: () => void;
};
const noopContext: AutoScrollContextValue = {
@@ -96,9 +98,8 @@ const noopContext: AutoScrollContextValue = {
detachFromBottom: () => {
/* no viewport mounted */
},
- adjustForContentInsertedAbove: () => {
- /* no viewport mounted */
- },
+ adjustForContentInsertedAbove: () => false,
+ notifyContentResized: () => undefined,
};
const AutoScrollContext = createContext<AutoScrollContextValue>(noopContext);
@@ -122,7 +123,7 @@ export function useScrollThreadToBottom(): ScrollToBottom {
}
/** See AutoScrollContextValue.adjustForContentInsertedAbove. */
-export function useAdjustForContentInsertedAbove(): (deltaPx: number) => void {
+export function useAdjustForContentInsertedAbove(): (deltaPx: number) => boolean {
return useContext(AutoScrollContext).adjustForContentInsertedAbove;
}
@@ -139,10 +140,15 @@ export function useIsThreadAtBottom(): boolean {
export function useIntentAwareAutoScroll(): {
ref: RefCallback<HTMLElement>;
+ markerRef: RefCallback<HTMLElement>;
context: AutoScrollContextValue;
} {
const aui = useAui();
const cleanupRef = useRef<(() => void) | null>(null);
+ const markerElRef = useRef<HTMLElement | null>(null);
+ const markerRef = useCallback<RefCallback<HTMLElement>>((node) => {
+ markerElRef.current = node;
+ }, []);
const userDetachedRef = useRef(false);
const followUntilRef = useRef(0);
@@ -162,6 +168,7 @@ export function useIntentAwareAutoScroll(): {
const adjustImplRef = useRef<(deltaPx: number) => void>(() => {
/* no viewport mounted */
});
+ const tickRequestRef = useRef<() => void>(() => undefined);
const getIsAtBottom = useCallback(() => isAtBottomRef.current, []);
@@ -193,6 +200,11 @@ export function useIntentAwareAutoScroll(): {
const adjustForContentInsertedAbove = useCallback((deltaPx: number) => {
adjustImplRef.current(deltaPx);
+ return userDetachedRef.current;
+ }, []);
+
+ const notifyContentResized = useCallback(() => {
+ tickRequestRef.current();
}, []);
const attach = useCallback(
@@ -207,6 +219,8 @@ export function useIntentAwareAutoScroll(): {
let lastClientHeight = el.clientHeight;
let upwardAccumulator = 0;
let touchStartY = 0;
+ let scrollKeyAt = Number.NEGATIVE_INFINITY;
+ let pointerHeld = false;
const distanceFromBottom = (): number => {
if (el.scrollHeight <= el.clientHeight) {
@@ -215,10 +229,13 @@ export function useIntentAwareAutoScroll(): {
return el.scrollHeight - el.scrollTop - el.clientHeight;
};
let lastDistanceFromBottom = distanceFromBottom();
+ let lastScrollHeight = el.scrollHeight;
const atBottomStrict = (): boolean =>
distanceFromBottom() <= AT_BOTTOM_THRESHOLD_PX;
+ const marker = (): HTMLElement => markerElRef.current ?? el;
+
// Room to scroll upward. Guards wheel/touch detach: a gesture on a viewport with nothing
// above can't express intent to leave the bottom and must not flip userDetachedRef, else
// later streaming skips extendFollow and auto-follow stays dead for the session.
@@ -309,6 +326,7 @@ export function useIntentAwareAutoScroll(): {
};
let parked = false;
+ let pendingInitialPin = false;
const detach = (): void => {
parked = false;
@@ -332,6 +350,7 @@ export function useIntentAwareAutoScroll(): {
if (ceiling === null || el.scrollHeight - el.clientHeight < ceiling) {
return false;
}
+ pendingInitialPin = false;
el.scrollTo({ top: ceiling, behavior: "instant" });
detach();
parked = true;
@@ -343,6 +362,7 @@ export function useIntentAwareAutoScroll(): {
rafId = requestAnimationFrame(tick);
}
};
+ tickRequestRef.current = requestTick;
// A quiet pinned frame stops chaining and hands the rest of the window to this timer, which
// re-arms itself while the window is open. See SETTLE_CHECK_MS.
@@ -352,6 +372,7 @@ export function useIntentAwareAutoScroll(): {
}
const remaining = followUntilRef.current - performance.now();
if (remaining <= 0) {
+ requestTick();
return;
}
settleTimer = window.setTimeout(
@@ -375,14 +396,24 @@ export function useIntentAwareAutoScroll(): {
settleCheckDue = false;
// Park first so a frame without an observer record can't overshoot.
parkIfHeld();
+ if (pendingInitialPin && el.querySelector("[data-role]") !== null) {
+ pendingInitialPin = false;
+ if (el.scrollHeight > el.clientHeight) {
+ parked = false;
+ userDetachedRef.current = false;
+ extendFollow();
+ }
+ }
const following =
!userDetachedRef.current &&
(settling || performance.now() < followUntilRef.current);
if (following) {
+ marker().toggleAttribute("data-aui-following", true);
+ const scrollHeight = stabilize();
const pinned = atBottomStrict();
- if (!pinned && el.scrollHeight > el.clientHeight) {
- el.scrollTo({ top: el.scrollHeight, behavior: "instant" });
+ if (!pinned && scrollHeight > el.clientHeight) {
+ el.scrollTo({ top: scrollHeight, behavior: "instant" });
}
setIsAtBottom(true);
if (layoutChanged || !pinned) {
@@ -394,6 +425,7 @@ export function useIntentAwareAutoScroll(): {
return;
}
+ marker().toggleAttribute("data-aui-following", false);
setIsAtBottom(atBottomStrict());
};
@@ -402,6 +434,7 @@ export function useIntentAwareAutoScroll(): {
userDetachedRef.current = false;
followUntilRef.current = performance.now() + FOLLOW_SETTLE_MS;
if (el.scrollHeight > el.clientHeight) {
+ pendingInitialPin = false;
el.scrollTo({ top: el.scrollHeight, behavior });
}
setIsAtBottom(true);
@@ -418,8 +451,8 @@ export function useIntentAwareAutoScroll(): {
// Content inserted above the viewport by a progressive-mount widening. THIS HOOK OWNS
// scrollTop; the progressive mount only reports the height it put above the fold, so the two
// never both write. While the user is FOLLOWING there is deliberately nothing to do: the
- // MutationObserver below already runs onLayoutChange -> pinIfFollowing in the same frame
- // before paint, and since widening only prepends, "pin to the bottom" and "shift by the
+ // MutationObserver below already requests the tick, which pins in the same frame before
+ // paint, and since widening only prepends, "pin to the bottom" and "shift by the
// height inserted above" are the same pixel. Correcting here too would double the forced
// layouts per frame and its scroll event could re-attach a user who deliberately detached
// within RE_ATTACH_THRESHOLD_PX of the bottom. While the user is DETACHED nothing else moves
@@ -449,6 +482,7 @@ export function useIntentAwareAutoScroll(): {
// effects run before it is dispatched, so resyncing here reads as zero.
lastScrollTop = el.scrollTop;
lastDistanceFromBottom = distanceFromBottom();
+ lastScrollHeight = el.scrollHeight;
};
const onWheel = (e: WheelEvent) => {
@@ -457,10 +491,40 @@ export function useIntentAwareAutoScroll(): {
canScrollUp() &&
!innerScrollWillConsumeUpward(e.target)
) {
+ pendingInitialPin = false;
detach();
}
};
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (
+ e.defaultPrevented ||
+ !(
+ e.key === "ArrowUp" ||
+ e.key === "PageUp" ||
+ e.key === "Home" ||
+ (e.key === " " && e.shiftKey)
+ )
+ ) {
+ return;
+ }
+ const target = e.target instanceof HTMLElement ? e.target : null;
+ if (
+ target?.isContentEditable ||
+ target?.closest("input, textarea, select")
+ ) {
+ return;
+ }
+ scrollKeyAt = performance.now();
+ };
+
+ const onPointerDown = () => {
+ pointerHeld = true;
+ };
+ const onPointerUp = () => {
+ pointerHeld = false;
+ };
+
const onTouchStart = (e: TouchEvent) => {
touchStartY = e.touches[0]?.clientY ?? 0;
};
@@ -473,6 +537,7 @@ export function useIntentAwareAutoScroll(): {
canScrollUp() &&
!innerScrollWillConsumeUpward(e.target)
) {
+ pendingInitialPin = false;
detach();
}
};
@@ -486,6 +551,7 @@ export function useIntentAwareAutoScroll(): {
const delta = scrollTop - lastScrollTop;
const distanceNow = distanceFromBottom();
+ const scrollHeight = el.scrollHeight;
// Viewport resizes can clamp scrollTop and produce spurious
// direction signals. Only flip intent on deliberate scrolls.
@@ -510,9 +576,23 @@ export function useIntentAwareAutoScroll(): {
// scrollTop and scrollHeight drop together and distance is unchanged. Those layout deltas
// must not flip intent.
const distanceDelta = distanceNow - lastDistanceFromBottom;
- if (distanceDelta > 0) {
+ const keyed =
+ performance.now() - scrollKeyAt < SCROLL_KEY_WINDOW_MS;
+ // Leaving a pinned bottom in the same event the content changed, with no key or pointer
+ // behind it, is a clamp (something below shrank as a new row landed), not the user.
+ const clamped =
+ lastDistanceFromBottom <= AT_BOTTOM_THRESHOLD_PX &&
+ scrollHeight !== lastScrollHeight &&
+ !keyed &&
+ !pointerHeld;
+ if (
+ distanceDelta > 0 &&
+ !clamped &&
+ (keyed || scrollHeight >= lastScrollHeight)
+ ) {
upwardAccumulator += distanceDelta;
if (upwardAccumulator >= UPWARD_DETACH_THRESHOLD_PX) {
+ pendingInitialPin = false;
detach();
upwardAccumulator = 0;
}
@@ -523,6 +603,7 @@ export function useIntentAwareAutoScroll(): {
lastClientWidth = clientWidth;
lastClientHeight = clientHeight;
lastDistanceFromBottom = distanceNow;
+ lastScrollHeight = scrollHeight;
requestTick();
};
@@ -602,8 +683,20 @@ export function useIntentAwareAutoScroll(): {
requestTick();
};
+ const onMutation = (): void => {
+ if (el.ownerDocument.hidden) {
+ onLayoutChange();
+ return;
+ }
+ layoutChanged = true;
+ if (!parkIfHeld()) {
+ extendFollow();
+ }
+ requestTick();
+ };
+
const resizeObserver = new ResizeObserver(onLayoutChange);
- const mutationObserver = new MutationObserver(onLayoutChange);
+ const mutationObserver = new MutationObserver(onMutation);
const onViewportResize = onLayoutChange;
// Fresh attach always starts pinned. Rebinds to the SAME element must not pin or reset detach
@@ -617,6 +710,8 @@ export function useIntentAwareAutoScroll(): {
extendFollow();
if (el.scrollHeight > el.clientHeight) {
el.scrollTo({ top: el.scrollHeight, behavior: "instant" });
+ } else {
+ pendingInitialPin = true;
}
setIsAtBottom(true);
}
@@ -647,6 +742,12 @@ export function useIntentAwareAutoScroll(): {
el.addEventListener("touchstart", onTouchStart, { passive: true });
el.addEventListener("touchmove", onTouchMove, { passive: true });
el.addEventListener("scroll", onScroll, { passive: true });
+ el.ownerDocument.addEventListener("keydown", onKeyDown, {
+ passive: true,
+ });
+ el.addEventListener("pointerdown", onPointerDown, { passive: true });
+ el.ownerDocument.addEventListener("pointerup", onPointerUp, true);
+ el.ownerDocument.addEventListener("pointercancel", onPointerUp, true);
// ResizeObserver covers window resizes. visualViewport.resize is the
// only signal for iOS software-keyboard changes, where the visual
// viewport shrinks without the element's clientHeight changing.
@@ -676,12 +777,17 @@ export function useIntentAwareAutoScroll(): {
rafId = null;
}
clearSettleCheck();
+ marker().removeAttribute("data-aui-following");
resizeObserver.disconnect();
mutationObserver.disconnect();
el.removeEventListener("wheel", onWheel);
el.removeEventListener("touchstart", onTouchStart);
el.removeEventListener("touchmove", onTouchMove);
el.removeEventListener("scroll", onScroll);
+ el.ownerDocument.removeEventListener("keydown", onKeyDown);
+ el.removeEventListener("pointerdown", onPointerDown);
+ el.ownerDocument.removeEventListener("pointerup", onPointerUp, true);
+ el.ownerDocument.removeEventListener("pointercancel", onPointerUp, true);
window.visualViewport?.removeEventListener("resize", onViewportResize);
scrollImplRef.current = () => {
/* no viewport mounted */
@@ -692,14 +798,13 @@ export function useIntentAwareAutoScroll(): {
adjustImplRef.current = () => {
/* no viewport mounted */
};
+ tickRequestRef.current = () => undefined;
};
},
[aui, setIsAtBottom],
);
// Thread lifecycle moments that always pin, regardless of detach state.
- // "auto" respects CSS smooth scroll for runStart (new turns glide in);
- // "instant" snaps for load/switch where animation is wasted.
const pinToBottom = useCallback((behavior: ScrollBehavior) => {
userDetachedRef.current = false;
scrollImplRef.current(behavior);
@@ -708,7 +813,7 @@ export function useIntentAwareAutoScroll(): {
useAuiEvent("thread.runStart", () => {
runStartedHereRef.current = true;
runEndAtRef.current = Number.NEGATIVE_INFINITY;
- pinToBottom("auto");
+ pinToBottom("instant");
});
useAuiEvent("thread.runEnd", () => {
runEndAtRef.current = performance.now();
@@ -748,6 +853,7 @@ export function useIntentAwareAutoScroll(): {
subscribe,
detachFromBottom,
adjustForContentInsertedAbove,
+ notifyContentResized,
}),
[
scrollToBottom,
@@ -755,8 +861,9 @@ export function useIntentAwareAutoScroll(): {
subscribe,
detachFromBottom,
adjustForContentInsertedAbove,
+ notifyContentResized,
],
);
- return { ref, context };
+ return { ref, markerRef, context };
}
diff --git a/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts b/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts
index 8d1c22b0ed7..2c3be2c8bda 100644
--- a/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts
+++ b/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts
@@ -1,93 +1,214 @@
// 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 { useEffect, useRef, useState } from "react";
-import type {
- ReasoningHighlightReply,
- ReasoningHighlightRequest,
+import type { HighlightResult } from "@streamdown/code";
+import { useChatRuntimeStore } from "@/features/chat";
+import {
+ reasoningHighlightFailure,
+ type ReasoningHighlightMessage,
+ type ReasoningHighlightReply,
+ type ReasoningHighlightRequest,
} from "./reasoning-highlight";
+import { createStreamActivity, type StreamActivity } from "./stream-activity";
-export type ReasoningLineTokens = Map<
- number,
- ReasoningHighlightReply["lines"][number]["tokens"]
->;
+export type HighlightWorkerState =
+ | "untested"
+ | "ready"
+ | "stalled"
+ | "unavailable";
+
+const READY_TIMEOUT_MS = 5_000;
+const REPLY_SILENCE_MS = 15_000;
+const IDLE_TEARDOWN_MS = 10_000;
+let state: HighlightWorkerState = "untested";
let worker: Worker | null = null;
-let nextClient = 0;
+let boot: { instance: Worker; timer: ReturnType<typeof setTimeout> } | null =
+ null;
let idle: ReturnType<typeof setTimeout> | undefined;
+let nextClient = 0;
const listeners = new Map<number, (reply: ReasoningHighlightReply) => void>();
+const patientClients = new Set<number>();
+const awaitingReply = new Set<number>();
+let silence: ReturnType<typeof setTimeout> | undefined;
+let activity: StreamActivity | null = null;
+
+export const highlightWorkerState = (): HighlightWorkerState => state;
+
+export const streamActive = (): boolean =>
+ (activity ??= createStreamActivity(useChatRuntimeStore)).active();
+
+const clearBoot = (instance: Worker): void => {
+ if (boot?.instance !== instance) return;
+ clearTimeout(boot.timer);
+ boot = null;
+};
+
+const afterQueuedMessages = (callback: () => void): void => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => {
+ channel.port1.close();
+ callback();
+ };
+ channel.port2.postMessage(0);
+};
+
+const flushListeners = (spared?: ReadonlySet<number>): void => {
+ const waiting = [...listeners].filter(([id]) => !spared?.has(id));
+ const deliver = (): void => {
+ const next = waiting.shift();
+ if (next === undefined) return;
+ const [id, listener] = next;
+ if (listeners.get(id) === listener) {
+ listeners.delete(id);
+ listener(reasoningHighlightFailure(id, 0));
+ }
+ if (waiting.length > 0) setTimeout(deliver, 0);
+ };
+ if (waiting.length > 0) setTimeout(deliver, 0);
+};
+
+function fail(instance: Worker, reason: string): void {
+ if (worker !== instance) return;
+ state = "unavailable";
+ clearBoot(instance);
+ if (idle) clearTimeout(idle);
+ worker = null;
+ instance.terminate();
+ console.warn(
+ "[Unsloth Code] highlight worker unavailable, highlighting on the main thread:",
+ reason,
+ );
+ flushListeners();
+}
+
+function stall(instance: Worker): void {
+ if (worker !== instance || boot?.instance !== instance) return;
+ state = "stalled";
+ console.warn(
+ "[Unsloth Code] highlight worker did not answer within",
+ READY_TIMEOUT_MS,
+ "ms, highlighting on the main thread until it does",
+ );
+ flushListeners(patientClients);
+}
-function getWorker(): Worker | null {
+function silenced(instance: Worker): void {
+ if (worker !== instance || boot?.instance === instance) return;
+ if (awaitingReply.size === 0) return;
+ state = "stalled";
+ console.warn(
+ "[Unsloth Code] highlight worker sent nothing for",
+ REPLY_SILENCE_MS,
+ "ms, highlighting on the main thread until it does",
+ );
+ flushListeners(patientClients);
+}
+
+const watchSilence = (instance: Worker): void => {
+ if (silence) clearTimeout(silence);
+ silence = undefined;
+ if (awaitingReply.size === 0) return;
+ silence = setTimeout(() => {
+ silence = undefined;
+ afterQueuedMessages(() => silenced(instance));
+ }, REPLY_SILENCE_MS);
+};
+
+function getWorker(patient = false): Worker | null {
+ if (state === "unavailable") return null;
+ if (state === "stalled" && !patient) return null;
if (idle) clearTimeout(idle);
if (worker) return worker;
- if (typeof Worker === "undefined") return null;
+ if (typeof Worker === "undefined") {
+ state = "unavailable";
+ return null;
+ }
+ let instance: Worker;
try {
- worker = new Worker(
+ instance = new Worker(
new URL("./reasoning-highlight.worker.ts", import.meta.url),
{ type: "module" },
);
- worker.onmessage = ({ data }: MessageEvent<ReasoningHighlightReply>) =>
- listeners.get(data.client)?.(data);
- worker.onerror = () => {
- worker?.terminate();
- worker = null;
- };
- return worker;
- } catch {
+ } catch (error) {
+ state = "unavailable";
+ console.warn(
+ "[Unsloth Code] highlight worker unavailable, highlighting on the main thread:",
+ error,
+ );
return null;
}
+ instance.onmessage = ({ data }: MessageEvent<ReasoningHighlightMessage>) => {
+ if (instance !== worker) return;
+ if ("ready" in data) {
+ clearBoot(instance);
+ state = "ready";
+ watchSilence(instance);
+ if (listeners.size === 0) scheduleIdle();
+ return;
+ }
+ if (state === "stalled" && boot === null) state = "ready";
+ listeners.get(data.client)?.(data);
+ watchSilence(instance);
+ };
+ instance.onerror = (event) => fail(instance, event.message || event.type);
+ worker = instance;
+ boot = {
+ instance,
+ timer: setTimeout(
+ () => afterQueuedMessages(() => stall(instance)),
+ READY_TIMEOUT_MS,
+ ),
+ };
+ return instance;
+}
+
+function scheduleIdle(): void {
+ if (idle) clearTimeout(idle);
+ idle = setTimeout(() => {
+ if (!worker || boot?.instance === worker) return;
+ worker.terminate();
+ worker = null;
+ if (state === "stalled") state = "untested";
+ }, IDLE_TEARDOWN_MS);
}
-/** Text is synchronous; expensive grammar work must never hold up chat or scrolling. */
-export function useReasoningHighlight(
+export function requestFullHighlight(
source: string,
language: string | null,
- lines: number[],
-): ReasoningLineTokens {
- const [tokens, setTokens] = useState<ReasoningLineTokens>(() => new Map());
- const client = useRef<number | null>(null);
- const revision = useRef(0);
- const sent = useRef<{ worker: Worker; source: string } | null>(null);
- const lineKey = lines.join(",");
- useEffect(() => {
- const instance = getWorker();
- if (!instance) return;
- const id = (client.current ??= ++nextClient);
- const version = ++revision.current;
- listeners.set(id, (reply) => {
- if (reply.revision !== version) return;
- setTokens(new Map(reply.lines.map(({ line, tokens }) => [line, tokens])));
- });
- const request: ReasoningHighlightRequest = {
- client: id,
- revision: version,
- source:
- sent.current?.worker === instance &&
- source.startsWith(sent.current.source)
- ? {
- from: sent.current.source.length,
- text: source.slice(sent.current.source.length),
- }
- : source,
- language,
- lines: lineKey.split(",").filter(Boolean).map(Number),
- };
- instance.postMessage(request);
- sent.current = { worker: instance, source };
- }, [source, language, lineKey]);
- useEffect(
- () => () => {
- if (client.current !== null) {
- sent.current = null;
- listeners.delete(client.current);
- worker?.postMessage({ cancel: client.current });
- }
- if (listeners.size === 0)
- idle = setTimeout(() => {
- worker?.terminate();
- worker = null;
- }, 10_000);
- },
- [],
- );
- return tokens;
+ onResult: (result: HighlightResult | null) => void,
+ speculative = false,
+ patient = !speculative,
+): (() => void) | null {
+ const instance = getWorker(patient);
+ if (!instance) return null;
+ const id = ++nextClient;
+ if (patient) patientClients.add(id);
+ listeners.set(id, (reply) => {
+ if (!reply.failed && (reply.revision !== 1 || !reply.result)) return;
+ listeners.delete(id);
+ patientClients.delete(id);
+ awaitingReply.delete(id);
+ onResult(reply.failed ? null : (reply.result as HighlightResult));
+ if (listeners.size === 0 && worker) scheduleIdle();
+ });
+ const request: ReasoningHighlightRequest = {
+ client: id,
+ revision: 1,
+ source,
+ language,
+ lines: [],
+ full: true,
+ ...(speculative ? { speculative: true } : {}),
+ };
+ instance.postMessage(request);
+ awaitingReply.add(id);
+ if (!silence) watchSilence(instance);
+ return () => {
+ if (!listeners.has(id)) return;
+ listeners.delete(id);
+ patientClients.delete(id);
+ awaitingReply.delete(id);
+ worker?.postMessage({ cancel: id });
+ if (listeners.size === 0 && worker) scheduleIdle();
+ };
}
diff --git a/studio/frontend/src/components/assistant-ui/use-thinking-code-colour.ts b/studio/frontend/src/components/assistant-ui/use-thinking-code-colour.ts
new file mode 100644
index 00000000000..1480ab83d68
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/use-thinking-code-colour.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 type { HighlightResult } from "@streamdown/code";
+import { type RefObject, useEffect, useRef, useState } from "react";
+import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
+import {
+ cachedSettledColour,
+ keepUnchangedLines,
+ rememberSettledColour,
+} from "./reasoning-code-colour";
+import { requestFullHighlight } from "./use-reasoning-highlight";
+
+export const LIVE_COLOUR_MS = 250;
+
+const OBSERVES = typeof IntersectionObserver !== "undefined";
+
+const viewportOf = (element: Element): Element | null =>
+ element.closest(".aui-thread-viewport");
+
+// Worker colours for a thinking code block: settled ones once near the viewport, growing ones
+// every LIVE_COLOUR_MS while on screen (possibly for a shorter source; callers re-check lines).
+export function useThinkingCodeColour(
+ surface: RefObject<HTMLElement | null>,
+ source: string,
+ language: string | null,
+ settled: boolean,
+): HighlightResult | null {
+ const [colour, setColour] = useState<{
+ source: string;
+ result: HighlightResult;
+ } | null>(null);
+ const [reached, setReached] = useState(!OBSERVES);
+ const [visible, setVisible] = useState(!OBSERVES);
+ const latest = useRef(source);
+ const flight = useRef<{
+ busy: boolean;
+ off: boolean;
+ startedAt: number;
+ cancel: (() => void) | null;
+ }>({ busy: false, off: false, startedAt: Number.NEGATIVE_INFINITY, cancel: null });
+ useEffect(() => {
+ latest.current = source;
+ });
+
+ const held = colour !== null && colour.source === source ? colour.result : null;
+ const final = settled ? (held ?? cachedSettledColour(language, source)) : null;
+ const coloured = final !== null;
+ const caughtUp = !settled && colour !== null && colour.source === source;
+
+ useEffect(() => {
+ const element = surface.current;
+ if (!settled || reached || coloured || !element) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (!entries.some((entry) => entry.isIntersecting)) return;
+ observer.disconnect();
+ setReached(true);
+ },
+ { root: viewportOf(element), rootMargin: "100% 0px" },
+ );
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [surface, settled, reached, coloured]);
+
+ useEffect(() => {
+ if (!settled || !reached || coloured) return;
+ let live = true;
+ const cancel = requestFullHighlight(
+ source,
+ language,
+ (late) => {
+ if (!live || late === null) return;
+ rememberSettledColour(language, source, late);
+ setColour((old) => ({
+ source,
+ result: keepUnchangedLines(old?.result ?? null, late),
+ }));
+ },
+ true,
+ );
+ return () => {
+ live = false;
+ cancel?.();
+ };
+ }, [settled, reached, coloured, source, language]);
+
+ useEffect(() => {
+ const element = surface.current;
+ if (settled || !OBSERVES || !element) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ const entry = entries.at(-1);
+ if (entry) setVisible(entry.isIntersecting);
+ },
+ { root: viewportOf(element) },
+ );
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [surface, settled]);
+
+ useEffect(() => {
+ const state = flight.current;
+ if (settled || !visible || caughtUp || state.busy || state.off) return;
+ if (source.length > MAX_HIGHLIGHT_CHARS) return;
+ const timer = setTimeout(
+ () => {
+ const asked = latest.current;
+ state.busy = true;
+ state.startedAt = performance.now();
+ state.cancel = requestFullHighlight(
+ asked,
+ language,
+ (result) => {
+ state.busy = false;
+ state.cancel = null;
+ if (result === null) {
+ state.off = true;
+ return;
+ }
+ setColour((old) => ({
+ source: asked,
+ result: keepUnchangedLines(old?.result ?? null, result),
+ }));
+ },
+ true,
+ );
+ if (state.cancel === null) {
+ state.busy = false;
+ state.off = true;
+ }
+ },
+ Math.max(0, state.startedAt + LIVE_COLOUR_MS - performance.now()),
+ );
+ return () => clearTimeout(timer);
+ }, [settled, visible, caughtUp, source, language, colour]);
+
+ useEffect(() => {
+ const state = flight.current;
+ return () => {
+ state.cancel?.();
+ state.cancel = null;
+ state.busy = false;
+ };
+ }, []);
+
+ return final ?? colour?.result ?? null;
+}
diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsx
index 406e7ab9e3e..43f0073fcaa 100644
--- a/studio/frontend/src/components/floating-monitor.tsx
+++ b/studio/frontend/src/components/floating-monitor.tsx
@@ -510,7 +510,7 @@ export function FloatingMonitor() {
// follows the painted width and falls back to the committed one.
const [paintedSettingsWidth, setPaintedSettingsWidth] = useState(0);
useEffect(() => {
- if (!(isChatRoute && settingsPanelOpen)) {
+ if (!(isOpen && isChatRoute && settingsPanelOpen)) {
setPaintedSettingsWidth(0);
return;
}
@@ -528,7 +528,7 @@ export function FloatingMonitor() {
const observer = new ResizeObserver(measure);
observer.observe(panel);
return () => observer.disconnect();
- }, [isChatRoute, settingsPanelOpen, isMobile]);
+ }, [isOpen, isChatRoute, settingsPanelOpen, isMobile]);
// Same lag as the settings panel: the sidebar paints per frame and commits
// on release, so a docked monitor could sit under a grown sidebar.
@@ -538,7 +538,7 @@ export function FloatingMonitor() {
// state that takes the monitor's room.
const [sidebarHoldsRail, setSidebarHoldsRail] = useState(false);
useEffect(() => {
- const sidebar = document.querySelector('[data-slot="sidebar"]');
+ const sidebar = isOpen ? document.querySelector('[data-slot="sidebar"]') : null;
if (!sidebar) {
setPaintedSidebarWidth(0);
setSidebarHoldsRail(false);
@@ -556,7 +556,7 @@ export function FloatingMonitor() {
const observer = new ResizeObserver(measure);
observer.observe(sidebar);
return () => observer.disconnect();
- }, [isMobile]);
+ }, [isOpen, isMobile]);
// `useIsMobile` only notifies when the 768 px breakpoint is crossed, and the
// two width stores stop notifying at their maxima, so the capacity decision
diff --git a/studio/frontend/src/components/sidebar-edge-trigger.tsx b/studio/frontend/src/components/sidebar-edge-trigger.tsx
index a731f83daf8..a9945351ab7 100644
--- a/studio/frontend/src/components/sidebar-edge-trigger.tsx
+++ b/studio/frontend/src/components/sidebar-edge-trigger.tsx
@@ -7,6 +7,7 @@ import { useSidebar } from "@/components/ui/sidebar";
import {
SIDEBAR_WIDTH_MIN,
clampSidebarWidth,
+ useSidebarWidth,
} from "@/hooks/use-sidebar-width";
import { useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
@@ -42,13 +43,15 @@ export function SidebarEdgeTrigger({
pinned,
setPeeking,
toggleSidebar,
+ } = useSidebar();
+ const {
width,
- widthScale,
- storedWidth,
- maxWidth,
+ scale: widthScale,
+ stored: storedWidth,
+ max: maxWidth,
setWidth,
resetWidth,
- } = useSidebar();
+ } = useSidebarWidth();
// A drag that reaches the minimum pins the sidebar part-way through, which
// would unmount this: the handle would lose pointer capture and the width
// would never commit. Hold on until the pointer is released.
@@ -56,7 +59,7 @@ export function SidebarEdgeTrigger({
const release = () => setHolding(false);
const sidebarShowing = isMobile ? openMobile : pinned;
- if (!isTauri || (sidebarShowing && !holding)) {
+ if (!isTauri) {
return null;
}
@@ -78,74 +81,56 @@ export function SidebarEdgeTrigger({
onFocus={() => setPeeking(true)}
onBlur={() => setPeeking(false)}
>
- <PanelResizeHandle
- edge="right"
- // Follows the pin, which a drag flips part-way through: from there the
- // handle resizes the sidebar it just opened and commits on release.
- open={pinned}
- width={width}
- stored={storedWidth}
- min={SIDEBAR_WIDTH_MIN}
- max={maxWidth}
- scale={widthScale}
- clamp={clampSidebarWidth}
- setWidth={setWidth}
- resetWidth={resetWidth}
- onToggle={toggleSidebar}
- // Start from what is on screen: held out, the panel is already at its
- // full width, so a drag carries on from there instead of jumping.
- measure={() => (peeking ? width : 0)}
- target={() =>
- ref.current?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]') ??
- null
- }
- cssVar="--sidebar-width"
- rootVar="--studio-sidebar-live-width"
- // The sidebar declares --sidebar-width on itself, so a live width
- // painted any higher up is shadowed. Queried, not `closest`: this
- // strip is the sidebar's sibling.
- scopedTarget={() =>
- ref.current
- ?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]')
- ?.querySelector<HTMLElement>('[data-slot="sidebar"]') ?? null
- }
- rootVarTargets={() =>
- Array.from(
- document.querySelectorAll<HTMLElement>(
- "[data-titlebar-live-width-scope]",
- ),
- )
- }
- label={t("shell.aria.resizeSidebar")}
- toggleLabel={t("shell.aria.openSidebar")}
- // The sidebar coming out says it better than a label would.
- hideTooltip={true}
- onHoverChange={setPeeking}
- dataSlot="sidebar-edge-trigger"
- className={cn(
- // Below the titlebar so the window controls and drag region keep
- // their clicks, above the panel it holds out so the edge still
- // answers under the sidebar. `block` beats the handle's
- // `hidden sm:block`, which a narrowed window would trip.
- "fixed bottom-0 left-0 right-auto top-[var(--studio-desktop-titlebar-height,48px)] z-[55] block",
- // The window edge and nothing more: every pixel here takes a click
- // from the page. Wider where the window is undecorated (Windows,
- // Linux, see `setup_custom_titlebar`): there the toolkit hit-tests
- // its own resize border inside the window, so 2px would land
- // entirely within it. macOS keeps that border outside the content.
- usesCustomTitlebar ? "w-3" : "w-0.5",
- // The sidebar sliding out is the hover feedback, not a hairline
- // hanging down the middle of the page.
- "after:hidden",
- // That hairline is also where the shared handle marks focus, and on
- // a 2px strip it would sit off-screen, so mark it on the strip.
- "focus-visible:bg-sidebar-ring/60",
- // The two-headed resize cursor other chat apps put here, not the
- // one-way `e-resize` of a collapsed panel border.
- "cursor-col-resize!",
- className,
- )}
- />
+ {(!sidebarShowing || holding) && (
+ <PanelResizeHandle
+ edge="right"
+ open={pinned}
+ width={width}
+ stored={storedWidth}
+ min={SIDEBAR_WIDTH_MIN}
+ max={maxWidth}
+ scale={widthScale}
+ clamp={clampSidebarWidth}
+ setWidth={setWidth}
+ resetWidth={resetWidth}
+ onToggle={toggleSidebar}
+ measure={() => (peeking ? width : 0)}
+ target={() =>
+ ref.current?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]') ??
+ null
+ }
+ cssVar="--sidebar-width"
+ rootVar="--studio-sidebar-live-width"
+ // The sidebar declares --sidebar-width itself, shadowing any ancestor.
+ scopedTarget={() =>
+ ref.current
+ ?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]')
+ ?.querySelector<HTMLElement>('[data-slot="sidebar"]') ?? null
+ }
+ rootVarTargets={() =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>(
+ "[data-titlebar-live-width-scope]",
+ ),
+ )
+ }
+ label={t("shell.aria.resizeSidebar")}
+ toggleLabel={t("shell.aria.openSidebar")}
+ hideTooltip={true}
+ onHoverChange={setPeeking}
+ dataSlot="sidebar-edge-trigger"
+ className={cn(
+ // Below the titlebar, above the held-out panel; `block` beats the handle's `hidden sm:block`.
+ "fixed bottom-0 left-0 right-auto top-[var(--studio-desktop-titlebar-height,48px)] z-[55] block",
+ // Undecorated windows (Windows, Linux) hit-test their resize border inside the content.
+ usesCustomTitlebar ? "w-3" : "w-0.5",
+ "after:hidden",
+ "focus-visible:bg-sidebar-ring/60",
+ "cursor-col-resize!",
+ className,
+ )}
+ />
+ )}
</div>
);
}
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index 3e6d44c3485..368fcfc5d33 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -12,6 +12,7 @@ import {
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import type { BackendStatus } from "@/hooks/use-tauri-backend";
+import { useDocumentFlag } from "@/lib/document-flag";
import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import { AnimatePresence, motion } from "motion/react";
@@ -446,6 +447,7 @@ function StartupSurface({ children }: { children: ReactNode }) {
* it is Z_LAYER.STARTUP_SCREEN, which lib/z-layers puts over both.
*/
export function ClosingScreen() {
+ useDocumentFlag("data-blocking-screen-open", true);
return (
// pointer-events-auto, not the inherited default: Radix parks pointer-events:none on
// <body> while any modal layer is open, and a quit raised from the window controls,
diff --git a/studio/frontend/src/components/tauri/viewport-backdrop.ts b/studio/frontend/src/components/tauri/viewport-backdrop.ts
new file mode 100644
index 00000000000..4256c80d3f9
--- /dev/null
+++ b/studio/frontend/src/components/tauri/viewport-backdrop.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const BACKDROP_ATTRIBUTES = ["data-state", "data-viewport-backdrop"];
+
+let backdropOpen = false;
+const backdropListeners = new Set<() => void>();
+let bodyChildObserver: MutationObserver | null = null;
+let backdropStateObserver: MutationObserver | null = null;
+
+function readViewportBackdrop(): void {
+ let next = false;
+ for (const child of document.body.children) {
+ if (
+ child.getAttribute("data-viewport-backdrop") === "true" &&
+ child.getAttribute("data-state") === "open"
+ ) {
+ next = true;
+ break;
+ }
+ }
+ if (next === backdropOpen) return;
+ backdropOpen = next;
+ for (const listener of backdropListeners) listener();
+}
+
+function watchBodyChildren(): void {
+ if (!backdropStateObserver) return;
+ backdropStateObserver.disconnect();
+ for (const child of document.body.children) {
+ backdropStateObserver.observe(child, {
+ attributes: true,
+ attributeFilter: BACKDROP_ATTRIBUTES,
+ });
+ }
+ readViewportBackdrop();
+}
+
+export function subscribeViewportBackdrop(listener: () => void): () => void {
+ const subscription = () => listener();
+ backdropListeners.add(subscription);
+ if (!bodyChildObserver && typeof MutationObserver !== "undefined") {
+ backdropStateObserver = new MutationObserver(readViewportBackdrop);
+ bodyChildObserver = new MutationObserver(watchBodyChildren);
+ bodyChildObserver.observe(document.body, { childList: true });
+ watchBodyChildren();
+ }
+ return () => {
+ backdropListeners.delete(subscription);
+ if (backdropListeners.size > 0) return;
+ bodyChildObserver?.disconnect();
+ backdropStateObserver?.disconnect();
+ bodyChildObserver = null;
+ backdropStateObserver = null;
+ backdropOpen = false;
+ };
+}
+
+export function getViewportBackdropOpen(): boolean {
+ return backdropOpen;
+}
diff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsx
index a8250eeedbc..993f409a7b2 100644
--- a/studio/frontend/src/components/tauri/window-titlebar.tsx
+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx
@@ -1,6 +1,10 @@
// 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 {
+ getViewportBackdropOpen,
+ subscribeViewportBackdrop,
+} from "@/components/tauri/viewport-backdrop";
import { useIsMobileShell } from "@/hooks/use-mobile";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useSidebarWidth } from "@/hooks/use-sidebar-width";
@@ -20,10 +24,19 @@ import {
useEffect,
useRef,
useState,
+ useSyncExternalStore,
} from "react";
const CUSTOM_TITLEBAR_PLATFORMS = ["win", "linux", "x11"] as const;
+function subscribeNever(): () => void {
+ return () => undefined;
+}
+
+function backdropClosed(): boolean {
+ return false;
+}
+
type WindowResizeDirection =
| "East"
| "North"
@@ -286,6 +299,11 @@ export function WindowTitlebar({
const [enabled] = useState(shouldUseCustomWindowTitlebar);
const [maximized, setMaximized] = useState(false);
const [focused, setFocused] = useState(true);
+ const backdropOpen = useSyncExternalStore(
+ enabled ? subscribeViewportBackdrop : subscribeNever,
+ enabled ? getViewportBackdropOpen : backdropClosed,
+ backdropClosed,
+ );
const { pinned, togglePinned } = useSidebarPin();
// Outside SidebarProvider, so read the same media query the provider does.
const isMobile = useIsMobileShell();
@@ -458,17 +476,22 @@ export function WindowTitlebar({
style={{ left: cornerLeft }}
/>
)}
- {/* One border for edge and corner: it snaps to device pixels where a 1px box blurs. Pinned, it
- is also the sidebar's full-height edge (app-sidebar drops border-r; dark has none). Dark
- hides it: any visible border there is lighter than both surfaces and reads as a white seam. */}
+ {/* Borders for edge and corner: they snap to device pixels where a 1px box blurs. Pinned, they
+ are also the sidebar's full-height edge (app-sidebar drops border-r; dark has none). Dark
+ hides them: any visible border there is lighter than both surfaces and reads as a white seam. */}
<div
className={cn(
"absolute top-0 right-0 h-[12px] border-t border-sidebar-edge dark:border-transparent",
- pinned &&
- "h-[calc(100dvh-var(--studio-custom-titlebar-height))] rounded-tl-[12px] border-l",
+ pinned && "rounded-tl-[12px] border-l",
)}
style={{ left: pinned ? cornerLeft : 0 }}
/>
+ {pinned && (
+ <div
+ className="absolute top-[12px] h-[calc(100dvh-var(--studio-custom-titlebar-height)-12px)] w-0 border-l border-sidebar-edge dark:border-transparent"
+ style={{ left: cornerLeft }}
+ />
+ )}
</div>
)}
<header
@@ -478,6 +501,7 @@ export function WindowTitlebar({
)}
data-titlebar-live-width-scope=""
data-slot="window-titlebar"
+ data-viewport-backdrop-open={backdropOpen ? "" : undefined}
aria-label="Window titlebar"
>
{showSidebarSurface && (
diff --git a/studio/frontend/src/components/ui/alert-dialog.tsx b/studio/frontend/src/components/ui/alert-dialog.tsx
index 1cf45f19a16..47369fb890c 100644
--- a/studio/frontend/src/components/ui/alert-dialog.tsx
+++ b/studio/frontend/src/components/ui/alert-dialog.tsx
@@ -4,8 +4,13 @@
import { AppPortalGate } from "@/components/app-readiness";
import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
import type * as React from "react";
+import { useContext } from "react";
import { Button } from "@/components/ui/button";
+import {
+ DropdownGlowContext,
+ dialogDropdownGlow,
+} from "@/components/ui/dropdown-glow";
import { cn } from "@/lib/utils";
function AlertDialog({
@@ -51,6 +56,7 @@ function AlertDialogOverlay({
function AlertDialogContent({
className,
+ children,
size = "default",
overlayClassName,
onOverlayClick,
@@ -61,6 +67,7 @@ function AlertDialogContent({
/** Alert dialogs ignore outside clicks; set this to cancel on backdrop click. */
onOverlayClick?: () => void;
}) {
+ const glow = dialogDropdownGlow(className, useContext(DropdownGlowContext));
return (
<AlertDialogPortal>
<AlertDialogOverlay className={overlayClassName} onClick={onOverlayClick} />
@@ -76,7 +83,11 @@ function AlertDialogContent({
className,
)}
{...props}
- />
+ >
+ <DropdownGlowContext.Provider value={glow}>
+ {children}
+ </DropdownGlowContext.Provider>
+ </AlertDialogPrimitive.Content>
</AlertDialogPortal>
);
}
diff --git a/studio/frontend/src/components/ui/combobox.tsx b/studio/frontend/src/components/ui/combobox.tsx
index 342a58e4990..63bc5a1ae36 100644
--- a/studio/frontend/src/components/ui/combobox.tsx
+++ b/studio/frontend/src/components/ui/combobox.tsx
@@ -12,6 +12,7 @@ import { createContext, useState } from "react";
import { Button } from "@/components/ui/button";
import { useDialogPortalContainer } from "@/components/ui/dialog";
+import { useDropdownGlow } from "@/components/ui/dropdown-glow";
import {
InputGroup,
InputGroupAddon,
@@ -174,6 +175,7 @@ function ComboboxContent({
<ComboboxPrimitive.Popup
ref={snappedRef}
data-slot="combobox-content"
+ data-dropdown-glow={useDropdownGlow()}
data-chips={!!anchor}
onWheel={(event) => {
onWheel?.(event);
diff --git a/studio/frontend/src/components/ui/context-menu.tsx b/studio/frontend/src/components/ui/context-menu.tsx
index be7e80b0154..5762eb5c32d 100644
--- a/studio/frontend/src/components/ui/context-menu.tsx
+++ b/studio/frontend/src/components/ui/context-menu.tsx
@@ -10,6 +10,7 @@ import { MenuChevronRightIcon } from "@/lib/chevron-icons";
import { MenuTickIcon } from "@/lib/tick-icon";
import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { useWindowChromeCollisionPadding } from "@/lib/window-chrome";
+import { useDropdownGlow } from "@/components/ui/dropdown-glow";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -80,6 +81,7 @@ function ContextMenuContent({
<ContextMenuPrimitive.Content
ref={snappedRef}
data-slot="context-menu-content"
+ data-dropdown-glow={useDropdownGlow()}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
className={cn(
"data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-edge-gain,1)),transparent)] bg-popover text-popover-foreground min-w-48 max-w-[calc(100vw-32px)] rounded-2xl p-1 shadow-2xl ring-1 duration-100 z-50 max-h-(--radix-context-menu-content-available-height) origin-(--radix-context-menu-content-transform-origin) flex flex-col overflow-hidden",
@@ -167,6 +169,7 @@ function ContextMenuSubContent({
<ContextMenuPrimitive.SubContent
ref={snappedRef}
data-slot="context-menu-sub-content"
+ data-dropdown-glow={useDropdownGlow()}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
// Capped and scrolled like ContextMenuContent, so a long list stays reachable.
className={cn(
diff --git a/studio/frontend/src/components/ui/dialog.tsx b/studio/frontend/src/components/ui/dialog.tsx
index 64c04dfe438..dfde28393ec 100644
--- a/studio/frontend/src/components/ui/dialog.tsx
+++ b/studio/frontend/src/components/ui/dialog.tsx
@@ -10,6 +10,10 @@ import type * as React from "react";
import { createContext, useContext } from "react";
import { Button } from "@/components/ui/button";
+import {
+ DropdownGlowContext,
+ dialogDropdownGlow,
+} from "@/components/ui/dropdown-glow";
import { cn } from "@/lib/utils";
import { Cancel01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -87,6 +91,11 @@ function DialogContent({
overlayPosition?: "fixed" | "absolute";
}) {
const resolvedContainer = container ?? null;
+ const inheritedGlow = useContext(DropdownGlowContext);
+ const glow =
+ resolvedContainer === null
+ ? dialogDropdownGlow(className, inheritedGlow)
+ : inheritedGlow;
return (
<DialogPortalContainerContext.Provider value={resolvedContainer}>
<DialogPortal container={resolvedContainer ?? undefined}>
@@ -121,7 +130,9 @@ function DialogContent({
}}
{...props}
>
- {children}
+ <DropdownGlowContext.Provider value={glow}>
+ {children}
+ </DropdownGlowContext.Provider>
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button
diff --git a/studio/frontend/src/components/ui/dropdown-glow.ts b/studio/frontend/src/components/ui/dropdown-glow.ts
new file mode 100644
index 00000000000..d65a0a93ba5
--- /dev/null
+++ b/studio/frontend/src/components/ui/dropdown-glow.ts
@@ -0,0 +1,24 @@
+// 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 { createContext, useContext } from "react";
+
+export type DropdownGlow = "card" | "picker";
+
+export const DropdownGlowContext = createContext<DropdownGlow | null>(null);
+
+const CARD_SURFACE = /(?:^|\s)(?:dialog-soft-surface|settings-surface)(?:\s|$)/;
+
+export function dialogDropdownGlow(
+ className: string | undefined,
+ inherited: DropdownGlow | null,
+): DropdownGlow | null {
+ if (className === undefined) return inherited;
+ return CARD_SURFACE.test(className) || className.includes("dark:bg-card")
+ ? "card"
+ : inherited;
+}
+
+export function useDropdownGlow(): DropdownGlow | undefined {
+ return useContext(DropdownGlowContext) ?? undefined;
+}
diff --git a/studio/frontend/src/components/ui/dropdown-menu.tsx b/studio/frontend/src/components/ui/dropdown-menu.tsx
index 567241b8ba4..ee5d675a17c 100644
--- a/studio/frontend/src/components/ui/dropdown-menu.tsx
+++ b/studio/frontend/src/components/ui/dropdown-menu.tsx
@@ -9,6 +9,7 @@ import { MenuChevronRightIcon } from "@/lib/chevron-icons";
import { useIsMobile } from "@/hooks/use-mobile";
import { snapRowInsets, useSnappedPaddingRef } from "@/lib/snap-padding";
import { useWindowChromeCollisionPadding } from "@/lib/window-chrome";
+import { useDropdownGlow } from "@/components/ui/dropdown-glow";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -52,6 +53,7 @@ function DropdownMenuContent({
<DropdownMenuPrimitive.Content
ref={snappedRef}
data-slot="dropdown-menu-content"
+ data-dropdown-glow={useDropdownGlow()}
sideOffset={sideOffset}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
align={align}
@@ -344,6 +346,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
ref={composedRef}
data-slot="dropdown-menu-sub-content"
+ data-dropdown-glow={useDropdownGlow()}
sideOffset={compactSideOffset}
alignOffset={resolvedAlignOffset}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
diff --git a/studio/frontend/src/components/ui/panel-drag-overlay.ts b/studio/frontend/src/components/ui/panel-drag-overlay.ts
new file mode 100644
index 00000000000..0e3c49dc353
--- /dev/null
+++ b/studio/frontend/src/components/ui/panel-drag-overlay.ts
@@ -0,0 +1,81 @@
+// 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 { Z_LAYER } from "@/lib/z-layers"
+
+// One fixed overlay owns the drag cursor and hit testing. Not `html[data-panel-resizing] *` or
+// inherited cursor / user-select / pointer-events on <body> or the inset: those restyle the whole DOM.
+const DRAG_OVERLAY_SLOT = "panel-resize-drag-overlay"
+const PANEL_RESIZING_ATTRIBUTE = "data-panel-resizing"
+let dragOverlayOwners = 0
+let resizingHolders = 0
+const DRAG_SLOP = 4
+
+function holdResizing(): void {
+ resizingHolders += 1
+ if (resizingHolders > 1) return
+ document.documentElement.setAttribute(PANEL_RESIZING_ATTRIBUTE, "true")
+}
+
+function releaseResizing(): void {
+ if (resizingHolders === 0) return
+ resizingHolders -= 1
+ if (resizingHolders > 0) return
+ document.documentElement.removeAttribute(PANEL_RESIZING_ATTRIBUTE)
+}
+
+export function acquireDragOverlay(): void {
+ dragOverlayOwners += 1
+ if (dragOverlayOwners > 1) return
+ holdResizing()
+ const el = document.createElement("div")
+ el.setAttribute("data-slot", DRAG_OVERLAY_SLOT)
+ el.setAttribute("aria-hidden", "true")
+ const s = el.style
+ s.position = "fixed"
+ s.inset = "0"
+ s.zIndex = String(Z_LAYER.DRAG_CURSOR_OVERLAY)
+ s.background = "transparent"
+ // The hit target for the whole viewport: keeps hover and click off the content below.
+ s.pointerEvents = "auto"
+ s.cursor = "col-resize"
+ s.userSelect = "none"
+ s.touchAction = "none"
+ document.body.appendChild(el)
+}
+
+export function releaseDragOverlay(): void {
+ if (dragOverlayOwners === 0) return
+ dragOverlayOwners -= 1
+ if (dragOverlayOwners > 0) return
+ document
+ .querySelector(`[data-slot="${DRAG_OVERLAY_SLOT}"]`)
+ ?.remove()
+ releaseResizing()
+}
+
+export function armPanelDrag(startX: number): {
+ move: (x: number) => void
+ release: () => void
+} {
+ holdResizing()
+ let overlaid = false
+ let released = false
+ return {
+ move: (x) => {
+ if (overlaid || released || Math.abs(x - startX) < DRAG_SLOP) return
+ overlaid = true
+ acquireDragOverlay()
+ },
+ release: () => {
+ if (released) return
+ released = true
+ if (overlaid) releaseDragOverlay()
+ releaseResizing()
+ },
+ }
+}
+
+export function panelDragInProgress(): boolean {
+ return dragOverlayOwners > 0
+}
diff --git a/studio/frontend/src/components/ui/panel-resize-handle.tsx b/studio/frontend/src/components/ui/panel-resize-handle.tsx
index 0908b9de2d6..0111339f0bd 100644
--- a/studio/frontend/src/components/ui/panel-resize-handle.tsx
+++ b/studio/frontend/src/components/ui/panel-resize-handle.tsx
@@ -13,7 +13,7 @@ import {
} from "@/components/ui/tooltip"
import { getClientPlatform } from "@/components/tauri/window-titlebar"
import { PANEL_RESIZE_SCOPED_VARS_ENABLED } from "@/components/ui/panel-resize-recalc-flags"
-import { Z_LAYER } from "@/lib/z-layers"
+import { acquireDragOverlay, releaseDragOverlay } from "@/components/ui/panel-drag-overlay"
/** Pointer travel (px) below which a drag counts as a plain click. */
const DRAG_SLOP = 4
@@ -22,61 +22,6 @@ const CLICK_COMPAT_WINDOW_MS = 300
/** Arrow-key resize step for keyboard users. */
const RESIZE_STEP = 16
-// A drag needs one cursor over the whole viewport, because the pointer travels across buttons and
-// text that would otherwise claim their own. That used to be `html[data-panel-resizing] *` plus
-// `cursor`/`user-select` on <body>. Both reach every element in the document: the universal
-// selector matches all of them, and `cursor` and `user-select` are inherited, so writing them on
-// <body> marks inherited style dirty for everything below it. The cost is therefore proportional to
-// the STANDING DOM rather than to the one thing that changed, which is the same shape as the
-// sidebar-width writes scoped in #9400/#9441. The same is true of the rule that blanked pointer
-// events on the sidebar and on [data-slot="sidebar-inset"], the <main> holding the whole app
-// including the thread: `pointer-events` is inherited too, so that write dirtied the thread's
-// subtree on both flips as well. A single fixed element on top of the viewport does both jobs with
-// an invalidation set of one element. It carries the cursor, and by being the hit test target for
-// the whole viewport it keeps hover and click off the content underneath. It is transparent and it
-// is removed the instant the drag ends, so nothing about what the user sees changes.
-const DRAG_OVERLAY_SLOT = "panel-resize-drag-overlay"
-/** Nested drags cannot happen through pointer capture, but a stuck overlay would
- * swallow the whole UI, so ownership is explicit rather than assumed. */
-let dragOverlayOwners = 0
-
-function acquireDragOverlay(): void {
- dragOverlayOwners += 1
- if (dragOverlayOwners > 1) return
- const el = document.createElement("div")
- el.setAttribute("data-slot", DRAG_OVERLAY_SLOT)
- // Decorative and non-interactive as far as assistive tech is concerned: it
- // exists only to own the cursor while the pointer is already captured.
- el.setAttribute("aria-hidden", "true")
- const s = el.style
- s.position = "fixed"
- s.inset = "0"
- // Top of the named scale, not a hand-picked large number: the rules it replaces were `!important`
- // and blanked whole subtrees, so anything it did not out-rank it would only partly stand in for.
- s.zIndex = String(Z_LAYER.DRAG_CURSOR_OVERLAY)
- s.background = "transparent"
- // Explicit, because it is load-bearing rather than incidental. Being the hit
- // test target for the whole viewport is what keeps hover and click off the
- // content underneath, which is the job `pointer-events: none` on
- // [data-slot="sidebar-inset"] used to do by dirtying the thread's subtree.
- s.pointerEvents = "auto"
- // col-resize unconditionally, which is what the replaced rule did even when a
- // collapsed edge was being dragged open.
- s.cursor = "col-resize"
- s.userSelect = "none"
- s.touchAction = "none"
- document.body.appendChild(el)
-}
-
-function releaseDragOverlay(): void {
- if (dragOverlayOwners === 0) return
- dragOverlayOwners -= 1
- if (dragOverlayOwners > 0) return
- document
- .querySelector(`[data-slot="${DRAG_OVERLAY_SLOT}"]`)
- ?.remove()
-}
-
type DragState = {
startX: number
startWidth: number
@@ -249,7 +194,6 @@ export function PanelResizeHandle({
}
rootTargetsRef.current = []
targetRef.current?.removeAttribute("data-resizing")
- document.documentElement.removeAttribute("data-panel-resizing")
targetRef.current = null
setDragging(false)
if (overlayHeldRef.current) {
@@ -277,7 +221,6 @@ export function PanelResizeHandle({
pendingRef.current = start
rawRef.current = start
targetRef.current?.setAttribute("data-resizing", "true")
- document.documentElement.setAttribute("data-panel-resizing", "true")
setDragging(true)
overlayHeldRef.current = true
acquireDragOverlay()
@@ -377,6 +320,9 @@ export function PanelResizeHandle({
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={endDrag}
+ onLostPointerCapture={() => {
+ if (dragRef.current) endDrag()
+ }}
onKeyDown={handleKeyDown}
onClick={() => {
// Switch and voice control activate by dispatching a bare click
diff --git a/studio/frontend/src/components/ui/popover.tsx b/studio/frontend/src/components/ui/popover.tsx
index 7c250aa6fa1..44708511f07 100644
--- a/studio/frontend/src/components/ui/popover.tsx
+++ b/studio/frontend/src/components/ui/popover.tsx
@@ -5,10 +5,15 @@
import { Popover as PopoverPrimitive } from "radix-ui";
import type * as React from "react";
+import { useContext } from "react";
import { useDialogPortalContainer } from "@/components/ui/dialog";
import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { useWindowChromeCollisionPadding } from "@/lib/window-chrome";
+import {
+ type DropdownGlow,
+ DropdownGlowContext,
+} from "@/components/ui/dropdown-glow";
import { cn } from "@/lib/utils";
function Popover({
@@ -29,12 +34,16 @@ function PopoverContent({
sideOffset = 0,
collisionPadding,
container,
+ dropdownGlow,
+ children,
ref,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content> & {
container?: HTMLElement | null;
+ dropdownGlow?: DropdownGlow;
}) {
const snappedRef = useSnappedPaddingRef(ref);
+ const inheritedGlow = useContext(DropdownGlowContext);
// Inside a modal dialog the body scroll lock swallows wheel events on
// body-portaled content; portal into the dialog instead (like Select).
const dialogContainer = useDialogPortalContainer();
@@ -45,6 +54,7 @@ function PopoverContent({
<PopoverPrimitive.Content
ref={snappedRef}
data-slot="popover-content"
+ data-dropdown-glow={inheritedGlow ?? undefined}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
align={align}
sideOffset={sideOffset}
@@ -54,7 +64,11 @@ function PopoverContent({
className,
)}
{...props}
- />
+ >
+ <DropdownGlowContext.Provider value={dropdownGlow ?? inheritedGlow}>
+ {children}
+ </DropdownGlowContext.Provider>
+ </PopoverPrimitive.Content>
</PopoverPrimitive.Portal>
);
}
diff --git a/studio/frontend/src/components/ui/select.tsx b/studio/frontend/src/components/ui/select.tsx
index 5cb8de8f1ea..a7fa9b10fc0 100644
--- a/studio/frontend/src/components/ui/select.tsx
+++ b/studio/frontend/src/components/ui/select.tsx
@@ -16,6 +16,7 @@ import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { useWindowChromeCollisionPadding } from "@/lib/window-chrome";
import { cn } from "@/lib/utils";
import { useDialogPortalContainer } from "@/components/ui/dialog";
+import { useDropdownGlow } from "@/components/ui/dropdown-glow";
import { HugeiconsIcon } from "@hugeicons/react";
const SelectOpenContext = createContext(false);
@@ -130,6 +131,7 @@ function SelectContent({
<SelectPrimitive.Content
ref={snappedRef}
data-slot="select-content"
+ data-dropdown-glow={useDropdownGlow()}
collisionPadding={useWindowChromeCollisionPadding(collisionPadding)}
data-align-trigger={position === "item-aligned"}
className={cn(
diff --git a/studio/frontend/src/components/ui/sidebar.tsx b/studio/frontend/src/components/ui/sidebar.tsx
index cfd9aaac0d2..17bbe234484 100644
--- a/studio/frontend/src/components/ui/sidebar.tsx
+++ b/studio/frontend/src/components/ui/sidebar.tsx
@@ -60,13 +60,6 @@ type SidebarContextProps = {
/** The unpinned sidebar is held out over the content, from the window edge. */
peeking: boolean
setPeeking: (value: boolean) => void
- width: number
- /** Browser interface scale: the sidebar renders at width * widthScale. */
- widthScale: number
- storedWidth: number
- maxWidth: number
- setWidth: (value: number) => void
- resetWidth: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
@@ -105,11 +98,7 @@ function SidebarProvider({
const [openMobile, setOpenMobile] = React.useState(false)
const {
width,
- max: maxWidth,
scale: widthScale,
- stored: storedWidth,
- setWidth,
- resetWidth,
} = useSidebarWidth()
const prevIsMobileRef = React.useRef(isMobile)
@@ -203,14 +192,8 @@ function SidebarProvider({
togglePinned,
peeking,
setPeeking,
- width,
- widthScale,
- storedWidth,
- maxWidth,
- setWidth,
- resetWidth,
}),
- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar, hasPinMode, pinned, setPinned, togglePinned, peeking, setPeeking, width, widthScale, storedWidth, maxWidth, setWidth, resetWidth]
+ [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar, hasPinMode, pinned, setPinned, togglePinned, peeking, setPeeking]
)
return (
@@ -297,8 +280,9 @@ function Sidebar({
collapsible?: "offcanvas" | "icon" | "none"
collapseToZero?: boolean
}) {
- const { isMobile, state, openMobile, setOpenMobile, hasPinMode, pinned, peeking, setPeeking, width, widthScale } =
+ const { isMobile, state, openMobile, setOpenMobile, hasPinMode, pinned, peeking, setPeeking } =
useSidebar()
+ const { width, scale: widthScale } = useSidebarWidth()
// Only a sidebar that collapses to nothing has an edge to be held out from.
const holdsOut = hasPinMode && !pinned && collapseToZero
const heldOut = holdsOut && peeking
@@ -481,8 +465,15 @@ function SidebarResizeHandle({
className?: string
side?: "left" | "right"
}) {
- const { open, toggleSidebar, width, widthScale, storedWidth, maxWidth, setWidth, resetWidth } =
- useSidebar()
+ const { open, toggleSidebar } = useSidebar()
+ const {
+ width,
+ scale: widthScale,
+ stored: storedWidth,
+ max: maxWidth,
+ setWidth,
+ resetWidth,
+ } = useSidebarWidth()
const ref = React.useRef<HTMLDivElement>(null)
const t = useT()
diff --git a/studio/frontend/src/components/ui/sonner.tsx b/studio/frontend/src/components/ui/sonner.tsx
index 92c414bccbe..37d805eca49 100644
--- a/studio/frontend/src/components/ui/sonner.tsx
+++ b/studio/frontend/src/components/ui/sonner.tsx
@@ -10,6 +10,7 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { useTheme } from "@/features/settings/stores/theme-store";
import { createLoadingToastIcon } from "@/lib/toast";
+import { cornerInsetScope } from "@/lib/toast-offset";
import { Toaster as Sonner, type ToasterProps } from "sonner";
// Make toast text selectable. Sonner's onPointerDown calls setPointerCapture(), which steals the
@@ -40,6 +41,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
// display:contents adds no box; only carries the selection-fix handler.
// biome-ignore lint/a11y/noStaticElementInteractions: capture-only guard, not interactive
<div
+ ref={cornerInsetScope}
style={{ display: "contents" }}
onPointerDownCapture={handleToastPointerDownCapture}
>
diff --git a/studio/frontend/src/features/audio/components/music-edit-inputs.tsx b/studio/frontend/src/features/audio/components/music-edit-inputs.tsx
index 93a37ee96c8..5163e60df8c 100644
--- a/studio/frontend/src/features/audio/components/music-edit-inputs.tsx
+++ b/studio/frontend/src/features/audio/components/music-edit-inputs.tsx
@@ -4,7 +4,7 @@
import { Textarea } from "@/components/ui/textarea";
import { ParamSlider } from "@/features/chat";
import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";
-import { type JSX, type Ref, useEffect } from "react";
+import { type JSX, type Ref, useEffect, useState } from "react";
import type { AudioSourceStatus } from "../hooks/audio-source-state";
import {
EXTEND_MAX_S,
@@ -60,6 +60,7 @@ export function MusicEditInputs({
const action: MusicEditAction | null =
draft.action && actions.includes(draft.action) ? draft.action : null;
const sourceDurationS = draft.source?.durationS ?? null;
+ const [draggedExtendS, setDraggedExtendS] = useState<number | null>(null);
// The tabs always show a choice, so a missing or stale action takes the first one.
const firstAction = actions[0] ?? null;
@@ -133,7 +134,7 @@ export function MusicEditInputs({
durationS={preview.durationS}
src={preview.src}
label={preview.label}
- tailS={action === "extend" ? draft.extendS : 0}
+ tailS={action === "extend" ? (draggedExtendS ?? draft.extendS) : 0}
/>
)
}
@@ -209,7 +210,7 @@ export function MusicEditInputs({
max={1}
step={0.05}
onChange={(strength) => onChange({ strength })}
- displayValue={(draft.strength ?? defaultStrength).toFixed(2)}
+ format={(v) => v.toFixed(2)}
disabled={disabled}
info="Lower keeps more of the original."
/>
@@ -223,6 +224,7 @@ export function MusicEditInputs({
max={EXTEND_MAX_S}
step={1}
onChange={(extendS) => onChange({ extendS })}
+ onDraft={setDraggedExtendS}
disabled={disabled}
info="New music is added after the clip's end."
/>
diff --git a/studio/frontend/src/features/audio/pages/convert-page.tsx b/studio/frontend/src/features/audio/pages/convert-page.tsx
index 4be745b35ea..1fb00249b9d 100644
--- a/studio/frontend/src/features/audio/pages/convert-page.tsx
+++ b/studio/frontend/src/features/audio/pages/convert-page.tsx
@@ -207,7 +207,7 @@ function ConvertInputs({
max={24}
step={1}
disabled={disabled}
- displayValue={`${convert.pitch > 0 ? "+" : ""}${convert.pitch} st`}
+ format={(v) => `${v > 0 ? "+" : ""}${v} st`}
info={
pitchSupport.auto && convert.pitchAuto
? "Semitones added after matching the target's pitch, e.g. +12 to sing an octave up."
diff --git a/studio/frontend/src/features/audio/pages/edit-page.tsx b/studio/frontend/src/features/audio/pages/edit-page.tsx
index 024331275d8..bfd687a9f06 100644
--- a/studio/frontend/src/features/audio/pages/edit-page.tsx
+++ b/studio/frontend/src/features/audio/pages/edit-page.tsx
@@ -235,9 +235,10 @@ function EditInputs({
min={deliveryRange.speed[0]}
max={deliveryRange.speed[1]}
step={deliveryRange.speed[2]}
- displayValue={`${Number(delivery.speed.toFixed(2))}×`}
+ format={(v) => `${Number(v.toFixed(2))}×`}
disabled={disabled}
onChange={(speed) => setDelivery({ speed })}
+ commitWhileDragging
/>
<ParamSlider
label={EDIT_COPY.pitchLabel}
@@ -245,11 +246,10 @@ function EditInputs({
min={0}
max={deliveryRange.pitchSteps[1]}
step={1}
- displayValue={
- delivery.pitchSteps > 0 ? `+${delivery.pitchSteps} steps` : "Off"
- }
+ format={(v) => (v > 0 ? `+${v} steps` : "Off")}
disabled={disabled}
onChange={(pitchSteps) => setDelivery({ pitchSteps })}
+ commitWhileDragging
/>
<p className="text-ui-11p5 leading-snug text-muted-foreground">
{EDIT_COPY.pitchHint}
diff --git a/studio/frontend/src/features/audio/pages/music-page.tsx b/studio/frontend/src/features/audio/pages/music-page.tsx
index 0b578ea469e..48088a2b78e 100644
--- a/studio/frontend/src/features/audio/pages/music-page.tsx
+++ b/studio/frontend/src/features/audio/pages/music-page.tsx
@@ -152,6 +152,7 @@ function VariationsSlider({
valueSize={2}
disabled={disabled}
onChange={onChange}
+ commitWhileDragging
info="Several takes of the same request, kept together in history."
/>
{notice ? (
diff --git a/studio/frontend/src/features/audio/tools/clone-panels.tsx b/studio/frontend/src/features/audio/tools/clone-panels.tsx
index 2e205ecbb74..86a3adf38e5 100644
--- a/studio/frontend/src/features/audio/tools/clone-panels.tsx
+++ b/studio/frontend/src/features/audio/tools/clone-panels.tsx
@@ -262,7 +262,7 @@ const f5SpeedDialectPanel: AudioToolPanel<SpeedDialectValue> = {
max={2}
step={0.05}
disabled={disabled}
- displayValue={`${value.speed.toFixed(2)}×`}
+ format={(v) => `${v.toFixed(2)}×`}
onChange={(speed) => onChange({ ...value, speed })}
/>
{specs.some((spec) => spec.name === "dialect") ? (
diff --git a/studio/frontend/src/features/audio/tools/convert-panels.tsx b/studio/frontend/src/features/audio/tools/convert-panels.tsx
index 24051e172bd..3bdaaeb4a87 100644
--- a/studio/frontend/src/features/audio/tools/convert-panels.tsx
+++ b/studio/frontend/src/features/audio/tools/convert-panels.tsx
@@ -180,7 +180,7 @@ export const seedVcPanel: AudioToolPanel<SeedVcValue> = {
max={SEED_VC_LENGTH_RANGE.max}
step={0.05}
disabled={disabled}
- displayValue={`${value.length.toFixed(2)}×`}
+ format={(v) => `${v.toFixed(2)}×`}
info="Below 1 speeds the result up, above 1 slows it down."
onChange={(length) => onChange({ ...value, length })}
/>
diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.ts
index 7ae4680e9b5..33b38e1a2b4 100644
--- a/studio/frontend/src/features/browser/native-view.ts
+++ b/studio/frontend/src/features/browser/native-view.ts
@@ -10,13 +10,14 @@ import type { TranslationKey } from "@/i18n";
import type { InterpolationValues } from "@/i18n";
import { openExternalLink } from "@/lib/open-link";
import { toast } from "@/lib/toast";
-import { BROWSER_PAGE_INSET_VAR, CHAT_SETTINGS_INSET_VAR } from "@/lib/toast-offset";
+import { BROWSER_PAGE_INSET_VAR, CHAT_SETTINGS_INSET_VAR, cornerInsets } from "@/lib/toast-offset";
import { hostOf } from "./address";
import { approveChosenDownload, approveDownload, downloadSiteOf } from "./download-approval-queue";
import { abandonDownload, beginDownload, finishDownload, useDownloadActivity } from "./download-activity";
import { proxiedFavicon } from "./favicon";
import { useBrowserHistoryStore } from "./history-store";
import { decideNativeDownload } from "./native-downloads";
+import { outsideThread } from "./outside-thread";
import { callNative as call, nativeClearing, onNativeViewsClosed } from "./native-support";
import { useBrowserPrefsStore } from "./prefs-store";
import { type BrowserEntry, type BrowserTab, currentEntry, entryKey, useBrowserStore } from "./store";
@@ -403,7 +404,7 @@ const HOVER_ONLY = '[role="tooltip"], [data-slot="hover-card-content"]';
/** Boxes of `selector` over `rect` (anywhere when null), minus those holding `skip`. */
function overlays(selector: string, rect: DOMRect | null, skip: string | null = TOOLTIP): DOMRect[] {
const boxes: DOMRect[] = [];
- for (const element of document.querySelectorAll<HTMLElement>(selector)) {
+ for (const element of outsideThread(selector)) {
if (element.closest("[data-native-page]")) continue;
if (skip && element.querySelector(skip)) continue;
const box = element.getBoundingClientRect();
@@ -562,7 +563,7 @@ function visibleRect(element: HTMLElement): DOMRect | null {
if (rect.width < 2 || rect.height < 2) return null;
let bottom = rect.bottom;
// `data-native-inset`: panel UI below the page, e.g. the annotate bar.
- for (const dock of document.querySelectorAll<HTMLElement>(
+ for (const dock of outsideThread(
".chat-full-view-dock, .chat-full-view-dock-minimized, [data-native-inset]",
)) {
const box = dock.getBoundingClientRect();
@@ -583,7 +584,7 @@ let toastInset: string | null = null;
// native views cover DOM toasts, so reserve a left column when the page reaches the right edge or Run settings.
function insetToasts(rect: DOMRect | null): void {
- const style = document.documentElement.style;
+ const style = cornerInsets.style;
// read the inline value set by watchChatSettingsInset; it is absent when the panel is closed or the row is narrow.
const settings = Number.parseFloat(style.getPropertyValue(CHAT_SETTINGS_INSET_VAR)) || 0;
const room = rect && rect.right >= window.innerWidth - settings - 2 && rect.left >= TOAST_COLUMN;
diff --git a/studio/frontend/src/features/browser/outside-thread.ts b/studio/frontend/src/features/browser/outside-thread.ts
new file mode 100644
index 00000000000..2636c551032
--- /dev/null
+++ b/studio/frontend/src/features/browser/outside-thread.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const THREAD_VIEWPORT = ".aui-thread-viewport";
+
+export function outsideThread<T extends Element = HTMLElement>(
+ selector: string,
+ root: Pick<ParentNode, "querySelector" | "querySelectorAll"> = document,
+): T[] {
+ const thread = root.querySelector(THREAD_VIEWPORT);
+ if (!thread) return [...root.querySelectorAll<T>(selector)];
+ const found: T[] = [];
+ for (let node: Element = thread; node.parentElement; node = node.parentElement) {
+ const parent = node.parentElement;
+ if (parent.matches(selector)) found.push(parent as unknown as T);
+ for (const sibling of parent.children) {
+ if (sibling === node) continue;
+ if (sibling.matches(selector)) found.push(sibling as T);
+ found.push(...sibling.querySelectorAll<T>(selector));
+ }
+ }
+ return found;
+}
diff --git a/studio/frontend/src/features/browser/resize-pin.ts b/studio/frontend/src/features/browser/resize-pin.ts
index 0a063783d1b..1be47572ea0 100644
--- a/studio/frontend/src/features/browser/resize-pin.ts
+++ b/studio/frontend/src/features/browser/resize-pin.ts
@@ -14,7 +14,7 @@ export function pinBrowserPage(handle: Element): () => void {
const right = handle.getBoundingClientRect().left < rect.left;
Object.assign(page.style, {
position: "absolute",
- top: "0",
+ top: `${rect.top - box.top}px`,
bottom: "0",
margin: "0",
width: `${rect.width}px`,
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index da0593cc52b..5383d96c99b 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1,12 +1,18 @@
// 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 {
+ forgetThreadReads,
+ inFlightThreadReads,
+ type InFlightThreadRead,
+} from "./thread-read-cache.ts";
import { skillLoadCardEvent } from "./skill-load-event";
import { authFetch, getAuthSessionEpoch } from "@/features/auth";
import { prepareHfTokenForUse } from "@/features/hf-auth";
// These helpers are deliberately API-layer-only, not part of their features' public barrels.
// eslint-disable-next-line no-restricted-imports
import {
+ abortError,
combineAbortSignals,
disposableTimeoutSignal,
} from "@/features/hub/lib/abort-signals";
@@ -47,7 +53,10 @@ import type {
UnloadModelRequest,
ValidateModelResponse,
} from "../types/api";
-import { publishChatHistoryRevision } from "../utils/chat-history-revision";
+import {
+ CHAT_HISTORY_REVISION_KEY,
+ publishChatHistoryRevision,
+} from "../utils/chat-history-revision";
import {
type GgufVariantsRequestOptions,
ggufVariantsQuery,
@@ -78,6 +87,7 @@ const THREAD_WRITE_TIMEOUT_MS = 30_000;
async function threadWriteFetch(
input: string,
init: RequestInit,
+ affected: readonly string[] | null,
caller?: AbortSignal,
): Promise<Response> {
const timeout = disposableTimeoutSignal(THREAD_WRITE_TIMEOUT_MS);
@@ -86,6 +96,7 @@ async function threadWriteFetch(
return await authFetch(input, { ...init, signal: timeout.signal });
} finally {
timeout.dispose();
+ forgetThreadReads(affected);
}
}
// Either reason ends the request. Linked by hand rather than with AbortSignal.any, which Safari only got in 17.4.
@@ -99,6 +110,7 @@ async function threadWriteFetch(
} finally {
caller.removeEventListener("abort", abort);
timeout.dispose();
+ forgetThreadReads(affected);
}
}
@@ -165,6 +177,84 @@ export function notifyChatHistoryUpdated(
}
}
+export function subscribeChatHistoryUpdated(
+ listener: (detail: ChatHistoryUpdatedDetail) => void,
+): () => void {
+ if (typeof window === "undefined") return () => {};
+ const onEvent = (event: Event) =>
+ listener((event as CustomEvent<ChatHistoryUpdatedDetail>).detail ?? {});
+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onEvent);
+ return () => window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onEvent);
+}
+
+const THREAD_READ_JOIN_MS = 2_000;
+
+if (typeof window !== "undefined") {
+ window.addEventListener("storage", (event) => {
+ if (event.key === CHAT_HISTORY_REVISION_KEY) forgetThreadReads(null);
+ });
+}
+
+async function readThreadRecord(
+ threadId: string,
+ signal?: AbortSignal,
+): Promise<ThreadRecord | null> {
+ const response = await authFetch(
+ `/api/chat/threads/${encodeURIComponent(threadId)}`,
+ signal ? { signal } : undefined,
+ );
+ if (response.status === 404) return null;
+ return parseJsonOrThrow<ThreadRecord>(response);
+}
+
+function shareThreadRead(
+ threadId: string,
+ signal?: AbortSignal,
+): Promise<ThreadRecord | null> {
+ if (signal?.aborted) return Promise.reject(abortError(signal));
+ let shared = inFlightThreadReads.get(threadId);
+ const authEpoch = getAuthSessionEpoch();
+ if (
+ !shared
+ || shared.authEpoch !== authEpoch
+ || performance.now() - shared.startedAt > THREAD_READ_JOIN_MS
+ ) {
+ const controller = new AbortController();
+ const started: InFlightThreadRead = {
+ controller,
+ readers: 0,
+ startedAt: performance.now(),
+ authEpoch,
+ promise: readThreadRecord(threadId, controller.signal),
+ };
+ const forget = () => {
+ if (inFlightThreadReads.get(threadId) === started) {
+ inFlightThreadReads.delete(threadId);
+ }
+ };
+ started.promise.then(forget, forget);
+ inFlightThreadReads.set(threadId, started);
+ shared = started;
+ }
+ shared.readers += 1;
+ if (!signal) return shared.promise;
+ const joined = shared;
+ return new Promise<ThreadRecord | null>((resolve, reject) => {
+ const onAbort = () => {
+ joined.readers -= 1;
+ if (inFlightThreadReads.get(threadId) === joined) {
+ inFlightThreadReads.delete(threadId);
+ }
+ if (joined.readers === 0) joined.controller.abort(signal.reason);
+ reject(abortError(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ joined.promise.then(resolve, reject).finally(() => {
+ signal.removeEventListener("abort", onAbort);
+ });
+ });
+}
+
export function notifyChatProjectsUpdated(): void {
notifyChatHistoryUpdated();
if (typeof window !== "undefined") {
@@ -939,7 +1029,12 @@ export async function deleteChatAttachment(
export async function getChatThread(
threadId: string,
- options: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal } = {},
+ options: {
+ bounded?: boolean;
+ timeoutMs?: number;
+ signal?: AbortSignal;
+ share?: boolean;
+ } = {},
): Promise<ThreadRecord | null> {
// Bounded for the delete reconciliation: an unbounded read there would hang the delete the write timeout
// exists to keep moving. `timeoutMs` is for a caller with a deadline of its own, since the settings pairing
@@ -955,12 +1050,9 @@ export async function getChatThread(
: null;
const signal = combined?.signal ?? timeout?.signal ?? options.signal;
try {
- const response = await authFetch(
- `/api/chat/threads/${encodeURIComponent(threadId)}`,
- signal ? { signal } : undefined,
- );
- if (response.status === 404) return null;
- return parseJsonOrThrow<ThreadRecord>(response);
+ return options.share
+ ? await shareThreadRead(threadId, signal)
+ : await readThreadRecord(threadId, signal);
} finally {
combined?.dispose();
timeout?.dispose();
@@ -989,11 +1081,15 @@ export class ChatThreadWriteError extends Error {
export async function saveChatThread(
thread: ThreadRecord,
): Promise<ThreadRecord> {
- const response = await threadWriteFetch("/api/chat/threads", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(thread),
- });
+ const response = await threadWriteFetch(
+ "/api/chat/threads",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(thread),
+ },
+ [thread.id],
+ );
if (response.status === 410) {
const body = await response.json().catch(() => null);
throw new ChatThreadDeletedError(parseErrorText(response.status, body));
@@ -1051,6 +1147,7 @@ export async function updateChatThread(
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
},
+ [threadId],
options.signal,
);
const thread = await parseJsonOrThrow<ThreadRecord>(response);
@@ -1070,14 +1167,19 @@ export async function forkChatThread(
* the chat is not generating. */
args: { messageId?: string; newThreadId: string; createdAt: number },
): Promise<ForkChatThreadResult> {
- const response = await authFetch(
- `/api/chat/threads/${encodeURIComponent(threadId)}/fork`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(args),
- },
- );
+ let response: Response;
+ try {
+ response = await authFetch(
+ `/api/chat/threads/${encodeURIComponent(threadId)}/fork`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(args),
+ },
+ );
+ } finally {
+ forgetThreadReads([threadId, args.newThreadId]);
+ }
const data = await parseJsonOrThrow<{
thread: ThreadRecord;
messages: MessageRecord[];
@@ -1107,11 +1209,15 @@ export async function deleteChatThreads(
args: { deleteFiles?: boolean } = {},
): Promise<string[]> {
if (threadIds.length === 0) return [];
- const response = await threadWriteFetch("/api/chat/threads", {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: threadIds, delete_files: !!args.deleteFiles }),
- });
+ const response = await threadWriteFetch(
+ "/api/chat/threads",
+ {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: threadIds, delete_files: !!args.deleteFiles }),
+ },
+ threadIds,
+ );
const data = await parseJsonOrThrow<{ sandboxes_kept?: string[] }>(response);
notifyChatHistoryUpdated();
return Array.isArray(data?.sandboxes_kept) ? data.sandboxes_kept : [];
@@ -1207,10 +1313,15 @@ export async function deleteChatProject(
const params = new URLSearchParams();
if (args.deleteFiles) params.set("delete_files", "true");
const qs = params.toString();
- const response = await authFetch(
- `/api/chat/projects/${encodeURIComponent(projectId)}${qs ? `?${qs}` : ""}`,
- { method: "DELETE" },
- );
+ let response: Response;
+ try {
+ response = await authFetch(
+ `/api/chat/projects/${encodeURIComponent(projectId)}${qs ? `?${qs}` : ""}`,
+ { method: "DELETE" },
+ );
+ } finally {
+ forgetThreadReads(null);
+ }
const data = await parseJsonOrThrow<
ProjectRecord & { sandboxes_kept?: string[] }
>(response);
@@ -1313,14 +1424,19 @@ export async function saveChatMessage(
const editQuery = options.allowGenerationEdit
? "?allowGenerationEdit=true"
: "";
- const response = await authFetch(
- `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}${editQuery}`,
- {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(message),
- },
- );
+ let response: Response;
+ try {
+ response = await authFetch(
+ `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}${editQuery}`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(message),
+ },
+ );
+ } finally {
+ forgetThreadReads([message.threadId]);
+ }
// Two failures share this status: a protected message, where the autosave must stop, and a
// thread-id collision, which the caller must see. Only the header separates them.
if (
@@ -1358,6 +1474,7 @@ export async function syncChatMessages(
deletedMessageIds: options.deletedMessageIds ?? [],
}),
},
+ [threadId],
);
const data = await parseJsonOrThrow<{ messages: MessageRecord[] }>(response);
// Pruning is how a message is deleted, which no other tab should keep matching for a whole
@@ -1391,6 +1508,7 @@ export async function clearBackendChats(
operationId: options.operationId,
}),
},
+ null,
);
const data = await parseJsonOrThrow<{
deletedThreadIds?: string[];
diff --git a/studio/frontend/src/features/chat/api/thread-read-cache.ts b/studio/frontend/src/features/chat/api/thread-read-cache.ts
new file mode 100644
index 00000000000..84ead4ef390
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/thread-read-cache.ts
@@ -0,0 +1,23 @@
+// 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 { ThreadRecord } from "../types";
+
+export type InFlightThreadRead = {
+ promise: Promise<ThreadRecord | null>;
+ controller: AbortController;
+ readers: number;
+ startedAt: number;
+ // Auth session it was read under: a read never answers a later session.
+ authEpoch: number;
+};
+
+export const inFlightThreadReads = new Map<string, InFlightThreadRead>();
+
+export function forgetThreadReads(threadIds: readonly string[] | null): void {
+ if (threadIds === null) {
+ inFlightThreadReads.clear();
+ return;
+ }
+ for (const threadId of threadIds) inFlightThreadReads.delete(threadId);
+}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 80dea6daa8d..5364a0c6004 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -46,6 +46,7 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
+import { armPanelDrag } from "@/components/ui/panel-drag-overlay";
import {
ResizableHandle,
ResizablePanel,
@@ -83,6 +84,7 @@ import {
import { isNpuModelId } from "@/features/npu";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { isTauri } from "@/lib/api-base";
+import { useDocumentFlag } from "@/lib/document-flag";
import { chatModelLoaded } from "./lib/chat-model-loaded";
import { hasKnownContextWindow } from "./lib/context-window-known";
import { isDownloadCancelled } from "@/lib/native-files";
@@ -363,6 +365,7 @@ const BrowserOverlaidContext = createContext(false);
function BrowserOverlay(): ReactElement {
const t = useT();
const dialogRef = useRef<HTMLDivElement>(null);
+ useDocumentFlag("data-browser-overlay-open", true);
useEffect(() => {
const previous = document.activeElement;
const id = window.setTimeout(() => {
@@ -866,6 +869,7 @@ const SingleContent = memo(function SingleContent({
<>
<ResizablePanelGroup
orientation="horizontal"
+ disableCursor
data-artifact-layout-animating={
isArtifactLayoutAnimating ? "true" : "false"
}
@@ -897,7 +901,7 @@ const SingleContent = memo(function SingleContent({
<div
data-expanded={chatDock === "expanded" ? "true" : "false"}
className={cn(
- "flex h-full min-h-0 min-w-0 flex-col overflow-hidden",
+ "flex h-full min-h-0 min-w-0 flex-col overflow-hidden [html[data-panel-resizing]_&]:pointer-events-auto",
browserFullView &&
(chatDock === "minimized"
? "chat-full-view-dock-minimized"
@@ -919,17 +923,26 @@ const SingleContent = memo(function SingleContent({
withHandle={false}
// The library's double-click reset would shut the panel without closing the artifact.
disableDoubleClick
+ disabled={!artifactLayoutActive || browserFullView}
onPointerDown={(event) => {
if (event.button !== 0) return;
+ const drag = armPanelDrag(event.clientX);
const unpin = pinBrowserPage(event.currentTarget);
const release = () => {
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", release);
+ window.removeEventListener("pointermove", moved);
+ drag.release();
unpin();
rememberArtifactPanelWidth();
};
+ const moved = (move: PointerEvent) => {
+ if (move.buttons === 0) release();
+ else drag.move(move.clientX);
+ };
window.addEventListener("pointerup", release);
window.addEventListener("pointercancel", release);
+ window.addEventListener("pointermove", moved);
}}
onKeyUp={rememberArtifactPanelWidth}
className={cn(
@@ -2769,8 +2782,9 @@ export function ChatPage({
lastNonCompareViewRef.current = { ...search };
}
}, [search]);
- const inferenceParams = useChatRuntimeStore((state) => state.params);
- const setInferenceParams = useChatRuntimeStore((state) => state.setParams);
+ const inferenceCheckpoint = useChatRuntimeStore(
+ (state) => state.params.checkpoint,
+ );
const activeGgufVariant = useChatRuntimeStore(
(state) => state.activeGgufVariant,
);
@@ -2927,7 +2941,7 @@ export function ChatPage({
const prevConnectionsEnabledRef = useRef(connectionsEnabled);
useEffect(() => {
const turnedOff = prevConnectionsEnabledRef.current && !connectionsEnabled;
- if (!connectionsEnabled && isExternalModelId(inferenceParams.checkpoint)) {
+ if (!connectionsEnabled && isExternalModelId(inferenceCheckpoint)) {
clearCheckpoint();
if (turnedOff) {
toast.info("Connections disabled", {
@@ -2939,7 +2953,7 @@ export function ChatPage({
}, [
clearCheckpoint,
connectionsEnabled,
- inferenceParams.checkpoint,
+ inferenceCheckpoint,
]);
const pendingNativeModelIntent = useNativeIntentStore(
(state) => state.pendingModelIntent,
@@ -2968,8 +2982,8 @@ export function ChatPage({
[],
);
const isExternalModel = useMemo(
- () => isExternalModelId(inferenceParams.checkpoint),
- [inferenceParams.checkpoint],
+ () => isExternalModelId(inferenceCheckpoint),
+ [inferenceCheckpoint],
);
const contextWindowKnown = hasKnownContextWindow({
loadedContextLength,
@@ -2988,13 +3002,13 @@ export function ChatPage({
(s) => s.loadedIsDiffusion,
);
const activeModelIsLora = useMemo(() => {
- const checkpoint = inferenceParams.checkpoint;
+ const checkpoint = inferenceCheckpoint;
if (!checkpoint || isExternalModel) return false;
const model = modelsFromStore.find((entry) => entry.id === checkpoint);
if (model) return model.isLora;
const lora = lorasFromStore.find((entry) => entry.id === checkpoint);
return lora?.exportType === "lora";
- }, [inferenceParams.checkpoint, isExternalModel, modelsFromStore, lorasFromStore]);
+ }, [inferenceCheckpoint, isExternalModel, modelsFromStore, lorasFromStore]);
const reasoningEnabled = useChatRuntimeStore((s) => s.reasoningEnabled);
const reasoningStyle = useChatRuntimeStore((s) => s.reasoningStyle);
const reasoningEffort = useChatRuntimeStore((s) => s.reasoningEffort);
@@ -3002,17 +3016,17 @@ export function ChatPage({
(s) => s.supportsReasoningOff,
);
const activeExternalProvider = useMemo(() => {
- const selection = parseExternalModelId(inferenceParams.checkpoint);
+ const selection = parseExternalModelId(inferenceCheckpoint);
if (!selection) return null;
return (
externalProvidersForChat.find((p) => p.id === selection.providerId) ??
null
);
- }, [externalProvidersForChat, inferenceParams.checkpoint]);
+ }, [externalProvidersForChat, inferenceCheckpoint]);
const activeExternalProviderType =
activeExternalProvider?.providerType ?? null;
const activeProviderCapabilities = useMemo(() => {
- const selection = parseExternalModelId(inferenceParams.checkpoint);
+ const selection = parseExternalModelId(inferenceCheckpoint);
if (!selection) return null;
const provider = externalProvidersForChat.find(
(p) => p.id === selection.providerId,
@@ -3037,14 +3051,14 @@ export function ChatPage({
};
}, [
externalProvidersForChat,
- inferenceParams.checkpoint,
+ inferenceCheckpoint,
reasoningEnabled,
reasoningStyle,
reasoningEffort,
supportsReasoningOff,
]);
useEffect(() => {
- const selection = parseExternalModelId(inferenceParams.checkpoint);
+ const selection = parseExternalModelId(inferenceCheckpoint);
if (!selection) return;
const provider = externalProvidersForChat.find(
(p) => p.id === selection.providerId,
@@ -3065,7 +3079,7 @@ export function ChatPage({
// resync, and resolving it without the pin is what put the provider default back over a
// level the user had set on the model's row.
const pinnedEffort = externalReasoningTakesEffort(reasoningCaps)
- ? pinnedReasoningEffort(inferenceParams.checkpoint, effortLevels)
+ ? pinnedReasoningEffort(inferenceCheckpoint, effortLevels)
: null;
const nextReasoningEffort = resolveExternalReasoningEffort({
caps: reasoningCaps,
@@ -3189,19 +3203,19 @@ export function ChatPage({
});
// Reruns once settings hydrate: this normalization reads the stored pills and clamps them to the
// model, and hydration refreshes what it reads, so it has to be applied last.
- }, [externalProvidersForChat, inferenceParams.checkpoint, settingsHydrated]);
+ }, [externalProvidersForChat, inferenceCheckpoint, settingsHydrated]);
// Another tab can change the active model's pin (the pin store listens for the storage event),
// and the normalization above reads the pin through a getState helper without subscribing, so
// the composer kept the old level until a switch. Only the effort here: the pills and the rest
// of that block are not this one's to rerun.
const activePinnedEffort = useModelReasoningEffortStore(
- (state) => state.effortByModel[inferenceParams.checkpoint],
+ (state) => state.effortByModel[inferenceCheckpoint],
);
const appliedPinnedEffort = useRef(activePinnedEffort);
useEffect(() => {
if (appliedPinnedEffort.current === activePinnedEffort) return;
appliedPinnedEffort.current = activePinnedEffort;
- const selection = parseExternalModelId(inferenceParams.checkpoint);
+ const selection = parseExternalModelId(inferenceCheckpoint);
if (!selection) return;
const provider = externalProvidersForChat.find(
(p) => p.id === selection.providerId,
@@ -3217,12 +3231,12 @@ export function ChatPage({
},
);
reconcilePinnedReasoningEffort({
- checkpoint: inferenceParams.checkpoint,
+ checkpoint: inferenceCheckpoint,
caps,
providerType: provider?.providerType,
apiType: provider?.apiType,
});
- }, [activePinnedEffort, externalProvidersForChat, inferenceParams.checkpoint]);
+ }, [activePinnedEffort, externalProvidersForChat, inferenceCheckpoint]);
// A catalog that lands after selection refreshes only the stored reasoning fields (the effort shortcut reads them),
// never the selection defaults above, so a chosen effort and the pills survive the refresh.
const modelCatalogChange = useSyncExternalStore(
@@ -3233,7 +3247,7 @@ export function ChatPage({
useEffect(() => {
if (appliedCatalogChange.current === modelCatalogChange) return;
appliedCatalogChange.current = modelCatalogChange;
- const selection = parseExternalModelId(inferenceParams.checkpoint);
+ const selection = parseExternalModelId(inferenceCheckpoint);
if (!selection) return;
const { providers, connectionsEnabled: enabled } = useExternalProvidersStore.getState();
const provider = enabled
@@ -3255,15 +3269,15 @@ export function ChatPage({
// After the levels, not before: a pin is only applied while the catalogue calls it legal, so
// the refresh that publishes the level is what puts the model's own pin in force.
reconcilePinnedReasoningEffort({
- checkpoint: inferenceParams.checkpoint,
+ checkpoint: inferenceCheckpoint,
caps,
providerType: provider?.providerType,
apiType: provider?.apiType,
});
- }, [modelCatalogChange, inferenceParams.checkpoint]);
+ }, [modelCatalogChange, inferenceCheckpoint]);
const canCompare = useMemo(() => {
- return Boolean(inferenceParams.checkpoint) && !isExternalModel;
- }, [inferenceParams.checkpoint, isExternalModel]);
+ return Boolean(inferenceCheckpoint) && !isExternalModel;
+ }, [inferenceCheckpoint, isExternalModel]);
useEffect(() => {
let canceled = false;
@@ -3470,7 +3484,7 @@ export function ChatPage({
useBrowserStore.getState().closeChatPages();
}, [shownChatKey]);
- const hasActiveModel = Boolean(inferenceParams.checkpoint);
+ const hasActiveModel = Boolean(inferenceCheckpoint);
const chatContextKey = `${view.mode}|${activeThreadId ?? ""}|${search.new ?? ""}|${search.project ?? ""}`;
const [pendingHubAutoLoad, setPendingHubAutoLoad] =
useState<PendingHubAutoLoad | null>(null);
@@ -4058,7 +4072,7 @@ export function ChatPage({
);
const handleReloadActiveModel = useCallback(
(config: PerModelConfig) => {
- const checkpoint = inferenceParams.checkpoint;
+ const checkpoint = inferenceCheckpoint;
if (!checkpoint) return;
const runtime = useChatRuntimeStore.getState();
const activeLoadId = runtime.activeLoadId;
@@ -4089,7 +4103,7 @@ export function ChatPage({
});
},
[
- inferenceParams.checkpoint,
+ inferenceCheckpoint,
activeGgufVariant,
activeModelIsLora,
activeModelIsGguf,
@@ -4231,7 +4245,7 @@ export function ChatPage({
const fastModeSupported = providerSupportsFastMode(
activeExternalProviderType,
- parseExternalModelId(inferenceParams.checkpoint)?.modelId ?? null,
+ parseExternalModelId(inferenceCheckpoint)?.modelId ?? null,
);
useShortcut(
"toggleFastMode",
@@ -4691,13 +4705,13 @@ export function ChatPage({
loraModels={loraModels}
externalModels={externalModels}
externalConnections={externalConnections}
- value={inferenceParams.checkpoint}
+ value={inferenceCheckpoint}
// Resident, not merely picked: an image or video load evicts the chat model and leaves this
// selection behind, so the tick stayed on a released model.
loaded={chatModelLoaded({
- checkpoint: inferenceParams.checkpoint,
+ checkpoint: inferenceCheckpoint,
isExternalModel: isExternalModelId(
- inferenceParams.checkpoint,
+ inferenceCheckpoint,
),
residentCheckpoint,
})}
@@ -4903,7 +4917,7 @@ export function ChatPage({
{view.mode === "single" && (
<ChatModelNotice
threadId={view.threadId ?? newChatThreadId ?? undefined}
- checkpoint={inferenceParams.checkpoint}
+ checkpoint={inferenceCheckpoint}
activeGgufVariant={activeGgufVariant}
selectableModelIds={selectableModelIds}
onSwitch={handleSwitchBackToChatModel}
@@ -4994,12 +5008,10 @@ export function ChatPage({
onOpenChange={(open) => {
setSettingsOpen(open);
}}
- params={inferenceParams}
- onParamsChange={setInferenceParams}
modelConfig={
view.mode !== "compare" && activeModelConfig && !modelLoading ? (
<SidebarModelConfig
- modelId={inferenceParams.checkpoint}
+ modelId={inferenceCheckpoint}
ggufVariant={activeGgufVariant ?? null}
isGguf={activeModelIsGguf}
isLora={activeModelIsLora}
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 3898f15c60c..7fc78ad800e 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -52,6 +52,7 @@ import {
import { RetrievalSettingsSection } from "@/features/rag";
import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";
import { useScrollFades } from "@/hooks/use-scroll-fades";
+import { useSliderDraft } from "@/hooks/use-slider-draft";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import {
CHAT_SETTINGS_WIDTH_MIN,
@@ -62,7 +63,7 @@ import { useIsCompact } from "@/hooks/use-mobile";
import { useT } from "@/i18n";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { toast } from "@/lib/toast";
-import { watchChatSettingsInset } from "@/lib/toast-offset";
+import { cornerInsets, watchChatSettingsInset } from "@/lib/toast-offset";
import { cn } from "@/lib/utils";
import { Edit03Icon, PanelRightIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -167,11 +168,13 @@ export function ParamSlider({
max,
step,
onChange,
- displayValue,
+ onDraft,
+ format,
info,
valueSize,
disabled,
inline,
+ commitWhileDragging = false,
}: {
label: string;
value: number;
@@ -179,13 +182,25 @@ export function ParamSlider({
max: number;
step: number;
onChange: (v: number) => void;
- displayValue?: string;
+ onDraft?: (value: number | null) => void;
+ format?: (value: number) => string | undefined;
info?: ReactNode;
valueSize?: number;
disabled?: boolean;
/** Label, track and value on one row, for narrow settings columns. */
inline?: boolean;
+ commitWhileDragging?: boolean;
}) {
+ const commit = (v: number) => onChange(snapToStep(v, step, min, max));
+ const { draft, sliderProps: draftProps } = useSliderDraft(
+ value,
+ commit,
+ onDraft,
+ );
+ const sliderProps = commitWhileDragging
+ ? { value: [value], onValueChange: ([v]: number[]) => commit(v) }
+ : draftProps;
+ const shown = draft ?? value;
if (inline) {
return (
<div className="flex items-center gap-3">
@@ -200,18 +215,17 @@ export function ParamSlider({
min={min}
max={max}
step={step}
- value={[value]}
- onValueChange={([v]) => onChange(snapToStep(v, step, min, max))}
+ {...sliderProps}
className="panel-slider min-w-0 flex-1"
disabled={disabled}
/>
<NumericValueInput
- value={value}
+ value={shown}
min={min}
max={max}
step={step}
onChange={onChange}
- displayValue={displayValue}
+ displayValue={format?.(shown)}
ariaLabel={label}
size={valueSize ?? 4}
className="panel-number-input"
@@ -230,12 +244,12 @@ export function ParamSlider({
{info && <InfoHint>{info}</InfoHint>}
</div>
<NumericValueInput
- value={value}
+ value={shown}
min={min}
max={max}
step={step}
onChange={onChange}
- displayValue={displayValue}
+ displayValue={format?.(shown)}
ariaLabel={label}
size={valueSize ?? 4}
className="panel-number-input"
@@ -246,8 +260,7 @@ export function ParamSlider({
min={min}
max={max}
step={step}
- value={[value]}
- onValueChange={([v]) => onChange(snapToStep(v, step, min, max))}
+ {...sliderProps}
className="panel-slider"
disabled={disabled}
/>
@@ -404,11 +417,6 @@ function CollapsibleSection({
interface ChatSettingsPanelProps {
open: boolean;
onOpenChange?: (open: boolean) => void;
- params: InferenceParams;
- onParamsChange: (
- params: InferenceParams,
- options?: { minPChoiceEdited?: boolean },
- ) => void;
modelConfig?: ReactNode;
isExternalModel?: boolean;
/** Sampling-param capabilities for the active external provider, or `null` for local models
@@ -480,8 +488,6 @@ function specFallbackMessage({
export function ChatSettingsPanel({
open,
onOpenChange,
- params,
- onParamsChange,
modelConfig = null,
isExternalModel = false,
providerCapabilities = null,
@@ -491,6 +497,8 @@ export function ChatSettingsPanel({
}: ChatSettingsPanelProps) {
const asideRef = useRef<HTMLElement>(null);
const t = useT();
+ const params = useChatRuntimeStore((s) => s.params);
+ const setParams = useChatRuntimeStore((s) => s.setParams);
const {
width: settingsWidth,
max: settingsMax,
@@ -522,7 +530,7 @@ export function ChatSettingsPanel({
useEffect(() => {
if (!open || isCompact) return;
return watchChatSettingsInset(
- document.documentElement,
+ cornerInsets,
asideRef.current,
settingsWidth * settingsScale,
uiSpaceScale,
@@ -882,7 +890,7 @@ export function ChatSettingsPanel({
function set<K extends keyof InferenceParams>(key: K) {
return (v: InferenceParams[K]) => {
const nextParams = {
- ...params,
+ ...useChatRuntimeStore.getState().params,
[key]: v,
...(key === "minP" ? { minPMode: "custom" as const } : {}),
};
@@ -890,7 +898,7 @@ export function ChatSettingsPanel({
? getPresetSource(activePreset)
: "modified";
setActivePresetSource(nextSource);
- onParamsChange(nextParams, {
+ setParams(nextParams, {
minPChoiceEdited: key === "minP" || key === "minPMode",
});
};
@@ -917,14 +925,14 @@ export function ChatSettingsPanel({
? getPresetSource(activePreset)
: "modified";
setActivePresetSource(nextSource);
- onParamsChange(nextParams);
+ setParams(nextParams);
}, [
activeExternalProvider,
activePreset,
activePresetBaseline,
isExternalModel,
maxTokensMax,
- onParamsChange,
+ setParams,
params,
settingsHydrated,
setActivePresetSource,
@@ -949,7 +957,7 @@ export function ChatSettingsPanel({
}
const p = presets.find((pr) => pr.name === name);
if (p) {
- onParamsChange(applyPresetParamsWithinCurrentLimits(p), {
+ setParams(applyPresetParamsWithinCurrentLimits(p), {
minPChoiceEdited: true,
});
if (p.loadConfig) {
@@ -1011,7 +1019,7 @@ export function ChatSettingsPanel({
setCustomPresets(next);
if (activePreset === name) {
if (fallbackPreset) {
- onParamsChange(
+ setParams(
applyPresetParamsWithinCurrentLimits(fallbackPreset),
{ minPChoiceEdited: true },
);
@@ -1050,7 +1058,7 @@ export function ChatSettingsPanel({
? getPresetSource(activePreset)
: "modified";
setActivePresetSource(nextSource);
- onParamsChange(nextParams);
+ setParams(nextParams);
setSystemPromptEditorOpen(false);
}
@@ -1554,7 +1562,7 @@ export function ChatSettingsPanel({
max={1}
step={0.05}
onChange={set("topP")}
- displayValue={params.topP === 1 ? "Off" : undefined}
+ format={(v) => (v === 1 ? "Off" : undefined)}
info="Nucleus sampling. Restricts choices to the smallest set of tokens whose cumulative probability reaches this threshold. 1.0 = off."
/>
) : null}
@@ -1566,7 +1574,7 @@ export function ChatSettingsPanel({
max={100}
step={1}
onChange={set("topK")}
- displayValue={params.topK === 0 ? "Off" : undefined}
+ format={(v) => (v === 0 ? "Off" : undefined)}
info="Limits sampling to the K most likely tokens at each step. 0 = off."
/>
) : null}
@@ -1619,9 +1627,7 @@ export function ChatSettingsPanel({
max={2}
step={0.05}
onChange={set("repetitionPenalty")}
- displayValue={
- params.repetitionPenalty === 1 ? "Off" : undefined
- }
+ format={(v) => (v === 1 ? "Off" : undefined)}
info="Down-weights tokens that have already appeared, reducing repetition. 1.0 = off; higher values penalize more strongly."
/>
) : null}
@@ -1633,9 +1639,7 @@ export function ChatSettingsPanel({
max={2}
step={0.1}
onChange={set("presencePenalty")}
- displayValue={
- params.presencePenalty === 0 ? "Off" : undefined
- }
+ format={(v) => (v === 0 ? "Off" : undefined)}
info="Penalizes any token that has already appeared at least once, encouraging the model to introduce new topics. 0 = off."
/>
) : null}
@@ -1650,10 +1654,8 @@ export function ChatSettingsPanel({
max={maxTokensMax}
step={64}
onChange={set("maxTokens")}
- displayValue={
- !isExternalModel && params.maxTokens >= maxTokensMax
- ? "Max"
- : undefined
+ format={(v) =>
+ !isExternalModel && v >= maxTokensMax ? "Max" : undefined
}
info="Maximum number of tokens to generate per response. Generation stops at this limit or when the model emits an end-of-sequence token."
/>
@@ -1972,9 +1974,7 @@ function MaxToolCallsSlider() {
max={41}
step={1}
onChange={(v) => setMaxToolCalls(v >= 41 ? 9999 : v)}
- displayValue={
- sliderValue >= 41 ? "Max" : sliderValue === 0 ? "Off" : undefined
- }
+ format={(v) => (v >= 41 ? "Max" : v === 0 ? "Off" : undefined)}
info="Cap on tool/function calls the model may invoke within a single response. 0 disables tool use; Max removes the cap."
/>
);
@@ -1987,13 +1987,6 @@ function ToolCallTimeoutSlider() {
// Slider 1-31; 31 maps to 9999 ("Max")
const sliderValue = timeout >= 9999 ? 31 : Math.min(Math.max(timeout, 1), 30);
- const displayValue =
- sliderValue >= 31
- ? "Max"
- : sliderValue === 1
- ? "1 minute"
- : `${sliderValue} minutes`;
-
return (
<ParamSlider
label="Max Tool Call Duration"
@@ -2002,7 +1995,9 @@ function ToolCallTimeoutSlider() {
max={31}
step={1}
onChange={(v) => setTimeout_(v >= 31 ? 9999 : v)}
- displayValue={displayValue}
+ format={(v) =>
+ v >= 31 ? "Max" : v === 1 ? "1 minute" : `${v} minutes`
+ }
valueSize={10}
info="Per-call wall-clock limit. Long-running tool executions are terminated when this elapses; the model continues with what completed."
/>
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index e6406ffb606..4f17c5e9d21 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -879,7 +879,7 @@ function pickOf(info: {
}
export function useChatModelRuntime() {
- const params = useChatRuntimeStore((state) => state.params);
+ const checkpoint = useChatRuntimeStore((state) => state.params.checkpoint);
const models = useChatRuntimeStore((state) => state.models);
const loras = useChatRuntimeStore((state) => state.loras);
const setParams = useChatRuntimeStore((state) => state.setParams);
@@ -1290,7 +1290,7 @@ export function useChatModelRuntime() {
if (
!forceReload &&
(!modelId ||
- (params.checkpoint === modelId &&
+ (checkpoint === modelId &&
(ggufVariant ?? null) === (currentVariant ?? null) &&
!loadingModelRef.current &&
!useChatRuntimeStore.getState().loadingModelPick &&
@@ -3730,9 +3730,9 @@ export function useChatModelRuntime() {
},
[
cancelLoading,
+ checkpoint,
loras,
models,
- params.checkpoint,
refresh,
renderLoadDescription,
resetLoadingUiForRun,
@@ -3885,7 +3885,7 @@ export function useChatModelRuntime() {
modelId?: string,
confirmed?: StopRunningChatsDecision,
): Promise<boolean> => {
- if (modelId && modelId !== params.checkpoint) {
+ if (modelId && modelId !== checkpoint) {
const toastId = toast.loading("Unloading model");
try {
if (!(await unloadKeptModel(modelId))) {
@@ -3903,7 +3903,7 @@ export function useChatModelRuntime() {
return false;
}
}
- if (!params.checkpoint) {
+ if (!checkpoint) {
return false;
}
const bailIfLoading = (): boolean => {
@@ -3920,7 +3920,7 @@ export function useChatModelRuntime() {
};
if (bailIfLoading()) return false;
setModelsError(null);
- if (isExternalModelId(params.checkpoint)) {
+ if (isExternalModelId(checkpoint)) {
clearCheckpoint();
await refresh();
return true;
@@ -3942,7 +3942,7 @@ export function useChatModelRuntime() {
// loaded, so it must not be worded as a reload. With several loaded only this one's chats stop.
const scope =
!confirmed && useChatRuntimeStore.getState().loadedModels.length > 1
- ? params.checkpoint
+ ? checkpoint
: undefined;
const stopDecision =
confirmed ??
@@ -3959,7 +3959,7 @@ export function useChatModelRuntime() {
async function performUnload(): Promise<void> {
stopQueuedRuns(stopDecision, Boolean(scope));
await unloadModel({
- model_path: params.checkpoint,
+ model_path: checkpoint,
force_cancel_active: stopDecision.forceCancelActive,
});
if (!scope) {
@@ -3990,15 +3990,15 @@ export function useChatModelRuntime() {
useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
}
}
- }, [clearCheckpoint, params.checkpoint, refresh, setModelsError]);
+ }, [checkpoint, clearCheckpoint, refresh, setModelsError]);
const ejectAllModels = useCallback(async (): Promise<boolean> => {
const others = useChatRuntimeStore
.getState()
.loadedModels.map((m) => m.checkpoint ?? m.id)
- .filter((id) => id !== params.checkpoint);
+ .filter((id) => id !== checkpoint);
const selectedLocal =
- Boolean(params.checkpoint) && !isExternalModelId(params.checkpoint);
+ Boolean(checkpoint) && !isExternalModelId(checkpoint);
const decision = await confirmStopRunningChatsIfNeeded(
"Unloading every model",
"unload",
@@ -4026,7 +4026,7 @@ export function useChatModelRuntime() {
return false;
}
return true;
- }, [ejectModel, params.checkpoint, refresh, setModelsError]);
+ }, [checkpoint, ejectModel, refresh, setModelsError]);
return {
refresh,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index b8e9e12441e..be40afa8e24 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -27,6 +27,7 @@ export {
notifyChatHistoryUpdated,
notifyChatProjectsUpdated,
removeScanFolder,
+ subscribeChatHistoryUpdated,
revealCachedModel,
revealFineTunedModel,
validateModel,
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 34ebc094c1c..1e0eb4f1860 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -156,6 +156,7 @@ import {
createRecoveryPublishSchedule,
registerRecoveredRunStop,
threadHasDurableGenerationRun,
+ threadHasLiveGenerationRun,
generationNeedsRecovery,
requestParsesThinkTags,
restoreCarriedPartsFromRaw,
@@ -3945,7 +3946,10 @@ function ThreadBackendAutosave({
const checkpointsRef = useRef<RunCheckpointScheduler | null>(null);
const checkpoints = useCallback((): RunCheckpointScheduler => {
checkpointsRef.current ??= createRunCheckpointScheduler(
- (threadId) => queueSaveRef.current(threadId),
+ (threadId) =>
+ threadHasLiveGenerationRun(threadId)
+ ? Promise.resolve()
+ : queueSaveRef.current(threadId),
{
isActive: (threadId) => isRunActiveRef.current(threadId),
isBounded: (threadId) => threadHasDurableGenerationRun(threadId),
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index adbdbf05c05..f56ed0ccdf1 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { authFetch } from "@/features/auth";
+import { forgetThreadReads } from "../api/thread-read-cache.ts";
import type { ImageDisclosure } from "../api/mcp-image";
import {
mirrorHfTokenInto,
@@ -1241,7 +1242,10 @@ export function replayUnconfirmedThreadSettings(): void {
body: JSON.stringify(body),
signal: timeout.signal,
})
- .finally(() => clearTimeout(timer))
+ .finally(() => {
+ clearTimeout(timer);
+ forgetThreadReads([threadId]);
+ })
// Only an ok response means it landed: authFetch resolves for 404 and 5xx too, and the
// missing-row case this exists for is exactly the one that 404s.
.then((res) => {
@@ -1319,7 +1323,9 @@ function sendThreadScopedSettingsBeacon(
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
keepalive: true,
- }).catch(() => undefined);
+ })
+ .finally(() => forgetThreadReads([threadId]))
+ .catch(() => undefined);
}
// One chain per thread: the write REPLACES settings_json, so two unordered writes pick a
diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
index cdd085a9ea7..a2dfe63f539 100644
--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
@@ -821,12 +821,17 @@ export function isLiveGenerationRun(runId: string): boolean {
return liveGenerationRuns.has(runId);
}
-/** Whether `threadId` has a durable run, streaming here or named by the server. A
- * subscriber-owned stream has none, and its periodic checkpoint is its ONLY persistence. */
-export function threadHasDurableGenerationRun(threadId: string): boolean {
+export function threadHasLiveGenerationRun(threadId: string): boolean {
for (const [runId, owner] of liveGenerationThreads.entries()) {
if (owner === threadId && !provisionalGenerationRuns.has(runId)) return true;
}
+ return false;
+}
+
+/** Whether `threadId` has a durable run, streaming here or named by the server. A
+ * subscriber-owned stream has none, and its periodic checkpoint is its ONLY persistence. */
+export function threadHasDurableGenerationRun(threadId: string): boolean {
+ if (threadHasLiveGenerationRun(threadId)) return true;
for (const owner of serverActiveGenerationRuns.values()) {
if (owner === threadId) return true;
}
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index dcbe7c06adb..62c2292a6e8 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -671,6 +671,7 @@ export async function getStoredChatThreadReadResult(
bounded: options.bounded,
timeoutMs: options.timeoutMs,
signal: options.signal,
+ share: true,
});
} catch (error) {
if (legacyThread && !isChatThreadDeleted(legacyThread.id)) {
@@ -850,7 +851,7 @@ export async function readStoredChatMessages(
[] as MessageRecord[],
);
const [backendThread, backendMessages] = await Promise.all([
- getChatThread(threadId).catch(() => undefined),
+ getChatThread(threadId, { share: true }).catch(() => undefined),
listChatMessages(threadId).catch((error) => {
if (legacyMessages.length > 0) {
return undefined;
@@ -974,8 +975,12 @@ export async function listStoredChatThreadsWithMessages(
): Promise<ThreadRecord[]> {
const threads = await listStoredChatThreads(args);
if (threads.length === 0) return [];
- // One batched HTTP call instead of N. Per-thread legacy Dexie fallback only fires when the batch result is empty.
const threadIds = threads.map((t) => t.id);
+ const counts = await countStoredChatMessages(threadIds).catch(() => null);
+ if (counts !== null) {
+ return threads.filter((thread) => (counts.get(thread.id) ?? 0) > 0);
+ }
+ // Per-thread Dexie fallback only when the batch is empty.
let backendByThread: Map<string, MessageRecord[]>;
try {
backendByThread = await batchListChatMessages(threadIds);
diff --git a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
index 24cc2c18886..39d2b2fc93a 100644
--- a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
+++ b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
@@ -13,6 +13,7 @@ import {
useShortcut,
useShortcutAvailable,
} from "@/features/settings";
+import { useDocumentFlag } from "@/lib/document-flag";
import { Z_LAYER } from "@/lib/z-layers";
import { Search01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -296,7 +297,8 @@ export function FindInPage({ enabled = true }: { enabled?: boolean }) {
});
// False while a modal is open.
- const foreground = useShortcutAvailable("findInPage", true);
+ const foreground = useShortcutAvailable("findInPage", open);
+ useDocumentFlag("data-find-bar-open", enabled && open && foreground);
if (!enabled || !open) return null;
// Top layer, outside any stacking context. Hidden (not unmounted) under a modal so it returns as it was.
diff --git a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
index 440791f4573..2254b0de08e 100644
--- a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
+++ b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
@@ -277,6 +277,26 @@ export function useFindInPage(
search(false, reindex());
});
+ let scrolledAt = Number.NEGATIVE_INFINITY;
+ let reindexBy = Number.POSITIVE_INFINITY;
+ const noteScroll = () => {
+ scrolledAt = performance.now();
+ };
+ const flush = () => {
+ const now = performance.now();
+ const wait = Math.min(
+ REINDEX_INTERVAL_MS - (now - scrolledAt),
+ reindexBy - now,
+ );
+ if (wait > 0) {
+ timerRef.current = setTimeout(flush, wait);
+ return;
+ }
+ timerRef.current = null;
+ if (!staleRef.current) return;
+ search(false, reindex());
+ };
+
// Mark the index stale and schedule one rebuild. No reveal: something moved under the reader,
// they did not ask to go anywhere.
const invalidate = () => {
@@ -285,16 +305,18 @@ export function useFindInPage(
if (queryRef.current.length === 0) return;
// Already scheduled: the interval is the floor, so a burst costs one rebuild, not one each.
if (timerRef.current !== null) return;
- timerRef.current = setTimeout(() => {
- timerRef.current = null;
- if (!staleRef.current) return;
- search(false, reindex());
- }, REINDEX_INTERVAL_MS);
+ reindexBy = performance.now() + 4 * REINDEX_INTERVAL_MS;
+ timerRef.current = setTimeout(flush, REINDEX_INTERVAL_MS);
};
// A media query is not a mutation: crossing a breakpoint hides or reveals whole columns with
// nothing in the DOM to observe, so without this the bar searches the layout that has gone.
window.addEventListener("resize", invalidate);
+ window.addEventListener("wheel", noteScroll, { capture: true, passive: true });
+ window.addEventListener("touchmove", noteScroll, {
+ capture: true,
+ passive: true,
+ });
// And a container query does not even need the window to change. Images is an `@container` with
// labels on `@[50rem]`, so pinning or collapsing the sidebar crosses that breakpoint on its own.
@@ -352,6 +374,8 @@ export function useFindInPage(
// The bar is going away; any queued reveal would scroll the reader after it is gone.
cancelRevealPasses();
window.removeEventListener("resize", invalidate);
+ window.removeEventListener("wheel", noteScroll, { capture: true });
+ window.removeEventListener("touchmove", noteScroll, { capture: true });
sized?.disconnect();
observer?.disconnect();
if (timerRef.current !== null) {
@@ -389,13 +413,23 @@ export function useFindInPage(
const step = useCallback(
(delta: number) => {
- const count = matchesRef.current.length;
+ const matches = matchesRef.current;
+ const count = matches.length;
if (count === 0) return;
// Wraps, so the walk never dead-ends.
activeRef.current = (activeRef.current + delta + count) % count;
+ const target = matches[activeRef.current];
+ if (staleRef.current) {
+ const range = rangeForMatch(indexRef.current, target);
+ if (!(range?.startContainer.isConnected && range.endContainer.isConnected)) {
+ activeStartRef.current = target.start;
+ search(true, reindex());
+ return;
+ }
+ }
apply(true);
},
- [apply],
+ [apply, reindex, search],
);
const next = useCallback(() => step(1), [step]);
diff --git a/studio/frontend/src/features/interface-zoom/components/interface-zoom.tsx b/studio/frontend/src/features/interface-zoom/components/interface-zoom.tsx
index 9c02a5fe4d0..44d45a9849a 100644
--- a/studio/frontend/src/features/interface-zoom/components/interface-zoom.tsx
+++ b/studio/frontend/src/features/interface-zoom/components/interface-zoom.tsx
@@ -200,6 +200,10 @@ export function InterfaceZoom() {
const wheelStep = createWheelZoomAccumulator();
const scopeWheelStep = createWheelZoomAccumulator();
const onWheel = (event: WheelEvent) => {
+ if (modifierHeld && !event.ctrlKey && !event.metaKey) {
+ modifierHeld = false;
+ syncWheel();
+ }
if (event.defaultPrevented || !isZoomWheel(event)) return;
const scope = zoomScopeFor(event.target);
if (scope) {
@@ -213,9 +217,57 @@ export function InterfaceZoom() {
const direction = wheelStep(event, getAppliedInterfaceZoom());
if (direction !== null) zoomInterface(direction);
};
- window.addEventListener("wheel", onWheel, { passive: false });
+ let wheelArmed = false;
+ const armWheel = () => {
+ if (wheelArmed) return;
+ wheelArmed = true;
+ window.addEventListener("wheel", onWheel, { passive: false });
+ };
+ const disarmWheel = () => {
+ if (!wheelArmed) return;
+ wheelArmed = false;
+ window.removeEventListener("wheel", onWheel);
+ };
+ let modifierHeld = false;
+ let pointerInScope = false;
+ const syncWheel = () => {
+ if (modifierHeld || pointerInScope) armWheel();
+ else disarmWheel();
+ };
+ const onModifierChange = (event: KeyboardEvent) => {
+ modifierHeld = event.ctrlKey || event.metaKey;
+ syncWheel();
+ };
+ const onPointerOver = (event: PointerEvent) => {
+ modifierHeld = event.ctrlKey || event.metaKey;
+ pointerInScope = zoomScopeFor(event.target) !== null;
+ syncWheel();
+ };
+ const onBlur = () => {
+ modifierHeld = false;
+ syncWheel();
+ };
+ const onPassiveWheel = (event: WheelEvent) => {
+ if (wheelArmed || !isZoomWheel(event)) return;
+ modifierHeld = true;
+ syncWheel();
+ };
+ if (mac) {
+ armWheel();
+ } else {
+ window.addEventListener("keydown", onModifierChange, true);
+ window.addEventListener("keyup", onModifierChange, true);
+ window.addEventListener("pointerover", onPointerOver, true);
+ window.addEventListener("blur", onBlur);
+ window.addEventListener("wheel", onPassiveWheel, { passive: true });
+ }
return () => {
document.removeEventListener("keydown", onKeyDown, true);
+ window.removeEventListener("keydown", onModifierChange, true);
+ window.removeEventListener("keyup", onModifierChange, true);
+ window.removeEventListener("pointerover", onPointerOver, true);
+ window.removeEventListener("blur", onBlur);
+ window.removeEventListener("wheel", onPassiveWheel);
window.removeEventListener("wheel", onWheel);
};
}, []);
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index bc4e39c9060..54bba704586 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -13,6 +13,7 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useLlamaCppBackend } from "@/hooks/use-llama-backend";
+import { useSliderDraft } from "@/hooks/use-slider-draft";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { InfoHint } from "@/components/ui/info-hint";
@@ -502,6 +503,12 @@ function MaxSeqLengthSetting({
// MLX sizes itself when unpinned, so the control is the GGUF path's Context Length and
// shows the length that will be served, not "Auto". A dash only while it is unknown.
const label = isMlx ? "Context Length" : "Max Seq Length";
+ const { draft, sliderProps } = useSliderDraft(
+ // Clamped, or the first nudge would jump from the shown number to the bound.
+ Math.min(Math.max(value, MAX_SEQ_LENGTH_MIN), max),
+ onChange,
+ );
+ const dragging = draft !== null;
return (
<div className="space-y-2">
<div className={ROW_CLASS}>
@@ -519,13 +526,13 @@ function MaxSeqLengthSetting({
</div>
<NumericValueInput
ref={inputRef}
- value={value}
+ value={draft ?? value}
min={MAX_SEQ_LENGTH_MIN}
max={inputMax}
step={MAX_SEQ_LENGTH_STEP}
onChange={onChange}
- displayValue={isMlx && windowUnknown ? "—" : undefined}
- derived={isMlx && !pinned}
+ displayValue={isMlx && windowUnknown && !dragging ? "—" : undefined}
+ derived={isMlx && !pinned && !dragging}
ariaLabel={label}
className={NUMBER_INPUT_CLASS}
fixedWidth={true}
@@ -536,10 +543,7 @@ function MaxSeqLengthSetting({
min={MAX_SEQ_LENGTH_MIN}
max={max}
step={MAX_SEQ_LENGTH_STEP}
- // Outside the control's range it sits at the nearer edge, or the first nudge
- // would step from the shown number onto the bound.
- value={[Math.min(Math.max(value, MAX_SEQ_LENGTH_MIN), max)]}
- onValueChange={([next]) => onChange(next)}
+ {...sliderProps}
className="panel-slider"
aria-label={label}
/>
@@ -547,6 +551,92 @@ function MaxSeqLengthSetting({
);
}
+function GgufContextLengthSetting({
+ value,
+ autoValue,
+ min,
+ max,
+ nativeContextLength,
+ activeLoadedContext,
+ inputRef,
+ onChange,
+ renderWarning,
+}: {
+ value: number;
+ autoValue: number;
+ min: number;
+ max: number;
+ nativeContextLength: number | null;
+ activeLoadedContext: number | null;
+ inputRef?: Ref<NumericValueInputHandle>;
+ onChange: (value: number) => void;
+ renderWarning: (value: number) => ReactNode;
+}) {
+ const { draft, sliderProps } = useSliderDraft(value, onChange);
+ const shown = draft ?? value;
+ const isAuto = shown === 0;
+ return (
+ <div className="space-y-2">
+ <div className={ROW_CLASS}>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className={LABEL_CLASS}>Context Length</span>
+ <InfoHint>
+ Drag all the way left for Auto, which picks a context that
+ fits while keeping GPU speed. Custom values request an exact
+ context; higher ones use more memory.
+ {isAuto && activeLoadedContext != null
+ ? ` Auto currently selected ${activeLoadedContext.toLocaleString()} tokens.`
+ : ""}
+ {nativeContextLength != null
+ ? ` This model's native context is ${nativeContextLength.toLocaleString()} tokens.`
+ : ""}
+ </InfoHint>
+ </div>
+ <NumericValueInput
+ ref={inputRef}
+ value={isAuto ? autoValue : shown}
+ min={min}
+ max={max}
+ step={1}
+ onChange={onChange}
+ displayValue={isAuto ? "Auto" : undefined}
+ ariaLabel="Context Length"
+ className={NUMBER_INPUT_CLASS}
+ fixedWidth={true}
+ size={8}
+ />
+ </div>
+ {/* Grouped so the warning sits 4px under the slider, as advice does elsewhere. */}
+ <div className="space-y-1">
+ {nativeContextLength != null ? (
+ <div className="space-y-1">
+ <Slider
+ min={0}
+ max={max}
+ step={128}
+ {...sliderProps}
+ className="panel-slider"
+ aria-label="Context Length"
+ thumbValueText={(v) =>
+ v !== 0
+ ? `${v.toLocaleString()} tokens`
+ : activeLoadedContext != null
+ ? `Auto, currently ${autoValue.toLocaleString()} tokens`
+ : "Auto"
+ }
+ />
+ <div className="flex justify-between text-ui-10 text-muted-foreground">
+ <span>Auto</span>
+ <span>{max.toLocaleString()}</span>
+ </div>
+ </div>
+ ) : null}
+ {renderWarning(shown)}
+ </div>
+ </div>
+ );
+}
+
function clampMaxSeqLength(value: number, max: number): number {
const normalized = normalizeMaxSeqLength(value) ?? MAX_SEQ_LENGTH_MIN;
return Math.max(MAX_SEQ_LENGTH_MIN, Math.min(max, normalized));
@@ -558,7 +648,8 @@ function AdvancedGpuSlider({
min,
max,
onChange,
- displayValue,
+ onDraft,
+ format,
info,
inputRef,
step = 1,
@@ -569,12 +660,15 @@ function AdvancedGpuSlider({
min: number;
max: number;
onChange: (value: number) => void;
- displayValue?: string;
+ onDraft?: (value: number | null) => void;
+ format?: (value: number) => string | undefined;
info?: ReactNode;
inputRef?: Ref<NumericValueInputHandle>;
step?: number;
disabled?: boolean;
}) {
+ const { draft, sliderProps } = useSliderDraft(value, onChange, onDraft);
+ const shown = draft ?? value;
return (
<div className="space-y-2">
<div className={ROW_CLASS}>
@@ -584,12 +678,12 @@ function AdvancedGpuSlider({
</div>
<NumericValueInput
ref={inputRef}
- value={value}
+ value={shown}
min={min}
max={max}
step={step}
onChange={onChange}
- displayValue={displayValue}
+ displayValue={format?.(shown)}
ariaLabel={label}
className={NUMBER_INPUT_CLASS}
fixedWidth={true}
@@ -601,8 +695,7 @@ function AdvancedGpuSlider({
min={min}
max={max}
step={step}
- value={[value]}
- onValueChange={([next]) => onChange(next)}
+ {...sliderProps}
className="panel-slider"
aria-label={label}
disabled={disabled}
@@ -621,6 +714,7 @@ function VramBudgetRow() {
const isMac = usePlatformStore((s) => s.deviceType === "mac");
const [settings, setSettings] = useState<VramBudgetSettings | null>(null);
const [percent, setPercent] = useState<number | null>(null);
+ const [draftPercent, setDraftPercent] = useState<number | null>(null);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const adviceId = useId();
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
@@ -712,6 +806,7 @@ function VramBudgetRow() {
}
const defaultPercent = vramFractionToPercent(settings.defaultFraction);
+ const shownPercent = draftPercent ?? percent;
// Stored beats UNSLOTH_VRAM_FRACTION, so once the slider has been touched there is otherwise
// no way back to inheriting it. Clearing is what the null the API accepts is for.
const resetBudget = () => {
@@ -734,7 +829,7 @@ function VramBudgetRow() {
};
const commit = (next: number) => {
setPercent(next);
- // Debounced: the slider fires per pointer move, so a drag would be dozens of writes, each
+ // Debounced: a held arrow key commits every step, so one press would be dozens of writes, each
// invalidating the read cache.
if (saveTimer.current) {
clearTimeout(saveTimer.current);
@@ -761,8 +856,9 @@ function VramBudgetRow() {
min={vramFractionToPercent(settings.minFraction)}
max={vramFractionToPercent(settings.maxFraction)}
step={VRAM_BUDGET_PERCENT_STEP}
- displayValue={`${percent}%`}
+ format={(v) => `${v}%`}
onChange={commit}
+ onDraft={setDraftPercent}
disabled={locked}
info={
<div className="flex flex-col gap-1.5">
@@ -784,9 +880,9 @@ function VramBudgetRow() {
</div>
}
/>
- {percent !== defaultPercent && (
+ {shownPercent !== defaultPercent && (
<p id={adviceId} className="text-ui-11 text-amber-500">
- {percent > defaultPercent
+ {shownPercent > defaultPercent
? "Above the default fits more context but leaves less slack, so a load can run out of memory. llama.cpp treats that as a hard failure rather than falling back."
: "Below the default is safer on a shared GPU, but a tight fit may push layers onto the CPU and generate slowly."}
</p>
@@ -993,7 +1089,7 @@ function GpuMemorySettings({
onChange={(v) =>
update(v < 0 ? { gpuLayers: v, tensorSplit: null } : { gpuLayers: v })
}
- displayValue={autoLayers ? "Auto" : undefined}
+ format={(v) => (v < 0 ? "Auto" : undefined)}
info={
<>
Layers to keep on the GPU (--gpu-layers); the rest run on CPU.
@@ -2979,19 +3075,6 @@ export function ModelConfigPage({
maxContext,
);
const contextIsAuto = config.customContextLength == null;
- const contextInputValue = contextIsAuto
- ? Math.min(
- Math.max(
- activeLoadedContext ?? AUTO_OFFLOAD_CONTEXT_LENGTH,
- minContext,
- ),
- maxContext,
- )
- : contextValue;
- const contextSliderValue = contextIsAuto ? 0 : contextValue;
- const setContextLength = (v: number) => update({ customContextLength: v });
- const setContextSliderValue = (v: number) =>
- update({ customContextLength: v === 0 ? null : v });
const rawBaseline = loadedConfig ?? DEFAULT_PER_MODEL_CONFIG;
const baseline = resolvedIsDiffusion
? withoutUnsupportedDiffusionSettings(rawBaseline, gpuIndexKind)
@@ -3650,87 +3733,44 @@ export function ModelConfigPage({
)}
{target.isGguf && !audioRuntimeGguf && (
<>
- <div className="space-y-2">
- <div className={ROW_CLASS}>
- <div className="flex min-w-0 items-center gap-1.5">
- <span className={LABEL_CLASS}>Context Length</span>
- <InfoHint>
- Drag all the way left for Auto, which picks a context that
- fits while keeping GPU speed. Custom values request an exact
- context; higher ones use more memory.
- {contextIsAuto && activeLoadedContext != null
- ? ` Auto currently selected ${activeLoadedContext.toLocaleString()} tokens.`
- : ""}
- {nativeContextLength != null
- ? ` This model's native context is ${nativeContextLength.toLocaleString()} tokens.`
- : ""}
- </InfoHint>
- </div>
- <NumericValueInput
- ref={contextInputRef}
- value={contextInputValue}
- min={minContext}
- max={maxContext}
- step={1}
- onChange={setContextLength}
- displayValue={contextIsAuto ? "Auto" : undefined}
- ariaLabel="Context Length"
- className={NUMBER_INPUT_CLASS}
- fixedWidth={true}
- size={8}
- />
- </div>
- {/* Grouped so the warning sits 4px under the slider, as advice does elsewhere. */}
- <div className="space-y-1">
- {nativeContextLength != null ? (
- <div className="space-y-1">
- <Slider
- min={0}
- max={maxContext}
- step={128}
- value={[contextSliderValue]}
- onValueChange={([v]) => setContextSliderValue(v)}
- className="panel-slider"
- aria-label="Context Length"
- // Position 0 is Auto, not a zero-token context, so aria-valuenow alone reads as a length no
- // model has. The number is only spoken once one exists.
- thumbValueText={(v) =>
- v !== 0
- ? `${v.toLocaleString()} tokens`
- : activeLoadedContext != null
- ? `Auto, currently ${contextInputValue.toLocaleString()} tokens`
- : "Auto"
- }
- />
- <div className="flex justify-between text-ui-10 text-muted-foreground">
- <span>Auto</span>
- <span>{maxContext.toLocaleString()}</span>
- </div>
- </div>
- ) : null}
- {!contextIsAuto &&
- isActiveModel &&
- loadedMaxContextLength != null &&
- contextValue > loadedMaxContextLength && (
- <p className="text-ui-11 text-amber-500">
- {isAppleUnifiedMemory ? (
- <>
- Above Studio&apos;s free-memory estimate (
- {loadedMaxContextLength.toLocaleString()} tokens). It
- may still load, but macOS may have to compress or swap
- other apps and generation may slow down.
- </>
- ) : (
- <>
- Exceeds estimated VRAM capacity (
- {loadedMaxContextLength.toLocaleString()} tokens). The
- model may use system RAM.
- </>
- )}
- </p>
- )}
- </div>
- </div>
+ <GgufContextLengthSetting
+ value={contextIsAuto ? 0 : contextValue}
+ autoValue={Math.min(
+ Math.max(
+ activeLoadedContext ?? AUTO_OFFLOAD_CONTEXT_LENGTH,
+ minContext,
+ ),
+ maxContext,
+ )}
+ min={minContext}
+ max={maxContext}
+ nativeContextLength={nativeContextLength}
+ activeLoadedContext={activeLoadedContext}
+ inputRef={contextInputRef}
+ onChange={(v) => update({ customContextLength: v === 0 ? null : v })}
+ renderWarning={(v) =>
+ isActiveModel &&
+ loadedMaxContextLength != null &&
+ v > loadedMaxContextLength && (
+ <p className="text-ui-11 text-amber-500">
+ {isAppleUnifiedMemory ? (
+ <>
+ Above Studio&apos;s free-memory estimate (
+ {loadedMaxContextLength.toLocaleString()} tokens). It
+ may still load, but macOS may have to compress or swap
+ other apps and generation may slow down.
+ </>
+ ) : (
+ <>
+ Exceeds estimated VRAM capacity (
+ {loadedMaxContextLength.toLocaleString()} tokens). The
+ model may use system RAM.
+ </>
+ )}
+ </p>
+ )
+ }
+ />
{/* Above the block it reveals, so expanding never moves the switch. */}
<AdvancedSettingsToggle
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 56415df7b1f..f3d98ba2a29 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -585,6 +585,7 @@ function ModelSelectorContent({
<PopoverContent
align="start"
alignOffset={10}
+ dropdownGlow="picker"
// Read by the model list, which sets its right inset against the panel's own.
data-external={hasExternal || undefined}
aria-label={
@@ -624,7 +625,7 @@ function ModelSelectorContent({
disableHoverableContent={true}
>
{visibleConfigTarget ? (
- <div className="min-h-0 w-full overflow-y-auto px-4 pt-4 pb-4">
+ <div className="min-h-0 w-full overflow-y-auto px-4 pt-4 pb-4 [scrollbar-gutter:stable]">
<ModelConfigPage
key={modelConfigInstanceKey(
visibleConfigTarget.configId ?? visibleConfigTarget.id,
diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
index 572615ab738..5a385a64160 100644
--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
@@ -64,6 +64,7 @@ import {
isPastedTextFile,
isTextAttachment,
isThreadIncognito,
+ subscribeChatHistoryUpdated,
} from "@/features/chat";
import {
useNativeAttachmentTargetKey,
@@ -184,43 +185,57 @@ function useThreadProjectId(
const activeProjectId = useChatRuntimeStore((s) => s.activeProjectId);
const [resolved, setResolved] = useState<{
threadId: string;
- // The activeProjectId this answer was produced for. A change means the chat
- // may have moved, so the old answer stops counting until the re-read lands.
- trigger: string | null;
projectId: string | null;
+ editedAt: number;
} | null>(null);
- // activeProjectId is a trigger, not the answer: moving the open chat updates
- // its row and this value without changing the thread id.
useEffect(() => {
if (!threadId || isThreadIncognito(threadId)) {
return;
}
let cancelled = false;
+ let announced = false;
+ const record = (projectId: string | null, editedAt: number) =>
+ setResolved((previous) =>
+ previous?.threadId === threadId
+ && (previous.editedAt > editedAt
+ || (previous.editedAt === editedAt
+ && previous.projectId === projectId))
+ ? previous
+ : { threadId, projectId, editedAt },
+ );
+ const unsubscribe = subscribeChatHistoryUpdated(({ thread }) => {
+ if (!thread || thread.id !== threadId) return;
+ announced = true;
+ record(thread.projectId ?? null, thread.modifiedAt ?? 0);
+ });
void (async () => {
// A failed read is not proof of no project, and recording one would file
// the next attachment into the chat. Retry, then leave it unresolved:
- // nothing re-runs this until the chat or the open project changes.
+ // nothing re-runs this until the chat changes or its row is announced.
for (let attempt = 0; attempt < PROJECT_LOOKUP_RETRIES; attempt += 1) {
try {
const thread = await getStoredChatThread(threadId);
- if (cancelled) return;
+ if (cancelled || announced) return;
// No row yet: initialize() does not await the write, so the composer's
// project is the answer that row is about to record.
- const projectId = thread ? (thread.projectId ?? null) : activeProjectId;
- setResolved({ threadId, trigger: activeProjectId, projectId });
+ const projectId = thread
+ ? (thread.projectId ?? null)
+ : useChatRuntimeStore.getState().activeProjectId;
+ record(projectId, thread?.modifiedAt ?? 0);
return;
} catch {
- if (cancelled) return;
+ if (cancelled || announced) return;
await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));
- if (cancelled) return;
+ if (cancelled || announced) return;
}
}
})();
return () => {
cancelled = true;
+ unsubscribe();
};
- }, [threadId, activeProjectId]);
+ }, [threadId]);
// A chat with no id yet is the one being composed, so it belongs to whatever
// project the composer is in.
@@ -230,9 +245,7 @@ function useThreadProjectId(
if (isThreadIncognito(threadId)) {
return null;
}
- return resolved?.threadId === threadId && resolved.trigger === activeProjectId
- ? resolved.projectId
- : undefined;
+ return resolved?.threadId === threadId ? resolved.projectId : undefined;
}
function isRagIndexable(file: File): boolean {
diff --git a/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts b/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts
index 1d7089908cf..88983e7912e 100644
--- a/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts
+++ b/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts
@@ -46,3 +46,26 @@ export function setAppliedInterfaceZoom(zoom: number): void {
);
for (const listener of appliedInterfaceZoomListeners) listener();
}
+
+const ZOOMING_ATTRIBUTE = "data-interface-zooming";
+const ZOOMING_RELEASE_MS = 300;
+let zoomingRelease: ReturnType<typeof setTimeout> | null = null;
+
+export function holdSkippedContent(): void {
+ if (zoomingRelease !== null) clearTimeout(zoomingRelease);
+ zoomingRelease = null;
+ document.documentElement.setAttribute(ZOOMING_ATTRIBUTE, "");
+}
+
+export function releaseSkippedContent(): void {
+ if (zoomingRelease !== null) clearTimeout(zoomingRelease);
+ zoomingRelease = setTimeout(() => {
+ zoomingRelease = null;
+ document.documentElement.removeAttribute(ZOOMING_ATTRIBUTE);
+ }, ZOOMING_RELEASE_MS);
+}
+
+export function remeasureSkippedContent(): void {
+ holdSkippedContent();
+ releaseSkippedContent();
+}
diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
index ae086769c13..36dd44ceb45 100644
--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
@@ -8,6 +8,7 @@ import {
persist,
} from "zustand/middleware";
import { COLOR_THEMES, type ColorThemeId } from "../lib/color-themes.ts";
+import { remeasureSkippedContent } from "../lib/interface-scale-runtime.ts";
import type { ResolvedTheme } from "./theme-store";
// Best-effort persistence: localStorage can be blocked (private browsing) and
@@ -878,6 +879,8 @@ const ACCENT_FG_VARS = [
"--primary-foreground",
] as const;
+let appliedTypography: string | null = null;
+
/**
* Push the customization onto <html> as inline CSS variables, attributes, and
* classes. Everything is keyed off explicit hooks (inline vars beat every
@@ -1003,6 +1006,19 @@ export function applyCustomizationToDocument(
setVar("--custom-code-font-size", null);
}
+ const typography = JSON.stringify([
+ c.uiFont,
+ c.headingFont,
+ c.codeFont,
+ c.chatFont,
+ effectiveUiFontSize,
+ c.codeFontSize,
+ ]);
+ if (appliedTypography !== null && appliedTypography !== typography) {
+ remeasureSkippedContent();
+ }
+ appliedTypography = typography;
+
if (c.contrast !== 50) {
// Distance from the default, then one color-mix percentage per group of
// tokens. Everything mixes toward --contrast-target: the foreground above
diff --git a/studio/frontend/src/features/settings/stores/interface-scale-store.ts b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
index 879d75bc114..51691a5aa4a 100644
--- a/studio/frontend/src/features/settings/stores/interface-scale-store.ts
+++ b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
@@ -11,6 +11,9 @@ import {
} from "zustand/middleware";
import {
getAppliedInterfaceZoom,
+ holdSkippedContent,
+ releaseSkippedContent,
+ remeasureSkippedContent,
setAppliedInterfaceZoom,
} from "../lib/interface-scale-runtime.ts";
@@ -108,6 +111,8 @@ let interfaceScaleApplicationQueue = Promise.resolve();
/** Browser-only multiplier on --ui-font-scale; spacing and icons follow. */
export const INTERFACE_SCALE_VAR = "--ui-interface-scale";
+let appliedWebZoom: number | null = null;
+
/**
* The browser scales through the UI tokens, not CSS `zoom`: root zoom inflates
* viewport units (a 100dvh shell overflows at 125%).
@@ -116,6 +121,10 @@ function applyWebInterfaceScale(scale: number): void {
if (typeof document === "undefined") return;
const zoom = interfaceScaleToZoom(scale);
setLayoutScale(zoom);
+ if (appliedWebZoom !== null && appliedWebZoom !== zoom) {
+ remeasureSkippedContent();
+ }
+ appliedWebZoom = zoom;
const style = document.documentElement.style;
if (zoom === 1) style.removeProperty(INTERFACE_SCALE_VAR);
else style.setProperty(INTERFACE_SCALE_VAR, String(zoom));
@@ -126,6 +135,18 @@ export function webInterfaceScaleFactor(scale: number): number {
return isTauri ? 1 : interfaceScaleToZoom(scale);
}
+const holdsContainmentAcrossZoom = !(
+ typeof navigator !== "undefined" && navigator.userAgent.includes("Windows")
+);
+
+function holdContainmentAcrossZoom(): void {
+ if (holdsContainmentAcrossZoom) holdSkippedContent();
+}
+
+function releaseContainmentAfterZoom(): void {
+ if (holdsContainmentAcrossZoom) releaseSkippedContent();
+}
+
export function applyInterfaceScale(scale: number): Promise<void> {
if (!isTauri) {
applyWebInterfaceScale(scale);
@@ -139,7 +160,12 @@ export function applyInterfaceScale(scale: number): Promise<void> {
}
const { getCurrentWebview } = await import("@tauri-apps/api/webview");
const zoom = interfaceScaleToZoom(nextScale);
- await getCurrentWebview().setZoom(zoom);
+ holdContainmentAcrossZoom();
+ try {
+ await getCurrentWebview().setZoom(zoom);
+ } finally {
+ releaseContainmentAfterZoom();
+ }
if (nextScale !== requestedInterfaceScale) {
// a timed-out command can overwrite a newer native zoom when it finishes.
appliedInterfaceScale = null;
@@ -175,6 +201,7 @@ export function applyInterfaceScaleBeforeFirstPaint(
// settle, and everything after it waits behind that. Cut it loose or the retry in
// `provider.tsx` and every later scale change are dead until restart.
interfaceScaleApplicationQueue = Promise.resolve();
+ releaseContainmentAfterZoom();
resolve();
}, timeoutMs);
void applied.finally(() => {
diff --git a/studio/frontend/src/hooks/collapse-scroll-lock.ts b/studio/frontend/src/hooks/collapse-scroll-lock.ts
new file mode 100644
index 00000000000..11d4d8661ce
--- /dev/null
+++ b/studio/frontend/src/hooks/collapse-scroll-lock.ts
@@ -0,0 +1,61 @@
+// 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 USER_SCROLL_EVENTS = ["wheel", "touchstart"] as const;
+export const USER_DISCRETE_EVENTS = ["pointerdown", "keydown"] as const;
+
+export type GestureTarget = {
+ addEventListener(
+ type: string,
+ listener: () => void,
+ options?: AddEventListenerOptions,
+ ): void;
+ removeEventListener(
+ type: string,
+ listener: () => void,
+ options?: EventListenerOptions,
+ ): void;
+};
+
+export type CollapseScrollContainer = GestureTarget & {
+ readonly scrollTop: number;
+ scrollTo(options: { top: number; behavior: "instant" }): void;
+};
+
+export function lockCollapseScroll(
+ container: CollapseScrollContainer,
+ durationMs: number,
+ discrete: GestureTarget = container,
+): () => void {
+ const scrollPosition = container.scrollTop;
+ let released = false;
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
+ const resetPosition = () => {
+ if (container.scrollTop === scrollPosition) return;
+ container.scrollTo({ top: scrollPosition, behavior: "instant" });
+ };
+ const release = () => {
+ if (released) return;
+ released = true;
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ timeoutId = null;
+ }
+ container.removeEventListener("scroll", resetPosition);
+ for (const type of USER_SCROLL_EVENTS) {
+ container.removeEventListener(type, release, { capture: true });
+ }
+ for (const type of USER_DISCRETE_EVENTS) {
+ discrete.removeEventListener(type, release, { capture: true });
+ }
+ };
+ container.addEventListener("scroll", resetPosition);
+ for (const type of USER_SCROLL_EVENTS) {
+ container.addEventListener(type, release, { capture: true, passive: true });
+ }
+ for (const type of USER_DISCRETE_EVENTS) {
+ discrete.addEventListener(type, release, { capture: true, passive: true });
+ }
+ timeoutId = setTimeout(release, durationMs);
+ return release;
+}
diff --git a/studio/frontend/src/hooks/use-collapse-scroll-lock.ts b/studio/frontend/src/hooks/use-collapse-scroll-lock.ts
index 5ad8853839f..3941b8b157a 100644
--- a/studio/frontend/src/hooks/use-collapse-scroll-lock.ts
+++ b/studio/frontend/src/hooks/use-collapse-scroll-lock.ts
@@ -3,6 +3,20 @@
import { type RefObject, useCallback, useEffect, useRef } from "react";
+import { lockCollapseScroll } from "./collapse-scroll-lock";
+
+function findScrollContainer(element: HTMLElement): HTMLElement | null {
+ let node: HTMLElement | null = element;
+ while (node) {
+ const { overflowY } = getComputedStyle(node);
+ if (overflowY === "scroll" || overflowY === "auto") {
+ return node;
+ }
+ node = node.parentElement;
+ }
+ return null;
+}
+
/**
* Locks the nearest scrollable ancestor's scrollTop during a collapsible
* animation so the page doesn't jump when content height changes.
@@ -15,49 +29,28 @@ export function useCollapseScrollLock(
animatedElementRef: RefObject<HTMLElement | null>,
animationDurationMs: number,
): () => void {
- const cleanupRef = useRef<(() => void) | null>(null);
+ const releaseRef = useRef<(() => void) | null>(null);
useEffect(() => {
return () => {
- cleanupRef.current?.();
+ releaseRef.current?.();
+ releaseRef.current = null;
};
}, []);
return useCallback(() => {
- cleanupRef.current?.();
+ releaseRef.current?.();
+ releaseRef.current = null;
const animatedElement = animatedElementRef.current;
if (!animatedElement) return;
-
- let scrollContainer: HTMLElement | null = animatedElement;
- while (scrollContainer) {
- const { overflowY } = getComputedStyle(scrollContainer);
- if (overflowY === "scroll" || overflowY === "auto") {
- break;
- }
- scrollContainer = scrollContainer.parentElement;
- }
- if (!scrollContainer) return;
-
- const container = scrollContainer;
- const scrollPosition = container.scrollTop;
- const resetPosition = () => {
- container.scrollTop = scrollPosition;
- };
-
- container.addEventListener("scroll", resetPosition);
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
- const cleanup = () => {
- if (timeoutId !== null) {
- clearTimeout(timeoutId);
- timeoutId = null;
- }
- container.removeEventListener("scroll", resetPosition);
- if (cleanupRef.current === cleanup) {
- cleanupRef.current = null;
- }
- };
- timeoutId = setTimeout(cleanup, animationDurationMs);
- cleanupRef.current = cleanup;
+ const container = findScrollContainer(animatedElement);
+ if (!container) return;
+
+ releaseRef.current = lockCollapseScroll(
+ container,
+ animationDurationMs,
+ container.ownerDocument,
+ );
}, [animatedElementRef, animationDurationMs]);
}
diff --git a/studio/frontend/src/hooks/use-panel-width.ts b/studio/frontend/src/hooks/use-panel-width.ts
index eaf040fd148..45b9a022b50 100644
--- a/studio/frontend/src/hooks/use-panel-width.ts
+++ b/studio/frontend/src/hooks/use-panel-width.ts
@@ -77,6 +77,7 @@ export function createPanelWidthStore({
let effectiveWidth = clamp(storedWidth);
let effectiveMax = maxWidth();
const listeners = new Set<() => void>();
+ let unsubscribeScale: (() => void) | undefined;
let lastStored = storedWidth;
@@ -96,6 +97,12 @@ export function createPanelWidthStore({
listeners.forEach((cb) => cb());
}
+ function onStorage(event: StorageEvent) {
+ if (event.key !== key && event.key !== null) return;
+ storedWidth = load();
+ recompute();
+ }
+
function subscribe(cb: () => void) {
// With no subscribers there is no resize listener, so the cache can be
// stale after a resize on a route that hides every panel. Refresh first;
@@ -105,23 +112,19 @@ export function createPanelWidthStore({
if (typeof window === "undefined") {
return () => listeners.delete(cb);
}
- // Keep tabs in sync, same as the pin flag.
- const onStorage = (e: StorageEvent) => {
- if (e.key === key || e.key === null) {
- storedWidth = load();
- effectiveWidth = clamp(storedWidth);
- effectiveMax = maxWidth();
- cb();
- }
- };
- window.addEventListener("storage", onStorage);
- window.addEventListener("resize", recompute);
- const unsubscribeScale = subscribeLayoutScale(recompute);
+ if (listeners.size === 1) {
+ window.addEventListener("storage", onStorage);
+ window.addEventListener("resize", recompute);
+ unsubscribeScale = subscribeLayoutScale(recompute);
+ }
return () => {
listeners.delete(cb);
- unsubscribeScale();
- window.removeEventListener("storage", onStorage);
- window.removeEventListener("resize", recompute);
+ if (listeners.size === 0) {
+ unsubscribeScale?.();
+ unsubscribeScale = undefined;
+ window.removeEventListener("storage", onStorage);
+ window.removeEventListener("resize", recompute);
+ }
};
}
diff --git a/studio/frontend/src/hooks/use-slider-draft.ts b/studio/frontend/src/hooks/use-slider-draft.ts
new file mode 100644
index 00000000000..ef6388799bc
--- /dev/null
+++ b/studio/frontend/src/hooks/use-slider-draft.ts
@@ -0,0 +1,73 @@
+// 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 { useEffectEvent, useLayoutEffect, useRef, useState } from "react";
+import { flushSync } from "react-dom";
+
+export function useSliderDraft(
+ value: number,
+ onCommit: (value: number) => void,
+ onDraft?: (value: number | null) => void,
+) {
+ const [draft, setDraft] = useState<number | null>(null);
+ const pointers = useRef(new Set<number>());
+ const dragged = useRef<{ value: number; base: number } | null>(null);
+ const owner = useRef(value);
+ useLayoutEffect(() => {
+ owner.current = value;
+ }, [value]);
+ const show = (next: number | null) => {
+ setDraft(next);
+ onDraft?.(next);
+ };
+ const end = () => {
+ const drag = dragged.current;
+ pointers.current.clear();
+ dragged.current = null;
+ show(null);
+ if (
+ drag !== null &&
+ drag.base === owner.current &&
+ drag.value !== owner.current
+ )
+ onCommit(drag.value);
+ };
+ const release = ({ pointerId }: { pointerId: number }) => {
+ if (!pointers.current.delete(pointerId)) return;
+ if (pointers.current.size === 0) end();
+ };
+ const endOnUnmount = useEffectEvent(() => {
+ if (pointers.current.size > 0) end();
+ });
+ const releaseRemoved = useEffectEvent((event: PointerEvent) => {
+ if (event.target === document) release(event);
+ });
+ useLayoutEffect(() => {
+ const onLostCapture = (event: PointerEvent) => releaseRemoved(event);
+ document.addEventListener("lostpointercapture", onLostCapture);
+ return () => {
+ document.removeEventListener("lostpointercapture", onLostCapture);
+ endOnUnmount();
+ };
+ }, []);
+ return {
+ draft,
+ sliderProps: {
+ value: [draft ?? value],
+ onPointerDown: ({ pointerId }: { pointerId: number }) => {
+ pointers.current.add(pointerId);
+ },
+ onValueChange: ([next]: number[]) => {
+ if (pointers.current.size === 0) return;
+ const drag = { value: next, base: owner.current };
+ dragged.current = drag;
+ flushSync(() => show(next));
+ drag.base = owner.current;
+ },
+ onValueCommit: ([next]: number[]) => {
+ if (pointers.current.size === 0) onCommit(next);
+ },
+ onLostPointerCapture: release,
+ },
+ };
+}
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index edfb8ed3f3a..cf8cd9d7513 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -21,8 +21,7 @@
and page navigation. Window controls paint above it, keeping their glyphs
and hover feedback sharp without changing hit testing.
Only viewport backdrops participate; a panel-local dialog or a menu must
- not dim the window chrome. :has also keeps stacked modals correct without
- a separate counter or document-wide MutationObserver. */
+ not dim the window chrome. */
[data-slot="window-titlebar"]::after {
content: "";
position: absolute;
@@ -35,8 +34,7 @@
opacity: 0;
transition: opacity 100ms;
}
- body:has(> [data-viewport-backdrop="true"][data-state="open"])
- [data-slot="window-titlebar"]::after {
+ [data-slot="window-titlebar"][data-viewport-backdrop-open]::after {
opacity: 1;
}
@@ -1842,7 +1840,8 @@ html[data-contrast-adjust].dark .hub-page :is([class*="bg-background"], [class*=
/* Code font size: only overrides when the user sets an explicit size, so the
per-element Tailwind sizes stay authoritative by default. */
-html[data-code-font-size] :is(pre, code, kbd, samp) {
+html[data-code-font-size] :is(pre, code, kbd, samp),
+html[data-code-font-size] .aui-reasoning-code-lines {
font-size: var(--custom-code-font-size) !important;
}
@@ -2426,14 +2425,14 @@ html[data-chat-font] .aui-root {
margin-right: calc(3.4px * var(--ui-space-scale, 1));
}
.aui-branch-chevron-btn,
- .aui-branch-chevron-btn + * {
+ .aui-branch-chevron-btn + .aui-branch-picker-state {
--aui-chevron-slot: calc(20px * var(--ui-space-scale, 1));
--aui-chevron-hit: max(calc(24px * var(--ui-interface-scale, 1)), var(--aui-chevron-slot));
--aui-chevron-extra: calc(var(--aui-chevron-hit) - var(--aui-chevron-slot));
}
/* The count between the chevrons is at least as wide as both extensions, so they cannot meet over it even
in a narrow custom chat font. Wider counts, the usual case, are untouched. */
- .aui-branch-chevron-btn + :not(.aui-branch-chevron-btn) {
+ .aui-branch-chevron-btn + .aui-branch-picker-state {
/* 1px of slack: two targets that only touch can still trade a sub-pixel once snapped to device pixels. */
min-inline-size: calc(var(--aui-chevron-extra) * 2 + 1px);
text-align: center;
@@ -3139,74 +3138,19 @@ html[data-chat-font] .aui-root {
background-color: var(--sidebar) !important;
}
- /* Menus portal after the dialog or picker they open from. There they glow
- in its surface, and stock menus lift to the Hub tone. Sibling selectors,
- as body:has() restyles the whole page on every <body> insert.
- Defined on <html> so --accent can be reassigned without a cycle. */
+ /* On <html> so --accent can be reassigned without a cycle. */
.dark {
--dropdown-lift-surface: color-mix(in srgb, var(--accent) 60%, var(--popover));
--dropdown-lift-accent: color-mix(in srgb, var(--foreground) 6%, var(--accent));
}
- .dark
- body
- > :is([data-slot="dialog-content"], [data-slot="alert-dialog-content"])[data-state="open"]:is(
- .dialog-soft-surface,
- .settings-surface,
- [class*="dark:bg-card"]
- )
- ~ *
- :is(
- [data-slot="dropdown-menu-content"],
- [data-slot="dropdown-menu-sub-content"],
- [data-slot="context-menu-content"],
- [data-slot="context-menu-sub-content"],
- [data-slot="select-content"],
- [data-slot="combobox-content"],
- [data-slot="popover-content"],
- .dropdown-surface
- ) {
+ .dark [data-dropdown-glow="card"] {
--dropdown-glow: var(--card);
}
- /* After the dialog rule, so a picker in a dialog wins. */
- .dark
- body
- > [data-radix-popper-content-wrapper]:has(> .unsloth-model-selector-menu[data-state="open"])
- ~ *
- :is(
- [data-slot="dropdown-menu-content"],
- [data-slot="dropdown-menu-sub-content"],
- [data-slot="context-menu-content"],
- [data-slot="context-menu-sub-content"],
- [data-slot="select-content"],
- [data-slot="combobox-content"],
- [data-slot="popover-content"],
- .dropdown-surface
- ) {
+ .dark [data-dropdown-glow="picker"] {
--dropdown-glow: var(--sidebar);
}
.dark
- :is(
- body
- > :is([data-slot="dialog-content"], [data-slot="alert-dialog-content"])[data-state="open"]:is(
- .dialog-soft-surface,
- .settings-surface,
- [class*="dark:bg-card"]
- )
- ~ *,
- body
- > [data-radix-popper-content-wrapper]:has(> .unsloth-model-selector-menu[data-state="open"])
- ~ *
- )
- :is(
- [data-slot="dropdown-menu-content"],
- [data-slot="dropdown-menu-sub-content"],
- [data-slot="context-menu-content"],
- [data-slot="context-menu-sub-content"],
- [data-slot="select-content"],
- [data-slot="combobox-content"],
- [data-slot="popover-content"],
- .dropdown-surface
- ):not(
+ [data-dropdown-glow]:not(
.unsloth-model-selector-menu,
.sidebar-menu,
.sidebar-more-menu,
@@ -3789,55 +3733,46 @@ html[data-chat-font] .aui-root {
The gutters here are on the pane's width, not the window's: an artifact
split can leave a 42% thread pane inside a wide window, and a viewport
breakpoint would keep the full 20px there. */
- @container (max-width: 31.5rem) {
- .unsloth-composer-dock-inner {
- padding-left: calc(0.75rem * var(--ui-space-scale, 1));
- padding-right: calc(0.75rem * var(--ui-space-scale, 1));
- }
+ :where(.aui-thread-root[data-thread-narrow]) .unsloth-composer-dock-inner {
+ padding-left: calc(0.75rem * var(--ui-space-scale, 1));
+ padding-right: calc(0.75rem * var(--ui-space-scale, 1));
+ }
- /* The welcome screen is inside the viewport's own 20px gutter, so pull
- back to the dock's 12px rather than adding to it; otherwise the empty
- state is 40px narrower than the thread it turns into. */
- .aui-thread-welcome-message {
- padding-left: 0;
- padding-right: 0;
- margin-left: calc(-0.5rem * var(--ui-space-scale, 1));
- margin-right: calc(-0.5rem * var(--ui-space-scale, 1));
- /* w-full would pin the width and the margins would only shift the
- box left. An explicit width widens it into the gutter instead;
- auto would shrink-wrap, since the parent centres its children. */
- width: calc(100% + 1rem * var(--ui-space-scale, 1));
- }
+ /* Pull back into the viewport's gutter, or the empty state is 40px narrower than the thread. */
+ :where(.aui-thread-root[data-thread-narrow]) .aui-thread-welcome-message {
+ padding-left: 0;
+ padding-right: 0;
+ margin-left: calc(-0.5rem * var(--ui-space-scale, 1));
+ margin-right: calc(-0.5rem * var(--ui-space-scale, 1));
+ width: calc(100% + 1rem * var(--ui-space-scale, 1));
+ }
- .unsloth-welcome-title {
- font-size: var(--text-2xl);
- }
+ :where(.aui-thread-root[data-thread-narrow]) .unsloth-welcome-title {
+ font-size: var(--text-2xl);
+ }
- .unsloth-welcome-sloth {
- width: calc(2.125rem * var(--ui-space-scale, 1));
- height: calc(2.125rem * var(--ui-space-scale, 1));
- }
+ :where(.aui-thread-root[data-thread-narrow]) .unsloth-welcome-sloth {
+ width: calc(2.125rem * var(--ui-space-scale, 1));
+ height: calc(2.125rem * var(--ui-space-scale, 1));
+ }
- .unsloth-welcome-greeting {
- gap: calc(0.625rem * var(--ui-space-scale, 1));
- }
+ :where(.aui-thread-root[data-thread-narrow]) .unsloth-welcome-greeting {
+ gap: calc(0.625rem * var(--ui-space-scale, 1));
}
/* ~300px and under: one step further, so the greeting holds a single line
beside the mascot instead of wrapping over the composer. */
- @container (max-width: 18.75rem) {
- .unsloth-welcome-title {
- font-size: var(--text-xl);
- }
+ :where(.aui-thread-root[data-thread-tiny]) .unsloth-welcome-title {
+ font-size: var(--text-xl);
+ }
- .unsloth-welcome-sloth {
- width: calc(1.75rem * var(--ui-space-scale, 1));
- height: calc(1.75rem * var(--ui-space-scale, 1));
- }
+ :where(.aui-thread-root[data-thread-tiny]) .unsloth-welcome-sloth {
+ width: calc(1.75rem * var(--ui-space-scale, 1));
+ height: calc(1.75rem * var(--ui-space-scale, 1));
+ }
- .unsloth-welcome-greeting {
- gap: calc(0.5rem * var(--ui-space-scale, 1));
- }
+ :where(.aui-thread-root[data-thread-tiny]) .unsloth-welcome-greeting {
+ gap: calc(0.5rem * var(--ui-space-scale, 1));
}
/* Right-side Thinking pill (toggle or dropdown). pl-2 matches the left
@@ -4388,7 +4323,7 @@ html[data-chat-font] .aui-root {
border-bottom-left-radius: 1.5rem;
border-bottom-right-radius: 1.5rem;
}
- .aui-reasoning-code-fragment pre,
+ .aui-reasoning-code-fragment .aui-reasoning-code-lines,
.aui-reasoning-code-fragment code {
font-family: var(--custom-code-font, "Fira Code", ui-monospace, monospace);
}
@@ -4460,7 +4395,11 @@ html[data-chat-font] .aui-root {
font-size: calc(0.6875rem * var(--ui-font-scale, 1));
}
- @container (min-width: 36rem) {
+ .aui-thread-root:where([data-thread-wide]) [data-streamdown="code-block-header"] {
+ font-size: calc(0.75rem * var(--ui-font-scale, 1));
+ }
+
+ @media print {
.aui-thread-root [data-streamdown="code-block-header"] {
font-size: calc(0.75rem * var(--ui-font-scale, 1));
}
@@ -4472,12 +4411,12 @@ html[data-chat-font] .aui-root {
margin-right: calc(var(--spacing) * 1);
}
- .aui-thread-root [data-streamdown="table-wrapper"] > div:first-child:not(:last-child) > .relative {
+ .aui-thread-root [data-streamdown="table-wrapper"] > div > .relative {
display: flex;
}
- .aui-thread-root [data-streamdown="table-wrapper"] > div:first-child:not(:last-child) > button,
- .aui-thread-root [data-streamdown="table-wrapper"] > div:first-child:not(:last-child) > .relative > button {
+ .aui-thread-root [data-streamdown="table-wrapper"] > div > button,
+ .aui-thread-root [data-streamdown="table-wrapper"] > div > .relative > button {
display: flex;
align-items: center;
justify-content: center;
@@ -4488,8 +4427,8 @@ html[data-chat-font] .aui-root {
color: var(--color-chat-icon-fg);
}
- .aui-thread-root [data-streamdown="table-wrapper"] > div:first-child:not(:last-child) > button:hover:not(:disabled),
- .aui-thread-root [data-streamdown="table-wrapper"] > div:first-child:not(:last-child) > .relative > button:hover:not(:disabled) {
+ .aui-thread-root [data-streamdown="table-wrapper"] > div > button:hover:not(:disabled),
+ .aui-thread-root [data-streamdown="table-wrapper"] > div > .relative > button:hover:not(:disabled) {
background-color: var(--color-chat-icon-bg-hover);
color: var(--color-chat-icon-fg-hover);
}
@@ -4528,10 +4467,10 @@ html[data-chat-font] .aui-root {
paragraph. `:where()` keeps this at zero specificity so a part that does set its own
`mt-*` still wins. The first real child follows a zero-height badge anchor and gets none.
Not `* + *`: that restyles the whole page when Radix inserts its focus guard. */
- :where(.aui-assistant-message-content > :not(:first-child)) {
+ :where(.aui-assistant-message-content > *):where(:not(:first-child)) {
margin-top: calc(1rem * var(--ui-space-scale, 1));
}
- :where(.aui-assistant-message-content > .h-0 + *) {
+ :where(.aui-assistant-message-content > *):where(.h-0 + *) {
margin-top: 0;
}
@@ -4760,6 +4699,44 @@ html[data-chat-font] .aui-root {
contain-intrinsic-size: none !important;
}
}
+
+ 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);
+ }
+
+ html[data-interface-zooming] .aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk],
+ html[data-interface-zooming] .aui-thread-root [data-unsloth-fence-windowed],
+ html[data-interface-zooming] .aui-thread-root .aui-math-block,
+ html[data-interface-zooming] .aui-thread-root .aui-math-display {
+ content-visibility: visible !important;
+ }
+
+ @media print {
+ .aui-thread-root [data-unsloth-fence-windowed] {
+ content-visibility: visible !important;
+ contain-intrinsic-size: none !important;
+ }
+ }
+
+ .aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk] {
+ contain-intrinsic-size: auto var(--unsloth-chunk-estimate);
+ }
+
+ html[data-reasoning-row-containment="on"] .aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk] {
+ display: flow-root;
+ }
+
+ html[data-reasoning-row-containment="on"] .aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk][data-settled] {
+ content-visibility: auto;
+ }
+
+ @media print {
+ .aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk] {
+ content-visibility: visible !important;
+ contain-intrinsic-size: none !important;
+ }
+ }
}
/* No border line; the composer's shadow lifts the toast off the page.
@@ -5379,11 +5356,10 @@ html.force-reduced-motion .sidebar-section-drop-line {
}
/* Chromium ignores ::-webkit-scrollbar while scrollbar-width/color are set, and its standard
- Windows scrollbar draws arrows. :hover too, or the reveal rules flip it back; the width
- stays overridable so !important and inline hides still win. */
+ Windows scrollbar draws arrows. The width stays overridable so !important and inline
+ hides still win. */
@supports selector(::-webkit-scrollbar) {
- :root.client-windows *,
- :root.client-windows *:hover {
+ :root.client-windows * {
scrollbar-width: auto;
scrollbar-color: auto !important;
}
@@ -5397,15 +5373,6 @@ html.force-reduced-motion .sidebar-section-drop-line {
:root.client-windows .no-scrollbar::-webkit-scrollbar {
display: block;
}
-
- :root.client-windows {
- --thread-scrollbar-gutter: 8px;
- }
-}
-
-/* Start the classic scrollbar below the chat header, which overlays the thread. */
-:root.client-windows .aui-thread-viewport::-webkit-scrollbar-track {
- margin-top: var(--thread-header-offset, 0px);
}
/* Run settings: always reserve the scrollbar gutter so the header close
@@ -5420,8 +5387,10 @@ html.force-reduced-motion .sidebar-section-drop-line {
}
/* Chromium's thin scrollbar width; scrollbars ignore the UI scale. */
-:root {
- --thread-scrollbar-gutter: 10px;
+@property --thread-scrollbar-gutter {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 10px;
}
/* Chat viewport: scrollbar styled with Run settings above, so no track to clip at the corner. */
@@ -5433,6 +5402,35 @@ html.force-reduced-motion .sidebar-section-drop-line {
scrollbar-gutter: stable both-edges;
}
+.aui-thread-host[data-aui-following] + .aui-thread-root .aui-thread-viewport {
+ overflow-anchor: none;
+}
+
+@supports selector(::-webkit-scrollbar) {
+ :root.client-windows .aui-thread-viewport {
+ scrollbar-width: thin;
+ scrollbar-color: transparent transparent !important;
+ }
+
+ :root.client-windows .aui-thread-viewport:hover {
+ scrollbar-color: oklch(0.5 0 0 / 0.4) transparent !important;
+ }
+
+ .dark:root.client-windows .aui-thread-viewport:hover,
+ :root.client-windows .dark .aui-thread-viewport:hover {
+ scrollbar-color: oklch(0.72 0 0 / 0.4) transparent !important;
+ }
+
+ @media screen and (forced-colors: none) {
+ :root.client-windows[data-low-device-scale] .aui-thread-viewport:not(.chat-full-view-dock *) {
+ scrollbar-gutter: auto;
+ overflow-y: scroll;
+ border-inline-start: var(--thread-scrollbar-gutter) solid transparent;
+ background-color: var(--background);
+ }
+ }
+}
+
/* An unregistered custom property always inherits, so writing
--aui-scroll-stabilizer on the scroll container dirties inherited style for
every descendant and the next scrollHeight read restyles the whole thread.
@@ -5457,6 +5455,24 @@ html.force-reduced-motion .sidebar-section-drop-line {
initial-value: 0px;
}
+@property --removed-body-scroll-bar-size {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+@property --unsloth-fence-height {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+@property --unsloth-chunk-estimate {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
/* Marker class applied only to actual streaming-thread viewports
(see ThreadPrimitive.Viewport in components/assistant-ui/thread.tsx).
Scoped separately from `.aui-thread-viewport` because that class is
@@ -5935,15 +5951,18 @@ html.force-reduced-motion .sidebar-section-drop-line {
top: calc(var(--studio-content-top-inset, 0px) + 3.5rem);
}
-/* Nothing notifies JS when these mount, so CSS keeps the portaled bars under them. */
-html:has([aria-modal="true"], [data-blocking-screen]) [data-find-bar-layer],
-html:has([data-blocking-screen]) .interface-zoom-position {
+html[data-blocking-screen-open] [data-find-bar-layer],
+html[data-blocking-screen-open] .interface-zoom-position {
+ display: none;
+}
+
+html[data-browser-overlay-open] [data-find-bar-layer] {
display: none;
}
/* Toasts stack under the open find bar: its top, its h-13, then 8px. Not the zoom popup, which
shares the surface class. */
-:root:has([data-find-bar-layer]:not([hidden]) .find-bar-surface) [data-sonner-toaster][data-y-position="top"] {
+html[data-find-bar-open] [data-sonner-toaster][data-y-position="top"] {
--offset-top: calc(var(--studio-content-top-inset, 0px) + 3.5rem + 3.25rem * var(--ui-space-scale, 1) + 0.5rem) !important;
--mobile-offset-top: calc(var(--studio-content-top-inset, 0px) + 3.5rem + 3.25rem * var(--ui-space-scale, 1) + 0.5rem) !important;
}
@@ -5984,7 +6003,7 @@ html:has([data-blocking-screen]) .interface-zoom-position {
--studio-content-top-inset: 0px;
--studio-chat-header-height: 0px;
--studio-chat-notice-height: 0px;
- --thread-scrollbar-gutter: 0px;
+ --studio-chat-scroller-top: 0px;
height: auto;
border-radius: 28px;
background-color: var(--dock-surface);
@@ -5993,6 +6012,10 @@ html:has([data-blocking-screen]) .interface-zoom-position {
0 12px 32px -8px rgb(0 0 0 / 0.22);
}
+.chat-full-view-dock .aui-thread-composer-dock {
+ --thread-scrollbar-gutter: 0px;
+}
+
.dark .chat-full-view-dock {
--dock-surface: var(--card);
box-shadow:
diff --git a/studio/frontend/src/lib/document-flag.ts b/studio/frontend/src/lib/document-flag.ts
new file mode 100644
index 00000000000..577857223dd
--- /dev/null
+++ b/studio/frontend/src/lib/document-flag.ts
@@ -0,0 +1,31 @@
+// 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 { useLayoutEffect } from "react";
+
+const holders = new Map<string, number>();
+
+export function acquireDocumentFlag(name: string): () => void {
+ const root = document.documentElement;
+ holders.set(name, (holders.get(name) ?? 0) + 1);
+ root.setAttribute(name, "");
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const left = (holders.get(name) ?? 1) - 1;
+ if (left > 0) {
+ holders.set(name, left);
+ return;
+ }
+ holders.delete(name);
+ root.removeAttribute(name);
+ };
+}
+
+export function useDocumentFlag(name: string, active: boolean): void {
+ useLayoutEffect(() => {
+ if (!active) return;
+ return acquireDocumentFlag(name);
+ }, [name, active]);
+}
diff --git a/studio/frontend/src/lib/schedule-idle-task.ts b/studio/frontend/src/lib/schedule-idle-task.ts
index 63dcb760f96..88321de8ac5 100644
--- a/studio/frontend/src/lib/schedule-idle-task.ts
+++ b/studio/frontend/src/lib/schedule-idle-task.ts
@@ -1,6 +1,33 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+const INPUT_QUIET_MS = 300;
+const INPUT_EVENTS = [
+ "wheel",
+ "scroll",
+ "pointerdown",
+ "keydown",
+ "touchstart",
+ "touchmove",
+] as const;
+let lastInputAt = Number.NEGATIVE_INFINITY;
+let watchingInput = false;
+const noteInput = (): void => {
+ lastInputAt = performance.now();
+};
+const watchInput = (): void => {
+ if (watchingInput || typeof document === "undefined") return;
+ watchingInput = true;
+ for (const type of INPUT_EVENTS) {
+ document.addEventListener(type, noteInput, { capture: true, passive: true });
+ }
+};
+
+export const inputQuietIn = (): number => {
+ watchInput();
+ return INPUT_QUIET_MS - (performance.now() - lastInputAt);
+};
+
/**
* 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 webview
@@ -41,3 +68,29 @@ export function scheduleIdleTask(
globalThis.clearTimeout(handle);
};
}
+
+export function scheduleQuietIdleTask(
+ callback: () => void,
+ timeout = 250,
+): () => void {
+ if (
+ typeof window === "undefined" ||
+ typeof window.requestIdleCallback === "function"
+ ) {
+ return scheduleIdleTask(callback, timeout);
+ }
+
+ watchInput();
+ const deadline = performance.now() + timeout;
+ let handle: ReturnType<typeof setTimeout>;
+ const attempt = (): void => {
+ const wait = Math.min(inputQuietIn(), deadline - performance.now());
+ if (wait > 0) {
+ handle = globalThis.setTimeout(attempt, wait);
+ return;
+ }
+ callback();
+ };
+ handle = globalThis.setTimeout(attempt, Math.min(timeout, 16));
+ return () => globalThis.clearTimeout(handle);
+}
diff --git a/studio/frontend/src/lib/toast-offset.ts b/studio/frontend/src/lib/toast-offset.ts
index a2b94675a9c..c291004d5dd 100644
--- a/studio/frontend/src/lib/toast-offset.ts
+++ b/studio/frontend/src/lib/toast-offset.ts
@@ -72,6 +72,51 @@ export function insetPastChatSettings(offset: ToastOffset): {
};
}
+type InsetStyle = Pick<
+ CSSStyleDeclaration,
+ "setProperty" | "removeProperty" | "getPropertyValue"
+>;
+
+const insetScopes = new Set<HTMLElement>();
+const insetValues = new Map<string, string>();
+
+function removeCornerInset(name: string): string {
+ const previous = insetValues.get(name) ?? "";
+ insetValues.delete(name);
+ for (const scope of insetScopes) scope.style.removeProperty(name);
+ return previous;
+}
+
+function setCornerInset(name: string, value: string | null): void {
+ if (!value) {
+ removeCornerInset(name);
+ return;
+ }
+ insetValues.set(name, value);
+ for (const scope of insetScopes) scope.style.setProperty(name, value);
+}
+
+export const cornerInsets: { style: InsetStyle } = {
+ style: {
+ setProperty: setCornerInset,
+ removeProperty: removeCornerInset,
+ getPropertyValue: (name: string) => insetValues.get(name) ?? "",
+ },
+};
+
+export function cornerInsetScope(
+ element: HTMLElement | null,
+): (() => void) | undefined {
+ if (!element) return undefined;
+ insetScopes.add(element);
+ for (const [name, value] of insetValues) {
+ element.style.setProperty(name, value);
+ }
+ return () => {
+ insetScopes.delete(element);
+ };
+}
+
type InsetPanel = {
offsetWidth: number;
parentElement: { clientWidth: number } | null;
diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsx
index bf72c0ba2ea..963a7e67bfe 100644
--- a/studio/frontend/src/main.tsx
+++ b/studio/frontend/src/main.tsx
@@ -6,10 +6,18 @@ import { createRoot } from "react-dom/client";
import "./index.css";
import { App } from "./app/app";
+import {
+ applyCodeBlockContainment,
+ watchCodeBlockContainmentOverride,
+} from "./components/assistant-ui/code-block-containment";
import {
applyMathBlockContainment,
watchMathBlockContainmentOverride,
} from "./components/assistant-ui/math-block-containment";
+import {
+ applyReasoningRowContainment,
+ watchReasoningRowContainmentOverride,
+} from "./components/assistant-ui/reasoning-row-containment";
import { fetchDeviceType } from "./config/env";
import { refreshSession } from "./features/auth/api";
import {
@@ -56,6 +64,10 @@ applyMathBlockContainment();
// And keep watching, so a devtools flip of `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` reapplies instead of
// leaving the session measuring the arm it was already in.
watchMathBlockContainmentOverride();
+applyCodeBlockContainment();
+watchCodeBlockContainmentOverride();
+applyReasoningRowContainment();
+watchReasoningRowContainmentOverride();
// Keep right-edge controls clear of overlay scrollbars.
watchOverlayScrollbarGutter(window);
diff --git a/studio/frontend/tests/browser-native-view-snapshot.test.ts b/studio/frontend/tests/browser-native-view-snapshot.test.ts
index fe78aac9226..144fac0c58f 100644
--- a/studio/frontend/tests/browser-native-view-snapshot.test.ts
+++ b/studio/frontend/tests/browser-native-view-snapshot.test.ts
@@ -110,6 +110,16 @@ const { currentEntry, useBrowserStore } = await import("../src/features/browser/
const { refreshCoveredPage, startNativeViews } = await import(
"../src/features/browser/native-view.ts"
);
+const { cornerInsetScope, cornerInsets } = await import(
+ "../src/lib/toast-offset.ts"
+);
+const insetVars = new Map<string, string>();
+cornerInsetScope({
+ style: {
+ setProperty: (name: string, value: string) => insetVars.set(name, value),
+ removeProperty: (name: string) => insetVars.delete(name),
+ },
+} as unknown as HTMLElement);
const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
// apply overlay mutations before their scheduled frame
@@ -346,24 +356,27 @@ test("toasts move left of a page that sits beside the Run settings panel", async
try {
pageBox = rect(500, 100, 500, 600);
await frame();
- assert.equal(rootVars.get("--studio-browser-page-inset"), "500px");
+ assert.equal(insetVars.get("--studio-browser-page-inset"), "500px");
// ignore pages away from the window edge because they do not constrain toasts
pageBox = rect(400, 100, 300, 600);
await frame();
- assert.equal(rootVars.has("--studio-browser-page-inset"), false);
+ assert.equal(insetVars.has("--studio-browser-page-inset"), false);
// include the 300px Run settings panel between the page and window edge
- rootVars.set("--studio-chat-settings-inset", "300px");
+ cornerInsets.style.setProperty("--studio-chat-settings-inset", "300px");
await frame();
- assert.equal(rootVars.get("--studio-browser-page-inset"), "600px");
+ assert.equal(insetVars.get("--studio-browser-page-inset"), "600px");
// omit the inset when no toast column fits; an overlapping toast will hide the page instead
pageBox = rect(200, 100, 500, 600);
await frame();
- assert.equal(rootVars.has("--studio-browser-page-inset"), false);
+ assert.equal(insetVars.has("--studio-browser-page-inset"), false);
+ assert.equal(rootVars.size, 0, "the insets reach their consumers, never <html>");
} finally {
stop();
+ cornerInsets.style.removeProperty("--studio-chat-settings-inset");
+ cornerInsets.style.removeProperty("--studio-browser-page-inset");
rootVars.clear();
pageBox = rect(500, 100, 500, 600);
}
diff --git a/studio/frontend/tests/browser-outside-thread.test.ts b/studio/frontend/tests/browser-outside-thread.test.ts
new file mode 100644
index 00000000000..41a726d8545
--- /dev/null
+++ b/studio/frontend/tests/browser-outside-thread.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { outsideThread } from "../src/features/browser/outside-thread.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+class Node {
+ readonly children: Node[] = [];
+ parentElement: Node | null = null;
+ readonly name: string;
+ readonly marks: string[];
+ constructor(name: string, marks: string[] = []) {
+ this.name = name;
+ this.marks = marks;
+ }
+ add(...nodes: Node[]): this {
+ for (const node of nodes) {
+ node.parentElement = this;
+ this.children.push(node);
+ }
+ return this;
+ }
+ matches(selector: string): boolean {
+ return this.marks.includes(selector);
+ }
+ descendants(): Node[] {
+ return this.children.flatMap((child) => [child, ...child.descendants()]);
+ }
+ querySelectorAll(selector: string): Node[] {
+ return this.descendants().filter((node) => node.matches(selector));
+ }
+ querySelector(selector: string): Node | null {
+ return this.querySelectorAll(selector)[0] ?? null;
+ }
+}
+
+function page(withThread: boolean) {
+ const inside = new Node("inside", ["overlay"]);
+ const viewport = new Node("viewport", withThread ? [".aui-thread-viewport"] : []).add(
+ new Node("message").add(inside),
+ );
+ const dock = new Node("dock", ["dock"]).add(viewport, new Node("composer"));
+ const html = new Node("html").add(
+ new Node("head"),
+ new Node("body").add(
+ new Node("portal", ["overlay"]).add(new Node("menu", ["overlay"])),
+ new Node("root").add(
+ new Node("sidebar").add(new Node("inline", ["overlay"])),
+ new Node("main").add(
+ dock,
+ new Node("panel").add(new Node("cover", ["overlay"]), new Node("inset", ["dock"])),
+ ),
+ ),
+ ),
+ );
+ return { html, document: { querySelector: (s: string) => html.querySelector(s), querySelectorAll: (s: string) => html.querySelectorAll(s) } };
+}
+
+const names = (nodes: unknown[]) => (nodes as Node[]).map((node) => node.name).sort();
+
+test("the native page's overlay scan covers everything but the thread's messages", () => {
+ const { document } = page(true);
+ assert.deepEqual(names(outsideThread("overlay", document as never)), ["cover", "inline", "menu", "portal"]);
+ assert.deepEqual(
+ names(outsideThread("dock", document as never)),
+ ["dock", "inset"],
+ "the full-view dock encloses the thread and is still found",
+ );
+});
+
+test("without a thread on the page the scan is the whole document", () => {
+ const { document } = page(false);
+ assert.deepEqual(names(outsideThread("overlay", document as never)), ["cover", "inline", "inside", "menu", "portal"]);
+});
+
+test("nothing that can cover a native page renders inside the thread", () => {
+ const native = readSrc("features/browser/native-view.ts");
+ assert.match(native, /for \(const element of outsideThread(?:<HTMLElement>)?\(selector\)\)/);
+ assert.match(native, /for \(const dock of outsideThread\(\s*"\.chat-full-view-dock, \.chat-full-view-dock-minimized, \[data-native-inset\]",\s*\)\)/);
+ assert.doesNotMatch(native, /document\.querySelectorAll/, "a document-wide scan walked every message of a long thread on each 300 ms recheck, about 10 ms a time beside a native page");
+ for (const wrapper of ["dialog", "sheet", "alert-dialog", "popover", "dropdown-menu", "select", "tooltip", "hover-card", "context-menu", "combobox", "menubar"]) {
+ assert.match(readSrc(`components/ui/${wrapper}.tsx`), /Portal/, `${wrapper} renders into a portal`);
+ }
+ assert.match(readSrc("components/assistant-ui/image.tsx"), /createPortal\(\s*<button[\s\S]*?data-slot="image-zoom-overlay"[\s\S]*?document\.body,?\s*\)/, "the image zoom overlay leaves the thread");
+ assert.match(readSrc("app/provider.tsx"), /<Toaster\b/, "toasts render from the app shell");
+ for (const attribute of ["data-native-cover", "data-native-inset"]) {
+ assert.match(readSrc("features/browser/annotate-layer.tsx"), new RegExp(attribute));
+ }
+});
diff --git a/studio/frontend/tests/browser-resize-pin.test.ts b/studio/frontend/tests/browser-resize-pin.test.ts
new file mode 100644
index 00000000000..d806983a4b8
--- /dev/null
+++ b/studio/frontend/tests/browser-resize-pin.test.ts
@@ -0,0 +1,37 @@
+// 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";
+
+const box = (left: number, top: number, width: number, height: number) => ({
+ left,
+ top,
+ width,
+ height,
+ right: left + width,
+ bottom: top + height,
+});
+
+const style: Record<string, string> = { cssText: "" };
+const page = {
+ style,
+ getBoundingClientRect: () => box(836, 134, 602, 1068),
+ parentElement: { getBoundingClientRect: () => box(836, 83, 602, 1119) },
+};
+Object.assign(globalThis, {
+ document: { querySelector: () => page },
+});
+
+const { pinBrowserPage } = await import("../src/features/browser/resize-pin.ts");
+
+test("a page pinned for a split drag stays below the browser's toolbar", () => {
+ const unpin = pinBrowserPage({ getBoundingClientRect: () => box(826, 0, 20, 1200) } as Element);
+ assert.equal(style.position, "absolute");
+ assert.equal(style.top, "51px", "pinned at top: 0, the page covered the address bar and bookmarks for the whole drag");
+ assert.equal(style.bottom, "0");
+ assert.equal(style.width, "602px");
+ assert.equal(style.right, "0px", "anchored to the panel's outer edge, which stays put");
+ unpin();
+ assert.equal(style.cssText, "");
+});
diff --git a/studio/frontend/tests/chat-autoscroll-shrink-intent.test.ts b/studio/frontend/tests/chat-autoscroll-shrink-intent.test.ts
new file mode 100644
index 00000000000..0c448db8bb5
--- /dev/null
+++ b/studio/frontend/tests/chat-autoscroll-shrink-intent.test.ts
@@ -0,0 +1,71 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const HOOK = readSrc("components/assistant-ui/use-intent-aware-autoscroll.tsx");
+
+const between = (from: string, to: string): string => {
+ const start = HOOK.indexOf(from);
+ assert.notEqual(start, -1, `source assertion anchor is gone: ${from}`);
+ const end = HOOK.indexOf(to, start + from.length);
+ assert.notEqual(end, -1, `source assertion anchor is gone: ${to}`);
+ return HOOK.slice(start, end);
+};
+
+test("an upward scroll that arrives with a shorter page is content leaving, not the reader leaving the bottom", () => {
+ const body = between("const onScroll = () => {", "\n };");
+ assert.match(body, /const scrollHeight = el\.scrollHeight;/);
+ assert.match(
+ body,
+ /if \(\s*distanceDelta > 0 &&\s*!clamped &&\s*\(keyed \|\| scrollHeight >= lastScrollHeight\)\s*\) \{\s*upwardAccumulator \+= distanceDelta;/,
+ "a removal clamps scrollTop and content regrown before the scroll event lands must not read as the reader scrolling up, unless a scroll-up key was just pressed",
+ );
+ assert.match(body, /lastScrollHeight = scrollHeight;\s*requestTick\(\);/, "the height baseline advances with every scroll event");
+});
+
+test("leaving a pinned bottom as the page changes height, with no key or pointer behind it, is a clamp", () => {
+ const body = between("const onScroll = () => {", "\n };");
+ assert.match(
+ body,
+ /const clamped =\s*lastDistanceFromBottom <= AT_BOTTOM_THRESHOLD_PX &&\s*scrollHeight !== lastScrollHeight &&\s*!keyed &&\s*!pointerHeld;/,
+ "a row below shrinking as the next one lands pulls scrollTop up in the same event; detaching there stops the stream following",
+ );
+ assert.match(HOOK, /el\.addEventListener\("pointerdown", onPointerDown, \{ passive: true \}\);/, "a scrollbar drag starts with a pointerdown on the viewport");
+ assert.match(HOOK, /el\.ownerDocument\.addEventListener\("pointerup", onPointerUp, true\);/);
+ assert.match(HOOK, /el\.removeEventListener\("pointerdown", onPointerDown\);/);
+ assert.match(HOOK, /el\.ownerDocument\.removeEventListener\("pointerup", onPointerUp, true\);/);
+});
+
+test("the correction resyncs the height baseline with the others", () => {
+ const body = between("adjustImplRef.current = (", "const onWheel = ");
+ assert.match(body, /lastScrollTop = el\.scrollTop;\s*lastDistanceFromBottom = distanceFromBottom\(\);\s*lastScrollHeight = el\.scrollHeight;/);
+});
+
+test("the height baseline starts from the attached viewport", () => {
+ assert.match(HOOK, /let lastDistanceFromBottom = distanceFromBottom\(\);\s*let lastScrollHeight = el\.scrollHeight;/);
+});
+
+test("a scroll-up key opens the window in which a shorter page still counts as the reader leaving", () => {
+ const handler = between("const onKeyDown = (e: KeyboardEvent) => {", "const onTouchStart = ");
+ for (const key of ['e.key === "ArrowUp"', 'e.key === "PageUp"', 'e.key === "Home"', '(e.key === " " && e.shiftKey)']) {
+ assert.ok(handler.includes(key), `listens for ${key}`);
+ }
+ assert.match(handler, /e\.defaultPrevented/, "a key the page already handled does not scroll");
+ assert.match(handler, /target\?\.isContentEditable \|\|\s*target\?\.closest\("input, textarea, select"\)/, "keys typed into the composer or a field move a caret, not the thread");
+ assert.match(handler, /scrollKeyAt = performance\.now\(\);/);
+ assert.match(HOOK, /el\.ownerDocument\.addEventListener\("keydown", onKeyDown, \{\s*passive: true,\s*\}\);/);
+ assert.match(HOOK, /el\.ownerDocument\.removeEventListener\("keydown", onKeyDown\);/);
+});
+
+test("the first pin waits for the messages, then gives way to any later detach", () => {
+ const tick = between("const tick = (): void => {", "const following =");
+ assert.match(
+ tick,
+ /if \(pendingInitialPin && el\.querySelector\("\[data-role\]"\) !== null\) \{\s*pendingInitialPin = false;\s*if \(el\.scrollHeight > el\.clientHeight\) \{\s*parked = false;\s*userDetachedRef\.current = false;\s*extendFollow\(\);\s*\}\s*\}/,
+ "a thread that opens without overflowing has nothing to pin, so opening a card by hand in it later keeps the view where the reader put it",
+ );
+});
diff --git a/studio/frontend/tests/chat-column-centering.test.ts b/studio/frontend/tests/chat-column-centering.test.ts
index f719b540ed0..f4fe1541e02 100644
--- a/studio/frontend/tests/chat-column-centering.test.ts
+++ b/studio/frontend/tests/chat-column-centering.test.ts
@@ -47,15 +47,16 @@ test("nothing around the composer re-adds a one-sided inset", async () => {
});
// The gutter is a scrollbar, which the UI scale does not touch, so a scaled inset drifted the
-// composer off the message column. Windows lets the 8px ::-webkit-scrollbar through.
+// composer off the message column. The thread keeps Chromium's thin standard scrollbar on
+// Windows too, so there is one gutter width everywhere.
test("the overlays around the thread stop at its real scrollbar gutter", async () => {
const css = await readSrcAsync("index.css");
- for (const rule of [
- ":root {\n\t--thread-scrollbar-gutter: 10px;",
- ":root.client-windows {\n\t\t--thread-scrollbar-gutter: 8px;",
- ]) {
- assert.ok(css.includes(rule), rule);
- }
+ assert.match(css, /@property --thread-scrollbar-gutter \{\s*syntax: "<length>";\s*inherits: false;\s*initial-value: 10px;/);
+ assert.ok(!css.includes("--thread-scrollbar-gutter: 8px;"));
+ assert.match(
+ css,
+ /:root\.client-windows \.aui-thread-viewport \{\s*scrollbar-width: thin;/,
+ );
for (const file of [
"features/chat/chat-page.tsx",
"components/assistant-ui/thread.tsx",
diff --git a/studio/frontend/tests/chat-remembers-its-model.test.ts b/studio/frontend/tests/chat-remembers-its-model.test.ts
index 92c34c82491..c6cc6a84ecc 100644
--- a/studio/frontend/tests/chat-remembers-its-model.test.ts
+++ b/studio/frontend/tests/chat-remembers-its-model.test.ts
@@ -345,7 +345,7 @@ test("the conversation reserves the space the notice overlay takes", () => {
// 0px so every surface without a notice keeps exactly the padding it had.
assert.match(
thread,
- /\[--thread-header-offset:calc\(var\(--studio-content-top-inset,0px\)\+var\(--studio-chat-header-height,48px\)\+var\(--studio-chat-notice-height,0px\)\)\] pt-\[var\(--thread-header-offset\)\]/,
+ /\[--thread-header-offset:calc\(var\(--studio-content-top-inset,0px\)-var\(--studio-chat-scroller-top,0px\)\+var\(--studio-chat-header-height,48px\)\+var\(--studio-chat-notice-height,0px\)\)\] mt-\[var\(--studio-chat-scroller-top,0px\)\] pt-\[var\(--thread-header-offset\)\]/,
);
// And the fade moves down with it, or it would dissolve behind the opaque bar.
const fade = slice(page, "chat-header-fade", '"');
diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.ts
index c881a700b36..e5fd83d0f77 100644
--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts
+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts
@@ -49,6 +49,10 @@ function harness(response: ReturnType<typeof jsonResponse>) {
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
"./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
"@/features/auth": {
authFetch: async (url: string, init?: RequestInit) => {
requests.push({ url, init });
diff --git a/studio/frontend/tests/chat-split-drag-costs.test.ts b/studio/frontend/tests/chat-split-drag-costs.test.ts
new file mode 100644
index 00000000000..3f40557b968
--- /dev/null
+++ b/studio/frontend/tests/chat-split-drag-costs.test.ts
@@ -0,0 +1,37 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("the panel library's pointer-events toggle during a split drag stops at each panel's wrapper", () => {
+ const page = readSrc("features/chat/chat-page.tsx");
+ assert.match(
+ page,
+ /data-expanded=\{chatDock === "expanded" \? "true" : "false"\}\s*className=\{cn\(\s*"flex h-full min-h-0 min-w-0 flex-col overflow-hidden \[html\[data-panel-resizing\]_&\]:pointer-events-auto",/,
+ "react-resizable-panels sets pointer-events: none on both panels for the whole drag; inherited, it restyled the entire thread on press and again on release",
+ );
+ assert.doesNotMatch(
+ page,
+ /"pointer-events-auto flex h-full min-h-0 min-w-0 flex-col overflow-hidden"/,
+ "outside a drag the thread inherits pointer-events, so the body lock of an open modal menu keeps the dismissing click off the messages below",
+ );
+ assert.match(readSrc("components/ui/panel-drag-overlay.ts"), /document\.documentElement\.setAttribute\(PANEL_RESIZING_ATTRIBUTE, "true"\)/);
+ const css = readSrc("index.css");
+ assert.match(css, /\.chat-artifact-pop-surface \{\s*pointer-events: none;/);
+ assert.match(
+ css,
+ /\.chat-artifact-pop-surface\[data-artifact-surface-visible="true"\] \{\s*pointer-events: auto;/,
+ "the browser side's wrapper already sets its own",
+ );
+});
+
+test("thinking boxes wait for a panel drag to end before re-measuring their rows", () => {
+ assert.match(
+ readSrc("components/assistant-ui/reasoning-transcript.tsx"),
+ /const resettleLater = \(\) => \{\s*settleTimer = 0;\s*if \(panelDragInProgress\(\)\) \{\s*settleTimer = window\.setTimeout\(resettleLater, RESETTLE_DELAY_MS\);\s*return;\s*\}\s*resettleRows\(element\);/,
+ "a drag that paused for 150 ms, or met a panel's limit, re-laid every row of every open thinking box in the middle of the drag",
+ );
+});
diff --git a/studio/frontend/tests/child-selector-order.test.ts b/studio/frontend/tests/child-selector-order.test.ts
new file mode 100644
index 00000000000..5ddfe3f35f0
--- /dev/null
+++ b/studio/frontend/tests/child-selector-order.test.ts
@@ -0,0 +1,298 @@
+// 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 tailwindVite from "@tailwindcss/vite";
+import { compile } from "tailwindcss";
+
+import {
+ childSelectorOrder,
+ parentFirstChildSelectors,
+} from "../vite-plugin-child-selectors.ts";
+import { readSrc, readText } from "./helpers/kit.ts";
+
+const CHILD_POSITION_FIRST = />\s*:not\(:last-child\)\)/;
+
+test("Tailwind's spacing and divide utilities are rewritten to test the parent first", async () => {
+ const compiler = await compile(
+ "@theme { --spacing: 0.25rem; --color-border: #ddd; } @tailwind utilities;",
+ );
+ const generated = compiler.build([
+ "space-y-4",
+ "-space-x-0.5",
+ "space-x-2",
+ "divide-y",
+ "divide-border",
+ "divide-border/50",
+ ...["hover", "group-hover"].map((variant) => `${variant}:space-y-4`),
+ ]);
+ assert.match(
+ generated,
+ CHILD_POSITION_FIRST,
+ "Tailwind still emits :where(& > :not(:last-child)), the shape this plugin rewrites",
+ );
+ const rewritten = parentFirstChildSelectors(generated);
+ assert.doesNotMatch(
+ rewritten,
+ CHILD_POSITION_FIRST,
+ "a :not(:last-child) Chromium evaluates first flags every element in the app, so appending to any container restyled its previous last child's whole subtree",
+ );
+ assert.equal(
+ rewritten.split(":where(& > *):where(:not(:last-child))").length - 1,
+ generated.split(":where(& > :not(:last-child))").length - 1,
+ );
+});
+
+test("the rewrite keeps the match and the zero specificity, in every form Tailwind ships", () => {
+ const cases: [string, string][] = [
+ [
+ ":where(.space-y-4>:not(:last-child)){margin:0}",
+ ":where(.space-y-4 > *):where(:not(:last-child)){margin:0}",
+ ],
+ [
+ ".space-y-4 {\n :where(& > :not(:last-child)) {",
+ ".space-y-4 {\n :where(& > *):where(:not(:last-child)) {",
+ ],
+ [
+ ":where(.divide-border>:not(:last-child)),:where(.divide-border\\/50>:not(:last-child)){",
+ ":where(.divide-border > *):where(:not(:last-child)),:where(.divide-border\\/50 > *):where(:not(:last-child)){",
+ ],
+ [
+ ":where(.divide-border\\/\\[0\\.06\\]>:not(:last-child)){",
+ ":where(.divide-border\\/\\[0\\.06\\] > *):where(:not(:last-child)){",
+ ],
+ [
+ ":where(.group-hover\\:space-y-2:is(:where(.group):hover *)>:not(:last-child)){",
+ ":where(.group-hover\\:space-y-2:is(:where(.group):hover *) > *):where(:not(:last-child)){",
+ ],
+ [
+ ":where(.a\\)b>:not(:last-child)){",
+ ":where(.a\\)b > *):where(:not(:last-child)){",
+ ],
+ ];
+ for (const [input, output] of cases) {
+ assert.equal(parentFirstChildSelectors(input), output);
+ }
+});
+
+test("selectors the rewrite cannot keep equivalent are left alone", () => {
+ for (const css of [
+ ".not-last\\:border-b:not(:last-child){",
+ ":where(.a :not(:last-child)){",
+ ":where(.a > :not(:last-child), .b){",
+ ":where(.a > .b:not(:last-child)){",
+ ":where(.a > :not(:first-child)){",
+ ":where(> :not(:last-child)){",
+ ":is(.a > :not(:last-child)){",
+ ":where(.a > :not(:last-child)",
+ ]) {
+ assert.equal(parentFirstChildSelectors(css), css);
+ }
+});
+
+test("the plugin rewrites stylesheets only, after Tailwind has generated them", () => {
+ const hook = childSelectorOrder().transform as {
+ filter: { id: RegExp; code: string };
+ handler: (code: string) => { code: string; map: null } | null;
+ };
+ assert.ok(hook.filter.id.test("/app/src/index.css"));
+ assert.ok(hook.filter.id.test("/app/src/index.css?direct"));
+ assert.ok(!hook.filter.id.test("/app/src/main.tsx"));
+ assert.ok(!hook.filter.id.test("/app/src/theme.css.ts"));
+ assert.equal(hook.filter.code, ":not(:last-child)");
+ assert.deepEqual(hook.handler(":where(.a>:not(:last-child)){}"), {
+ code: ":where(.a > *):where(:not(:last-child)){}",
+ map: null,
+ });
+ assert.equal(hook.handler(".a:not(:last-child){}"), null);
+
+ const generators = tailwindVite().filter((plugin) =>
+ plugin.name.includes(":generate:"),
+ );
+ assert.ok(generators.length > 0);
+ for (const plugin of generators) {
+ assert.equal(
+ plugin.enforce,
+ "pre",
+ "Tailwind generates its CSS before normal plugins, so this one sees the utilities",
+ );
+ }
+ assert.match(
+ readText("../vite.config.ts"),
+ /plugins: \[react\(\), tailwindcss\(\), childSelectorOrder\(\),/,
+ );
+});
+
+type Complex = { compounds: string[]; combinators: string[] };
+
+function topLevel(selector: string, split: (char: string) => boolean): string[] {
+ const parts: string[] = [];
+ let depth = 0;
+ let current = "";
+ for (let i = 0; i < selector.length; i++) {
+ const char = selector[i];
+ if (char === "\\") {
+ current += char + (selector[i + 1] ?? "");
+ i++;
+ continue;
+ }
+ if (char === "(" || char === "[") depth++;
+ if (char === ")" || char === "]") depth--;
+ if (depth === 0 && split(char)) {
+ parts.push(current, char);
+ current = "";
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+}
+
+function complexSelectors(css: string): string[] {
+ const preludes =
+ css.replace(/\/\*[\s\S]*?\*\//g, "").match(/[^{};]+(?=\{)/g) ?? [];
+ return preludes
+ .map((prelude) => prelude.trim())
+ .filter((prelude) => prelude && !prelude.startsWith("@"))
+ .flatMap((prelude) =>
+ topLevel(prelude, (char) => char === ",")
+ .filter((part) => part !== ",")
+ .map((part) => part.trim()),
+ )
+ .filter((selector) => selector && !/^(?:from|to|[\d.]+%)$/.test(selector));
+}
+
+function parse(selector: string): Complex {
+ const tokens = topLevel(
+ selector.replace(/\s+/g, " ").replace(/\s*([>+~])\s*/g, "$1").trim(),
+ (char) => char === ">" || char === "+" || char === "~" || char === " ",
+ );
+ return {
+ compounds: tokens.filter((_, index) => index % 2 === 0),
+ combinators: tokens.filter((_, index) => index % 2 === 1),
+ };
+}
+
+function hasFeature(compound: string): boolean {
+ const outside = topLevel(compound, () => false)
+ .join("")
+ .replace(/\((?:[^()]|\([^()]*\))*\)/g, "()");
+ return /(?:^|[^:\\])[.#[&]|^[a-z]/i.test(outside);
+}
+
+function testsParentFirst(compound: string): boolean {
+ return /^:(?:where|is)\([^()]*>\s*\*\)/.test(compound);
+}
+
+function functionalArguments(compound: string): string[] {
+ const found: string[] = [];
+ const opener = /:(?:is|where|not|has)\(/g;
+ let match: RegExpExecArray | null;
+ while ((match = opener.exec(compound))) {
+ let depth = 1;
+ let i = match.index + match[0].length;
+ const start = i;
+ for (; i < compound.length && depth > 0; i++) {
+ if (compound[i] === "\\") {
+ i++;
+ continue;
+ }
+ if (compound[i] === "(") depth++;
+ if (compound[i] === ")") depth--;
+ }
+ found.push(
+ ...topLevel(compound.slice(start, i - 1), (char) => char === ",")
+ .filter((part) => part !== ",")
+ .map((part) => part.trim())
+ .filter(Boolean),
+ );
+ opener.lastIndex = i;
+ }
+ return found;
+}
+
+function siblingOnUnnamedElement(selector: string): boolean {
+ const { compounds, combinators } = parse(selector.replace(/^\s*[>+~]\s*/, ""));
+ for (let i = 0; i < combinators.length; i++) {
+ if (/[+~]/.test(combinators[i]) && !hasFeature(compounds[i + 1])) return true;
+ }
+ return compounds.some(
+ (compound) =>
+ !testsParentFirst(compound) &&
+ functionalArguments(compound).some(siblingOnUnnamedElement),
+ );
+}
+
+test("index.css never makes Chromium check a sibling or a child position on every element", () => {
+ const offenders: string[] = [];
+ for (const selector of complexSelectors(readSrc("index.css"))) {
+ const { compounds, combinators } = parse(selector);
+ const subject = compounds[compounds.length - 1];
+ if (hasFeature(subject) || testsParentFirst(subject)) continue;
+ const sibling = /[+~]/.test(combinators[combinators.length - 1] ?? "");
+ const structural =
+ combinators.length === 0 &&
+ /:(?:first|last|only)-child|:nth-|-of-type\b|[+~]/.test(subject);
+ if (sibling || structural) offenders.push(selector);
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ "with KaTeX's MathML on the page, Chromium's universal sibling set invalidates whole subtrees: one flagged parent turned every middle insert or remove into a restyle of everything below it, <body> included",
+ );
+});
+
+test("no rule tries a sibling combinator on an element it cannot name, in any position", () => {
+ for (const flagged of [
+ ".dark\n\t\tbody\n\t\t> :is([data-slot=\"dialog-content\"])[data-state=\"open\"]\n\t\t~ *\n\t\t:is([data-slot=\"select-content\"], .dropdown-surface)",
+ ".dark body > [data-radix-popper-content-wrapper]:has(> .menu[data-state=\"open\"]) ~ * :is([data-slot=\"popover-content\"])",
+ ".dark :is(body > .dialog[data-state=\"open\"] ~ *, body > .picker ~ *) :is([data-slot=\"popover-content\"]):not(.a)",
+ ".a + *",
+ ":where(.a ~ *)",
+ ]) {
+ assert.ok(siblingOnUnnamedElement(flagged), flagged);
+ }
+ for (const allowed of [
+ ".aui-branch-chevron-btn + .aui-branch-picker-state",
+ ":where(.aui-assistant-message-content > *):where(.h-0 + *)",
+ ".dark [data-dropdown-glow]:not(.sidebar-menu, .browser-menu)",
+ ".a:has(> .b + .c)",
+ ]) {
+ assert.ok(!siblingOnUnnamedElement(allowed), allowed);
+ }
+ for (const file of ["index.css", "features/hub/hub.css"]) {
+ assert.deepEqual(
+ complexSelectors(readSrc(file)).filter(siblingOnUnnamedElement),
+ [],
+ `${file}: a sibling combinator whose right side names nothing is tried on every ancestor of the subject, so the parents of <body>'s children get flagged and, with KaTeX's MathML on the page, every insert at the start of <body> (Radix focus guards, toasts) restyles the whole page`,
+ );
+ }
+});
+
+test("the message spacing, the badge follower and the branch count keep their rules in the parent-first form", () => {
+ const css = readSrc("index.css");
+ for (const selector of [
+ ":where(.aui-assistant-message-content > *):where(:not(:first-child)) {",
+ ":where(.aui-assistant-message-content > *):where(.h-0 + *) {",
+ ".aui-branch-chevron-btn,\n\t.aui-branch-chevron-btn + .aui-branch-picker-state {",
+ "\t.aui-branch-chevron-btn + .aui-branch-picker-state {\n",
+ ]) {
+ assert.ok(css.includes(selector), selector);
+ }
+ for (const removed of [
+ ".aui-branch-chevron-btn + *",
+ ".aui-branch-chevron-btn + :not(",
+ ":where(.aui-assistant-message-content > :not(:first-child))",
+ ":where(.aui-assistant-message-content > .h-0 + *)",
+ ]) {
+ assert.ok(!css.includes(removed), removed);
+ }
+ assert.match(
+ readSrc("components/assistant-ui/thread.tsx"),
+ /className="aui-branch-chevron-btn"[\s\S]{0,400}?<span className="aui-branch-picker-state[\s\S]{0,400}?className="aui-branch-chevron-btn"/,
+ "the count the rules target is the element between the two chevrons",
+ );
+});
diff --git a/studio/frontend/tests/code-block-containment-mode.test.ts b/studio/frontend/tests/code-block-containment-mode.test.ts
new file mode 100644
index 00000000000..3c56ee1221a
--- /dev/null
+++ b/studio/frontend/tests/code-block-containment-mode.test.ts
@@ -0,0 +1,82 @@
+// 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 {
+ CODE_BLOCK_CONTAINMENT_ATTRIBUTE,
+ CODE_BLOCK_CONTAINMENT_GLOBAL,
+ CODE_BLOCK_CONTAINMENT_ON,
+ FENCE_HEIGHT_PROPERTY,
+ SHIP_DEFAULT,
+ codeBlockContainmentMode,
+ installCodeBlockContainmentWatcher,
+ resolveCodeBlockContainmentMode,
+} from "../src/components/assistant-ui/code-block-containment-mode.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+test("an install that has never set the flag gets the ship default", () => {
+ assert.equal(SHIP_DEFAULT, "contain");
+ assert.equal(resolveCodeBlockContainmentMode(undefined, ""), SHIP_DEFAULT);
+ assert.equal(resolveCodeBlockContainmentMode(null, ""), SHIP_DEFAULT);
+});
+
+test("a mistyped flag turns it off rather than falling back to the default", () => {
+ for (const typo of ["conatin", "true", "yes", "on", "2", " contain"]) {
+ assert.equal(resolveCodeBlockContainmentMode(undefined, typo), "off", `build ${typo}`);
+ assert.equal(resolveCodeBlockContainmentMode(typo, ""), "off", `runtime ${typo}`);
+ }
+});
+
+test("the build flag and the runtime global work in both directions", () => {
+ assert.equal(resolveCodeBlockContainmentMode(undefined, "contain"), "contain");
+ assert.equal(resolveCodeBlockContainmentMode(undefined, "1"), "contain");
+ assert.equal(resolveCodeBlockContainmentMode(undefined, "off"), "off");
+ assert.equal(resolveCodeBlockContainmentMode(undefined, "0"), "off");
+ assert.equal(resolveCodeBlockContainmentMode(true, "off"), "contain");
+ assert.equal(resolveCodeBlockContainmentMode(false, "contain"), "off");
+ assert.equal(resolveCodeBlockContainmentMode("off", "contain"), "off");
+ assert.equal(resolveCodeBlockContainmentMode("contain", "off"), "contain");
+});
+
+test("the engine gate refuses containment where find-in-page cannot reach skipped content", () => {
+ assert.equal(codeBlockContainmentMode(undefined, "", true), "contain");
+ assert.equal(codeBlockContainmentMode(undefined, "", false), "off");
+ assert.equal(codeBlockContainmentMode(undefined, "contain", false), "off", "a build flag cannot see the engine");
+ assert.equal(codeBlockContainmentMode(true, "", false), "contain", "an explicit runtime override does");
+ assert.equal(codeBlockContainmentMode("contain", "", false), "contain");
+ assert.equal(codeBlockContainmentMode(false, "", true), "off");
+});
+
+test("assigning the override reapplies the mode and reads back what was written", () => {
+ const scope: Record<string, unknown> = {};
+ const calls: number[] = [];
+ assert.equal(installCodeBlockContainmentWatcher(scope, () => { calls.push(1); return "off"; }), true);
+ assert.equal(calls.length, 0);
+ scope[CODE_BLOCK_CONTAINMENT_GLOBAL] = "contain";
+ assert.equal(calls.length, 1);
+ assert.equal(scope[CODE_BLOCK_CONTAINMENT_GLOBAL], "contain");
+ scope[CODE_BLOCK_CONTAINMENT_GLOBAL] = false;
+ assert.equal(calls.length, 2);
+ assert.equal(scope[CODE_BLOCK_CONTAINMENT_GLOBAL], false);
+});
+
+test("a frozen scope cannot take the watcher and says so", () => {
+ const frozen = Object.freeze({}) as Record<string, unknown>;
+ assert.equal(installCodeBlockContainmentWatcher(frozen, () => "off"), false);
+});
+
+test("the names the stylesheet and the component read are the exported ones", () => {
+ assert.equal(CODE_BLOCK_CONTAINMENT_ATTRIBUTE, "data-code-block-containment");
+ assert.equal(CODE_BLOCK_CONTAINMENT_ON, "on");
+ assert.equal(FENCE_HEIGHT_PROPERTY, "--unsloth-fence-height");
+});
+
+test("the mode module is plain TypeScript", () => {
+ const source = readSrc("components/assistant-ui/code-block-containment-mode.ts");
+ assert.ok(!/<\/?[a-z]+[\s>]/i.test(source.replace(/^\s*[/*].*$/gm, "")), "no JSX");
+ assert.ok(!/\bfrom\s+["']react["']/.test(source), "no react import");
+ assert.ok(!source.includes("import.meta"), "no import.meta: the DOM half owns the build flag");
+});
diff --git a/studio/frontend/tests/code-block-containment-wiring.test.ts b/studio/frontend/tests/code-block-containment-wiring.test.ts
new file mode 100644
index 00000000000..0a3739d7716
--- /dev/null
+++ b/studio/frontend/tests/code-block-containment-wiring.test.ts
@@ -0,0 +1,147 @@
+// 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 {
+ CODE_BLOCK_CONTAINMENT_ATTRIBUTE,
+ CODE_BLOCK_CONTAINMENT_ON,
+ FENCE_HEIGHT_PROPERTY,
+} from "../src/components/assistant-ui/code-block-containment-mode.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const INDEX_CSS = readSrc("index.css");
+const DEFER = readSrc("components/assistant-ui/code-fence-defer.tsx");
+const MAIN = readSrc("main.tsx");
+const CONTAINMENT = readSrc("components/assistant-ui/code-block-containment.ts");
+const GLUE = readSrc("components/assistant-ui/progressive-messages.tsx");
+
+const GATE = `html[${CODE_BLOCK_CONTAINMENT_ATTRIBUTE}="${CODE_BLOCK_CONTAINMENT_ON}"]`;
+
+const layerBounds = (css: string, name: string): [number, number] => {
+ const open = css.indexOf(`@layer ${name} {`);
+ assert.ok(open >= 0, `PRECONDITION: @layer ${name} exists`);
+ let depth = 0;
+ for (let i = css.indexOf("{", open); i < css.length; i += 1) {
+ if (css[i] === "{") depth += 1;
+ else if (css[i] === "}") {
+ depth -= 1;
+ if (depth === 0) return [open, i];
+ }
+ }
+ throw new Error(`@layer ${name} never closes`);
+};
+
+const printBlocks = (css: string): string[] => {
+ const blocks: string[] = [];
+ for (let start = css.indexOf("@media print"); start >= 0; start = css.indexOf("@media print", start + 1)) {
+ let depth = 0;
+ for (let i = css.indexOf("{", start); i < css.length; i += 1) {
+ if (css[i] === "{") depth += 1;
+ else if (css[i] === "}") {
+ depth -= 1;
+ if (depth === 0) {
+ blocks.push(css.slice(start, i + 1));
+ break;
+ }
+ }
+ }
+ }
+ 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);
+ 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("}"));
+ 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");
+ assert.ok(rule.includes("content-visibility: auto;"), "the declaration under test");
+ assert.ok(rule.includes(`contain-intrinsic-size: auto var(${FENCE_HEIGHT_PROPERTY})`), "sized by the component's measurement");
+ assert.equal(rule.includes(":has("), false, "never :has()");
+ assert.equal(rule.includes("!important"), false, "the windowed box is not the element the visible override targets");
+});
+
+test("the wrapper keeps the visible override and the body keeps the DOM contract", () => {
+ assert.ok(
+ INDEX_CSS.includes('.aui-thread-root [data-streamdown="code-block"] {\n\t\tcontent-visibility: visible !important;'),
+ "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(!/contentVisibility:\s*"hidden"|display:\s*"none"/.test(body), "no line may be hidden from the engine");
+});
+
+test("the component writes the measured height before paint and only when it changes", () => {
+ assert.ok(DEFER.includes('import { FENCE_HEIGHT_PROPERTY } from "./code-block-containment-mode";'));
+ assert.match(DEFER, /const declared = `\$\{height\}px`;\s*if \(region\.style\.getPropertyValue\(FENCE_HEIGHT_PROPERTY\) !== declared\) \{\s*region\.style\.setProperty\(FENCE_HEIGHT_PROPERTY, declared\);/, "compared with the element's own declaration, so a box that remounts is written again");
+ assert.match(DEFER, /insets: Math\.max\(0, surface\.getBoundingClientRect\(\)\.height - lineCount \* lineHeight\)/, "the box holds the whole body, so its border, padding and horizontal scrollbar are part of the height a skipped box reproduces");
+ assert.match(DEFER, /const height =\s*Math\.round\(\s*\(lines\.current \* known\.lineHeight \+ known\.insets\) \* measureIntrinsicScale\(region\) \* 1000,\s*\) \/ 1000;/, "scaled where WebKit lays out contain-intrinsic-size lengths without the page zoom");
+ assert.match(DEFER, /contain:size;contain-intrinsic-size:0 1000px/);
+ assert.match(DEFER, /CSS\.supports\("contain-intrinsic-size", "0 1000px"\);\s*const measureIntrinsicScale = \(beside: HTMLElement\): number => \{\s*if \(!intrinsicSizeSupported\) return 1;/, "an engine without contain-intrinsic-size probes nothing, since its probe measures 0 and would be inserted again on every measure");
+ assert.match(DEFER, /window\.devicePixelRatio,\s*measureIntrinsicScale\(beside\),\s*\]\.join\("\|"\);/, "a page zoom WebKit hides from devicePixelRatio still re-probes the pitch");
+ const measure = DEFER.slice(DEFER.indexOf("measure.current = () => {"), DEFER.indexOf("useLayoutEffect(() => {", DEFER.indexOf("measure.current = () => {")));
+ assert.ok(measure.indexOf("setProperty(FENCE_HEIGHT_PROPERTY") < measure.indexOf("const reach ="), "written before the far-away early return, so a fence measured once always carries its height");
+});
+
+test("the measured height does not inherit, so a streamed line restyles only the box it sizes", () => {
+ assert.ok(new RegExp(`@property ${FENCE_HEIGHT_PROPERTY} \\{\\s*syntax: "<length>";\\s*inherits: false;\\s*initial-value: 0px;\\s*\\}`).test(INDEX_CSS), "registered, so a write restyles the box and not every line inside it");
+});
+
+test("the window measure never reads inside a body that may be skipped", () => {
+ const measure = DEFER.slice(DEFER.indexOf("measure.current = () => {"), DEFER.indexOf("useLayoutEffect(() => {", DEFER.indexOf("measure.current = () => {")));
+ assert.ok(!/(node|body|code\.current)\.getBoundingClientRect|rectDuringFrame\(body\)/.test(measure), "descendant rects are read by readFenceMetrics on registration and resize only");
+ assert.match(measure, /rectDuringFrame\(region\)/, "the box around the body is what the window is read against");
+ assert.match(measure, /\} else if \(metricsStale\.current && !skippedByContainment\(body\)\) \{/, "a resize re-reads a skipped fence's metrics once it is laid out again, instead of forcing its layout");
+ assert.match(DEFER, /const FAR_VIEWPORTS = OVERSCAN_VIEWPORTS \+ HYSTERESIS_VIEWPORTS \+ 1;/, "the far band is derived from the window's own margins");
+});
+
+test("the line pitch is measured from layout once per metric set, beside the box around the body", () => {
+ const metrics = DEFER.slice(DEFER.indexOf("const measureLinePitch = "), DEFER.indexOf("const readFenceGeometry = ("));
+ assert.match(metrics, /const pitch = measureLinePitch\(region\);/);
+ assert.match(metrics, /pitch > 0\s*\? pitch/, "the laid-out pitch wins over a computed line-height the engine truncates to 1/64 px per line");
+ assert.match(metrics, /const context = getComputedStyle\(parent\);/, "keyed on the wrapper, never on the body that may be skipped");
+ assert.equal(/getComputedStyle\((node|code)\b/.test(metrics), false);
+ assert.match(metrics, /beside\.before\(probe\);/, "the probe sits beside the box, outside the skipped subtree");
+ assert.match(metrics, /line\.className = LINE_CLASS;/, "built like the fence's own lines, inside a pre and a code");
+ assert.match(metrics, /\(lines\[PITCH_PROBE_LINES - 1\]\.getBoundingClientRect\(\)\.top - lines\[0\]\.getBoundingClientRect\(\)\.top\)\s*\/ \(PITCH_PROBE_LINES - 1\)/, "the mean advance across the probe's lines, so no padding or border of the probe can leak in and no single line's rounding is multiplied");
+ const probeLines = Number(/const PITCH_PROBE_LINES = (\d+);/.exec(DEFER)?.[1] ?? 0);
+ assert.ok(probeLines >= 32, "enough lines to average Firefox's per-line rounding");
+ assert.match(metrics, /getPropertyValue\("--custom-code-font-size"\)/, "a custom Code font size gets its own entry");
+ assert.match(metrics, /window\.devicePixelRatio/);
+ assert.match(metrics, /probe\.remove\(\);/);
+});
+
+test("a print clears the containment on every windowed fence, through the media query", () => {
+ const block = printBlocks(INDEX_CSS).find((candidate) => candidate.includes("[data-unsloth-fence-windowed]")) ?? "";
+ assert.notEqual(block, "", "a @media print block names the windowed box");
+ assert.ok(block.includes("content-visibility: visible !important"));
+ assert.ok(block.includes("contain-intrinsic-size: none !important"));
+});
+
+test("startup arms the attribute and watches the console override, after the maths one", () => {
+ assert.ok(MAIN.includes('} from "./components/assistant-ui/code-block-containment";'));
+ const math = MAIN.indexOf("watchMathBlockContainmentOverride();");
+ const apply = MAIN.indexOf("applyCodeBlockContainment();");
+ const watch = MAIN.indexOf("watchCodeBlockContainmentOverride();");
+ assert.ok(math >= 0 && apply > math && watch > apply, "in that order, before the first render");
+ assert.ok(apply < MAIN.indexOf("function renderApp()"), "before renderApp");
+ assert.ok(CONTAINMENT.includes('import { engineFindsSkippedContent } from "./math-block-containment";'), "the same engine gate as the maths blocks");
+ assert.ok(CONTAINMENT.includes("import.meta.env.VITE_UNSLOTH_CODE_BLOCK_CONTAINMENT"));
+ assert.ok(CONTAINMENT.includes("root.removeAttribute(CODE_BLOCK_CONTAINMENT_ATTRIBUTE)"), "off presents the same DOM as an install that never heard of it");
+});
+
+test("the widening anchor stops at a skipped subtree instead of forcing it to render", () => {
+ const pick = GLUE.slice(GLUE.indexOf("function pickAnchorRow("), GLUE.indexOf("function sampleAnchor("));
+ assert.match(pick, /anchor\.checkVisibility\(\{ contentVisibilityAuto: true \}\)/);
+ assert.ok(pick.indexOf("checkVisibility") < pick.indexOf("for (const child of anchor.children)"), "checked before any child rect is read");
+ const loop = pick.slice(pick.indexOf("for (const child of anchor.children)"));
+ assert.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");
+});
diff --git a/studio/frontend/tests/code-fence-body.test.ts b/studio/frontend/tests/code-fence-body.test.ts
index ddff6feb662..e70c39f824b 100644
--- a/studio/frontend/tests/code-fence-body.test.ts
+++ b/studio/frontend/tests/code-fence-body.test.ts
@@ -88,7 +88,7 @@ test("the fence branch no longer renders streamdown's Block", () => {
test("a streaming open fence is highlighted rather than shown plain", () => {
assert.ok(
- /if \(props\.isIncomplete\) \{\s*const openFence = markdownBlockFallback\(props\.content\);\s*if \(openFence\.fenced\) \{\s*return \(\s*<StreamingFenceBlock/m
+ /if \(props\.isIncomplete\) \{\s*const openFence = markdownBlockFallback\(props\.content\);\s*if \(openFence\.fenced\) \{\s*return highlightCode \? \(\s*<StreamingFenceBlock/m
.test(MARKDOWN_TEXT),
"an open fence must leave the bare Block route",
);
@@ -102,6 +102,26 @@ test("a streaming open fence is highlighted rather than shown plain", () => {
);
});
+test("a fence in the thinking box is coloured off the main thread, while it grows only on screen", () => {
+ assert.match(readSrc("components/assistant-ui/code-highlight-context.ts"), /export const CodeHighlightModeContext = createContext<CodeHighlightMode>\("all"\);/);
+ assert.match(MARKDOWN_TEXT, /\{highlightCode \|\| highlightMode === "settled" \? \(\s*<FenceBlock[\s\S]{0,300}isIncomplete=\{highlightCode \? props\.isIncomplete : false\}/, "a closed fence in a trace takes the deferred, worker-routed block, never the growing fence's tokenizer");
+ assert.equal((MARKDOWN_TEXT.match(/\) : \(\s*<PlainFenceBlock/g) ?? []).length, 2, "the closed fence routes keep a plain twin");
+ assert.match(MARKDOWN_TEXT, /<StreamingFenceBlock\s*language=\{openFence\.language\}\s*source=\{openFence\.text\}\s*\/>\s*\) : \(\s*<LiveThinkingFence/, "a growing thinking fence takes the viewport-gated worker route");
+ const live = MARKDOWN_TEXT.slice(MARKDOWN_TEXT.indexOf("function LiveThinkingFence("), MARKDOWN_TEXT.indexOf("function FenceBlock("));
+ assert.match(live, /useThinkingCodeColour\(host, source, languageToken, false\)/);
+ assert.equal(/useFenceTokens|code\.highlight|noteStreamingFence/.test(live), false, "no main-thread tokenizer for a growing thinking fence");
+ assert.match(live, /result === null \? \(\s*<PlainFenceShell language=\{languageToken\} source=\{source\} \/>/, "plain until the worker answers");
+ assert.match(MARKDOWN_TEXT, /const STREAMDOWN_PLAIN_CODE_PLUGINS = \{ math, mermaid \}/);
+ assert.match(MARKDOWN_TEXT, /plugins=\{\s*highlightCode \? STREAMDOWN_PLUGINS : STREAMDOWN_PLAIN_CODE_PLUGINS\s*\}/, "a fence nested in a list or a quote is plain too");
+ const start = MARKDOWN_TEXT.indexOf("function PlainFenceBlock(");
+ const 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, /data-unsloth-fence-deferred=\{plain \? undefined : "true"\}/, "a plain fence is never upgraded, so it does not carry the deferred marker");
+});
+
test("a completed fence on a non-``` form keeps the bounded renderer", () => {
// A completed tilde / four-backtick / indented fence used to fall to `Block` and remount every
// span; a stopped reply takes the same route.
@@ -236,7 +256,7 @@ test("a print colours the whole fence, and the window comes back afterwards", ()
"synchronously, because there is no next paint before the print snapshot",
);
assert.ok(
- /if \(printing\) \{\s*if \(current\.current === null\) return;/.test(DEFER),
+ /if \(printing \|\| findBarOpen\(\)\) \{\s*if \(current\.current === null && pinned\.current === null\) return;/.test(DEFER),
"and the measurement has to honour it",
);
});
@@ -285,8 +305,9 @@ test("a fence source is highlighted once per revision, not twice", () => {
);
});
-const TABLE_CONTROLS =
- '[data-streamdown="table-wrapper"] > div:first-child:not(:last-child)';
+const TABLE_CONTROLS = '[data-streamdown="table-wrapper"] > div';
+const POSITIONAL_ANCESTOR =
+ /:(?:first|last|only)-child[^{,]*?>\s*(?:\.relative|button)\b/;
const TABLE_BUTTON =
/height: calc\(var\(--spacing\) \* 8\);[\s\S]*border-radius: 10px;\s*color: var\(--color-chat-icon-fg\);/;
@@ -299,3 +320,19 @@ test("a table's toolbar buttons are drawn like the code block's", () => {
css.includes(`${TABLE_CONTROLS} > .relative {\n\t\tdisplay: flex;`),
);
});
+
+test("no positional pseudo-class sits above .relative or button in a selector", () => {
+ const css = readSrc("index.css");
+ const rules = css.match(/[^{}]+\{/g) ?? [];
+ const offenders = rules.filter((rule) => POSITIONAL_ANCESTOR.test(rule));
+ assert.deepEqual(
+ offenders,
+ [],
+ "a :first-child or :last-child above a subject keys the invalidation set on that subject, so inserting before #root (every modal's focus guard) restyled every .relative and button in the app",
+ );
+ assert.ok(
+ css.includes('[data-streamdown="table-wrapper"] > div:first-child:not(:last-child) {\n\t\tmargin-right:'),
+ "on the subject itself the same test only invalidates the controls",
+ );
+});
+
diff --git a/studio/frontend/tests/code-fence-mode.test.ts b/studio/frontend/tests/code-fence-mode.test.ts
index 9fff82774ac..f597a9db654 100644
--- a/studio/frontend/tests/code-fence-mode.test.ts
+++ b/studio/frontend/tests/code-fence-mode.test.ts
@@ -21,8 +21,24 @@ import { readSrc } from "./helpers/kit.ts";
*/
test("an install that has never set the flag gets the ship default", () => {
- assert.equal(SHIP_DEFAULT, "defer", "the ship default is deferral");
- assert.equal(resolveFenceMode(undefined, ""), "defer");
+ assert.equal(SHIP_DEFAULT, "window", "the ship default is the windowed deferral");
+ assert.equal(resolveFenceMode(undefined, ""), "window");
+});
+
+test("the plain deferral stays reachable as the ablation arm", () => {
+ assert.equal(resolveFenceMode(undefined, "defer"), "defer");
+ assert.equal(resolveFenceMode("defer", ""), "defer");
+ assert.equal(resolveFenceMode(true, ""), "defer");
+ assert.equal(resolveFenceMode(undefined, "window"), "window");
+ assert.equal(resolveFenceMode("window", ""), "window");
+});
+
+test("every answer fence takes its line window from the mode, streaming or not", () => {
+ assert.deepEqual(
+ readSrc("components/assistant-ui/markdown-text.tsx").match(/windowing=\{[^}]*\}/g),
+ ['windowing={fenceMode() === "window"}', 'windowing={fenceMode() === "window"}', 'windowing={mode === "window"}'],
+ "a streaming fence that windowed whatever the mode kept \"off\" from restoring the old rendering",
+ );
});
test("the build flag overrides the default in both directions", () => {
diff --git a/studio/frontend/tests/code-fence-print.test.ts b/studio/frontend/tests/code-fence-print.test.ts
new file mode 100644
index 00000000000..643c20925a5
--- /dev/null
+++ b/studio/frontend/tests/code-fence-print.test.ts
@@ -0,0 +1,87 @@
+// 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 { planPrintTokenization } from "../src/components/assistant-ui/code-fence-print.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+test("the smallest fences are planned first and the plan stops at the first one that does not fit", () => {
+ assert.deepEqual(planPrintTokenization([42_000, 45_000, 300_000], 200_000), [0, 1]);
+ assert.deepEqual(planPrintTokenization([150_000, 150_000], 200_000), [0]);
+ assert.deepEqual(planPrintTokenization([5, 1, 3], 4), [1, 2]);
+ assert.deepEqual(planPrintTokenization([], 200_000), []);
+ assert.deepEqual(planPrintTokenization([300_000], 200_000), []);
+ assert.deepEqual(planPrintTokenization([100, 100], 200), [0, 1]);
+});
+
+test("the plan module stays plain TypeScript the test runner can execute", () => {
+ const source = readSrc("components/assistant-ui/code-fence-print.ts");
+ assert.equal(/<\/?[a-z]+[\s>]/i.test(source), false);
+ assert.equal(source.includes("from \"react\""), false);
+});
+
+test("a print tokenizes what the worker still owes, synchronously and within a budget", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ assert.ok(defer.includes("const PRINT_TOKENIZE_CHARS = 10 * MAX_HIGHLIGHT_CHARS;"));
+ assert.ok(defer.includes("export const awaitWorker = ("));
+ assert.ok(defer.includes('import { planPrintTokenization } from "./code-fence-print";'));
+ const printing = defer.slice(defer.indexOf("const setPrinting = "), defer.indexOf("const scheduleRemeasure = "));
+ assert.ok(printing.indexOf("if (value) tokenizeForPrint();") < printing.indexOf("flushSync(remeasureWindows);"));
+ const tokenize = defer.slice(defer.indexOf("const tokenizeForPrint = "), defer.indexOf("const remeasureWindows = "));
+ assert.match(tokenize, /flushSync\(\(\) => \{\s*for \(const index of order\) pending\[index\]\.tokenizeNow\(\);/);
+ assert.ok(defer.includes("return overCap && !printing && !findBarOpen() ? EMPTY_WINDOW : NO_WINDOW;"));
+ assert.ok(defer.includes("const EMPTY_WINDOW = { window: EMPTY_LINE_WINDOW, pins: null, measured: false } as const;"));
+ const markdown = readSrc("components/assistant-ui/markdown-text.tsx");
+ const 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");
+ const probes = [...hook.matchAll(/highlight\("", /g)];
+ assert.ok(probes.length >= 2);
+ for (const probe of probes) {
+ assert.ok(hook.startsWith("() => {})", (probe.index ?? 0) + probe[0].length));
+ }
+});
+
+test("a drag freezes the line window, and a selection pins only the lines holding its boundaries", () => {
+ const 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;");
+ 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;/);
+ assert.match(defer, /while \(line !== null && line\.parentNode !== codeNode\) line = line\.parentNode;/, "a boundary maps to the line span under code");
+ assert.match(defer, /windowed=\{lineRendered\(lineWindow, pins, index\)\}/);
+ assert.equal(defer.includes("heldDuringFrame"), false);
+ assert.equal(defer.includes("intersectsNode"), false);
+ assert.ok(defer.includes("selection.rangeCount > 0 && !selection.isCollapsed"));
+ assert.ok(defer.includes('if (event.pointerType === "touch" || event.button !== 0) return;'));
+ for (const type of ["pointerdown", "pointerup", "pointercancel", "dragend", "drop", "pointermove", "blur", "selectionchange"]) {
+ assert.ok(defer.includes(`addEventListener("${type}",`), `watches ${type}`);
+ assert.ok(defer.includes(`removeEventListener("${type}",`), `unwatches ${type}`);
+ }
+ assert.match(defer, /window\.addEventListener\("dragend", releasePointer,/, "WebKit ends a text drag with dragend and never sends pointerup or pointercancel");
+ assert.match(defer, /window\.addEventListener\("drop", releasePointer,/);
+ assert.match(defer, /const onPointerMove = \(event: PointerEvent\): void => \{\s*if \(pointerHeld !== null && event\.buttons === 0\) releasePointer\(\);/, "and a move with no button down ends any hold an engine forgot to release");
+ assert.match(defer, /const onSelectionChange = \(\): void => \{\s*if \(heldLastFrame\) scheduleRemeasure\(\);/);
+});
+
+test("the scroller walk is memoized for one synchronous stack and nowhere longer", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ const predicate = defer.slice(defer.indexOf("const isScrollable"), defer.indexOf("const scrollerOf"));
+ assert.ok(predicate.includes("scrollableNow.get(el)"));
+ assert.ok(predicate.includes("queueMicrotask(forgetScrollable)"));
+ for (const token of ['"auto"', '"scroll"', '"overlay"', "scrollHeight > el.clientHeight"]) {
+ assert.ok(predicate.includes(token), token);
+ }
+ assert.match(defer, /region\.style\.setProperty\(FENCE_HEIGHT_PROPERTY, declared\);\s*forgetScrollable\(\);/);
+ assert.match(defer, /const remeasureWindows = \(\): void => \{\s*windowFrame = 0;\s*forgetScrollable\(\);/);
+ assert.equal(defer.includes("requestAnimationFrame(forgetScrollable"), false);
+ assert.equal(defer.includes("frameScrollable"), false);
+ assert.equal(defer.includes("scrollableDuringFrame"), false);
+ assert.ok(defer.includes("!isScrollable(known.scroller)"));
+});
diff --git a/studio/frontend/tests/code-fence-window-transition.test.ts b/studio/frontend/tests/code-fence-window-transition.test.ts
new file mode 100644
index 00000000000..a6d7cdac5c4
--- /dev/null
+++ b/studio/frontend/tests/code-fence-window-transition.test.ts
@@ -0,0 +1,44 @@
+// 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";
+
+const DEFER = readFileSync(
+ new URL("../src/components/assistant-ui/code-fence-defer.tsx", import.meta.url),
+ "utf8",
+);
+
+test("a finished fence moves its line window in a transition, a streaming one does not", () => {
+ const measure = DEFER.slice(
+ DEFER.indexOf("measure.current = () => {"),
+ DEFER.indexOf("useLayoutEffect(() => {", DEFER.indexOf("measure.current = () => {")),
+ );
+ assert.match(
+ measure,
+ /const shifting =\s*deferShifts && current\.current !== null && frameRects !== null && !resized;/,
+ "only a window that already exists, of a finished fence, moved in a frame where the viewport kept its size",
+ );
+ assert.match(
+ measure,
+ /const size = `\$\{bounds \? bounds\.width : window\.innerWidth\}x\$\{viewportHeight\}`;\s*if \(size !== viewportSize\.current\) resizedAt\.current = performance\.now\(\);\s*viewportSize\.current = size;\s*const resized = performance\.now\(\) - resizedAt\.current < RESIZE_SETTLE_MS;/,
+ "a resize re-wraps every line, so its steps and the frames right after stay synchronous",
+ );
+ assert.match(
+ measure,
+ /if \(shifting\) startTransition\(\(\) => setState\(update\)\);\s*else setState\(update\);/,
+ "the first measure, print, find and streaming fences keep the synchronous update",
+ );
+ assert.equal(
+ (measure.match(/startTransition\(/g) ?? []).length,
+ 1,
+ "the window that hides every line for print or find is never deferred",
+ );
+ const body = DEFER.slice(DEFER.indexOf("export const FenceBody = memo("));
+ assert.match(
+ body,
+ /useLineWindow\(\s*code,\s*surface,\s*wrapper,\s*frame,\s*tokens\?\.length \?\? 0,\s*windowing,\s*!isIncomplete,\s*\)/,
+ "a fence still streaming keeps its window in step with the lines being appended",
+ );
+});
diff --git a/studio/frontend/tests/code-fence-window.test.ts b/studio/frontend/tests/code-fence-window.test.ts
index 644af2e671a..05f22428440 100644
--- a/studio/frontend/tests/code-fence-window.test.ts
+++ b/studio/frontend/tests/code-fence-window.test.ts
@@ -5,8 +5,12 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
+ EMPTY_LINE_WINDOW,
HYSTERESIS_VIEWPORTS,
lineIsWindowed,
+ lineRendered,
+ pinBoundaryLines,
+ samePins,
OVERSCAN_VIEWPORTS,
selectLineWindow,
WINDOW_CAP_LINES,
@@ -145,6 +149,17 @@ test("geometry that cannot be trusted degrades to highlighting everything", () =
}
});
+test("the empty window highlights no line and never pins a measurement", () => {
+ assert.equal(lineIsWindowed(EMPTY_LINE_WINDOW, 0), false);
+ assert.equal(lineIsWindowed(EMPTY_LINE_WINDOW, 19_999), false);
+ const measured = selectLineWindow(
+ geometry({ viewportTop: 10_000, previous: EMPTY_LINE_WINDOW }),
+ );
+ assert.ok(measured);
+ assert.notEqual(measured, EMPTY_LINE_WINDOW, "the first measurement replaces it");
+ assert.ok(measured.first <= 500 && measured.last >= 529, "with the visible lines");
+});
+
test("a null window highlights every line", () => {
assert.equal(lineIsWindowed(null, 0), true);
assert.equal(lineIsWindowed(null, 19_999), true);
@@ -170,3 +185,22 @@ test("the window module is plain TypeScript", () => {
"and no react import: this module has to load under --experimental-strip-types",
);
});
+
+test("a selection boundary line keeps its rendering while the window moves on", () => {
+ const before = { first: 0, last: 239 };
+ const after = { first: 300, last: 539 };
+ const pins = pinBoundaryLines([8, 8, 450], before, null);
+ assert.deepEqual(pins, [{ index: 8, windowed: true }, { index: 450, windowed: false }], "boundaries are deduplicated and keep what they were showing");
+ assert.equal(lineRendered(after, pins, 8), true, "the selected word's line stays coloured outside the new window");
+ assert.equal(lineRendered(after, pins, 450), false, "and a plain boundary stays plain inside it, so its text node survives");
+ assert.equal(lineRendered(after, pins, 400), true, "every other line follows the window");
+ assert.equal(lineRendered(after, pins, 20), false);
+ const kept = pinBoundaryLines([8], after, pins);
+ assert.deepEqual(kept, [{ index: 8, windowed: true }], "a pin carries over while its boundary stays");
+ assert.equal(pinBoundaryLines([], after, pins), null, "a cleared selection drops every pin");
+ assert.equal(samePins(kept, [{ index: 8, windowed: true }]), true);
+ assert.equal(samePins(kept, [{ index: 8, windowed: false }]), false);
+ assert.equal(samePins(null, null), true);
+ assert.equal(samePins(kept, null), false);
+});
+
diff --git a/studio/frontend/tests/code-plugin-fork.test.ts b/studio/frontend/tests/code-plugin-fork.test.ts
new file mode 100644
index 00000000000..e0915b3fe8e
--- /dev/null
+++ b/studio/frontend/tests/code-plugin-fork.test.ts
@@ -0,0 +1,72 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+import type { HighlightOptions, HighlightResult, ThemeInput } from "@streamdown/code";
+
+register("./shiki-tokenization-resolver.mjs", import.meta.url);
+const { createCodePlugin } = await import("../src/components/assistant-ui/code-plugin.ts");
+const { tokenized } = await import("./shiki-tokenization-counter.mts");
+
+const THEMES: [ThemeInput, ThemeInput] = ["github-light", "github-dark"];
+const LANGUAGE = "typescript" as HighlightOptions["language"];
+const options = (code: string): HighlightOptions => ({ code, language: LANGUAGE, themes: THEMES });
+type Plugin = ReturnType<typeof createCodePlugin>;
+
+const exactly = (plugin: Plugin, code: string): Promise<HighlightResult> =>
+ new Promise((resolve) => {
+ const now = plugin.highlightExact(options(code), resolve);
+ if (now) resolve(now);
+ });
+
+const lines = (name: string, count: number) =>
+ Array.from({ length: count }, (_, i) => `const ${name}${i} = ${i} * 2;`).join("\n") + "\n";
+
+const a = lines("a", 120);
+const b = a + lines("b", 6);
+const c = b + lines("c", 6);
+
+test("settled fences that extend one another each get exact tokens once, and the shorter keeps its own entry", async () => {
+ const reference = createCodePlugin({ themes: THEMES });
+ const expected = [await exactly(reference, a), await exactly(reference, b), await exactly(reference, c)];
+ const plugin = createCodePlugin({ themes: THEMES });
+ await exactly(plugin, "const warm = 1;\n");
+ assert.ok(a.length > 2000, "the family is past the size where the throttled path would answer");
+ tokenized.characters = 0;
+ const warmPass = [a, b, c].map((code) => plugin.highlightExact(options(code)));
+ const effectPass = [a, b, c].map((code) => plugin.highlightExact(options(code)));
+ for (let i = 0; i < 3; i += 1) {
+ assert.ok(warmPass[i], `fence ${i} answered synchronously`);
+ assert.deepEqual(warmPass[i]!.tokens, expected[i].tokens, `fence ${i} has every line coloured`);
+ assert.equal(effectPass[i], warmPass[i], `fence ${i} is served from its own entry on the second pass`);
+ }
+ assert.ok(
+ tokenized.characters <= c.length + 64,
+ `${tokenized.characters} characters were tokenized for a family whose longest fence is ${c.length}; a sibling must reuse the committed lines instead of re-tokenizing the fence it extends`,
+ );
+});
+
+test("an exact request leaves a streaming sibling's queued refresh in place", async () => {
+ const reference = createCodePlugin({ themes: THEMES });
+ const expected = await exactly(reference, b);
+ const plugin = createCodePlugin({ themes: THEMES });
+ await exactly(plugin, a);
+ // Refresh slices can land partial on a slow runner; the same callback fires again until complete.
+ const refined = new Promise<HighlightResult>((resolve) => {
+ const approximate = plugin.highlight(options(b), (result) => {
+ if (JSON.stringify(result.tokens) === JSON.stringify(expected.tokens)) resolve(result);
+ });
+ assert.ok(approximate, "the growing fence is answered with the throttled approximation");
+ assert.notDeepEqual(approximate!.tokens, expected.tokens);
+ });
+ const sibling = plugin.highlightExact(options(a + lines("z", 3)));
+ assert.ok(sibling);
+ const late = await Promise.race([
+ refined,
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), 2000)),
+ ]);
+ assert.ok(late, "the streaming fence still receives its refresh");
+ assert.deepEqual(late!.tokens, expected.tokens);
+});
diff --git a/studio/frontend/tests/code-plugin-incremental.test.ts b/studio/frontend/tests/code-plugin-incremental.test.ts
index 998ea4e9038..91224cad5d5 100644
--- a/studio/frontend/tests/code-plugin-incremental.test.ts
+++ b/studio/frontend/tests/code-plugin-incremental.test.ts
@@ -715,3 +715,41 @@ test("a throttled multiline tail matches the previous plugin", async () => {
...expectedTail,
]);
});
+
+test("cover reports what the cache leaves untokenized, and never tokenizes", async () => {
+ const plugin = createCodePlugin({ themes: THEMES });
+ const language = "python" as HighlightOptions["language"];
+ const streamedTo = PYTHON.lastIndexOf("\n", PYTHON.length - 2) + 1;
+ await highlightOnce(plugin, { code: PYTHON.slice(0, streamedTo), language, themes: THEMES });
+ const settled = `${PYTHON}value = 1`;
+ const cover = plugin.cover({ code: settled, language, themes: THEMES });
+ assert.equal(cover.uncovered, settled.length - streamedTo, "only the text past the last line the stream committed");
+ const full = await reference(settled, "python");
+ const covered = PYTHON.slice(0, streamedTo).split("\n").length - 1;
+ assert.deepEqual(cover.result?.tokens.slice(0, covered), full.tokens.slice(0, covered), "the committed lines carry their real colours");
+ assert.deepEqual(
+ cover.result?.tokens.slice(covered).map((line) => line.map((token) => token.content).join("")),
+ settled.slice(streamedTo).split("\n"),
+ "the rest is every remaining line, plain",
+ );
+ assert.equal(cover.result?.tokens.length, full.tokens.length, "the same lines as the finished fence, so its body keeps its shape");
+ assert.equal(plugin.cached({ code: settled, language, themes: THEMES }), null, "asking created no cache entry");
+ const exact = await highlightOnce(plugin, { code: settled, language, themes: THEMES });
+ assert.deepEqual(plugin.cover({ code: settled, language, themes: THEMES }), { uncovered: 0, result: exact });
+ const other = "def unrelated():\n return 2\n";
+ assert.deepEqual(plugin.cover({ code: other, language, themes: THEMES }), { uncovered: other.length, result: null });
+ assert.deepEqual(
+ plugin.cover({ code: settled, language: "typescript" as HighlightOptions["language"], themes: THEMES }),
+ { uncovered: settled.length, result: null },
+ "another grammar's tokens are never offered",
+ );
+});
+
+test("cover never offers a worker's seeded result as a prefix to resume from", async () => {
+ const plugin = createCodePlugin({ themes: THEMES });
+ const language = "python" as HighlightOptions["language"];
+ const seeded = await reference(PYTHON, "python");
+ plugin.seed({ code: PYTHON, language, themes: THEMES }, seeded as unknown as HighlightResult);
+ const grown = `${PYTHON}value = 1\n`;
+ assert.deepEqual(plugin.cover({ code: grown, language, themes: THEMES }), { uncovered: grown.length, result: null });
+});
diff --git a/studio/frontend/tests/code-plugin-javascriptcore.test.ts b/studio/frontend/tests/code-plugin-javascriptcore.test.ts
new file mode 100644
index 00000000000..611900430f7
--- /dev/null
+++ b/studio/frontend/tests/code-plugin-javascriptcore.test.ts
@@ -0,0 +1,141 @@
+// 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 type {
+ HighlightOptions,
+ HighlightResult,
+ ThemeInput,
+} from "@streamdown/code";
+import { createHighlighter } from "shiki";
+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+
+const WEBKIT =
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";
+Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent: WEBKIT },
+ configurable: true,
+});
+const { createCodePlugin, TOKENIZE_LIMITS } = await import(
+ "../src/components/assistant-ui/code-plugin.ts"
+);
+
+const THEMES: [ThemeInput, ThemeInput] = ["github-light", "github-dark"];
+
+const SAMPLES: Record<string, string> = {
+ html: `<!doctype html>
+<html lang="en">
+<head>
+ <style>
+ canvas { display: block; margin: 0 auto; background: #70c5ce; }
+ .score::after { content: "pts"; color: rgb(255 255 255 / 0.8); }
+ </style>
+</head>
+<body>
+ <canvas id="game" width="400" height="600"></canvas>
+ <script>
+ const canvas = document.getElementById("game");
+ const ctx = canvas.getContext("2d");
+ let bird = { x: 80, y: 300, velocity: 0 };
+ const pipes = [];
+ function tick(now) {
+ bird.velocity = Math.min(bird.velocity + 0.5, 12);
+ bird.y += bird.velocity;
+ if (pipes.length === 0 || pipes.at(-1).x < 200) pipes.push({ x: 400, gap: 120 + Math.random() * 200 });
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ requestAnimationFrame(tick);
+ }
+ document.addEventListener("keydown", (event) => { if (event.code === "Space") bird.velocity = -8; });
+ requestAnimationFrame(tick);
+ </script>
+</body>
+</html>
+`,
+ typescript: `type Pipe = { x: number; gap: number };
+export class Game<T extends { score: number }> {
+ #pipes: Pipe[] = [];
+ constructor(private readonly state: T) {}
+ async load(url: string): Promise<Map<string, number>> {
+ const response = await fetch(\`\${url}?v=\${Date.now()}\`);
+ return new Map(Object.entries(await response.json()) as [string, number][]);
+ }
+ get best(): number { return this.#pipes.reduce((max, { gap }) => (gap > max ? gap : max), 0); }
+}
+const re = /(?<=\\$)\\d+(?:\\.\\d{2})?/gu;
+`,
+ python: `import re
+from dataclasses import dataclass, field
+
+PRICE = re.compile(r"(?<=\\$)\\d+(?:\\.\\d{2})?")
+
+@dataclass
+class Bird:
+ x: float = 80.0
+ y: float = 300.0
+ velocity: float = field(default=0.0)
+
+ def flap(self, *, strength: float = 8.0) -> None:
+ """Jump, but never faster than the cap."""
+ self.velocity = max(-strength, self.velocity - strength)
+
+print(f"{Bird()!r} {PRICE.findall('$12.50 and $3')}")
+`,
+ css: `@layer base {
+ :root { --sky: oklch(78% 0.08 220); }
+ .pipe:is(.top, .bottom):not([hidden]) > .cap::before {
+ inset: 0 auto auto 0;
+ transform: translate3d(calc(var(--x, 0) * 1px), 0, 0) rotate(-2deg);
+ }
+ @media (prefers-reduced-motion: reduce) { * { animation: none !important; } }
+}
+`,
+ json: `{"bird": {"x": 80, "y": 300, "velocity": -8.5}, "pipes": [{"x": 400, "gap": 160}], "scores": [12, 7, 33], "name": "flappy \\"bird\\"", "ok": true, "none": null}
+`,
+ shellscript: `#!/usr/bin/env bash
+set -euo pipefail
+for file in "\${@:-src/*.ts}"; do
+ if [[ "$file" =~ \\.test\\.ts$ ]]; then echo "skip \${file##*/}"; continue; fi
+ sed -E 's/(foo|bar)+/baz/g' "$file" | tee "\${file%.ts}.out" >/dev/null
+done
+cat <<EOF
+done: $(date +%s)
+EOF
+`,
+};
+
+async function reference(code: string, language: string) {
+ const highlighter = await createHighlighter({
+ themes: THEMES,
+ langs: [language],
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
+ });
+ return highlighter.codeToTokens(code, {
+ lang: language as never,
+ themes: { light: "github-light", dark: "github-dark" },
+ ...TOKENIZE_LIMITS,
+ });
+}
+
+function highlightOnce(
+ plugin: ReturnType<typeof createCodePlugin>,
+ options: HighlightOptions,
+): Promise<HighlightResult> {
+ return new Promise((resolve) => {
+ const immediate = plugin.highlightExact(options, resolve);
+ if (immediate) resolve(immediate);
+ });
+}
+
+for (const [language, code] of Object.entries(SAMPLES)) {
+ test(`under JavaScriptCore's patterns, ${language} tokenizes exactly as with the engine's own`, async () => {
+ const plugin = createCodePlugin({ themes: THEMES });
+ const result = await highlightOnce(plugin, {
+ code,
+ language: language as HighlightOptions["language"],
+ themes: THEMES,
+ });
+ const full = await reference(code, language);
+ assert.deepEqual(result.tokens, full.tokens);
+ });
+}
diff --git a/studio/frontend/tests/code-plugin-refresh-slices.test.ts b/studio/frontend/tests/code-plugin-refresh-slices.test.ts
new file mode 100644
index 00000000000..1f994292603
--- /dev/null
+++ b/studio/frontend/tests/code-plugin-refresh-slices.test.ts
@@ -0,0 +1,83 @@
+// 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 type {
+ HighlightOptions,
+ HighlightResult,
+ ThemeInput,
+} from "@streamdown/code";
+import { createHighlighter } from "shiki";
+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+
+import {
+ createCodePlugin,
+ MIN_INCREMENTAL_CHARS,
+ TOKENIZE_LIMITS,
+} from "../src/components/assistant-ui/code-plugin.ts";
+
+const THEMES: [ThemeInput, ThemeInput] = ["github-light", "github-dark"];
+const LANGUAGE = "typescript" as HighlightOptions["language"];
+
+const SOURCE = `${Array.from(
+ { length: 260 },
+ (_, index) =>
+ `export const value_${index} = { id: ${index}, label: "row ${index}" };`,
+).join("\n")}\n`;
+
+const text = (result: HighlightResult): string =>
+ result.tokens.map((line) => line.map((token) => token.content).join("")).join("\n");
+
+test("a refresh that falls behind the stream is tokenized in slices and still settles exact", async () => {
+ const reference = await createHighlighter({
+ themes: THEMES,
+ langs: ["typescript"],
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
+ });
+ const expected = reference.codeToTokens(SOURCE, {
+ lang: "typescript",
+ themes: { light: "github-light", dark: "github-dark" },
+ ...TOKENIZE_LIMITS,
+ }).tokens;
+ const plugin = createCodePlugin({ themes: THEMES });
+ const prefix = SOURCE.slice(0, SOURCE.indexOf("\n", MIN_INCREMENTAL_CHARS + 500) + 1);
+ await new Promise<void>((resolve) => {
+ const immediate = plugin.highlight(
+ { code: prefix, language: LANGUAGE, themes: THEMES },
+ () => resolve(),
+ );
+ if (immediate) resolve();
+ });
+
+ const realNow = performance.now.bind(performance);
+ const base = realNow();
+ let ticks = 0;
+ performance.now = () => base + (ticks += 3);
+ const deliveries: HighlightResult[] = [];
+ try {
+ const settled = await new Promise<HighlightResult>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("the sliced refresh never settled")), 10_000);
+ const immediate = plugin.highlight(
+ { code: SOURCE, language: LANGUAGE, themes: THEMES },
+ (result) => {
+ deliveries.push(result);
+ if (result.tokens.length === expected.length && JSON.stringify(result.tokens) === JSON.stringify(expected)) {
+ clearTimeout(timer);
+ resolve(result);
+ }
+ },
+ );
+ assert.ok(immediate, "a throttled frame still answers at once");
+ assert.equal(text(immediate), SOURCE, "the throttled frame renders every character");
+ });
+ assert.deepEqual(settled.tokens, expected);
+ } finally {
+ performance.now = realNow;
+ }
+
+ assert.ok(deliveries.length > 2, `the refresh ran as ${deliveries.length} slice(s), not several`);
+ for (const result of deliveries) {
+ assert.equal(text(result), SOURCE, "every slice renders every character, coloured or plain");
+ }
+});
diff --git a/studio/frontend/tests/code-plugin-seed.test.ts b/studio/frontend/tests/code-plugin-seed.test.ts
new file mode 100644
index 00000000000..8bad97e1569
--- /dev/null
+++ b/studio/frontend/tests/code-plugin-seed.test.ts
@@ -0,0 +1,52 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+import type { HighlightOptions, HighlightResult, ThemeInput } from "@streamdown/code";
+
+register("./shiki-tokenization-resolver.mjs", import.meta.url);
+const { createCodePlugin } = await import("../src/components/assistant-ui/code-plugin.ts");
+
+const THEMES: [ThemeInput, ThemeInput] = ["github-light", "github-dark"];
+const LANGUAGE = "typescript" as HighlightOptions["language"];
+const options = (code: string): HighlightOptions => ({ code, language: LANGUAGE, themes: THEMES });
+
+const highlighted = (plugin: ReturnType<typeof createCodePlugin>, code: string): Promise<HighlightResult> =>
+ new Promise((resolve) => {
+ const now = plugin.highlight(options(code), resolve);
+ if (now) resolve(now);
+ });
+
+const SEEDED = "const a = 1;\nexport function f() {\n return `x${a}`;\n}";
+
+test("the exact path never answers with the throttled approximation of a fence that extends another", async () => {
+ const plugin = createCodePlugin({ themes: THEMES });
+ const reference = createCodePlugin({ themes: THEMES });
+ const base = Array.from({ length: 120 }, (_, i) => `const value${i} = ${i} * 2;`).join("\n") + "\n";
+ assert.ok(base.length > 2000);
+ const longer = `${base}export function tail() {\n return value1 + value2;\n}\n`;
+ await highlighted(plugin, base);
+ const approximate = plugin.highlight(options(longer), () => {});
+ const exact = plugin.highlightExact(options(longer));
+ const expected = await highlighted(reference, longer);
+ assert.ok(approximate && exact);
+ assert.notDeepEqual(approximate.tokens, expected.tokens, "the ordinary path still throttles a large growing fence");
+ assert.deepEqual(exact.tokens, expected.tokens, "the exact path tokenizes the whole body");
+ assert.equal(plugin.cached(options(longer)), exact, "and caches it as the fence's exact result");
+});
+
+test("a seeded result is served for its exact source only, never as a prefix for a longer one", async () => {
+ const fresh = createCodePlugin({ themes: THEMES });
+ const seeded = createCodePlugin({ themes: THEMES });
+ const result = await highlighted(fresh, SEEDED);
+ const extended = `${SEEDED}\nconst more = a + 1;\n`;
+ const expected = await highlighted(fresh, extended);
+ seeded.seed(options(SEEDED), result);
+ assert.equal(seeded.cached(options(SEEDED)), result, "an exact hit hands back the seeded object");
+ assert.equal(seeded.highlight(options(SEEDED), () => {}), result, "and the ordinary highlight path too");
+ const continued = await highlighted(seeded, extended);
+ assert.deepEqual(continued.tokens, expected.tokens, "a longer body is tokenized afresh, not continued from the seeded lines");
+ assert.equal(continued.tokens.length, expected.tokens.length);
+});
diff --git a/studio/frontend/tests/collapse-scroll-lock.test.ts b/studio/frontend/tests/collapse-scroll-lock.test.ts
new file mode 100644
index 00000000000..f6370a4216c
--- /dev/null
+++ b/studio/frontend/tests/collapse-scroll-lock.test.ts
@@ -0,0 +1,144 @@
+// 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, { mock } from "node:test";
+
+import {
+ USER_DISCRETE_EVENTS,
+ USER_SCROLL_EVENTS,
+ lockCollapseScroll,
+} from "../src/hooks/collapse-scroll-lock.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+class FakeContainer extends EventTarget {
+ scrollTop = 1000;
+ writes: Array<{ top: number; behavior: string }> = [];
+
+ scrollTo(options: { top: number; behavior: "instant" }): void {
+ this.writes.push(options);
+ this.scrollTop = options.top;
+ this.dispatchEvent(new Event("scroll"));
+ }
+
+ layoutShift(delta: number): void {
+ this.scrollTop += delta;
+ this.dispatchEvent(new Event("scroll"));
+ }
+
+ gesture(type: string): void {
+ this.dispatchEvent(new Event(type));
+ }
+}
+
+test("a layout-driven scroll inside the window is undone with one instant write", () => {
+ const container = new FakeContainer();
+ const release = lockCollapseScroll(container, 250);
+ container.layoutShift(-300);
+ assert.deepEqual(container.writes, [{ top: 1000, behavior: "instant" }]);
+ assert.equal(container.scrollTop, 1000);
+ release();
+});
+
+test("the write's own scroll event does not write again", () => {
+ const container = new FakeContainer();
+ const release = lockCollapseScroll(container, 250);
+ container.layoutShift(120);
+ container.layoutShift(-45);
+ assert.equal(container.writes.length, 2);
+ assert.equal(container.scrollTop, 1000);
+ release();
+});
+
+for (const type of USER_DISCRETE_EVENTS) {
+ test(`a ${type} anywhere in the document releases the hold`, () => {
+ const container = new FakeContainer();
+ const page = new EventTarget();
+ lockCollapseScroll(container, 250, page);
+ page.dispatchEvent(new Event(type));
+ container.layoutShift(360);
+ assert.equal(container.writes.length, 0);
+ assert.equal(container.scrollTop, 1360);
+ });
+}
+
+for (const type of USER_SCROLL_EVENTS) {
+ test(`a ${type} gesture releases the hold and the user's scroll stands`, () => {
+ const container = new FakeContainer();
+ lockCollapseScroll(container, 250);
+ container.gesture(type);
+ container.layoutShift(360);
+ assert.equal(container.writes.length, 0);
+ assert.equal(container.scrollTop, 1360);
+ container.layoutShift(-50);
+ assert.equal(container.writes.length, 0);
+ assert.equal(container.scrollTop, 1310);
+ });
+}
+
+for (const type of ["pointermove", "touchmove", "mousemove", "scrollend"]) {
+ test(`a ${type} event does not release the hold`, () => {
+ const container = new FakeContainer();
+ const release = lockCollapseScroll(container, 250);
+ container.gesture(type);
+ container.layoutShift(-10);
+ assert.equal(container.writes.length, 1);
+ assert.equal(container.scrollTop, 1000);
+ release();
+ });
+}
+
+test("the hold expires after the animation duration", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const container = new FakeContainer();
+ lockCollapseScroll(container, 250);
+ mock.timers.tick(249);
+ container.layoutShift(-10);
+ assert.equal(container.writes.length, 1);
+ mock.timers.tick(1);
+ container.layoutShift(-10);
+ assert.equal(container.writes.length, 1);
+ assert.equal(container.scrollTop, 990);
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("release is idempotent and removes every listener", () => {
+ const container = new FakeContainer();
+ const release = lockCollapseScroll(container, 250);
+ release();
+ release();
+ for (const type of [...USER_SCROLL_EVENTS, ...USER_DISCRETE_EVENTS]) {
+ container.gesture(type);
+ }
+ container.layoutShift(-10);
+ assert.equal(container.writes.length, 0);
+});
+
+test("a gesture after expiry is harmless", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const container = new FakeContainer();
+ lockCollapseScroll(container, 100);
+ mock.timers.tick(100);
+ container.gesture("wheel");
+ container.layoutShift(40);
+ assert.equal(container.writes.length, 0);
+ assert.equal(container.scrollTop, 1040);
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("the hook never assigns scrollTop and delegates to the pure lock", () => {
+ const hook = readSrc("hooks/use-collapse-scroll-lock.ts");
+ assert.doesNotMatch(hook, /scrollTop\s*=[^=]/);
+ assert.ok(hook.includes('from "./collapse-scroll-lock"'));
+ assert.match(hook, /lockCollapseScroll\(\s*container,\s*animationDurationMs,\s*container\.ownerDocument,\s*\)/);
+ const lock = readSrc("hooks/collapse-scroll-lock.ts");
+ assert.doesNotMatch(lock, /scrollTop\s*=[^=]/);
+ assert.ok(lock.includes('behavior: "instant"'));
+});
diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
index 03d40be5fe2..fdba41a0023 100644
--- a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
@@ -129,3 +129,17 @@ test("the newest message still gets the whole continue bar", () => {
assert.match(shared, marker);
}
});
+
+test("a streaming reply does not re-read its content for the continue bar on every token", () => {
+ const shared = body(thread, "function useContinuation() {", "\n}\n");
+ for (const gated of [
+ /const reasoning = useAuiState\(\(\{ message \}\) =>\s*"status" in message && message\.status\?\.type === "running"\s*\? ""\s*: readContinuationSource\(message\.content\)\.reasoning,/,
+ /const messageContent = useAuiState\(\(\{ message \}\) =>\s*"status" in message && message\.status\?\.type === "running"\s*\? undefined\s*: message\.content,/,
+ ]) {
+ assert.match(
+ shared,
+ gated,
+ "the bar cannot resume a running reply, so joining its reasoning or scanning its parts per token is wasted work",
+ );
+ }
+});
diff --git a/studio/frontend/tests/connected-model-row-actions.test.ts b/studio/frontend/tests/connected-model-row-actions.test.ts
index 8ce25475b8d..7c97de8da12 100644
--- a/studio/frontend/tests/connected-model-row-actions.test.ts
+++ b/studio/frontend/tests/connected-model-row-actions.test.ts
@@ -372,7 +372,7 @@ test("per-model prompt and cap reuse the memory Chat already keeps", () => {
const chatPage = readSrc("features/chat/chat-page.tsx");
assert.match(
chatPage,
- /const activePinnedEffort = useModelReasoningEffortStore\(\s*\(state\) => state\.effortByModel\[inferenceParams\.checkpoint\],/,
+ /const activePinnedEffort = useModelReasoningEffortStore\(\s*\(state\) => state\.effortByModel\[inferenceCheckpoint\],/,
);
assert.match(
chatPage,
@@ -383,7 +383,7 @@ test("per-model prompt and cap reuse the memory Chat already keeps", () => {
// one, and the pin effect's own guard sees no change in the stored string.
assert.match(
chatPage,
- /reconcilePinnedReasoningEffort\(\{\s*checkpoint: inferenceParams\.checkpoint,\s*caps,\s*providerType: provider\?\.providerType,\s*apiType: provider\?\.apiType,\s*\}\);\s*\}, \[activePinnedEffort,/,
+ /reconcilePinnedReasoningEffort\(\{\s*checkpoint: inferenceCheckpoint,\s*caps,\s*providerType: provider\?\.providerType,\s*apiType: provider\?\.apiType,\s*\}\);\s*\}, \[activePinnedEffort,/,
);
assert.match(
chatPage,
@@ -644,7 +644,7 @@ test("a pinned reasoning effort wins, unless the catalogue withdrew it", () => {
);
assert.match(
chatPage,
- /externalReasoningTakesEffort\(reasoningCaps\)\s*\? pinnedReasoningEffort\(inferenceParams\.checkpoint, effortLevels\)/,
+ /externalReasoningTakesEffort\(reasoningCaps\)\s*\? pinnedReasoningEffort\(inferenceCheckpoint, effortLevels\)/,
);
// Both record the level the pin takes the place of, so clearing it can put that back.
assert.match(
@@ -659,7 +659,7 @@ test("a pinned reasoning effort wins, unless the catalogue withdrew it", () => {
// that used to put the provider default back over the pin.
assert.match(
chatPage,
- /\}, \[externalProvidersForChat, inferenceParams\.checkpoint, settingsHydrated\]\);/,
+ /\}, \[externalProvidersForChat, inferenceCheckpoint, settingsHydrated\]\);/,
);
assert.doesNotMatch(chatPage, /const anthropicTopEffort =/);
});
diff --git a/studio/frontend/tests/context-mode-ux.test.ts b/studio/frontend/tests/context-mode-ux.test.ts
index 0072f1c73a3..84da4a34b36 100644
--- a/studio/frontend/tests/context-mode-ux.test.ts
+++ b/studio/frontend/tests/context-mode-ux.test.ts
@@ -25,7 +25,7 @@ test("the far-left slider position is Auto", () => {
);
assert.match(
panelCode,
- /const contextSliderValue = contextIsAuto \? 0 : contextValue/,
+ /<GgufContextLengthSetting value=\{contextIsAuto \? 0 : contextValue\}/,
);
assert.match(panelCode, /<Slider min=\{0\}/);
assert.match(panelCode, /customContextLength: v === 0 \? null : v/);
@@ -35,15 +35,15 @@ test("the far-left slider position is Auto", () => {
test("moving right or typing a number creates a custom context", () => {
assert.match(
panelCode,
- /onValueChange=\{\(\[v\]\) => setContextSliderValue\(v\)\}/,
+ /onChange=\{\(v\) => update\(\{ customContextLength: v === 0 \? null : v \}\)\}/,
);
assert.match(
panelCode,
- /const setContextLength = \(v: number\) => update\(\{ customContextLength: v \}\)/,
+ /const \{ draft, sliderProps \} = useSliderDraft\(value, onChange\); const shown = draft \?\? value; const isAuto = shown === 0;/,
);
assert.match(
panelCode,
- /displayValue=\{contextIsAuto \? "Auto" : undefined\}/,
+ /<NumericValueInput ref=\{inputRef\} value=\{isAuto \? autoValue : shown\} min=\{min\} max=\{max\} step=\{1\} onChange=\{onChange\} displayValue=\{isAuto \? "Auto" : undefined\}/,
);
assert.doesNotMatch(panelCode, /ariaLabel="Context length mode"/);
});
@@ -61,7 +61,11 @@ test("the existing info hint owns the mode explanation and fitted result", () =>
panelCode,
/<InfoHint> Drag all the way left for Auto,[\s\S]*Custom values request an exact context;[\s\S]*Auto currently selected \$\{activeLoadedContext\.toLocaleString\(\)\} tokens\.[\s\S]*<\/InfoHint>/,
);
- assert.match(panelCode, /\{!contextIsAuto && isActiveModel/);
+ assert.match(
+ panelCode,
+ /renderWarning=\{\(v\) => isActiveModel && loadedMaxContextLength != null && v > loadedMaxContextLength && \(/,
+ );
+ assert.match(panelCode, /\{renderWarning\(shown\)\}/);
assert.doesNotMatch(
panelCode,
/<p className="text-ui-11 leading-relaxed text-muted-foreground">/,
diff --git a/studio/frontend/tests/desktop-app-menus.test.ts b/studio/frontend/tests/desktop-app-menus.test.ts
index e06cf65f758..8e3ba971cd0 100644
--- a/studio/frontend/tests/desktop-app-menus.test.ts
+++ b/studio/frontend/tests/desktop-app-menus.test.ts
@@ -319,7 +319,7 @@ test("menu items for web shortcuts follow a mounted handler, and honour claims",
// Backdrops portal to body, and Radix skips aria-hidden on anything holding aria-live.
assert.match(hook, /modalObserver\.observe\(document\.body, \{ childList: true \}\)/);
for (const id of ["toggleSidebar", "findInPage", "previousChat", "nextChat"]) {
- assert.ok(ROOT.includes(`useShortcutAvailable("${id}", isTauri)`), `${id} enables its item`);
+ assert.ok(ROOT.includes(`useShortcutAvailable("${id}", hasAppMenus)`), `${id} enables its item`);
}
});
diff --git a/studio/frontend/tests/desktop-webkit-paths.test.ts b/studio/frontend/tests/desktop-webkit-paths.test.ts
new file mode 100644
index 00000000000..b8f581e2795
--- /dev/null
+++ b/studio/frontend/tests/desktop-webkit-paths.test.ts
@@ -0,0 +1,90 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("a fence body becomes skippable only once it carries its measured height", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ assert.match(
+ defer,
+ /data-unsloth-fence-windowed=\{lineWindow === null \|\| !measured \? undefined : "true"\}/,
+ "a fence that upgrades off screen is first laid out as its plain lines; skipped before its height is written, it collapses, and WebKit, with no scroll anchoring, clamps a following reader's scrollTop and detaches them",
+ );
+ assert.match(defer, /const NO_WINDOW = \{ window: null, pins: null, measured: false \} as const;\s*const EMPTY_WINDOW = \{ window: EMPTY_LINE_WINDOW, pins: null, measured: false \} as const;/);
+ const measure = defer.slice(defer.indexOf("measure.current = () => {"), defer.indexOf("setState({ measured: true, window: next, pins });"));
+ assert.ok(measure.indexOf("region.style.setProperty(FENCE_HEIGHT_PROPERTY, declared);") >= 0, "the measure that first marks a fence measured writes its height before it does");
+ const autoscroll = readSrc("components/assistant-ui/use-intent-aware-autoscroll.tsx");
+ assert.match(autoscroll, /const onMutation = \(\): void => \{\s*if \(el\.ownerDocument\.hidden\) \{\s*onLayoutChange\(\);\s*return;\s*\}\s*layoutChanged = true;\s*if \(!parkIfHeld\(\)\) \{\s*extendFollow\(\);\s*\}\s*requestTick\(\);\s*\};/, "a mutation on a shown page never forces layout, following stays the frame loop's job; a hidden page runs no frames, so it pins at once and a reply that ends there is at the bottom when the tab comes back");
+ assert.match(autoscroll, /const adjustForContentInsertedAbove = useCallback\(\(deltaPx: number\) => \{\s*adjustImplRef\.current\(deltaPx\);\s*return userDetachedRef\.current;\s*\}, \[\]\);/, "the hold learns whether its correction was written, even when the engine rounded it to nothing");
+});
+
+test("only engines without requestIdleCallback shrink the widening step after a long commit", () => {
+ const transcript = readSrc("components/assistant-ui/reasoning-transcript.tsx");
+ assert.match(transcript, /if \(grew && withoutIdleCallback\)\s*widenCommitMs = Math\.max\(widenCommitMs, performance\.now\(\) - commitStartedAt\);/, "Blink commits a full step inside a frame, so it keeps filling at full speed");
+ assert.match(transcript, /widenScale \* Math\.min\(2, WIDEN_COMMIT_TARGET_MS \/ widenCommitMs\)/);
+ assert.match(transcript, /const MIN_WIDEN_SCALE = 1 \/ 8;/);
+});
+
+test("a desktop zoom shows skipped content until WebKit has measured it at the new zoom", () => {
+ const store = readSrc("features/settings/stores/interface-scale-store.ts");
+ assert.match(store, /holdContainmentAcrossZoom\(\);\s*try \{\s*await getCurrentWebview\(\)\.setZoom\(zoom\);\s*\} finally \{\s*releaseContainmentAfterZoom\(\);\s*\}/);
+ assert.match(store, /const holdsContainmentAcrossZoom = !\(\s*typeof navigator !== "undefined" && navigator\.userAgent\.includes\("Windows"\)\s*\);/, "WebView2 rescales remembered sizes itself");
+ assert.match(readSrc("features/settings/lib/interface-scale-runtime.ts"), /const ZOOMING_RELEASE_MS = 300;/);
+ const css = readSrc("index.css");
+ assert.match(css, /html\[data-interface-zooming\] \.aui-thread-root \[data-slot="reasoning-transcript"\] > \[data-reasoning-chunk\],\s*html\[data-interface-zooming\] \.aui-thread-root \[data-unsloth-fence-windowed\],\s*html\[data-interface-zooming\] \.aui-thread-root \.aui-math-block,\s*html\[data-interface-zooming\] \.aui-thread-root \.aui-math-display \{\s*content-visibility: visible !important;\s*\}/, "WebKit keeps contain-intrinsic-size: auto sizes in the old zoom's units, maths blocks included");
+ assert.match(store, /interfaceScaleApplicationQueue = Promise\.resolve\(\);\s*releaseContainmentAfterZoom\(\);\s*resolve\(\);/, "a setZoom that never settles must not leave every skipped block rendered");
+});
+
+test("the Windows thread gutter follows the native thin bar, which neither browser nor desktop zoom scales", () => {
+ const provider = readSrc("app/provider.tsx");
+ assert.match(provider, /if \(!root\.classList\.contains\("client-windows"\)\) return;/);
+ assert.match(provider, /if \(CSS\.supports\("selector\(::-webkit-scrollbar\)"\)\) \{[\s\S]*?watchThreadScrollbarGutter\(\{\s*source,\s*measure: measureThinScrollbar,\s*style: rule\.style,\s*\}\)/, "the measurement updates a scoped stylesheet rule before paint");
+ assert.equal(readSrc("index.css").includes("--studio-interface-zoom"), false);
+ assert.equal(readSrc("features/settings/lib/interface-scale-runtime.ts").includes("--studio-interface-zoom"), false);
+});
+
+test("below 1.5x device scale the Windows thread scrolls on the compositor and keeps LCD text", () => {
+ const css = readSrc("index.css");
+ assert.match(
+ css,
+ /@media screen and \(forced-colors: none\) \{\s*:root\.client-windows\[data-low-device-scale\] \.aui-thread-viewport:not\(\.chat-full-view-dock \*\) \{\s*scrollbar-gutter: auto;\s*overflow-y: scroll;\s*border-inline-start: var\(--thread-scrollbar-gutter\) solid transparent;\s*background-color: var\(--background\);\s*\}\s*\}/,
+ "Chromium composites a scroller below 1.5x only when its scrolling background is opaque, which it paints that way only with an auto gutter; the always-on bar and the start border keep the stable both-edges geometry. A contrast theme paints that transparent border in its text colour, so forced colours keep the stable gutter",
+ );
+ const supports = css.lastIndexOf("@supports selector(::-webkit-scrollbar)", css.indexOf("[data-low-device-scale]"));
+ assert.ok(supports > css.indexOf(".aui-thread-viewport {\n\t/* Reserve scrollbar space"), "the Chromium-only scrollbar block holds it, so Firefox keeps its own scrolling");
+ const provider = readSrc("app/provider.tsx");
+ assert.match(provider, /const stopFlag = watchLowDeviceScale\(\{\s*source,\s*interfaceZoom: getAppliedInterfaceZoom,\s*subscribeInterfaceZoom: subscribeAppliedInterfaceZoom,\s*root,\s*\}\);/, "the desktop divides its own page zoom out, since Chromium decides on the display's scale, not the zoomed ratio");
+ assert.match(provider, /<AppearanceCustomizationEffect \/>\s*<LowDeviceScaleEffect \/>/);
+});
+
+test("without requestIdleCallback, main-thread grammar work waits for the reader and 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.ok(defer.indexOf("if (warmMustWait()) {") < defer.indexOf("grammarsWarmed.add(language);"), "a warm that has to wait does not mark its grammar warmed");
+});
+
+test("settled fences go to the worker where the main thread's regex engine is slow", () => {
+ const markdown = readSrc("components/assistant-ui/markdown-text.tsx");
+ assert.match(markdown, /const slowMainThreadRegex =\s*typeof window !== "undefined"\s*&& typeof window\.requestIdleCallback !== "function";/);
+ assert.match(markdown, /if \(!tokenizesOffThread\(body, streaming\)\) \{\s*if \(streaming \|\| !slowMainThreadRegex\) return false;\s*const state = highlightWorkerState\(\);\s*if \(state === "unavailable" \|\| state === "stalled"\) return false;\s*\}\s*return code\.cover\(options\)\.uncovered > MAIN_THREAD_TAIL_CHARS;/, "JavaScriptCore interprets every lookbehind pattern, so WebKit tokenizes settled fences off the main thread, and a fence too long for the main thread goes to the worker, unless the main thread's own cache leaves only a short tail, as it does for the fence that just streamed");
+ assert.match(markdown, /const MAIN_THREAD_TAIL_CHARS = 512;/);
+ const warm = markdown.slice(markdown.indexOf("const warm = useCallback("), markdown.indexOf("const speculate = useCallback("));
+ assert.match(warm, /!settlesOffThread\(body, Boolean\(isIncomplete\), options\)/, "the reach latch's warm routes a settled fence the same way the render does, or a scroll tokenizes on the main thread a fence WebKit sends to the worker");
+ assert.equal(markdown.includes("fenceJustStreamed"), false, "routing reads the cache itself, not a guess about which fence streamed last");
+ const plugin = readSrc("components/assistant-ui/code-plugin.ts");
+ assert.match(plugin, /return defaultJavaScriptRegexConstructor\(pattern, \{\s*target: "ES2018",\s*accuracy: "strict",\s*\}\);\s*\} catch \{\s*return defaultJavaScriptRegexConstructor\(pattern\);\s*\}/, "u-flag patterns build several times faster in JavaScriptCore, and anything ES2018 cannot express keeps today's constructor");
+ assert.match(plugin, /const javaScriptCore =\s*typeof navigator !== "undefined"\s*&& navigator\.userAgent\.includes\("AppleWebKit\/"\)\s*&& !\/Chrom\(\?:e\|ium\)\\\/\/\.test\(navigator\.userAgent\);/, "workers have a navigator too, so the worker's highlighter makes the same choice");
+ assert.match(plugin, /: \{ forgiving: true \},\s*\);/, "V8 matches the emulated ES2018 patterns about 7% slower, so Blink keeps the engine's own target");
+});
+
+test("find in page defers rebuilds during scrolling with a maximum wait", () => {
+ const find = readSrc("features/find-in-page/hooks/use-find-in-page.ts");
+ assert.match(find, /reindexBy = performance\.now\(\) \+ 4 \* REINDEX_INTERVAL_MS;/);
+ assert.match(find, /const flush = \(\) => \{\s*const now = performance\.now\(\);\s*const wait = Math\.min\(\s*REINDEX_INTERVAL_MS - \(now - scrolledAt\),\s*reindexBy - now,\s*\);\s*if \(wait > 0\) \{\s*timerRef\.current = setTimeout\(flush, wait\);\s*return;\s*\}/);
+ assert.match(find, /window\.addEventListener\("wheel", noteScroll, \{ capture: true, passive: true \}\);/);
+ assert.match(find, /window\.removeEventListener\("wheel", noteScroll, \{ capture: true \}\);/);
+ assert.equal(/addEventListener\("scroll", noteScroll/.test(find), false, "autoscroll's own scrolling must not starve a followed stream of rebuilds");
+});
diff --git a/studio/frontend/tests/dialog-toast-outside.test.ts b/studio/frontend/tests/dialog-toast-outside.test.ts
index 63ac4aed972..e38a24c52f2 100644
--- a/studio/frontend/tests/dialog-toast-outside.test.ts
+++ b/studio/frontend/tests/dialog-toast-outside.test.ts
@@ -61,6 +61,10 @@ test("an interaction on a toast does not dismiss the dialog under it", () => {
},
"@/components/app-readiness": { AppPortalGate: "AppPortalGate" },
"@/components/ui/button": { Button: "Button" },
+ "@/components/ui/dropdown-glow": {
+ DropdownGlowContext: { Provider: "Provider" },
+ dialogDropdownGlow: () => null,
+ },
"@/lib/utils": { cn: (...classes: unknown[]) => classes.join(" ") },
"@hugeicons/core-free-icons": { Cancel01Icon: {} },
"@hugeicons/react": { HugeiconsIcon: "HugeiconsIcon" },
@@ -100,6 +104,10 @@ test("an interaction on a toast does not dismiss the sheet under it", () => {
},
"@/components/app-readiness": { AppPortalGate: "AppPortalGate" },
"@/components/ui/button": { Button: "Button" },
+ "@/components/ui/dropdown-glow": {
+ DropdownGlowContext: { Provider: "Provider" },
+ dialogDropdownGlow: () => null,
+ },
"@/components/ui/dialog": {
DialogPortalContainerContext: { Provider: "Provider" },
},
diff --git a/studio/frontend/tests/discrete-input.test.ts b/studio/frontend/tests/discrete-input.test.ts
new file mode 100644
index 00000000000..ee5f130de02
--- /dev/null
+++ b/studio/frontend/tests/discrete-input.test.ts
@@ -0,0 +1,77 @@
+// 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 {
+ DISCRETE_INPUT_EVENTS,
+ DISCRETE_INPUT_WINDOW_MS,
+ createDiscreteInputTracker,
+ discreteInputPending,
+} from "../src/components/assistant-ui/discrete-input.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+test("no input ever seen is never pending", () => {
+ assert.equal(discreteInputPending(Number.NEGATIVE_INFINITY, 0), false);
+ assert.equal(discreteInputPending(Number.NEGATIVE_INFINITY, 1e9), false);
+});
+
+test("the window is half-open: pending strictly inside, not at the edge", () => {
+ assert.equal(DISCRETE_INPUT_WINDOW_MS, 50);
+ assert.equal(discreteInputPending(100, 100), true);
+ assert.equal(discreteInputPending(100, 149.9), true);
+ assert.equal(discreteInputPending(100, 150), false);
+ assert.equal(discreteInputPending(100, 120, 10), false);
+});
+
+test("the tracker counts every discrete event through the window", () => {
+ assert.deepEqual([...DISCRETE_INPUT_EVENTS], ["keydown", "pointerdown", "touchstart"]);
+ for (const type of DISCRETE_INPUT_EVENTS) {
+ let now = 1000;
+ const target = new EventTarget();
+ const tracker = createDiscreteInputTracker(target, () => now);
+ assert.equal(tracker.pending(), false);
+ target.dispatchEvent(new Event(type));
+ now = 1020;
+ assert.equal(tracker.pending(), true, type);
+ now = 1049;
+ assert.equal(tracker.pending(), true, type);
+ now = 1050;
+ assert.equal(tracker.pending(), false, type);
+ tracker.dispose();
+ }
+});
+
+test("continuous input never counts, matching Chromium's isInputPending default", () => {
+ let now = 1000;
+ const target = new EventTarget();
+ const tracker = createDiscreteInputTracker(target, () => now);
+ for (const type of ["wheel", "pointermove", "mousemove", "touchmove", "scroll", "keyup", "pointerup"]) {
+ target.dispatchEvent(new Event(type));
+ now += 1;
+ assert.equal(tracker.pending(), false, type);
+ }
+ tracker.dispose();
+});
+
+test("dispose stops recording", () => {
+ let now = 0;
+ const target = new EventTarget();
+ const tracker = createDiscreteInputTracker(target, () => now);
+ tracker.dispose();
+ target.dispatchEvent(new Event("keydown"));
+ now = 10;
+ assert.equal(tracker.pending(), false);
+});
+
+test("the stream loop prefers the native signal and only then the tracker", () => {
+ const source = readSrc("components/assistant-ui/markdown-text.tsx");
+ assert.match(
+ source,
+ /if \(scheduling\?\.isInputPending\) \{\s*return scheduling\.isInputPending\(\);\s*\}/,
+ );
+ assert.ok(source.includes("discreteInput ??= createDiscreteInputTracker(document);"));
+ assert.ok(!source.includes("includeContinuous: true"));
+});
diff --git a/studio/frontend/tests/dropdown-glow.test.ts b/studio/frontend/tests/dropdown-glow.test.ts
new file mode 100644
index 00000000000..b97d1039dd7
--- /dev/null
+++ b/studio/frontend/tests/dropdown-glow.test.ts
@@ -0,0 +1,65 @@
+// 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 { dialogDropdownGlow } from "../src/components/ui/dropdown-glow.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+test("a card dialog surface sets the card glow, anything else keeps the one around it", () => {
+ for (const className of [
+ "dialog-soft-surface",
+ "sm:max-w-lg settings-surface p-0",
+ "bg-background dark:bg-card",
+ "dark:bg-card/80 rounded-3xl",
+ ]) {
+ assert.equal(dialogDropdownGlow(className, null), "card", className);
+ assert.equal(dialogDropdownGlow(className, "picker"), "card", className);
+ }
+ for (const className of [undefined, "", "sm:max-w-md", "settings-surface-muted", "bg-card"]) {
+ assert.equal(dialogDropdownGlow(className, null), null, String(className));
+ assert.equal(dialogDropdownGlow(className, "picker"), "picker", String(className));
+ }
+});
+
+test("every menu surface carries the glow of the dialog or picker it opens from", () => {
+ for (const [file, slots] of [
+ ["components/ui/dropdown-menu.tsx", ["dropdown-menu-content", "dropdown-menu-sub-content"]],
+ ["components/ui/context-menu.tsx", ["context-menu-content", "context-menu-sub-content"]],
+ ["components/ui/select.tsx", ["select-content"]],
+ ["components/ui/combobox.tsx", ["combobox-content"]],
+ ] as const) {
+ const source = readSrc(file);
+ for (const slot of slots) {
+ assert.match(
+ source,
+ new RegExp(`data-slot="${slot}"\\s*data-dropdown-glow=\\{useDropdownGlow\\(\\)\\}`),
+ `${file}: ${slot}`,
+ );
+ }
+ }
+ const popover = readSrc("components/ui/popover.tsx");
+ assert.match(popover, /data-slot="popover-content"\s*data-dropdown-glow=\{inheritedGlow \?\? undefined\}/);
+ assert.match(
+ popover,
+ /<DropdownGlowContext\.Provider value=\{dropdownGlow \?\? inheritedGlow\}>\s*\{children\}/,
+ );
+ assert.match(
+ readSrc("features/model-picker/components/model-selector.tsx"),
+ /<PopoverContent\s+align="start"\s+alignOffset=\{10\}\s+dropdownGlow="picker"/,
+ );
+});
+
+test("dialogs hand their surface to the menus opened inside them, without remounting their content", () => {
+ const dialog = readSrc("components/ui/dialog.tsx");
+ assert.match(
+ dialog,
+ /resolvedContainer === null\s*\? dialogDropdownGlow\(className, inheritedGlow\)\s*: inheritedGlow;/,
+ "a dialog portaled into a container is not the body-level surface its menus sit beside",
+ );
+ assert.match(dialog, /<DropdownGlowContext\.Provider value=\{glow\}>\s*\{children\}/);
+ const alert = readSrc("components/ui/alert-dialog.tsx");
+ assert.match(alert, /dialogDropdownGlow\(className, useContext\(DropdownGlowContext\)\)/);
+ assert.match(alert, /<DropdownGlowContext\.Provider value=\{glow\}>\s*\{children\}/);
+});
diff --git a/studio/frontend/tests/fence-speculation-wiring.test.ts b/studio/frontend/tests/fence-speculation-wiring.test.ts
new file mode 100644
index 00000000000..f47ac2eda15
--- /dev/null
+++ b/studio/frontend/tests/fence-speculation-wiring.test.ts
@@ -0,0 +1,48 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const DEFER = readSrc("components/assistant-ui/code-fence-defer.tsx");
+const MARKDOWN = readSrc("components/assistant-ui/markdown-text.tsx");
+const THREAD = readSrc("components/assistant-ui/thread.tsx");
+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, /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, /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);
+ const speculate = MARKDOWN.slice(MARKDOWN.indexOf("const speculate = useCallback("), MARKDOWN.indexOf("const reached = useFenceReached("));
+ assert.ok(speculate.indexOf("code.cached(options) !== null") < speculate.indexOf("requestFullHighlight("));
+ assert.match(speculate, /requestFullHighlight\(\s*body,\s*languageToken,\s*\(result\) => \{\s*if \(result !== null\) code\.seed\(options, result\);\s*settle\(result !== null\);\s*\},\s*true,\s*\);/);
+ assert.match(MARKDOWN, /useFenceReached\(\s*host,\s*mode !== "off",\s*Boolean\(isIncomplete\),[\s\S]{0,200}?trimmedLength\(source\),\s*source,\s*warm,\s*speculate,\s*\);/);
+});
+
+test("every gate joins and leaves the speculator with its registration, and a latch withdraws it first", () => {
+ assert.match(DEFER, /scheduleGrammarWarm\(\);\s*fenceSpeculator\.add\(registered\);/);
+ assert.match(DEFER, /fenceSpeculator\.remove\(registered\);\s*unreached\.delete\(registered\);/);
+ assert.match(DEFER, /unreached\.delete\(gate\);\s*fenceSpeculator\.remove\(gate\);\s*gate\.warm\(true\);/);
+ assert.match(DEFER, /latchNow\(arrived\);\s*fenceSpeculator\.rerank\(\);/);
+ assert.match(PLUGIN, /const reachInto = \(fence: Fence, code: string\): number => \{\s*if \(fence\.result === null \|\| fence\.seeded\) return -1;/, "a seeded entry is an exact hit only, never a prefix anchor");
+ assert.match(PLUGIN, /export const MAX_FENCES = 512;\s*export const MAX_CACHED_CHARACTERS = 512_000;/);
+});
+
+test("the grammar pre-warm runs once per session from the thread root, idle and quiet only, over untrimmed samples", () => {
+ assert.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, /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-speculation.test.ts b/studio/frontend/tests/fence-speculation.test.ts
new file mode 100644
index 00000000000..9254e4bcd28
--- /dev/null
+++ b/studio/frontend/tests/fence-speculation.test.ts
@@ -0,0 +1,256 @@
+// 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 {
+ createFenceSpeculator,
+ type SpeculationGate,
+} from "../src/components/assistant-ui/fence-speculation.ts";
+
+type Gate = SpeculationGate & { name: string; at: number; language: string };
+
+const harness = (overrides: Partial<Parameters<typeof createFenceSpeculator<Gate>>[0]> = {}) => {
+ const idle: (() => void)[] = [];
+ const waits: { callback: () => void; ms: number }[] = [];
+ const settled = new Map<Gate, (ok: boolean) => void>();
+ const warmed = new Set<string>();
+ const speculator = createFenceSpeculator<Gate>({
+ idle: (callback) => {
+ idle.push(callback);
+ return () => {
+ const at = idle.indexOf(callback);
+ if (at >= 0) idle.splice(at, 1);
+ };
+ },
+ wait: (callback, ms) => {
+ waits.push({ callback, ms });
+ return () => {
+ const at = waits.findIndex((entry) => entry.callback === callback);
+ if (at >= 0) waits.splice(at, 1);
+ };
+ },
+ enabled: () => true,
+ busy: () => false,
+ eligible: (gate) => warmed.has(gate.language),
+ rank: (gates) => gates.map((gate) => gate.at),
+ maxChars: 20_000,
+ budgetChars: 100_000,
+ budgetFences: 4,
+ ...overrides,
+ });
+ const gate = (name: string, at: number, chars = 100, language = "js"): Gate => ({
+ name,
+ at,
+ chars,
+ language,
+ speculate: (settle) => {
+ settled.set(gate_(name), settle);
+ return () => settled.delete(gate_(name));
+ },
+ });
+ const gates = new Map<string, Gate>();
+ const gate_ = (name: string) => gates.get(name)!;
+ const make = (name: string, at: number, chars?: number, language?: string) => {
+ const g = gate(name, at, chars, language);
+ gates.set(name, g);
+ return g;
+ };
+ const runIdle = () => {
+ const callback = idle.shift();
+ callback?.();
+ };
+ return { speculator, idle, waits, settled, warmed, make, gate_, runIdle };
+};
+
+test("the nearest warmed fence goes first, one at a time, until the budget is spent", () => {
+ const h = harness();
+ h.warmed.add("js");
+ const far = h.make("far", 900);
+ const near = h.make("near", 10);
+ const middle = h.make("middle", 400);
+ h.speculator.add(far);
+ h.speculator.add(near);
+ h.speculator.add(middle);
+ assert.equal(h.idle.length, 1, "one idle slot for three candidates");
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["near"]);
+ assert.equal(h.idle.length, 0, "nothing else is picked while one is in flight");
+ h.settled.get(near)!(true);
+ assert.equal(h.speculator.snapshot().seeded, 1);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["near", "middle"]);
+ h.settled.get(middle)!(true);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["near", "middle", "far"]);
+});
+
+test("fences that are empty or over the cap are never candidates", () => {
+ const h = harness();
+ h.warmed.add("js");
+ h.speculator.add(h.make("empty", 0, 0));
+ h.speculator.add(h.make("huge", 0, 20_001));
+ assert.equal(h.speculator.snapshot().candidates, 0);
+ assert.equal(h.idle.length, 0);
+});
+
+test("a language the main thread has not warmed waits instead of being seeded", () => {
+ const h = harness();
+ const cold = h.make("cold", 0, 100, "python");
+ h.speculator.add(cold);
+ h.runIdle();
+ assert.equal(h.settled.size, 0);
+ assert.equal(h.waits.length, 1);
+ assert.equal(h.waits[0].ms, 1000);
+ h.warmed.add("python");
+ h.waits.shift()!.callback();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["cold"]);
+});
+
+test("removing the in-flight fence cancels it and frees the slot; removing a seeded one releases its budget", () => {
+ const h = harness();
+ h.warmed.add("js");
+ const a = h.make("a", 0, 1000);
+ const b = h.make("b", 1, 1000);
+ h.speculator.add(a);
+ h.speculator.add(b);
+ h.runIdle();
+ assert.ok(h.settled.has(a));
+ h.speculator.remove(a);
+ assert.equal(h.settled.has(a), false, "the cancel closure ran");
+ assert.equal(h.speculator.snapshot().inFlight, false);
+ h.runIdle();
+ assert.ok(h.settled.has(b));
+ h.settled.get(b)!(true);
+ assert.equal(h.speculator.snapshot().seededChars, 1000);
+ h.speculator.remove(b);
+ assert.equal(h.speculator.snapshot().seededChars, 0);
+});
+
+test("the character budget skips a nearer fence that does not fit and the fence budget stops picking", () => {
+ const h = harness({ budgetChars: 1500, budgetFences: 2 });
+ h.warmed.add("js");
+ const big = h.make("big", 0, 1400);
+ const near = h.make("near", 3, 200);
+ const small = h.make("small", 5, 50);
+ const tiny = h.make("tiny", 9, 10);
+ for (const g of [big, near, small, tiny]) h.speculator.add(g);
+ h.runIdle();
+ h.settled.get(big)!(true);
+ assert.equal(h.speculator.snapshot().seededChars, 1400);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["big", "small"], "the 200-character fence is nearer but would pass 1500, so the 50-character one is picked");
+ h.settled.get(small)!(true);
+ h.runIdle();
+ assert.equal(h.settled.has(tiny), false, "two seeded fences is the fence budget");
+});
+
+test("a failed speculation spends no budget", () => {
+ const h = harness({ budgetChars: 1000, budgetFences: 1 });
+ h.warmed.add("js");
+ const a = h.make("a", 0, 900);
+ const b = h.make("b", 1, 900);
+ h.speculator.add(a);
+ h.speculator.add(b);
+ h.runIdle();
+ h.settled.get(a)!(false);
+ assert.deepEqual([h.speculator.snapshot().seeded, h.speculator.snapshot().seededChars], [0, 0]);
+ h.runIdle();
+ assert.ok(h.settled.has(b), "the next fence still fits");
+});
+
+test("a pause while the worker is late keeps every candidate, and speculation resumes once it answers", () => {
+ let busy = true;
+ const h = harness({ busy: () => busy });
+ h.warmed.add("js");
+ const gates = ["a", "b", "c"].map((name, at) => h.make(name, at));
+ for (const g of gates) h.speculator.add(g);
+ h.runIdle();
+ assert.equal(h.settled.size, 0);
+ assert.equal(h.speculator.snapshot().candidates, 3);
+ h.waits.shift()!.callback();
+ assert.equal(h.speculator.snapshot().candidates, 3, "still paused, nothing dropped");
+ busy = false;
+ h.waits.shift()!.callback();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["a"]);
+});
+
+test("a stream defers the pick, a disabled worker drops every candidate, and a throw settles false", () => {
+ let busy = true;
+ let enabled = true;
+ const h = harness({ busy: () => busy, enabled: () => enabled });
+ h.warmed.add("js");
+ const a = h.make("a", 0);
+ h.speculator.add(a);
+ h.runIdle();
+ assert.equal(h.settled.size, 0);
+ assert.equal(h.waits.length, 1);
+ busy = false;
+ h.waits.shift()!.callback();
+ assert.ok(h.settled.has(a));
+ h.settled.get(a)!(false);
+ const thrower: Gate = { name: "t", at: 0, chars: 10, language: "js", speculate: () => { throw new Error("boom"); } };
+ h.speculator.add(thrower);
+ h.runIdle();
+ assert.equal(h.speculator.snapshot().inFlight, false, "a throw never wedges the slot");
+ enabled = false;
+ h.speculator.add(h.make("b", 1));
+ h.runIdle();
+ assert.equal(h.speculator.snapshot().candidates, 0);
+});
+
+test("with several slots, one idle task launches nearest first up to the limit and a settle refills it", () => {
+ const h = harness({ maxInFlight: 3 });
+ h.warmed.add("js");
+ const gates = ["a", "b", "c", "d", "e"].map((name, at) => h.make(name, at * 10));
+ for (const g of gates) h.speculator.add(g);
+ assert.equal(h.idle.length, 1);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["a", "b", "c"]);
+ assert.equal(h.speculator.snapshot().inFlightCount, 3);
+ assert.equal(h.idle.length, 0, "a full set of slots schedules nothing more");
+ h.settled.get(gates[1])!(true);
+ assert.equal(h.idle.length, 1, "a settled slot asks for one more idle task");
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["a", "b", "c", "d"]);
+ h.speculator.remove(gates[0]);
+ assert.equal(h.settled.has(gates[0]), false, "removing an in-flight fence cancels it");
+ assert.equal(h.speculator.snapshot().inFlightCount, 2);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["b", "c", "d", "e"]);
+});
+
+test("characters and fences in flight count against the budget, so concurrency never overshoots it", () => {
+ const h = harness({ maxInFlight: 3, budgetChars: 250, budgetFences: 3 });
+ h.warmed.add("js");
+ const a = h.make("a", 0, 100);
+ const b = h.make("b", 1, 100);
+ const c = h.make("c", 2, 100);
+ const d = h.make("d", 3, 40);
+ for (const g of [a, b, c, d]) h.speculator.add(g);
+ h.runIdle();
+ assert.deepEqual([...h.settled.keys()].map((g) => g.name), ["a", "b", "d"], "the third 100-char fence would pass 250 with two in flight, the 40-char one fits");
+ h.settled.get(a)!(true);
+ h.settled.get(b)!(true);
+ h.settled.get(d)!(true);
+ h.runIdle();
+ assert.equal(h.settled.has(c), false, "three seeded fences is the fence budget");
+});
+
+test("a settle for a fence that is no longer in flight is ignored and ranking refreshes on demand", () => {
+ const h = harness();
+ h.warmed.add("js");
+ const a = h.make("a", 0);
+ const b = h.make("b", 1);
+ h.speculator.add(a);
+ h.speculator.add(b);
+ h.runIdle();
+ const settleA = h.settled.get(a)!;
+ h.speculator.remove(a);
+ settleA(true);
+ assert.equal(h.speculator.snapshot().seeded, 0, "a late settle for a removed fence does not count");
+ h.speculator.rerank();
+ h.runIdle();
+ assert.ok(h.settled.has(b));
+});
diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.ts
index 579ae62c5e4..6bf82ae6520 100644
--- a/studio/frontend/tests/find-in-page.test.ts
+++ b/studio/frontend/tests/find-in-page.test.ts
@@ -1576,10 +1576,7 @@ test("toasts clear the bar while it is open", () => {
assert.match(FIND_BAR, FIND_SURFACE_GEOMETRY);
assert.match(FIND_IN_PAGE, FIND_SURFACE_GEOMETRY);
const toaster = '[data-sonner-toaster][data-y-position="top"]';
- const rule = cssRule(
- INDEX,
- `:root:has([data-find-bar-layer]:not([hidden]) .find-bar-surface) ${toaster}`,
- );
+ const rule = cssRule(INDEX, `html[data-find-bar-open] ${toaster}`);
assert.match(rule, TOAST_UNDER_FIND_BAR);
// The toaster renders outside the chrome wrapper, so the bar's inset has to reach <html>.
assert.match(
@@ -3271,3 +3268,12 @@ test("nothing of the engine is mounted while the bar is closed", async () => {
assert.equal((FIND_BAR.match(/useFindInPage\(/g) ?? []).length, 1);
});
+
+test("the find bar hides under the Browser overlay from its first frame", () => {
+ const page = readSrc("features/chat/chat-page.tsx");
+ const start = page.indexOf("function BrowserOverlay(");
+ const overlay = page.slice(start, page.indexOf("\n}\n", start));
+ assert.match(overlay, /useDocumentFlag\("data-browser-overlay-open", true\);/, "the inline modal tells CSS it is up, which nothing else notices until its lazy panel loads");
+ assert.match(INDEX, /html\[data-browser-overlay-open\] \[data-find-bar-layer\] \{\s*display: none;\s*\}/);
+ assert.equal(/html\[data-browser-overlay-open\][^{]*\.interface-zoom-position/.test(INDEX), false, "the zoom popup stays, as upstream keeps it under any dialog");
+});
diff --git a/studio/frontend/tests/find-windowed-fence.test.ts b/studio/frontend/tests/find-windowed-fence.test.ts
new file mode 100644
index 00000000000..fb49e367693
--- /dev/null
+++ b/studio/frontend/tests/find-windowed-fence.test.ts
@@ -0,0 +1,37 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("stepping onto a match whose text a line window swapped out rebuilds the index first", () => {
+ const hook = readSrc("features/find-in-page/hooks/use-find-in-page.ts");
+ const step = hook.slice(
+ hook.indexOf("const step = useCallback("),
+ hook.indexOf("const next = useCallback("),
+ );
+ assert.match(
+ step,
+ /if \(staleRef\.current\) \{\s*const range = rangeForMatch\(indexRef\.current, target\);\s*if \(!\(range\?\.startContainer\.isConnected && range\.endContainer\.isConnected\)\) \{\s*activeStartRef\.current = target\.start;\s*search\(true, reindex\(\)\);\s*return;\s*\}\s*\}\s*apply\(true\);/,
+ "a windowed fence swaps a line between one text node and its token spans as the reader moves, and the throttled rebuild came too late for a quick Enter",
+ );
+});
+
+test("while the find bar is open a long fence renders every line, so the highlights keep their text", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ assert.match(
+ readSrc("features/find-in-page/components/find-in-page.tsx"),
+ /useDocumentFlag\("data-find-bar-open", enabled && open && foreground\);/,
+ );
+ assert.match(defer, /const FIND_BAR_FLAG = "data-find-bar-open";/);
+ assert.match(
+ defer,
+ /findBarObserver = new MutationObserver\(scheduleRemeasure\);\s*findBarObserver\.observe\(document\.documentElement, \{\s*attributes: true,\s*attributeFilter: \[FIND_BAR_FLAG\],\s*\}\);/,
+ "find paints live ranges over a line's text, and a window move swapped that text for token spans, so the highlights vanished until the index was rebuilt",
+ );
+ assert.ok(defer.indexOf("findBarObserver?.disconnect();") > defer.indexOf("const unwatchWindows = "));
+ assert.match(defer, /if \(printing \|\| findBarOpen\(\)\) \{\s*if \(current\.current === null && pinned\.current === null\) return;/);
+ assert.ok(defer.includes("return overCap && !printing && !findBarOpen() ? EMPTY_WINDOW : NO_WINDOW;"), "a fence that mounts while the bar is open starts unwindowed");
+});
diff --git a/studio/frontend/tests/fixtures/user-message-time/main.tsx b/studio/frontend/tests/fixtures/user-message-time/main.tsx
index 2aee525278f..f5c28d018c6 100644
--- a/studio/frontend/tests/fixtures/user-message-time/main.tsx
+++ b/studio/frontend/tests/fixtures/user-message-time/main.tsx
@@ -81,7 +81,7 @@ function User() {
<button className="aui-branch-chevron-btn" aria-label="Previous">
‹
</button>
- <span className="font-mono tabular-nums">1/2</span>
+ <span className="aui-branch-picker-state font-mono tabular-nums">1/2</span>
<button className="aui-branch-chevron-btn" aria-label="Next">
›
</button>
diff --git a/studio/frontend/tests/floating-monitor-dock.test.ts b/studio/frontend/tests/floating-monitor-dock.test.ts
index d76639612e9..402146e1812 100644
--- a/studio/frontend/tests/floating-monitor-dock.test.ts
+++ b/studio/frontend/tests/floating-monitor-dock.test.ts
@@ -140,8 +140,10 @@ test("the monitor reads the panel's painted width and keeps its floating layer",
});
test("responsive changes reattach geometry observers and recalculate capacity", () => {
- assert.match(source, /\}, \[isChatRoute, settingsPanelOpen, isMobile\]\);/);
- assert.match(source, /\}, \[isMobile\]\);/);
+ assert.match(source, /\}, \[isOpen, isChatRoute, settingsPanelOpen, isMobile\]\);/);
+ assert.match(source, /\}, \[isOpen, isMobile\]\);/);
+ assert.match(source, /if \(!\(isOpen && isChatRoute && settingsPanelOpen\)\) \{/, "a closed monitor does not re-render on every frame of a Run settings drag");
+ assert.match(source, /const sidebar = isOpen \? document\.querySelector\('\[data-slot="sidebar"\]'\) : null;/, "nor of a sidebar drag");
assert.match(source, /paintedSidebarWidth > 0 \? paintedSidebarWidth : committedSidebarWidth/);
assert.match(source, /const sidebarWidth = pinned \? pinnedSidebarWidth : unpinnedSidebarWidth/);
assert.match(source, /const viewportWidth = useSyncExternalStore\(/);
diff --git a/studio/frontend/tests/grammar-prewarm.test.ts b/studio/frontend/tests/grammar-prewarm.test.ts
new file mode 100644
index 00000000000..0d70b8a21a3
--- /dev/null
+++ b/studio/frontend/tests/grammar-prewarm.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ GRAMMAR_SAMPLES,
+ PREWARM_GUARD_MS,
+ PREWARM_RETRY_MS,
+ createGrammarPrewarm,
+} from "../src/components/assistant-ui/grammar-prewarm.ts";
+
+const harness = (options: { quiet?: () => boolean; skip?: (language: string) => boolean; sync?: boolean } = {}) => {
+ const idle: (() => void)[] = [];
+ const waits: { callback: () => void; ms: number }[] = [];
+ const calls: { code: string; language: string }[] = [];
+ const lates: (() => void)[] = [];
+ const prewarm = createGrammarPrewarm(
+ (code, language, late) => {
+ calls.push({ code, language });
+ if (options.sync === false) {
+ lates.push(late);
+ return null;
+ }
+ return {};
+ },
+ {
+ idle: (callback) => {
+ idle.push(callback);
+ return () => {
+ const at = idle.indexOf(callback);
+ if (at >= 0) idle.splice(at, 1);
+ };
+ },
+ wait: (callback, ms) => {
+ waits.push({ callback, ms });
+ return () => {
+ const at = waits.findIndex((entry) => entry.callback === callback);
+ if (at >= 0) waits.splice(at, 1);
+ };
+ },
+ quiet: options.quiet ?? (() => true),
+ skip: options.skip ?? (() => false),
+ },
+ [
+ { language: "python", lines: ["# a", "import os"] },
+ { language: "css", lines: ["/* b */", ".x { }", ".y { }"] },
+ ],
+ );
+ return { prewarm, idle, waits, calls, lates };
+};
+
+test("every sample starts with its marker line and names a grammar the plugin keys by", () => {
+ for (const sample of GRAMMAR_SAMPLES) {
+ assert.ok(sample.lines[0].includes("unsloth grammar warm"), sample.language);
+ assert.equal(sample.language, sample.language.toLowerCase());
+ assert.ok(sample.lines.length >= 2);
+ }
+});
+
+test("one step per idle task, each tokenizing one more line, sample by sample", () => {
+ const h = harness();
+ h.prewarm.start();
+ assert.equal(h.idle.length, 1);
+ h.idle.shift()!();
+ assert.deepEqual(h.calls.map((call) => call.code), ["# a\n"]);
+ h.idle.shift()!();
+ h.idle.shift()!();
+ assert.deepEqual(h.calls.map((call) => [call.language, call.code]), [
+ ["python", "# a\n"],
+ ["python", "# a\nimport os\n"],
+ ["css", "/* b */\n"],
+ ]);
+ h.idle.shift()!();
+ h.idle.shift()!();
+ assert.equal(h.calls.length, 5);
+ h.idle.shift()!();
+ assert.equal(h.idle.length, 0, "the chain ends after the last line");
+ h.prewarm.start();
+ assert.equal(h.idle.length, 0, "and never restarts");
+});
+
+test("a stream or recent input defers the step without tokenizing", () => {
+ let quiet = false;
+ const h = harness({ quiet: () => quiet });
+ h.prewarm.start();
+ h.idle.shift()!();
+ assert.equal(h.calls.length, 0);
+ assert.equal(h.waits.length, 1);
+ assert.equal(h.waits[0].ms, PREWARM_RETRY_MS);
+ quiet = true;
+ h.waits.shift()!.callback();
+ assert.equal(h.calls.length, 1);
+});
+
+test("a grammar still loading advances when its late callback fires, or after the guard", () => {
+ const h = harness({ sync: false });
+ h.prewarm.start();
+ h.idle.shift()!();
+ assert.equal(h.calls.length, 1);
+ assert.equal(h.idle.length, 0);
+ assert.equal(h.waits.length, 1);
+ assert.equal(h.waits[0].ms, PREWARM_GUARD_MS);
+ h.lates.shift()!();
+ assert.equal(h.idle.length, 1, "the late result schedules the next step");
+ assert.equal(h.waits.length, 0, "and cancels the guard");
+ h.idle.shift()!();
+ h.waits.shift()!.callback();
+ assert.equal(h.idle.length, 1, "the guard alone also advances");
+});
+
+test("cancel during a grammar load stops the chain, and a restart runs exactly one chain", () => {
+ const h = harness({ sync: false });
+ h.prewarm.start();
+ h.idle.shift()!();
+ assert.equal(h.calls.length, 1);
+ assert.equal(h.waits.length, 1, "the guard is armed while the grammar loads");
+ h.prewarm.cancel();
+ assert.equal(h.waits.length, 0, "cancel disarms the guard");
+ h.lates.shift()!();
+ assert.equal(h.idle.length, 0, "a late result for the cancelled step does not resume the chain");
+ h.prewarm.start();
+ assert.equal(h.idle.length, 1, "start schedules one chain");
+});
+
+test("languages the main thread already warmed are skipped and cancel stops the chain", () => {
+ const h = harness({ skip: (language) => language === "python" });
+ h.prewarm.start();
+ h.idle.shift()!();
+ assert.deepEqual(h.calls.map((call) => call.language), ["css"]);
+ h.prewarm.cancel();
+ assert.equal(h.idle.length, 0);
+});
diff --git a/studio/frontend/tests/helpers/module-stubs.ts b/studio/frontend/tests/helpers/module-stubs.ts
index b7548aacc8b..9821a2697f2 100644
--- a/studio/frontend/tests/helpers/module-stubs.ts
+++ b/studio/frontend/tests/helpers/module-stubs.ts
@@ -36,7 +36,11 @@ export function loadWithStubs<T>(
options: { relativePassthrough?: boolean } = {},
): T {
const path = fileURLToPath(moduleUrl);
- const { outputText } = ts.transpileModule(readFileSync(path, "utf8"), {
+ const source = readFileSync(path, "utf8").replaceAll(
+ "import.meta.url",
+ JSON.stringify(pathToFileURL(path).href),
+ );
+ const { outputText } = ts.transpileModule(source, {
fileName: path,
compilerOptions: {
target: ts.ScriptTarget.ES2022,
diff --git a/studio/frontend/tests/highlight-worker-failover.test.ts b/studio/frontend/tests/highlight-worker-failover.test.ts
new file mode 100644
index 00000000000..4e88c8b00fc
--- /dev/null
+++ b/studio/frontend/tests/highlight-worker-failover.test.ts
@@ -0,0 +1,72 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const HOOK = readSrc("components/assistant-ui/use-reasoning-highlight.ts");
+const WORKER = readSrc("components/assistant-ui/reasoning-highlight.worker.ts");
+const MARKDOWN = readSrc("components/assistant-ui/markdown-text.tsx");
+
+test("the worker announces itself last, after its handler and highlighter exist", () => {
+ const ready = WORKER.lastIndexOf("self.postMessage({ ready: true }");
+ const handler = WORKER.indexOf("self.onmessage ??= ");
+ assert.ok(handler >= 0 && ready > handler, "a second evaluation of the entry, which WebKit runs when a grammar chunk imports it back, keeps the first handler and its sources");
+ assert.ok(ready > WORKER.indexOf("const highlighter = createCodePlugin("));
+ assert.equal(WORKER.slice(ready).trim().split("\n").length, 1, "nothing follows the ready message");
+ assert.ok(WORKER.includes("orderHighlightRequests([...pending.values()])"));
+ assert.match(WORKER, /catch \{\s*if \(current\(\)\) \{\s*self\.postMessage\(\s*reasoningHighlightFailure\(request\.client, request\.revision\),/);
+});
+
+test("a failed worker is never rebuilt and every waiting caller hears about it once", () => {
+ assert.equal((HOOK.match(/new Worker\(/g) ?? []).length, 1);
+ const refused = HOOK.indexOf('if (state === "unavailable") return null;');
+ assert.ok(refused >= 0 && refused < HOOK.indexOf("new Worker("));
+ const fail = HOOK.slice(HOOK.indexOf("function fail("), HOOK.indexOf("function stall("));
+ assert.ok(fail.includes('state = "unavailable";'));
+ assert.ok(fail.includes("flushListeners();"));
+ const flush = HOOK.slice(HOOK.indexOf("const flushListeners = "), HOOK.indexOf("function fail("));
+ assert.equal(flush.includes("listeners.clear()"), false, "a listener cancelled after the snapshot is never called");
+ assert.match(flush, /const \[id, listener\] = next;\s*if \(listeners\.get\(id\) === listener\) \{\s*listeners\.delete\(id\);\s*listener\(reasoningHighlightFailure\(id, 0\)\);/, "a listener set again after the snapshot belongs to a newer request and is not failed");
+ assert.equal((flush.match(/setTimeout\(deliver, 0\)/g) ?? []).length, 2, "every failure, the first included, is its own task");
+ const stall = HOOK.slice(HOOK.indexOf("function stall("), HOOK.indexOf("function getWorker("));
+ assert.ok(stall.includes('state = "stalled";') && !stall.includes("terminate()"), "a worker that is late keeps running and recovers on its ready message");
+ assert.ok(stall.includes("flushListeners(patientClients);"), "a late worker fails every caller except the whole-fence requests waiting on it");
+ assert.match(HOOK, /if \(state === "stalled" && !patient\) return null;\s*if \(idle\) clearTimeout\(idle\);/, "a whole-fence request queues on a late worker; every other caller highlights on the main thread while it is late, and turning one away leaves the idle teardown armed");
+ assert.match(HOOK, /speculative = false,\s*patient = !speculative,\s*\): \(\(\) => void\) \| null \{\s*const instance = getWorker\(patient\);\s*if \(!instance\) return null;\s*const id = \+\+nextClient;\s*if \(patient\) patientClients\.add\(id\);/);
+ assert.equal((HOOK.match(/patientClients\.delete\(id\);/g) ?? []).length, 2, "an answered or cancelled request stops waiting");
+ assert.match(HOOK, /idle = setTimeout\(\(\) => \{\s*if \(!worker \|\| boot\?\.instance === worker\) return;\s*worker\.terminate\(\);/, "and the idle teardown never kills a worker that is still booting, so the late ready can arrive");
+ assert.match(HOOK, /clearBoot\(instance\);\s*state = "ready";\s*watchSilence\(instance\);\s*if \(listeners\.size === 0\) scheduleIdle\(\);/, "a worker that recovered with nothing waiting is torn down when idle like any other");
+ const writes = HOOK.match(/state = "unavailable";/g) ?? [];
+ assert.equal(writes.length, 3, "fail() and the two constructor guards; a stall is not a failure");
+ const idle = HOOK.slice(HOOK.indexOf("function scheduleIdle("), HOOK.indexOf("export function requestFullHighlight("));
+ assert.match(idle, /worker = null;\s*if \(state === "stalled"\) state = "untested";/, "a late worker that idles out takes its stall with it, so the next request boots a fresh one");
+ assert.equal((idle.match(/\bstate = "/g) ?? []).length, 1, "and the teardown never lifts an unavailable worker");
+ assert.ok(HOOK.includes("afterQueuedMessages(() => stall(instance))"));
+ assert.ok(HOOK.includes("new MessageChannel()"));
+ assert.match(HOOK, /const READY_TIMEOUT_MS = 5_000;/);
+ assert.match(HOOK, /const IDLE_TEARDOWN_MS = 10_000;/);
+});
+
+test("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, /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(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");
+ assert.match(WORKER, /const FULL_REPLY_GUARD_MS = 15_000;/);
+});
+
+test("the stream signal is read lazily, never at module scope", () => {
+ assert.match(HOOK, /\(activity \?\?= createStreamActivity\(useChatRuntimeStore\)\)\.active\(\)/);
+ assert.equal(/^const activity = createStreamActivity/m.test(HOOK), false);
+});
diff --git a/studio/frontend/tests/highlight-worker-stall.test.ts b/studio/frontend/tests/highlight-worker-stall.test.ts
new file mode 100644
index 00000000000..2bd28e36167
--- /dev/null
+++ b/studio/frontend/tests/highlight-worker-stall.test.ts
@@ -0,0 +1,240 @@
+// 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, { type TestContext } from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Client = {
+ requestFullHighlight: (
+ source: string,
+ language: string | null,
+ onResult: (result: unknown) => void,
+ speculative?: boolean,
+ patient?: boolean,
+ ) => (() => void) | null;
+ highlightWorkerState: () => string;
+};
+
+class FakeWorker {
+ static made: FakeWorker[] = [];
+ posted: Record<string, unknown>[] = [];
+ terminated = false;
+ onmessage: ((event: { data: unknown }) => void) | null = null;
+ onerror: ((event: { message: string; type: string }) => void) | null = null;
+
+ constructor() {
+ FakeWorker.made.push(this);
+ }
+
+ postMessage(data: Record<string, unknown>): void {
+ this.posted.push(data);
+ }
+
+ terminate(): void {
+ this.terminated = true;
+ }
+
+ send(data: unknown): void {
+ this.onmessage?.({ data });
+ }
+
+ requests(): number[] {
+ return this.posted.flatMap((message) =>
+ typeof message.client === "number" ? [message.client] : [],
+ );
+ }
+}
+
+const RESULT = { tokens: [[]], fg: "#000", bg: "#fff" };
+
+const MESSAGES = loadWithStubs<Record<string, unknown>>(
+ new URL("../src/components/assistant-ui/reasoning-highlight.ts", import.meta.url),
+ {},
+);
+
+function setup(t: TestContext): { client: Client; drain: () => void } {
+ FakeWorker.made = [];
+ const scope = globalThis as { Worker?: unknown };
+ scope.Worker = FakeWorker;
+ t.after(() => {
+ delete scope.Worker;
+ });
+ t.mock.method(console, "warn", () => {});
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const client = loadWithStubs<Client>(
+ new URL("../src/components/assistant-ui/use-reasoning-highlight.ts", import.meta.url),
+ {
+ "@/features/chat": { useChatRuntimeStore: {} },
+ "./reasoning-highlight": MESSAGES,
+ "./stream-activity": { createStreamActivity: () => ({ active: () => false }) },
+ },
+ );
+ const drain = (): void => {
+ for (let round = 0; round < 10; round += 1) t.mock.timers.tick(1);
+ };
+ return { client, drain };
+}
+
+async function settleChannels(client: Client): Promise<void> {
+ for (let turn = 0; turn < 50 && client.highlightWorkerState() !== "stalled"; turn += 1) {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ }
+}
+
+async function stallBoot(t: TestContext, client: Client): Promise<void> {
+ t.mock.timers.tick(5_000);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "stalled");
+}
+
+test("a whole-fence request waits out a slow boot and the worker that was late answers it", async (t) => {
+ const { client, drain } = setup(t);
+ const fence: unknown[] = [];
+ const speculation: unknown[] = [];
+ assert.ok(client.requestFullHighlight("<html></html>", "html", (result) => fence.push(result)));
+ assert.ok(client.requestFullHighlight("<p></p>", "html", (result) => speculation.push(result), true));
+ const [booting] = FakeWorker.made;
+ await stallBoot(t, client);
+ drain();
+ assert.deepEqual(speculation, [null], "the speculator hears of the stall, so it can pause");
+ assert.deepEqual(fence, [], "the fence is not failed over to the main thread");
+ const mounted: unknown[] = [];
+ assert.ok(
+ client.requestFullHighlight("<div></div>", "html", (result) => mounted.push(result)),
+ "a fence that mounts during the stall queues on the same worker",
+ );
+ assert.equal(client.requestFullHighlight("<b></b>", "html", () => {}, true), null, "speculation is not sent to a late worker");
+ assert.equal(FakeWorker.made.length, 1);
+ booting.send({ ready: true });
+ assert.equal(client.highlightWorkerState(), "ready");
+ const [waited, , queued] = booting.requests();
+ booting.send({ client: waited, revision: 1, lines: [], result: RESULT });
+ booting.send({ client: queued, revision: 1, lines: [], result: RESULT });
+ assert.deepEqual(fence, [RESULT]);
+ assert.deepEqual(mounted, [RESULT]);
+ t.mock.timers.tick(10_000);
+ assert.equal(booting.terminated, true, "with nothing left waiting, the recovered worker idles out");
+});
+
+test("a whole-fence request cancelled during the stall is never answered and lets the worker idle", async (t) => {
+ const { client, drain } = setup(t);
+ const fence: unknown[] = [];
+ const cancel = client.requestFullHighlight("<html></html>", "html", (result) => fence.push(result));
+ assert.ok(cancel);
+ const [booting] = FakeWorker.made;
+ await stallBoot(t, client);
+ drain();
+ cancel();
+ assert.deepEqual(booting.posted.at(-1), { cancel: booting.requests()[0] });
+ booting.send({ ready: true });
+ booting.send({ client: booting.requests()[0], revision: 1, lines: [], result: RESULT });
+ assert.deepEqual(fence, []);
+ t.mock.timers.tick(10_000);
+ assert.equal(booting.terminated, true);
+});
+
+test("a crashed worker fails every waiting request, whole-fence ones included, and is never rebuilt", (t) => {
+ const { client, drain } = setup(t);
+ const fence: unknown[] = [];
+ client.requestFullHighlight("<html></html>", "html", (result) => fence.push(result));
+ const [crashed] = FakeWorker.made;
+ crashed.onerror?.({ message: "boom", type: "error" });
+ assert.equal(client.highlightWorkerState(), "unavailable");
+ assert.equal(crashed.terminated, true);
+ drain();
+ assert.deepEqual(fence, [null]);
+ assert.equal(client.requestFullHighlight("<html></html>", "html", () => {}), null);
+ assert.equal(FakeWorker.made.length, 1);
+});
+
+test("a worker that fails a whole-fence request answers it once with a failure", (t) => {
+ const { client, drain } = setup(t);
+ const fence: unknown[] = [];
+ client.requestFullHighlight("<html></html>", "html", (result) => fence.push(result));
+ const [ready] = FakeWorker.made;
+ ready.send({ ready: true });
+ const [id] = ready.requests();
+ ready.send({ client: id, revision: 1, lines: [], failed: true });
+ ready.send({ client: id, revision: 1, lines: [], result: RESULT });
+ drain();
+ assert.deepEqual(fence, [null]);
+ assert.equal(client.highlightWorkerState(), "ready");
+});
+
+test("a fence the main thread could tokenize does not wait out a late boot", async (t) => {
+ const { client, drain } = setup(t);
+ const short: unknown[] = [];
+ const long: unknown[] = [];
+ assert.ok(client.requestFullHighlight("<p></p>", "html", (result) => short.push(result), false, false));
+ assert.ok(client.requestFullHighlight("<html></html>", "html", (result) => long.push(result)));
+ await stallBoot(t, client);
+ drain();
+ assert.deepEqual(short, [null], "handed back, so it is tokenized on the main thread as it would be without a worker");
+ assert.deepEqual(long, [], "a fence too long for the main thread keeps waiting");
+ assert.equal(client.requestFullHighlight("<b></b>", "html", () => {}, false, false), null, "while the worker is late, short fences never queue on it");
+});
+
+test("a ready worker that sends nothing while a fence waits is treated as late until it answers", async (t) => {
+ const { client, drain } = setup(t);
+ const short: unknown[] = [];
+ const long: unknown[] = [];
+ client.requestFullHighlight("<p></p>", "html", (result) => short.push(result), false, false);
+ client.requestFullHighlight("<html></html>", "html", (result) => long.push(result));
+ const [silent] = FakeWorker.made;
+ silent.send({ ready: true });
+ t.mock.timers.tick(14_999);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "ready", "fifteen seconds of silence, not less");
+ t.mock.timers.tick(1);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "stalled");
+ drain();
+ assert.deepEqual(short, [null]);
+ assert.deepEqual(long, []);
+ const [, waiting] = silent.requests();
+ silent.send({ client: waiting, revision: 1, lines: [], result: RESULT });
+ assert.equal(client.highlightWorkerState(), "ready", "the first word from the worker ends the stall");
+ assert.deepEqual(long, [RESULT]);
+ assert.equal(silent.terminated, false);
+});
+
+test("a busy worker that keeps answering is never declared silent", async (t) => {
+ const { client } = setup(t);
+ const results: unknown[] = [];
+ for (const source of ["<a></a>", "<b></b>", "<i></i>"]) {
+ client.requestFullHighlight(source, "html", (result) => results.push(result), false, false);
+ }
+ const [busy] = FakeWorker.made;
+ busy.send({ ready: true });
+ for (const id of busy.requests()) {
+ t.mock.timers.tick(10_000);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "ready");
+ busy.send({ client: id, revision: 1, lines: [], result: RESULT });
+ }
+ assert.deepEqual(results, [RESULT, RESULT, RESULT]);
+ t.mock.timers.tick(30_000);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "ready", "with nothing waiting, silence means nothing");
+});
+
+test("a late worker that idles out is replaced, so the next long fence is coloured again", async (t) => {
+ const { client } = setup(t);
+ const cancel = client.requestFullHighlight("<html></html>", "html", () => {});
+ assert.ok(cancel);
+ const [late] = FakeWorker.made;
+ late.send({ ready: true });
+ t.mock.timers.tick(15_000);
+ await settleChannels(client);
+ assert.equal(client.highlightWorkerState(), "stalled");
+ cancel();
+ t.mock.timers.tick(5_000);
+ assert.equal(client.requestFullHighlight("<p></p>", "html", () => {}, false, false), null);
+ t.mock.timers.tick(5_000);
+ assert.equal(late.terminated, true, "with nothing left waiting, the late worker idles out, however many callers it turned away meanwhile");
+ assert.equal(client.highlightWorkerState(), "untested");
+ assert.ok(client.requestFullHighlight("<html></html>", "html", () => {}), "the next long fence gets a worker again");
+ assert.equal(FakeWorker.made.length, 2);
+});
diff --git a/studio/frontend/tests/interface-scale.test.ts b/studio/frontend/tests/interface-scale.test.ts
index ff6b4cd5d76..4527b9dc2e9 100644
--- a/studio/frontend/tests/interface-scale.test.ts
+++ b/studio/frontend/tests/interface-scale.test.ts
@@ -72,6 +72,8 @@ async function load(tauri: boolean) {
define("window", windowStub);
define("document", {
documentElement: {
+ setAttribute: () => undefined,
+ removeAttribute: () => undefined,
style: {
setProperty: (name: string, value: string) => styles.set(name, value),
removeProperty: (name: string) => styles.delete(name),
diff --git a/studio/frontend/tests/interface-zoom.test.ts b/studio/frontend/tests/interface-zoom.test.ts
index 5e09b30d023..39084efc8f3 100644
--- a/studio/frontend/tests/interface-zoom.test.ts
+++ b/studio/frontend/tests/interface-zoom.test.ts
@@ -211,6 +211,17 @@ test("the popup keeps one on-screen size and does not dismiss a modal", () => {
);
assert.match(zoom, /if \(!isTauri \|\| mac\) return;\s*event\.preventDefault\(\);/);
assert.match(zoom, /window\.addEventListener\("wheel", onWheel, \{ passive: false \}\)/);
+ assert.match(zoom, /if \(mac\) \{\s*armWheel\(\);\s*\} else \{/, "only macOS keeps the blocking listener armed, since a pinch reaches its zoom scopes without a keydown; anywhere else a blocking window wheel listener puts every scroll on the main thread, which dropped 40% of desktop frames in a long maths chat");
+ assert.match(zoom, /const onPassiveWheel = \(event: WheelEvent\) => \{\s*if \(wheelArmed \|\| !isZoomWheel\(event\)\) return;\s*modifierHeld = true;\s*syncWheel\(\);\s*\};/, "a Ctrl+wheel whose keydown went to another window arms the blocking listener, so only that first notch scrolls instead of zooming");
+ assert.match(zoom, /window\.addEventListener\("wheel", onPassiveWheel, \{ passive: true \}\);/);
+ assert.match(zoom, /window\.removeEventListener\("wheel", onPassiveWheel\);/);
+ assert.match(zoom, /if \(modifierHeld && !event\.ctrlKey && !event\.metaKey\) \{\s*modifierHeld = false;\s*syncWheel\(\);\s*\}/, "a plain wheel disarms a listener that a missed keyup left armed, so scrolling does not stay on the main thread");
+ assert.match(zoom, /if \(wheelArmed\) return;\s*wheelArmed = true;\s*window\.addEventListener\("wheel", onWheel, \{ passive: false \}\);/, "arming is idempotent, so a Ctrl+wheel zooms once");
+ assert.match(zoom, /modifierHeld = event\.ctrlKey \|\| event\.metaKey;\s*pointerInScope = zoomScopeFor/, "a modifier pressed while another window had focus arms the listener as soon as the pointer moves");
+ assert.match(zoom, /const syncWheel = \(\) => \{\s*if \(modifierHeld \|\| pointerInScope\) armWheel\(\);\s*else disarmWheel\(\);\s*\};/, "in the browser the blocking listener is armed while Ctrl/Meta is held or the pointer is over a zoom scope, so a pinch, which arrives as Ctrl+wheel with no keydown, still reaches the scope");
+ assert.match(zoom, /pointerInScope = zoomScopeFor\(event\.target\) !== null;/);
+ assert.match(zoom, /window\.addEventListener\("pointerover", onPointerOver, true\);/);
+ assert.match(zoom, /window\.removeEventListener\("pointerover", onPointerOver, true\);/);
// Below the shortcut recorder's window capture listener, so recording Mod+= does not zoom.
assert.match(zoom, /document\.addEventListener\("keydown", onKeyDown, true\)/);
assert.match(
@@ -245,7 +256,12 @@ test("the zoom popup takes the find bar's corner", () => {
// Under the startup and closing screens, like the find bar.
assert.match(
css,
- /html:has\(\[aria-modal="true"\], \[data-blocking-screen\]\) \[data-find-bar-layer\],\s*html:has\(\[data-blocking-screen\]\) \.interface-zoom-position \{\s*display: none;/,
+ /html\[data-blocking-screen-open\] \[data-find-bar-layer\],\s*html\[data-blocking-screen-open\] \.interface-zoom-position \{\s*display: none;/,
+ );
+ assert.match(
+ readSrc("lib/document-flag.ts"),
+ /useLayoutEffect\(\(\) => \{\s*if \(!active\) return;\s*return acquireDocumentFlag\(name\);/,
+ "a screen that mounts from a background update painted under the find bar for a frame before a passive effect set the flag",
);
assert.match(provider, /data-blocking-screen=""\s*className="fixed inset-0 z-40 bg-background"/);
assert.match(
diff --git a/studio/frontend/tests/link-repair-memo.test.ts b/studio/frontend/tests/link-repair-memo.test.ts
new file mode 100644
index 00000000000..c686fdcc39f
--- /dev/null
+++ b/studio/frontend/tests/link-repair-memo.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Module = {
+ hasIncompleteLinkRepair: (source: string, repaired?: string) => boolean;
+ repairStreamingMarkdown: (source: string) => string;
+};
+
+function harness() {
+ let calls = 0;
+ const module = loadWithStubs<Module>(
+ new URL("../src/components/assistant-ui/streaming-render-schedule.ts", import.meta.url),
+ {
+ remend: {
+ default: (source: string) => {
+ calls += 1;
+ const open = source.lastIndexOf("[");
+ return open !== -1 && !source.slice(open).includes("]")
+ ? `${source}](streamdown:incomplete-link)`
+ : source;
+ },
+ },
+ streamdown: {},
+ "../../lib/parse-markdown-blocks.ts": { parseMarkdownIntoBlocks: (s: string) => [s] },
+ },
+ );
+ return { module, remendCalls: () => calls };
+}
+
+test("a settled body pays for the remend pass once per distinct text", () => {
+ const { module, remendCalls } = harness();
+ assert.equal(module.hasIncompleteLinkRepair("See [example"), true);
+ assert.equal(module.hasIncompleteLinkRepair("See [example"), true);
+ assert.equal(module.hasIncompleteLinkRepair(["See ", "[example"].join("")), true);
+ assert.equal(remendCalls(), 1);
+ assert.equal(module.hasIncompleteLinkRepair("See [example](https://example.com)"), false);
+ assert.equal(module.hasIncompleteLinkRepair("See [example](https://example.com)"), false);
+ assert.equal(remendCalls(), 2);
+});
+
+test("a bracket-free body and the two-argument streaming form never touch remend or the memo", () => {
+ const { module, remendCalls } = harness();
+ assert.equal(module.hasIncompleteLinkRepair("plain prose"), false);
+ assert.equal(module.hasIncompleteLinkRepair("tail [x", "tail [x](streamdown:incomplete-link)"), true);
+ assert.equal(module.hasIncompleteLinkRepair("tail [x", "tail [x"), false);
+ assert.equal(remendCalls(), 0);
+ assert.equal(module.hasIncompleteLinkRepair("tail [x"), true);
+ assert.equal(remendCalls(), 1);
+});
+
+test("repairStreamingMarkdown does not fill the memo with streaming prefixes", () => {
+ const { module, remendCalls } = harness();
+ module.repairStreamingMarkdown("See [exa");
+ const before = remendCalls();
+ module.hasIncompleteLinkRepair("See [exa");
+ assert.equal(remendCalls(), before + 1);
+});
+
+test("the memo keeps at most 256 bodies, dropping the oldest unrefreshed one", () => {
+ const { module, remendCalls } = harness();
+ module.hasIncompleteLinkRepair("[first");
+ for (let i = 0; i < 255; i += 1) module.hasIncompleteLinkRepair(`[filler ${i}`);
+ module.hasIncompleteLinkRepair("[first");
+ module.hasIncompleteLinkRepair("[one more");
+ const before = remendCalls();
+ module.hasIncompleteLinkRepair("[first");
+ assert.equal(remendCalls(), before);
+ module.hasIncompleteLinkRepair("[filler 0");
+ assert.equal(remendCalls(), before + 1);
+});
+
+test("the memo holds at most 4 Mi characters of text and never retains an oversized body", () => {
+ const { module, remendCalls } = harness();
+ const big = `[${"x".repeat(3_000_000)}`;
+ const other = `[${"y".repeat(2_000_000)}`;
+ module.hasIncompleteLinkRepair(big);
+ module.hasIncompleteLinkRepair(other);
+ const before = remendCalls();
+ module.hasIncompleteLinkRepair(other);
+ assert.equal(remendCalls(), before);
+ module.hasIncompleteLinkRepair(big);
+ assert.equal(remendCalls(), before + 1);
+ const huge = `[${"z".repeat(4_194_304)}`;
+ module.hasIncompleteLinkRepair(huge);
+ module.hasIncompleteLinkRepair(huge);
+ assert.equal(remendCalls(), before + 3);
+});
diff --git a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
index b664382f3b2..84f04792d40 100644
--- a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
+++ b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
@@ -111,6 +111,10 @@ function realAuthFetch(port: number): AuthApi {
function realLoadModel(auth: AuthApi): ChatApi {
return loadWithStubs<ChatApi>(new URL("../src/features/chat/api/chat-api.ts", import.meta.url), {
"./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
"@/features/auth": { authFetch: auth.authFetch },
"./padded-response": paddedResponse,
"@/lib/format-fastapi-error": {
diff --git a/studio/frontend/tests/load-warning-toast.test.ts b/studio/frontend/tests/load-warning-toast.test.ts
index 36a779dae07..4e6b5b8a75a 100644
--- a/studio/frontend/tests/load-warning-toast.test.ts
+++ b/studio/frontend/tests/load-warning-toast.test.ts
@@ -31,6 +31,10 @@ function chatApi(body: Record<string, unknown>) {
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
"./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
"@/features/auth": {
authFetch: async () => ({
status: 200,
diff --git a/studio/frontend/tests/low-device-scale.test.ts b/studio/frontend/tests/low-device-scale.test.ts
new file mode 100644
index 00000000000..0fb7afd1d9a
--- /dev/null
+++ b/studio/frontend/tests/low-device-scale.test.ts
@@ -0,0 +1,150 @@
+// 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 {
+ LOW_DEVICE_SCALE_ATTRIBUTE,
+ THREAD_SCROLLBAR_GUTTER_PROPERTY,
+ isLowDeviceScale,
+ watchLowDeviceScale,
+ watchThreadScrollbarGutter,
+} from "../src/app/low-device-scale.ts";
+
+type Query = {
+ dppx: number;
+ listeners: Set<() => void>;
+ addEventListener: (type: "change", listener: () => void) => void;
+ removeEventListener: (type: "change", listener: () => void) => void;
+};
+
+function fakeWorld(initialRatio: number, initialZoom: number) {
+ let ratio = initialRatio;
+ let zoom = initialZoom;
+ const queries: Query[] = [];
+ const zoomListeners = new Set<() => void>();
+ const attributes = new Set<string>();
+ const source = {
+ devicePixelRatio: () => ratio,
+ matchResolution: (dppx: number) => {
+ const query: Query = {
+ dppx,
+ listeners: new Set(),
+ addEventListener: (_type, listener) => query.listeners.add(listener),
+ removeEventListener: (_type, listener) => query.listeners.delete(listener),
+ };
+ queries.push(query);
+ return query;
+ },
+ };
+ const root = {
+ toggleAttribute: (name: string, force: boolean) => {
+ if (force) attributes.add(name);
+ else attributes.delete(name);
+ return force;
+ },
+ removeAttribute: (name: string) => {
+ attributes.delete(name);
+ },
+ };
+ return {
+ source,
+ root,
+ flagged: () => attributes.has(LOW_DEVICE_SCALE_ATTRIBUTE),
+ live: () => queries.filter((query) => query.listeners.size > 0),
+ zoomListeners,
+ subscribeInterfaceZoom: (listener: () => void) => {
+ zoomListeners.add(listener);
+ return () => zoomListeners.delete(listener);
+ },
+ interfaceZoom: () => zoom,
+ changeRatio(next: number) {
+ ratio = next;
+ for (const query of queries.filter((entry) => entry.listeners.size > 0)) {
+ for (const listener of [...query.listeners]) listener();
+ }
+ },
+ changeZoom(next: number) {
+ zoom = next;
+ for (const listener of [...zoomListeners]) listener();
+ },
+ };
+}
+
+test("the device scale is the pixel ratio with WebView2's own page zoom divided out", () => {
+ assert.equal(isLowDeviceScale(1, 1), true);
+ assert.equal(isLowDeviceScale(1.25, 1), true);
+ assert.equal(isLowDeviceScale(1.5, 1), false);
+ assert.equal(isLowDeviceScale(2.25, 1.5), false);
+ assert.equal(isLowDeviceScale(1.5, 1.5), true);
+ assert.equal(isLowDeviceScale(1.875, 1.25), false);
+ assert.equal(isLowDeviceScale(1, 0), true);
+});
+
+test("the flag follows the display and the zoom, and goes with its watcher", () => {
+ const world = fakeWorld(1.5, 1);
+ const stop = watchLowDeviceScale({
+ source: world.source,
+ interfaceZoom: world.interfaceZoom,
+ subscribeInterfaceZoom: world.subscribeInterfaceZoom,
+ root: world.root,
+ });
+ assert.equal(world.flagged(), false);
+
+ world.changeRatio(1);
+ assert.equal(world.flagged(), true, "moved to a 100% display");
+ assert.equal(world.live().length, 1, "one resolution query stays armed for the ratio now in force");
+ assert.equal(world.live()[0]?.dppx, 1);
+
+ world.changeRatio(1.5);
+ world.changeZoom(1.5);
+ assert.equal(world.flagged(), true, "a 150% interface zoom on a 100% display still reads 1.5 dppx");
+
+ world.changeRatio(2.25);
+ assert.equal(world.flagged(), false, "back on the 150% display with the zoom kept");
+
+ stop();
+ assert.equal(world.flagged(), false);
+ assert.equal(world.live().length, 0);
+ assert.equal(world.zoomListeners.size, 0);
+});
+
+test("a watcher starting on a low-scale display flags it before the first change", () => {
+ const world = fakeWorld(1.25, 1);
+ const stop = watchLowDeviceScale({
+ source: world.source,
+ interfaceZoom: world.interfaceZoom,
+ subscribeInterfaceZoom: world.subscribeInterfaceZoom,
+ root: world.root,
+ });
+ assert.equal(world.flagged(), true);
+ stop();
+});
+
+test("the thread gutter is the measured thin bar, measured again whenever the pixel ratio moves", () => {
+ const world = fakeWorld(1, 1);
+ const properties = new Map<string, string>();
+ const root = {
+ style: {
+ setProperty: (name: string, value: string) => void properties.set(name, value),
+ removeProperty: (name: string) => {
+ const value = properties.get(name) ?? "";
+ properties.delete(name);
+ return value;
+ },
+ },
+ };
+ let thickness = 10;
+ const stop = watchThreadScrollbarGutter({ source: world.source, measure: () => thickness, style: root.style });
+ assert.equal(properties.get(THREAD_SCROLLBAR_GUTTER_PROPERTY), "10px");
+
+ thickness = 8;
+ world.changeRatio(1.25);
+ assert.equal(properties.get(THREAD_SCROLLBAR_GUTTER_PROPERTY), "8px", "a 125% browser or desktop zoom keeps the bar's device size");
+ assert.equal(world.live().length, 1);
+
+ stop();
+ assert.equal(properties.has(THREAD_SCROLLBAR_GUTTER_PROPERTY), false, "the stylesheet's default is back once the watcher goes");
+ assert.equal(world.live().length, 0);
+});
diff --git a/studio/frontend/tests/markdown-streaming-scheduling.test.ts b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
index 17f1c8b6aa9..00c48832536 100644
--- a/studio/frontend/tests/markdown-streaming-scheduling.test.ts
+++ b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
@@ -105,8 +105,12 @@ test("token updates keep Streamdown's expensive configuration props stable", ()
const streamdown = findChatStreamdown();
assert.ok(streamdown, "chat <Streamdown> is missing");
+ assert.equal(
+ jsxAttribute(streamdown, "plugins")?.initializer?.getText(source).replace(/\s+/g, " "),
+ "{ highlightCode ? STREAMDOWN_PLUGINS : STREAMDOWN_PLAIN_CODE_PLUGINS }",
+ "plugins must retain object identity while raw tokens arrive",
+ );
for (const [attribute, constant] of [
- ["plugins", "STREAMDOWN_PLUGINS"],
["controls", "STREAMDOWN_CONTROLS"],
["shikiTheme", "STREAMDOWN_SHIKI_THEME"],
]) {
@@ -118,7 +122,7 @@ test("token updates keep Streamdown's expensive configuration props stable", ()
}
});
-test("stream updates are paint-coalesced without a time or length throttle", () => {
+test("stream updates are paint-coalesced with a cost-aware cadence and no length throttle", () => {
const markdownSource = source.getText();
const hookStart = markdownSource.indexOf(
"function useCoalescedStreamingText",
@@ -129,6 +133,17 @@ test("stream updates are paint-coalesced without a time or length throttle", ()
assert.ok(hook.includes("requestAnimationFrame"));
assert.ok(!hook.includes("setTimeout"));
+ assert.match(hook, /if \(frameTime > frameAtRef\.current\) \{\s*frameIntervalRef\.current = Math\.min\(\s*frameIntervalRef\.current,\s*frameTime - frameAtRef\.current,\s*\);\s*frameAtRef\.current = frameTime;\s*\}/, "the shortest gap between frames is the display's frame interval");
+ assert.match(
+ hook,
+ /frameTime - renderedAtRef\.current <\s*Math\.max\(\s*16 - Math\.min\(frameIntervalRef\.current, 16\) \/ 2,\s*STREAMING_RENDER_DUTY \* costRef\.current,\s*\)/,
+ "frame times come in whole frames, so the 16 ms floor allows half a frame or a 75, 90 or 144 Hz display renders every second or third frame",
+ );
+ assert.match(
+ hook,
+ /afterFrame\(\(\) => \{\s*const startedAt = performance\.now\(\);\s*flushSync\(\(\) => setDisplayed\(pendingRef\.current\)\);\s*costRef\.current = performance\.now\(\) - startedAt;\s*\}\);/,
+ "the cost is the render alone, in the task after the frame, so an unrelated long task is not charged to the stream and the text resumes as soon as it ends",
+ );
// A running message can be replaced rather than appended to, as the audio
// path does when it swaps its placeholder for the player, so holding the last
diff --git a/studio/frontend/tests/math-block-containment-wiring.test.ts b/studio/frontend/tests/math-block-containment-wiring.test.ts
index 72ffc8d3bc3..90ad81ead8d 100644
--- a/studio/frontend/tests/math-block-containment-wiring.test.ts
+++ b/studio/frontend/tests/math-block-containment-wiring.test.ts
@@ -146,13 +146,13 @@ test("the rule is armed by nothing except that attribute", () => {
"the code-block flicker rule is still there",
);
- // Two gated copies of `auto`, one per population. A third, ungated one would turn the flag
- // into decoration.
+ // Two gated copies of `auto`, one per population, plus the engine-gated one on windowed code
+ // bodies. An ungated one would turn the flag into decoration.
const declarations = INDEX_CSS.split("content-visibility: auto;").length - 1;
assert.equal(
declarations,
- 2,
- "exactly two `content-visibility: auto` declarations in the whole stylesheet",
+ 4,
+ "exactly four `content-visibility: auto` declarations in the whole stylesheet",
);
const gateAt = INDEX_CSS.indexOf(`html[${MATH_BLOCK_CONTAINMENT_ATTRIBUTE}=`);
assert.ok(gateAt >= 0, "PRECONDITION: the gate is present");
@@ -234,8 +234,8 @@ test("a print turns the containment off, for both populations", () => {
// still there to override. Without this the block above could be defending nothing.
assert.equal(
INDEX_CSS.split("content-visibility: auto;").length - 1,
- 2,
- "PRECONDITION: the two gated declarations this print block exists to switch off",
+ 4,
+ "PRECONDITION: the gated declarations this print block and the two engine-gated ones switch off",
);
});
diff --git a/studio/frontend/tests/message-derived.test.ts b/studio/frontend/tests/message-derived.test.ts
index da376a47e8b..5670027b636 100644
--- a/studio/frontend/tests/message-derived.test.ts
+++ b/studio/frontend/tests/message-derived.test.ts
@@ -6,6 +6,7 @@ import test from "node:test";
import {
compactionNoticeMessageIds,
memoOnArray,
+ memoOnArrayByKey,
partsHaveNonEmptyText,
partsHaveRenderableRenderHtmlTool,
partsPrecedingText,
@@ -20,6 +21,7 @@ import {
precedingTextForMessagePart,
searchImagesSignature,
} from "../src/features/chat/search-images/search-images.ts";
+import { readSrc } from "./helpers/kit.ts";
test("memoOnArray computes once per array and again for a new array", () => {
let calls = 0;
@@ -193,3 +195,33 @@ test("compaction notice ids match the per-message walk", () => {
assert.equal(compactionNoticeMessageIds(messages), ids);
assert.notEqual(compactionNoticeMessageIds([...messages]), ids);
});
+
+test("memoOnArrayByKey caches per array and per key", () => {
+ const messages = [{ id: "a" }, { id: "b" }];
+ let computed = 0;
+ const first = memoOnArrayByKey(messages, "k", () => {
+ computed += 1;
+ return new Set(["a"]);
+ });
+ const again = memoOnArrayByKey(messages, "k", () => {
+ computed += 1;
+ return new Set(["b"]);
+ });
+ assert.equal(first, again);
+ assert.equal(computed, 1);
+ const other = memoOnArrayByKey(messages, "other", () => {
+ computed += 1;
+ return 1;
+ });
+ assert.equal(other, 1);
+ assert.equal(computed, 2);
+ assert.notEqual(memoOnArrayByKey([...messages], "k", () => new Set()), first, "a new array computes anew");
+});
+
+test("a message with search images lists its texts while it runs, so a card placed later stops an earlier part repeating it", () => {
+ assert.match(
+ readSrc("components/assistant-ui/markdown-text.tsx"),
+ /const messageTextKey = useAuiState\(\(\{ message \}\) =>\s*allowSearchImages && partsSearchImagesSignature\(message\.parts\) !== ""\s*\? partsTextKey\(message\.parts\)\s*: "\[\]",\s*\);/,
+ "without images the texts change nothing, so only then may a running reply skip serialising them",
+ );
+});
diff --git a/studio/frontend/tests/modal-open-restyle.test.ts b/studio/frontend/tests/modal-open-restyle.test.ts
index e1c9b25de87..5f4a98513a8 100644
--- a/studio/frontend/tests/modal-open-restyle.test.ts
+++ b/studio/frontend/tests/modal-open-restyle.test.ts
@@ -21,7 +21,7 @@ function rules(css: string): [string, string][] {
]);
}
-test("dark menus find their dialog or picker by sibling, not body:has()", async () => {
+test("dark menus take their dialog or picker glow from an attribute, not a sibling or body:has()", async () => {
const css = rules(await readSrcAsync("index.css"));
const context = css.filter(
([, body]) =>
@@ -30,7 +30,8 @@ test("dark menus find their dialog or picker by sibling, not body:has()", async
assert.ok(context.length >= 3, "the glow and lift context rules are present");
for (const [selector] of context) {
assert.doesNotMatch(selector, /body:has\(/, selector);
- assert.match(selector, /~ \*/, selector);
+ assert.doesNotMatch(selector, /[~+]/, selector);
+ assert.match(selector, /\[data-dropdown-glow/, selector);
}
});
diff --git a/studio/frontend/tests/model-config-popover-scroller.test.ts b/studio/frontend/tests/model-config-popover-scroller.test.ts
index e9da3b33d0b..1ce3eafe8ae 100644
--- a/studio/frontend/tests/model-config-popover-scroller.test.ts
+++ b/studio/frontend/tests/model-config-popover-scroller.test.ts
@@ -34,9 +34,9 @@ test("the popover surface clips and caps, so it never scrolls itself", () => {
test("the config page gets its own scroller inside that surface", () => {
assert.ok(
SELECTOR.includes(
- '<div className="min-h-0 w-full overflow-y-auto px-4 pt-4 pb-4">',
+ '<div className="min-h-0 w-full overflow-y-auto px-4 pt-4 pb-4 [scrollbar-gutter:stable]">',
),
- "the inner box scrolls and carries the padding the surface gave up",
+ "the inner box scrolls, carries the padding the surface gave up, and reserves its scrollbar gutter: on an auto gutter the custom scrollbar re-laid out the whole page twice a frame while a slider was dragged",
);
});
diff --git a/studio/frontend/tests/panel-drag-overlay.test.ts b/studio/frontend/tests/panel-drag-overlay.test.ts
new file mode 100644
index 00000000000..bec50e7044d
--- /dev/null
+++ b/studio/frontend/tests/panel-drag-overlay.test.ts
@@ -0,0 +1,116 @@
+// 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 { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+type FakeElement = {
+ attributes: Map<string, string>;
+ style: Record<string, string>;
+ setAttribute(name: string, value: string): void;
+ remove(): void;
+};
+
+const htmlAttributes = new Map<string, string>();
+const body: FakeElement[] = [];
+
+function element(): FakeElement {
+ const self: FakeElement = {
+ attributes: new Map(),
+ style: {},
+ setAttribute: (name, value) => self.attributes.set(name, value),
+ remove: () => {
+ const at = body.indexOf(self);
+ if (at >= 0) body.splice(at, 1);
+ },
+ };
+ return self;
+}
+
+Object.assign(globalThis, {
+ document: {
+ documentElement: {
+ setAttribute: (name: string, value: string) => htmlAttributes.set(name, value),
+ removeAttribute: (name: string) => htmlAttributes.delete(name),
+ },
+ createElement: () => element(),
+ body: { appendChild: (child: FakeElement) => body.push(child) },
+ querySelector: (selector: string) =>
+ body.find(
+ (child) =>
+ `[data-slot="${child.attributes.get("data-slot")}"]` === selector,
+ ) ?? null,
+ },
+});
+
+registerBundlerResolver();
+const { acquireDragOverlay, armPanelDrag, releaseDragOverlay, panelDragInProgress } =
+ await import("../src/components/ui/panel-drag-overlay.ts");
+
+test("a held drag overlay marks the drag in progress until its last owner lets go", () => {
+ assert.equal(panelDragInProgress(), false);
+ acquireDragOverlay();
+ assert.equal(panelDragInProgress(), true);
+ assert.equal(htmlAttributes.get("data-panel-resizing"), "true");
+ assert.equal(body.length, 1);
+ assert.equal(body[0].style.pointerEvents, "auto");
+
+ acquireDragOverlay();
+ assert.equal(body.length, 1, "nested owners share one overlay");
+ releaseDragOverlay();
+ assert.equal(panelDragInProgress(), true);
+ assert.equal(body.length, 1);
+
+ releaseDragOverlay();
+ assert.equal(panelDragInProgress(), false);
+ assert.equal(body.length, 0);
+ assert.equal(htmlAttributes.has("data-panel-resizing"), false);
+
+ releaseDragOverlay();
+ assert.equal(panelDragInProgress(), false, "an unmatched release is a no-op");
+});
+
+test("a native browser page yields to its snapshot while any panel is dragged", () => {
+ acquireDragOverlay();
+ const slot = body[0].attributes.get("data-slot") ?? "";
+ releaseDragOverlay();
+ assert.ok(slot.endsWith("-overlay"));
+ assert.match(
+ readSrc("features/browser/native-view.ts"),
+ /const OVERLAY_SELECTOR =\s*'[^']*\[data-slot\$="-overlay"\]/,
+ "the overlay counts as covering the page, so the page shows a snapshot the DOM clips instead of a native view that cannot follow the drag",
+ );
+ for (const [file, pattern] of [
+ ["components/ui/panel-resize-handle.tsx", /acquireDragOverlay\(\)/],
+ ["features/chat/chat-page.tsx", /armPanelDrag\(event\.clientX\);/],
+ ] as const) {
+ assert.match(readSrc(file), pattern, file);
+ }
+});
+
+test("a split press marks the drag at once but covers the page only once the pointer travels", () => {
+ const click = armPanelDrag(100);
+ assert.equal(htmlAttributes.get("data-panel-resizing"), "true", "the library blanks both panels on press, so the thread's wrapper must already keep its pointer events");
+ click.move(102);
+ assert.equal(body.length, 0, "a click hid a native browser page behind its snapshot and showed it again");
+ assert.equal(panelDragInProgress(), false);
+ click.release();
+ assert.equal(htmlAttributes.has("data-panel-resizing"), false);
+
+ const drag = armPanelDrag(100);
+ drag.move(96);
+ assert.equal(body.length, 1);
+ assert.equal(panelDragInProgress(), true);
+ acquireDragOverlay();
+ drag.release();
+ drag.release();
+ assert.equal(body.length, 1, "another owner keeps the overlay");
+ assert.equal(htmlAttributes.get("data-panel-resizing"), "true");
+ releaseDragOverlay();
+ assert.equal(body.length, 0);
+ assert.equal(htmlAttributes.has("data-panel-resizing"), false);
+ drag.move(50);
+ assert.equal(body.length, 0, "a released press never takes the overlay");
+});
diff --git a/studio/frontend/tests/panel-resize-handle-capture.test.ts b/studio/frontend/tests/panel-resize-handle-capture.test.ts
new file mode 100644
index 00000000000..9ad1df73213
--- /dev/null
+++ b/studio/frontend/tests/panel-resize-handle-capture.test.ts
@@ -0,0 +1,26 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("a drag that loses pointer capture without a pointerup still ends, so its overlay cannot swallow the UI", () => {
+ const source = readSrc("components/ui/panel-resize-handle.tsx");
+ assert.match(source, /onPointerCancel=\{endDrag\}/);
+ assert.match(
+ source,
+ /onLostPointerCapture=\{\(\) => \{\s*if \(dragRef\.current\) endDrag\(\)\s*\}\}/,
+ "only a drag still in progress: a normal pointerup has already ended it, and the capture it releases is lost right after",
+ );
+ const up = source.slice(
+ source.indexOf("const handlePointerUp"),
+ source.indexOf("const handleKeyDown"),
+ );
+ assert.ok(
+ up.indexOf("releasePointerCapture") < up.indexOf("endDrag()"),
+ "pointerup releases capture before ending the drag, so the commit below reads the drag it captured first",
+ );
+ assert.match(up, /const drag = dragRef\.current/);
+});
diff --git a/studio/frontend/tests/panel-separator-hover.test.ts b/studio/frontend/tests/panel-separator-hover.test.ts
new file mode 100644
index 00000000000..3f8c7a71fbc
--- /dev/null
+++ b/studio/frontend/tests/panel-separator-hover.test.ts
@@ -0,0 +1,34 @@
+// 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 { readSrc, readText } from "./helpers/kit.ts";
+
+test("the chat split never installs the library's universal cursor rule", () => {
+ const page = readSrc("features/chat/chat-page.tsx");
+ assert.match(page, /<ResizablePanelGroup[\s\S]*?\bdisableCursor\b[\s\S]*?<ResizablePanel\b/);
+ assert.equal(readSrc("index.css").includes("data-chat-split-resizing"), false, "no whole-document cursor rule: on WebKit toggling one restyles every element, 0.2-0.3 s on a long thread");
+ assert.match(page, /onPointerDown=\{\(event\) => \{\s*if \(event\.button !== 0\) return;\s*const drag = armPanelDrag\(event\.clientX\);/, "one overlay owns the cursor and the hit test once the press moves, the same one the sidebar and Run settings drags hold");
+ assert.match(page, /const release = \(\) => \{[\s\S]*?drag\.release\(\);[\s\S]*?\};/);
+ assert.match(page, /window\.addEventListener\("pointercancel", release\);\s*window\.addEventListener\("pointermove", moved\);/, "a drag whose release never reaches the page, because the window lost the pointer, still removes the overlay");
+ assert.equal(page.includes('window.addEventListener("blur", release)'), false, "the library keeps dragging through a blur, so ending here would forget the width the drag ends at");
+ assert.match(page, /const moved = \(move: PointerEvent\) => \{\s*if \(move\.buttons === 0\) release\(\);\s*else drag\.move\(move\.clientX\);\s*\};/, "the same buttons === 0 check react-resizable-panels uses to end its own drag");
+});
+
+test("the handle is out of the hit test exactly while it is 0 px wide", () => {
+ const page = readSrc("features/chat/chat-page.tsx");
+ const open = page.indexOf("<ResizableHandle");
+ const handle = page.slice(open, page.indexOf("/>", open));
+ assert.match(handle, /disabled=\{!artifactLayoutActive \|\| browserFullView\}/);
+ assert.match(handle, /\(!artifactLayoutActive \|\| browserFullView\) &&\s*"pointer-events-none -ml-0 -mr-0 w-0"/, "the width collapse and the hit test read the same condition");
+ assert.equal((handle.match(/artifactLayoutActive/g) ?? []).length, 2);
+});
+
+test("react-resizable-panels still exposes the props the fix rests on", () => {
+ const dts = readText("../node_modules/react-resizable-panels/dist/react-resizable-panels.d.ts");
+ assert.match(dts, /disableCursor\?: boolean \| undefined;/);
+ assert.match(dts, /disableDoubleClick\?: boolean/);
+ assert.match(dts, /export declare type SeparatorProps[\s\S]*?disabled\?: boolean \| undefined;/);
+});
diff --git a/studio/frontend/tests/panel-width-subscriptions.test.ts b/studio/frontend/tests/panel-width-subscriptions.test.ts
new file mode 100644
index 00000000000..7f2878378ee
--- /dev/null
+++ b/studio/frontend/tests/panel-width-subscriptions.test.ts
@@ -0,0 +1,98 @@
+// 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 type { PanelWidthStore } from "../src/hooks/use-panel-width.ts";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+function setup() {
+ const fake = installLocalStorageFake();
+ window.innerWidth = 1000;
+ let scale = 1;
+ const scaleListeners = new Set<() => void>();
+ let cleanups: (() => void)[] = [];
+ let values: unknown[] = [];
+ const { createPanelWidthStore } = loadWithStubs<{
+ createPanelWidthStore: (options: {
+ key: string;
+ min: number;
+ max: number;
+ fallback: number;
+ }) => PanelWidthStore;
+ }>(new URL("../src/hooks/use-panel-width.ts", import.meta.url), {
+ react: {
+ useCallback: (callback: unknown) => callback,
+ useSyncExternalStore: (subscribe: (cb: () => void) => () => void, read: () => unknown) => {
+ const target = values;
+ const index = target.length;
+ target.push(read());
+ cleanups.push(subscribe(() => { target[index] = read(); }));
+ return read();
+ },
+ },
+ "../lib/layout-scale.ts": {
+ layoutScale: () => scale,
+ subscribeLayoutScale: (callback: () => void) => {
+ scaleListeners.add(callback);
+ return () => scaleListeners.delete(callback);
+ },
+ },
+ });
+ const store = createPanelWidthStore({ key: "panel", min: 200, max: 600, fallback: 480 });
+ return {
+ ...fake,
+ mount() {
+ cleanups = [];
+ values = [];
+ const actions = store.useWidth();
+ const unmount = cleanups;
+ return { actions, values, unmount: () => unmount.forEach((stop) => stop()) };
+ },
+ setScale(next: number) {
+ scale = next;
+ for (const callback of scaleListeners) callback();
+ },
+ };
+}
+
+test("unmounting one panel consumer preserves resizing and scaling for the others", () => {
+ const app = setup();
+ const titlebar = app.mount();
+ const sidebar = app.mount();
+ titlebar.unmount();
+ window.innerWidth = 800;
+ assert.equal(app.fireWindowEvent("resize", {}), 1);
+ assert.deepEqual(sidebar.values, [320, 320, 480, 1]);
+ app.setScale(2);
+ assert.deepEqual(sidebar.values, [200, 200, 480, 2]);
+ sidebar.unmount();
+ assert.equal(app.fireWindowEvent("resize", {}), 0);
+ window.innerWidth = 1500;
+ app.setScale(1);
+ const reopened = app.mount();
+ assert.equal(reopened.actions.width, 480);
+ assert.equal(reopened.actions.max, 600);
+ reopened.unmount();
+});
+
+test("cross-window width updates notify every consumer and preserve the uncapped preference", () => {
+ const app = setup();
+ const first = app.mount();
+ const second = app.mount();
+ app.storage.setItem("panel", "560");
+ assert.equal(app.fireWindowEvent("storage", { key: "panel" }), 1);
+ assert.deepEqual(first.values, [400, 400, 560, 1]);
+ assert.deepEqual(second.values, first.values);
+ window.innerWidth = 1500;
+ app.fireWindowEvent("resize", {});
+ assert.deepEqual(second.values, [560, 600, 560, 1]);
+ first.unmount();
+ app.storage.removeItem("panel");
+ app.fireWindowEvent("storage", { key: null });
+ assert.deepEqual(second.values, [480, 600, 480, 1]);
+ second.unmount();
+ assert.equal(app.fireWindowEvent("storage", { key: "panel" }), 0);
+});
diff --git a/studio/frontend/tests/provider-max-output-tokens.test.ts b/studio/frontend/tests/provider-max-output-tokens.test.ts
index 039e1a2742e..6d94eb83135 100644
--- a/studio/frontend/tests/provider-max-output-tokens.test.ts
+++ b/studio/frontend/tests/provider-max-output-tokens.test.ts
@@ -97,11 +97,11 @@ test("preset application clamps live Max Tokens to the active external cap", ()
);
assert.match(
settings,
- /onParamsChange\(applyPresetParamsWithinCurrentLimits\(p\),\s*\{\s*minPChoiceEdited: true,\s*\}\)/,
+ /setParams\(applyPresetParamsWithinCurrentLimits\(p\),\s*\{\s*minPChoiceEdited: true,\s*\}\)/,
);
assert.match(
settings,
- /onParamsChange\(\s*applyPresetParamsWithinCurrentLimits\(fallbackPreset\),\s*\{ minPChoiceEdited: true \},\s*\)/,
+ /setParams\(\s*applyPresetParamsWithinCurrentLimits\(fallbackPreset\),\s*\{ minPChoiceEdited: true \},\s*\)/,
);
});
@@ -113,6 +113,6 @@ test("lowering an active external cap immediately clamps live Max Tokens", () =>
// writes back through the preset-source bookkeeping.
assert.match(
settings,
- /useEffect\(\(\) => \{\s*const clampedMaxTokens = resolveExternalMaxTokensClamp\(\{[\s\S]*?settingsHydrated,[\s\S]*?hasActiveExternalProvider: activeExternalProvider != null,[\s\S]*?isExternalModel,[\s\S]*?maxTokens: params\.maxTokens,[\s\S]*?maxTokensMax,[\s\S]*?\}\);[\s\S]*?if \(clampedMaxTokens == null\) \{[\s\S]*?maxTokens: clampedMaxTokens[\s\S]*?setActivePresetSource\(nextSource\)[\s\S]*?onParamsChange\(nextParams\)/,
+ /useEffect\(\(\) => \{\s*const clampedMaxTokens = resolveExternalMaxTokensClamp\(\{[\s\S]*?settingsHydrated,[\s\S]*?hasActiveExternalProvider: activeExternalProvider != null,[\s\S]*?isExternalModel,[\s\S]*?maxTokens: params\.maxTokens,[\s\S]*?maxTokensMax,[\s\S]*?\}\);[\s\S]*?if \(clampedMaxTokens == null\) \{[\s\S]*?maxTokens: clampedMaxTokens[\s\S]*?setActivePresetSource\(nextSource\)[\s\S]*?setParams\(nextParams\)/,
);
});
diff --git a/studio/frontend/tests/rag-refresh-sequencing.test.ts b/studio/frontend/tests/rag-refresh-sequencing.test.ts
index 120b27925c3..b7c77ebd83e 100644
--- a/studio/frontend/tests/rag-refresh-sequencing.test.ts
+++ b/studio/frontend/tests/rag-refresh-sequencing.test.ts
@@ -720,7 +720,12 @@ test("a failed project lookup leaves the scope unresolved", () => {
// Nothing records a null project on the failure path any more.
assert.doesNotMatch(
THREAD_DOCUMENTS_BAR,
- /setResolved\(\{ threadId, trigger: activeProjectId, projectId: null \}\);/,
+ /record\(null, 0\)|setResolved\(\{ threadId, projectId: null/,
+ );
+ assert.match(
+ THREAD_DOCUMENTS_BAR,
+ /\} catch \{\s*if \(cancelled \|\| announced\) return;\s*await new Promise/,
+ "a failed read records nothing and retries",
);
// And unresolved still disables the attach controls.
assert.match(THREAD_DOCUMENTS_BAR, /const projectUnresolved = threadProjectId === undefined;/);
diff --git a/studio/frontend/tests/rag-thread-initialization.test.ts b/studio/frontend/tests/rag-thread-initialization.test.ts
index 8ae60b3abfb..067950f8cf2 100644
--- a/studio/frontend/tests/rag-thread-initialization.test.ts
+++ b/studio/frontend/tests/rag-thread-initialization.test.ts
@@ -15,6 +15,13 @@ const OUTGOING_ID = "__LOCALID_outgoing";
const flush = () => new Promise<void>((resolve) => setImmediate(resolve));
type Scope = { type: "thread"; threadId: string };
+type AnnouncedRow = {
+ id: string;
+ projectId?: string | null;
+ updatedAt?: number;
+ modifiedAt?: number | null;
+};
+
function harness(
options: {
propId?: string | null;
@@ -24,6 +31,7 @@ function harness(
persist?: Promise<void>;
itemId?: string;
storedIds?: string[];
+ row?: AnnouncedRow;
ragSource?: { type: "thread" } | { type: "kb"; kbId: string };
} = {},
) {
@@ -43,6 +51,9 @@ function harness(
}> = [];
const dismissed: number[] = [];
const adopted: string[] = [];
+ let threadReads = 0;
+ const announce: Array<(detail: { thread?: AnnouncedRow }) => void> = [];
+ const scopes: unknown[] = [];
const itemId = options.itemId ?? ID;
const storedIds = new Set(options.storedIds ?? []);
const state = {
@@ -115,7 +126,10 @@ function harness(
return [
slots[index],
(next: unknown) => {
- slots[index] = next;
+ slots[index] =
+ typeof next === "function"
+ ? (next as (previous: unknown) => unknown)(slots[index])
+ : next;
},
];
},
@@ -163,7 +177,16 @@ function harness(
isThreadIncognito: () => incognito,
isPastedTextFile: () => false,
annotationsOfFile: () => null,
- getStoredChatThread: async () => undefined,
+ getStoredChatThread: async () => {
+ threadReads += 1;
+ return options.row;
+ },
+ subscribeChatHistoryUpdated: (listener: (typeof announce)[number]) => {
+ announce.push(listener);
+ return () => {
+ announce.splice(announce.indexOf(listener), 1);
+ };
+ },
ensureStoredChatThread: async (threadId: string) => {
if (storedIds.has(threadId)) return { id: threadId };
if (!initialized || options.missing) return undefined;
@@ -215,7 +238,8 @@ function harness(
token: intent.path.token,
name: intent.displayLabel,
}),
- useRagDocuments: () => ({
+ useRagDocuments: (scope: unknown) => ({
+ ...(scopes.push(scope), {}),
documents: [],
uploading: false,
hasIndexing: false,
@@ -271,6 +295,20 @@ function harness(
get initializeCalls() {
return initializeCalls;
},
+ get threadReads() {
+ return threadReads;
+ },
+ get projectScopes() {
+ return scopes.filter(
+ (scope) => (scope as { type?: string } | null)?.type === "project",
+ );
+ },
+ setActiveProjectId(projectId: string | null) {
+ state.activeProjectId = projectId as never;
+ },
+ announce(thread: AnnouncedRow) {
+ for (const listener of [...announce]) listener({ thread });
+ },
};
}
@@ -354,6 +392,49 @@ test("overlapping attachments initialize once and wait for persistence", async (
assert.ok(app.uploads.every((scope) => scope.threadId === ID));
});
+test("the chat's row is read once, however often the open project changes", async () => {
+ const app = harness({ row: { id: ID, projectId: "p1" } });
+ app.render();
+ await flush();
+ app.render();
+ app.setActiveProjectId("p1");
+ app.render();
+ await flush();
+ app.render();
+ assert.equal(app.threadReads, 1);
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p1" });
+});
+
+test("a row announced on the history event moves the chat without another read", async () => {
+ const app = harness({ row: { id: ID, projectId: "p1" } });
+ app.render();
+ await flush();
+ app.render();
+ app.announce({ id: ID, projectId: "p2" });
+ app.render();
+ assert.equal(app.threadReads, 1);
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p2" });
+ app.announce({ id: "someone-else", projectId: "p3" });
+ app.render();
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p2" });
+});
+
+test("announcements are ordered by the row's edit clock, not by message activity", async () => {
+ const app = harness({ row: { id: ID, projectId: "p1", updatedAt: 9_000, modifiedAt: 100 } });
+ app.render();
+ await flush();
+ app.render();
+ app.announce({ id: ID, projectId: "p2", updatedAt: 5_000, modifiedAt: 200 });
+ app.render();
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p2" }, "a move after a pruned message lowered updatedAt still lands");
+ app.announce({ id: ID, projectId: "p1", updatedAt: 9_500, modifiedAt: 100 });
+ app.render();
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p2" }, "a response written before the move cannot move it back");
+ app.announce({ id: ID, projectId: "p3", modifiedAt: 300 });
+ app.render();
+ assert.deepEqual(app.projectScopes.at(-1), { type: "project", projectId: "p3" });
+});
+
test("initialization tags a temporary chat before the persistence check", async () => {
const app = harness({ temporary: true, missing: true });
app.render();
diff --git a/studio/frontend/tests/reasoning-code-colour.test.ts b/studio/frontend/tests/reasoning-code-colour.test.ts
new file mode 100644
index 00000000000..4d3393be3da
--- /dev/null
+++ b/studio/frontend/tests/reasoning-code-colour.test.ts
@@ -0,0 +1,68 @@
+// 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 {
+ cachedSettledColour,
+ clipLineTokens,
+ keepUnchangedLines,
+ rememberSettledColour,
+ spellLines,
+} from "../src/components/assistant-ui/reasoning-code-colour.ts";
+
+const token = (content: string, color = "#111") => ({ content, offset: 0, color });
+
+test("a row that starts mid-line takes only the tokens it shows", () => {
+ const line = [token("const "), token("value"), token(" = 1;")];
+ const clipped = clipLineTokens(line as never, 3, "st value");
+ assert.deepEqual(clipped?.map((t) => t.content), ["st ", "value"]);
+ assert.equal(clipped?.[1], line[1], "an untouched token keeps its identity");
+});
+
+test("tokens that do not spell the row are refused, so stale colours never show", () => {
+ assert.equal(clipLineTokens([token("old")] as never, 0, "new"), null);
+ assert.equal(clipLineTokens(undefined, 0, "x"), null);
+});
+
+test("settled colours outlive their rows and are keyed on language and source", () => {
+ const result = { tokens: [[token("a")]] } as never;
+ rememberSettledColour("python", "a", result);
+ assert.equal(cachedSettledColour("python", "a"), result);
+ assert.equal(cachedSettledColour("python", "a "), null);
+ assert.equal(cachedSettledColour("ts", "a"), null);
+});
+
+test("a re-coloured growing fence keeps every unchanged line's identity", () => {
+ const first = { tokens: [[token("a")], [token("b", "#222")]] } as never;
+ const second = {
+ tokens: [[token("a")], [token("b", "#333")], [token("c")]],
+ } as never;
+ const kept = keepUnchangedLines(first, second) as { tokens: unknown[][] };
+ const before = first as { tokens: unknown[][] };
+ const after = second as { tokens: unknown[][] };
+ assert.equal(kept.tokens[0], before.tokens[0], "same tokens: the old line is reused");
+ assert.equal(kept.tokens[1], after.tokens[1], "a recoloured line is replaced");
+ assert.equal(kept.tokens[2], after.tokens[2]);
+ assert.equal(keepUnchangedLines(null, second), second);
+});
+
+test("colours for a shorter source are kept only on the lines they still spell", () => {
+ const line0 = [token("def "), token("f():")];
+ const result = { tokens: [line0, [token(" ret")]] } as never;
+ const spelled = spellLines(result, ["def f():", " return 1", "x"]) as {
+ tokens: { content: string; color?: string }[][];
+ };
+ assert.equal(spelled.tokens[0], line0, "a finished line keeps its colours and its identity");
+ assert.deepEqual(spelled.tokens[1].map((t) => [t.content, t.color]), [[" return 1", undefined]], "the growing line is plain");
+ assert.deepEqual(spelled.tokens[2].map((t) => t.content), ["x"], "a line the worker has not seen is plain");
+});
+
+test("evicting a settled colour returns exactly what it added", () => {
+ for (let i = 0; i < 200; i += 1) rememberSettledColour("ts", `${i}`.padStart(9_000, "x"), { tokens: [] } as never);
+ assert.notEqual(cachedSettledColour("ts", "199".padStart(9_000, "x")), null, "the newest entry survives");
+ assert.equal(cachedSettledColour("ts", "0".padStart(9_000, "x")), null, "the oldest is gone");
+ rememberSettledColour("ts", "small", { tokens: [] } as never);
+ assert.notEqual(cachedSettledColour("ts", "small"), null);
+});
diff --git a/studio/frontend/tests/reasoning-code-groups.test.ts b/studio/frontend/tests/reasoning-code-groups.test.ts
new file mode 100644
index 00000000000..6c5eeee7dd2
--- /dev/null
+++ b/studio/frontend/tests/reasoning-code-groups.test.ts
@@ -0,0 +1,47 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const TRANSCRIPT = readSrc("components/assistant-ui/reasoning-transcript.tsx");
+
+test("thinking code is coloured by the worker: once settled near the screen, and while growing only on screen", () => {
+ assert.match(TRANSCRIPT, /\{tokens === null\s*\? codeRowText\(fragment, leading\)\s*: colouredRow\(fragment, leading, tokens\)\}/);
+ assert.match(TRANSCRIPT, /if \(column === 0 && line > 0 && !\(leading && at === 0\)\) nodes\.push\("\\n"\);\s*if \(text !== ""\) nodes\.push\(text\);/, "one text node per line and per line break: a streamed append rewrites only the growing line, and a reading anchor never spans a row's line break");
+ assert.match(TRANSCRIPT, /useThinkingCodeColour\(\s*surface,\s*code\.source,\s*code\.language,[\s\S]{0,120}!code\.incomplete \|\| !streaming,\s*\)/);
+ const hook = readSrc("components/assistant-ui/use-thinking-code-colour.ts");
+ assert.match(hook, /export const LIVE_COLOUR_MS = 250;/, "a growing fence is re-coloured a few times a second at most");
+ assert.match(hook, /new IntersectionObserver\([\s\S]*rootMargin: "100% 0px"/, "a settled block is asked for once it nears the viewport");
+ assert.match(hook, /if \(settled \|\| !visible \|\| caughtUp \|\| state\.busy \|\| state\.off\) return;/, "a growing block off screen, or with a request in flight, asks for nothing");
+ assert.match(hook, /if \(source\.length > MAX_HIGHLIGHT_CHARS\) return;/, "a growing block past the highlight cap waits for its close");
+ assert.equal((hook.match(/requestFullHighlight\([\s\S]*?,\s*true,\s*\)/g) ?? []).length, 2, "thinking colour is speculative, behind the answer's own fences");
+ assert.equal(/highlightFenceSource|code\.highlight|useReasoningHighlight/.test(TRANSCRIPT), false, "no main-thread tokenizer for thinking code");
+ assert.match(TRANSCRIPT, /<CodeHighlightModeContext\.Provider value="settled">/, "a fence inside a prose row of the trace follows the same rule");
+ assert.match(
+ readSrc("components/assistant-ui/reasoning.tsx"),
+ /<CodeHighlightModeContext\.Provider value="settled">\s*<MarkdownText \/>/,
+ "and so does a fence in a trace too short for the transcript",
+ );
+});
+
+test("a code group the fence continues past owns the line break after it, in a block that is not a <pre>", () => {
+ assert.match(TRANSCRIPT, /const breaksAfter =\s*!last\.last &&\s*fragments\[indices\[indices\.length - 1\] \+ 1\]\?\.code\?\.lines\[0\]\?\.column === 0;/);
+ assert.match(TRANSCRIPT, /\{breaksAfter && "\\n"\}\s*<\/code>\s*<\/div>/, "a blank last line needs a break after it to take up its row, and a copy across the seam keeps it");
+ assert.equal(TRANSCRIPT.includes('<pre className="!m-0 min-h-[1lh]'), false, "Firefox copies a blank line between two <pre> blocks");
+});
+
+test("a code group's block still reads as a passage and takes the chosen code size, as its <pre> did", () => {
+ assert.match(
+ readSrc("components/assistant-ui/reasoning-reading-anchor.ts"),
+ /const passages =\s*"p, pre, \.aui-reasoning-code-lines, li, /,
+ "with only thinking code on screen, a width change moved the reader by the whole height the trace above it gained",
+ );
+ assert.match(
+ readSrc("index.css"),
+ /html\[data-code-font-size\] :is\(pre, code, kbd, samp\),\nhtml\[data-code-font-size\] \.aui-reasoning-code-lines \{\n\tfont-size: var\(--custom-code-font-size\) !important;/,
+ "a smaller code font kept the block's default line spacing",
+ );
+});
diff --git a/studio/frontend/tests/reasoning-highlight.test.ts b/studio/frontend/tests/reasoning-highlight.test.ts
index 7948f98d398..d55494f2508 100644
--- a/studio/frontend/tests/reasoning-highlight.test.ts
+++ b/studio/frontend/tests/reasoning-highlight.test.ts
@@ -4,6 +4,8 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ orderHighlightRequests,
+ reasoningHighlightFailure,
reasoningHighlightReply,
reasoningHighlightSource,
} from "../src/components/assistant-ui/reasoning-highlight.ts";
@@ -53,3 +55,25 @@ test("unavailable grammar produces no stale highlighted lines", () => {
{ client: 3, revision: 4, lines: [] },
);
});
+
+test("a failed request is reported without tokens and never by the ordinary reply", () => {
+ const failure = reasoningHighlightFailure(3, 4);
+ assert.deepEqual(failure, { client: 3, revision: 4, lines: [], failed: true });
+ assert.equal("result" in failure, false);
+ const reply = reasoningHighlightReply(
+ { client: 1, revision: 1, source: "x", language: null, lines: [], full: true },
+ null,
+ );
+ assert.equal("failed" in reply, false);
+});
+
+test("demanded requests go before speculative ones, each group in arrival order", () => {
+ const ordered = orderHighlightRequests([
+ { client: 1, speculative: true },
+ { client: 2 },
+ { client: 3, speculative: true },
+ { client: 4, speculative: false },
+ ]);
+ assert.deepEqual(ordered.map((request) => request.client), [2, 4, 1, 3]);
+ assert.deepEqual(orderHighlightRequests([]), []);
+});
diff --git a/studio/frontend/tests/reasoning-live-tail.test.ts b/studio/frontend/tests/reasoning-live-tail.test.ts
index 3683140fb0a..919c7e7ce83 100644
--- a/studio/frontend/tests/reasoning-live-tail.test.ts
+++ b/studio/frontend/tests/reasoning-live-tail.test.ts
@@ -89,15 +89,21 @@ test("focus landing in the clipped lines lifts the cap instead of staying invisi
test("a bounded transcript corrects nothing through the thread and mounts the tail", () => {
assert.match(
transcript,
- /shouldAdjustScrollPositionOnItemSizeChange = \(item, delta\) => \{\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(bounded\) return false;/,
+ /const adjustAbove = useCallback\(\s*\(delta: number\) => !boundedRef\.current && adjustThread\(delta\),/,
+ "a bounded transcript still writes thread corrections",
);
- assert.match(transcript, /if \(passage && !bounded\)\s*adjustAbove/);
- assert.match(transcript, /if \(readingAnchor && !bounded\)/);
+ assert.equal(
+ (transcript.match(/adjustThread\(/g) ?? []).length,
+ 1,
+ "every thread correction goes through the bounded guard",
+ );
+ assert.match(transcript, /boundedRef\.current = bounded;/);
assert.match(
transcript,
- /if \(bounded\) \{[\s\S]*?fragments\.length - 1[\s\S]*?BOUNDED_TAIL_PX[\s\S]*?mounted\.add\(i\)/,
+ /if \(!bounded \|\| covered\) return;[\s\S]*?BOUNDED_TAIL_PX[\s\S]*?end: fragments\.length[\s\S]*?setIslands\(next\);/,
+ "the newest rows are not mounted while the prefix catches up",
);
- assert.match(transcript, /\}, \[viewport, virtualizer, bounded\]\);/);
+ assert.match(transcript, /recapture\.current\(true\);\s*\}, \[bounded\]\);/);
});
test("a closing block keeps the cap it had while open", () => {
diff --git a/studio/frontend/tests/reasoning-mount-controller.test.ts b/studio/frontend/tests/reasoning-mount-controller.test.ts
new file mode 100644
index 00000000000..5c2898c9304
--- /dev/null
+++ b/studio/frontend/tests/reasoning-mount-controller.test.ts
@@ -0,0 +1,461 @@
+// 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 {
+ INITIAL_VIEWPORTS,
+ SETTLE_MS,
+ WIDEN_CHARACTERS_PER_FRAME,
+ WIDEN_FRAGMENTS_PER_FRAME,
+ estimateFragmentHeight,
+ estimateFragmentHeights,
+ closedChunkUnchanged,
+ frameBudget,
+ buildChunkGrid,
+ chunkEndAt,
+ chunkPieces,
+ chunkStartAt,
+ addIsland,
+ mountedRanges,
+ mountPlan,
+ type MountItem,
+ NO_ISLANDS,
+ TAIL_RESERVE,
+ CHUNK_CHARACTERS,
+ CHUNK_MAX_GROUPS,
+ initialRows,
+ isCovered,
+ anchorAtSamePlace,
+ widenBudget,
+} from "../src/components/assistant-ui/reasoning-mount-controller.ts";
+import { ReasoningTranscriptIndex } from "../src/components/assistant-ui/reasoning-transcript-index.ts";
+import {
+ REASONING_ROW_CONTAINMENT,
+ REASONING_ROW_CONTAINMENT_ATTRIBUTE,
+ ROW_SETTLED_ATTRIBUTE,
+ CHUNK_ESTIMATE_PROPERTY,
+ SHIP_DEFAULT,
+} from "../src/components/assistant-ui/reasoning-row-containment-mode.ts";
+import { defineContainmentFlag } from "../src/components/assistant-ui/containment-flag.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const geometry = { width: 640, lineHeight: 24, fontPixels: 15, codeLineHeight: 18.9, codeFontPixels: 12.2, codeFooter: 12.25 };
+
+test("a hidden fragment has no height and prose loses its paragraph gap", () => {
+ assert.equal(estimateFragmentHeight({ text: "x", first: true, last: false, hidden: true }, geometry), 0);
+ const prose = estimateFragmentHeight({ text: "one\ntwo\nthree\nfour", first: false, last: false }, geometry);
+ assert.equal(prose, 2 * 24, "four lines of prose estimate as the lines minus the two blank separators");
+ const first = estimateFragmentHeight({ text: "one\ntwo\nthree\nfour", first: true, last: false }, geometry);
+ assert.equal(first, prose + 16, "the first fragment carries the pane's top padding");
+});
+
+test("a code fragment is sized per line of the code block, with its header and footer", () => {
+ const code = { source: "a\nb", incomplete: false, language: "ts", lines: [] };
+ const middle = estimateFragmentHeight({ text: "a\nb", first: false, last: false, code }, geometry);
+ assert.equal(middle, 2 * 18.9, "code lines at the prose line height reserved 13% too much, and a reader following a stream was clamped up when the rows mounted");
+ const whole = estimateFragmentHeight({ text: "a\nb", first: true, last: true, code }, geometry);
+ assert.equal(whole, 2 * 18.9 + 40 + 12.25, "and the footer is the measured one, never more");
+ const transcript = readSrc("components/assistant-ui/reasoning-transcript.tsx");
+ assert.match(transcript, /<div\s+ref=\{codeProbe\}\s+aria-hidden\s+className="aui-reasoning-code-fragment aui-reasoning-code-last pointer-events-none invisible absolute"\s*>\s*<div className="aui-reasoning-code-lines" \/>\s*<\/div>/, "the metrics come from the code block's own rules, chosen font size included");
+ assert.equal((transcript.match(/measureGeometry\(element, codeProbe\.current\)/g) ?? []).length, 2);
+});
+
+test("long lines wrap into the estimate at the measured column count", () => {
+ const columns = Math.floor(640 / (15 * 0.48));
+ const text = "x".repeat(columns * 6);
+ const single = estimateFragmentHeight({ text: "x", first: false, last: false }, geometry);
+ const wrapped = estimateFragmentHeight({ text, first: false, last: false }, geometry);
+ assert.ok(wrapped > single, "a wrapped line costs more than a short one");
+});
+
+test("a streaming commit estimates only the rows it has not seen at this geometry", () => {
+ let reads = 0;
+ const row = (text: string) => ({
+ get text() {
+ reads += 1;
+ return text;
+ },
+ first: false,
+ last: false,
+ });
+ const kept = row("one\ntwo\nthree");
+ const first = estimateFragmentHeights([kept, row("x")], geometry);
+ assert.deepEqual(first, [estimateFragmentHeight(kept, geometry), estimateFragmentHeight({ text: "x", first: false, last: false }, geometry)]);
+ reads = 0;
+ const grown = row("x y");
+ assert.deepEqual(estimateFragmentHeights([kept, grown], geometry), [first[0], estimateFragmentHeight(grown, geometry)]);
+ assert.equal(reads, 2, "every commit re-split the text of every row in the trace");
+ reads = 0;
+ estimateFragmentHeights([kept], { ...geometry, width: 320 });
+ assert.equal(reads, 1, "a new width estimates every row again");
+});
+
+test("the first commit covers the budget and always includes the anchor row", () => {
+ const estimates = [100, 100, 100, 100, 100, 100, 100, 100];
+ assert.equal(initialRows(estimates, 250, -1), 3, "three rows cover 250px");
+ assert.equal(initialRows(estimates, 250, 5), 8, "the anchor row, everything above it, and the budget below it so the reader's position survives the hand-over");
+ assert.equal(initialRows(estimates, 250, 7), 8, "an anchor near the end mounts to the end");
+ assert.equal(initialRows(estimates, 10_000, -1), 8, "and never more than there are");
+ assert.equal(initialRows(estimates, 10_000, -1, Array(8).fill(1500)), 3, "and never more characters than one frame can parse, so a reopen stays inside the collapse scroll lock");
+ assert.equal(initialRows(estimates, 10_000, -1, Array(8).fill(9000)), 1, "one oversized fragment still mounts alone");
+ assert.equal(initialRows(estimates, 10_000, 6, Array(8).fill(9000)), 7, "unless the anchor row needs more");
+ assert.equal(initialRows(estimates, 0, -1), 1, "at least one row, so an opened pane is never empty");
+ assert.equal(initialRows([], 250, -1), 0, "an empty trace has nothing to mount");
+});
+
+test("widening covers the trace and stops at the end", () => {
+ assert.equal(isCovered(10, 10), true);
+ assert.equal(isCovered(9, 10), false);
+ const sizes = Array(40).fill(100);
+ let mounted = initialRows(sizes, 2 * 900, -1);
+ let steps = 0;
+ while (!isCovered(mounted, 40)) {
+ mounted = widenBudget(sizes, mounted, 300).rows;
+ steps += 1;
+ assert.ok(steps < 100, "widening converges");
+ }
+ assert.equal(mounted, 40);
+ assert.ok(steps <= Math.ceil(40 / 3) + 1);
+ assert.equal(INITIAL_VIEWPORTS, 1);
+});
+
+test("widening stays light while the collapse animation and its scroll lock run", () => {
+ const settling = frameBudget(0);
+ const steady = frameBudget(SETTLE_MS);
+ assert.ok(settling.characters < steady.characters && settling.fragments < steady.fragments);
+ assert.equal(steady.characters, WIDEN_CHARACTERS_PER_FRAME);
+ assert.equal(steady.fragments, WIDEN_FRAGMENTS_PER_FRAME);
+ assert.ok(SETTLE_MS >= 200, "at least the collapsible's animation");
+});
+
+test("a frame's widening is budgeted by characters, never by fragment count", () => {
+ const sizes = [200, 200, 8000, 8000, 200, 200];
+ assert.deepEqual(widenBudget(sizes, 0, 1000), { rows: 2, spent: 400 }, "small fragments fill the budget together");
+ assert.deepEqual(widenBudget(sizes, 2, 1000), { rows: 3, spent: 8000 }, "an oversized fragment still mounts, alone");
+ assert.deepEqual(widenBudget(sizes, 3, 24_000), { rows: 6, spent: 8400 }, "the rest fits in one frame");
+ assert.deepEqual(widenBudget(sizes, 6, 24_000), { rows: 6, spent: 0 }, "nothing left");
+ assert.ok(WIDEN_CHARACTERS_PER_FRAME >= 8_192, "at least one full fragment per frame");
+ const tiny = Array(500).fill(10);
+ assert.deepEqual(widenBudget(tiny, 0, 24_000), { rows: 64, spent: 640 }, "many tiny fragments are capped per frame too");
+ assert.deepEqual(widenBudget(tiny, 0, 24_000, 8), { rows: 8, spent: 80 });
+});
+
+test("the reasoning-row flag is a containment flag with its own names", () => {
+ assert.equal(SHIP_DEFAULT, "contain");
+ assert.equal(REASONING_ROW_CONTAINMENT_ATTRIBUTE, "data-reasoning-row-containment");
+ assert.equal(REASONING_ROW_CONTAINMENT.global, "__UNSLOTH_REASONING_ROW_CONTAINMENT__");
+ assert.equal(ROW_SETTLED_ATTRIBUTE, "data-settled");
+ assert.equal(REASONING_ROW_CONTAINMENT.resolve(undefined, ""), "contain");
+ assert.equal(REASONING_ROW_CONTAINMENT.resolve(undefined, "typo"), "off");
+ assert.equal(REASONING_ROW_CONTAINMENT.mode(undefined, "", false), "off", "gated on the engine");
+ assert.equal(REASONING_ROW_CONTAINMENT.mode(true, "", false), "contain", "unless forced from the console");
+});
+
+test("the flag factory resolves, gates and watches independently per instance", () => {
+ const a = defineContainmentFlag({ attribute: "data-a", global: "__A__" });
+ const b = defineContainmentFlag({ attribute: "data-b", global: "__B__", shipDefault: "off" });
+ assert.equal(a.resolve(undefined, ""), "contain");
+ assert.equal(b.resolve(undefined, ""), "off");
+ assert.equal(b.resolve("contain", ""), "contain");
+ assert.equal(a.resolve(false, "contain"), "off");
+ assert.equal(a.mode("contain", "", false), "contain");
+ assert.equal(a.mode(undefined, "contain", false), "off");
+ const scope: Record<string, unknown> = {};
+ const applied: string[] = [];
+ assert.equal(a.installWatcher(scope, () => { applied.push("a"); return "off"; }), true);
+ assert.equal(b.installWatcher(scope, () => { applied.push("b"); return "off"; }), true);
+ scope.__A__ = "off";
+ scope.__B__ = true;
+ assert.deepEqual(applied, ["a", "b"]);
+ assert.equal(scope.__A__, "off");
+ assert.equal(scope.__B__, true);
+ assert.equal(a.installWatcher(Object.freeze({}) as Record<string, unknown>, () => "off"), false);
+});
+
+test("the controller and flag modules are plain TypeScript", () => {
+ for (const file of [
+ "components/assistant-ui/reasoning-mount-controller.ts",
+ "components/assistant-ui/reasoning-row-containment-mode.ts",
+ "components/assistant-ui/containment-flag.ts",
+ ]) {
+ const source = readSrc(file);
+ assert.ok(!/<\/?[a-z]+[\s>]/i.test(source.replace(/^\s*[/*].*$/gm, "")), `${file}: no JSX`);
+ assert.ok(!/\bfrom\s+["']react["']/.test(source), `${file}: no react import`);
+ assert.ok(!source.includes("import.meta"), `${file}: no import.meta`);
+ }
+});
+
+type GridInput = { key: string; text: string; document: number; start: number; code?: { source: string; incomplete: boolean; language: string | null; lines: { line: number; column: number; text: string }[] } };
+const prose = (key: string, chars: number, start = 0): GridInput => ({ key, text: "x".repeat(chars), document: 0, start });
+const code = (fence: number, line: number, chars: number): GridInput => ({
+ key: `0:0:${fence}:code:${line}:0`,
+ text: "y".repeat(chars),
+ document: 0,
+ start: fence,
+ code: { source: "", incomplete: false, language: "js", lines: [] },
+});
+
+test("the grid groups a fence's fragments, closes chunks by characters or count, and keys each by its first group", () => {
+ assert.equal(CHUNK_ESTIMATE_PROPERTY, "--unsloth-chunk-estimate");
+ assert.ok(CHUNK_CHARACTERS >= 4_096 && CHUNK_MAX_GROUPS >= 8);
+ const fragments = [prose("a", 3000), prose("b", 3000), prose("c", 3000), code(9000, 0, 2000), code(9000, 1, 2000), prose("e", 10)];
+ const grid = buildChunkGrid(fragments, fragments.map(() => 10), 8_192, 12);
+ assert.deepEqual(grid.groups.map((g) => [g.key, g.first, g.end, g.code]), [
+ ["a", 0, 1, false], ["b", 1, 2, false], ["c", 2, 3, false], ["0:9000", 3, 5, true], ["e", 5, 6, false],
+ ]);
+ assert.deepEqual(grid.chunks.map((c) => [c.key, c.first, c.end]), [["a", 0, 3], ["0:9000", 3, 6]], "a chunk takes groups until it already holds the budget");
+ assert.deepEqual([...grid.heights], [0, 10, 20, 30, 40, 50, 60]);
+ const many = Array.from({ length: 30 }, (_, i) => prose(`g${i}`, 10));
+ assert.deepEqual(buildChunkGrid(many, many.map(() => 1), 8_192, 12).chunks.map((c) => c.end - c.first), [12, 12, 6]);
+ assert.deepEqual(buildChunkGrid([], []).chunks, []);
+});
+
+test("a long fence splits into chunk-sized groups at line starts, keyed so its growth never re-keys one", () => {
+ const row = (line: number, chars: number, column = 0): GridInput => ({
+ key: `0:0:7:code:${line}:${column}`,
+ text: "y".repeat(chars),
+ document: 0,
+ start: 7,
+ code: { source: "", incomplete: true, language: "js", lines: [{ line, column, text: "" }] },
+ });
+ const fence = Array.from({ length: 12 }, (_, i) => row(i * 16, 1000));
+ const grid = buildChunkGrid(fence, fence.map(() => 1), 8_192, 12);
+ assert.deepEqual(grid.groups.map((g) => [g.key, g.first, g.end, g.code]), [
+ ["0:7", 0, 9, true], [fence[9].key, 9, 12, true],
+ ]);
+ assert.deepEqual(grid.chunks.map((c) => [c.key, c.first, c.end]), [["0:7", 0, 9], [fence[9].key, 9, 12]]);
+ assert.equal(chunkEndAt(grid, 3), 9, "the mount budget can stop inside a long fence");
+ const grown = [...fence, row(192, 1000)];
+ assert.deepEqual(buildChunkGrid(grown, grown.map(() => 1), 8_192, 12).groups.slice(0, 2).map((g) => [g.key, g.first]), grid.groups.map((g) => [g.key, g.first]));
+ const continued = fence.map((fragment, i) => (i === 9 ? row(128, 1000, 4000) : fragment));
+ assert.deepEqual(buildChunkGrid(continued, continued.map(() => 1), 8_192, 12).groups.map((g) => [g.first, g.end]), [[0, 10], [10, 12]], "a row that continues a line stays with the line it continues");
+});
+
+test("a growing last group never moves to another chunk, and appended groups never move a boundary", () => {
+ const base = [prose("a", 6000), prose("b", 1000), prose("tail", 100)];
+ const grown = [prose("a", 6000), prose("b", 1000), prose("tail", 20_000)];
+ const key = (fragments: GridInput[]) => buildChunkGrid(fragments, fragments.map(() => 1)).chunks.map((c) => [c.key, c.first, c.end]);
+ assert.deepEqual(key(grown), key(base), "membership is decided by what the chunk held before the group");
+ const before = Array.from({ length: 18 }, (_, i) => prose(`g${i}`, 700));
+ const after = [...before, ...Array.from({ length: 7 }, (_, i) => prose(`h${i}`, 700))];
+ const a = buildChunkGrid(before, before.map(() => 1)).chunks;
+ const b = buildChunkGrid(after, after.map(() => 1)).chunks;
+ for (let i = 0; i < a.length - 1; i += 1) assert.deepEqual(b[i], a[i]);
+ assert.equal(b[a.length - 1].key, a.at(-1)!.key, "the open chunk keeps its key while it grows and when it closes");
+});
+
+test("a range cuts grid chunks into pieces whose keys stay unique and stable as the range moves", () => {
+ const fragments = [prose("p0", 3000), prose("p1", 3000), code(6000, 0, 2000), code(6000, 1, 2000), code(6000, 2, 2000), prose("p5", 3000), prose("p6", 3000)];
+ const grid = buildChunkGrid(fragments, fragments.map(() => 5), 8_192, 12);
+ const key = (at: number) => fragments[at].key;
+ const whole = chunkPieces(grid, key, 0, fragments.length);
+ assert.deepEqual(whole.map((p) => [p.key, p.first, p.end, p.whole, p.last]), grid.chunks.map((c, i) => [c.key, c.first, c.end, true, i === grid.chunks.length - 1]));
+ const prefix = chunkPieces(grid, key, 0, 3);
+ const island = chunkPieces(grid, key, 4, 7);
+ const keys = [...prefix, ...island].map((p) => p.key);
+ assert.equal(new Set(keys).size, keys.length, "a fence split by a range edge never gives two sibling chunks one key");
+ assert.equal(prefix[0].key, whole[0].key, "the piece at a chunk's start keeps the chunk's key");
+ assert.deepEqual(island[0].groups[0], { index: 2, first: 4, end: 5 }, "the cut fence keeps only its lines inside the range");
+ assert.equal(prefix.at(-1)?.whole, false, "a piece missing part of its chunk stays open");
+ const grownPrefix = chunkPieces(grid, key, 0, 4);
+ assert.deepEqual(grownPrefix.map((p) => p.key), prefix.map((p) => p.key), "a prefix growing inside a chunk keeps every key");
+});
+
+test("a closed chunk re-renders only when a prop, a slice or one of its rows changes", () => {
+ const rows = [{}, {}, {}, {}];
+ const slice = { key: "a", code: false, first: 1, end: 2, streaming: false };
+ const chunk = (over: Record<string, unknown> = {}) => ({
+ slices: [slice, { key: "b", code: true, first: 2, end: 3, streaming: false }],
+ fragments: rows,
+ closed: true,
+ estimate: 120,
+ messageId: "m",
+ ...over,
+ });
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ fragments: [...rows, {}] })), true, "a commit that only grew the trace past it leaves it alone");
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ closed: false })), false);
+ assert.equal(closedChunkUnchanged(chunk({ closed: false }), chunk()), false, "the commit that closes it renders it");
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ estimate: 140 })), false);
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ messageId: "n" })), false, "any other prop is compared too");
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ extra: 1 })), false);
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ fragments: [rows[0], {}, rows[2], rows[3]] })), false, "a replaced row inside it");
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ fragments: [rows[0], rows[1], rows[2], {}] })), false, "or the row after it, whose first line decides the group's trailing line break");
+ assert.equal(closedChunkUnchanged(chunk(), chunk({ fragments: [{}, rows[1], rows[2], rows[3]] })), true, "a row before it is not its business");
+ assert.equal(
+ closedChunkUnchanged(chunk(), chunk({ slices: [slice, { key: "b", code: true, first: 2, end: 3, streaming: true }] })),
+ false,
+ "a fence still being written keeps its copy button disabled, and the commit that finishes it enables the button with the whole source",
+ );
+});
+
+test("islands only grow, keep their identity, and stay listed after the prefix passes them", () => {
+ let islands = addIsland(NO_ISLANDS, { start: 50, end: 60 }, 10);
+ assert.deepEqual(islands, [{ id: 50, start: 50, end: 60 }]);
+ const same = addIsland(islands, { start: 52, end: 58 }, 10);
+ assert.equal(same, islands, "a covered request returns the same array, so nothing commits");
+ islands = addIsland(islands, { start: 90, end: 95 }, 10);
+ assert.deepEqual(islands, [{ id: 50, start: 50, end: 60 }, { id: 90, start: 90, end: 95 }], "a jump elsewhere keeps the rows already mounted");
+ islands = addIsland(islands, { start: 60, end: 70 }, 10);
+ assert.deepEqual(islands, [{ id: 50, start: 50, end: 70 }, { id: 90, start: 90, end: 95 }], "an adjacent request grows the island it touches");
+ islands = addIsland(islands, { start: 40, end: 92 }, 10);
+ assert.deepEqual(islands, [{ id: 50, start: 40, end: 92 }, { id: 90, start: 90, end: 95 }], "a request across two islands grows the first, and the second keeps its identity");
+ assert.equal(addIsland(islands, { start: 60, end: 94 }, 10), islands, "rows held by overlapping islands count as covered");
+ assert.equal(addIsland(islands, { start: 0, end: 20 }, 30), islands, "rows the prefix already holds are never an island");
+ assert.deepEqual(addIsland(islands, { start: 100, end: 110 }, 96), [...islands, { id: 100, start: 100, end: 110 }], "islands the prefix passed stay listed, so their spacers keep their place");
+ assert.deepEqual(addIsland(addIsland(NO_ISLANDS, { start: 5, end: 15 }, 0), { start: 5, end: 40 }, 30).map((island) => island.id), [5, 30], "an island is named by the first row it mounts, so a request clipped by the prefix cannot reuse another island's name");
+});
+
+test("a rewrite that re-keys every row still finds each row at its place in the trace", () => {
+ const code = Array.from({ length: 600 }, (_, i) => `const line${i} = ${i};`).join("\n");
+ const trace = `First thought.\n\n\`\`\`javascript\n${code}\n\`\`\`\n\nLast thought.`;
+ const index = new ReasoningTranscriptIndex();
+ const before = index.update([`${trace} </thi`]);
+ const after = index.update([trace]);
+ const prose = before[0];
+ const codeRow = before.find((fragment) => (fragment.code?.lines[0]?.line ?? 0) > 0);
+ assert.ok(codeRow, "the fence spans several code rows");
+ for (const row of [prose, codeRow]) {
+ const place = anchorAtSamePlace(before, after, row, "const", 2);
+ assert.ok(place);
+ assert.notEqual(after[place.index].key, row.key, "a split closing tag rewrote the trace, so every key changed");
+ assert.equal(after[place.index].text, row.text);
+ assert.equal(place.occurrence, 2);
+ }
+ assert.equal(anchorAtSamePlace(before, after, { ...prose, document: 1 }, "First", 0), null);
+});
+
+test("a streamed fence's rows keep the reader's place when the rewrite parses the fence as one prose row", () => {
+ const code = Array.from({ length: 40 }, (_, i) => `const line${i} = ${i};`).join("\n");
+ const trace = `First thought.\n\n\`\`\`javascript\n${code}\n\`\`\`\n\nSecond thought.\n\nThird thought.`;
+ const index = new ReasoningTranscriptIndex();
+ for (let end = 8; end < trace.length; end += 8) index.update([trace.slice(0, end)]);
+ const before = index.update([`${trace} </thi`]);
+ const after = index.update([trace]);
+ const fence = after.find((fragment) => fragment.text.startsWith("```"));
+ assert.ok(fence && !fence.code, "PRECONDITION: the full parse holds the fence as prose");
+ const codeRows = before.filter((fragment) => fragment.code);
+ assert.ok(codeRows.length > 1, "PRECONDITION: the stream held the fence as several code rows");
+ for (const row of codeRows) assert.equal(after[anchorAtSamePlace(before, after, row, "const", 0)!.index], fence);
+ const third = codeRows[2];
+ assert.equal(third.code?.lines[0]?.line, 32, "PRECONDITION: code rows hold 16 lines");
+ assert.deepEqual(
+ anchorAtSamePlace(before, after, third, "const", 3),
+ { index: after.indexOf(fence), occurrence: 35 },
+ "the passage on line 35 is the fourth match in its code row but the 36th in the whole fence, so the reader was moved up to line 3",
+ );
+ assert.deepEqual(
+ anchorAtSamePlace(after, before, fence, "const", 35),
+ { index: before.indexOf(third), occurrence: 3 },
+ "a fence held as one prose row finds the code row that holds the passage",
+ );
+ for (const row of before.filter((fragment) => !fragment.code)) {
+ const place = anchorAtSamePlace(before, after, row, "thought", 0);
+ assert.ok(place, `no place for ${JSON.stringify(row.text)}`);
+ assert.ok(after[place.index].text.includes(row.text.trim().replace(" </thi", "")));
+ }
+});
+
+test("mounted ranges merge the prefix with the islands and clip to the trace", () => {
+ assert.deepEqual(mountedRanges(10, NO_ISLANDS, 100), [[0, 10]]);
+ assert.deepEqual(mountedRanges(10, [{ start: 40, end: 50 }, { start: 80, end: 120 }], 100), [[0, 10], [40, 50], [80, 100]]);
+ assert.deepEqual(mountedRanges(45, [{ start: 40, end: 50 }], 100), [[0, 50]], "an island the prefix reached joins it");
+ assert.deepEqual(mountedRanges(10, [{ start: 10, end: 20 }], 100), [[0, 20]]);
+ assert.deepEqual(mountedRanges(0, [{ start: 5, end: 9 }], 100), [[5, 9]]);
+ assert.deepEqual(mountedRanges(Number.POSITIVE_INFINITY, [{ start: 5, end: 9 }], 30), [[0, 30]]);
+});
+
+test("the prefix and islands snap to whole grid chunks, so no chunk is ever split across two pieces", () => {
+ const fragments = Array.from({ length: 30 }, (_, i) => prose(`r${i}`, 1000));
+ const grid = buildChunkGrid(fragments, fragments.map(() => 1), 4_096, 12);
+ assert.deepEqual(grid.chunks.map((c) => [c.first, c.end]), [[0, 5], [5, 10], [10, 15], [15, 20], [20, 25], [25, 30]]);
+ assert.equal(chunkEndAt(grid, 0), 0);
+ assert.equal(chunkEndAt(grid, 1), 5);
+ assert.equal(chunkEndAt(grid, 5), 5);
+ assert.equal(chunkEndAt(grid, 6), 10);
+ assert.equal(chunkEndAt(grid, 30), 30);
+ assert.equal(chunkEndAt(grid, Number.POSITIVE_INFINITY), Number.POSITIVE_INFINITY);
+ assert.equal(chunkStartAt(grid, 0), 0);
+ assert.equal(chunkStartAt(grid, 7), 5);
+ assert.equal(chunkStartAt(grid, 10), 10);
+ assert.equal(chunkStartAt(grid, 30), 30);
+ const key = (at: number) => fragments[at].key;
+ const pieces = [...chunkPieces(grid, key, 0, chunkEndAt(grid, 7)), ...chunkPieces(grid, key, chunkStartAt(grid, 17), chunkEndAt(grid, 22))];
+ assert.ok(pieces.every((piece) => piece.whole), "aligned ranges only ever render whole chunks");
+ assert.deepEqual(pieces.map((piece) => piece.key), ["r0", "r5", "r15", "r20"]);
+});
+
+
+test("the mount plan gives every unmounted stretch to the island below it, or to the tail", () => {
+ assert.deepEqual(mountPlan(10, NO_ISLANDS, 100), [{ from: 0, to: 10 }, { from: 10, to: 100, reserve: TAIL_RESERVE }]);
+ assert.deepEqual(mountPlan(100, NO_ISLANDS, 100), [{ from: 0, to: 100 }, { from: 100, to: 100, reserve: TAIL_RESERVE }], "a covered trace keeps its tail spacer, at zero height");
+ const middle = [{ id: 40, start: 40, end: 50 }];
+ assert.deepEqual(mountPlan(10, middle, 100), [{ from: 0, to: 10 }, { from: 10, to: 40, reserve: "40" }, { from: 40, to: 50 }, { from: 50, to: 100, reserve: TAIL_RESERVE }]);
+ assert.deepEqual(mountPlan(60, middle, 100), [{ from: 0, to: 40 }, { from: 40, to: 40, reserve: "40" }, { from: 40, to: 60 }, { from: 60, to: 100, reserve: TAIL_RESERVE }], "a closed gap keeps its spacer where it closed");
+ const overlapping = [{ id: 50, start: 40, end: 92 }, { id: 90, start: 90, end: 95 }];
+ assert.deepEqual(mountPlan(10, overlapping, 100), [{ from: 0, to: 10 }, { from: 10, to: 40, reserve: "50" }, { from: 40, to: 90 }, { from: 90, to: 90, reserve: "90" }, { from: 90, to: 95 }, { from: 95, to: 100, reserve: TAIL_RESERVE }]);
+ assert.deepEqual(mountPlan(10, middle, 30), [{ from: 0, to: 10 }, { from: 10, to: 10, reserve: "40" }, { from: 10, to: 30, reserve: TAIL_RESERVE }], "an island the trace no longer reaches keeps its spacer, at zero height, before the tail");
+});
+
+test("a reader at the bottom gets an island while the remainder's spacer stays the same element", () => {
+ assert.deepEqual(mountPlan(8, NO_ISLANDS, 100), [{ from: 0, to: 8 }, { from: 8, to: 100, reserve: TAIL_RESERVE }]);
+ const islands = addIsland(NO_ISLANDS, { start: 90, end: 100 }, 8);
+ assert.deepEqual(mountPlan(12, islands, 100), [{ from: 0, to: 12 }, { from: 12, to: 90, reserve: "90" }, { from: 90, to: 100 }, { from: 100, to: 100, reserve: TAIL_RESERVE }], "the island and its spacer are inserted before the tail, which only shrinks");
+});
+
+const planElements = (plan: MountItem[]): string[] =>
+ plan.flatMap((item) => (item.reserve === undefined ? Array.from({ length: item.to - item.from }, (_, i) => `row:${item.from + i}`) : [`reserve:${item.reserve}`]));
+
+test("no plan step removes or reorders an element, so WebKit never lays the thread out without a spacer", () => {
+ let seed = 7;
+ const random = () => {
+ seed = (seed * 1103515245 + 12345) % 2147483648;
+ return seed / 2147483648;
+ };
+ for (let trial = 0; trial < 300; trial += 1) {
+ let total = 20 + Math.floor(random() * 180);
+ let prefix = 1 + Math.floor(random() * 8);
+ let islands = NO_ISLANDS;
+ let previous = mountPlan(prefix, islands, total);
+ for (let step = 0; step < 50; step += 1) {
+ const roll = random();
+ if (roll < 0.4) prefix = Math.min(total, prefix + 1 + Math.floor(random() * 12));
+ else if (roll < 0.85) {
+ const start = Math.floor(random() * total);
+ islands = addIsland(islands, { start, end: Math.min(total, start + 1 + Math.floor(random() * 12)) }, prefix);
+ } else if (roll < 0.95) {
+ const covered = prefix >= total;
+ total += Math.floor(random() * 8);
+ if (covered) prefix = total;
+ } else {
+ total = Math.max(1, total - 1 - Math.floor(random() * 6));
+ prefix = Math.min(prefix, total);
+ }
+ const ids = islands.map((island) => island.id);
+ assert.equal(new Set(ids).size, ids.length, "island names stay unique, so no two spacers share a key");
+ for (const island of islands) assert.ok(island.start <= island.id && island.id < island.end, "an island is named by one of its own rows");
+ const plan = mountPlan(prefix, islands, total);
+ let cursor = 0;
+ for (const item of plan) {
+ assert.equal(item.from, cursor, "the plan walks the trace in order with no gap or overlap");
+ assert.ok(item.to >= item.from);
+ cursor = item.to;
+ }
+ assert.equal(cursor, total, "and accounts for every row");
+ const mounted = new Set<number>();
+ for (let row = 0; row < Math.min(prefix, total); row += 1) mounted.add(row);
+ for (const island of islands) for (let row = island.start; row < Math.min(island.end, total); row += 1) mounted.add(row);
+ const rows = plan.filter((item) => item.reserve === undefined).reduce((sum, item) => sum + item.to - item.from, 0);
+ assert.equal(rows, mounted.size, "rows are mounted exactly where the prefix and the islands reach");
+ const before = planElements(previous).filter((element) => !element.startsWith("row:") || Number(element.slice(4)) < total);
+ const after = planElements(plan);
+ const kept = new Set(after);
+ for (const element of before) assert.ok(kept.has(element), `${element} was removed by a later plan`);
+ const earlier = new Set(before);
+ assert.deepEqual(after.filter((element) => earlier.has(element)), before, "elements that stay keep their order, so none is moved");
+ previous = plan;
+ }
+ }
+});
diff --git a/studio/frontend/tests/reasoning-row-containment-wiring.test.ts b/studio/frontend/tests/reasoning-row-containment-wiring.test.ts
new file mode 100644
index 00000000000..26001e62555
--- /dev/null
+++ b/studio/frontend/tests/reasoning-row-containment-wiring.test.ts
@@ -0,0 +1,199 @@
+// 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 {
+ REASONING_ROW_CONTAINMENT_ATTRIBUTE,
+ REASONING_ROW_CONTAINMENT_ON,
+ CHUNK_ESTIMATE_PROPERTY,
+ ROW_SETTLED_ATTRIBUTE,
+} from "../src/components/assistant-ui/reasoning-row-containment-mode.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const INDEX_CSS = readSrc("index.css");
+const TRANSCRIPT = readSrc("components/assistant-ui/reasoning-transcript.tsx");
+const ANCHOR = readSrc("components/assistant-ui/reasoning-reading-anchor.ts");
+const MAIN = readSrc("main.tsx");
+const CONTAINMENT = readSrc("components/assistant-ui/reasoning-row-containment.ts");
+
+const GATE = `html[${REASONING_ROW_CONTAINMENT_ATTRIBUTE}="${REASONING_ROW_CONTAINMENT_ON}"]`;
+const ROWS = '.aui-thread-root [data-slot="reasoning-transcript"] > [data-reasoning-chunk]';
+
+const layerBounds = (css: string, name: string): [number, number] => {
+ const open = css.indexOf(`@layer ${name} {`);
+ assert.ok(open >= 0, `PRECONDITION: @layer ${name} exists`);
+ let depth = 0;
+ for (let i = css.indexOf("{", open); i < css.length; i += 1) {
+ if (css[i] === "{") depth += 1;
+ else if (css[i] === "}") {
+ depth -= 1;
+ if (depth === 0) return [open, i];
+ }
+ }
+ throw new Error(`@layer ${name} never closes`);
+};
+
+test("every chunk records its size before any chunk can be skipped", () => {
+ const at = INDEX_CSS.indexOf(`${ROWS} {`);
+ assert.ok(at >= 0, "an ungated rule on every transcript chunk");
+ const rule = INDEX_CSS.slice(at, INDEX_CSS.indexOf("}", at));
+ assert.ok(rule.includes(`contain-intrinsic-size: auto var(${CHUNK_ESTIMATE_PROPERTY})`), "auto, so the engine remembers the rendered size, with the controller's estimate until then");
+ assert.equal(rule.includes("content-visibility"), false, "sizing alone: the skipping is gated separately");
+ const [open, close] = layerBounds(INDEX_CSS, "utilities");
+ assert.ok(at > open && at < close);
+});
+
+test("the chunk estimate does not inherit, so a growing chunk restyles only itself", () => {
+ assert.ok(new RegExp(`@property ${CHUNK_ESTIMATE_PROPERTY} \\{\\s*syntax: "<length>";\\s*inherits: false;\\s*initial-value: 0px;\\s*\\}`).test(INDEX_CSS), "registered, so a write restyles the chunk and not every element inside it");
+});
+
+test("only settled rows are skipped, and only where the engine finds skipped content", () => {
+ const rules = INDEX_CSS.split(GATE).slice(1).map((rule) => rule.slice(0, rule.indexOf("}")));
+ assert.equal(rules.length, 2, "two gated rules");
+ const [box, rule] = rules;
+ assert.ok(box.startsWith(` ${ROWS} {`), "every chunk, settled or not");
+ assert.match(box, /^\s*\S[^{]*\{\s*display: flow-root;\s*$/, "is its own formatting context from the start, so settling changes no margin and no height");
+ assert.ok(rule.startsWith(` ${ROWS}[${ROW_SETTLED_ATTRIBUTE}]`), "the settled chunk, a direct child of the transcript");
+ assert.ok(rule.includes("content-visibility: auto;"));
+ for (const gated of rules) {
+ assert.equal(gated.includes(":has("), false);
+ assert.equal(gated.includes("!important"), false);
+ }
+ const at = INDEX_CSS.indexOf(GATE);
+ const [open, close] = layerBounds(INDEX_CSS, "utilities");
+ assert.ok(at > open && at < close, "inside @layer utilities");
+ const printAt = INDEX_CSS.indexOf("@media print", at);
+ assert.ok(printAt > at, "a print override follows");
+ const print = INDEX_CSS.slice(printAt, INDEX_CSS.indexOf("}", INDEX_CSS.indexOf("}", printAt) + 1));
+ assert.ok(print.includes(ROWS), "and names the transcript chunks");
+ assert.ok(print.includes("content-visibility: visible !important") && print.includes("contain-intrinsic-size: none !important"));
+});
+
+test("the transcript mounts every fragment and never unmounts one for scrolling", () => {
+ assert.equal(TRANSCRIPT.includes("@tanstack/react-virtual"), false, "no virtualizer");
+ assert.equal(/translateY|getTotalSize|measureElement|rangeExtractor/.test(TRANSCRIPT), false, "no absolute row positioning");
+ assert.match(TRANSCRIPT, /const shown = covered \? fragments\.length : limit;/, "rows render in order up to the widening limit");
+ assert.match(TRANSCRIPT, /limitRef\.current = isCovered\(rows, all\.length\)\s*\? Number\.POSITIVE_INFINITY\s*: rows;/, "and the limit is dropped for good once it covers the trace");
+ assert.match(TRANSCRIPT, /if \(streamingRef\.current\) setLimit\(value\);\s*else startTransition\(\(\) => setLimit\(value\)\);/, "widening yields to input on a settled trace and cannot be starved by a stream");
+ assert.match(TRANSCRIPT, /if \(widenFrame === 0\) widenFrame = requestAnimationFrame\(widenAll\);/, "one shared frame drives every open transcript");
+ assert.match(TRANSCRIPT, /let characters = Math\.ceil\(WIDEN_CHARACTERS_PER_FRAME \* widenScale\);/, "under one shared budget of characters per frame");
+ const movers = TRANSCRIPT.replace(/useState\(\(\) => \{[\s\S]*?\n {2}\}\);/, "").replace(/setLimit\(isCovered\(value, fragments\.length\) \? Number\.POSITIVE_INFINITY : value\);/, "").replace(/requestedAt\.current = performance\.now\(\);\s*setLimit\(current\);/, "");
+ assert.equal(/setLimit\((?!value\))/.test(movers), false, "no other path moves the limit, except the bounded restart for a replaced document and the re-issue of a starved request at its own value");
+ assert.match(TRANSCRIPT, /if \(mount\.origin !== origin\) \{[\s\S]*?setMount\(\{\s*origin,\s*limit:/, "a replaced document restarts the bounded mount instead of mounting the new trace whole");
+ assert.match(TRANSCRIPT, /const setLimit = useCallback\(\(value: number\) => \{\s*setMount\(\{ origin: originRef\.current, limit: value \}\);\s*\}, \[\]\);/, "every limit carries the document it was computed for, so a widening, print or re-issue queued for the previous document resolves to a restart, and one for the new document wins even when React replays it on a stale base");
+ assert.match(TRANSCRIPT, /const islands = islandState\.origin === origin \? islandState\.list : NO_ISLANDS;/, "islands belong to the document they were made for");
+ assert.equal(/setMountedFor|setIslands\(NO_ISLANDS\)/.test(TRANSCRIPT), false, "the restart needs no reset in render beyond the tagged limit");
+ assert.match(TRANSCRIPT, /const restarted = originRef\.current !== origin;\s*if \(restarted\) \{\s*originRef\.current = origin;\s*mountedAt\.current = performance\.now\(\);\s*islandsRef\.current = NO_ISLANDS;\s*limitRef\.current = limit;\s*\}/, "and the requested limit follows it down once");
+ assert.match(TRANSCRIPT, /const carried = restarted && carry\.current\(previous\);/, "a rewrite that is not an append re-keys every row, so the reader's passage is found again by its place in the trace and mounted at once");
+ assert.match(TRANSCRIPT, /if \(restarted && !carried\) demandNow\.current\(\);/, "and a still reader gets rows under the viewport at once instead of a spacer until the next scroll");
+ assert.match(TRANSCRIPT, /if \(limit > limitRef\.current\) limitRef\.current = limit;/, "a committed limit never moves the requested one backwards");
+});
+
+test("a row settles one frame after it has been laid out, so the engine remembers its real size", () => {
+ assert.match(TRANSCRIPT, /const settleQueue = createSettleQueue<HTMLElement>\(\s*\(callback\) => requestAnimationFrame\(callback\),\s*\(row\) => \{\s*if \(!row\.isConnected\) return;\s*row\.setAttribute\(ROW_SETTLED_ATTRIBUTE, ""\);\s*const transcript = row\.parentElement;\s*if \(transcript && hiddenTranscripts\.has\(transcript\)\)\s*blindTranscripts\.add\(transcript\);\s*\},\s*\);/, "rows settle through the frame-counted queue: a whole frame lays each row out and records it before it may be skipped, and a row settled while its transcript has no box marks the transcript");
+ assert.match(TRANSCRIPT, /const changed = new MutationObserver\(\(\) => \{\s*if \(!element\.hasAttribute\(ROW_SETTLED_ATTRIBUTE\)\) settleQueue\.add\(element\);\s*\}\);/, "a late render inside a closed chunk that has not settled yet restarts its frame count, so it is never skipped on the size it had before; a settled chunk is never unsettled, so no growth lands outside a commit");
+ assert.match(TRANSCRIPT, /changed\.observe\(element, \{\s*subtree: true,\s*childList: true,\s*characterData: true,\s*\}\);/, "every row change inside a closed chunk is seen");
+ assert.match(TRANSCRIPT, /getSnapshotBeforeUpdate\(\) \{\s*this\.props\.before\(\);\s*return null;\s*\}\s*componentDidUpdate\(\) \{\s*this\.props\.after\(\);\s*\}/, "a trace's growth is measured across its own commit, where no scroll by the reader can land");
+ assert.match(TRANSCRIPT, /<CommitBounds before=\{beforeCommit\} after=\{afterCommit\}>\s*\{rendered\}\s*<\/CommitBounds>/);
+ assert.match(TRANSCRIPT, /if \(!laidOut\(\)\) return;\s*reading \?\?= visibleAnchor\(\);\s*if \(reading\) \{\s*rootBefore = element\.getBoundingClientRect\(\)\.top;\s*return;\s*\}\s*if \(hasPendingProgressiveMounts\(\)\) return;\s*const bounds = scroll\.getBoundingClientRect\(\);\s*const box = element\.getBoundingClientRect\(\);\s*if \(box\.top < bounds\.top && box\.bottom <= bounds\.bottom\)\s*edge = box\.bottom - bounds\.top;/, "a reader who arrived since the last frame is anchored before the commit changes the DOM, so the commit's own hold corrects it; a trace that starts above the viewport and ends in it, with none of its rows on screen and no progressive message window correcting the same growth, measures its edge, so the reply below it stays put");
+ assert.match(TRANSCRIPT, /const keepOnScreen = \(\) => \{\s*if \(reading && rootBefore !== null\)\s*reading\.offset \+= rootBefore - element\.getBoundingClientRect\(\)\.top;\s*rootBefore = null;\s*\};/, "a rewrite near the end of a trace shrank it to estimates, the browser clamped scrollTop, and the hold, which measures from the transcript, never saw it: the reader was thrown to the bottom and followed again");
+ assert.match(TRANSCRIPT, /carry\.current = \(previous\) => \{\s*keepOnScreen\(\);/, "the restart commit's own movement");
+ assert.match(TRANSCRIPT, /setIslands\(next\);\s*carrying = true;\s*return true;/);
+ assert.match(TRANSCRIPT, /after: \(\) => \{\s*if \(carrying\) \{\s*carrying = false;\s*keepOnScreen\(\);\s*\}/, "and the island commit's, where native anchoring on a reply below kept the page at the clamped bottom");
+ assert.match(TRANSCRIPT, /if \(Math\.abs\(shift\) >= SHIFT_EPSILON_PX\) adjustAbove\(Math\.round\(shift\)\);/, "undoes its growth, which WebKit's anchoring leaves to the page, so a reader below it stays put; native anchoring has already zeroed the shift elsewhere");
+ assert.match(TRANSCRIPT, /return \(\) => \{\s*changed\.disconnect\(\);\s*remeasureQueue\.forget\(element\);\s*settleQueue\.forget\(element\);\s*\};/, "a chunk that unmounts or reopens leaves both queues");
+ assert.equal(/data-settled=\{/.test(TRANSCRIPT), false, "settling is never a React prop");
+ assert.equal((TRANSCRIPT.match(/removeAttribute\(ROW_SETTLED_ATTRIBUTE\)/g) ?? []).length, 1, "and the only unsettle is the relayout after a width change or a blind reveal");
+ assert.match(TRANSCRIPT, /if \(blindTranscripts\.delete\(element\) && !widened\) \{\s*if \(settleTimer !== 0\) clearTimeout\(settleTimer\);\s*settleTimer = window\.setTimeout\(resettleLater, RESETTLE_DELAY_MS\);\s*\}/, "a trace shown again at its width after rows settled while it was hidden is laid out again, as after a width change, and a plain reopen costs nothing extra");
+ assert.match(TRANSCRIPT, /data-reasoning-chunk=""/, "closed chunks of rows are the skip units");
+ assert.match(TRANSCRIPT, /\[CHUNK_ESTIMATE_PROPERTY\]: `\$\{estimate\}px`/, "each chunk carries its estimate for the time before it has rendered");
+ assert.match(TRANSCRIPT, /useSettledRow\(box, closed\);/, "a chunk settles once it is closed, never while rows can still join it");
+ assert.match(TRANSCRIPT, /const Chunk = memo\(function Chunk\(\{[\s\S]*?\}, closedChunkUnchanged\);/, "every streaming commit re-rendered every mounted chunk, row and code group of the trace");
+ assert.match(TRANSCRIPT, /streaming:\s*streaming &&\s*\(group\.code\s*\? fragments\[first\]\.code!\.incomplete\s*: first === fragments\.length - 1\),/, "a slice says whether it is still being written, so a closed chunk holding a fence's copy button renders again when the fence ends");
+ assert.equal((TRANSCRIPT.match(/useSettledRow\(/g) ?? []).length, 2, "rows and code groups no longer settle on their own");
+ assert.match(TRANSCRIPT, /closed=\{piece\.whole && \(!piece\.last \|\| sealed\)\}/, "only a whole grid chunk settles, and the last one only once the trace is complete and mounted");
+ assert.match(TRANSCRIPT, /const sealed = covered && !streaming;/);
+});
+
+test("the DOM the rest of the app reads is unchanged", () => {
+ for (const token of [
+ 'data-slot="reasoning-transcript"',
+ 'data-slot="reasoning-code-fragment"',
+ 'data-reasoning-code-row=""',
+ "data-reasoning-fragment={fragment.key}",
+ 'style={{ overflowAnchor: "none" }}',
+ "SearchImagesEnabledContext.Provider value={false}",
+ "aui-reasoning-prose-fragment",
+ ]) {
+ assert.ok(TRANSCRIPT.includes(token), `kept: ${token}`);
+ }
+ assert.equal(TRANSCRIPT.split("data-reasoning-fragment={fragment.key}").length - 1, 2, "prose rows and code rows");
+ assert.match(TRANSCRIPT, /if \(touches\) detach\(\);/, "a selection or focus inside the trace still parks the autoscroll");
+ assert.match(TRANSCRIPT, /for \(const \{ from, to, reserve \} of mountPlan\(\s*shown,\s*islands,\s*fragments\.length,\s*\)\) \{/, "every unmounted stretch keeps its estimated height, laid out by the plan");
+ assert.match(TRANSCRIPT, /data-reasoning-reserve=""\s*style=\{\{ height: grid\.heights\[to\] - grid\.heights\[from\] \}\}/, "as a spacer that shrinks as rows mount, so the thread below never jumps");
+ assert.match(TRANSCRIPT, /const key = `reserve:\$\{reserve\}`;\s*rendered\.push\(\s*<div\s*key=\{key\}/, "and each spacer keeps one element for its whole life, so WebKit never lays the thread out without it mid-commit");
+ assert.equal(/reserve:\$\{to\}|reserved > 0/.test(TRANSCRIPT), false, "no spacer is keyed by a moving row or dropped when its stretch fills");
+ assert.match(TRANSCRIPT, /adjustAbove\(passage\.getBoundingClientRect\(\)\.top - pending\.top\)/, "the threshold handover still restores the reading passage");
+ assert.match(TRANSCRIPT, /const top = passage\.getBoundingClientRect\(\)\.top;\s*anchor\.offset = top - box\.top;\s*adjustAbove\(top - anchor\.top\);/, "and a width change still re-finds it, against the viewport so a prompt above that re-wraps is undone too");
+ assert.match(TRANSCRIPT, /settleTimer = window\.setTimeout\(resettleLater, RESETTLE_DELAY_MS\);/, "after a width change every chunk is laid out again before it may be skipped, once the drag has settled");
+ assert.match(TRANSCRIPT, /resettleRows\(element\);\s*const next = measureGeometry\(element, codeProbe\.current\);\s*if \(next\) setGeometry\(keepGeometry\(next\)\);\s*if \(reading\) hold\(reading\);/, "and the relayout that follows keeps the reading passage where it was, with the spacers re-estimated for the new width");
+ assert.match(TRANSCRIPT, /const rootTop = element\.getBoundingClientRect\(\)\.top;\s*const was = rootTop \+ anchor\.offset;\s*const bounds = scroll\.getBoundingClientRect\(\);\s*if \(was < bounds\.top - bounds\.height \|\| was > bounds\.bottom \+ bounds\.height\)\s*return false;\s*const passage = passageOf\(anchor\);/, "an anchor the reader has scrolled away from is dropped before anything inside a skipped chunk is measured");
+ assert.match(TRANSCRIPT, /const top = passage\.getBoundingClientRect\(\)\.top;\s*const shift = top - was;/, "a shift is measured inside the transcript, which has native anchoring off, so a reader's own scroll is never undone");
+ assert.match(TRANSCRIPT, /const chunks = element\.querySelectorAll<HTMLElement>\(\s*":scope > \[data-reasoning-chunk\]",\s*\);/, "the fold is found among chunk boxes, whose size is known while they are skipped");
+ assert.match(TRANSCRIPT, /const rows = chunk\.querySelectorAll<HTMLElement>\(\s*"\[data-reasoning-fragment\]",\s*\);/, "and rows are measured only inside the chunk at the fold, never inside a skipped one");
+ assert.match(TRANSCRIPT, /if \(Math\.abs\(shift\) < SHIFT_EPSILON_PX\) \{\s*residue = shift;\s*return true;\s*\}\s*anchor\.offset = top - rootTop;/, "sub-pixel residue accumulates instead of being dropped");
+ assert.match(TRANSCRIPT, /if \(applied !== 0 \|\| \(acted && rounded !== 0\)\) \{\s*anchor\.offset -= shift - applied;\s*residue = shift - applied;\s*\}/, "and so does the part of a correction that whole-pixel scrolling could not apply");
+ assert.match(TRANSCRIPT, /reading = visibleAnchor\(\);\s*if \(held && reading\) reading\.offset -= residue;/, "an anchor captured after a hold inherits that residue, so Firefox and WebKit do not creep a fraction of a pixel per commit");
+ assert.match(TRANSCRIPT, /if \(!widened\) \{\s*if \(anchor && !atBottom\(\)\) hold\(anchor\);\s*return;\s*\}/, "a height change holds the passage unless the reader sits at the bottom");
+ assert.match(TRANSCRIPT, /passageRange \?\?= document\.createRange\(\);\s*return reasoningTextRange\(row, anchor\.text, anchor\.occurrence, passageRange\);/, "passage lookups on every scrolled frame reuse one Range, which Blink would otherwise walk on every node removal");
+ assert.match(TRANSCRIPT, /if \(committedRef\.current !== current\) \{\s*if \(performance\.now\(\) - requestedAt\.current < STARVED_MS\)\s*return NOTHING_SPENT;\s*requestedAt\.current = performance\.now\(\);\s*setLimit\(current\);\s*return NOTHING_SPENT;\s*\}/, "widening waits for the previous limit to commit, and a transition another reply's stream keeps discarding is re-issued through the sync path after STARVED_MS");
+ assert.match(TRANSCRIPT, /const STARVED_MS = 200;/);
+ assert.match(TRANSCRIPT, /return NOTHING_SPENT;\s*\}\s*if \(isCovered\(current, all\.length\)\) return null;/, "the final step waits for its own commit too, so a starved last transition is re-issued instead of leaving the tail a spacer");
+ assert.equal(TRANSCRIPT.includes("afterprint"), false, "nothing unmounts rows after a print");
+ assert.match(TRANSCRIPT, /let characters = Math\.ceil\(WIDEN_CHARACTERS_PER_FRAME \* widenScale\);\s*let rows = Math\.ceil\(WIDEN_FRAGMENTS_PER_FRAME \* widenScale\);\s*const pending = \[\.\.\.wideners\];/, "one frame's rows are shared by every open transcript, so their transitions land as one bounded commit");
+ assert.match(TRANSCRIPT, /const remaining = pending\.length - at;/, "and a transcript that spends nothing passes its share on");
+ assert.match(TRANSCRIPT, /Math\.min\(share, allowed\.fragments\),/, "and a transcript's rows never exceed its share of the frame");
+ assert.match(TRANSCRIPT, /requestedAt\.current = performance\.now\(\);\s*limitRef\.current = isCovered\(rows, all\.length\)/, "the request time is what the starvation check measures from");
+ assert.match(TRANSCRIPT, /if \(spent === null\) wideners\.delete\(widen\);/, "only a covered transcript leaves the shared frame");
+ assert.match(TRANSCRIPT, /if \(next === islandsRef\.current\) return;\s*islandsRef\.current = next;\s*setIslands\(next\);/, "a reader who scrolls into an unmounted stretch gets an island of rows around the viewport at once");
+ assert.match(TRANSCRIPT, /if \(end > start\) next = addIsland\(next, \{ start, end \}, prefix\);/, "islands only ever grow, so rows a reader saw stay mounted when they jump elsewhere");
+ assert.match(TRANSCRIPT, /if \(!rect\.height \|\| rect\.bottom <= above \|\| rect\.top >= below\) continue;/, "a spacer with no box, as in a hidden folded round, never asks for rows");
+ assert.match(TRANSCRIPT, /let rows = chunkEndAt\(gridRef\.current, budgeted\.rows\);/, "the prefix grows by whole grid chunks, so it never meets an island inside a chunk");
+ assert.match(TRANSCRIPT, /const start = chunkStartAt\(\s*gridRef\.current,/, "and islands start and end on chunk boundaries too");
+ assert.match(TRANSCRIPT, /window\.matchMedia\?\.\("print"\)\?\.addEventListener\?\.\(\s*"change",\s*\(event\) => \{\s*if \(event\.matches\) printTranscripts\(\);\s*\},\s*\{ capture: true \},\s*\);/, "the print media query is a door of its own, for page.pdf() and print emulation");
+ assert.match(TRANSCRIPT, /for \(const skip of islandsRef\.current\)\s*if \(rows >= skip\.start && rows < skip\.end\) rows = skip\.end;/, "the bounded prefix then fills the gaps and steps over rows the islands already hold");
+ assert.match(TRANSCRIPT, /for \(const piece of chunkPieces\(grid, fragmentKey, from, to\)\)/, "chunk boundaries come from one grid over the whole trace, so a range edge never re-keys the chunks on either side of it");
+ assert.match(TRANSCRIPT, /registry\.set\(key, \{ element, from, to \}\);\s*return \(\) => \{\s*if \(registry\.get\(key\)\?\.element === element\) registry\.delete\(key\);/, "each spacer registers the stretch it stands for, so demand reads committed geometry");
+ assert.match(TRANSCRIPT, /if \(grew \|\| mountedIslands\.current !== islands\) \{\s*mountedIslands\.current = islands;\s*if \(!carried\) recapture\.current\(\);\s*\}/, "the reading anchor is captured as soon as rows land under a viewport that had none, so a reflow still has a passage to restore");
+ assert.match(TRANSCRIPT, /const laidOut = \(\) => \{\s*const now = element\.getBoundingClientRect\(\)\.width;\s*return now !== 0 && now === width;\s*\};/, "a transcript inside a hidden ancestor has no box, so it neither captures nor demands rows");
+ assert.match(TRANSCRIPT, /const rounded = Math\.round\(shift\);\s*const acted = adjustAbove\(rounded\);\s*const applied = scroll\.scrollTop - before;\s*if \(applied !== 0 \|\| \(acted && rounded !== 0\)\) \{\s*anchor\.offset -= shift - applied;/, "the part of a correction the engine rounded away or clamped is carried to the next one, so the passage never creeps and a clamped correction lands once the scroll range allows it");
+ assert.match(TRANSCRIPT, /recapture\.current = \(fresh = false\) => \{\s*if \(!laidOut\(\)\) return;\s*if \(!fresh && reading && hold\(reading\)\) return;\s*reading = visibleAnchor\(\);/, "a commit undoes its own shift in the task that made it, before a scrolled frame could capture the shifted layout as the new anchor");
+ assert.match(TRANSCRIPT, /adjustAbove\(passage\.getBoundingClientRect\(\)\.top - pending\.top\);\s*recapture\.current\(true\);/, "and re-read right after the reopen restore moves the viewport");
+ assert.match(TRANSCRIPT, /const mounted = committedRef\.current;\s*const prefix = isCovered\(mounted, all\) \? all : mounted;/, "demand measures the spacer the DOM has, not the limit a pending transition will give it");
+ assert.match(TRANSCRIPT, /const capture = \(\) => \{\s*frame = 0;\s*if \(!laidOut\(\)\) return;\s*const held = reading !== undefined && hold\(reading\);\s*demand\(\);\s*reading = visibleAnchor\(\);/, "a scroll the engine's own anchoring fires inside the resize frame must not replace the pre-reflow anchor, nor demand rows for a position the width handler is about to undo");
+ assert.match(TRANSCRIPT, /if \(committedRef\.current === value\) return;\s*limitRef\.current = value;\s*setLimit\(value\);/, "a print mounts the whole trace even while the last widening transition is still pending");
+ assert.match(TRANSCRIPT, /const printTranscripts = \(\): void => \{\s*flushSync\(\(\) => \{\s*for \(const print of printers\) print\(\);\s*\}\);\s*\};/, "every open transcript lands in one synchronous commit; its code is plain, so there is no fence left to latch");
+ assert.match(TRANSCRIPT, /for \(let i = firstEndingBelow\(rows, bounds\.top\); i < rows\.length; i \+= 1\) \{\s*const row = rows\[i\];\s*if \(row\.getBoundingClientRect\(\)\.top >= bounds\.bottom\) return undefined;/, "a fold row without capturable text falls through to the next visible row");
+ assert.match(TRANSCRIPT, /const chunk = chunks\[at\];\s*if \(chunk\.getBoundingClientRect\(\)\.top >= bounds\.bottom\) break;/, "and on into the next chunk while it is still on screen");
+ assert.match(TRANSCRIPT, /row\.removeAttribute\(ROW_SETTLED_ATTRIBUTE\);\s*settleQueue\.add\(row\);/, "re-settling goes through the same queue as the first settle");
+ assert.match(TRANSCRIPT, /"aui-reasoning-code-fragment relative isolate min-w-0"/, "a code group positions its own copy actions; chunks settle now, so no containment around the group gives them a box");
+ assert.match(TRANSCRIPT, /useState\(\(\) => cachedReasoningTranscriptIndex\(indexKey\)\)/, "a reopened transcript keeps the index it already parsed");
+});
+
+test("the per-frame reading capture reuses one Range", () => {
+ assert.match(ANCHOR, /const range = \(probe \?\?= document\.createRange\(\)\);/, "one live Range for every capture: the engine walks every attached Range on each node removal, so a Range per text node per scrolled frame made the fence windows' span churn an order of magnitude dearer");
+ assert.equal((ANCHOR.match(/document\.createRange\(\)/g) ?? []).length, 2, "the only other Range is the one a caller asked for by position");
+});
+
+test("startup arms the attribute after the code-block one", () => {
+ const code = MAIN.indexOf("watchCodeBlockContainmentOverride();");
+ const apply = MAIN.indexOf("applyReasoningRowContainment();");
+ const watch = MAIN.indexOf("watchReasoningRowContainmentOverride();");
+ assert.ok(code >= 0 && apply > code && watch > apply && watch < MAIN.indexOf("function renderApp()"));
+ assert.ok(CONTAINMENT.includes('import { engineFindsSkippedContent } from "./math-block-containment";'));
+ assert.ok(CONTAINMENT.includes("import.meta.env.VITE_UNSLOTH_REASONING_ROW_CONTAINMENT"));
+ assert.ok(CONTAINMENT.includes("root.removeAttribute(REASONING_ROW_CONTAINMENT.attribute)"));
+});
diff --git a/studio/frontend/tests/reasoning-settle-queue.test.ts b/studio/frontend/tests/reasoning-settle-queue.test.ts
new file mode 100644
index 00000000000..03c3023c0ca
--- /dev/null
+++ b/studio/frontend/tests/reasoning-settle-queue.test.ts
@@ -0,0 +1,146 @@
+// 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 {
+ createRemeasureQueue,
+ createSettleQueue,
+} from "../src/components/assistant-ui/reasoning-settle-queue.ts";
+
+const frames = () => {
+ let queue: (() => void)[] = [];
+ return {
+ request: (callback: () => void) => {
+ queue.push(callback);
+ },
+ run: () => {
+ const due = queue;
+ queue = [];
+ for (const callback of due) callback();
+ return due.length;
+ },
+ pending: () => queue.length,
+ };
+};
+
+test("a row settles only after one whole frame has laid it out unsettled", () => {
+ const clock = frames();
+ const settled: string[] = [];
+ const queue = createSettleQueue<string>(clock.request, (row) => settled.push(row));
+ queue.add("a");
+ queue.add("b");
+ assert.equal(clock.pending(), 1, "one frame request covers every row queued before it");
+ clock.run();
+ assert.deepEqual(settled, [], "the first frame lays the rows out and records their size");
+ clock.run();
+ assert.deepEqual(settled, ["a", "b"]);
+ assert.equal(clock.pending(), 0, "no frame is requested once nothing waits");
+});
+
+test("a row queued while a settle is one frame along waits its own whole frame", () => {
+ const clock = frames();
+ const settled: string[] = [];
+ const queue = createSettleQueue<string>(clock.request, (row) => settled.push(row));
+ queue.add("mounted");
+ clock.run();
+ queue.add("unsettled by a width change");
+ clock.run();
+ assert.deepEqual(settled, ["mounted"], "the late row has not been through a layout yet, so it must not be skipped on a stale size");
+ clock.run();
+ assert.deepEqual(settled, ["mounted", "unsettled by a width change"]);
+});
+
+test("re-queuing a ripening row restarts its wait, and a forgotten row never settles", () => {
+ const clock = frames();
+ const settled: string[] = [];
+ const queue = createSettleQueue<string>(clock.request, (row) => settled.push(row));
+ queue.add("a");
+ queue.add("b");
+ clock.run();
+ queue.add("a");
+ queue.forget("b");
+ clock.run();
+ assert.deepEqual(settled, []);
+ clock.run();
+ assert.deepEqual(settled, ["a"]);
+ assert.equal(clock.pending(), 0);
+});
+
+test("a row forgotten before its first frame never settles and keeps no frame requested", () => {
+ const clock = frames();
+ const settled: string[] = [];
+ const queue = createSettleQueue<string>(clock.request, (row) => settled.push(row));
+ queue.add("a");
+ queue.forget("a");
+ clock.run();
+ assert.equal(clock.pending(), 0);
+ clock.run();
+ assert.deepEqual(settled, []);
+});
+
+test("forgetting a row at either stage leaves the rows beside it", () => {
+ const clock = frames();
+ const settled: string[] = [];
+ const queue = createSettleQueue<string>(clock.request, (row) => settled.push(row));
+ queue.add("ripe kept");
+ queue.add("ripe forgotten");
+ clock.run();
+ queue.add("queued kept");
+ queue.add("queued forgotten");
+ queue.forget("ripe forgotten");
+ queue.forget("queued forgotten");
+ clock.run();
+ assert.deepEqual(settled, ["ripe kept"]);
+ clock.run();
+ assert.deepEqual(settled, ["ripe kept", "queued kept"]);
+ assert.equal(clock.pending(), 0);
+});
+
+test("remeasuring long transcripts lays out one row per frame and preserves the settle delay", () => {
+ const clock = frames();
+ const visible = new Set<number>();
+ const settled: number[] = [];
+ const settle = createSettleQueue<number>(clock.request, (row) => {
+ visible.delete(row);
+ settled.push(row);
+ });
+ const remeasure = createRemeasureQueue<number>(clock.request, (row) => {
+ visible.add(row);
+ settle.add(row);
+ }, () => false);
+ for (let i = 0; i < 100; i++) remeasure.add(i);
+ clock.run();
+ assert.deepEqual([...visible], [0]);
+ assert.deepEqual(settled, []);
+ clock.run();
+ assert.deepEqual([...visible], [0, 1]);
+ assert.deepEqual(settled, []);
+ for (let i = 0; clock.pending() && i < 200; i++) {
+ clock.run();
+ assert.ok(visible.size <= 3);
+ }
+ assert.deepEqual(settled, Array.from({ length: 100 }, (_, i) => i));
+ assert.equal(clock.pending(), 0);
+});
+
+test("a drag pauses remeasurement, repeated resizes coalesce, and removed rows stay removed", () => {
+ const clock = frames();
+ let dragging = true;
+ const measured: string[] = [];
+ const queue = createRemeasureQueue<string>(clock.request, (row) => measured.push(row), () => dragging);
+ queue.add("first");
+ queue.add("removed");
+ queue.add("last");
+ clock.run();
+ assert.deepEqual(measured, []);
+ queue.add("first");
+ queue.forget("removed");
+ dragging = false;
+ clock.run();
+ assert.deepEqual(measured, ["first"]);
+ clock.run();
+ assert.deepEqual(measured, ["first", "last"]);
+ assert.equal(clock.pending(), 0);
+});
diff --git a/studio/frontend/tests/reasoning-transcript-index.test.ts b/studio/frontend/tests/reasoning-transcript-index.test.ts
index 7a72c6f1f51..119bdfb7ae2 100644
--- a/studio/frontend/tests/reasoning-transcript-index.test.ts
+++ b/studio/frontend/tests/reasoning-transcript-index.test.ts
@@ -9,6 +9,7 @@ import { gfm } from "micromark-extension-gfm";
import { gfmFromMarkdown } from "mdast-util-gfm";
import {
ReasoningTranscriptIndex,
+ cachedReasoningTranscriptIndex,
findReasoningAnchor,
REASONING_FRAGMENT_CHARACTERS,
} from "../src/components/assistant-ui/reasoning-transcript-index.ts";
@@ -41,6 +42,50 @@ test("long prose remains lossless and completed fragments keep their identity",
);
});
+test("rewrites in any thinking segment advance the transcript generation", () => {
+ const index = new ReasoningTranscriptIndex();
+ const first = "Before the tool call.\n\n";
+ const second = "After the tool call.\n\n";
+ const before = index.update([first, second]);
+ const generation = index.generation;
+ const after = index.update([first, "Revised after the tool call.\n\n"]);
+ assert.equal(after[0], before[0]);
+ assert.notEqual(after[1].key, before[1].key);
+ assert.ok(index.generation > generation);
+
+ const restarted = index.generation;
+ index.update(["Revised before the tool call.\n\n", second]);
+ assert.ok(index.generation > restarted);
+});
+
+test("streamed appends and additional segments preserve the transcript generation", () => {
+ const index = new ReasoningTranscriptIndex();
+ index.update(["First thought.\n\n"]);
+ const generation = index.generation;
+ for (const sources of [
+ ["First thought.\n\n"],
+ ["First thought.\n\nMore thoughts."],
+ ["First thought.\n\nMore thoughts.", ""],
+ ["First thought.\n\nMore thoughts.", "After the tool call."],
+ ]) {
+ index.update(sources);
+ assert.equal(index.generation, generation);
+ }
+});
+
+test("removing and replacing a later segment cannot reuse its old transcript generation", () => {
+ const index = new ReasoningTranscriptIndex();
+ index.update(["First thought.", "Second thought."]);
+ const before = index.generation;
+ index.update(["First thought."]);
+ assert.ok(index.generation > before);
+ const removed = index.generation;
+ index.update(["First thought.", "Replacement thought."]);
+ assert.equal(index.generation, removed);
+ index.update(["First thought.", ""]);
+ assert.ok(index.generation > removed);
+});
+
test("a giant fence does not swallow the surrounding prose", () => {
const body = Array.from(
{ length: 5000 },
@@ -406,3 +451,20 @@ test("a list split between items does not invent a nested continuation", () => {
);
}
});
+
+test("a remount reuses the index it parsed before, bounded to the last eight messages", () => {
+ const first = cachedReasoningTranscriptIndex("m1");
+ assert.equal(cachedReasoningTranscriptIndex("m1"), first);
+ const source = "Earlier paragraph.\n\n```js\nconst x = 1;\n```\n\nLater paragraph.";
+ const fragments = first.update([source]);
+ const again = cachedReasoningTranscriptIndex("m1").update([source]);
+ assert.equal(again.length, fragments.length);
+ for (let i = 0; i < fragments.length; i += 1) {
+ assert.equal(again[i], fragments[i], "the same documents hand back the fragments already parsed");
+ }
+ for (let i = 2; i <= 9; i += 1) cachedReasoningTranscriptIndex(`m${i}`);
+ assert.notEqual(cachedReasoningTranscriptIndex("m1"), first, "the oldest entry was evicted");
+ const warm = cachedReasoningTranscriptIndex("m3");
+ for (let i = 10; i <= 16; i += 1) cachedReasoningTranscriptIndex(`m${i}`);
+ assert.equal(cachedReasoningTranscriptIndex("m3"), warm, "a recently used entry survives");
+});
diff --git a/studio/frontend/tests/reasoning-transcript-offscreen-scroll.test.ts b/studio/frontend/tests/reasoning-transcript-offscreen-scroll.test.ts
index ab56baba53b..668acdef074 100644
--- a/studio/frontend/tests/reasoning-transcript-offscreen-scroll.test.ts
+++ b/studio/frontend/tests/reasoning-transcript-offscreen-scroll.test.ts
@@ -34,23 +34,10 @@ test("a transcript watches its distance from the thread viewport", () => {
);
});
-test("a far transcript drops both viewport scroll listeners and resumes when near", () => {
+test("a far transcript drops its viewport scroll listener and resumes when near", () => {
const toggle = between(transcript, "const setNearby = ", "const proximity =");
- const [near, far] = toggle.split("} else {");
- assert.match(
- far,
- /followOffset\.current\?\.\(\s*false,/,
- "offset observer kept offscreen",
- );
- assert.match(
- far,
- /box\.bottom <= scroll\.getBoundingClientRect\(\)\.top\s*\?\s*1e9\s*:\s*-1e9/,
- );
- assert.match(
- far,
- /scroll\.removeEventListener\("scroll", schedule\)/,
- "measure listener kept offscreen",
- );
+ const [near, far] = toggle.split("\n scroll.removeEventListener(");
+ assert.ok(far, "no far branch");
assert.match(
near,
/scroll\.addEventListener\("scroll", schedule/,
@@ -58,28 +45,11 @@ test("a far transcript drops both viewport scroll listeners and resumes when nea
);
assert.match(
near,
- /if \(beforePaint\)[\s\S]*?flushSync\(\(\) => \{\s*measure\(\);\s*followOffset\.current\?\.\(true\);\s*\}\)/,
- );
-
- const observe = between(
- transcript,
- "observeElementOffset: (instance, callback) => {",
- "overscan:",
- );
- assert.match(
- observe,
- /if \(!on\) \{[\s\S]*?if \(park !== undefined\) callback\(park, false\);\s*return;\s*\}/,
- "offset observer cannot be stopped or parked",
- );
- assert.match(
- observe,
- /callback\(instance\.scrollElement\?\.scrollTop \?\? 0, false\);\s*stop = observeElementOffset\(instance,/,
- "resubscribing does not seed the current offset first",
- );
- assert.match(
- observe,
- /if \(current === generation\) callback\(offset, isScrolling\)/,
+ /if \(beforePaint\) flushSync\(capture\);\s*else schedule\(\);/,
+ "a jump back does not mount the rows in view before paint",
);
+ assert.match(far, /^"scroll", schedule\);/, "measure listener kept offscreen");
+ assert.match(far, /cancelAnimationFrame\(frame\);\s*frame = 0;/);
});
test("a jump past the observer margin wakes far transcripts through one listener per viewport", () => {
@@ -100,22 +70,15 @@ test("a jump past the observer margin wakes far transcripts through one listener
);
});
-test("a far transcript corrects a resize above the reader by its size change, not its frozen offset", () => {
- const adjust = between(
- transcript,
- "virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, delta) => {",
- "useLayoutEffect(",
- );
- assert.match(
- adjust,
- /if \(nearby\.current\) return true;\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*adjustAbove\(delta\);\s*return false;/,
- "a far transcript hands TanStack a correction from its frozen offset",
- );
+test("a far transcript still corrects a resize above the reader without the scroll listener", () => {
+ const remeasure = between(transcript, "rowRemeasurers.set(element, (row) => {", "});");
+ assert.match(remeasure, /element\.getBoundingClientRect\(\)\.bottom -/);
+ assert.match(remeasure, /adjustAbove\(Math\.round\(shift\)\)/);
+ assert.match(transcript, /const observer = new ResizeObserver\(/);
});
-test("a far transcript skips the reading-anchor scan", () => {
- assert.match(
- transcript,
- /if \(nearby\.current\)\s*for \(const row of element\.querySelectorAll<HTMLElement>\(\s*"\[data-index\]",?\s*\)\)/,
- );
+test("a far transcript drops its reading anchor and runs no anchor scan", () => {
+ const toggle = between(transcript, "const setNearby = ", "const proximity =");
+ assert.match(toggle, /reading = undefined;/);
+ assert.match(transcript, /if \(nearby\.current\)\s*scroll\.addEventListener\("scroll", schedule/);
});
diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.ts
index 2b84b4e0673..40fddf09aa4 100644
--- a/studio/frontend/tests/reload-snapshot.test.ts
+++ b/studio/frontend/tests/reload-snapshot.test.ts
@@ -326,6 +326,8 @@ function createEnvironment(options: {
const fontFaces: Array<{ family: string; source: string }> = [];
const appended: Array<{ innerHTML: string; removed: boolean }> = [];
let scrollRestoreCalls = 0;
+ let attributeObserver: ((records: { attributeName: string }[]) => void) | null = null;
+ let observingAttributes = false;
const bodyTree = options.rootTree
? createElement({
tag: "body",
@@ -372,6 +374,9 @@ function createEnvironment(options: {
removeAttribute: (name: string) => {
htmlAttributes.delete(name);
},
+ get attributes() {
+ return [...htmlAttributes].map(([name, value]) => ({ name, value }));
+ },
appendChild(element: { innerHTML: string; removed: boolean }) {
appended.push(element);
},
@@ -442,6 +447,11 @@ function createEnvironment(options: {
setAttribute(name: string, value: string) {
element.attributes[name] = value;
},
+ toggleAttribute(name: string, force: boolean) {
+ if (force) element.attributes[name] = "";
+ else delete element.attributes[name];
+ return force;
+ },
getAttribute(name: string) {
return element.attributes[name] ?? null;
},
@@ -486,6 +496,19 @@ function createEnvironment(options: {
// Timer bookkeeping is outside this lifecycle test.
},
document,
+ MutationObserver: class {
+ constructor(callback: (records: { attributeName: string }[]) => void) {
+ attributeObserver = callback;
+ }
+ observe(target: unknown, options: { attributes: boolean }) {
+ assert.equal(target, documentElement);
+ assert.equal(options.attributes, true);
+ observingAttributes = true;
+ }
+ disconnect() {
+ observingAttributes = false;
+ }
+ },
getComputedStyle: (element: StubElement) =>
// <html> resolves to its own declaration block, which is where the
// design tokens the copy has to carry are read from.
@@ -535,6 +558,14 @@ function createEnvironment(options: {
appended,
htmlVariables: documentElement.style,
htmlAttributes,
+ get observingAttributes() {
+ return observingAttributes;
+ },
+ changeRootAttribute(name: string, value: string | null) {
+ if (value === null) htmlAttributes.delete(name);
+ else htmlAttributes.set(name, value);
+ if (observingAttributes) attributeObserver?.([{ attributeName: name }]);
+ },
get scrollRestoreCalls() {
return scrollRestoreCalls;
},
@@ -1183,6 +1214,48 @@ test("roots the copy in an html element so html-anchored rules still match", ()
});
});
+test("gives the copy's root the live root's viewport gates, so width-gated rules match the same", () => {
+ const outgoing = createEnvironment({
+ navigationType: "navigate",
+ rootHtml: "<main>Existing chat</main>",
+ styleSheets: ["/assets/index-abc123.css"],
+ htmlAttributes: { "data-palette": "classic" },
+ });
+ outgoing.dispatch("pageswap", {
+ activation: { navigationType: "reload" },
+ });
+
+ const incoming = createEnvironment({
+ navigationType: "reload",
+ storage: outgoing.storage,
+ htmlAttributes: {
+ lang: "en",
+ "data-mq-min-width-40rem": "",
+ "data-mq-min-width-48rem": "",
+ },
+ });
+ assert.deepEqual(incoming.shell?.rootAttributes, {
+ "data-palette": "classic",
+ "data-mq-min-width-40rem": "",
+ "data-mq-min-width-48rem": "",
+ });
+ incoming.changeRootAttribute("data-mq-min-width-48rem", null);
+ incoming.changeRootAttribute("data-mq-min-width-64rem", "");
+ incoming.changeRootAttribute("data-palette", "changed");
+ assert.deepEqual(incoming.shell?.rootAttributes, {
+ "data-palette": "classic",
+ "data-mq-min-width-40rem": "",
+ "data-mq-min-width-64rem": "",
+ });
+ assert.equal(incoming.observingAttributes, true);
+ incoming.dispatch("unsloth:app-shell-ready");
+ incoming.runAnimationFrame();
+ incoming.runAnimationFrame();
+ assert.equal(incoming.observingAttributes, false);
+ incoming.changeRootAttribute("data-mq-min-width-40rem", null);
+ assert.equal(incoming.shell?.rootAttributes["data-mq-min-width-40rem"], "");
+});
+
test("freezes the design tokens onto the copy's own root", () => {
// `:root` matches a document's root element only, so tokens declared there
// never reach a shadow tree; the copy carries the resolved set instead.
diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.ts
index 875e32011c6..c2da6f5ad72 100644
--- a/studio/frontend/tests/resident-config-match.test.ts
+++ b/studio/frontend/tests/resident-config-match.test.ts
@@ -2020,7 +2020,7 @@ test("ejects stop only the ejected model's chats; eject all asks once and unload
);
assert.match(
USE_CHAT_MODEL_RUNTIME,
- /const scope =\s*!confirmed && useChatRuntimeStore\.getState\(\)\.loadedModels\.length > 1\s*\?\s*params\.checkpoint\s*:\s*undefined;\s*const stopDecision =\s*confirmed \?\?\s*\(await confirmStopRunningChatsIfNeeded\(\s*"Unloading the model",\s*"unload",\s*scope,\s*\)\);/,
+ /const scope =\s*!confirmed && useChatRuntimeStore\.getState\(\)\.loadedModels\.length > 1\s*\?\s*checkpoint\s*:\s*undefined;\s*const stopDecision =\s*confirmed \?\?\s*\(await confirmStopRunningChatsIfNeeded\(\s*"Unloading the model",\s*"unload",\s*scope,\s*\)\);/,
);
assert.match(USE_CHAT_MODEL_RUNTIME, /stopQueuedRuns\(stopDecision, Boolean\(scope\)\);/);
assert.match(
diff --git a/studio/frontend/tests/run-checkpoint-live-run.test.ts b/studio/frontend/tests/run-checkpoint-live-run.test.ts
new file mode 100644
index 00000000000..3dde42348d9
--- /dev/null
+++ b/studio/frontend/tests/run-checkpoint-live-run.test.ts
@@ -0,0 +1,52 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+registerBundlerResolver();
+
+const {
+ claimLiveGenerationRun,
+ releaseLiveGenerationRun,
+ resetServerActiveGenerationRuns,
+ syncServerActiveGenerationRuns,
+ threadHasDurableGenerationRun,
+ threadHasLiveGenerationRun,
+} = await import("../src/features/chat/utils/chat-generation-recovery.ts");
+
+test("only a run this tab streams counts as live, not one the server last named", () => {
+ resetServerActiveGenerationRuns();
+ syncServerActiveGenerationRuns("thread-1", ["followed-run"]);
+ assert.equal(threadHasDurableGenerationRun("thread-1"), true);
+ assert.equal(
+ threadHasLiveGenerationRun("thread-1"),
+ false,
+ "a follower that stalls leaves the server's answer behind, and a Continue after it streams through checkpoints alone",
+ );
+
+ claimLiveGenerationRun("run-1", "thread-1", { provisional: true });
+ assert.equal(threadHasLiveGenerationRun("thread-1"), false, "not admitted yet, so nothing on the server holds it");
+ claimLiveGenerationRun("run-1", "thread-1");
+ assert.equal(threadHasLiveGenerationRun("thread-1"), true);
+ assert.equal(threadHasLiveGenerationRun("thread-2"), false);
+ releaseLiveGenerationRun("run-1");
+ assert.equal(threadHasLiveGenerationRun("thread-1"), false);
+ resetServerActiveGenerationRuns();
+});
+
+test("checkpoints are skipped only while this tab streams the thread's durable run", () => {
+ const provider = readSrc("features/chat/runtime-provider.tsx");
+ assert.match(
+ provider,
+ /\(threadId\) =>\s*threadHasLiveGenerationRun\(threadId\)\s*\?\s*Promise\.resolve\(\)\s*:\s*queueSaveRef\.current\(threadId\),/,
+ );
+ assert.match(
+ provider,
+ /isBounded: \(threadId\) => threadHasDurableGenerationRun\(threadId\),/,
+ );
+});
diff --git a/studio/frontend/tests/schedule-idle-task-fallback.test.ts b/studio/frontend/tests/schedule-idle-task-fallback.test.ts
new file mode 100644
index 00000000000..7b32c1998da
--- /dev/null
+++ b/studio/frontend/tests/schedule-idle-task-fallback.test.ts
@@ -0,0 +1,118 @@
+// 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, { type TestContext } from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type IdleModule = {
+ scheduleIdleTask: (callback: () => void, timeout?: number) => () => void;
+ scheduleQuietIdleTask: (callback: () => void, timeout?: number) => () => void;
+ inputQuietIn: () => number;
+};
+
+function engine(t: TestContext, idle?: (callback: () => void) => number) {
+ let now = 1_000;
+ const listeners = new Map<string, () => void>();
+ const scope = globalThis as Record<string, unknown>;
+ const saved = { window: scope.window, document: scope.document, performance: scope.performance };
+ scope.window = idle ? { requestIdleCallback: idle, cancelIdleCallback: () => {} } : {};
+ scope.document = {
+ addEventListener: (type: string, listener: () => void) => listeners.set(type, listener),
+ };
+ Object.defineProperty(globalThis, "performance", { value: { now: () => now }, configurable: true, writable: true });
+ t.after(() => {
+ scope.window = saved.window;
+ scope.document = saved.document;
+ Object.defineProperty(globalThis, "performance", { value: saved.performance, configurable: true, writable: true });
+ });
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const idleModule = loadWithStubs<IdleModule>(new URL("../src/lib/schedule-idle-task.ts", import.meta.url), {});
+ const advance = (ms: number) => {
+ for (let step = 0; step < ms; step += 1) {
+ now += 1;
+ t.mock.timers.tick(1);
+ }
+ };
+ const input = (type: string) => listeners.get(type)?.();
+ return { idleModule, advance, input, listeners };
+}
+
+test("without requestIdleCallback, the shared scheduler keeps its 120 ms timer whatever the input", (t) => {
+ const { idleModule, advance, input } = engine(t);
+ let ran = 0;
+ input("pointerdown");
+ idleModule.scheduleIdleTask(() => (ran += 1), 1000);
+ advance(119);
+ assert.equal(ran, 0);
+ advance(2);
+ assert.equal(ran, 1, "settings, the hub readme and markdown previews wait no longer than on main");
+});
+
+test("without requestIdleCallback, a quiet task runs soon when nothing is happening", (t) => {
+ const { idleModule, advance } = engine(t);
+ let ran = 0;
+ idleModule.scheduleQuietIdleTask(() => (ran += 1), 1000);
+ advance(15);
+ assert.equal(ran, 0);
+ advance(2);
+ assert.equal(ran, 1);
+});
+
+test("a quiet task waits for input to go quiet, so it never lands in the middle of a scroll", (t) => {
+ const { idleModule, advance, input, listeners } = engine(t);
+ for (const type of ["wheel", "scroll", "pointerdown", "keydown", "touchstart", "touchmove"]) {
+ idleModule.inputQuietIn();
+ assert.ok(listeners.has(type), `${type} counts as input`);
+ }
+ let ran = 0;
+ input("wheel");
+ idleModule.scheduleQuietIdleTask(() => (ran += 1), 1000);
+ advance(200);
+ input("scroll");
+ advance(299);
+ assert.equal(ran, 0, "300 ms after the last input, not after the first");
+ advance(2);
+ assert.equal(ran, 1);
+});
+
+test("continuous input cannot starve a quiet task past its deadline", (t) => {
+ const { idleModule, advance, input } = engine(t);
+ let ran = 0;
+ idleModule.scheduleQuietIdleTask(() => (ran += 1), 500);
+ for (let at = 0; at < 480; at += 40) {
+ input("wheel");
+ advance(40);
+ }
+ assert.equal(ran, 0);
+ input("wheel");
+ advance(40);
+ assert.equal(ran, 1, "the deadline holds, as requestIdleCallback's timeout does");
+});
+
+test("a cancelled task never runs", (t) => {
+ const { idleModule, advance, input } = engine(t);
+ let ran = 0;
+ idleModule.scheduleIdleTask(() => (ran += 1), 1000)();
+ idleModule.scheduleQuietIdleTask(() => (ran += 1), 1000)();
+ input("wheel");
+ const cancel = idleModule.scheduleQuietIdleTask(() => (ran += 1), 1000);
+ advance(100);
+ cancel();
+ advance(2000);
+ assert.equal(ran, 0, "including a quiet task already waiting out input");
+});
+
+test("engines with requestIdleCallback keep it", (t) => {
+ const queued: Array<() => void> = [];
+ const { idleModule, advance } = engine(t, (callback) => queued.push(callback));
+ let ran = 0;
+ idleModule.scheduleIdleTask(() => (ran += 1), 1000);
+ idleModule.scheduleQuietIdleTask(() => (ran += 1), 1000);
+ advance(1000);
+ assert.equal(ran, 0);
+ assert.equal(queued.length, 2);
+ for (const callback of queued) callback();
+ assert.equal(ran, 2);
+});
diff --git a/studio/frontend/tests/sidebar-action-rows-inert.test.ts b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
index 07d1d486111..3984eef51bf 100644
--- a/studio/frontend/tests/sidebar-action-rows-inert.test.ts
+++ b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
@@ -161,7 +161,7 @@ test("the sidebar list measures its scroll rail", async () => {
assert.deepEqual(railWidthDecls, []);
assert.match(
INDEX,
- /:root\.client-windows \*,\s*:root\.client-windows \*:hover \{\s*scrollbar-width: auto;/,
+ /:root\.client-windows \* \{\s*scrollbar-width: auto;/,
);
assert.equal(
/\.sidebar-scroll-fade::-webkit-scrollbar \{/.test(INDEX),
diff --git a/studio/frontend/tests/sidebar-wrapper-children.test.ts b/studio/frontend/tests/sidebar-wrapper-children.test.ts
new file mode 100644
index 00000000000..9a7cd12626b
--- /dev/null
+++ b/studio/frontend/tests/sidebar-wrapper-children.test.ts
@@ -0,0 +1,27 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("pinning the desktop sidebar never adds or removes a child of the sidebar wrapper", () => {
+ const trigger = readSrc("components/sidebar-edge-trigger.tsx");
+ assert.match(trigger, /if \(!isTauri\) \{\s*return null;\s*\}/);
+ assert.doesNotMatch(
+ trigger,
+ /sidebarShowing && !holding\)\) \{\s*return null/,
+ "returning null while pinned inserted the strip between the sidebar and <main> on every unpin",
+ );
+ assert.match(
+ trigger,
+ /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",
+ );
+});
diff --git a/studio/frontend/tests/skipped-content-remeasure.test.ts b/studio/frontend/tests/skipped-content-remeasure.test.ts
new file mode 100644
index 00000000000..ce74fab3826
--- /dev/null
+++ b/studio/frontend/tests/skipped-content-remeasure.test.ts
@@ -0,0 +1,73 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+register("./helpers/tauri-webview-resolver.mjs", import.meta.url);
+
+const attributes = new Set<string>();
+const scope = globalThis as { window?: unknown; document?: unknown };
+scope.window = {
+ location: { protocol: "https:" },
+ localStorage: {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ },
+};
+scope.document = {
+ documentElement: {
+ style: {
+ setProperty: () => undefined,
+ removeProperty: () => undefined,
+ },
+ setAttribute: (name: string) => attributes.add(name),
+ removeAttribute: (name: string) => attributes.delete(name),
+ toggleAttribute: (name: string, on: boolean) =>
+ on ? attributes.add(name) : attributes.delete(name),
+ classList: { toggle: () => undefined },
+ },
+};
+
+const { applyCustomizationToDocument, DEFAULT_CUSTOMIZATION } = await import(
+ "../src/features/settings/stores/appearance-custom-store.ts"
+);
+const { applyInterfaceScale } = await import(
+ "../src/features/settings/stores/interface-scale-store.ts"
+);
+
+const HOLD = "data-interface-zooming";
+
+test("a typography change renders skipped blocks until they are laid out at the new metrics", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ applyCustomizationToDocument(DEFAULT_CUSTOMIZATION, "light");
+ assert.equal(attributes.has(HOLD), false, "the first application has nothing laid out at older metrics");
+ applyCustomizationToDocument({ ...DEFAULT_CUSTOMIZATION, contrast: 70 }, "light");
+ assert.equal(attributes.has(HOLD), false, "a colour change leaves every remembered size right");
+ applyCustomizationToDocument({ ...DEFAULT_CUSTOMIZATION, codeFontSize: 16 }, "light");
+ assert.equal(attributes.has(HOLD), true, "a skipped code block keeps the height of the old code font size");
+ t.mock.timers.tick(299);
+ assert.equal(attributes.has(HOLD), true);
+ t.mock.timers.tick(1);
+ assert.equal(attributes.has(HOLD), false);
+ applyCustomizationToDocument({ ...DEFAULT_CUSTOMIZATION, codeFontSize: 16, uiFontSize: 18 }, "light");
+ assert.equal(attributes.has(HOLD), true, "and a thinking chunk the height of the old UI font size");
+ t.mock.timers.tick(300);
+ applyCustomizationToDocument({ ...DEFAULT_CUSTOMIZATION, codeFontSize: 16, uiFontSize: 18, chatFont: "Inter" }, "dark");
+ assert.equal(attributes.has(HOLD), true, "a font family changes the metrics as much as a size");
+ t.mock.timers.tick(300);
+ assert.equal(attributes.has(HOLD), false);
+});
+
+test("a browser scale change renders skipped blocks until they are laid out at the new scale", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await applyInterfaceScale(110);
+ await applyInterfaceScale(110);
+ assert.equal(attributes.has(HOLD), false, "the scale applied before the first paint has nothing laid out at another scale");
+ await applyInterfaceScale(125);
+ assert.equal(attributes.has(HOLD), true, "a skipped block keeps the height it had at the old scale");
+ t.mock.timers.tick(300);
+ assert.equal(attributes.has(HOLD), false);
+});
diff --git a/studio/frontend/tests/slider-draft.test.ts b/studio/frontend/tests/slider-draft.test.ts
new file mode 100644
index 00000000000..af6bdac5936
--- /dev/null
+++ b/studio/frontend/tests/slider-draft.test.ts
@@ -0,0 +1,324 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Draft = {
+ draft: number | null;
+ sliderProps: {
+ value: number[];
+ onPointerDown: (event: { pointerId: number }) => void;
+ onValueChange: (value: number[]) => void;
+ onValueCommit: (value: number[]) => void;
+ onLostPointerCapture: (event: { pointerId: number }) => void;
+ };
+};
+
+const documentEvents = new EventTarget();
+Object.defineProperty(globalThis, "document", {
+ value: documentEvents,
+ configurable: true,
+ writable: true,
+});
+const teardown: (() => void)[] = [];
+test.afterEach(() => {
+ for (const cleanup of teardown.splice(0)) cleanup();
+});
+
+const FINGER = { pointerId: 1 };
+
+function mountDraft(value: number, onDraft?: (value: number | null) => void) {
+ const slots: unknown[] = [];
+ const synced: unknown[] = [];
+ const cleanups: (() => void)[] = [];
+ let cursor = 0;
+ let flushing = false;
+ let pendingOwned: number | null = null;
+ const react = {
+ useState: (initial: unknown) => {
+ const at = cursor++;
+ if (!(at in slots)) slots[at] = initial;
+ return [
+ slots[at],
+ (next: unknown) => {
+ slots[at] = next;
+ if (flushing) synced.push(next);
+ },
+ ];
+ },
+ useRef: (initial: unknown) => {
+ const at = cursor++;
+ if (!(at in slots)) slots[at] = { current: initial };
+ return slots[at];
+ },
+ useEffectEvent: (handler: (event?: Event) => void) => {
+ const at = cursor++;
+ if (!(at in slots)) slots[at] = { handler, call: (event?: Event) => (slots[at] as { handler: (event?: Event) => void }).handler(event) };
+ const event = slots[at] as { handler: (event?: Event) => void; call: (event?: Event) => void };
+ event.handler = handler;
+ return event.call;
+ },
+ useLayoutEffect: (effect: () => (() => void) | void, deps: unknown[]) => {
+ const at = cursor++;
+ const previous = slots[at] as unknown[] | undefined;
+ if (
+ previous &&
+ deps.every((value, index) => Object.is(value, previous[index]))
+ ) return;
+ slots[at] = deps;
+ const cleanup = effect();
+ if (cleanup) cleanups.push(cleanup);
+ },
+ };
+ const { useSliderDraft } = loadWithStubs<{
+ useSliderDraft: (
+ value: number,
+ onCommit: (value: number) => void,
+ onDraft?: (value: number | null) => void,
+ ) => Draft;
+ }>(new URL("../src/hooks/use-slider-draft.ts", import.meta.url), {
+ react,
+ "react-dom": {
+ flushSync: (update: () => void) => {
+ flushing = true;
+ update();
+ if (pendingOwned !== null) {
+ owned = pendingOwned;
+ pendingOwned = null;
+ }
+ SliderRow();
+ flushing = false;
+ },
+ },
+ });
+ const commits: number[] = [];
+ let owned = value;
+ const SliderRow = () => {
+ cursor = 0;
+ return useSliderDraft(owned, (next) => commits.push(next), onDraft);
+ };
+ const unmount = () => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+ };
+ const setOwned = (next: number) => {
+ owned = next;
+ };
+ teardown.push(unmount);
+ const queueOwned = (next: number) => {
+ pendingOwned = next;
+ };
+ return { render: SliderRow, commits, synced, unmount, setOwned, queueOwned };
+}
+
+test("a drag moves the thumb locally and hands its owner one settled value", () => {
+ const { render, commits } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onValueChange([0.6]);
+ render().sliderProps.onValueChange([0.7]);
+ const dragging = render();
+ assert.equal(dragging.draft, 0.7);
+ assert.deepEqual(dragging.sliderProps.value, [0.7]);
+ assert.deepEqual(commits, [], "the owner re-renders once per drag, not once per pointer move");
+
+ dragging.sliderProps.onValueCommit([0.7]);
+ dragging.sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(commits, [0.7], "Radix's own commit at release is not a second one");
+ assert.equal(render().draft, null);
+});
+
+test("a release right behind the last move commits that move", () => {
+ const { render, commits } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ const row = render();
+ row.sliderProps.onValueChange([0.6]);
+ row.sliderProps.onValueChange([0.9]);
+ row.sliderProps.onValueCommit([0.6]);
+ row.sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(commits, [0.9], "Radix commits the value its last render saw, a move behind the pointer");
+});
+
+test("each move is drawn in the frame it arrives in", () => {
+ const { render, synced } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onValueChange([0.6]);
+ render().sliderProps.onValueChange([0.9]);
+ assert.deepEqual(synced, [0.6, 0.9], "a plain state update waits for a later task and trails the pointer by a frame");
+});
+
+test("a drag that ends where it started commits nothing and leaves no draft", () => {
+ const { render, commits } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onValueChange([0.6]);
+ render().sliderProps.onValueChange([0.5]);
+ render().sliderProps.onLostPointerCapture(FINGER);
+ assert.equal(render().draft, null);
+ assert.deepEqual(commits, []);
+});
+
+test("a drag cut short keeps the value it reached, as a native range input does", () => {
+ const { render, commits } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onValueChange([0.8]);
+ render().sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(commits, [0.8], "a pointercancel or a stolen capture threw the drag away");
+ assert.equal(render().draft, null);
+});
+
+test("a drag whose row goes away keeps the value it reached, as main's live writes did", () => {
+ const previews: (number | null)[] = [];
+ const cut = mountDraft(0.5, (next) => previews.push(next));
+ cut.render().sliderProps.onPointerDown(FINGER);
+ cut.render().sliderProps.onValueChange([0.8]);
+ cut.unmount();
+ assert.deepEqual(cut.commits, [0.8], "Escape closed the model picker mid-drag and dropped the dragged value");
+ assert.deepEqual(previews, [0.8, null], "an owner that follows the drag hears that it ended");
+
+ const ended = mountDraft(0.5);
+ ended.render().sliderProps.onPointerDown(FINGER);
+ ended.render().sliderProps.onValueChange([0.8]);
+ ended.render().sliderProps.onLostPointerCapture(FINGER);
+ ended.unmount();
+ assert.deepEqual(ended.commits, [0.8], "a drag that already ended is not committed twice");
+});
+
+test("a change from outside after the last move wins at release, as it did with main's live writes", () => {
+ const held = mountDraft(0.7);
+ held.render().sliderProps.onPointerDown(FINGER);
+ held.render().sliderProps.onValueChange([0.9]);
+ held.setOwned(0.6);
+ held.render().sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(held.commits, [], "a model load that landed while the thumb was held still was overwritten by the dragged value");
+ assert.equal(held.render().draft, null);
+
+ const moved = mountDraft(0.7);
+ moved.render().sliderProps.onPointerDown(FINGER);
+ moved.render().sliderProps.onValueChange([0.9]);
+ moved.setOwned(0.6);
+ moved.render().sliderProps.onValueChange([0.8]);
+ moved.render().sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(moved.commits, [0.8], "a move after the change is the newer intent");
+});
+
+test("a second finger on the slider keeps the drag going after the first one lifts", () => {
+ const { render, commits } = mountDraft(0.5);
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onPointerDown({ pointerId: 2 });
+ render().sliderProps.onValueChange([0.6]);
+ render().sliderProps.onValueCommit([0.6]);
+ render().sliderProps.onLostPointerCapture(FINGER);
+ render().sliderProps.onValueChange([0.8]);
+ assert.equal(render().draft, 0.8, "the second finger's moves were dropped once the first one lifted");
+ assert.deepEqual(commits, []);
+ render().sliderProps.onLostPointerCapture({ pointerId: 2 });
+ assert.deepEqual(commits, [0.8]);
+ assert.equal(render().draft, null);
+});
+
+test("an owner can follow the drag and hears when it ends", () => {
+ const previews: (number | null)[] = [];
+ const { render } = mountDraft(10, (next) => previews.push(next));
+ render().sliderProps.onPointerDown(FINGER);
+ render().sliderProps.onValueChange([12]);
+ render().sliderProps.onValueChange([14]);
+ render().sliderProps.onLostPointerCapture(FINGER);
+ assert.deepEqual(previews, [12, 14, null]);
+});
+
+test("keyboard steps go straight to the owner", () => {
+ const { render, commits } = mountDraft(4);
+ render().sliderProps.onValueChange([5]);
+ render().sliderProps.onValueCommit([5]);
+ assert.equal(render().draft, null);
+ assert.deepEqual(commits, [5]);
+});
+
+test("the Run settings and model picker sliders drag on a draft", () => {
+ for (const [file, rows] of [
+ ["features/chat/chat-settings-sheet.tsx", 1],
+ ["features/model-picker/components/model-config-page.tsx", 3],
+ ] as const) {
+ const source = readSrc(file);
+ assert.equal(source.match(/= useSliderDraft\(/g)?.length, rows, file);
+ assert.doesNotMatch(source, /onValueChange=\{\(\[\w+\]\) => (?:onChange|setContextSliderValue)\(/, file);
+ }
+});
+
+test("what an owner shows beside its slider follows the drag", () => {
+ const picker = readSrc("features/model-picker/components/model-config-page.tsx");
+ assert.match(picker, /onDraft=\{setDraftPercent\}/);
+ assert.match(picker, /\{shownPercent !== defaultPercent && \(/, "the VRAM advice contradicted the dragged percent");
+ assert.match(picker, /displayValue=\{isMlx && windowUnknown && !dragging \? "—" : undefined\}/, "an unknown MLX window showed a dash for the whole drag");
+ assert.match(picker, /\{renderWarning\(shown\)\}/);
+ const music = readSrc("features/audio/components/music-edit-inputs.tsx");
+ assert.match(music, /onDraft=\{setDraggedExtendS\}/);
+ assert.match(music, /tailS=\{action === "extend" \? \(draggedExtendS \?\? draft\.extendS\) : 0\}/, "the extend tail stopped growing while Add seconds was dragged");
+ assert.match(
+ readSrc("features/chat/chat-settings-sheet.tsx"),
+ /const sliderProps = commitWhileDragging\s*\? \{ value: \[value\], onValueChange: \(\[v\]: number\[\]\) => commit\(v\) \}\s*: draftProps;/,
+ );
+ assert.match(
+ readSrc("features/audio/pages/music-page.tsx"),
+ /label="Variations"[\s\S]*?onChange=\{onChange\}\s*commitWhileDragging/,
+ "the reload notice under Variations named the count from before the drag",
+ );
+ const edit = readSrc("features/audio/pages/edit-page.tsx");
+ assert.match(edit, /onChange=\{\(speed\) => setDelivery\(\{ speed \}\)\}\s*commitWhileDragging/, "the Generate blocker and the edit-pass text lagged a Speed drag");
+ assert.match(edit, /onChange=\{\(pitchSteps\) => setDelivery\(\{ pitchSteps \}\)\}\s*commitWhileDragging/);
+});
+
+test("a sampling change re-renders the Run settings panel, not the chat page", () => {
+ const page = readSrc("features/chat/chat-page.tsx");
+ assert.match(page, /const inferenceCheckpoint = useChatRuntimeStore\(\s*\(state\) => state\.params\.checkpoint,\s*\);/);
+ for (const file of ["features/chat/chat-page.tsx", "features/chat/hooks/use-chat-model-runtime.ts"]) {
+ assert.doesNotMatch(readSrc(file), /useChatRuntimeStore\(\(\w+\) => \w+\.params\)/, `${file} re-rendered the whole chat page for every sampling change`);
+ }
+ assert.match(readSrc("features/chat/chat-settings-sheet.tsx"), /const params = useChatRuntimeStore\(\(s\) => s\.params\);/);
+});
+
+test("a Run settings commit lands on the params the store holds when it is made", () => {
+ assert.match(
+ readSrc("features/chat/chat-settings-sheet.tsx"),
+ /function set<K extends keyof InferenceParams>\(key: K\) \{\s*return \(v: InferenceParams\[K\]\) => \{\s*const nextParams = \{\s*\.\.\.useChatRuntimeStore\.getState\(\)\.params,/,
+ "a slider that unmounts in the commit that switched the model commits from its last render, and that render's params would switch the model back",
+ );
+});
+
+test("a track click after a number input blur commits against the flushed owner", () => {
+ const held = mountDraft(0.5);
+ const stale = held.render().sliderProps;
+ stale.onPointerDown(FINGER);
+ held.queueOwned(0.9);
+ stale.onValueChange([0.3]);
+ stale.onLostPointerCapture(FINGER);
+ assert.deepEqual(held.commits, [0.3]);
+});
+
+test("a removed capture target releases its pointer through the document", () => {
+ const held = mountDraft(0.5);
+ held.render().sliderProps.onPointerDown(FINGER);
+ held.render().sliderProps.onValueChange([0.7]);
+ documentEvents.dispatchEvent(Object.assign(new Event("lostpointercapture"), FINGER));
+ assert.deepEqual(held.commits, [0.7]);
+ held.setOwned(0.7);
+ held.render().sliderProps.onValueCommit([0.8]);
+ assert.deepEqual(held.commits, [0.7, 0.8]);
+ held.unmount();
+ documentEvents.dispatchEvent(Object.assign(new Event("lostpointercapture"), FINGER));
+ assert.deepEqual(held.commits, [0.7, 0.8]);
+});
+
+test("a draft callback that unmounts the row still commits the latest move", () => {
+ let remove = () => {};
+ const held = mountDraft(0.5, (next) => {
+ if (next !== null) remove();
+ });
+ remove = held.unmount;
+ held.render().sliderProps.onPointerDown(FINGER);
+ held.render().sliderProps.onValueChange([0.8]);
+ assert.deepEqual(held.commits, [0.8]);
+ assert.equal(held.render().draft, null);
+});
diff --git a/studio/frontend/tests/slider-thumb-accessible-value.test.ts b/studio/frontend/tests/slider-thumb-accessible-value.test.ts
index 560e61fd3ae..b5e35332504 100644
--- a/studio/frontend/tests/slider-thumb-accessible-value.test.ts
+++ b/studio/frontend/tests/slider-thumb-accessible-value.test.ts
@@ -55,12 +55,12 @@ test("the context slider says Auto rather than zero", () => {
});
test("Auto announces a current value only once one exists", () => {
- // Before a load contextInputValue is the offload fallback that seeds the input,
+ // Before a load autoValue is the offload fallback that seeds the input,
// not a selection: Auto may still fit the model's native context. Announcing it
// as "currently N" tells a screen-reader user a number no other user is shown.
assert.match(
panel,
- /activeLoadedContext != null \? `Auto, currently \$\{contextInputValue\.toLocaleString\(\)\} tokens` : "Auto"/,
+ /activeLoadedContext != null \? `Auto, currently \$\{autoValue\.toLocaleString\(\)\} tokens` : "Auto"/,
);
});
diff --git a/studio/frontend/tests/stream-activity.test.ts b/studio/frontend/tests/stream-activity.test.ts
new file mode 100644
index 00000000000..65750b734cc
--- /dev/null
+++ b/studio/frontend/tests/stream-activity.test.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
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ STREAM_COOLDOWN_MS,
+ createStreamActivity,
+} from "../src/components/assistant-ui/stream-activity.ts";
+
+type Running = { runningByThreadId: Record<string, boolean> };
+
+const stubStore = () => {
+ let state: Running = { runningByThreadId: {} };
+ const listeners = new Set<(next: Running, previous: Running) => void>();
+ return {
+ getState: () => state,
+ subscribe: (listener: (next: Running, previous: Running) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ set: (running: Record<string, boolean>) => {
+ const previous = state;
+ state = { runningByThreadId: running };
+ for (const listener of listeners) listener(state, previous);
+ },
+ };
+};
+
+test("a stream is active while any thread runs and for the cooldown after the last run ends", () => {
+ assert.equal(STREAM_COOLDOWN_MS, 2_000);
+ let now = 10_000;
+ const store = stubStore();
+ const activity = createStreamActivity(store, () => now);
+ assert.equal(activity.active(), false);
+ store.set({ a: true });
+ assert.equal(activity.active(), true);
+ store.set({ a: true, b: false });
+ assert.equal(activity.active(), true);
+ store.set({ a: false, b: false });
+ assert.equal(activity.active(), true);
+ now += STREAM_COOLDOWN_MS - 1;
+ assert.equal(activity.active(), true);
+ now += 1;
+ assert.equal(activity.active(), false);
+});
+
+test("a run that never started leaves no cooldown behind", () => {
+ let now = 0;
+ const store = stubStore();
+ const activity = createStreamActivity(store, () => now);
+ store.set({ a: false });
+ now = 1;
+ assert.equal(activity.active(), false);
+});
diff --git a/studio/frontend/tests/streaming-render-schedule.test.ts b/studio/frontend/tests/streaming-render-schedule.test.ts
index b5e04981bd4..84bfb148144 100644
--- a/studio/frontend/tests/streaming-render-schedule.test.ts
+++ b/studio/frontend/tests/streaming-render-schedule.test.ts
@@ -1143,3 +1143,18 @@ test("a live reference pair inside a list or quote still holds as one document",
assert.equal(isFullDocumentMode(cache), true, definition);
}
});
+
+test("the animation-free plugin list keeps its identity across Streamdown's rebuilds", () => {
+ const animation = () => undefined;
+ const other = () => undefined;
+ const tuple = [other, { depth: 1 }] as const;
+ const animatePlugin = { rehypePlugin: animation } as never;
+ const streaming = [other, [tuple[0], tuple[1]], animation] as never;
+ const settled = [other, [tuple[0], tuple[1]]] as never;
+ const first = withoutStreamdownAnimationPlugin(streaming, animatePlugin);
+ const second = withoutStreamdownAnimationPlugin(settled, animatePlugin);
+ assert.equal(first, second, "the same plugins in the same order are one list, so blocks keep their memoised render");
+ assert.equal(withoutStreamdownAnimationPlugin(streaming, animatePlugin), first, "and a repeated input is a cache hit");
+ const different = [other] as never;
+ assert.notEqual(withoutStreamdownAnimationPlugin(different, animatePlugin), first, "a different list is a different identity");
+});
diff --git a/studio/frontend/tests/thread-portal-page-drop.test.ts b/studio/frontend/tests/thread-portal-page-drop.test.ts
new file mode 100644
index 00000000000..49ece4159bd
--- /dev/null
+++ b/studio/frontend/tests/thread-portal-page-drop.test.ts
@@ -0,0 +1,24 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("a file dropped on a message reaches the page-wide drop handlers through the portal host", () => {
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ const hostStart = thread.indexOf("<ThreadPrimitive.Viewport");
+ const portalStart = thread.indexOf("createPortal(", hostStart);
+ const rootStart = thread.indexOf("<ThreadPrimitive.Root", portalStart);
+ assert.ok(hostStart >= 0 && portalStart > hostStart && rootStart > portalStart);
+ const host = thread.slice(hostStart, portalStart);
+ const portal = thread.slice(portalStart, rootStart);
+ const root = thread.slice(rootStart, thread.indexOf("<IntentAwareScrollProvider", rootStart));
+ assert.match(host, /className="aui-thread-host hidden"/);
+ assert.ok(portal.includes("<ProgressiveMessages"), "the rows are portaled from the host, so React routes their events to it and never to the root");
+ for (const handler of ["onDragEnter", "onDragOver", "onDragLeave", "onDrop"]) {
+ assert.ok(host.includes(`${handler}={${handler}}`), `the portal host forwards ${handler}`);
+ assert.ok(root.includes(`${handler}={${handler}}`), `the thread root keeps ${handler} for the viewport padding and the composer dock`);
+ }
+});
diff --git a/studio/frontend/tests/thread-read-sharing-source.test.ts b/studio/frontend/tests/thread-read-sharing-source.test.ts
new file mode 100644
index 00000000000..873de9d4dd0
--- /dev/null
+++ b/studio/frontend/tests/thread-read-sharing-source.test.ts
@@ -0,0 +1,70 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const API = readSrc("features/chat/api/chat-api.ts");
+const STORAGE = readSrc("features/chat/utils/chat-history-storage.ts");
+const BAR = readSrc("features/rag/components/thread-documents-bar.tsx");
+
+function slice(source: string, from: string, to: string): string {
+ const start = source.indexOf(from);
+ assert.ok(start !== -1, `not found: ${from}`);
+ const end = source.indexOf(to, start + from.length);
+ assert.ok(end !== -1, `not found: ${to}`);
+ return source.slice(start, end);
+}
+
+test("only the UI readers share a thread read; every post-write reader stays private", () => {
+ const uiRead = slice(STORAGE, "export async function getStoredChatThreadReadResult", "\n}");
+ assert.match(uiRead, /share: true/);
+ const history = slice(STORAGE, "export async function readStoredChatMessages", "\n}");
+ assert.match(history, /getChatThread\(threadId, \{ share: true \}\)/);
+ for (const name of [
+ "export async function ensureStoredChatThread",
+ "async function retryFailedThreadRecord",
+ "async function publishForkBoundary",
+ "export async function syncStoredChatMessages",
+ "export async function deleteStoredChatThreads",
+ "export async function readBackendChatThread",
+ ]) {
+ assert.doesNotMatch(slice(STORAGE, name, "\n}"), /share: true/, name);
+ }
+});
+
+test("every thread write through chat-api drops the thread's in-flight read when it settles", () => {
+ const write = slice(API, "async function threadWriteFetch", "\n}");
+ assert.equal((write.match(/forgetThreadReads\(affected\)/g) ?? []).length, 2);
+ assert.match(slice(API, "export async function saveChatThread", "\n}"), /\[thread\.id\],/);
+ assert.match(slice(API, "export async function updateChatThread", "\n}"), /\[threadId\],\s*options\.signal,/);
+ assert.match(slice(API, "export async function deleteChatThreads", "\n}"), /threadIds,\s*\);/);
+ assert.match(slice(API, "export async function syncChatMessages", "\n}"), /\[threadId\],\s*\);/);
+ assert.match(slice(API, "export async function clearBackendChats", "\n}"), /null,\s*\);/);
+ assert.match(slice(API, "export async function saveChatMessage", "\n}"), /forgetThreadReads\(\[message\.threadId\]\)/);
+ assert.match(slice(API, "export async function forkChatThread", "\n}"), /forgetThreadReads\(\[threadId, args\.newThreadId\]\)/);
+ assert.match(slice(API, "export async function deleteChatProject", "\n}"), /forgetThreadReads\(null\)/);
+});
+
+test("the shared read keeps the deadline and abort handling the pairing relies on", () => {
+ const get = slice(API, "export async function getChatThread", "\n}");
+ assert.match(get, /options\.timeoutMs !== undefined/);
+ assert.match(get, /combineAbortSignals\(\[timeout\.signal, options\.signal\]\)/);
+ assert.match(get, /options\.share\s*\?\s*await shareThreadRead\(threadId, signal\)/);
+ const share = slice(API, "function shareThreadRead", "\n}");
+ assert.match(share, /\|\| performance\.now\(\) - shared\.startedAt > THREAD_READ_JOIN_MS/, "only a read started inside the join window is shared");
+ assert.match(share, /\|\| shared\.authEpoch !== authEpoch/, "a read started under another auth session is never joined");
+ assert.match(share, /if \(joined\.readers === 0\) joined\.controller\.abort\(signal\.reason\)/);
+ assert.match(share, /reject\(abortError\(signal\)\)/);
+});
+
+test("the documents bar reads the row once per chat and follows the history event for moves", () => {
+ const hook = slice(BAR, "function useThreadProjectId", "\n}");
+ assert.match(hook, /\}, \[threadId\]\);/);
+ assert.doesNotMatch(hook, /\[threadId, activeProjectId\]/);
+ assert.match(hook, /subscribeChatHistoryUpdated\(\(\{ thread \}\) => \{/);
+ assert.match(hook, /thread\.id !== threadId\) return;/);
+ assert.match(hook, /useChatRuntimeStore\.getState\(\)\.activeProjectId/);
+});
diff --git a/studio/frontend/tests/thread-read-sharing.test.ts b/studio/frontend/tests/thread-read-sharing.test.ts
new file mode 100644
index 00000000000..af7ab4a6bc3
--- /dev/null
+++ b/studio/frontend/tests/thread-read-sharing.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 * as abortSignals from "../src/features/hub/lib/abort-signals.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Row = { id: string; title: string };
+type Module = {
+ getChatThread: (
+ threadId: string,
+ options?: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal; share?: boolean },
+ ) => Promise<Row | null>;
+ updateChatThread: (threadId: string, patch: object) => Promise<Row>;
+ saveChatMessage: (message: { id: string; threadId: string }) => Promise<unknown>;
+};
+
+type Pending = {
+ url: string;
+ init?: RequestInit;
+ resolve: (status: number, body: unknown) => void;
+ reject: (error: unknown) => void;
+};
+
+function harness() {
+ const pending: Pending[] = [];
+ const auth = { epoch: 1 };
+ const module = loadWithStubs<Module>(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ {
+ "./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
+ "@/features/auth": {
+ getAuthSessionEpoch: () => auth.epoch,
+ authFetch: (url: string, init?: RequestInit) =>
+ new Promise((resolve, reject) => {
+ const entry: Pending = {
+ url,
+ init,
+ resolve: (status, body) =>
+ resolve({
+ status,
+ ok: status >= 200 && status < 300,
+ headers: { get: () => null },
+ async json() {
+ return body;
+ },
+ }),
+ reject,
+ };
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
+ pending.push(entry);
+ }),
+ },
+ "@/lib/format-fastapi-error": { formatApiErrorBody: () => null },
+ "../types": {},
+ "../types/api": {},
+ "../utils/chat-history-revision": {
+ publishChatHistoryRevision: () => {},
+ CHAT_HISTORY_REVISION_KEY: "unsloth_chat_history_revision",
+ },
+ "../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "./generation-length.ts": {},
+ "./gguf-variants-request": {},
+ "./padded-response": { assertCompletedPaddedBody: () => {} },
+ "@/features/hf-auth": { prepareHfTokenForUse: async () => undefined },
+ "@/features/settings/low-disk-check": { checkDiskSpace: () => Promise.resolve() },
+ "@/features/igpu-carveout": {
+ dismissCarveoutAdviceForModel: () => {},
+ showCarveoutAdvice: () => {},
+ },
+ "@/features/hub/lib/abort-signals": abortSignals,
+ "@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },
+ "@/features/hub/lib/network": { isHuggingFaceOffline: () => false },
+ "@/features/native-intents/api": { consumeNativePathToken: () => undefined },
+ "@/lib/model-lifecycle-events": {},
+ },
+ );
+ const requests = () => pending.filter((p) => p.url.endsWith("/api/chat/threads/t1") && !p.init?.method);
+ return { module, pending, requests, auth };
+}
+
+const row: Row = { id: "t1", title: "T" };
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+test("concurrent shared reads of one thread make one request and share its record", async () => {
+ const { module, requests } = harness();
+ const reads = Array.from({ length: 6 }, () => module.getChatThread("t1", { share: true }));
+ assert.equal(requests().length, 1);
+ requests()[0].resolve(200, row);
+ const results = await Promise.all(reads);
+ assert.ok(results.every((r) => r === results[0]));
+ assert.deepEqual(results[0], row);
+});
+
+test("a read is only shared when asked: the default stays a private request", async () => {
+ const { module, requests } = harness();
+ void module.getChatThread("t1", { share: true });
+ void module.getChatThread("t1");
+ void module.getChatThread("t1", { bounded: true });
+ assert.equal(requests().length, 3);
+ for (const r of requests()) r.resolve(200, row);
+ await tick();
+});
+
+test("there is no TTL: a shared read after the request settled starts a new one", async () => {
+ const { module, requests } = harness();
+ const first = module.getChatThread("t1", { share: true });
+ requests()[0].resolve(200, row);
+ await first;
+ await tick();
+ void module.getChatThread("t1", { share: true });
+ assert.equal(requests().length, 2);
+ requests()[1].resolve(200, row);
+ await tick();
+});
+
+test("a read still pending past the join window is not joined, so one stalled socket cannot hold every later reader", async () => {
+ const { module, requests } = harness();
+ const real = performance.now.bind(performance);
+ const stalled = module.getChatThread("t1", { share: true });
+ try {
+ performance.now = () => real() + 2_500;
+ const later = module.getChatThread("t1", { share: true });
+ assert.equal(requests().length, 2);
+ const joined = module.getChatThread("t1", { share: true });
+ assert.equal(requests().length, 2, "readers inside the new window join the fresh request");
+ requests()[1].resolve(200, { ...row, title: "fresh" });
+ assert.equal((await later)?.title, "fresh");
+ assert.equal((await joined)?.title, "fresh");
+ } finally {
+ delete (performance as { now?: unknown }).now;
+ }
+ requests()[0].resolve(200, row);
+ assert.deepEqual(await stalled, row);
+});
+
+test("a 404 is shared as null and a failure is shared as the same error", async () => {
+ const { module, requests } = harness();
+ const missing = [module.getChatThread("t1", { share: true }), module.getChatThread("t1", { share: true })];
+ requests()[0].resolve(404, null);
+ assert.deepEqual(await Promise.all(missing), [null, null]);
+ await tick();
+ const failing = [module.getChatThread("t1", { share: true }), module.getChatThread("t1", { share: true })];
+ requests()[1].resolve(500, { detail: "boom" });
+ const errors = await Promise.all(failing.map((p) => p.then(() => null, (e: unknown) => e)));
+ assert.ok(errors[0] instanceof Error);
+ assert.equal(errors[0], errors[1]);
+});
+
+test("one reader's deadline detaches that reader alone, and a retry starts a fresh request", async () => {
+ const { module, requests } = harness();
+ const quiet = module.getChatThread("t1", { share: true });
+ const bounded = module.getChatThread("t1", { share: true, timeoutMs: 1 });
+ // AbortSignal.timeout's timer does not hold the event loop open (seen on Node 22 CI).
+ const alive = setTimeout(() => {}, 10_000);
+ await assert.rejects(bounded, (e: DOMException) => e.name === "TimeoutError");
+ clearTimeout(alive);
+ assert.equal(requests()[0].init?.signal?.aborted, false);
+ const retry = module.getChatThread("t1", { share: true, timeoutMs: 1000 });
+ assert.equal(requests().length, 2);
+ requests()[1].resolve(200, { ...row, title: "fresh" });
+ assert.equal((await retry)?.title, "fresh");
+ requests()[0].resolve(200, row);
+ assert.deepEqual(await quiet, row);
+});
+
+test("the request itself is aborted only when every reader with a signal has gone", async () => {
+ const { module, requests } = harness();
+ const a = new AbortController();
+ const b = new AbortController();
+ const ra = module.getChatThread("t1", { share: true, signal: a.signal });
+ const rb = module.getChatThread("t1", { share: true, signal: b.signal });
+ a.abort();
+ await assert.rejects(ra, (e: DOMException) => e.name === "AbortError");
+ assert.equal(requests()[0].init?.signal?.aborted, false);
+ b.abort();
+ await assert.rejects(rb, (e: DOMException) => e.name === "AbortError");
+ assert.equal(requests()[0].init?.signal?.aborted, true);
+});
+
+test("a thread write settling drops that thread's in-flight read, so a later reader starts fresh", async () => {
+ const { module, pending, requests } = harness();
+ const older = module.getChatThread("t1", { share: true });
+ const patch = module.updateChatThread("t1", { title: "renamed" });
+ await tick();
+ const patchRequest = pending.find((p) => p.init?.method === "PATCH")!;
+ patchRequest.resolve(200, { ...row, title: "renamed" });
+ await patch;
+ void module.getChatThread("t1", { share: true });
+ assert.equal(requests().length, 2);
+ requests()[0].resolve(200, row);
+ requests()[1].resolve(200, { ...row, title: "renamed" });
+ assert.equal((await older)?.title, "T");
+ await tick();
+});
+
+test("a message save in another thread leaves this thread's shared read joinable", async () => {
+ const { module, pending, requests } = harness();
+ void module.getChatThread("t1", { share: true });
+ const save = module.saveChatMessage({ id: "m1", threadId: "other" });
+ await tick();
+ pending.find((p) => p.init?.method === "PUT")!.resolve(200, { id: "m1", threadId: "other" });
+ await save;
+ void module.getChatThread("t1", { share: true });
+ assert.equal(requests().length, 1);
+ requests()[0].resolve(200, row);
+ await tick();
+});
+
+test("a read started under one auth session is never joined by the next", async () => {
+ const { module, requests, auth } = harness();
+ const before = module.getChatThread("t1", { share: true });
+ auth.epoch += 1;
+ const after = module.getChatThread("t1", { share: true });
+ await tick();
+ assert.equal(requests().length, 2);
+ requests()[0].resolve(200, { id: "t1", title: "first session" });
+ requests()[1].resolve(200, row);
+ assert.deepEqual(await before, { id: "t1", title: "first session" });
+ assert.deepEqual(await after, row);
+});
diff --git a/studio/frontend/tests/thread-scroller-below-titlebar.test.ts b/studio/frontend/tests/thread-scroller-below-titlebar.test.ts
new file mode 100644
index 00000000000..efc581c5c12
--- /dev/null
+++ b/studio/frontend/tests/thread-scroller-below-titlebar.test.ts
@@ -0,0 +1,32 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("the thread scrolls below the custom titlebar, so its scrollbar is never painted over", () => {
+ const provider = readSrc("app/provider.tsx");
+ const chrome = provider.slice(provider.indexOf("const CUSTOM_CHROME_STYLE = {"));
+ const titlebar = /"--studio-custom-titlebar-height": "(\d+px)",/.exec(chrome)?.[1];
+ assert.ok(titlebar);
+ assert.match(chrome, new RegExp(`"--studio-chat-scroller-top": "${titlebar}",`));
+ assert.doesNotMatch(
+ provider.slice(0, provider.indexOf("const CUSTOM_CHROME_STYLE = {")),
+ /--studio-chat-scroller-top/,
+ "the macOS titlebar is native and the web has none, so the scroller stays at the top there",
+ );
+
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ assert.match(
+ thread,
+ /\[--thread-header-offset:calc\(var\(--studio-content-top-inset,0px\)-var\(--studio-chat-scroller-top,0px\)\+[^\]]*\)\] mt-\[var\(--studio-chat-scroller-top,0px\)\] pt-\[var\(--thread-header-offset\)\]/,
+ "the content keeps its place: what the margin adds, the padding gives back",
+ );
+
+ const css = readSrc("index.css");
+ const dock = css.slice(css.indexOf(".chat-full-view-dock {"), css.indexOf("}", css.indexOf(".chat-full-view-dock {")));
+ assert.match(dock, /--studio-content-top-inset: 0px;/);
+ assert.match(dock, /--studio-chat-scroller-top: 0px;/, "the docked thread sits below the page, not under the titlebar");
+});
diff --git a/studio/frontend/tests/thread-settings-read-invalidation.test.ts b/studio/frontend/tests/thread-settings-read-invalidation.test.ts
new file mode 100644
index 00000000000..8c9731fee49
--- /dev/null
+++ b/studio/frontend/tests/thread-settings-read-invalidation.test.ts
@@ -0,0 +1,55 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+import { inFlightThreadReads } from "../src/features/chat/api/thread-read-cache.ts";
+
+const { store: storage, fireWindowEvent } = installLocalStorageFake();
+register("./thread-sampling-resolver.mjs", import.meta.url);
+const runtime = await import("../src/features/chat/stores/chat-runtime-store.ts");
+
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+const pending = () => ({
+ promise: new Promise<null>(() => {}),
+ controller: new AbortController(),
+ readers: 1,
+ startedAt: performance.now(),
+ authEpoch: 0,
+});
+
+test("settings replay prevents later readers from joining the pre-replay request", async () => {
+ const before = pending();
+ inFlightThreadReads.set("replay", before);
+ const unrelated = pending();
+ inFlightThreadReads.set("other", unrelated);
+ storage.set("unsloth_chat_thread_settings_replay", JSON.stringify({
+ replay: { settings: { temperature: 0.9 } },
+ }));
+ runtime.replayUnconfirmedThreadSettings();
+ await tick();
+ assert.equal(inFlightThreadReads.has("replay"), false);
+ assert.equal(inFlightThreadReads.get("other"), unrelated);
+ assert.equal(before.controller.signal.aborted, false);
+ inFlightThreadReads.clear();
+});
+
+test("a terminal settings write also invalidates reads without aborting existing readers", async () => {
+ storage.set("unsloth_chat_settings_imported_to_studio_db", "true");
+ const store = runtime.useChatRuntimeStore;
+ await store.getState().hydratePersistedSettings();
+ store.getState().setActiveThreadId("beacon");
+ runtime.beginThreadScopedPairing("beacon");
+ store.getState().setParams({ ...store.getState().params, temperature: 0.7 });
+ const before = pending();
+ inFlightThreadReads.set("beacon", before);
+ assert.ok(fireWindowEvent("pagehide", {}) > 0);
+ await tick();
+ assert.equal(inFlightThreadReads.has("beacon"), false);
+ assert.equal(before.controller.signal.aborted, false);
+ await runtime.flushPendingChatSettings();
+ await runtime.awaitStartedThreadScopedSettingsWrites();
+ inFlightThreadReads.clear();
+});
diff --git a/studio/frontend/tests/thread-width-steps.test.ts b/studio/frontend/tests/thread-width-steps.test.ts
new file mode 100644
index 00000000000..5a3686ae929
--- /dev/null
+++ b/studio/frontend/tests/thread-width-steps.test.ts
@@ -0,0 +1,61 @@
+// 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 { applyThreadWidthSteps } from "../src/components/assistant-ui/thread-width-steps.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+function fakeRoot() {
+ const attributes = new Set<string>();
+ return {
+ attributes,
+ toggleAttribute(name: string, force: boolean) {
+ if (force) attributes.add(name);
+ else attributes.delete(name);
+ return force;
+ },
+ };
+}
+
+test("the steps match the container queries they replace, bounds included", () => {
+ const root = fakeRoot();
+ const at = (width: number) => {
+ applyThreadWidthSteps(root as unknown as Element, width, 16);
+ return [...root.attributes].sort();
+ };
+ assert.deepEqual(at(800), ["data-thread-wide"]);
+ assert.deepEqual(at(576), ["data-thread-wide"], "min-width: 36rem holds at exactly 576 px");
+ assert.deepEqual(at(575.5), []);
+ assert.deepEqual(at(504), ["data-thread-narrow"], "max-width: 31.5rem holds at exactly 504 px");
+ assert.deepEqual(at(504.5), []);
+ assert.deepEqual(at(300), ["data-thread-narrow", "data-thread-tiny"], "max-width: 18.75rem holds at exactly 300 px");
+ assert.deepEqual(at(301), ["data-thread-narrow"]);
+ applyThreadWidthSteps(root as unknown as Element, 600, 20);
+ assert.deepEqual([...root.attributes], ["data-thread-narrow"], "rem follows the root font size, as in a container query: 600 px is under 31.5 x 20 px and not over 36 x 20 px");
+});
+
+test("the thread root is no longer a size container, so a width change restyles only what the steps select", () => {
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ const open = thread.indexOf("<ThreadPrimitive.Root");
+ const root = thread.slice(open, thread.indexOf(">", thread.indexOf("className=", open)));
+ assert.match(root, /ref=\{watchWidthSteps\}/);
+ assert.equal(root.includes("@container"), false);
+ assert.ok(root.includes("[contain:style]"), "the style containment the size container carried scopes KaTeX's equation counter; without it each numbered equation counts on from the ones in earlier messages");
+ assert.match(thread, /const watchWidthSteps = useCallback\(\s*\(root: HTMLDivElement \| null\) =>\s*root \? observeThreadWidthSteps\(root\) : undefined,\s*\[\],\s*\);/);
+ const css = readSrc("index.css");
+ assert.equal(/@container \((max|min)-width: (31\.5|18\.75)rem\)/.test(css), false);
+ assert.equal(css.includes("@container (min-width: 36rem)"), false);
+ for (const selector of [
+ ":where(.aui-thread-root[data-thread-narrow]) .unsloth-composer-dock-inner {",
+ ":where(.aui-thread-root[data-thread-narrow]) .aui-thread-welcome-message {",
+ ":where(.aui-thread-root[data-thread-narrow]) .unsloth-welcome-title {",
+ ":where(.aui-thread-root[data-thread-tiny]) .unsloth-welcome-title {",
+ '.aui-thread-root:where([data-thread-wide]) [data-streamdown="code-block-header"] {',
+ ]) {
+ assert.ok(css.includes(selector), `${selector} keeps the selector's own specificity`);
+ }
+ assert.ok(css.includes("@container (max-width: 36rem)"), "the thinking pill still queries its composer surface");
+ assert.match(css, /\.aui-thread-root:where\(\[data-thread-wide\]\) \[data-streamdown="code-block-header"\] \{\s*font-size: calc\(0\.75rem \* var\(--ui-font-scale, 1\)\);\s*\}\s*@media print \{\s*\.aui-thread-root \[data-streamdown="code-block-header"\] \{\s*font-size: calc\(0\.75rem \* var\(--ui-font-scale, 1\)\);\s*\}\s*\}/, "a print is laid out at the page's width, which no observer reports, so it takes the wide header a page always was under the container query");
+});
diff --git a/studio/frontend/tests/titlebar-modal-layering.test.ts b/studio/frontend/tests/titlebar-modal-layering.test.ts
index 6b4ccc594c0..256450b71c1 100644
--- a/studio/frontend/tests/titlebar-modal-layering.test.ts
+++ b/studio/frontend/tests/titlebar-modal-layering.test.ts
@@ -21,10 +21,14 @@ const CLOSED_DECORATION_PATTERN = /<\/div>\s*\)\}\s*$/;
const DIALOG_SURFACE_CLASSES =
/<(?:DialogContent|AlertDialogContent|CommandDialog)\b(?:[^>]|=>)*?\bclassName="([^"]*)"/g;
const WHOLE_WINDOW_CENTRE = /(?:^|\s)(?:max-sm:)?top-1\/2(?:\s|$)/;
-const DIRECT_VIEWPORT_BACKDROP_PATTERN =
- /body:has\(> \[data-viewport-backdrop="true"\]\[data-state="open"\]\)/;
-const DESCENDANT_VIEWPORT_BACKDROP_PATTERN =
- /body:has\(\[data-viewport-backdrop="true"\]\[data-state="open"\]\)/;
+const DOCUMENT_ROOT_HAS_PATTERN =
+ /(?:^|[\s,{}(>~+])(?:html|body|:root)(?:\[[^\]]*\]|\.[\w-]+|#[\w-]+)*:has\(/m;
+const TITLEBAR_BACKDROP_RULE_PATTERN =
+ /\[data-slot="window-titlebar"\]\[data-viewport-backdrop-open\]::after\s*\{\s*opacity:\s*1;\s*\}/;
+const TITLEBAR_BACKDROP_STORE_PATTERN =
+ /useSyncExternalStore\(\s*enabled \? subscribeViewportBackdrop : subscribeNever,/;
+const TITLEBAR_BACKDROP_ATTRIBUTE_PATTERN =
+ /data-slot="window-titlebar"\s+data-viewport-backdrop-open=\{backdropOpen \? "" : undefined\}/;
const TOUR_VIEWPORT_BACKDROP_PATTERN =
/data-slot="dialog-overlay"[\s\S]*?data-viewport-backdrop=\{true\}/;
@@ -87,6 +91,23 @@ test("below-titlebar decoration is not trapped in the titlebar stacking context"
assert.doesNotMatch(header, TOP_FULL_PATTERN);
});
+test("the pinned sidebar edge is drawn with borders, not a box over the chat", () => {
+ const titlebar = readSrc("components/tauri/window-titlebar.tsx");
+ const start = titlebar.indexOf('data-slot="window-titlebar-decoration"');
+ const decoration = titlebar.slice(start, titlebar.indexOf("<header", start));
+ assert.doesNotMatch(
+ decoration,
+ /right-0[^"]*h-\[calc\(100dvh|h-\[calc\(100dvh[^"]*right-0/,
+ "a full-height box from the sidebar edge to the window edge covered the chat, so the compositor could not hit-test a wheel and every desktop scroll waited on the main thread",
+ );
+ assert.match(decoration, /pinned && "rounded-tl-\[12px\] border-l"/);
+ assert.match(
+ decoration,
+ /className="absolute top-\[12px\] h-\[calc\(100dvh-var\(--studio-custom-titlebar-height\)-12px\)\] w-0 border-l border-sidebar-edge dark:border-transparent"\s*style=\{\{ left: cornerLeft \}\}/,
+ "the edge below the corner is a border on a zero-width box, so it snaps to device pixels like the corner",
+ );
+});
+
// A top-* class at a call site makes twMerge drop the base's chrome-aware centre, so a plain
// top-1/2 centres on the whole window and the titlebar covers the dialog's top.
test("dialogs that set their own top still centre below the window chrome", () => {
@@ -100,13 +121,16 @@ test("dialogs that set their own top still centre below the window chrome", () =
assert.ok(checked > 10, `only ${checked} dialog surfaces matched`);
});
-test("viewport titlebar effects stay mutation-scoped and cover custom modal chrome", async () => {
- const [styles, tour] = await Promise.all([
+test("the titlebar dims for viewport backdrops without a :has() on the document root", async () => {
+ const [styles, titlebar, tour] = await Promise.all([
readSrc("index.css"),
+ readSrc("components/tauri/window-titlebar.tsx"),
readSrc("features/tour/components/guided-tour.tsx"),
]);
- assert.match(styles, DIRECT_VIEWPORT_BACKDROP_PATTERN);
- assert.doesNotMatch(styles, DESCENDANT_VIEWPORT_BACKDROP_PATTERN);
+ assert.doesNotMatch(styles.replace(/\/\*[\s\S]*?\*\//g, ""), DOCUMENT_ROOT_HAS_PATTERN);
+ assert.match(styles, TITLEBAR_BACKDROP_RULE_PATTERN);
+ assert.match(titlebar, TITLEBAR_BACKDROP_STORE_PATTERN);
+ assert.match(titlebar, TITLEBAR_BACKDROP_ATTRIBUTE_PATTERN);
assert.match(tour, TOUR_VIEWPORT_BACKDROP_PATTERN);
});
diff --git a/studio/frontend/tests/toast-offset.test.ts b/studio/frontend/tests/toast-offset.test.ts
index 3cada5fcec5..bc7e5b129c1 100644
--- a/studio/frontend/tests/toast-offset.test.ts
+++ b/studio/frontend/tests/toast-offset.test.ts
@@ -5,10 +5,15 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
+ BROWSER_PAGE_INSET_VAR,
+ CHAT_SETTINGS_INSET_VAR,
+ cornerInsetScope,
+ cornerInsets,
getToastOffsets,
insetPastChatSettings,
watchChatSettingsInset,
} from "../src/lib/toast-offset.ts";
+import { readSrc } from "./helpers/kit.ts";
test("web chat toasts clear the header and stay against the right edge", () => {
assert.deepEqual(getToastOffsets("/chat", false, false), {
@@ -212,3 +217,73 @@ test("a smaller UI scale still leaves room for the fixed-width download panel",
watchChatSettingsInset(dom.root, dom.panel, 340, 0.8, dom.Observer);
assert.equal(dom.vars.has("--studio-chat-settings-inset"), false);
});
+
+function fakeScope() {
+ const vars = new Map<string, string>();
+ const element = {
+ style: {
+ setProperty: (name: string, value: string) => void vars.set(name, value),
+ removeProperty: (name: string) => {
+ vars.delete(name);
+ return "";
+ },
+ },
+ } as unknown as HTMLElement;
+ return { vars, element };
+}
+
+test("corner insets reach every scope, including one that mounts later", (t) => {
+ const toaster = fakeScope();
+ const rail = fakeScope();
+ t.after(cornerInsetScope(toaster.element) ?? (() => {}));
+ t.after(cornerInsetScope(rail.element) ?? (() => {}));
+ t.after(() => {
+ cornerInsets.style.removeProperty(CHAT_SETTINGS_INSET_VAR);
+ cornerInsets.style.removeProperty(BROWSER_PAGE_INSET_VAR);
+ });
+
+ cornerInsets.style.setProperty(CHAT_SETTINGS_INSET_VAR, "320px");
+ assert.equal(toaster.vars.get(CHAT_SETTINGS_INSET_VAR), "320px");
+ assert.equal(rail.vars.get(CHAT_SETTINGS_INSET_VAR), "320px");
+ assert.equal(cornerInsets.style.getPropertyValue(CHAT_SETTINGS_INSET_VAR), "320px");
+
+ const late = fakeScope();
+ const release = cornerInsetScope(late.element);
+ assert.equal(late.vars.get(CHAT_SETTINGS_INSET_VAR), "320px");
+ release?.();
+
+ cornerInsets.style.setProperty(BROWSER_PAGE_INSET_VAR, "600px");
+ assert.equal(late.vars.has(BROWSER_PAGE_INSET_VAR), false, "a released scope is no longer written");
+ assert.equal(toaster.vars.get(BROWSER_PAGE_INSET_VAR), "600px");
+
+ cornerInsets.style.removeProperty(CHAT_SETTINGS_INSET_VAR);
+ assert.equal(toaster.vars.has(CHAT_SETTINGS_INSET_VAR), false);
+ assert.equal(rail.vars.has(CHAT_SETTINGS_INSET_VAR), false);
+ assert.equal(cornerInsets.style.getPropertyValue(CHAT_SETTINGS_INSET_VAR), "");
+});
+
+test("the inset follows a drag through the corner scopes", (t) => {
+ const scope = fakeScope();
+ t.after(cornerInsetScope(scope.element) ?? (() => {}));
+ const dom = fakeInsetDom(1400, 320);
+ const stop = watchChatSettingsInset(cornerInsets, dom.panel, 320, 1, dom.Observer);
+ t.after(stop);
+ assert.equal(scope.vars.get(CHAT_SETTINGS_INSET_VAR), "320px");
+ dom.panel.offsetWidth = 480;
+ dom.resize(dom.panel);
+ assert.equal(scope.vars.get(CHAT_SETTINGS_INSET_VAR), "480px");
+ stop();
+ assert.equal(scope.vars.has(CHAT_SETTINGS_INSET_VAR), false);
+});
+
+test("panel insets are written to their consumers, never to <html>", () => {
+ const sheet = readSrc("features/chat/chat-settings-sheet.tsx");
+ assert.match(sheet, /return watchChatSettingsInset\(\s*cornerInsets,\s*asideRef\.current,/, "an inherited variable on <html> restyled the whole document on every drag frame");
+ assert.match(readSrc("features/browser/native-view.ts"), /const style = cornerInsets\.style;/);
+ assert.match(readSrc("components/ui/sonner.tsx"), /<div\s+ref=\{cornerInsetScope\}\s+style=\{\{ display: "contents" \}\}/);
+ assert.equal(readSrc("app/provider.tsx").match(/ref=\{cornerInsetScope\}\s*\/\/ Scrolls at the cap/g)?.length, 2, "both corner rails read the Run settings inset");
+ for (const file of ["features/chat/chat-settings-sheet.tsx", "features/browser/native-view.ts", "lib/toast-offset.ts"]) {
+ assert.equal(/documentElement\.style\.setProperty\((?:CHAT_SETTINGS_INSET_VAR|BROWSER_PAGE_INSET_VAR)/.test(readSrc(file)), false, file);
+ }
+});
+
diff --git a/studio/frontend/tests/tool-approval-gone.test.ts b/studio/frontend/tests/tool-approval-gone.test.ts
index 38e708a72f8..e76ef20a265 100644
--- a/studio/frontend/tests/tool-approval-gone.test.ts
+++ b/studio/frontend/tests/tool-approval-gone.test.ts
@@ -38,6 +38,10 @@ function harness(response: ReturnType<typeof jsonResponse>) {
new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
{
"./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
"@/features/auth": {
authFetch: async (url: string, init?: RequestInit) => {
requests.push({ url, init });
diff --git a/studio/frontend/tests/viewport-backdrop-store.test.ts b/studio/frontend/tests/viewport-backdrop-store.test.ts
new file mode 100644
index 00000000000..139ad5c83e8
--- /dev/null
+++ b/studio/frontend/tests/viewport-backdrop-store.test.ts
@@ -0,0 +1,223 @@
+// 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";
+
+type ObserverInit = {
+ attributes?: boolean;
+ attributeFilter?: string[];
+ childList?: boolean;
+ subtree?: boolean;
+};
+
+type FakeObserver = {
+ targets: { target: unknown; init: ObserverInit }[];
+ deliver: () => void;
+};
+
+class FakeElement {
+ private readonly attributes = new Map<string, string>();
+ constructor(attributes: Record<string, string> = {}) {
+ for (const [name, value] of Object.entries(attributes)) {
+ this.attributes.set(name, value);
+ }
+ }
+ getAttribute(name: string): string | null {
+ return this.attributes.get(name) ?? null;
+ }
+ setAttribute(name: string, value: string): void {
+ this.attributes.set(name, value);
+ }
+ removeAttribute(name: string): void {
+ this.attributes.delete(name);
+ }
+}
+
+const observers: FakeObserver[] = [];
+const children: FakeElement[] = [];
+const body = { children };
+
+class FakeMutationObserver {
+ private readonly entry: FakeObserver;
+ constructor(callback: () => void) {
+ this.entry = { targets: [], deliver: () => callback() };
+ observers.push(this.entry);
+ }
+ observe(target: unknown, init: ObserverInit) {
+ this.entry.targets.push({ target, init });
+ }
+ disconnect() {
+ this.entry.targets = [];
+ }
+}
+
+Object.assign(globalThis, {
+ document: { body },
+ MutationObserver: FakeMutationObserver,
+});
+
+const { getViewportBackdropOpen, subscribeViewportBackdrop } = await import(
+ "../src/components/tauri/viewport-backdrop.ts"
+);
+
+function stateObserver(): FakeObserver {
+ const entry = observers.at(-2);
+ assert.ok(entry);
+ return entry;
+}
+
+function childObserver(): FakeObserver {
+ const entry = observers.at(-1);
+ assert.ok(entry);
+ return entry;
+}
+
+function connected(): FakeObserver[] {
+ return observers.filter((entry) => entry.targets.length > 0);
+}
+
+function viewportBackdrop(state: string): FakeElement {
+ return new FakeElement({
+ "data-slot": "dialog-overlay",
+ "data-viewport-backdrop": "true",
+ "data-state": state,
+ });
+}
+
+function mount(element: FakeElement): void {
+ children.push(element);
+ childObserver().deliver();
+}
+
+function unmount(element: FakeElement): void {
+ children.splice(children.indexOf(element), 1);
+ childObserver().deliver();
+}
+
+function change(element: FakeElement, name: string, value: string | null): void {
+ assert.ok(
+ stateObserver().targets.some((entry) => entry.target === element),
+ "every child of the body is watched for its backdrop state",
+ );
+ if (value === null) element.removeAttribute(name);
+ else element.setAttribute(name, value);
+ stateObserver().deliver();
+}
+
+function reset(): void {
+ children.length = 0;
+}
+
+test("an open viewport backdrop dims the titlebar until it starts closing", (t) => {
+ reset();
+ let notified = 0;
+ t.after(subscribeViewportBackdrop(() => {
+ notified += 1;
+ }));
+ assert.equal(getViewportBackdropOpen(), false);
+
+ const overlay = viewportBackdrop("open");
+ mount(overlay);
+ assert.equal(getViewportBackdropOpen(), true);
+ assert.equal(notified, 1);
+
+ change(overlay, "data-state", "closed");
+ assert.equal(getViewportBackdropOpen(), false);
+ assert.equal(notified, 2);
+
+ unmount(overlay);
+ assert.equal(getViewportBackdropOpen(), false);
+ assert.equal(notified, 2);
+});
+
+test("stacked viewport backdrops keep the titlebar dimmed until the last one closes", (t) => {
+ reset();
+ t.after(subscribeViewportBackdrop(() => undefined));
+ const lower = viewportBackdrop("open");
+ const upper = viewportBackdrop("open");
+ mount(lower);
+ mount(upper);
+ assert.equal(getViewportBackdropOpen(), true);
+
+ change(upper, "data-state", "closed");
+ assert.equal(getViewportBackdropOpen(), true);
+ unmount(upper);
+ assert.equal(getViewportBackdropOpen(), true);
+
+ change(lower, "data-state", "closed");
+ assert.equal(getViewportBackdropOpen(), false);
+});
+
+test("panel-local overlays and menus never dim the titlebar", (t) => {
+ reset();
+ t.after(subscribeViewportBackdrop(() => undefined));
+ const panelOverlay = new FakeElement({
+ "data-slot": "dialog-overlay",
+ "data-state": "open",
+ });
+ const menu = new FakeElement({
+ "data-radix-popper-content-wrapper": "",
+ "data-state": "open",
+ });
+ mount(panelOverlay);
+ mount(menu);
+ assert.equal(getViewportBackdropOpen(), false);
+
+ change(panelOverlay, "data-viewport-backdrop", "true");
+ assert.equal(getViewportBackdropOpen(), true);
+ change(panelOverlay, "data-viewport-backdrop", null);
+ assert.equal(getViewportBackdropOpen(), false);
+});
+
+test("a backdrop already open when the titlebar mounts dims it at once", (t) => {
+ reset();
+ children.push(viewportBackdrop("open"));
+ let notified = 0;
+ t.after(subscribeViewportBackdrop(() => {
+ notified += 1;
+ }));
+ assert.equal(getViewportBackdropOpen(), true);
+ assert.equal(notified, 1);
+});
+
+test("only the body's own children are watched, never a subtree", (t) => {
+ reset();
+ const overlay = viewportBackdrop("open");
+ const root = new FakeElement({ id: "root" });
+ children.push(root, overlay);
+ t.after(subscribeViewportBackdrop(() => undefined));
+
+ assert.deepEqual(childObserver().targets, [
+ { target: body, init: { childList: true } },
+ ]);
+ assert.deepEqual(
+ stateObserver().targets.map((entry) => entry.target),
+ [root, overlay],
+ );
+ for (const { init } of stateObserver().targets) {
+ assert.deepEqual(init, {
+ attributes: true,
+ attributeFilter: ["data-state", "data-viewport-backdrop"],
+ });
+ }
+ for (const entry of connected()) {
+ for (const { init } of entry.targets) assert.notEqual(init.subtree, true);
+ }
+});
+
+test("both observers go when the last listener goes", (t) => {
+ reset();
+ const first = subscribeViewportBackdrop(() => undefined);
+ const second = subscribeViewportBackdrop(() => undefined);
+ t.after(first);
+ t.after(second);
+ mount(viewportBackdrop("open"));
+ first();
+ assert.ok(connected().length > 0);
+ assert.equal(getViewportBackdropOpen(), true);
+
+ second();
+ assert.deepEqual(connected(), []);
+ assert.equal(getViewportBackdropOpen(), false);
+});
diff --git a/studio/frontend/tests/viewport-media-gate.test.ts b/studio/frontend/tests/viewport-media-gate.test.ts
new file mode 100644
index 00000000000..772a738ff24
--- /dev/null
+++ b/studio/frontend/tests/viewport-media-gate.test.ts
@@ -0,0 +1,355 @@
+// 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 vm from "node:vm";
+
+import {
+ gateSelector,
+ gateViewportMedia,
+ viewportBootScript,
+ viewportGate,
+ viewportMediaGate,
+} from "../vite-plugin-viewport-media.ts";
+import { readText } from "./helpers/kit.ts";
+
+const SM = "data-mq-min-width-40rem";
+const MD = "data-mq-min-width-48rem";
+const LG = "data-mq-min-width-64rem";
+
+test("a viewport media block keeps its place, gated on <html> for screens and unchanged for print", () => {
+ const css =
+ ".a{display:block}@media (min-width:40rem){.sm\\:flex{display:flex}.x .y{color:red}}.b{display:grid}";
+ const { css: next, queries } = gateViewportMedia(css);
+ assert.deepEqual(queries, [{ attribute: SM, query: "(min-width:40rem)" }]);
+ assert.equal(
+ next,
+ ".a{display:block}" +
+ `@media screen{:where(html[${SM}]) .sm\\:flex,.sm\\:flex:where(html[${SM}]){display:flex}` +
+ `:where(html[${SM}]) .x .y,.x:where(html[${SM}]) .y{color:red}}` +
+ "@media print{@media (min-width:40rem){.sm\\:flex{display:flex}.x .y{color:red}}}" +
+ ".b{display:grid}",
+ );
+});
+
+test("the second form anchors the leftmost compound on <html>, so rules keyed on its classes still match", () => {
+ const root = `html[${SM}]`;
+ assert.equal(
+ gateSelector(".dark .md\\:x", root),
+ `:where(${root}) .dark .md\\:x,.dark:where(${root}) .md\\:x`,
+ );
+ assert.equal(gateSelector(":root", root), `:where(${root}) :root,:root:where(${root})`);
+ assert.equal(
+ gateSelector(".x>.y+.z~.w", root),
+ `:where(${root}) .x>.y+.z~.w,.x:where(${root})>.y+.z~.w`,
+ );
+});
+
+test("pseudo-elements stay last in their compound, and escaped colons are not pseudo-elements", () => {
+ const root = `html[${SM}]`;
+ assert.equal(
+ gateSelector(".sm\\:after\\:hidden:after", root),
+ `:where(${root}) .sm\\:after\\:hidden:after,.sm\\:after\\:hidden:where(${root}):after`,
+ );
+ assert.equal(
+ gateSelector(".a::-webkit-scrollbar-thumb:hover", root),
+ `:where(${root}) .a::-webkit-scrollbar-thumb:hover,.a:where(${root})::-webkit-scrollbar-thumb:hover`,
+ );
+ assert.equal(
+ gateSelector("::selection", root),
+ `:where(${root}) ::selection,:where(${root})::selection`,
+ );
+ assert.equal(
+ gateSelector(".a:before-ish", root),
+ `:where(${root}) .a:before-ish,.a:before-ish:where(${root})`,
+ );
+});
+
+test("escapes, strings and nested selector lists are not combinators or separators", () => {
+ const { css } = gateViewportMedia(
+ '@media (min-width:96rem){.\\32 xl\\:max-w-6xl{max-width:72rem}.a:is(.b,.c) .d,[data-x="a, b"]{content:"{}"}}',
+ );
+ const root = "html[data-mq-min-width-96rem]";
+ assert.ok(
+ css.startsWith(
+ `@media screen{:where(${root}) .\\32 xl\\:max-w-6xl,.\\32 xl\\:max-w-6xl:where(${root}){max-width:72rem}` +
+ `:where(${root}) .a:is(.b,.c) .d,.a:is(.b,.c):where(${root}) .d,` +
+ `:where(${root}) [data-x="a, b"],[data-x="a, b"]:where(${root}){content:"{}"}}`,
+ ),
+ css,
+ );
+});
+
+test("negated, nested and range queries combine into one gate, with one print copy at the top", () => {
+ const { css, queries } = gateViewportMedia(
+ "@media (min-width:48rem){.md\\:a{order:1}@media not all and (min-width:64rem){.md\\:max-lg\\:b{order:2}}@media (hover:hover){.md\\:hover\\:c:hover{order:3}}@supports (display:grid){.md\\:d{order:4}}}",
+ );
+ assert.deepEqual(
+ queries.map(({ attribute }) => attribute),
+ [MD, LG],
+ );
+ assert.ok(css.includes(`:where(html[${MD}]:not([${LG}])) .md\\:max-lg\\:b`));
+ assert.ok(css.includes(`@media (hover:hover){:where(html[${MD}]) .md\\:hover\\:c:hover`));
+ assert.ok(css.includes(`@supports (display:grid){:where(html[${MD}]) .md\\:d`));
+ assert.equal(css.match(/@media print/g)?.length, 1);
+ assert.ok(css.endsWith("@media print{@media (min-width:48rem){.md\\:a{order:1}@media not all and (min-width:64rem){.md\\:max-lg\\:b{order:2}}@media (hover:hover){.md\\:hover\\:c:hover{order:3}}@supports (display:grid){.md\\:d{order:4}}}}"));
+
+ assert.deepEqual(viewportGate("not all and (width>=40rem)"), { query: "(width>=40rem)", present: false });
+ assert.deepEqual(
+ gateViewportMedia("@media (width<=1023px){.a{order:1}}@media (width>=40rem){.b{order:2}}").queries.map(
+ ({ attribute }) => attribute,
+ ),
+ ["data-mq-width-lte-1023px", "data-mq-width-gte-40rem"],
+ );
+});
+
+test("selector comments cannot swallow gates or supply selector syntax", () => {
+ const root = `html[${SM}]`;
+ const { css } = gateViewportMedia(
+ "@media (min-width:40rem){.a, /* x, > ::before ( [ */ .b/* ::after, */::before{content:'x'}}",
+ );
+ assert.ok(css.startsWith(
+ `@media screen{:where(${root}) .a,.a:where(${root}),` +
+ `:where(${root}) .b/* ::after, */::before,.b/* ::after, */:where(${root})::before{content:'x'}}`,
+ ), css);
+ assert.equal(
+ gateSelector(" /* x */ /* y */ html.dark .b", root),
+ `:where(${root}) html.dark .b,html.dark:where(${root}) .b`,
+ );
+});
+
+test("what a selector gate cannot express is left as it was", () => {
+ for (const css of [
+ "@media (min-width:40rem){@keyframes k{to{opacity:1}}.a{animation:k 1s}}",
+ "@media (min-width:40rem){@scope (.card){.title{order:1}}}",
+ "@media screen and (min-width:40rem){.a{order:1}}",
+ "@media (min-width:40rem) and (max-width:60rem){.a{order:1}}",
+ "@media (hover:hover){.a:hover{order:1}}",
+ "@media print{.a{order:1}}",
+ "/* (min-width:40rem) */.a{order:1}",
+ ]) {
+ assert.deepEqual(gateViewportMedia(css), { css, queries: [] });
+ }
+});
+
+test("a block with a selector list the parser cannot rebuild stays native, and its neighbours are still gated", () => {
+ for (const invalid of [".b,/* x */", ".b,", ".a, ,.b", ",.a"]) {
+ const native = `@media (min-width:64rem){.c{order:1}${invalid}{order:2}}`;
+ const { css, queries } = gateViewportMedia(`@media (min-width:40rem){.a{order:1}}${native}`);
+ assert.ok(css.endsWith(`@media print{@media (min-width:40rem){.a{order:1}}}${native}`), css);
+ assert.deepEqual(queries, [{ attribute: SM, query: "(min-width:40rem)" }]);
+ }
+});
+
+test("a stylesheet that cannot be parsed is left ungated with a warning, never a failed build", () => {
+ const [gate] = viewportMediaGate();
+ const warnings: string[] = [];
+ const hook = gate.transform as {
+ handler: (this: { warn: (message: string) => void }, code: string, id: string) => unknown;
+ };
+ assert.equal(
+ hook.handler.call({ warn: (message) => warnings.push(message) }, "@media (min-width:40rem){.a{order:1}", "/app/broken.css"),
+ null,
+ );
+ assert.equal(warnings.length, 1);
+ assert.match(warnings[0], /\/app\/broken\.css.*Unclosed block/);
+});
+
+test("with build sourcemaps on, the rewrite returns its own map", () => {
+ const [gate] = viewportMediaGate();
+ (gate.configResolved as (config: { build: { sourcemap: boolean } }) => void)({ build: { sourcemap: true } });
+ const hook = gate.transform as {
+ handler: (this: unknown, code: string, id: string) => { code: string; map: string };
+ };
+ const result = hook.handler.call({}, "@media (min-width:40rem){.a{order:1}}", "/app/src/index.css");
+ const map: { sources: string[]; mappings: string } = JSON.parse(result.map);
+ assert.ok(result.code.startsWith("@media screen{"));
+ assert.ok(map.sources.includes("index.css"));
+ assert.notEqual(map.mappings, "");
+});
+
+test("the boot script mirrors each query onto <html> and follows its changes", () => {
+ const attributes = new Map<string, boolean>();
+ const lists = new Map<string, { matches: boolean; listeners: (() => void)[] }>();
+ const context = {
+ document: {
+ documentElement: {
+ toggleAttribute: (name: string, force: boolean) => attributes.set(name, force),
+ },
+ },
+ window: {
+ addEventListener: () => {},
+ matchMedia: (query: string) => {
+ const list = { matches: query === "(min-width:40rem)", listeners: [] as (() => void)[] };
+ lists.set(query, list);
+ return {
+ get matches() {
+ return list.matches;
+ },
+ addEventListener: (_type: string, listener: () => void) => list.listeners.push(listener),
+ };
+ },
+ },
+ };
+ vm.runInNewContext(
+ viewportBootScript([
+ { attribute: SM, query: "(min-width:40rem)" },
+ { attribute: LG, query: "(min-width:64rem)" },
+ ]),
+ context,
+ );
+ assert.deepEqual([...attributes], [[SM, true], [LG, false]]);
+ const large = lists.get("(min-width:64rem)")!;
+ large.matches = true;
+ for (const listener of large.listeners) listener();
+ assert.equal(attributes.get(LG), true);
+});
+
+test("boot script data cannot close an inline script and retains its exact runtime values", () => {
+ const values = [
+ "(width<=1023px)",
+ "(width>=40rem)",
+ '</script><script>globalThis.injected=true</script>',
+ '</ScRiPt><script>globalThis.injected=true</script>',
+ '<!--<script>',
+ '"];globalThis.injected=true;//',
+ '\\";globalThis.injected=true;//',
+ '` ${globalThis.injected=true}',
+ "quotes: \" ' \\; literal escapes: \\u003c \\u2028",
+ String.fromCharCode(...Array.from({ length: 32 }, (_, i) => i)),
+ "line\u2028paragraph\u2029end",
+ "surrogates: \ud800 \udfff; emoji: \ud83d\ude00",
+ ];
+ const queries = values.map((value) => ({ attribute: value, query: value }));
+ const script = viewportBootScript(queries);
+ assert.doesNotMatch(script, /[<>\u2028\u2029]/u);
+
+ const observedQueries: string[] = [];
+ const attributes: [string, boolean][] = [];
+ const context = {
+ injected: false,
+ document: {
+ documentElement: {
+ toggleAttribute: (name: string, force: boolean) => attributes.push([name, force]),
+ },
+ },
+ window: {
+ addEventListener: () => {},
+ matchMedia: (query: string) => {
+ observedQueries.push(query);
+ return { matches: true, addEventListener: () => {} };
+ },
+ },
+ };
+ vm.runInNewContext(script, context, { timeout: 1000 });
+ assert.equal(context.injected, false);
+ assert.deepEqual(observedQueries, values);
+ assert.deepEqual(attributes, values.map((value) => [value, true]));
+});
+
+test("resize refreshes gates before app listeners even while existing media lists are stale", () => {
+ const attributes = new Map<string, boolean>();
+ const listeners: (() => void)[] = [];
+ const lists: { matches: boolean }[] = [];
+ let matches = false;
+ vm.runInNewContext(viewportBootScript([{ attribute: SM, query: "(min-width:40rem)" }]), {
+ document: { documentElement: { toggleAttribute: (name: string, value: boolean) => attributes.set(name, value) } },
+ window: {
+ addEventListener: (type: string, listener: () => void) => {
+ assert.equal(type, "resize");
+ listeners.push(listener);
+ },
+ matchMedia: () => {
+ const list = { matches, addEventListener: () => {} };
+ lists.push(list);
+ return list;
+ },
+ },
+ });
+ const observed: boolean[] = [];
+ listeners.push(() => observed.push(attributes.get(SM)!));
+ for (const next of [true, false, true]) {
+ matches = next;
+ listeners.forEach((listener) => listener());
+ }
+ assert.deepEqual(observed, [true, false, true]);
+ assert.equal(lists[0].matches, false);
+});
+
+test("the build gates every main-document stylesheet and loads the boot script before the others", () => {
+ const [gate, boot] = viewportMediaGate();
+ assert.equal(gate.apply, "build");
+ assert.equal(gate.enforce, undefined, "before vite:css-post turns the stylesheet into a module");
+ const hook = gate.transform as {
+ filter: { id: { include: RegExp; exclude: RegExp }; code: string };
+ handler: (code: string) => { code: string; map: null } | null;
+ };
+ assert.ok(hook.filter.id.include.test("/app/src/index.css"));
+ assert.ok(hook.filter.id.exclude.test("/app/src/frame.css?inline"));
+ assert.ok(!hook.filter.id.exclude.test("/app/src/index.css"));
+ assert.equal(hook.handler(".a{order:1}"), null);
+ assert.ok(hook.handler("@media (min-width:40rem){.a{order:1}}")?.code.startsWith("@media screen{"));
+
+ assert.equal(boot.enforce, "post", "after vite:build-html has emitted the page");
+ const emitted: { name: string; source: string }[] = [];
+ const bundle: Record<string, { type: string; fileName: string; source: string }> = {
+ "index.html": {
+ type: "asset",
+ fileName: "index.html",
+ source: '<html>\n <head>\n <title>x</title>\n <script src="/crypto-boot.js"></script>\n </head>\n</html>',
+ },
+ };
+ (boot.generateBundle as (this: unknown, options: unknown, bundle: unknown) => void).call(
+ {
+ emitFile: (file: { name: string; source: string }) => {
+ emitted.push(file);
+ return "ref";
+ },
+ getFileName: () => "assets/viewport-media-abc.js",
+ },
+ {},
+ bundle,
+ );
+ assert.equal(emitted.length, 1);
+ assert.ok(emitted[0].source.includes(`"${SM}"`));
+ assert.match(
+ bundle["index.html"].source,
+ /<title>x<\/title>\n {4}<script src="\/assets\/viewport-media-abc\.js"><\/script>\n {4}<script src="\/crypto-boot\.js">/,
+ );
+});
+
+test("the build config and the reload snapshot use the gate", () => {
+ assert.match(
+ readText("../vite.config.ts"),
+ /plugins: \[react\(\), tailwindcss\(\), childSelectorOrder\(\), viewportMediaGate\(\),/,
+ );
+ assert.match(
+ readText("../public/reload-snapshot.js"),
+ /applyAppearanceAttributes\(shellRoot, snapshot\.appearance\);\s*Array\.prototype\.forEach\.call\(\s*document\.documentElement\.attributes,\s*function \(attribute\) \{\s*if \(attribute\.name\.indexOf\("data-mq-"\) === 0\) \{\s*shellRoot\.setAttribute\(attribute\.name, attribute\.value\);/,
+ "the restored shell sits in a shadow tree under its own <html>, which needs the same gates",
+ );
+});
+
+test("the boot asset honors absolute and relative Vite bases on nested pages", () => {
+ for (const [base, expected] of [
+ ["/", "/assets/viewport-media-abc.js"],
+ ["/studio/", "/studio/assets/viewport-media-abc.js"],
+ ["https://cdn.example/studio/", "https://cdn.example/studio/assets/viewport-media-abc.js"],
+ ["./", "./../assets/viewport-media-abc.js"],
+ ["", "./../assets/viewport-media-abc.js"],
+ ]) {
+ const [gate, boot] = viewportMediaGate();
+ (gate.transform as { handler: (code: string) => unknown }).handler(
+ "@media (min-width:40rem){.a{order:1}}",
+ );
+ (boot.configResolved as (config: { base: string }) => void)({ base });
+ const asset = { type: "asset", fileName: "nested/index.html", source: "<head></head>" };
+ (boot.generateBundle as (this: unknown, options: unknown, bundle: unknown) => void).call(
+ { emitFile: () => "ref", getFileName: () => "assets/viewport-media-abc.js" },
+ {},
+ { "nested/index.html": asset },
+ );
+ assert.ok(asset.source.includes(`<script src="${expected}">`), asset.source);
+ }
+});
diff --git a/studio/frontend/tests/vram-budget.test.ts b/studio/frontend/tests/vram-budget.test.ts
index 8cdc9c05baa..f72978c0adf 100644
--- a/studio/frontend/tests/vram-budget.test.ts
+++ b/studio/frontend/tests/vram-budget.test.ts
@@ -240,7 +240,7 @@ test("the budget reads as a percentage and steps in tenths", () => {
const row = vramBudgetRowSource();
// Without the suffix, 97 sits between controls measured in layers and tokens
// and reads as neither.
- assert.match(row, /displayValue=\{`\$\{percent\}%`\}/);
+ assert.match(row, /format=\{\(v\) => `\$\{v\}%`\}/);
assert.match(row, /step=\{VRAM_BUDGET_PERCENT_STEP\}/);
// The shared slider defaults to whole steps, so the other callers are untouched.
const slider = pageSource.slice(
diff --git a/studio/frontend/vite-plugin-child-selectors.ts b/studio/frontend/vite-plugin-child-selectors.ts
new file mode 100644
index 00000000000..76dd77b2fa3
--- /dev/null
+++ b/studio/frontend/vite-plugin-child-selectors.ts
@@ -0,0 +1,70 @@
+// 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 { Plugin } from "vite";
+
+const WHERE = ":where(";
+const NOT_LAST_CHILD = ":not(:last-child)";
+
+function closingParen(text: string, from: number): number {
+ let depth = 1;
+ for (let i = from; i < text.length; i++) {
+ const char = text[i];
+ if (char === "\\") i++;
+ else if (char === "(") depth++;
+ else if (char === ")" && --depth === 0) return i;
+ }
+ return -1;
+}
+
+function lastChildCombinator(selector: string): number {
+ let depth = 0;
+ let found = -1;
+ for (let i = 0; i < selector.length; i++) {
+ const char = selector[i];
+ if (char === "\\") i++;
+ else if (char === "(" || char === "[") depth++;
+ else if (char === ")" || char === "]") depth--;
+ else if (depth === 0 && char === ",") return -1;
+ else if (depth === 0 && char === ">") found = i;
+ }
+ return found;
+}
+
+export function parentFirstChildSelectors(css: string): string {
+ let out = "";
+ let cursor = 0;
+ for (
+ let at = css.indexOf(WHERE);
+ at !== -1;
+ at = css.indexOf(WHERE, cursor)
+ ) {
+ const start = at + WHERE.length;
+ const end = closingParen(css, start);
+ if (end === -1) break;
+ const argument = css.slice(start, end);
+ const split = lastChildCombinator(argument);
+ if (split > 0 && argument.slice(split + 1).trim() === NOT_LAST_CHILD) {
+ const parent = argument.slice(0, split).trim();
+ out += `${css.slice(cursor, at)}:where(${parent} > *):where(${NOT_LAST_CHILD})`;
+ cursor = end + 1;
+ } else {
+ out += css.slice(cursor, start);
+ cursor = start;
+ }
+ }
+ return out + css.slice(cursor);
+}
+
+export function childSelectorOrder(): Plugin {
+ return {
+ name: "child-selector-order",
+ transform: {
+ filter: { id: /\.css(?:$|\?)/, code: NOT_LAST_CHILD },
+ handler(code) {
+ const next = parentFirstChildSelectors(code);
+ return next === code ? null : { code: next, map: null };
+ },
+ },
+ };
+}
diff --git a/studio/frontend/vite-plugin-viewport-media.ts b/studio/frontend/vite-plugin-viewport-media.ts
new file mode 100644
index 00000000000..adc72d12cc4
--- /dev/null
+++ b/studio/frontend/vite-plugin-viewport-media.ts
@@ -0,0 +1,218 @@
+// 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 { posix } from "node:path";
+import postcss, { type AtRule, type Container, type Root, type Rule } from "postcss";
+import selectorParser, { type Node as SelectorNode, type Selector } from "postcss-selector-parser";
+import type { Plugin } from "vite";
+
+const VIEWPORT_FEATURE =
+ /\b(?:(?:min|max)-)?(?:device-)?(?:width|height|aspect-ratio)\b|\borientation\b/i;
+const GATED_AT_RULES = new Set([
+ "media",
+ "supports",
+ "layer",
+ "container",
+ "starting-style",
+]);
+const LEGACY_PSEUDO_ELEMENTS = new Set([":before", ":after", ":first-line", ":first-letter"]);
+const ATTRIBUTE_PREFIX = "data-mq-";
+const BOOT_SCRIPT_NAME = "viewport-media.js";
+
+export type ViewportQuery = { attribute: string; query: string };
+
+type Gate = { attribute: string; present: boolean };
+
+function isPseudoElement(node: SelectorNode): boolean {
+ return (
+ node.type === "pseudo" &&
+ (node.value.startsWith("::") || LEGACY_PSEUDO_ELEMENTS.has(node.value.toLowerCase()))
+ );
+}
+
+function gateComplex(selector: Selector, root: string): string {
+ const nodes = [...selector.nodes];
+ while (nodes[0]?.type === "comment" || (nodes[0]?.type === "combinator" && !nodes[0].value.trim())) {
+ nodes.shift();
+ }
+ const first = nodes[0];
+ const last = nodes[nodes.length - 1];
+ if (!first || !last) throw new Error(`empty selector in "${String(selector)}"`);
+ first.spaces.before = "";
+ last.spaces.after = "";
+ const cut = nodes.findIndex((node) => node.type === "combinator" || isPseudoElement(node));
+ const left = nodes.slice(0, cut === -1 ? nodes.length : cut).join("");
+ const right = cut === -1 ? "" : nodes.slice(cut).join("");
+ return `:where(${root}) ${left}${right},${left}:where(${root})${right}`;
+}
+
+export function gateSelector(selector: string, root: string): string {
+ const list = selectorParser().astSync(selector, { lossless: true }).nodes;
+ if (list.map(String).join(",") !== selector) {
+ throw new Error(`selector list "${selector}" does not round-trip`);
+ }
+ return list.map((complex) => gateComplex(complex, root)).join(",");
+}
+
+function gateRoot(gates: readonly Gate[]): string {
+ return `html${gates
+ .map(({ attribute, present }) => (present ? `[${attribute}]` : `:not([${attribute}])`))
+ .join("")}`;
+}
+
+function attributeFor(query: string): string {
+ const slug = query
+ .toLowerCase()
+ .replace(/>=/g, "-gte-")
+ .replace(/<=/g, "-lte-")
+ .replace(/>/g, "-gt-")
+ .replace(/</g, "-lt-")
+ .replace(/=/g, "-eq-")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return `${ATTRIBUTE_PREFIX}${slug}`;
+}
+
+export function viewportGate(condition: string): { query: string; present: boolean } | null {
+ const trimmed = condition.trim();
+ if (!VIEWPORT_FEATURE.test(trimmed)) return null;
+ const negated = /^not\s+all\s+and\s+(\([^()]*\))$/i.exec(trimmed);
+ if (negated) return { query: negated[1], present: false };
+ return /^\([^()]*\)$/.test(trimmed) ? { query: trimmed, present: true } : null;
+}
+
+function gatesEverything(block: AtRule): boolean {
+ let gated = true;
+ block.walkAtRules((rule) => {
+ if (GATED_AT_RULES.has(rule.name.toLowerCase())) return;
+ gated = false;
+ return false;
+ });
+ return gated;
+}
+
+function gateRule(rule: Rule, root: string): void {
+ rule.selector = gateSelector(rule.raws.selector?.raw ?? rule.selector, root);
+ delete rule.raws.selector;
+}
+
+function printCopy(block: AtRule): AtRule {
+ return postcss.atRule({
+ name: "media",
+ params: "print",
+ raws: { before: "", afterName: " ", between: "", after: "" },
+ nodes: [block.clone({ raws: { ...block.raws, before: "" } })],
+ });
+}
+
+function rewrite(container: Container, gates: readonly Gate[], queries: Map<string, string>): void {
+ for (const node of [...(container.nodes ?? [])]) {
+ if (node.type === "rule") {
+ if (gates.length > 0) gateRule(node, gateRoot(gates));
+ continue;
+ }
+ if (node.type !== "atrule" || !node.nodes) continue;
+ const name = node.name.toLowerCase();
+ const gate = name === "media" ? viewportGate(node.params) : null;
+ if (!gate || !gatesEverything(node)) {
+ if (GATED_AT_RULES.has(name)) rewrite(node, gates, queries);
+ continue;
+ }
+ const found = gates.length === 0 ? new Map(queries) : queries;
+ const attribute = found.get(gate.query) ?? attributeFor(gate.query);
+ found.set(gate.query, attribute);
+ const screen = node.clone({ params: "screen", raws: { ...node.raws, params: undefined } });
+ if (gates.length > 0) {
+ rewrite(screen, [...gates, { attribute, present: gate.present }], found);
+ node.replaceWith(screen);
+ continue;
+ }
+ try {
+ rewrite(screen, [{ attribute, present: gate.present }], found);
+ } catch {
+ continue;
+ }
+ found.forEach((value, query) => queries.set(query, value));
+ node.replaceWith(screen, printCopy(node));
+ }
+}
+
+function gateStylesheet(css: string, from?: string): { root: Root; queries: ViewportQuery[] } {
+ const queries = new Map<string, string>();
+ const root = postcss.parse(css, { from });
+ rewrite(root, [], queries);
+ return { root, queries: [...queries].map(([query, attribute]) => ({ attribute, query })) };
+}
+
+export function gateViewportMedia(css: string): { css: string; queries: ViewportQuery[] } {
+ const { root, queries } = gateStylesheet(css);
+ return { css: queries.length === 0 ? css : root.toString(), queries };
+}
+
+export function viewportBootScript(queries: readonly ViewportQuery[]): string {
+ // Escaped beyond JSON so the data stays safe if this script is ever inlined into HTML.
+ const entries = JSON.stringify(queries.map(({ attribute, query }) => [attribute, query]))
+ .replace(/</g, "\\u003c")
+ .replace(/>/g, "\\u003e")
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+ return `(function(){var root=document.documentElement;var entries=${entries};entries.forEach(function(entry){var list=window.matchMedia(entry[1]);var apply=function(){root.toggleAttribute(entry[0],list.matches)};apply();list.addEventListener("change",apply)});window.addEventListener("resize",function(){entries.forEach(function(entry){root.toggleAttribute(entry[0],window.matchMedia(entry[1]).matches)})})})();\n`;
+}
+
+export function viewportMediaGate(): Plugin[] {
+ const queries = new Map<string, ViewportQuery>();
+ let base = "/";
+ let sourcemap = false;
+ return [
+ {
+ name: "viewport-media-gate",
+ apply: "build",
+ configResolved(config) {
+ sourcemap = Boolean(config.build.sourcemap);
+ },
+ transform: {
+ filter: { id: { include: /\.css(?:$|\?)/, exclude: /[?&](?:inline|raw|url)\b/ }, code: "@media" },
+ handler(code, id) {
+ let gated: { root: Root; queries: ViewportQuery[] };
+ try {
+ gated = gateStylesheet(code, id);
+ } catch (error) {
+ this.warn(`left ${id} ungated: ${error instanceof Error ? error.message : String(error)}`);
+ return null;
+ }
+ if (gated.queries.length === 0) return null;
+ for (const query of gated.queries) queries.set(query.query, query);
+ if (!sourcemap) return { code: gated.root.toString(), map: null };
+ const result = gated.root.toResult({ to: id, map: { inline: false, annotation: false, sourcesContent: true } });
+ return { code: result.css, map: result.map.toString() };
+ },
+ },
+ },
+ {
+ name: "viewport-media-boot",
+ apply: "build",
+ enforce: "post",
+ configResolved(config) {
+ base = config.base;
+ },
+ generateBundle(_options, bundle) {
+ if (queries.size === 0) return;
+ const sorted = [...queries.values()].sort((a, b) => a.attribute.localeCompare(b.attribute));
+ const fileName = this.getFileName(
+ this.emitFile({ type: "asset", name: BOOT_SCRIPT_NAME, source: viewportBootScript(sorted) }),
+ );
+ for (const asset of Object.values(bundle)) {
+ if (asset.type !== "asset" || !asset.fileName.endsWith(".html")) continue;
+ const html = String(asset.source);
+ const head = html.indexOf("<head");
+ const script = head === -1 ? -1 : html.indexOf("<script", head);
+ const at = script === -1 ? html.indexOf("</head>") : script;
+ const src = base === "./" || base === ""
+ ? `./${posix.relative(posix.dirname(asset.fileName), fileName)}`
+ : `${base}${fileName}`;
+ if (at !== -1) asset.source = `${html.slice(0, at)}<script src="${src.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}"></script>\n ${html.slice(at)}`;
+ }
+ },
+ },
+ ];
+}
diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.ts
index 0da4ae19ca2..80e93d351b8 100644
--- a/studio/frontend/vite.config.ts
+++ b/studio/frontend/vite.config.ts
@@ -5,6 +5,8 @@ import path from "node:path";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { type Plugin, defineConfig } from "vite";
+import { childSelectorOrder } from "./vite-plugin-child-selectors";
+import { viewportMediaGate } from "./vite-plugin-viewport-media";
import { previewRuntime } from "./vite-preview-runtime.ts";
function smokeModuleDelay(): Plugin {
@@ -30,7 +32,7 @@ export default defineConfig({
cacheDir: process.env.VITE_TEST_CACHE_DIR || "node_modules/.vite",
// Reasoning's highlighter loads only the grammar it needs in its module worker.
worker: { format: "es" },
- plugins: [react(), tailwindcss(), smokeModuleDelay(), previewRuntime()],
+ plugins: [react(), tailwindcss(), childSelectorOrder(), viewportMediaGate(), smokeModuleDelay(), previewRuntime()],
// prevent ancestor PostCSS configs from leaking into installs; Tailwind uses its Vite plugin.
css: {
postcss: {
diff --git a/tests/studio/test_chat_eject_in_flight.py b/tests/studio/test_chat_eject_in_flight.py
index 4e7b69c31ef..27151fdfca1 100644
--- a/tests/studio/test_chat_eject_in_flight.py
+++ b/tests/studio/test_chat_eject_in_flight.py
@@ -17,7 +17,7 @@ export const world: any = { toasts: [], unloads: 0 };
let phase: string | null = null;
const chatModelLifecycleGate = { currentPhase: () => phase };
-const params = { checkpoint: "org/model" };
+const checkpoint = "org/model";
function setModelsError(_message: string | null): void {}
function clearCheckpoint(): void {}
async function refresh(): Promise<void> {}
@@ -66,8 +66,8 @@ def test_eject_toasts_before_the_check_and_refuses_a_second_click_as_unloading()
require_node((HOOK,))
body = slice_between(
read(HOOK),
- " if (!params.checkpoint) {\n return false;\n }",
- " }, [clearCheckpoint, params.checkpoint, refresh, setModelsError]);",
+ " if (!checkpoint) {\n return false;\n }",
+ " }, [checkpoint, clearCheckpoint, refresh, setModelsError]);",
)
out = run_harness(
WORKDIR / "temp" / "chat_eject_in_flight",
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index d9ab1ee6b26..4b6075493b8 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -698,15 +698,18 @@ def test_expanded_titlebar_button_and_corner_match_sidebar_edge():
assert "dark:border-white" not in decoration
assert "dark:border-t-white" not in decoration
# Pinned, it is the sidebar's full-height edge: dark has no sidebar border-r to continue it.
+ assert re.search(r'pinned &&\s*"rounded-tl-\[12px\] border-l"', decoration)
assert re.search(
- r'pinned &&\s*"h-\[calc\(100dvh-var\(--studio-custom-titlebar-height\)\)\] '
- r'rounded-tl-\[12px\] border-l"',
+ r'className="absolute top-\[12px\] '
+ r"h-\[calc\(100dvh-var\(--studio-custom-titlebar-height\)-12px\)\] "
+ r'w-0 border-l border-sidebar-edge dark:border-transparent"\s*'
+ r"style=\{\{ left: cornerLeft \}\}",
decoration,
)
assert "style={{ left: pinned ? cornerLeft : 0 }}" in decoration
assert "style={{ left: cornerLeft }}" in decoration
# The sidebar-coloured mask outside the corner only appears when pinned.
- assert decoration.count("{pinned && (") == 1
+ assert decoration.count("{pinned && (") == 2
assert "transparent_11px,var(--color-sidebar)_12px" in decoration
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index c866f69074a..80fab39b392 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1340,7 +1340,7 @@ def test_an_mlx_target_is_offered_a_context_length_not_a_sequence_length():
page = _read("features/model-picker/components/model-config-page.tsx")
assert 'const label = isMlx ? "Context Length" : "Max Seq Length";' in page
# A number, not a word: the placeholder is only for a window nobody has read.
- assert 'displayValue={isMlx && windowUnknown ? "—" : undefined}' in page
+ assert 'displayValue={isMlx && windowUnknown && !dragging ? "—" : undefined}' in page
assert (
"savedContextPin(config) == null &&\n mlxServedWindow == null &&\n"
" npuServedWindow == null\n" in page
@@ -1351,7 +1351,7 @@ def test_an_mlx_target_is_offered_a_context_length_not_a_sequence_length():
assert re.search(r"const servedWindow = [^;]*Math\.floor\(value\)\n\s*: null;", page), page
numeric = _read("features/model-picker/components/numeric-value-input.tsx")
# Typing the shown number is a choice even where it equals the value beneath it.
- assert "derived={isMlx && !pinned}" in page
+ assert "derived={isMlx && !pinned && !dragging}" in page
assert "pinned={savedContextPin(config) != null}" in page
# Committing pins that exact number; one outside the control's range is no commit,
# which is why the slider stays inside it too.
@@ -1359,7 +1359,10 @@ def test_an_mlx_target_is_offered_a_context_length_not_a_sequence_length():
assert re.search(r"shown && \(\(max[^{]+parsed < min\)+ \{\n\s+return null;", numeric)
assert "const final = commitDraft(draftRef.current);\n dirtyRef" in numeric
assert "value={maxSeqLengthValue}\n max={maxSeqLengthMax}" in page
- assert "value={[Math.min(Math.max(value, MAX_SEQ_LENGTH_MIN), max)]}" in page
+ assert re.search(
+ r"useSliderDraft\(\n(?:\s*//[^\n]*\n)*\s*Math\.min\(Math\.max\(value, MAX_SEQ_LENGTH_MIN\), max\),",
+ page,
+ )
assert "const final = shown ? parsed : snapToStep(parsed, step, min, max);" in numeric
assert re.search(
r"MAX_SEQ_LENGTH_MAX,\s+Math\.max\(native\w+, maxSeqLengthValue\),\s+\);", page