Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: skip layout of distant messages so the browser pane opens fast on long chats (#16986)
Daniel Han3d41bf4af3d7
diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 6283f4f4c24..456288b75be 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -63,6 +63,7 @@ import {WINDOW_CAP_LINES,} from "./code-fence-window";import { planPrintTokenization } from "./code-fence-print";+import { ROW_DISTANT_ATTRIBUTE } from "./distant-rows";import { createFenceSpeculator } from "./fence-speculation";import { highlightWorkerState, streamActive } from "./use-reasoning-highlight";import { inputQuietIn, scheduleQuietIdleTask } from "@/lib/schedule-idle-task";@@ -389,6 +390,7 @@ const scheduleGrammarWarm = (): void => {const rankGates = (gates: readonly FenceGate[]): number[] => {const boxes = new Map<HTMLElement | null, DOMRect>();+ const rows = new Map<Element, DOMRect>();return gates.map((gate) => {let box = boxes.get(gate.outer);if (box === undefined) {@@ -397,7 +399,15 @@ const rankGates = (gates: readonly FenceGate[]): number[] => {: new DOMRect(0, 0, window.innerWidth, window.innerHeight);boxes.set(gate.outer, box);}- const rect = gate.node.getBoundingClientRect();+ // Inside a skipped message row the fence has no box: reading it would lay out that row in+ // every idle pass (Chromium, one forced update per fence). The row's own box ranks it as well.+ const row = gate.node.closest(`[${ROW_DISTANT_ATTRIBUTE}]`);+ let rect = row ? rows.get(row) : undefined;+ if (row && !rect) {+ rect = row.getBoundingClientRect();+ rows.set(row, rect);+ }+ 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;diff --git a/studio/frontend/src/components/assistant-ui/distant-rows.ts b/studio/frontend/src/components/assistant-ui/distant-rows.tsnew file mode 100644index 00000000000..474cd8239ef--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/distant-rows.ts@@ -0,0 +1,179 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Marks message rows far from the reader so index.css can skip their layout: a narrower chat+// column (the browser pane halves it) then re-wraps only the rows near the viewport. A row is+// marked two frames after the observer finds it distant, once it has rendered, so the engine+// sizes it by its remembered height (contain-intrinsic-size: auto) rather than a guess.+export const ROW_DISTANT_ATTRIBUTE = "data-row-distant";+export const ROW_REACH_PX = 1500;+const GATE_ATTRIBUTE = "data-message-row-containment";+const ROW_SELECTOR = "[data-role][data-message-id]";+const NUMBERED_EQUATION = ".eqn-num, .mml-eqn-num";++/**+ * The reach must exceed the engine's own content-visibility: auto margin, so a row is released+ * (and the reader compensated) before the engine lays it out on its own. Chromium renders a skipped+ * element within 150% of the window's height of the window (kViewportMarginPercentage in+ * third_party/blink/renderer/core/display_lock/display_lock_document_state.cc); WebKit only once+ * it intersects the window (no root margin, Source/WebCore/dom/ContentVisibilityDocumentState.cpp).+ * Twice the window height covers Chromium's margin plus the thread scroller's offset inside it.+ */+export const rowReachPx = (windowHeight: number): number =>+ Math.max(ROW_REACH_PX, Math.ceil(2 * (Number.isFinite(windowHeight) ? windowHeight : 0)));++type Adjust = (deltaPx: number) => unknown;+type Watch = { observer: IntersectionObserver; reach: number; rows: Set<Element> };++/** Iterated on resize; an entry leaves with its last row. */+const watches = new Map<Element, Watch>();+const adjusters = new WeakMap<Element, Adjust>();++/** Rows are stacked in document order, so the first one reaching the fold is a binary search. */+function firstVisibleRow(viewport: Element): { anchor: Element; before: number } | null {+ const rows = viewport.querySelectorAll(ROW_SELECTOR);+ const fold = viewport.getBoundingClientRect().top;+ let lo = 0;+ let hi = rows.length - 1;+ let found = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (rows[mid].getBoundingClientRect().bottom > fold) {+ found = mid;+ hi = mid - 1;+ } else lo = mid + 1;+ }+ if (found < 0) return null;+ return { anchor: rows[found], before: rows[found].getBoundingClientRect().top };+}++/** Toggle rows, keeping the first visible row where the reader left it. A released row lays out at+ * the current width, which may differ from the remembered one (the column changed while it was+ * skipped); a newly skipped row should not move, but if it does the reader must not see it either. */+function toggleRows(viewport: Element, changes: Array<[Element, boolean]>) {+ const known = changes.length > 0 ? firstVisibleRow(viewport) : null;+ for (const [row, on] of changes) row.toggleAttribute(ROW_DISTANT_ATTRIBUTE, on);+ if (!known || !known.anchor.isConnected) return;+ // Zero when the engine anchored natively, so this never corrects twice.+ const delta = known.anchor.getBoundingClientRect().top - known.before;+ if (Math.abs(delta) < 0.5) return;+ // Through the autoscroll owner, which re-pins a following reader instead of reading a scroll-up.+ const owner = adjusters.get(viewport);+ if (owner) owner(delta);+ else viewport.scrollTo({ top: viewport.scrollTop + delta, behavior: "instant" });+}++const wanted = new WeakMap<Element, boolean>();+const settling = new WeakMap<Element, Set<Element>>();++/** Skip a row only after it has stayed distant for two frames, so the engine has recorded the+ * size it was laid out at (a chunk mounted above the reader lays out once, then settles). */+function settleLater(viewport: Element, rows: Element[]) {+ let pending = settling.get(viewport);+ const scheduled = pending !== undefined;+ if (!pending) {+ pending = new Set();+ settling.set(viewport, pending);+ }+ for (const row of rows) pending.add(row);+ if (scheduled) return;+ requestAnimationFrame(() => requestAnimationFrame(() => {+ const due = settling.get(viewport);+ settling.delete(viewport);+ if (!due) return;+ const changes: Array<[Element, boolean]> = [];+ for (const row of due) {+ if (row.isConnected && wanted.get(row) && !row.hasAttribute(ROW_DISTANT_ATTRIBUTE)) changes.push([row, true]);+ }+ toggleRows(viewport, changes);+ }));+}++function createObserver(viewport: Element, reach: number): IntersectionObserver {+ return new IntersectionObserver((entries) => {+ // Read before writing. A wide row owns horizontal scroll range, which containment would drop.+ // Numbered equations count across messages; containment would scope their counter to the row+ // (the same exemption math-block-marker.ts gives a single block).+ const distant = entries.map(({ target, boundingClientRect, rootBounds }) =>+ rootBounds !== null &&+ (boundingClientRect.bottom < rootBounds.top || boundingClientRect.top > rootBounds.bottom) &&+ target.scrollWidth <= target.clientWidth &&+ target.querySelector(NUMBERED_EQUATION) === null+ );+ const release: Array<[Element, boolean]> = [];+ const skip: Element[] = [];+ entries.forEach(({ target }, i) => {+ wanted.set(target, distant[i]);+ if (!distant[i] && target.hasAttribute(ROW_DISTANT_ATTRIBUTE)) release.push([target, false]);+ else if (distant[i] && !target.hasAttribute(ROW_DISTANT_ATTRIBUTE)) skip.push(target);+ });+ toggleRows(viewport, release);+ if (skip.length > 0) settleLater(viewport, skip);+ }, { root: viewport, rootMargin: `${reach}px 0px` });+}++const windowHeight = (): number => (typeof window === "undefined" ? 0 : window.innerHeight);++/** A taller window widens the engine's margin, so the reach follows; unchanged reach is a no-op. */+function refreshReach() {+ const reach = rowReachPx(windowHeight());+ for (const [viewport, watch] of watches) {+ if (watch.reach === reach) continue;+ watch.observer.disconnect();+ watch.reach = reach;+ watch.observer = createObserver(viewport, reach);+ for (const row of watch.rows) watch.observer.observe(row);+ }+}++/** Select All renders every skipped row at once (WebKit lays out selected content), so a reader+ * scrolled up after the column narrowed would jump. Release them first, anchored, before the+ * browser's default action picks its range (the same order message-window-controller.ts uses). */+export function releaseAllRows() {+ for (const [viewport, watch] of watches) {+ const changes: Array<[Element, boolean]> = [];+ for (const row of watch.rows) if (row.hasAttribute(ROW_DISTANT_ATTRIBUTE)) changes.push([row, false]);+ toggleRows(viewport, changes);+ }+}++function onKeyDown(event: KeyboardEvent) {+ if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "a") return;+ const target = event.target as Element | null;+ if (target?.closest?.("input, textarea, [contenteditable=true]")) return;+ releaseAllRows();+}++let resizeHooked = false;++export function observeDistantRow(row: HTMLElement, adjust?: Adjust) {+ if (typeof document === "undefined" || !document.documentElement.hasAttribute(GATE_ATTRIBUTE)) return;+ const viewport = row.closest(".aui-thread-viewport");+ if (!viewport || typeof IntersectionObserver === "undefined") return;+ if (adjust) adjusters.set(viewport, adjust);+ if (!resizeHooked && typeof window !== "undefined") {+ resizeHooked = true;+ window.addEventListener("resize", refreshReach, { passive: true });+ document.addEventListener("keydown", onKeyDown, true);+ }++ let watch = watches.get(viewport);+ if (!watch) {+ const reach = rowReachPx(windowHeight());+ watch = { observer: createObserver(viewport, reach), reach, rows: new Set() };+ watches.set(viewport, watch);+ }+ watch.rows.add(row);+ watch.observer.observe(row);+ const own = watch;+ return () => {+ own.observer.unobserve(row);+ own.rows.delete(row);+ if (own.rows.size === 0) {+ own.observer.disconnect();+ if (watches.get(viewport) === own) watches.delete(viewport);+ }+ wanted.delete(row);+ row.removeAttribute(ROW_DISTANT_ATTRIBUTE);+ };+}diff --git a/studio/frontend/src/components/assistant-ui/message-row-containment-mode.ts b/studio/frontend/src/components/assistant-ui/message-row-containment-mode.tsnew file mode 100644index 00000000000..87bf8f5380e--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/message-row-containment-mode.ts@@ -0,0 +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 {+ type ContainmentMode,+ defineContainmentFlag,+} from "./containment-flag.ts";++export type MessageRowContainmentMode = ContainmentMode;++/* Off on WebKitGTK: message-window-controller.ts already parks distant rows there. */+export const MESSAGE_ROW_CONTAINMENT = defineContainmentFlag({+ attribute: "data-message-row-containment",+ global: "__UNSLOTH_MESSAGE_ROW_CONTAINMENT__",+});++export const MESSAGE_ROW_CONTAINMENT_ATTRIBUTE = MESSAGE_ROW_CONTAINMENT.attribute;+export const MESSAGE_ROW_CONTAINMENT_ON = MESSAGE_ROW_CONTAINMENT.on;diff --git a/studio/frontend/src/components/assistant-ui/message-row-containment.ts b/studio/frontend/src/components/assistant-ui/message-row-containment.tsnew file mode 100644index 00000000000..bc1895ac68d--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/message-row-containment.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 { isWebKitGTK } from "@/components/ui/theme-view-transition";+import { engineFindsSkippedContent } from "./math-block-containment";+import {+ MESSAGE_ROW_CONTAINMENT,+ type MessageRowContainmentMode,+} from "./message-row-containment-mode";++const readBuildFlag = (): string => {+ try {+ return import.meta.env.VITE_UNSLOTH_MESSAGE_ROW_CONTAINMENT ?? "";+ } catch {+ return "";+ }+};++const runtimeFlag = (): unknown =>+ (globalThis as Record<string, unknown>)[MESSAGE_ROW_CONTAINMENT.global];++const webKitGTK = (): boolean =>+ typeof navigator !== "undefined"+ && isWebKitGTK(navigator.platform, navigator.userAgent);++/** Rows mounted while off are not observed, so a runtime switch on applies to threads opened after it. */+export const applyMessageRowContainment = (+ root: Element | null = typeof document === "undefined"+ ? null+ : document.documentElement,+): MessageRowContainmentMode => {+ const mode = MESSAGE_ROW_CONTAINMENT.mode(+ runtimeFlag(),+ readBuildFlag(),+ engineFindsSkippedContent() && !webKitGTK(),+ );+ if (!root) return mode;+ if (mode === "contain") {+ root.setAttribute(+ MESSAGE_ROW_CONTAINMENT.attribute,+ MESSAGE_ROW_CONTAINMENT.on,+ );+ } else {+ root.removeAttribute(MESSAGE_ROW_CONTAINMENT.attribute);+ }+ return mode;+};++export const watchMessageRowContainmentOverride = (+ scope: Record<string, unknown> = globalThis as Record<string, unknown>,+ apply: () => MessageRowContainmentMode = applyMessageRowContainment,+): boolean => MESSAGE_ROW_CONTAINMENT.installWatcher(scope, apply);diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex c783be672bb..7202c6307dc 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -53,6 +53,7 @@ import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-pimport { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-list";import { QueueResumeIcon } from "@/components/assistant-ui/queue-resume-icon";import { observeReplyPaint } from "@/components/assistant-ui/reply-paint";+import { observeDistantRow } from "@/components/assistant-ui/distant-rows";import { WindowedMessageBody } from "@/components/assistant-ui/windowed-message-body";import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";import { MessageMenuTime } from "@/components/assistant-ui/message-menu-time";@@ -157,6 +158,7 @@ import {} from "@/components/assistant-ui/turn-navigation";import {IntentAwareScrollProvider,+ useAdjustForContentInsertedAbove,useDetachThreadFromBottom,useIntentAwareAutoScroll,useIsThreadAtBottom,@@ -8276,6 +8278,10 @@ const AssistantMessage: FC = () => {useEffect(() => {if (replyRef.current) return observeReplyPaint(replyRef.current);}, [replyRef]);+ const adjustAbove = useAdjustForContentInsertedAbove();+ useEffect(() => {+ if (replyRef.current) return observeDistantRow(replyRef.current, adjustAbove);+ }, [replyRef, adjustAbove]);const messageId = useAuiState(({ message }) => message.id);const messageContent = useAuiState(({ message }) =>"status" in message && message.status?.type === "running"@@ -9078,6 +9084,11 @@ const ScheduledTaskSource: FC = () => {const UserMessage: FC = () => {const focusReveal = useActionBarFocusReveal();+ const promptRef = focusReveal.ref;+ const adjustAbove = useAdjustForContentInsertedAbove();+ useEffect(() => {+ if (promptRef.current) return observeDistantRow(promptRef.current, adjustAbove);+ }, [promptRef, adjustAbove]);// Attachments alone (annotations, images) get no empty bubble under them.const hasContent = useAuiState(({ message }) =>message.content.some((part) => part.type !== "text" || part.text.trim() !== ""),diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex fef3224fc12..7a26e0d0429 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -4516,6 +4516,30 @@ html[data-chat-font] .aui-root {contain-intrinsic-size: none !important;}}++ /* A width change re-wraps every message: the browser pane halves the column, 0.5-0.7 s per frame+ * on WebKit at 300 messages. Rows marked far away by distant-rows.ts skip layout instead. Every+ * row records its size here, so a skipped row keeps its last rendered height; the estimate is+ * only for a row never rendered. Gated like the blocks above, and off on WebKitGTK, where+ * message-window-controller.ts parks distant rows (message-row-containment.ts). Not released+ * by data-interface-zooming: that would lay out the whole thread on every typography change,+ * and a stale height after a zoom is corrected on release like one after a width change. */+ .aui-thread-viewport [data-role][data-message-id] {+ contain-intrinsic-size: auto 600px;+ }++ /* Rows are flex items: Chromium lets a size-contained item shrink below its remembered height. */+ html[data-message-row-containment="on"] .aui-thread-viewport [data-role][data-message-id][data-row-distant] {+ content-visibility: auto;+ flex-shrink: 0;+ }++ @media print {+ .aui-thread-viewport [data-role][data-message-id] {+ content-visibility: visible !important;+ contain-intrinsic-size: none !important;+ }+ }}/* !important because Sonner injects its base rules at runtime. */diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsxindex 35e749feb3a..6fc63864fed 100644--- a/studio/frontend/src/main.tsx+++ b/studio/frontend/src/main.tsx@@ -14,6 +14,10 @@ import {applyMathBlockContainment,watchMathBlockContainmentOverride,} from "./components/assistant-ui/math-block-containment";+import {+ applyMessageRowContainment,+ watchMessageRowContainmentOverride,+} from "./components/assistant-ui/message-row-containment";import {applyReasoningRowContainment,watchReasoningRowContainmentOverride,@@ -82,6 +86,8 @@ applyCodeBlockContainment();watchCodeBlockContainmentOverride();applyReasoningRowContainment();watchReasoningRowContainmentOverride();+applyMessageRowContainment();+watchMessageRowContainmentOverride();watchOverlayScrollbarGutter(window);watchInputModality(window);diff --git a/studio/frontend/tests/fence-speculation-wiring.test.ts b/studio/frontend/tests/fence-speculation-wiring.test.tsindex 7b0ce8348fd..108a7e99d4d 100644--- a/studio/frontend/tests/fence-speculation-wiring.test.ts+++ b/studio/frontend/tests/fence-speculation-wiring.test.ts@@ -20,7 +20,7 @@ test("the speculator seeds the same cache key the demanded path reads, and onlyassert.match(DEFER, /const SPECULATION_IN_FLIGHT = 3;/);assert.match(DEFER, /busy: \(\) => streamActive\(\) \|\| highlightWorkerState\(\) === "stalled"\s*\|\| inputPointerHeld\(\) \|\| inputQuietIn\(\) > 0,/, "a worker that is late pauses speculation instead of dropping every candidate, so it resumes on the ready message");assert.match(DEFER, /fenceMode\(\) !== "off" && highlightWorkerState\(\) !== "unavailable",/, "only a worker that failed turns speculation off");- assert.match(DEFER, /const rect = gate\.node\.getBoundingClientRect\(\);/);+ assert.match(DEFER, /rect \?\?= gate\.node\.getBoundingClientRect\(\);/, "ranked by the fence itself, or by its row while the row is skipped");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("));diff --git a/studio/frontend/tests/math-block-containment-wiring.test.ts b/studio/frontend/tests/math-block-containment-wiring.test.tsindex 0a79382100b..9b174526eee 100644--- a/studio/frontend/tests/math-block-containment-wiring.test.ts+++ b/studio/frontend/tests/math-block-containment-wiring.test.ts@@ -121,13 +121,14 @@ 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, plus the engine-gated one on windowed code- // bodies. An ungated one would turn the flag into decoration.+ // Two gated copies of `auto`, one per population, plus the engine-gated ones on windowed code+ // bodies, settled reasoning chunks and distant message rows. An ungated one would turn the flag+ // into decoration.const declarations = INDEX_CSS.split("content-visibility: auto;").length - 1;assert.equal(declarations,- 4,- "exactly four `content-visibility: auto` declarations in the whole stylesheet",+ 5,+ "exactly five `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");@@ -184,8 +185,8 @@ test("a print turns the containment off, for both populations", () => {assert.equal(INDEX_CSS.split("content-visibility: auto;").length - 1,- 4,- "PRECONDITION: the gated declarations this print block and the two engine-gated ones switch off",+ 5,+ "PRECONDITION: the gated declarations this print block and the three engine-gated ones switch off",);});diff --git a/studio/frontend/tests/message-row-containment.test.ts b/studio/frontend/tests/message-row-containment.test.tsnew file mode 100644index 00000000000..6eed9c138e1--- /dev/null+++ b/studio/frontend/tests/message-row-containment.test.ts@@ -0,0 +1,311 @@+// 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 vm from "node:vm";+import test from "node:test";+import ts from "@typescript/typescript6";++import {+ MESSAGE_ROW_CONTAINMENT,+ MESSAGE_ROW_CONTAINMENT_ATTRIBUTE,+ MESSAGE_ROW_CONTAINMENT_ON,+} from "../src/components/assistant-ui/message-row-containment-mode.ts";+import { readSrc } from "./helpers/kit.ts";++const source = readFileSync(new URL("../src/components/assistant-ui/distant-rows.ts", import.meta.url), "utf8");+const { outputText } = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } });++const INDEX_CSS = readSrc("index.css");+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const MAIN = readSrc("main.tsx");+const CONTAINMENT = readSrc("components/assistant-ui/message-row-containment.ts");+const ROWS = ".aui-thread-viewport [data-role][data-message-id]";++class Row {+ attributes = new Set<string>();+ scrollWidth = 600;+ clientWidth = 600;+ top: number;+ height: number;+ viewport: Viewport;+ constructor(viewport: Viewport, top: number, height: number) {+ this.viewport = viewport;+ this.top = top;+ this.height = height;+ viewport.rows.push(this);+ }+ closest(selector: string) { return selector === ".aui-thread-viewport" ? this.viewport : null; }+ hasAttribute(name: string) { return this.attributes.has(name); }+ removeAttribute(name: string) { this.attributes.delete(name); }+ toggleAttribute(name: string, on: boolean) {+ const was = this.attributes.has(name);+ if (on) this.attributes.add(name); else this.attributes.delete(name);+ // Releasing a row lays it out at the current width; skipping it uses its remembered size.+ if (was && !on) this.viewport.relayout(this);+ if (!was && on) this.viewport.skip(this);+ }+ numberedEquation = false;+ querySelector(selector: string) { return this.numberedEquation && selector.includes(".eqn-num") ? {} : null; }+ get isConnected() { return true; }+ getBoundingClientRect() {+ const top = this.viewport.offsetOf(this) - this.viewport.scrollTop;+ return { top, bottom: top + this.height };+ }+}++class Viewport {+ rows: Row[] = [];+ scrollTop = 0;+ /** Height a row takes once released; set to simulate a narrower column than when it was skipped. */+ releasedHeight = new Map<Row, number>();+ offsetOf(row: Row) {+ let y = 0;+ for (const r of this.rows) {+ if (r === row) return y;+ y += r.height;+ }+ return y;+ }+ relayout(row: Row) {+ const next = this.releasedHeight.get(row);+ if (next !== undefined) row.height = next;+ }+ /** Height a row takes once skipped, when the engine remembered a different one. */+ skippedHeight = new Map<Row, number>();+ skip(row: Row) {+ const next = this.skippedHeight.get(row);+ if (next !== undefined) row.height = next;+ }+ getBoundingClientRect() { return { top: 0, bottom: 800 }; }+ querySelectorAll() { return this.rows; }+ scrollTo({ top }: { top: number }) { this.scrollTop = top; }+}++type FakeObserver = { margin: string; observed: Set<Row>; disconnected: boolean };++function world(gate = true, innerHeight = 900) {+ let intersect: (entries: unknown[]) => void = () => {};+ const observers: FakeObserver[] = [];+ const resizeListeners: Array<() => void> = [];+ let frames: Array<() => void> = [];+ const keyListeners: Array<(event: unknown) => void> = [];+ const win = {+ innerHeight,+ addEventListener: (type: string, cb: () => void) => { if (type === "resize") resizeListeners.push(cb); },+ };+ const exports: {+ observeDistantRow?: (row: Row, adjust?: (delta: number) => void) => (() => void) | undefined;+ rowReachPx?: (height: number) => number;+ } = {};+ vm.runInNewContext(outputText, {+ exports,+ window: win,+ document: {+ documentElement: { hasAttribute: (name: string) => gate && name === MESSAGE_ROW_CONTAINMENT_ATTRIBUTE },+ addEventListener: (type: string, cb: (event: unknown) => void) => { if (type === "keydown") keyListeners.push(cb); },+ },+ requestAnimationFrame: (cb: () => void) => { frames.push(cb); return frames.length; },+ IntersectionObserver: class {+ own: FakeObserver;+ constructor(cb: typeof intersect, options: { rootMargin: string }) {+ intersect = cb;+ this.own = { margin: options.rootMargin, observed: new Set(), disconnected: false };+ observers.push(this.own);+ }+ observe(row: Row) { this.own.observed.add(row); }+ unobserve(row: Row) { this.own.observed.delete(row); }+ disconnect() { this.own.disconnected = true; this.own.observed.clear(); }+ },+ });+ const rootBounds = { top: -1500, bottom: 2300 };+ const entry = (row: Row) => ({ target: row, rootBounds, boundingClientRect: row.getBoundingClientRect() });+ const frame = () => { const run = frames; frames = []; run.forEach((cb) => cb()); };+ return {+ observe: exports.observeDistantRow!,+ rowReachPx: exports.rowReachPx!,+ report: (...rows: Row[]) => intersect(rows.map(entry)),+ /** Two frames: the settle before a distant row is skipped. */+ settle: () => { frame(); frame(); },+ get observed() { return observers.at(-1)?.observed ?? new Set<Row>(); },+ observers,+ resize: (height: number) => { win.innerHeight = height; resizeListeners.forEach((cb) => cb()); },+ resizeListeners,+ keydown: (event: { key: string; metaKey?: boolean; ctrlKey?: boolean; target?: unknown }) =>+ keyListeners.forEach((cb) => cb({ metaKey: false, ctrlKey: false, target: null, ...event })),+ };+}++test("the reach outruns the engine's own content-visibility margin, which grows with the window", () => {+ const w = world();+ assert.equal(w.rowReachPx(700), 1500, "a short window keeps the 1500 px floor");+ assert.equal(w.rowReachPx(900), 1800);+ assert.equal(w.rowReachPx(2200), 4400, "Chromium renders 150% of the window height out (3300 px here), so 1500 px released rows after it had re-wrapped them");+ assert.equal(w.rowReachPx(Number.NaN), 1500);+});++test("a resize to a new window height swaps the observer once, keeping every row; the same height does nothing", () => {+ const w = world(true, 900);+ const viewport = new Viewport();+ const rows = Array.from({ length: 4 }, () => new Row(viewport, 0, 600));+ const stops = rows.map((row) => w.observe(row)!);+ assert.equal(w.observers.length, 1, "one observer per thread viewport");+ assert.equal(w.observers[0].margin, "1800px 0px");+ assert.equal(w.resizeListeners.length, 1, "one resize listener for every viewport");+ w.resize(900);+ assert.equal(w.observers.length, 1, "same height, same reach: no new observer");+ w.resize(2200);+ assert.equal(w.observers.length, 2);+ assert.equal(w.observers[0].disconnected, true);+ assert.equal(w.observers[1].margin, "4400px 0px");+ assert.deepEqual([...w.observers[1].observed], rows, "the new observer watches every row the old one did");+ w.resize(2200);+ assert.equal(w.observers.length, 2, "idempotent");+ stops.forEach((stop) => stop());+ assert.equal(w.observers[1].disconnected, true, "the last row leaving disconnects its viewport's observer");+ const again = new Row(viewport, 0, 600);+ w.observe(again);+ assert.equal(w.observers.length, 3, "a remounted thread gets a fresh observer at the current reach");+ assert.equal(w.observers[2].margin, "4400px 0px");+});++test("off when the gate is off: no observer, no attribute", () => {+ const w = world(false);+ const viewport = new Viewport();+ const row = new Row(viewport, 0, 500);+ assert.equal(w.observe(row), undefined);+ assert.equal(w.observed.size, 0);+});++test("only rows outside the reach that fit the column are marked, and cleanup unmarks", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, (_, i) => new Row(viewport, i, 600));+ viewport.scrollTop = 6600; // rows 0-7 lie more than 1500 px above the viewport top+ const stops = rows.map((row) => w.observe(row)!);+ rows[1].scrollWidth = 900; // a wide row owns horizontal scroll range+ rows[3].numberedEquation = true; // its equation numbers count on into later messages+ w.report(...rows);+ assert.equal(rows.some((r) => r.hasAttribute("data-row-distant")), false, "nothing is skipped in the frame it was first seen");+ w.settle();+ assert.deepEqual(rows.map((r) => r.hasAttribute("data-row-distant")), [true, false, true, false, true, true, true, true, false, false, false, false]);+ stops[0]();+ assert.equal(rows[0].hasAttribute("data-row-distant"), false);+ assert.equal(w.observed.has(rows[0]), false);+});++test("a row released at a new width keeps the first visible row where the reader left it", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, () => new Row(viewport, 0, 600));+ viewport.scrollTop = 6600;+ rows.forEach((row) => w.observe(row, (delta) => { viewport.scrollTop += delta; }));+ w.report(...rows);+ w.settle();+ assert.equal(rows[7].hasAttribute("data-row-distant"), true);+ // The column narrowed while row 7 was skipped; scrolling up brings it inside the reach.+ viewport.releasedHeight.set(rows[7], 1000);+ viewport.scrollTop = 5800;+ const anchor = rows[9]; // first visible row after the scroll+ const before = anchor.getBoundingClientRect().top;+ w.report(rows[7]);+ assert.equal(rows[7].hasAttribute("data-row-distant"), false);+ assert.equal(anchor.getBoundingClientRect().top, before, "the 400 px the released row grew is scrolled away");+ assert.equal(viewport.scrollTop, 6200);+});++test("select all releases every skipped row before the browser selects, keeping the reader in place", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, () => new Row(viewport, 0, 600));+ viewport.scrollTop = 6600;+ rows.forEach((row) => w.observe(row, (delta) => { viewport.scrollTop += delta; }));+ w.report(...rows);+ w.settle();+ // The column narrowed while rows 0-7 were skipped: each is 1000 px once laid out again.+ for (const row of rows.slice(0, 8)) viewport.releasedHeight.set(row, 1000);+ const anchor = rows[11];+ const before = anchor.getBoundingClientRect().top;+ // Typing select-all in an input is the input's own; nothing is released.+ w.keydown({ key: "a", metaKey: true, target: { closest: () => ({}) } });+ assert.equal(rows[0].hasAttribute("data-row-distant"), true);+ w.keydown({ key: "a", ctrlKey: true });+ assert.equal(rows.some((r) => r.hasAttribute("data-row-distant")), false);+ assert.equal(anchor.getBoundingClientRect().top, before, "the 3200 px the released rows grew is scrolled away");+});++test("no correction when the release changed nothing, and none without a released row", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, () => new Row(viewport, 0, 600));+ viewport.scrollTop = 6600;+ let calls = 0;+ rows.forEach((row) => w.observe(row, () => { calls += 1; }));+ w.report(...rows);+ w.settle();+ viewport.scrollTop = 5800;+ w.report(rows[7]);+ w.report(rows[11]);+ assert.equal(calls, 0);+});++test("a row skipped at a different height than it rendered does not move the reader", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, () => new Row(viewport, 0, 600));+ viewport.scrollTop = 6600;+ rows.forEach((row) => w.observe(row, (delta) => { viewport.scrollTop += delta; }));+ viewport.skippedHeight.set(rows[2], 300);+ const anchor = rows[11];+ const before = anchor.getBoundingClientRect().top;+ w.report(...rows);+ w.settle();+ assert.equal(rows[2].hasAttribute("data-row-distant"), true);+ assert.equal(anchor.getBoundingClientRect().top, before, "the 300 px it lost above the reader is scrolled back");+});++test("a row that comes back inside the reach before it settles is never skipped", () => {+ const w = world();+ const viewport = new Viewport();+ const rows = Array.from({ length: 12 }, () => new Row(viewport, 0, 600));+ viewport.scrollTop = 6600;+ rows.forEach((row) => w.observe(row));+ w.report(...rows);+ viewport.scrollTop = 4000; // rows 5-7 are back inside the reach before the settle+ w.report(rows[5], rows[6], rows[7]);+ w.settle();+ assert.deepEqual(rows.slice(0, 8).map((r) => r.hasAttribute("data-row-distant")), [true, true, true, true, true, false, false, false]);+});++test("every row records its size ungated; skipping is gated, marked, and exempt for print", () => {+ const sizing = INDEX_CSS.indexOf(`\t${ROWS} {\n\t\tcontain-intrinsic-size: auto 600px;\n\t}`);+ assert.ok(sizing >= 0, "auto, so the engine remembers the rendered height before any row is skipped");+ const gate = `html[${MESSAGE_ROW_CONTAINMENT_ATTRIBUTE}="${MESSAGE_ROW_CONTAINMENT_ON}"] ${ROWS}[data-row-distant] {\n\t\tcontent-visibility: auto;\n\t\tflex-shrink: 0;\n\t}`;+ assert.ok(INDEX_CSS.includes(gate), "content-visibility: auto only on marked rows under the gate, which must not shrink as flex items");+ assert.equal(INDEX_CSS.includes(`html[data-interface-zooming] ${ROWS}`), false, "a typography change must not lay out the whole thread; stale heights are corrected on release");+ const print = INDEX_CSS.indexOf("@media print", sizing);+ const block = INDEX_CSS.slice(print, INDEX_CSS.indexOf("}\n\t}", print));+ assert.ok(block.includes(ROWS) && block.includes("content-visibility: visible !important") && block.includes("contain-intrinsic-size: none !important"));+});++test("gated on the engine finding skipped content, off on WebKitGTK, overridable at runtime", () => {+ assert.equal(MESSAGE_ROW_CONTAINMENT.mode(undefined, "", true), "contain");+ assert.equal(MESSAGE_ROW_CONTAINMENT.mode(undefined, "", false), "off");+ assert.equal(MESSAGE_ROW_CONTAINMENT.mode("contain", "", false), "contain");+ assert.equal(MESSAGE_ROW_CONTAINMENT.mode("off", "", true), "off");+ assert.match(CONTAINMENT, /engineFindsSkippedContent\(\) && !webKitGTK\(\)/);+ assert.match(MAIN, /applyMessageRowContainment\(\);\s*watchMessageRowContainmentOverride\(\);/);+});++test("both message rows are observed through the autoscroll owner", () => {+ assert.match(THREAD, /return observeDistantRow\(replyRef\.current, adjustAbove\);/);+ assert.match(THREAD, /return observeDistantRow\(promptRef\.current, adjustAbove\);/);+});++test("idle fence ranking reads a skipped row's box, never a fence inside it", () => {+ const DEFER = readSrc("components/assistant-ui/code-fence-defer.tsx");+ const rank = DEFER.slice(DEFER.indexOf("const rankGates"), DEFER.indexOf("const SPECULATION_IN_FLIGHT"));+ assert.match(rank, /const row = gate\.node\.closest\(`\[\$\{ROW_DISTANT_ATTRIBUTE\}\]`\);/);+ assert.ok(rank.indexOf("row.getBoundingClientRect()") < rank.indexOf("rect ??= gate.node.getBoundingClientRect()"), "the fence is read only outside a skipped row");+});diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.jsindex e91a48933ec..51727334ac2 100644--- a/tests/studio/studiobench/scene/parity.js+++ b/tests/studio/studiobench/scene/parity.js@@ -25,10 +25,10 @@const ID_ATTR_RE = /^data-[a-z0-9-]+-id$/;const isVolatile = (name) => VOLATILE_ATTRS.has(name) || ID_ATTR_RE.test(name);- // data-reply-paint is a paint-containment hint toggled by an IntersectionObserver on replies- // that are far from the viewport: it carries no content and its presence depends on scroll- // position, so it is not thread structure.- const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot", "data-reply-paint"]);+ // data-reply-paint and data-row-distant are containment hints toggled by IntersectionObservers on+ // messages far from the viewport: they carry no content and their presence depends on scroll+ // position, so they are not thread structure.+ const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot", "data-reply-paint", "data-row-distant"]);// Dropped only from the visible-region digest; see parityVisible.capture().const VIRTUALIZATION_ATTRS = new Set(["aria-posinset", "aria-setsize"]);