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.

Studio: reduce long-chat panel and scrolling lag on Linux (#16854)

Wasim Yousef Said6c2b895dcd38
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 c5ccc3f8762..e8937a7af1f 100644
--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx
@@ -14,9 +14,11 @@ import {
useMemo,
useRef,
useState,
+ useSyncExternalStore,
} from "react";
import { flushSync } from "react-dom";
+import { isWebKitGTK } from "@/components/ui/theme-view-transition";
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";
@@ -71,7 +73,35 @@ import {
normalizeLanguage,
} from "./code-plugin";
-/* One-way: a fence renders as a plain shell until it first nears the viewport, then stays highlighted. */
+// WebKitGTK restyles every retained highlight span when panels open. Keep the
+// Chromium default unchanged: line-window updates can regress fast scrollbar drags there.
+const WINDOW_SETTLED_FENCES = typeof navigator !== "undefined"
+ && isWebKitGTK(navigator.platform, navigator.userAgent);
+
+/* Tokenization is one-way. WebKitGTK can release offscreen highlight spans while keeping the tokens cached. */
+
+// Line windows assume one row per source line; wrapped code breaks that, so settled fences
+// only window themselves while wrapping is off. One shared observer for every fence.
+const wrapListeners = new Set<() => void>();
+let wrapObserver: MutationObserver | null = null;
+const subscribeCodeWrap = (listener: () => void): (() => void) => {
+ wrapListeners.add(listener);
+ if (wrapObserver === null && typeof MutationObserver !== "undefined") {
+ wrapObserver = new MutationObserver(() => {
+ for (const notify of wrapListeners) notify();
+ });
+ wrapObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-code-wrap"] });
+ }
+ return () => {
+ wrapListeners.delete(listener);
+ if (wrapListeners.size === 0) {
+ wrapObserver?.disconnect();
+ wrapObserver = null;
+ }
+ };
+};
+const codeWrapOn = (): boolean => document.documentElement.hasAttribute("data-code-wrap");
+const useCodeWrap = (): boolean => useSyncExternalStore(subscribeCodeWrap, codeWrapOn, () => false);
/* One viewport of lookahead. The percentage resolves against the root's HEIGHT in all engines
* (spec says width, w3c/IntersectionObserver#391); pf9462_parity.py guards it. */
@@ -1241,7 +1271,7 @@ const watchWindows = (): void => {
findBarObserver = new MutationObserver(scheduleRemeasure);
findBarObserver.observe(document.documentElement, {
attributes: true,
- attributeFilter: [FIND_BAR_FLAG],
+ attributeFilter: [FIND_BAR_FLAG, "data-code-wrap", "data-code-line-numbers"],
});
};
@@ -1437,6 +1467,9 @@ function useLineWindow(
setState({ measured: true, window: null, pins: null });
return;
}
+ // A parked message keeps its portal and state, but has no meaningful geometry.
+ // Find/print above still expand it before the body is reconnected.
+ if (!node.isConnected) return;
let known = geometry.current;
if (
known === null
@@ -1541,6 +1574,52 @@ function useLineWindow(
const NO_WINDOW = { window: null, pins: null, measured: false } as const;
const EMPTY_WINDOW = { window: EMPTY_LINE_WINDOW, pins: null, measured: false } as const;
+// Keep settled, offscreen fences as text instead of retaining every highlighted span.
+// Plain text has the same height only without wrapping or line-number gutters.
+// Reuse the windowing listeners to restore markup for find, print and selection.
+function useOffscreenFenceText(
+ frame: RefObject<HTMLElement | null>,
+ enabled: boolean,
+): boolean {
+ const [plain, setPlain] = useState(false);
+ useLayoutEffect(() => {
+ const node = frame.current;
+ if (!enabled || !node || typeof IntersectionObserver === "undefined") {
+ setPlain(false);
+ return;
+ }
+ let near = true;
+ const update = () => {
+ if (!node.isConnected && !printing && !findBarOpen()) return;
+ const selection = liveSelection();
+ // Never replace selection boundary nodes, or the browser loses the selection.
+ const selected = selection !== null && (node.contains(selection.anchorNode)
+ || node.contains(selection.focusNode));
+ if (selected || inputPointerHeld()) {
+ // Retry on pointer release or selection change, which remeasure only after a held frame.
+ heldLastFrame = true;
+ return;
+ }
+ setPlain(!near && !printing && !findBarOpen()
+ && !document.documentElement.hasAttribute("data-code-wrap")
+ && !document.documentElement.hasAttribute("data-code-line-numbers"));
+ };
+ const observer = new IntersectionObserver(([entry]) => {
+ near = entry.isIntersecting;
+ update();
+ }, { root: node.closest(".aui-thread-viewport"), rootMargin: "1000px 0px" });
+ observer.observe(node);
+ windowedFences.add(update);
+ watchWindows();
+ return () => {
+ observer.disconnect();
+ windowedFences.delete(update);
+ unwatchWindows();
+ };
+ }, [enabled, frame]);
+ return plain && enabled;
+}
+
/**
* A fence's body, highlighted, with the spans bounded to what is on screen.
*
@@ -1562,11 +1641,16 @@ export const FenceBody = memo(function FenceBody({
source: string;
windowing: boolean;
}) {
+ const codeWrap = useCodeWrap();
+ const tokens = result?.tokens ?? null;
+ // Only fences over the cap get a line window; below it the batched highlight path stays on,
+ // so a dense line (minified JSON) still renders in quiet-work batches.
+ windowing ||= WINDOW_SETTLED_FENCES && !isIncomplete && !codeWrap
+ && (tokens?.length ?? 0) > WINDOW_CAP_LINES;
const code = useRef<HTMLElement | null>(null);
const surface = useRef<HTMLDivElement | null>(null);
const wrapper = useRef<HTMLDivElement | null>(null);
const frame = useRef<HTMLDivElement | null>(null);
- const tokens = result?.tokens ?? null;
const highlight = useFenceHighlightLimit(tokens, isIncomplete, windowing, language, source, code, frame);
const { window: lineWindow, pins, measured } = useLineWindow(
code,
@@ -1577,6 +1661,10 @@ export const FenceBody = memo(function FenceBody({
windowing,
!isIncomplete,
);
+ const offscreenPlain = useOffscreenFenceText(
+ frame,
+ WINDOW_SETTLED_FENCES && !!tokens?.length && !isIncomplete,
+ );
const languageClass = language === null ? null : `language-${language}`;
const rootStyle = useMemo(() => {
@@ -1616,7 +1704,8 @@ export const FenceBody = memo(function FenceBody({
? "true"
: undefined
}
- data-unsloth-fence-windowed={lineWindow === null || !measured ? undefined : "true"}
+ data-unsloth-fence-offscreen={offscreenPlain || undefined}
+ data-unsloth-fence-windowed={offscreenPlain || lineWindow === null || !measured ? undefined : "true"}
ref={wrapper}
>
<div
@@ -1630,7 +1719,7 @@ export const FenceBody = memo(function FenceBody({
>
<pre className={joinClasses(languageClass, PRE_CLASS)} style={rootStyle}>
<code className={CODE_CLASS} ref={code}>
- {windowing ? tokens.map((line, index) => (
+ {offscreenPlain ? <PlainFenceText source={source} /> : windowing ? tokens.map((line, index) => (
<FenceLine
key={index}
line={line}
diff --git a/studio/frontend/src/components/assistant-ui/message-window-controller.ts b/studio/frontend/src/components/assistant-ui/message-window-controller.ts
new file mode 100644
index 00000000000..7fde7fe6dd2
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/message-window-controller.ts
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Detach the stable portal target so React retains message state, refs and handlers.
+const REACH = 2000;
+const FIND_FLAG = "data-find-bar-open";
+const controllers = new WeakMap<HTMLElement, MessageWindowController>();
+
+type Row = {
+ root: HTMLElement;
+ holder: HTMLElement;
+ content: HTMLElement;
+ text: HTMLElement;
+ saved: Array<[string, string, string]> | null;
+ frozen: Array<[string, string, string]> | null;
+};
+
+class MessageWindowController {
+ private rows = new Map<Element, Row>();
+ private observer: IntersectionObserver;
+ private flags: MutationObserver;
+ private media = window.matchMedia("print");
+ private printing = this.media.matches;
+ private pointerHeld = false;
+ private scrollbarHeld = false;
+ private frame = 0;
+ private settling = false;
+
+ private viewport: HTMLElement;
+ private adjust: ((deltaPx: number) => void) | null = null;
+
+ constructor(viewport: HTMLElement) {
+ this.viewport = viewport;
+ viewport.setAttribute("data-windowed-messages", "");
+ // IO records may predate a scroll or prepend; read current geometry instead.
+ this.observer = new IntersectionObserver(this.update,
+ { root: viewport, rootMargin: `${REACH}px 0px` });
+ this.flags = new MutationObserver(this.refresh);
+ this.flags.observe(document.documentElement, { attributes: true, attributeFilter: [FIND_FLAG] });
+ document.addEventListener("selectionchange", this.refresh);
+ document.addEventListener("keydown", this.onKeyDown, true);
+ viewport.addEventListener("pointerdown", this.onPointerDown, true);
+ viewport.addEventListener("focusin", this.onFocus, true);
+ viewport.addEventListener("scroll", this.onScroll, { passive: true });
+ window.addEventListener("pointerup", this.onPointerUp, true);
+ window.addEventListener("pointermove", this.onPointerMove, { capture: true, passive: true });
+ window.addEventListener("pointercancel", this.onPointerUp, true);
+ window.addEventListener("blur", this.onPointerUp);
+ window.addEventListener("beforeprint", this.beforePrint);
+ window.addEventListener("afterprint", this.afterPrint);
+ this.media.addEventListener("change", this.printChanged);
+ }
+
+ add(root: HTMLElement, holder: HTMLElement, content: HTMLElement, adjust?: (deltaPx: number) => void): () => void {
+ if (adjust) this.adjust = adjust;
+ const text = document.createElement("span");
+ text.className = "sr-only";
+ const row: Row = { root, holder, content, text, saved: null, frozen: null };
+ this.rows.set(root, row);
+ this.observer.observe(root);
+ return () => {
+ this.restore(row, false);
+ this.releaseHeight(row);
+ this.observer.unobserve(root);
+ this.rows.delete(root);
+ if (this.rows.size === 0) this.dispose();
+ };
+ }
+
+ private restoreHeight(row: Row, saved: Array<[string, string, string]>) {
+ for (const [name, value, priority] of saved) {
+ if (value) row.root.style.setProperty(name, value, priority);
+ else row.root.style.removeProperty(name);
+ }
+ }
+
+ private releaseHeight(row: Row): boolean {
+ if (!row.frozen) return false;
+ this.restoreHeight(row, row.frozen);
+ row.frozen = null;
+ return true;
+ }
+
+ private restore(row: Row, freeze = this.scrollbarHeld): boolean {
+ if (!row.saved) return false;
+ row.text.remove();
+ row.holder.append(row.content);
+ // Hold the scroll range steady until the native thumb is released. The reconnected body may
+ // be taller than its frozen height after a reflow, so clip it until then instead of painting
+ // over the next messages; release restores the original overflow with the height.
+ if (freeze) {
+ const style = row.root.style;
+ // A row parked again mid drag carries its first frozen snapshot, original overflow included.
+ row.frozen = row.saved.some(([name]) => name === "overflow")
+ ? row.saved
+ : [...row.saved, ["overflow", style.getPropertyValue("overflow"), style.getPropertyPriority("overflow")]];
+ style.setProperty("overflow", "hidden");
+ style.setProperty("overflow", "clip");
+ } else this.restoreHeight(row, row.saved);
+ row.saved = null;
+ row.root.removeAttribute("data-message-parked");
+ return true;
+ }
+
+ // Restored rows reflow at the current width; keep the first visible row where the reader left it.
+ private keepAnchor(change: () => boolean, known?: { anchor: HTMLElement | null; before: number }) {
+ let anchor: HTMLElement | null = known?.anchor ?? null;
+ let before = known?.before ?? 0;
+ if (!known) {
+ const top = this.viewport.getBoundingClientRect().top;
+ for (const row of this.rows.values()) {
+ const rect = row.root.getBoundingClientRect();
+ if (rect.bottom > top && (anchor === null || rect.top < before)) {
+ anchor = row.root;
+ before = rect.top;
+ }
+ }
+ }
+ // Nothing reconnected or released: skip the layout read on this scroll.
+ if (!change() || anchor === null || !anchor.isConnected) return;
+ // Zero when the engine anchored natively, so this never corrects twice.
+ const delta = anchor.getBoundingClientRect().top - before;
+ if (Math.abs(delta) < 0.5) return;
+ // The autoscroll owner applies it instantly and resyncs its follow intent; a direct write would
+ // animate under scroll-smooth and read as a downward reader scroll.
+ if (this.adjust) this.adjust(delta);
+ else this.viewport.scrollTo({ top: this.viewport.scrollTop + delta, behavior: "instant" });
+ }
+
+ private restoreAll = () => {
+ this.keepAnchor(() => {
+ let changed = false;
+ for (const row of this.rows.values()) {
+ changed = this.restore(row, false) || changed;
+ changed = this.releaseHeight(row) || changed;
+ }
+ return changed;
+ });
+ };
+
+ private held() {
+ const selection = document.getSelection();
+ return this.printing || document.documentElement.hasAttribute(FIND_FLAG)
+ || (selection !== null && !selection.isCollapsed && selection.rangeCount > 0
+ && selection.getRangeAt(0).intersectsNode(this.viewport));
+ }
+
+ private update = () => {
+ if (this.held()) {
+ this.restoreAll();
+ return;
+ }
+ const wanted = new Set<Row>();
+ const bounds = this.viewport.getBoundingClientRect();
+ const reach = this.scrollbarHeld ? Math.min(REACH, bounds.height) : REACH;
+ // Batch layout reads before reconnecting or detaching any subtree.
+ const candidates: Array<[Row, number]> = [];
+ const first: { anchor: HTMLElement | null; before: number } = { anchor: null, before: 0 };
+ for (const row of this.rows.values()) {
+ const rect = row.root.getBoundingClientRect();
+ if (rect.bottom > bounds.top && (first.anchor === null || rect.top < first.before)) {
+ first.anchor = row.root;
+ first.before = rect.top;
+ }
+ const margin = row.saved ? reach : REACH;
+ // Hysteresis avoids repeated swaps on small drag reversals.
+ if (rect.bottom >= bounds.top - margin && rect.top <= bounds.bottom + margin
+ || row.root.contains(document.activeElement)) {
+ wanted.add(row);
+ continue;
+ }
+ if (row.saved || this.pointerHeld || this.settling) continue;
+ // Embedded media must stay connected, and wide replies own horizontal scroll range.
+ if (row.content.querySelector("iframe, video, audio, canvas, textarea, [contenteditable=true]")) continue;
+ const height = rect.height;
+ if (height > 0 && row.root.scrollWidth <= row.root.clientWidth + 1) candidates.push([row, height]);
+ }
+ this.keepAnchor(() => this.apply(wanted, candidates), first);
+ };
+
+ private apply(wanted: Set<Row>, candidates: Array<[Row, number]>): boolean {
+ let changed = candidates.length > 0;
+ for (const row of this.rows.values()) {
+ if (wanted.has(row) || row.root.contains(document.activeElement)) changed = this.restore(row) || changed;
+ }
+ for (const [row, height] of candidates) {
+ row.saved = row.frozen ?? ["height"].map((name) =>
+ [name, row.root.style.getPropertyValue(name), row.root.style.getPropertyPriority(name)]);
+ row.frozen = null;
+ // Preserve accessible text; focus restores the rich body.
+ row.text.textContent = row.content.textContent;
+ row.root.style.height = `${height}px`;
+ row.content.remove();
+ row.holder.append(row.text);
+ row.root.setAttribute("data-message-parked", "");
+ }
+ return changed;
+ }
+
+ private refresh = () => {
+ if (this.held()) this.restoreAll();
+ if (this.frame) return;
+ // Let find/print code-fence layout changes settle before parking bodies.
+ this.settling = true;
+ this.frame = requestAnimationFrame(() => {
+ this.frame = requestAnimationFrame(() => {
+ this.frame = 0;
+ this.settling = false;
+ this.update();
+ });
+ });
+ };
+
+ private onScroll = () => {
+ // Restore before paint, including jumps that outrun IO.
+ this.update();
+ };
+
+ private onFocus = (event: FocusEvent) => {
+ for (const row of this.rows.values()) {
+ if (row.root.contains(event.target as Node)) this.restore(row);
+ }
+ };
+ private onPointerDown = (event: PointerEvent) => {
+ if (event.button !== 0) return;
+ // Native thumb hits target the viewport; text-selection drags target descendants.
+ this.scrollbarHeld = event.target === this.viewport && event.pointerType === "mouse";
+ this.pointerHeld = !this.scrollbarHeld;
+ if (this.scrollbarHeld && !this.held()) {
+ const active = [...this.rows.values()].filter((row) => !row.saved && !row.frozen);
+ const heights = active.map((row) => row.root.getBoundingClientRect().height);
+ active.forEach((row, index) => {
+ row.frozen = [["height", row.root.style.getPropertyValue("height"), row.root.style.getPropertyPriority("height")]];
+ row.root.style.height = `${heights[index]}px`;
+ });
+ }
+ };
+ private onPointerUp = () => {
+ this.pointerHeld = false;
+ this.scrollbarHeld = false;
+ this.keepAnchor(() => {
+ let changed = false;
+ for (const row of this.rows.values()) changed = this.releaseHeight(row) || changed;
+ return changed;
+ });
+ this.refresh();
+ };
+ private onPointerMove = (event: PointerEvent) => {
+ if ((this.pointerHeld || this.scrollbarHeld) && event.buttons === 0) this.onPointerUp();
+ };
+ private onKeyDown = (event: KeyboardEvent) => {
+ // Reconnect before the browser's select-all default action chooses its range.
+ const target = event.target as Element | null;
+ if (target?.closest?.("input, textarea, [contenteditable=true]")) return;
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "a") this.restoreAll();
+ };
+ private beforePrint = () => { this.printing = true; this.restoreAll(); };
+ private afterPrint = () => { this.printing = this.media.matches; this.refresh(); };
+ private printChanged = () => { this.printing = this.media.matches; this.refresh(); };
+
+ private dispose() {
+ this.observer.disconnect();
+ this.flags.disconnect();
+ cancelAnimationFrame(this.frame);
+ document.removeEventListener("selectionchange", this.refresh);
+ document.removeEventListener("keydown", this.onKeyDown, true);
+ this.viewport.removeEventListener("pointerdown", this.onPointerDown, true);
+ this.viewport.removeEventListener("focusin", this.onFocus, true);
+ this.viewport.removeEventListener("scroll", this.onScroll);
+ window.removeEventListener("pointerup", this.onPointerUp, true);
+ window.removeEventListener("pointermove", this.onPointerMove, true);
+ window.removeEventListener("pointercancel", this.onPointerUp, true);
+ window.removeEventListener("blur", this.onPointerUp);
+ window.removeEventListener("beforeprint", this.beforePrint);
+ window.removeEventListener("afterprint", this.afterPrint);
+ this.media.removeEventListener("change", this.printChanged);
+ this.viewport.removeAttribute("data-windowed-messages");
+ controllers.delete(this.viewport);
+ }
+}
+
+export function observeMessageWindow(
+ root: HTMLElement,
+ holder: HTMLElement,
+ content: HTMLElement,
+ adjust?: (deltaPx: number) => void,
+): (() => void) | undefined {
+ const viewport = root.closest<HTMLElement>(".aui-thread-viewport");
+ if (!viewport || typeof IntersectionObserver === "undefined") return;
+ let controller = controllers.get(viewport);
+ if (!controller) {
+ controller = new MessageWindowController(viewport);
+ controllers.set(viewport, controller);
+ }
+ return controller.add(root, holder, content, adjust);
+}
diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
index 7cfe1228448..292731b8945 100644
--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
@@ -18,14 +18,18 @@ import {
useRef,
useState,
} from "react";
+import { flushSync } from "react-dom";
import { createRowNotificationGate } from "@/components/assistant-ui/row-notification-gate";
import { MessageByIndexProvider } from "@/components/assistant-ui/stale-safe-scopes";
import {
type AnchorSample,
type MountWindow,
+ CHUNK_MESSAGES,
anchorCorrection,
+ alignAnchorCorrection,
initialWindow,
+ watchProgressiveScroll,
widen,
} from "@/components/assistant-ui/progressive-mount-controller";
import {
@@ -33,6 +37,13 @@ import {
rendersAsRow,
} from "@/components/assistant-ui/thread-message-slot";
import { useAdjustForContentInsertedAbove } from "@/components/assistant-ui/use-intent-aware-autoscroll";
+import { inputPointerHeld } from "@/lib/input-pointer-state";
+import { isWebKitGTK } from "@/components/ui/theme-view-transition";
+
+const WEBKIT_GTK = typeof navigator !== "undefined"
+ && isWebKitGTK(navigator.platform, navigator.userAgent);
+const MOUNT_CHUNK = WEBKIT_GTK ? 2 : CHUNK_MESSAGES;
+const ANCHOR_PRECISION = WEBKIT_GTK ? 1 / 64 : 1;
/** Module-level: consumers are imperative DOM readers, and a thread can mount twice (Compare). */
interface ActiveCompleter {
@@ -84,6 +95,13 @@ function restoreScrollAnchoring(viewport: HTMLElement | null): void {
if (viewport.getAttribute("style") === "") viewport.removeAttribute("style");
}
+function* layoutChildren(element: Element): Generator<Element> {
+ for (const child of element.children) {
+ if (getComputedStyle(child).display === "contents") yield* layoutChildren(child);
+ else yield child;
+ }
+}
+
/** The first row the reader can SEE: a relayout above the fold moves them, not the top row. */
function pickAnchorRow(viewport: HTMLElement): Element | null {
const fold = viewport.getBoundingClientRect().top;
@@ -96,6 +114,7 @@ function pickAnchorRow(viewport: HTMLElement): Element | null {
}
}
if (!anchor) return null;
+ if (anchor.hasAttribute("data-message-parked")) return anchor;
if (
typeof anchor.checkVisibility === "function"
&& !anchor.checkVisibility({ contentVisibilityAuto: true })
@@ -114,7 +133,7 @@ function pickAnchorRow(viewport: HTMLElement): Element | null {
for (let depth = 0; depth < 8; depth += 1) {
if (anchor.getBoundingClientRect().top >= fold) break;
let next: Element | null = null;
- for (const child of anchor.children) {
+ for (const child of layoutChildren(anchor)) {
if (
typeof child.checkVisibility === "function"
&& !child.checkVisibility({ contentVisibilityAuto: true })
@@ -171,9 +190,21 @@ function useProgressiveMountWindow(
count: number,
resetKey: string | undefined,
viewportRef: RefObject<HTMLElement | null>,
+ alignmentRef: RefObject<HTMLDivElement | null>,
): MountWindow {
const aui = useAui();
- const adjustForContentInsertedAbove = useAdjustForContentInsertedAbove();
+ const adjustScroll = useAdjustForContentInsertedAbove();
+ const adjustForContentInsertedAbove = useCallback((shift: number) => {
+ const spacer = alignmentRef.current;
+ if (spacer) {
+ // WebKit rounds scrollTop. Align the inserted height instead of moving text
+ // between two fractional positions on every background prepend.
+ const aligned = alignAnchorCorrection(shift, Number.parseFloat(spacer.style.height) || 0);
+ spacer.style.height = `${aligned.inset}px`;
+ return adjustScroll(aligned.scroll);
+ }
+ return adjustScroll(shift);
+ }, [adjustScroll, alignmentRef]);
// Imperative, so run start/stop does not re-render and rebuild the row array.
const isRunningNow = useCallback(
@@ -238,12 +269,35 @@ function useProgressiveMountWindow(
| null
>(null);
const idleRef = useRef<HeldAnchor | null>(null);
+ const scrollActivity = useRef<ReturnType<typeof watchProgressiveScroll> | null>(null);
+
+ useEffect(() => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ const activity = watchProgressiveScroll(viewport);
+ scrollActivity.current = activity;
+ return () => {
+ activity.dispose();
+ scrollActivity.current = null;
+ };
+ }, [viewportRef]);
const captureAnchor = useCallback(() => {
const viewport = viewportRef.current;
// Disarm native anchoring right before the capture. A layout effect is too early: as a descendant,
// this runs before the viewport ref callback on the mounting commit.
if (viewport) viewport.style.setProperty("overflow-anchor", "none");
+ // Preserve the last compensated position, including reflows between widening frames.
+ const held = idleRef.current;
+ if (viewport && held?.element.isConnected && isAnchorVisible(viewport, held.element)) {
+ anchorRef.current = {
+ element: held.element,
+ ...held.sample,
+ row: held.row,
+ rowSample: held.rowSample,
+ };
+ return;
+ }
const anchor = viewport ? pickAnchorRow(viewport) : null;
// Fall back to the row: the anchor is often a `<pre>` replaced when Shiki finishes.
const row = anchor?.closest("[data-role]") ?? null;
@@ -260,17 +314,27 @@ function useProgressiveMountWindow(
useEffect(() => {
if (mountWindow == null) return;
- const frame = requestAnimationFrame(() => {
+ let frame = 0;
+ const advance = () => {
// Re-check: a run can start between the commit and this frame.
if (isRunningNow()) {
setMountWindow(null);
return;
}
+ // A prepend's instant anchor correction also interrupts native wheel momentum.
+ if (scrollActivity.current?.blocked(inputPointerHeld())) {
+ frame = requestAnimationFrame(advance);
+ return;
+ }
captureAnchor();
- startTransition(() => {
- setMountWindow((current) => widen(current, count));
- });
- });
+ const commit = () => {
+ setMountWindow((current) => widen(current, count, MOUNT_CHUNK));
+ };
+ // Keep the prepend and its scroll correction inside the same WebKit rendering frame.
+ if (WEBKIT_GTK) flushSync(commit);
+ else startTransition(commit);
+ };
+ frame = requestAnimationFrame(advance);
return () => cancelAnimationFrame(frame);
}, [mountWindow, count, captureAnchor, isRunningNow]);
@@ -280,22 +344,27 @@ function useProgressiveMountWindow(
const captured = anchorRef.current;
anchorRef.current = null;
const viewport = viewportRef.current;
- if (!captured || !viewport) return;
+ if (!viewport) return;
+ if (!captured) {
+ // The initial tail has no earlier anchor. Pin it before its first paint,
+ // just as later prepends are corrected in this commit.
+ adjustForContentInsertedAbove(0);
+ return;
+ }
const [element, baseline] = captured.element.isConnected
? [captured.element, captured as AnchorSample]
: captured.row?.isConnected && captured.rowSample
? [captured.row, captured.rowSample]
: [null, null];
if (!element || !baseline) return;
- const shift = anchorCorrection(baseline, sampleAnchor(viewport, element));
+ const shift = anchorCorrection(baseline, sampleAnchor(viewport, element), ANCHOR_PRECISION);
// Call even with zero shift: it resyncs the hook's scroll bookkeeping.
adjustForContentInsertedAbove(shift ?? 0);
// Keep a post-correction baseline; nulling it folds an in-between reflow into the next one.
idleRef.current = holdAnchor(viewport, element);
}, [mountWindow, adjustForContentInsertedAbove, viewportRef]);
- // Compensates reflows above a detached reader while native anchoring is off. Currently dormant
- // because the widening effect above registers first: reordering these two effects turns it on.
+ // Compensate reflows between prepends while native anchoring is off.
useEffect(() => {
if (mountWindow == null) {
idleRef.current = null;
@@ -307,6 +376,10 @@ function useProgressiveMountWindow(
const viewport = viewportRef.current;
// A pending widening capture owns the correction; stepping in would correct twice.
if (!viewport || anchorRef.current) return;
+ if (scrollActivity.current?.blocked(inputPointerHeld())) {
+ idleRef.current = null;
+ return;
+ }
const held = idleRef.current;
if (!held) {
const element = pickAnchorRow(viewport);
@@ -335,7 +408,7 @@ function useProgressiveMountWindow(
: null;
return;
}
- const shift = anchorCorrection(baseline, sampleAnchor(viewport, element));
+ const shift = anchorCorrection(baseline, sampleAnchor(viewport, element), ANCHOR_PRECISION);
if (shift !== null) adjustForContentInsertedAbove(shift);
// Re-base every frame: anchorCorrection's clamp term reads the baseline scrollTop.
idleRef.current = holdAnchor(viewport, element);
@@ -405,7 +478,8 @@ export const ProgressiveMessages: FC<{
}> = memo(
({ renderMessage, resetKey, viewportRef }) => {
const count = useAuiState(({ thread }) => thread.messages.length);
- const mountWindow = useProgressiveMountWindow(count, resetKey, viewportRef);
+ const alignmentRef = useRef<HTMLDivElement>(null);
+ const mountWindow = useProgressiveMountWindow(count, resetKey, viewportRef, alignmentRef);
const aui = useAui();
const gate = useMemo(() => createRowNotificationGate(aui), [aui]);
@@ -425,7 +499,10 @@ export const ProgressiveMessages: FC<{
</AuiProvider>,
);
}
- return <>{rows}</>;
+ return <>
+ {WEBKIT_GTK && <div ref={alignmentRef} aria-hidden="true" style={{ height: 0, flexShrink: 0 }} />}
+ {rows}
+ </>;
}, [count, mountWindow, renderMessage, gate]);
},
(prev, next) =>
diff --git a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts
index 3ce8b8e44d3..33f444b2d0c 100644
--- a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts
+++ b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts
@@ -16,6 +16,46 @@ export const INITIAL_MESSAGES = 16;
/** Messages added per widening frame; trades build-in height against length, not total work. */
export const CHUNK_MESSAGES = 32;
+/** Leave native scrolling and its momentum alone before changing the scroll range. */
+export function watchProgressiveScroll(
+ viewport: EventTarget,
+ now: () => number = () => performance.now(),
+) {
+ // Let the initial tail paint before starting background work.
+ let resumeAt = now() + 300;
+ const pause = () => { resumeAt = now() + 300; };
+ const onScroll = () => { if (now() < resumeAt) pause(); };
+ const onKey = (event: Event) => {
+ const key = event as KeyboardEvent;
+ if (key.defaultPrevented || !["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(key.key)) return;
+ const target = key.target as HTMLElement | null;
+ if (target?.isContentEditable || target?.closest?.("input, textarea, select")) return;
+ pause();
+ };
+ const listeners = { wheel: pause, touchmove: pause, keydown: onKey, scroll: onScroll };
+ const inputTarget = (viewport as HTMLElement).ownerDocument ?? viewport;
+ inputTarget.addEventListener("pointerdown", pause, { capture: true, passive: true });
+ inputTarget.addEventListener("beforeinput", pause, { capture: true, passive: true });
+ inputTarget.addEventListener("compositionupdate", pause, { capture: true, passive: true });
+ for (const [type, listener] of Object.entries(listeners)) {
+ viewport.addEventListener(type, listener, { capture: true, passive: true });
+ }
+ return {
+ blocked(pointerHeld: boolean): boolean {
+ if (pointerHeld) pause();
+ return now() < resumeAt;
+ },
+ dispose() {
+ inputTarget.removeEventListener("pointerdown", pause, { capture: true });
+ inputTarget.removeEventListener("beforeinput", pause, { capture: true });
+ inputTarget.removeEventListener("compositionupdate", pause, { capture: true });
+ for (const [type, listener] of Object.entries(listeners)) {
+ viewport.removeEventListener(type, listener, { capture: true });
+ }
+ },
+ };
+}
+
/** Caps the tail walk so a tail of non-rendering messages cannot mount the whole thread. */
export const MAX_INITIAL_SPAN = INITIAL_MESSAGES * 4;
@@ -45,11 +85,11 @@ export function isCovered(current: MountWindow): boolean {
}
/** Returns null once it would cover the thread, so the restriction drops in the same commit. */
-export function widen(current: MountWindow, count: number): MountWindow {
+export function widen(current: MountWindow, count: number, chunk = CHUNK_MESSAGES): MountWindow {
if (current == null) return null;
// A start past the end withholds nothing; clamping then subtracting would unmount rows.
if (current.start >= count) return null;
- const start = Math.max(0, current.start - CHUNK_MESSAGES);
+ const start = Math.max(0, current.start - chunk);
if (start <= 0) return null;
return { start };
}
@@ -75,6 +115,7 @@ export type AnchorSample = {
export function anchorCorrection(
captured: AnchorSample,
now: AnchorSample,
+ minShift = 1,
): number | null {
// Subtract what the browser already absorbed via the clamp when content above shrank. Exact only
// for a reader who did not scroll this frame.
@@ -84,8 +125,13 @@ export function anchorCorrection(
now.scrollTop -
(captured.viewportOffset + captured.scrollTop) +
clamped;
- // Whole pixels only, so a subpixel reflow does not issue a scroll write every frame.
- return Math.abs(shift) >= 1 ? shift : null;
+ return Math.abs(shift) >= minShift ? shift : null;
+}
+
+/** Keep the scroll correction integral; a subpixel leading inset absorbs the remainder. */
+export function alignAnchorCorrection(shift: number, inset: number) {
+ const scroll = Math.ceil(shift - inset) || 0;
+ return { scroll, inset: inset + scroll - shift };
}
/** Tests assert on this so the constants cannot drift into a thread that never converges. */
diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsx
index 70d5886e2b1..bbf8ca26e48 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx
@@ -136,8 +136,7 @@ function ReasoningRoot({
}: ReasoningRootProps) {
const collapsibleRef = useRef<HTMLDivElement>(null);
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
- // The grid transition starts only after React commits `0fr`, so the lock needs the backstop
- // margin on this path; tool-group and tool-fallback keep the plain duration.
+ // The grid transition starts after React commits `0fr`, so include the backstop margin.
const lockScroll = useCollapseScrollLock(
collapsibleRef,
GRID_COLLAPSE_REASONING_ENABLED
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index f38f6dd7250..c783be672bb 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-p
import { 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 { 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";
import { AssistantMessageTime } from "@/components/assistant-ui/assistant-message-time";
@@ -8357,6 +8358,7 @@ const AssistantMessage: FC = () => {
onFocus={focusReveal.onFocus}
onBlur={focusReveal.onBlur}
>
+ <WindowedMessageBody enabled={!isEditing && messageContent !== null && !researchRunId}>
<div className="aui-assistant-message-content wrap-break-word min-w-0 text-[#0f1114] dark:text-foreground leading-relaxed">
{isEditing ? (
// Same surface as a prompt's EditComposer, at the reply's full width. Bottom gap is padding:
@@ -8416,6 +8418,7 @@ const AssistantMessage: FC = () => {
<LiveGenerationLine />
<AssistantActionBar />
</div>
+ </WindowedMessageBody>
{/* Renders nothing. `If last` keeps the hook off the other N-1. */}
<MessagePrimitive.If last={true}>
<ForkChatShortcut />
@@ -9086,6 +9089,7 @@ const UserMessage: FC = () => {
tabIndex={0}
{...focusReveal}
>
+ <WindowedMessageBody>
<ScheduledTaskSource />
<UserMessageAttachments />
<UserMessageAudio />
@@ -9103,6 +9107,7 @@ const UserMessage: FC = () => {
<BranchPicker className="aui-user-branch-picker ml-[calc(6px*var(--ui-space-scale,1))] shrink-0" />
</UserMessageFooter>
</div>
+ </WindowedMessageBody>
<MessagePrimitive.If last={true}>
<ForkChatShortcut />
</MessagePrimitive.If>
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index b662db94cee..3de4b923524 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -6,10 +6,11 @@
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@/components/ui/collapsible";
+ UnmeasuredCollapsible as Collapsible,
+ UnmeasuredCollapsibleContent as CollapsibleContent,
+ UnmeasuredCollapsibleTrigger as CollapsibleTrigger,
+ CLOSE_FALLBACK_MARGIN_MS,
+} from "@/components/ui/unmeasured-collapsible";
import { Spinner } from "@/components/ui/spinner";
// eslint-disable-next-line no-restricted-imports -- the feature barrel imports this component
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
@@ -105,7 +106,7 @@ function ToolFallbackRoot({
if (syncedUncontrolledState !== uncontrolledState) {
setUncontrolledState(syncedUncontrolledState);
}
- const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION);
+ const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS);
const isControlled = controlledOpen !== undefined;
const isOpen =
@@ -298,15 +299,12 @@ function ToolFallbackContent({
return (
<CollapsibleContent
data-slot="tool-fallback-content"
+ closeDurationMs={ANIMATION_DURATION}
className={cn(
"aui-tool-fallback-content relative overflow-hidden text-trace-foreground text-sm outline-none",
"group/collapsible-content ease-out",
- "data-[state=closed]:animate-collapsible-up",
- "data-[state=open]:animate-collapsible-down",
- "data-[state=closed]:fill-mode-forwards",
"data-[state=closed]:pointer-events-none",
- "data-[state=open]:duration-(--animation-duration)",
- "data-[state=closed]:duration-(--animation-duration)",
+ "duration-(--animation-duration)",
className,
)}
{...props}
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index d7da818d543..35263a40965 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -28,10 +28,11 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { cva, type VariantProps } from "class-variance-authority";
import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@/components/ui/collapsible";
+ UnmeasuredCollapsible as Collapsible,
+ UnmeasuredCollapsibleContent as CollapsibleContent,
+ UnmeasuredCollapsibleTrigger as CollapsibleTrigger,
+ CLOSE_FALLBACK_MARGIN_MS,
+} from "@/components/ui/unmeasured-collapsible";
import { useDetachThreadFromBottom } from "@/components/assistant-ui/use-intent-aware-autoscroll";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import { cn } from "@/lib/utils";
@@ -94,7 +95,7 @@ function ToolGroupRoot({
if (syncedUncontrolledState !== uncontrolledState) {
setUncontrolledState(syncedUncontrolledState);
}
- const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION);
+ const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS);
const isControlled = controlledOpen !== undefined;
const isOpen = isControlled
@@ -226,15 +227,12 @@ function ToolGroupContent({
return (
<CollapsibleContent
data-slot="tool-group-content"
+ closeDurationMs={ANIMATION_DURATION}
className={cn(
"aui-tool-group-content relative overflow-hidden text-sm outline-none",
"group/collapsible-content ease-out",
- "data-[state=closed]:animate-collapsible-up",
- "data-[state=open]:animate-collapsible-down",
- "data-[state=closed]:fill-mode-forwards",
"data-[state=closed]:pointer-events-none",
- "data-[state=open]:duration-(--animation-duration)",
- "data-[state=closed]:duration-(--animation-duration)",
+ "duration-(--animation-duration)",
className,
)}
{...props}
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 552d1c5f57d..b3cbf2a2f2e 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
@@ -190,6 +190,7 @@ export function useIntentAwareAutoScroll(): {
let touchStartY = 0;
let scrollKeyAt = Number.NEGATIVE_INFINITY;
let pointerHeld = false;
+ let insertionRemainder = 0;
const distanceFromBottom = (): number => {
if (el.scrollHeight <= el.clientHeight) {
@@ -404,25 +405,24 @@ export function useIntentAwareAutoScroll(): {
requestTick();
};
- // 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 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
- // the viewport: extendFollow early-returns, stabilize only rebases its high-water mark, and
- // pinIfFollowing returns without scrolling. So this is the only actor, and without it the
- // page slides down under the reader every widening frame. `behavior: "instant"` is required:
- // the viewport carries `scroll-smooth`, so an animated write would still be in flight at the
- // next frame's write.
+ // Correct prepends before paint: a queued follow tick can run a frame late.
+ // This hook owns scrollTop and resyncs intent after either kind of correction.
+ // Use instant scrolling despite the viewport's scroll-smooth class.
adjustImplRef.current = (deltaPx: number) => {
if (!userDetachedRef.current) {
- return;
- }
- if (deltaPx !== 0) {
- el.scrollTo({ top: el.scrollTop + deltaPx, behavior: "instant" });
+ insertionRemainder = 0;
+ if (!parkIfHeld()) {
+ extendFollow();
+ pinIfFollowing(stabilize());
+ }
+ } else if (deltaPx !== 0) {
+ const top = Math.max(0, Math.min(
+ el.scrollTop + deltaPx + insertionRemainder,
+ el.scrollHeight - el.clientHeight,
+ ));
+ el.scrollTo({ top, behavior: "instant" });
+ // WebKit rounds scrollTop; carry the fraction across background prepends.
+ insertionRemainder = top - el.scrollTop;
}
// Resync lastScrollTop even with no write: native anchoring may have moved scrollTop and its
// scroll event would otherwise read as a downward scroll that re-attaches the user.
diff --git a/studio/frontend/src/components/assistant-ui/windowed-message-body.tsx b/studio/frontend/src/components/assistant-ui/windowed-message-body.tsx
new file mode 100644
index 00000000000..2d4d2b55b1b
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/windowed-message-body.tsx
@@ -0,0 +1,63 @@
+// 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 { useAuiState } from "@assistant-ui/react";
+import { type ReactNode, useCallback, useLayoutEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { isWebKitGTK } from "@/components/ui/theme-view-transition";
+import { observeMessageWindow } from "./message-window-controller";
+import { useAdjustForContentInsertedAbove } from "./use-intent-aware-autoscroll";
+
+const ENABLED = typeof navigator !== "undefined"
+ && isWebKitGTK(navigator.platform, navigator.userAgent);
+
+export function WindowedMessageBody({ children, enabled = true }: {
+ children: ReactNode;
+ enabled?: boolean;
+}) {
+ return ENABLED ? <MessageBody enabled={enabled}>{children}</MessageBody> : children;
+}
+
+function MessageBody({ children, enabled }: { children: ReactNode; enabled: boolean }) {
+ const messageId = useAuiState(({ message }) => message.id);
+ const longThread = useAuiState(({ thread }) => thread.messages.length >= 100);
+ const holder = useRef<HTMLDivElement>(null);
+ // Restoration corrections go through the autoscroll owner, which keeps its intent in sync.
+ const adjustAbove = useAdjustForContentInsertedAbove();
+ const adjustRef = useRef(adjustAbove);
+ adjustRef.current = adjustAbove;
+ const [adjust] = useState(() => (deltaPx: number) => {
+ adjustRef.current(deltaPx);
+ });
+ const [content] = useState(() => {
+ const element = document.createElement("div");
+ element.style.display = "contents";
+ return element;
+ });
+ const attach = useCallback((node: HTMLDivElement | null) => {
+ holder.current = node;
+ if (!node) return;
+ // Attach before child layout effects and the progressive-mount anchor correction.
+ const root = node.closest<HTMLElement>("[data-role][data-message-id]");
+ root?.setAttribute("data-message-windowed", "");
+ node.append(content);
+ return () => {
+ content.remove();
+ root?.removeAttribute("data-message-windowed");
+ holder.current = null;
+ };
+ }, [content]);
+ useLayoutEffect(() => {
+ const shell = holder.current;
+ const root = shell?.closest<HTMLElement>("[data-role][data-message-id]");
+ if (!root || !shell) return;
+ const stop = enabled && longThread ? observeMessageWindow(root, shell, content, adjust) : undefined;
+ return stop;
+ }, [adjust, content, enabled, longThread, messageId]);
+ return (
+ <>
+ <div ref={attach} style={{ display: "contents" }} />
+ {createPortal(children, content)}
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 09a0523c92e..2c0b76839ee 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.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 { isWebKitGTK } from "@/components/ui/theme-view-transition";
import { useAppShellReadySignal } from "@/components/app-readiness";
import {
applyModelLoadConfigToRuntime,
@@ -620,6 +621,12 @@ function useStoredChatTitle(threadId: string | null): string | undefined {
return title && title.id === threadId ? title.title : undefined;
}
+// WebKitGTK restyles the long thread when panel constraints re-register, then again
+// for the staged resize. Keep constraints stable and resize in one step on this renderer.
+const IMMEDIATE_CONTEXT_PANEL =
+ typeof navigator !== "undefined" &&
+ isWebKitGTK(navigator.platform, navigator.userAgent);
+
const ARTIFACT_PANEL_DEFAULT_SIZE = "38%";
// t3code's default docked width, never more than half the chat or under the panel's 30% minimum.
const BROWSER_PANEL_DEFAULT_PX = 540;
@@ -716,7 +723,8 @@ const SingleContent = memo(function SingleContent({
});
const showContextPanel = showResearchPanel || browserDocked;
- const artifactLayoutActive = showContextPanel || isArtifactPanelLayoutActive;
+ const artifactLayoutActive =
+ showContextPanel || (!IMMEDIATE_CONTEXT_PANEL && isArtifactPanelLayoutActive);
const artifactPanelSettledOpen =
showContextPanel &&
isArtifactPanelLayoutActive &&
@@ -730,9 +738,17 @@ const SingleContent = memo(function SingleContent({
// biome-ignore lint/correctness/useExhaustiveDependencies: the open sequence is the re-expand trigger
useEffect(() => {
- if (!showContextPanel || browserOpenSequence === 0) return;
const panel = artifactPanelRef.current;
if (!panel) return;
+ if (IMMEDIATE_CONTEXT_PANEL) {
+ panel.resize(
+ showContextPanel
+ ? (artifactPanelWidthRef.current ?? defaultPanelSizeRef.current)
+ : "0%",
+ );
+ return;
+ }
+ if (!showContextPanel || browserOpenSequence === 0) return;
if (!panel.isCollapsed() && panel.getSize().asPercentage > 5) return;
// expand() alone restores the pre-collapse width, which is zero after a drag shut.
panel.expand();
@@ -740,6 +756,7 @@ const SingleContent = memo(function SingleContent({
}, [browserOpenSequence, showContextPanel]);
useEffect(() => {
+ if (IMMEDIATE_CONTEXT_PANEL) return;
const panel = artifactPanelRef.current;
if (!panel) return;
@@ -922,12 +939,14 @@ const SingleContent = memo(function SingleContent({
defaultSize="100%"
// Distinct per layout: re-registering re-sorts panels so resizing follows the chat.
// The browser can take most of the row (it opens small); research keeps the chat wider.
+ // On WebKitGTK the open constraints stay registered while closed: the zero-width,
+ // collapsed sibling already lets the chat fill the group.
minSize={
browserFullView
? "0%"
: chatOnRight
? "28%"
- : artifactLayoutActive
+ : IMMEDIATE_CONTEXT_PANEL || artifactLayoutActive
? showResearchPanel
? "42%"
: "30%"
@@ -997,7 +1016,7 @@ const SingleContent = memo(function SingleContent({
minSize={
showResearchPanel
? "30%"
- : artifactPanelSettledOpen
+ : (IMMEDIATE_CONTEXT_PANEL || artifactPanelSettledOpen)
? "30%"
: "0%"
}
@@ -1006,11 +1025,11 @@ const SingleContent = memo(function SingleContent({
? "72%"
: showResearchPanel
? "58%"
- : artifactLayoutActive
+ : IMMEDIATE_CONTEXT_PANEL || artifactLayoutActive
? "70%"
: "0%"
}
- collapsible={showBrowserPanel}
+ collapsible={IMMEDIATE_CONTEXT_PANEL ? !showResearchPanel : showBrowserPanel}
collapsedSize="0%"
className={cn(
"h-full min-h-0 min-w-0 overflow-visible",
@@ -1020,7 +1039,9 @@ const SingleContent = memo(function SingleContent({
<div
ref={contextSurfaceRef}
data-artifact-surface-visible={
- isArtifactSurfaceVisible ? "true" : "false"
+ (IMMEDIATE_CONTEXT_PANEL ? showContextPanel : isArtifactSurfaceVisible)
+ ? "true"
+ : "false"
}
{...{ "data-browser-floating": browserFloating ? "" : undefined }}
className={cn(
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index b4ab57ebe36..f5529d0330a 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -7152,6 +7152,27 @@ html[data-glass] :is([data-wallpaper-workspace], [data-chat-content-root]):has(>
display: none;
}
+/* MessagePrimitive's slack helper clears inline flex-shrink on viewport updates.
+ Keep measured placeholders and reconnected display:contents bodies at natural height. */
+.aui-thread-viewport [data-message-windowed] {
+ flex-shrink: 0;
+ /* duration-150 on user rows otherwise transitions the placeholder's height
+ from its empty padding box, moving the reader as every batch is parked. */
+ transition-property: none;
+}
+
+/* Keep WebKitGTK thumb jumps synchronized with paints of newly mounted bodies.
+ Fixed backgrounds synchronize overflow scrolling with main-thread paints. */
+.aui-thread-viewport[data-windowed-messages]::before {
+ content: "";
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ pointer-events: none;
+ background-image: linear-gradient(transparent, transparent);
+ background-attachment: fixed;
+}
+
/* Transparent glass: the plain theme, every surface in its own colour at the glass strength's
opacity, with no shadow or blur. Tokens are redefined on #root from the copies taken on html
(a token cannot mix itself), so portalled menus and dialogs stay solid. Sonner renders its
diff --git a/studio/frontend/tests/code-block-containment-wiring.test.ts b/studio/frontend/tests/code-block-containment-wiring.test.ts
index f5471dd1412..1b418e276d6 100644
--- a/studio/frontend/tests/code-block-containment-wiring.test.ts
+++ b/studio/frontend/tests/code-block-containment-wiring.test.ts
@@ -76,7 +76,7 @@ test("the wrapper keeps the visible override and the body keeps the DOM contract
"the flicker rule on the wrapper stays",
);
const body = DEFER.slice(DEFER.indexOf("export const FenceBody = memo("));
- assert.ok(/data-unsloth-fence-windowed=\{lineWindow === null \|\| !measured \? undefined : "true"\}\s*ref=\{wrapper\}\s*>\s*<div\s*className=\{joinClasses\([\s\S]*?\)\}\s*data-language=\{language \?\? undefined\}\s*data-streamdown="code-block-body"\s*ref=\{surface\}/.test(body), "the window hook sits on a box that does not scroll, around a body that keeps streamdown's markup and the measuring ref");
+ assert.ok(/data-unsloth-fence-windowed=\{offscreenPlain \|\| 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");
});
@@ -142,8 +142,8 @@ test("startup arms the attribute and watches the console override, after the mat
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(pick.indexOf("checkVisibility") < pick.indexOf("for (const child of layoutChildren(anchor))"), "checked before any child rect is read");
+ const loop = pick.slice(pick.indexOf("for (const child of layoutChildren(anchor))"));
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 47d22235035..03f67aea985 100644
--- a/studio/frontend/tests/code-fence-body.test.ts
+++ b/studio/frontend/tests/code-fence-body.test.ts
@@ -343,6 +343,9 @@ test("paint containment is limited to large completed full-token bodies", () =>
memo: React.memo,
useMemo: React.useMemo,
useRef: React.useRef,
+ WINDOW_SETTLED_FENCES: false,
+ useCodeWrap: () => false,
+ useOffscreenFenceText: () => false,
useFenceHighlightLimit: () => ({ progress: null, staged: false }),
FENCE_CHUNK_LINES,
sameFenceBodyProps,
diff --git a/studio/frontend/tests/desktop-webkit-paths.test.ts b/studio/frontend/tests/desktop-webkit-paths.test.ts
index 8fcc23855bd..1f0f3c32a2d 100644
--- a/studio/frontend/tests/desktop-webkit-paths.test.ts
+++ b/studio/frontend/tests/desktop-webkit-paths.test.ts
@@ -10,7 +10,7 @@ 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"\}/,
+ /data-unsloth-fence-windowed=\{offscreenPlain \|\| 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;/);
@@ -88,3 +88,26 @@ test("find in page defers rebuilds during scrolling with a maximum wait", () =>
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");
});
+
+test("an offscreen fence update skipped under a held pointer or selection is retried on release", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ const hook = defer.slice(defer.indexOf("function useOffscreenFenceText("), defer.indexOf("export const FenceBody = memo("));
+ assert.match(
+ hook,
+ /if \(selected \|\| inputPointerHeld\(\)\) \{[^}]*heldLastFrame = true;\s*return;\s*\}/,
+ "releasePointer and selectionchange remeasure only after a held frame, so a skip must mark one or a fence that entered view mid-drag stays plain",
+ );
+ assert.match(defer, /const releasePointer = \(\): void => \{\s*if \(pointerHeld === null\) return;\s*pointerHeld = null;\s*if \(heldLastFrame\) scheduleRemeasure\(\);/);
+});
+
+test("settled WebKitGTK fences only line-window themselves while code wrapping is off", () => {
+ const defer = readSrc("components/assistant-ui/code-fence-defer.tsx");
+ assert.match(
+ defer,
+ /windowing \|\|= WINDOW_SETTLED_FENCES && !isIncomplete && !codeWrap\s*&& \(tokens\?\.length \?\? 0\) > WINDOW_CAP_LINES;/,
+ "line windows map offsets with one unwrapped row per source line; wrapped lines would highlight a window ahead of the reader, "
+ + "and a fence under the cap has no line window, so forcing windowing there would only drop the batched highlight path",
+ );
+ assert.match(defer, /const useCodeWrap = \(\): boolean => useSyncExternalStore\(subscribeCodeWrap, codeWrapOn, \(\) => false\);/);
+ assert.match(defer, /attributeFilter: \["data-code-wrap"\]/);
+});
diff --git a/studio/frontend/tests/find-windowed-fence.test.ts b/studio/frontend/tests/find-windowed-fence.test.ts
index fb49e367693..f81a28c9f82 100644
--- a/studio/frontend/tests/find-windowed-fence.test.ts
+++ b/studio/frontend/tests/find-windowed-fence.test.ts
@@ -28,7 +28,7 @@ test("while the find bar is open a long fence renders every line, so the highlig
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*\}\);/,
+ /findBarObserver = new MutationObserver\(scheduleRemeasure\);\s*findBarObserver\.observe\(document\.documentElement, \{\s*attributes: true,\s*attributeFilter: \[FIND_BAR_FLAG, "data-code-wrap", "data-code-line-numbers"\],\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 = "));
diff --git a/studio/frontend/tests/message-window.test.ts b/studio/frontend/tests/message-window.test.ts
new file mode 100644
index 00000000000..09b4cf18020
--- /dev/null
+++ b/studio/frontend/tests/message-window.test.ts
@@ -0,0 +1,334 @@
+// 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";
+
+const source = readFileSync(new URL("../src/components/assistant-ui/message-window-controller.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } });
+
+type EventData = { target?: ElementFake; key?: string; ctrlKey?: boolean; metaKey?: boolean; pointerType?: string; button?: number; buttons?: number };
+class Events {
+ listeners = new Map<string, Set<(event: EventData) => void>>();
+ addEventListener(name: string, callback: (event: EventData) => void) {
+ if (!this.listeners.has(name)) this.listeners.set(name, new Set());
+ this.listeners.get(name)!.add(callback);
+ }
+ removeEventListener(name: string, callback: (event: EventData) => void) { this.listeners.get(name)?.delete(callback); }
+ fire(name: string, event: EventData = {}) { for (const callback of this.listeners.get(name) ?? []) callback(event); }
+ count() { return [...this.listeners.values()].reduce((sum, set) => sum + set.size, 0); }
+}
+class Style {
+ values = new Map<string, [string, string]>();
+ setProperty(name: string, value: string, priority = "") { this.values.set(name, [value, priority]); }
+ getPropertyValue(name: string) { return this.values.get(name)?.[0] ?? ""; }
+ getPropertyPriority(name: string) { return this.values.get(name)?.[1] ?? ""; }
+ removeProperty(name: string) { this.values.delete(name); }
+ set height(value: string) { this.setProperty("height", value); }
+ set minHeight(value: string) { this.setProperty("min-height", value); }
+ set flexShrink(value: string) { this.setProperty("flex-shrink", value); }
+}
+class ElementFake extends Events {
+ parent: ElementFake | null = null;
+ children: ElementFake[] = [];
+ attributes = new Map<string, string>();
+ style = new Style();
+ className = "";
+ textContent = "original message";
+ top = -5000;
+ height = 200;
+ clientWidth = 600;
+ scrollWidth = 600;
+ protectedMedia = false;
+ viewport: ElementFake | null = null;
+ append(child: ElementFake) { child.remove(); this.children.push(child); child.parent = this; }
+ remove() { if (this.parent) this.parent.children = this.parent.children.filter((node) => node !== this); this.parent = null; }
+ contains(node: ElementFake | null): boolean { return node === this || this.children.some((child) => child.contains(node)); }
+ closest(selector: string) { return selector === ".aui-thread-viewport" ? this.viewport : null; }
+ querySelector() { return this.protectedMedia ? this : null; }
+ getBoundingClientRect() { return { top: this.top, bottom: this.top + this.height, height: this.height }; }
+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }
+ removeAttribute(name: string) { this.attributes.delete(name); }
+ hasAttribute(name: string) { return this.attributes.has(name); }
+}
+
+function world() {
+ const viewport = new ElementFake(); viewport.top = 0; viewport.height = 800;
+ const html = new ElementFake();
+ let selected = false;
+ const doc = Object.assign(new Events(), {
+ documentElement: html, activeElement: null as ElementFake | null,
+ createElement: () => new ElementFake(), getSelection: () => ({ isCollapsed: !selected, rangeCount: 1, getRangeAt: () => ({ intersectsNode: () => true }) }),
+ });
+ const media = Object.assign(new Events(), { matches: false });
+ const win = Object.assign(new Events(), { matchMedia: () => media });
+ let intersections: (entries: Array<{ target: ElementFake; isIntersecting: boolean }>) => void = () => {};
+ let mutation: () => void = () => {};
+ let observers = 0, disconnected = 0, frameId = 0;
+ const frames = new Map<number, () => void>();
+ const exports: { observeMessageWindow?: (root: ElementFake, holder: ElementFake, content: ElementFake, adjust?: (deltaPx: number) => void) => () => void } = {};
+ vm.runInNewContext(outputText, {
+ exports, window: win, document: doc,
+ requestAnimationFrame: (callback: () => void) => { frames.set(++frameId, callback); return frameId; },
+ cancelAnimationFrame: (id: number) => frames.delete(id),
+ IntersectionObserver: class {
+ constructor(callback: typeof intersections) { intersections = callback; observers++; }
+ observe() {} unobserve() {} disconnect() { disconnected++; }
+ },
+ MutationObserver: class {
+ constructor(callback: () => void) { mutation = callback; }
+ observe() {} disconnect() { disconnected++; }
+ },
+ });
+ const flush = () => { while (frames.size) { const pending = [...frames.values()]; frames.clear(); pending.forEach((callback) => callback()); } };
+ const add = (adjust?: (deltaPx: number) => void) => {
+ const root = new ElementFake(), holder = new ElementFake(), content = new ElementFake(), child = new ElementFake();
+ root.viewport = viewport; viewport.append(root); root.append(holder); holder.append(content); content.append(child);
+ root.style.setProperty("height", "200px", "important");
+ const cleanup = exports.observeMessageWindow!(root, holder, content, adjust);
+ return { root, holder, content, child, cleanup, parked: () => root.hasAttribute("data-message-parked") };
+ };
+ return {
+ add, viewport, doc, win, html, media, flush,
+ near: (root: ElementFake, near: boolean, top = near ? 0 : -5000) => { root.top = top; intersections([{ target: root, isIntersecting: near }]); flush(); },
+ select: (value: boolean) => { selected = value; doc.fire("selectionchange"); flush(); },
+ find: (value: boolean) => { if (value) html.setAttribute("data-find-bar-open", ""); else html.removeAttribute("data-find-bar-open"); mutation(); flush(); },
+ observers: () => observers, disconnected: () => disconnected,
+ };
+}
+
+test("distant bodies keep their height and reconnect the same nodes and inline styles", () => {
+ const w = world(), row = w.add();
+ w.near(row.root, false);
+ assert.equal(row.parked(), true);
+ assert.equal(row.content.parent, null);
+ assert.equal(row.root.style.getPropertyValue("height"), "200px");
+ row.root.style.setProperty("min-height", "50px");
+ assert.equal(row.holder.children[0].textContent, "original message");
+ w.near(row.root, true);
+ assert.equal(row.parked(), false);
+ assert.equal(row.content.parent, row.holder);
+ assert.equal(row.content.children[0], row.child);
+ assert.equal(row.root.style.getPropertyPriority("height"), "important");
+ assert.equal(row.root.style.getPropertyValue("min-height"), "50px", "do not overwrite the viewport slack helper");
+ row.cleanup();
+});
+
+test("find, print and selection reconnect every body until the operation ends", () => {
+ const w = world(), a = w.add(), b = w.add();
+ w.near(a.root, false); w.near(b.root, false);
+ for (const hold of [w.find, w.select]) {
+ hold(true); assert.equal(a.parked() || b.parked(), false);
+ hold(false); assert.equal(a.parked() && b.parked(), true);
+ }
+ w.win.fire("beforeprint"); assert.equal(a.parked() || b.parked(), false);
+ w.win.fire("afterprint"); w.flush(); assert.equal(a.parked() && b.parked(), true);
+ w.media.matches = true; w.media.fire("change"); assert.equal(a.parked() || b.parked(), false);
+ a.cleanup(); b.cleanup();
+});
+
+test("focus and select-all reconnect before browser default actions; dragging does not detach", () => {
+ const w = world(), row = w.add();
+ w.viewport.fire("pointerdown", { target: row.child, pointerType: "mouse", button: 0 }); w.near(row.root, false); assert.equal(row.parked(), false);
+ w.win.fire("pointerup"); w.flush(); assert.equal(row.parked(), true);
+ w.viewport.fire("focusin", { target: row.root }); assert.equal(row.parked(), false);
+ w.near(row.root, false); w.doc.fire("keydown", { key: "a", ctrlKey: true }); assert.equal(row.parked(), false);
+ row.cleanup();
+});
+
+test("wide replies and embedded media stay connected; shared observers and listeners clean up", () => {
+ const w = world(), a = w.add(), b = w.add();
+ a.root.scrollWidth = 1200; b.content.protectedMedia = true;
+ w.near(a.root, false); w.near(b.root, false);
+ assert.equal(a.parked() || b.parked(), false);
+ assert.equal(w.observers(), 1);
+ assert.equal(w.viewport.hasAttribute("data-windowed-messages"), true);
+ a.cleanup(); assert.equal(w.disconnected(), 0);
+ b.cleanup(); assert.equal(w.disconnected(), 2);
+ assert.equal(w.viewport.hasAttribute("data-windowed-messages"), false);
+ assert.equal(w.doc.count() + w.win.count() + w.viewport.count() + w.media.count(), 0);
+});
+
+test("thumb dragging releases visited bodies and holds restored heights until release", () => {
+ const w = world(), row = w.add();
+ row.root.style.removeProperty("height");
+ w.near(row.root, false);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ w.near(row.root, true);
+ assert.equal(row.parked(), false);
+ assert.equal(row.content.children[0], row.child);
+ assert.equal(row.root.style.getPropertyValue("height"), "200px");
+ w.near(row.root, false);
+ assert.equal(row.parked(), true, "a held thumb must not accumulate visited bodies");
+ w.near(row.root, true);
+ w.win.fire("pointerup"); w.flush();
+ assert.equal(row.root.style.getPropertyValue("height"), "", "release the original natural height");
+ row.cleanup();
+});
+
+test("print and drag cancellation release frozen message heights", () => {
+ for (const event of ["beforeprint", "pointercancel", "blur"]) {
+ const w = world(), row = w.add();
+ row.root.style.removeProperty("height");
+ w.near(row.root, false);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ w.near(row.root, true);
+ w.win.fire(event); w.flush();
+ assert.equal(row.root.style.getPropertyValue("height"), "", event);
+ row.cleanup();
+ }
+});
+
+test("a thumb drag restores the viewport before the normal lookahead", () => {
+ const w = world(), row = w.add();
+ w.near(row.root, false);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ w.near(row.root, true, 1800);
+ assert.equal(row.parked(), true, "do not render a message beyond the drag buffer");
+ row.root.top = 700;
+ w.viewport.fire("scroll"); w.flush();
+ assert.equal(row.parked(), false, "scrolling into view must restore without another IO boundary");
+ row.cleanup();
+});
+
+test("a missed mouseup releases heights on the next pointer move", () => {
+ const w = world(), row = w.add();
+ row.root.style.removeProperty("height");
+ w.near(row.root, true);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ assert.equal(row.root.style.getPropertyValue("height"), "200px");
+ w.win.fire("pointermove", { buttons: 0 }); w.flush();
+ assert.equal(row.root.style.getPropertyValue("height"), "");
+ row.cleanup();
+});
+
+test("wheel, keyboard and thumb jumps restore visible bodies before the next frame or IO delivery", () => {
+ for (const thumb of [false, true]) {
+ const w = world(), row = w.add();
+ w.near(row.root, false);
+ if (thumb) w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ row.root.top = 100;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), false, "restore synchronously even though the last IO record said offscreen");
+ assert.equal(row.content.parent, row.holder);
+ row.root.top = -5000;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), true);
+ row.cleanup();
+ }
+});
+
+test("stale intersection records cannot detach content that moved into view after a prepend", () => {
+ const w = world(), row = w.add();
+ w.near(row.root, false, 100);
+ assert.equal(row.parked(), false, "current geometry overrides the old intersection record");
+ w.near(row.root, true, -5000);
+ assert.equal(row.parked(), true);
+ // Find/selection settling defers measurements for parking, but must not delay visibility.
+ w.doc.fire("selectionchange");
+ row.root.top = 100;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), false);
+ w.flush();
+ row.cleanup();
+});
+
+test("small thumb reversals retain already restored overscan content", () => {
+ const w = world(), row = w.add();
+ w.near(row.root, false);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ row.root.top = 100;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), false);
+ row.root.top = 2000;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), false, "keep connected content beyond the restore band");
+ row.root.top = 4000;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), true);
+ row.cleanup();
+});
+
+test("restoring a reflowed body above the reader keeps the first visible row in place", () => {
+ const w = world(), above = w.add(), visible = w.add();
+ const scrolls: Array<{ top: number; behavior: string }> = [];
+ Object.assign(w.viewport, {
+ scrollTop: 1000,
+ scrollTo(options: { top: number; behavior: string }) { scrolls.push(options); (this as unknown as { scrollTop: number }).scrollTop = options.top; },
+ });
+ w.near(above.root, false);
+ assert.equal(above.parked(), true);
+ // The chat narrowed while `above` was parked: reconnected, its body is 60px taller than the
+ // placeholder height it kept, so everything below it moves down by that much.
+ visible.root.top = 50;
+ Object.defineProperty(visible.root, "isConnected", { value: true });
+ visible.root.getBoundingClientRect = () => {
+ const top = visible.root.top + (above.content.parent ? 60 : 0);
+ return { top, bottom: top + visible.root.height, height: visible.root.height };
+ };
+ w.viewport.fire("scroll");
+ assert.equal((w.viewport as unknown as { scrollTop: number }).scrollTop, 1000, "nothing reconnected, nothing corrected");
+ above.root.top = -1500;
+ w.viewport.fire("scroll");
+ assert.equal(above.parked(), false);
+ assert.equal((w.viewport as unknown as { scrollTop: number }).scrollTop, 1060, "the reflow above the reader is scrolled away");
+ assert.equal(JSON.stringify(scrolls), JSON.stringify([{ top: 1060, behavior: "instant" }]), "instant despite the viewport's scroll-smooth class");
+ above.cleanup();
+ visible.cleanup();
+});
+
+test("with an autoscroll owner the correction goes through it instead of writing scrollTop", () => {
+ const w = world(), deltas: number[] = [];
+ const above = w.add((delta) => deltas.push(delta)), visible = w.add();
+ Object.assign(w.viewport, { scrollTop: 1000, scrollTo() { throw new Error("must not write scrollTop directly"); } });
+ w.near(above.root, false);
+ visible.root.top = 50;
+ Object.defineProperty(visible.root, "isConnected", { value: true });
+ visible.root.getBoundingClientRect = () => {
+ const top = visible.root.top + (above.content.parent ? 60 : 0);
+ return { top, bottom: top + visible.root.height, height: visible.root.height };
+ };
+ w.viewport.fire("scroll");
+ above.root.top = -1500;
+ w.viewport.fire("scroll");
+ assert.equal(JSON.stringify(deltas), "[60]", "the owner resyncs its follow intent and scrolls instantly");
+ above.cleanup();
+ visible.cleanup();
+});
+
+test("a body restored during a thumb drag is clipped until release, then keeps its own overflow", () => {
+ const w = world(), row = w.add();
+ row.root.style.setProperty("overflow", "visible");
+ w.near(row.root, false);
+ assert.equal(row.parked(), true);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ row.root.top = 100;
+ w.viewport.fire("scroll");
+ assert.equal(row.parked(), false);
+ assert.equal(row.root.style.getPropertyValue("height"), "200px", "height frozen while the thumb is held");
+ assert.equal(row.root.style.getPropertyValue("overflow"), "clip", "a reflowed body cannot paint over the next messages");
+ w.win.fire("pointerup");
+ assert.equal(row.root.style.getPropertyValue("overflow"), "visible", "release restores the original overflow");
+ assert.equal(row.root.style.getPropertyPriority("height"), "important", "and the original height");
+ row.cleanup();
+});
+
+test("a body parked and restored again in one thumb drag still releases its own overflow", () => {
+ const w = world(), row = w.add();
+ row.root.style.setProperty("overflow", "visible");
+ w.near(row.root, false);
+ w.viewport.fire("pointerdown", { target: w.viewport, pointerType: "mouse", button: 0 });
+ for (const top of [100, 4000, 100]) {
+ row.root.top = top;
+ w.viewport.fire("scroll");
+ }
+ assert.equal(row.parked(), false);
+ assert.equal(row.root.style.getPropertyValue("overflow"), "clip");
+ w.win.fire("pointerup");
+ assert.equal(row.root.style.getPropertyValue("overflow"), "visible", "the temporary clip is never saved as the original");
+ row.cleanup();
+ assert.equal(row.root.style.getPropertyValue("overflow"), "visible");
+});
diff --git a/studio/frontend/tests/progressive-mount-controller.test.ts b/studio/frontend/tests/progressive-mount-controller.test.ts
index 92d24a7f03c..aead9a1c7f2 100644
--- a/studio/frontend/tests/progressive-mount-controller.test.ts
+++ b/studio/frontend/tests/progressive-mount-controller.test.ts
@@ -15,12 +15,72 @@ import {
type MountWindow,
admits,
anchorCorrection,
+ alignAnchorCorrection,
initialWindow,
isCovered,
stepsToCover,
+ watchProgressiveScroll,
widen,
} from "../src/components/assistant-ui/progressive-mount-controller.ts";
+test("mounting waits for wheel momentum and thumb release, without pausing on its own corrections", () => {
+ const viewport = new EventTarget();
+ let time = 1000;
+ const activity = watchProgressiveScroll(viewport, () => time);
+ const send = (type: string) => viewport.dispatchEvent(new Event(type));
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ send("scroll");
+ assert.equal(activity.blocked(false), false);
+ send("wheel");
+ assert.equal(activity.blocked(false), true);
+ time += 250;
+ send("scroll");
+ time += 250;
+ assert.equal(activity.blocked(false), true);
+ time += 51;
+ assert.equal(activity.blocked(false), false);
+ send("scroll");
+ assert.equal(activity.blocked(false), false);
+ assert.equal(activity.blocked(true), true);
+ time += 1000;
+ assert.equal(activity.blocked(true), true);
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ assert.equal(activity.blocked(false), false);
+ activity.dispose();
+ send("wheel");
+ assert.equal(activity.blocked(false), false);
+});
+
+test("scroll keys, touch momentum, and composer input outside the viewport pause mounting", () => {
+ const document = new EventTarget();
+ const viewport = Object.assign(new EventTarget(), { ownerDocument: document });
+ let time = 1000;
+ const activity = watchProgressiveScroll(viewport, () => time);
+ time += 301;
+ viewport.dispatchEvent(Object.assign(new Event("keydown"), { key: "a" }));
+ assert.equal(activity.blocked(false), false);
+ viewport.dispatchEvent(Object.assign(new Event("keydown"), { key: "PageUp" }));
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ viewport.dispatchEvent(new Event("touchmove"));
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ document.dispatchEvent(new Event("beforeinput"));
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ document.dispatchEvent(new Event("compositionupdate"));
+ assert.equal(activity.blocked(false), true);
+ time += 301;
+ document.dispatchEvent(new Event("pointerdown"));
+ assert.equal(activity.blocked(false), true);
+ activity.dispose();
+ time += 301;
+ document.dispatchEvent(new Event("beforeinput"));
+ assert.equal(activity.blocked(false), false);
+});
+
test("a thread under the floor is never windowed", () => {
for (const count of [0, 1, 20, MIN_PROGRESSIVE_MESSAGES - 1]) {
assert.equal(
@@ -72,6 +132,17 @@ test("widening only ever moves start down", () => {
}
});
+test("smaller renderer batches still converge without skipping messages", () => {
+ let current = initialWindow(600, false);
+ let previous = current!.start;
+ while (current !== null) {
+ current = widen(current, 600, 2);
+ const start = current?.start ?? 0;
+ assert.ok(start < previous && previous - start <= 2);
+ previous = start;
+ }
+});
+
test("widening reaches null from every thread length", () => {
for (const count of [40, 41, 80, 220, 501, 5000]) {
assert.ok(stepsToCover(count) >= 1, `${count} never widened`);
@@ -332,3 +403,28 @@ test("a capped window still only widens, and still converges", () => {
assert.ok(steps <= count + 2, "widen made no progress");
}
});
+
+test("fractional prepends and reflows keep the visible anchor stationary with integer scrolling", () => {
+ let inset = 0;
+ let contentTop = 0;
+ let scrollTop = 0;
+ for (let index = 0; index < 600; index++) {
+ const delta = [4408.625, 4210.4375, -0.375, 0.1875, -12.5625][index % 5];
+ contentTop += delta;
+ const aligned = alignAnchorCorrection(delta, inset);
+ assert.equal(Number.isInteger(aligned.scroll), true);
+ assert.ok(aligned.inset >= 0 && aligned.inset < 1);
+ inset = aligned.inset;
+ scrollTop += aligned.scroll;
+ assert.equal(contentTop + inset - scrollTop, 0);
+ }
+});
+
+test("subpixel reflows can be absorbed without issuing fractional scroll writes", () => {
+ const before = sample(30, 12000);
+ const after = sample(30.375, 12000);
+ assert.equal(anchorCorrection(before, after), null);
+ assert.equal(anchorCorrection(before, after, 1 / 64), 0.375);
+ assert.equal(anchorCorrection(before, before, 1 / 64), null);
+ assert.deepEqual(alignAnchorCorrection(-0.375, 0), { scroll: 0, inset: 0.375 });
+});
diff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.ts
index bab95f88124..82ffa1539b9 100644
--- a/studio/frontend/tests/progressive-mount-glue.test.ts
+++ b/studio/frontend/tests/progressive-mount-glue.test.ts
@@ -87,7 +87,7 @@ test("the window is only ever advanced through widen", () => {
const ok =
call === "null" ||
call.startsWith("initialWindow(") ||
- call.includes("widen(current, count)");
+ call.includes("widen(current, count, MOUNT_CHUNK)");
assert.ok(
ok,
`setMountWindow(${call}) is not one of null / initialWindow / widen`,
@@ -105,10 +105,10 @@ test("a run drops the window", () => {
assert.match(GLUE, /if \(isRunningNow\(\)\) \{\s*setMountWindow\(null\);/);
});
-test("the widening step is deferred and transition-wrapped", () => {
- // Without rAF chunks collapse into one commit; without startTransition widening blocks input.
+test("the widening step is deferred and WebKit commits inside the animation frame", () => {
assert.match(GLUE, /requestAnimationFrame\(/);
assert.match(GLUE, /startTransition\(/);
+ assert.match(GLUE, /if \(WEBKIT_GTK\) flushSync\(commit\);/);
assert.match(GLUE, /cancelAnimationFrame\(frame\)/);
// Scoped to the widening effect: a timer fires before paint and its handle cannot be
// cancelled as a frame.
@@ -119,7 +119,7 @@ test("the widening step is deferred and transition-wrapped", () => {
);
assert.match(
widening,
- /const frame = requestAnimationFrame\(/,
+ /frame = requestAnimationFrame\(advance\)/,
"the widening step must be scheduled on a frame, not a timer",
);
assert.doesNotMatch(
@@ -127,6 +127,7 @@ test("the widening step is deferred and transition-wrapped", () => {
/setTimeout|setInterval|queueMicrotask/,
"cancelAnimationFrame does not cancel a timer, so a closed window would still widen",
);
+ assert.match(widening, /if \(scrollActivity\.current\?\.blocked\(inputPointerHeld\(\)\)\) \{\s*frame = requestAnimationFrame\(advance\);\s*return;/);
});
test("the anchor is measured against its scroll container, not against the window", () => {
@@ -138,7 +139,7 @@ test("the anchor is measured against its scroll container, not against the windo
);
assert.match(GLUE, /function sampleAnchor\(/);
assert.match(GLUE, /sampleAnchor\(viewport, anchor\)/);
- assert.match(GLUE, /anchorCorrection\(baseline, sampleAnchor\(viewport, element\)\)/);
+ assert.match(GLUE, /anchorCorrection\(baseline, sampleAnchor\(viewport, element\), ANCHOR_PRECISION\)/);
// The anchor is often a <pre> Streamdown replaces after Shiki, so fall back to the row.
assert.match(GLUE, /const row = anchor\?\.closest\("\[data-role\]"\) \?\? null;/);
assert.match(GLUE, /captured\.row\?\.isConnected && captured\.rowSample/);
@@ -209,10 +210,10 @@ test("the mount window never writes scrollTop itself", () => {
assert.match(glue, /adjustForContentInsertedAbove\(shift \?\? 0\)/);
});
-test("the hook's correction stands down while the user is following", () => {
- // While following, the hook already pins to bottom in the same frame.
+test("the hook pins a follower during the prepend commit", () => {
const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");
- assert.match(body, /if \(!userDetachedRef\.current\) \{\s*return;/);
+ assert.match(body, /if \(!userDetachedRef\.current\) \{\s*insertionRemainder = 0;\s*if \(!parkIfHeld\(\)\) \{\s*extendFollow\(\);\s*pinIfFollowing\(stabilize\(\)\);/);
+ assert.match(body, /else if \(deltaPx !== 0\)/);
});
test("the hook's correction is instant, because the viewport is scroll-smooth", () => {
@@ -333,7 +334,8 @@ test("the anchor is the first row the reader can see, not the first row in the l
assert.match(GLUE, /function pickAnchorRow\(viewport: HTMLElement\)/);
assert.match(GLUE, /if \(row\.getBoundingClientRect\(\)\.bottom > fold\) \{/);
// A row can be taller than the viewport, so descend to the fold.
- assert.match(GLUE, /for \(const child of anchor\.children\)/);
+ assert.match(GLUE, /for \(const child of layoutChildren\(anchor\)\)/);
+ assert.match(GLUE, /getComputedStyle\(child\)\.display === "contents"/);
assert.match(GLUE, /function isAnchorVisible\(/);
assert.match(GLUE, /return box\.bottom > fold && box\.top < fold \+ viewport\.clientHeight;/);
// Pass a post-correction baseline, or a reflow before the next frame is never corrected.
diff --git a/studio/frontend/tests/reasoning-grid-collapse.test.ts b/studio/frontend/tests/reasoning-grid-collapse.test.ts
index 981ddd194a7..f787b10b0a9 100644
--- a/studio/frontend/tests/reasoning-grid-collapse.test.ts
+++ b/studio/frontend/tests/reasoning-grid-collapse.test.ts
@@ -127,7 +127,7 @@ test("the reasoning pane picks its primitive from the flag on all three slots",
assert.ok(code.includes("<UnmeasuredCollapsibleContent"));
});
-test("the scroll lock outlasts the grid collapse, and the shared hook's other callers do not move", () => {
+test("reasoning and tool scroll locks outlast the grid collapse", () => {
const code = codeOf(REASONING);
// The lock arms a commit before the transition starts, so an exact duration releases mid-collapse.
assert.match(
@@ -136,7 +136,7 @@ test("the scroll lock outlasts the grid collapse, and the shared hook's other ca
);
for (const other of [TOOL_GROUP, TOOL_FALLBACK]) {
assert.ok(
- codeOf(other).includes("useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION)"),
+ codeOf(other).includes("useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS)"),
);
}
});
@@ -153,11 +153,15 @@ test("the flag-on reasoning content runs no height keyframes", () => {
assert.ok(REASONING.includes('"data-[state=open]:animate-collapsible-down"'));
});
-test("the height keyframes stay in use everywhere else, because the sidebar listens for them", () => {
+test("tool panes avoid measurement and height keyframes; the sidebar keeps its animations", () => {
assert.ok(SHARED_COLLAPSIBLE.includes("animate-collapsible-down"));
assert.ok(SHARED_COLLAPSIBLE.includes("animate-collapsible-up"));
- assert.ok(TOOL_GROUP.includes("animate-collapsible-down"));
- assert.ok(TOOL_FALLBACK.includes("animate-collapsible-down"));
+ for (const source of [TOOL_GROUP, TOOL_FALLBACK]) {
+ assert.ok(source.includes("UnmeasuredCollapsible as Collapsible"));
+ assert.ok(source.includes("UnmeasuredCollapsibleContent as CollapsibleContent"));
+ assert.ok(source.includes("UnmeasuredCollapsibleTrigger as CollapsibleTrigger"));
+ assert.ok(!source.includes("animate-collapsible-"));
+ }
assert.ok(APP_SIDEBAR.includes('e.animationName === "collapsible-down"'));
assert.ok(APP_SIDEBAR.includes('e.animationName === "collapsible-up"'));
});
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index 24295075dfe..19c385923bc 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -266,7 +266,8 @@ def test_research_presentation_is_integrated() -> None:
assert "MutationObserver" in activity
assert "[overflow-anchor:none]" in activity
assert 'behavior: "smooth"' not in activity
- assert "collapsible={showBrowserPanel}" in page
+ # Off WebKitGTK the panel collapses with the browser; WebKitGTK keeps it registered (#16854).
+ assert "collapsible={IMMEDIATE_CONTEXT_PANEL ? !showResearchPanel : showBrowserPanel}" in page
assert "(!artifactLayoutActive || browserFullView) &&" in page
assert '? "30%"' in page
assert '? "58%"' in page