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: three follow-ups to the Deep Research main-thread work (#8633)

Daniel Han8993f3311f93
diff --git a/studio/frontend/smoke-autoscroll-main.tsx b/studio/frontend/smoke-autoscroll-main.tsx
new file mode 100644
index 00000000000..46705cdb7f5
--- /dev/null
+++ b/studio/frontend/smoke-autoscroll-main.tsx
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for tests/studio/playwright_chat_autoscroll.py: the real useIntentAwareAutoScroll on a
+// real scroller with text streamed in, so measured per-frame work is the hook's own.
+// Same shape as smoke-ansi.html and smoke-research.html: a vite entry, no backend, no auth.
+
+import {
+ IntentAwareScrollProvider,
+ useIntentAwareAutoScroll,
+} from "@/components/assistant-ui/use-intent-aware-autoscroll";
+import { type ReactElement, useEffect, useRef, useState } from "react";
+import { createRoot } from "react-dom/client";
+import "./src/index.css";
+
+const PARAGRAPH =
+ "British cultural exports carry several distinct threads, and the reception of each " +
+ "varies by audience, decade and medium. This paragraph exists to give the viewport real " +
+ "prose to lay out and to wrap over several lines at this width.";
+
+function Harness(): ReactElement {
+ const { ref, context } = useIntentAwareAutoScroll();
+ const [blocks, setBlocks] = useState<string[]>([]);
+ const [tail, setTail] = useState("");
+ const viewportRef = useRef<HTMLElement | null>(null);
+ const spacerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const viewport = () => viewportRef.current;
+ const api = {
+ /** Seed a viewport that already overflows, as a loaded thread does. */
+ seed(count = 40): void {
+ setBlocks(Array.from({ length: count }, (_, index) => `${index}`));
+ setTail("");
+ },
+ /** One streamed token into the trailing message: a characterData mutation. */
+ token(text: string): void {
+ setTail((current) => current + text);
+ },
+ /** One finished message: a childList mutation. */
+ block(): void {
+ setBlocks((current) => [...current, `${current.length}`]);
+ setTail("");
+ },
+ /**
+ * Grow content with no mutation record and no border-box resize, like a decoding image, a
+ * `font-display: swap` webfont or a late KaTeX pass. The MutationObserver excludes `style`,
+ * so only a frame that reads layout notices.
+ */
+ growSilently(px: number): void {
+ const spacer = spacerRef.current;
+ if (spacer) spacer.style.height = `${px}px`;
+ },
+ resetGrowth(): void {
+ const spacer = spacerRef.current;
+ if (spacer) spacer.style.height = "0px";
+ },
+ distanceFromBottom(): number {
+ const element = viewport();
+ if (!element) return -1;
+ return Math.max(
+ 0,
+ element.scrollHeight - element.scrollTop - element.clientHeight,
+ );
+ },
+ isAtBottom(): boolean {
+ return context.getIsAtBottom();
+ },
+ /** Scroll up the way a reader does, so the hook detaches. */
+ scrollUpBy(px: number): void {
+ const element = viewport();
+ if (element) element.scrollTop = Math.max(0, element.scrollTop - px);
+ },
+ scrollDownBy(px: number): void {
+ const element = viewport();
+ if (element) element.scrollTop += px;
+ },
+ detach(): void {
+ context.detachFromBottom();
+ },
+ scrollToBottom(): void {
+ context.scrollToBottom("instant");
+ },
+ metrics(): { scrollHeight: number; scrollTop: number; clientHeight: number } {
+ const element = viewport();
+ if (!element) return { scrollHeight: -1, scrollTop: -1, clientHeight: -1 };
+ return {
+ scrollHeight: element.scrollHeight,
+ scrollTop: element.scrollTop,
+ clientHeight: element.clientHeight,
+ };
+ },
+ };
+ (window as unknown as { __autoscroll: typeof api }).__autoscroll = api;
+ }, [context]);
+
+ return (
+ <IntentAwareScrollProvider value={context}>
+ <div
+ data-smoke="viewport"
+ ref={(element) => {
+ viewportRef.current = element;
+ ref(element);
+ }}
+ style={{
+ height: "100vh",
+ // A chat column's width, so prose wraps as in the app and a seeded thread overflows.
+ width: "760px",
+ overflowY: "auto",
+ padding: "16px",
+ paddingBottom: "var(--aui-scroll-stabilizer, 0px)",
+ }}
+ >
+ {blocks.map((id) => (
+ <p key={id} style={{ margin: "0 0 16px" }}>
+ Message {id}. {PARAGRAPH}
+ </p>
+ ))}
+ <p data-smoke="tail" style={{ margin: "0 0 16px" }}>
+ {tail}
+ </p>
+ <div ref={spacerRef} data-smoke="spacer" style={{ height: "0px" }} />
+ </div>
+ </IntentAwareScrollProvider>
+ );
+}
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("missing #root");
+}
+createRoot(root).render(<Harness />);
diff --git a/studio/frontend/smoke-autoscroll.html b/studio/frontend/smoke-autoscroll.html
new file mode 100644
index 00000000000..41d6260454f
--- /dev/null
+++ b/studio/frontend/smoke-autoscroll.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>chat autoscroll smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-autoscroll-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/smoke-research-main.tsx b/studio/frontend/smoke-research-main.tsx
new file mode 100644
index 00000000000..69d51ccd2ee
--- /dev/null
+++ b/studio/frontend/smoke-research-main.tsx
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for the #8483 deep research freeze, driven by tests/studio/playwright_research_freeze.py.
+// Real activity panel and report renderer against the real store, so the measured main-thread cost
+// of a streaming run is the app's, not a mock's.
+// Same shape as smoke-ansi.html/smoke-ansi-main.tsx: a vite entry, no backend, no auth.
+
+import { MarkdownPreview } from "@/components/markdown/markdown-preview";
+import { ResearchActivityPanel } from "@/features/chat";
+/* eslint-disable no-restricted-imports -- a measurement entry point, not app code: it drives the
+ research store directly, which the chat barrel does not export. */
+import {
+ ingestResearchUpdate,
+ useResearchRunStore,
+} from "@/features/chat/stores/research-run-store";
+import type {
+ ResearchEvent,
+ ResearchEventType,
+ ResearchRun,
+} from "@/features/chat/types/research";
+/* eslint-enable no-restricted-imports */
+import { type ReactElement, useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+import "./src/index.css";
+
+const RUN_ID = "smoke-run";
+const THREAD_ID = "smoke-thread";
+
+function baseRun(): ResearchRun {
+ return {
+ id: RUN_ID,
+ threadId: THREAD_ID,
+ userMessageId: "smoke-user-message",
+ status: "running",
+ plan: null,
+ planRevision: 1,
+ planHash: null,
+ steps: [],
+ sources: [],
+ lastEventSeq: 0,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+}
+
+let currentRun = baseRun();
+let seq = 0;
+
+function push(
+ event: ResearchEventType,
+ data: Record<string, unknown>,
+ runPatch?: Partial<ResearchRun>,
+): void {
+ seq += 1;
+ // Always a fresh run object, as research-api.ts did for deltas before #8483. Held constant on
+ // purpose: this harness measures the panel and report renderer, not run identity, which
+ // tests/research-run-identity.test.ts covers against the real followResearchRun.
+ const run: ResearchRun = {
+ ...currentRun,
+ ...runPatch,
+ lastEventSeq: seq,
+ updatedAt: Date.now(),
+ };
+ currentRun = run;
+ const payload: ResearchEvent = {
+ id: seq,
+ event,
+ createdAt: Date.now(),
+ data: { ...data, run } as ResearchEvent["data"],
+ run,
+ };
+ ingestResearchUpdate(run, payload);
+}
+
+function Harness(): ReactElement {
+ // Mounted by seed(), not at start: the panel's scroll hook is a useLayoutEffect keyed on runId,
+ // so rendering with no session takes the loading branch, observes no viewport, and never re-runs.
+ // The app only opens the panel for a run it already holds; the harness must do the same.
+ const [panelMounted, setPanelMounted] = useState(false);
+ const [report, setReport] = useState<string | null>(null);
+ const [clicks, setClicks] = useState(0);
+
+ useEffect(() => {
+ const api = {
+ /** Seed a run the panel can render. */
+ seed(): void {
+ currentRun = baseRun();
+ seq = 0;
+ push("run.created", {}, { status: "running" });
+ push("run.started", {}, { status: "running" });
+ setPanelMounted(true);
+ },
+ /** One reasoning delta, the event the synthesis phase emits ~12x a second. */
+ delta(text: string, phase = "synthesis"): void {
+ push("reasoning.updated", {
+ callId: "call-1",
+ attempt: 0,
+ phase,
+ reasoningDelta: text,
+ });
+ },
+ /** One report-progress delta. */
+ reportDelta(length: number): void {
+ push("report.updated", { attempt: 0, length, delta: 32 });
+ },
+ /** A search step plus its sources: what grows the activity list row by row. */
+ step(position: number): void {
+ push("step.started", {
+ attempt: 0,
+ stepPosition: position,
+ action: "search",
+ title: `Searching the web (${position})`,
+ input: `query ${position}`,
+ });
+ for (let index = 0; index < 4; index += 1) {
+ push("source.added", {
+ attempt: 0,
+ stepPosition: position,
+ url: `https://example.invalid/${position}/${index}`,
+ title: `Source ${position}.${index}`,
+ snippet: "A snippet long enough to wrap onto a second line in the panel.",
+ });
+ }
+ push("step.completed", {
+ attempt: 0,
+ stepPosition: position,
+ sourceCount: 4,
+ });
+ },
+ /** A plan awaiting approval, which mounts PlanReview's modal Dialog. */
+ awaitApproval(): void {
+ push(
+ "plan.ready",
+ {},
+ {
+ status: "awaiting_approval",
+ plan: {
+ title: "Smoke plan",
+ steps: [
+ { title: "Step one", query: "first query" },
+ { title: "Step two", query: "second query" },
+ ],
+ },
+ },
+ );
+ },
+ /** Approve it: the status change unmounts PlanReview while it is open. */
+ approve(): void {
+ push("run.approved", {}, { status: "queued" });
+ },
+ /** Unmount the whole panel, as closing the research pane does. */
+ closePanel(): void {
+ setPanelMounted(false);
+ },
+ openPanel(): void {
+ setPanelMounted(true);
+ },
+ /** Publish a finished report through the real renderer. */
+ publishReport(markdown: string): void {
+ setReport(markdown);
+ },
+ clearReport(): void {
+ setReport(null);
+ },
+ /** What the store holds, for assertions about activity count and status. */
+ state(): { activities: number; status: string | undefined } {
+ const session = useResearchRunStore.getState().sessions[RUN_ID];
+ return {
+ activities: session?.activities.length ?? 0,
+ status: session?.run.status,
+ };
+ },
+ clicks(): number {
+ return clicksRef.current;
+ },
+ };
+ (window as unknown as { __research: typeof api }).__research = api;
+ }, []);
+
+ return (
+ <div style={{ display: "flex", height: "100vh", gap: "8px" }}>
+ <div style={{ width: "420px", height: "100%", position: "relative" }}>
+ {panelMounted ? (
+ <ResearchActivityPanel
+ runId={RUN_ID}
+ onClose={() => setPanelMounted(false)}
+ />
+ ) : null}
+ </div>
+ <div style={{ flex: 1, overflow: "auto", padding: "12px" }}>
+ {/* The click probe: a stranded body pointer-events:none stops this counting up. */}
+ <button
+ type="button"
+ data-smoke="click-probe"
+ onClick={() => {
+ clicksRef.current += 1;
+ setClicks((value) => value + 1);
+ }}
+ >
+ clicked {clicks}
+ </button>
+ <section data-smoke="report">
+ {report === null ? null : <MarkdownPreview markdown={report} />}
+ </section>
+ </div>
+ </div>
+ );
+}
+
+const clicksRef = { current: 0 };
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("missing #root");
+}
+createRoot(root).render(<Harness />);
diff --git a/studio/frontend/smoke-research.html b/studio/frontend/smoke-research.html
new file mode 100644
index 00000000000..27242eb2a9c
--- /dev/null
+++ b/studio/frontend/smoke-research.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>deep research freeze smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-research-main.tsx"></script>
+ </body>
+</html>
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 9488ca1db9a..73eaaded13a 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
@@ -49,6 +49,13 @@ const UPWARD_DETACH_THRESHOLD_PX = 2;
// on every resize/mutation, so streaming keeps it pinned; settles this
// long after the last change.
const FOLLOW_SETTLE_MS = 600;
+// How often a quiet pinned frame re-checks layout for the rest of the follow
+// window. Content can grow with no mutation record and no border-box resize
+// (image decode, font-display: swap, a late KaTeX pass), and the
+// MutationObserver below excludes style, so only a frame that reads layout
+// notices. 100ms not every frame: six times fewer forced layouts, and the view
+// is back on the bottom in ~115ms measured (timer plus the frame it schedules).
+const SETTLE_CHECK_MS = 100;
// Max stabilizer compensation. Absorbs sub-frame transients (~5-15px shiki
// re-renders, ~8px action-bar drift). Larger shrinks are intentional
// content removals (delete, regenerate clear, reasoning collapse); padding
@@ -158,6 +165,10 @@ export function useIntentAwareAutoScroll(): {
const attach = useCallback(
(el: HTMLElement, isRebind: boolean) => {
let rafId: number | null = null;
+ let settleTimer: number | null = null;
+ let settleCheckDue = false;
+ // Layout signal since the last frame. True so the first frame after attach follows.
+ let layoutChanged = true;
let lastScrollTop = el.scrollTop;
let lastClientWidth = el.clientWidth;
let lastClientHeight = el.clientHeight;
@@ -228,9 +239,20 @@ export function useIntentAwareAutoScroll(): {
followUntilRef.current = performance.now() + FOLLOW_SETTLE_MS;
};
+ const clearSettleCheck = (): void => {
+ if (settleTimer !== null) {
+ clearTimeout(settleTimer);
+ settleTimer = null;
+ }
+ settleCheckDue = false;
+ };
+
const detach = (): void => {
userDetachedRef.current = true;
followUntilRef.current = 0;
+ // Hygiene, not correctness: `following` checks userDetached before `settling`, so a
+ // queued check cannot re-pin anyway; it just should not sit on a timer.
+ clearSettleCheck();
// The stabilizer only matters while pinning. Once the user
// scrolls up, drop residual padding so the bottom stays flush on
// return. Safe mid-content: shrinking scrollHeight can't cap their
@@ -245,22 +267,51 @@ export function useIntentAwareAutoScroll(): {
}
};
+ // A quiet pinned frame stops chaining and hands the rest of the window to this timer, which
+ // re-arms itself while the window is open. See SETTLE_CHECK_MS.
+ const scheduleSettleCheck = (): void => {
+ if (settleTimer !== null) {
+ return;
+ }
+ const remaining = followUntilRef.current - performance.now();
+ if (remaining <= 0) {
+ return;
+ }
+ settleTimer = window.setTimeout(
+ () => {
+ settleTimer = null;
+ // The window may have closed by then; grant that frame one last follow pass.
+ settleCheckDue = true;
+ requestTick();
+ },
+ Math.min(SETTLE_CHECK_MS, remaining),
+ );
+ };
+
// Single rAF loop. Within the follow window and not detached, pin to
- // bottom and report isAtBottom=true each frame; otherwise settle on
- // the DOM. Edge-triggered: scroll/resize/mutation call requestTick(),
- // and the loop self-perpetuates only while pinning is active.
+ // bottom and report isAtBottom=true; otherwise settle on the DOM.
+ // Edge-triggered: scroll/resize/mutation call requestTick(). Re-arms only while layout is
+ // still moving; chaining on the window alone read layout every frame of a stream.
const tick = (): void => {
rafId = null;
+ const settling = settleCheckDue;
+ settleCheckDue = false;
const following =
!userDetachedRef.current &&
- performance.now() < followUntilRef.current;
+ (settling || performance.now() < followUntilRef.current);
if (following) {
- if (!atBottomStrict() && el.scrollHeight > el.clientHeight) {
+ const pinned = atBottomStrict();
+ if (!pinned && el.scrollHeight > el.clientHeight) {
el.scrollTo({ top: el.scrollHeight, behavior: "instant" });
}
setIsAtBottom(true);
- requestTick();
+ if (layoutChanged || !pinned) {
+ layoutChanged = false;
+ requestTick();
+ return;
+ }
+ scheduleSettleCheck();
return;
}
@@ -440,6 +491,7 @@ export function useIntentAwareAutoScroll(): {
// first so the stabilizer sees follow as active; stabilize before
// pinning so we scroll to the post-adjustment scrollHeight.
const onLayoutChange = (): void => {
+ layoutChanged = true;
extendFollow();
const scrollHeight = stabilize();
pinIfFollowing(scrollHeight);
@@ -505,6 +557,7 @@ export function useIntentAwareAutoScroll(): {
cancelAnimationFrame(rafId);
rafId = null;
}
+ clearSettleCheck();
resizeObserver.disconnect();
mutationObserver.disconnect();
el.removeEventListener("wheel", onWheel);
diff --git a/studio/frontend/src/components/ui/tooltip-modal-layer.ts b/studio/frontend/src/components/ui/tooltip-modal-layer.ts
index 3121c688714..f16e506ba04 100644
--- a/studio/frontend/src/components/ui/tooltip-modal-layer.ts
+++ b/studio/frontend/src/components/ui/tooltip-modal-layer.ts
@@ -4,17 +4,13 @@
/**
* Whether a tooltip trigger sits below the active modal rather than inside it.
*
- * Radix's DismissableLayer writes `pointer-events` inline: `none` on the body
- * while a modal is up, `auto` on the active layer, `none` on the layers under
- * it. Walking the ancestors for the nearest of those answers which layer owns
- * the trigger.
+ * Radix's DismissableLayer writes `pointer-events` inline: `none` on the body while a modal is up,
+ * `auto` on the active layer, `none` on the layers under it. The nearest ancestor with one of
+ * those owns the trigger.
*
- * The trigger's own style is deliberately skipped. A trigger can be authored
- * `pointer-events: none` and still belong to the modal, which is exactly what
- * the hint anchors inside the MCP dropdown rows do.
- *
- * Read the trigger, never the tooltip content: layers rank by mount order, so
- * content opened after the modal reads `auto` wherever its trigger sits.
+ * The trigger's own style is skipped on purpose: it can be authored `pointer-events: none` and
+ * still belong to the modal, as the hint anchors in the MCP dropdown rows do. Read the trigger,
+ * never the content: layers rank by mount order, so content opened after the modal reads `auto`.
*/
export function isBlockedByActiveModal(element: HTMLElement): boolean {
for (let node = element.parentElement; node; node = node.parentElement) {
@@ -24,3 +20,108 @@ export function isBlockedByActiveModal(element: HTMLElement): boolean {
}
return false;
}
+
+// Whether a modal layer is up at all, shared by every tooltip. Radix sets body pointer-events to
+// none while one is, which is also when a hovered trigger stops receiving pointerleave, so an
+// open tooltip hangs over the dialog with nothing able to close it.
+//
+// Two observers, because the questions cost differently: "is a modal up" is one attribute on one
+// node; "which layer owns a trigger" needs the whole subtree, and only matters while one is up.
+let modalLayerUp = false;
+const modalLayerListeners = new Set<() => void>();
+let bodyLayerObserver: MutationObserver | null = null;
+let stackedLayerObserver: MutationObserver | null = null;
+
+function notifyModalLayer(): void {
+ for (const listener of modalLayerListeners) listener();
+}
+
+function readPointerEvents(style: string | null): string {
+ return (
+ /(?:^|;)\s*pointer-events\s*:\s*([^;]+)/.exec(style ?? "")?.[1]?.trim() ??
+ ""
+ );
+}
+
+function readStackedLayerMutations(records: MutationRecord[]): void {
+ for (const record of records) {
+ const previous = record.oldValue;
+ // The live property, not getAttribute: that serialises the whole declaration, and most
+ // records landing here while a modal is up are inline styles being animated.
+ const current = (record.target as HTMLElement).style?.pointerEvents ?? "";
+ // A style that never named pointer-events cannot have changed it. That is every animation
+ // frame, popper reposition and resize drag, and this test is why none reach the regex.
+ if (
+ current === "" &&
+ (previous === null || !previous.includes("pointer-events"))
+ ) {
+ continue;
+ }
+ if (readPointerEvents(previous) !== current) {
+ notifyModalLayer();
+ return;
+ }
+ }
+}
+
+// Stacking only matters while a modal is up; otherwise this fires on every animated inline style.
+function syncStackedLayerObserver(): void {
+ if (!modalLayerUp) {
+ stackedLayerObserver?.disconnect();
+ stackedLayerObserver = null;
+ return;
+ }
+ if (stackedLayerObserver) return;
+ stackedLayerObserver = new MutationObserver(readStackedLayerMutations);
+ stackedLayerObserver.observe(document.body, {
+ attributes: true,
+ attributeFilter: ["style"],
+ attributeOldValue: true,
+ subtree: true,
+ });
+}
+
+function readModalLayer(): void {
+ const next = document.body.style.pointerEvents === "none";
+ if (next === modalLayerUp) return;
+ modalLayerUp = next;
+ syncStackedLayerObserver();
+ notifyModalLayer();
+}
+
+export function subscribeModalLayer(listener: () => void): () => void {
+ // A fresh identity per subscription: the Set would otherwise collapse two subscribers sharing a
+ // callback, and the first cleanup would tear the observers down under the second.
+ const subscription = () => listener();
+ modalLayerListeners.add(subscription);
+ // Both conditions: without the size check a duplicate listener builds a second body observer
+ // and orphans the first, which is the leak the teardown below exists for.
+ if (
+ modalLayerListeners.size === 1 &&
+ !bodyLayerObserver &&
+ typeof MutationObserver !== "undefined"
+ ) {
+ bodyLayerObserver = new MutationObserver(readModalLayer);
+ bodyLayerObserver.observe(document.body, {
+ attributes: true,
+ attributeFilter: ["style"],
+ });
+ // Nothing watched the body while there were no listeners, so the flag needs this read.
+ readModalLayer();
+ }
+ return () => {
+ modalLayerListeners.delete(subscription);
+ if (modalLayerListeners.size > 0) return;
+ // No reader left. A modal still up when the last tooltip unmounts would otherwise leave the
+ // subtree observer running with nobody to notify. Clearing the flag before the sync drops
+ // that observer and keeps `readModalLayer`'s early return honest for the next subscriber.
+ bodyLayerObserver?.disconnect();
+ bodyLayerObserver = null;
+ modalLayerUp = false;
+ syncStackedLayerObserver();
+ };
+}
+
+export function getModalLayer(): boolean {
+ return modalLayerUp;
+}
diff --git a/studio/frontend/src/components/ui/tooltip.tsx b/studio/frontend/src/components/ui/tooltip.tsx
index 9a4ba9c48c4..324450383df 100644
--- a/studio/frontend/src/components/ui/tooltip.tsx
+++ b/studio/frontend/src/components/ui/tooltip.tsx
@@ -12,7 +12,11 @@ import {
} from "react";
import type * as React from "react";
-import { isBlockedByActiveModal } from "@/components/ui/tooltip-modal-layer";
+import {
+ getModalLayer,
+ isBlockedByActiveModal,
+ subscribeModalLayer,
+} from "@/components/ui/tooltip-modal-layer";
import { resolveTooltipOpen } from "@/components/ui/tooltip-open-state";
import { cn } from "@/lib/utils";
@@ -22,80 +26,6 @@ const TooltipTriggerElementCtx = createContext<(element: HTMLElement | null) =>
() => undefined,
);
-// Radix sets body pointer-events to none while a modal layer is up. That is also when a hovered
-// trigger stops receiving pointerleave, so a tooltip already on screen hangs over the dialog
-// with nothing able to close it. Two shared observers serve every tooltip.
-let modalLayerUp = false;
-const modalLayerListeners = new Set<() => void>();
-let bodyLayerObserver: MutationObserver | null = null;
-let stackedLayerObserver: MutationObserver | null = null;
-
-function notifyModalLayer(): void {
- for (const listener of modalLayerListeners) listener();
-}
-
-function readPointerEvents(style: string | null): string {
- return (
- /(?:^|;)\s*pointer-events\s*:\s*([^;]+)/.exec(style ?? "")?.[1]?.trim() ??
- ""
- );
-}
-
-function readStackedLayerMutations(records: MutationRecord[]): void {
- const pointerEventsChanged = records.some(
- (record) =>
- readPointerEvents(record.oldValue) !==
- readPointerEvents(
- (record.target as Element).getAttribute?.("style") ?? null,
- ),
- );
- if (pointerEventsChanged) notifyModalLayer();
-}
-
-// stacking only matters while a modal is up; otherwise this fires on every animated inline style.
-function syncStackedLayerObserver(): void {
- if (!modalLayerUp) {
- stackedLayerObserver?.disconnect();
- stackedLayerObserver = null;
- return;
- }
- if (stackedLayerObserver) return;
- stackedLayerObserver = new MutationObserver(readStackedLayerMutations);
- stackedLayerObserver.observe(document.body, {
- attributes: true,
- attributeFilter: ["style"],
- attributeOldValue: true,
- subtree: true,
- });
-}
-
-function readModalLayer(): void {
- const next = document.body.style.pointerEvents === "none";
- if (next === modalLayerUp) return;
- modalLayerUp = next;
- syncStackedLayerObserver();
- notifyModalLayer();
-}
-
-function subscribeModalLayer(listener: () => void): () => void {
- modalLayerListeners.add(listener);
- if (!bodyLayerObserver && typeof MutationObserver !== "undefined") {
- bodyLayerObserver = new MutationObserver(readModalLayer);
- bodyLayerObserver.observe(document.body, {
- attributes: true,
- attributeFilter: ["style"],
- });
- readModalLayer();
- }
- return () => {
- modalLayerListeners.delete(listener);
- };
-}
-
-function getModalLayer(): boolean {
- return modalLayerUp;
-}
-
function assignRef<T>(ref: React.Ref<T> | undefined, value: T | null): void {
if (typeof ref === "function") {
ref(value);
diff --git a/studio/frontend/src/features/chat/components/research-activity-panel.tsx b/studio/frontend/src/features/chat/components/research-activity-panel.tsx
index 526ac6e6c90..ac6bc0e417b 100644
--- a/studio/frontend/src/features/chat/components/research-activity-panel.tsx
+++ b/studio/frontend/src/features/chat/components/research-activity-panel.tsx
@@ -100,6 +100,7 @@ function useResearchActivityScroll(runId: string) {
let animationFrame: number | null = null;
let settleTimer: number | null = null;
let settleCheckDue = false;
+ // Layout signal since the last frame. True so the first frame after mount follows.
let layoutChanged = true;
const distanceFromBottom = () =>
@@ -155,8 +156,14 @@ function useResearchActivityScroll(runId: string) {
const detach = () => {
detached = true;
followUntil = 0;
- // A settle check queued by the last quiet frame would otherwise fire mid-scroll and reconcile
- // isAtBottom back to true whenever the user has moved less than the bottom threshold.
+ // Cancel every pending follow step, not just the settle check. A frame queued before the
+ // detach still runs, falls through to the reconcile below, and reads a flick shorter than
+ // the bottom threshold as still-at-bottom: "Latest" never appears and nothing corrects it,
+ // since followLayout returns early from here on.
+ if (animationFrame !== null) {
+ cancelAnimationFrame(animationFrame);
+ animationFrame = null;
+ }
if (settleTimer !== null) {
window.clearTimeout(settleTimer);
settleTimer = null;
diff --git a/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts b/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts
new file mode 100644
index 00000000000..f367343a625
--- /dev/null
+++ b/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The chat viewport followed the bottom by chaining requestAnimationFrame off a 600ms window that
+// every mutation re-armed, so a streaming message forced a layout read every frame throughout.
+// Measured with tests/studio/playwright_chat_autoscroll.py on a frame pump, a message every 250ms
+// (deep research synthesis cadence) held the loop at the pump's ceiling of 62 frames a second;
+// after this change it settles to the 100ms settle check, about 12.
+//
+// The cost is invisible to a rendering test and the hook is a .tsx, which node's type stripping
+// cannot import, so the shape is pinned here as drag-costs-no-render.test.ts pins the drag path:
+// assert the cheap path, and assert the expensive one is gone.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const HOOK = readFileSync(
+ new URL(
+ "../src/components/assistant-ui/use-intent-aware-autoscroll.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+/** The body of `tick`, which is the only place the chain re-arms. */
+function tickBody(): string {
+ const start = HOOK.indexOf("const tick = (): void => {");
+ assert.notEqual(start, -1, "tick is gone; this test needs rewriting");
+ const end = HOOK.indexOf("\n };", start);
+ return HOOK.slice(start, end);
+}
+
+test("a following frame re-arms only while layout is still moving", () => {
+ const tick = tickBody();
+ assert.match(tick, /if \(layoutChanged \|\| !pinned\) \{/);
+ assert.match(tick, /layoutChanged = false;/);
+ // The old path: one requestTick per frame while the window stayed open, and every mutation
+ // extended it, so a streaming message never let it close.
+ assert.doesNotMatch(
+ tick,
+ /setIsAtBottom\(true\);\s*requestTick\(\);\s*return;/,
+ "tick chains unconditionally inside the follow window",
+ );
+});
+
+test("a quiet pinned frame hands the rest of the window to the settle check", () => {
+ const tick = tickBody();
+ assert.match(tick, /scheduleSettleCheck\(\);/);
+ // Growth that reaches neither observer (image decode, font-display: swap, a late KaTeX pass)
+ // is why the window exists at all, so it must still be followed.
+ assert.match(HOOK, /const SETTLE_CHECK_MS = 100;/);
+ assert.match(
+ HOOK,
+ /settleTimer = window\.setTimeout\(/,
+ "the settle check must be a timer, not another frame",
+ );
+ assert.match(HOOK, /Math\.min\(SETTLE_CHECK_MS, remaining\)/);
+});
+
+test("the settle check grants its frame one last follow pass", () => {
+ const tick = tickBody();
+ // Without settleCheckDue the timer's frame lands after the window closed and falls into the
+ // settle branch, so the growth it was scheduled for goes unfollowed.
+ assert.match(tick, /const settling = settleCheckDue;/);
+ assert.match(tick, /settleCheckDue = false;/);
+ assert.match(tick, /\(settling \|\| performance\.now\(\) < followUntilRef\.current\)/);
+});
+
+test("detaching cancels a queued settle check", () => {
+ const detach = HOOK.slice(
+ HOOK.indexOf("const detach = (): void => {"),
+ HOOK.indexOf("const requestTick = (): void => {"),
+ );
+ // `following` checks userDetached before `settling`, so a queued check cannot re-pin a detached
+ // viewport; cancelling it just avoids leaving a timer armed with nothing to do.
+ assert.match(detach, /clearSettleCheck\(\);/);
+ assert.match(HOOK, /const clearSettleCheck = \(\): void => \{/);
+ assert.match(HOOK, /settleCheckDue = false;\s*\};/);
+});
+
+test("teardown clears the settle timer", () => {
+ const cleanup = HOOK.slice(HOOK.indexOf("cancelAnimationFrame(rafId);"));
+ assert.match(cleanup, /clearSettleCheck\(\);/);
+ assert.match(cleanup, /resizeObserver\.disconnect\(\);/);
+});
+
+test("every layout signal marks layout as moving", () => {
+ const onLayoutChange = HOOK.slice(
+ HOOK.indexOf("const onLayoutChange = (): void => {"),
+ ).slice(0, 400);
+ // The single fan-in for ResizeObserver, MutationObserver and visualViewport.resize. Set the
+ // flag anywhere narrower and a mutation can arrive on a frame that declines to chase it.
+ assert.match(onLayoutChange, /layoutChanged = true;/);
+ assert.match(onLayoutChange, /extendFollow\(\);/);
+});
diff --git a/studio/frontend/tests/research-activity-follow-loop.test.ts b/studio/frontend/tests/research-activity-follow-loop.test.ts
new file mode 100644
index 00000000000..a8634eca485
--- /dev/null
+++ b/studio/frontend/tests/research-activity-follow-loop.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The research activity scroller follows a run that mutates several times a second, so its
+// per-frame work is what #8483 froze on. Cost and detach behaviour are invisible to a unit test
+// (tests/studio/playwright_research_freeze.py measures them in a real browser), so these pin the
+// shape the measurements were taken against, as drag-costs-no-render.test.ts does for panels.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+function followLoopSource(): string {
+ const text = readFileSync(
+ new URL(
+ "../src/features/chat/components/research-activity-panel.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const start = text.indexOf("function useResearchActivityScroll");
+ assert.ok(start >= 0, "useResearchActivityScroll is gone");
+ const end = text.indexOf("\n}", text.indexOf("}, [runId];".replace(";", ");")));
+ // Without this the slice widens to the rest of the file and every assertion passes for the
+ // wrong reason.
+ assert.ok(end > start, "could not find the end of useResearchActivityScroll");
+ return text.slice(start, end);
+}
+
+test("a follow frame chains while unpinned, plus one after every layout signal", () => {
+ const hook = followLoopSource();
+ assert.match(
+ hook,
+ /if \(layoutChanged \|\| !pinned\) \{\s*layoutChanged = false;\s*requestTick\(\);/,
+ );
+ // The guaranteed frame is not redundant: a click's frame can land before the Collapsible height
+ // animation it started has grown at all, so chaining on !pinned alone stops there and leaves the
+ // log behind until the settle check. Neither observer sees a height animation to restart it.
+ assert.match(hook, /layoutChanged = true;\s*followUntil = performance\.now\(\)/);
+});
+
+test("a quiet frame hands the rest of the window to one deferred check", () => {
+ const hook = followLoopSource();
+ assert.match(hook, /scheduleSettleCheck\(\);\s*return;\s*\}/);
+ assert.match(hook, /settleTimer = window\.setTimeout\(/);
+});
+
+test("detach cancels every pending follow step", () => {
+ const hook = followLoopSource();
+ const detach = hook.slice(
+ hook.indexOf("const detach = () => {"),
+ hook.indexOf("const innerScrollWillConsumeUpward"),
+ );
+ // Without the frame cancel, a follow step queued before the detach still runs, reconciles
+ // isAtBottom through the bottom threshold, and hides "Latest" after a short upward flick.
+ assert.match(detach, /cancelAnimationFrame\(animationFrame\)/);
+ assert.match(detach, /animationFrame = null/);
+ assert.match(detach, /window\.clearTimeout\(settleTimer\)/);
+ assert.match(detach, /settleCheckDue = false/);
+});
+
+test("the pinned threshold stays at 2px, not 1", () => {
+ const text = readFileSync(
+ new URL(
+ "../src/features/chat/components/research-activity-panel.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // HiDPI subpixel rounding leaves a fractional gap; at 1px the loop never reads as pinned and
+ // never exits, the configuration the freeze was reported on.
+ assert.match(text, /const ACTIVITY_PINNED_THRESHOLD_PX = 2;/);
+});
diff --git a/studio/frontend/tests/tooltip-modal-layer-store.test.ts b/studio/frontend/tests/tooltip-modal-layer-store.test.ts
new file mode 100644
index 00000000000..19491ca13e2
--- /dev/null
+++ b/studio/frontend/tests/tooltip-modal-layer-store.test.ts
@@ -0,0 +1,257 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The shared modal-layer subscription behind every tooltip. Two observers: a cheap one on the
+// body's style attribute answering "is a modal up", and a document-wide subtree one answering
+// "which layer owns this trigger", attached only while the first says yes.
+//
+// These pin that the expensive observer never exists outside a modal, never outlives its readers,
+// and comes back when a reader does while a modal is still up.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+type ObserverInit = {
+ attributes?: boolean;
+ attributeFilter?: string[];
+ attributeOldValue?: boolean;
+ subtree?: boolean;
+};
+
+type FakeObserver = {
+ init: ObserverInit;
+ connected: boolean;
+ deliver: (records: unknown[]) => void;
+};
+
+const observers: FakeObserver[] = [];
+/** getAttribute calls: the animation path must never serialise a style. */
+let attributeReads = 0;
+
+function fakeElement(pointerEvents = ""): HTMLElement {
+ return {
+ style: { pointerEvents },
+ getAttribute: (name: string) => {
+ attributeReads += 1;
+ return name === "style" ? `pointer-events: ${pointerEvents}` : null;
+ },
+ } as unknown as HTMLElement;
+}
+
+const body = fakeElement();
+
+class FakeMutationObserver {
+ private entry: FakeObserver;
+ constructor(callback: (records: unknown[]) => void) {
+ this.entry = {
+ init: {},
+ connected: false,
+ deliver: (records) => callback(records),
+ };
+ observers.push(this.entry);
+ }
+ observe(_target: unknown, init: ObserverInit) {
+ this.entry.init = init;
+ this.entry.connected = true;
+ }
+ disconnect() {
+ this.entry.connected = false;
+ }
+}
+
+Object.assign(globalThis, {
+ document: { body },
+ MutationObserver: FakeMutationObserver,
+});
+
+const { getModalLayer, subscribeModalLayer } = await import(
+ "../src/components/ui/tooltip-modal-layer.ts"
+);
+
+/** The document-wide stacking observer, if one is attached. */
+function stackedObserver(): FakeObserver | undefined {
+ return observers
+ .filter((entry) => entry.init.subtree && entry.connected)
+ .at(-1);
+}
+
+function bodyObserver(): FakeObserver | undefined {
+ return observers
+ .filter((entry) => !entry.init.subtree && entry.connected)
+ .at(-1);
+}
+
+function openModal(): void {
+ body.style.pointerEvents = "none";
+ bodyObserver()?.deliver([{ target: body, oldValue: "" }]);
+}
+
+function closeModal(): void {
+ body.style.pointerEvents = "";
+ bodyObserver()?.deliver([{ target: body, oldValue: "pointer-events: none" }]);
+}
+
+// Only the counters. The observers list is kept on purpose: module state is global and an
+// undisconnected leftover observer is the thing under test, so clearing the list would hide it.
+// The helpers above read the last *connected* entry, which is what the module is using.
+function reset(): void {
+ attributeReads = 0;
+}
+
+test("no modal means no document-wide observer", () => {
+ reset();
+ body.style.pointerEvents = "";
+ const unsubscribe = subscribeModalLayer(() => undefined);
+ assert.equal(getModalLayer(), false);
+ assert.equal(stackedObserver(), undefined);
+ assert.ok(bodyObserver(), "the body's own style attribute is always watched");
+ assert.equal(bodyObserver()?.init.subtree, undefined);
+ unsubscribe();
+});
+
+test("the document-wide observer follows the modal in and out", () => {
+ reset();
+ let notified = 0;
+ const unsubscribe = subscribeModalLayer(() => {
+ notified += 1;
+ });
+
+ openModal();
+ assert.equal(getModalLayer(), true);
+ assert.equal(notified, 1);
+ const stacked = stackedObserver();
+ assert.ok(stacked, "a modal is up, so stacking has to be watched");
+ assert.equal(stacked?.init.attributeOldValue, true);
+
+ closeModal();
+ assert.equal(getModalLayer(), false);
+ assert.equal(notified, 2);
+ assert.equal(stackedObserver(), undefined, "it must not outlive the modal");
+ unsubscribe();
+});
+
+test("both observers go when the last listener goes", () => {
+ reset();
+ const unsubscribe = subscribeModalLayer(() => undefined);
+ openModal();
+ assert.ok(stackedObserver());
+
+ unsubscribe();
+ // The modal is still up: nothing closed it before the last reader left.
+ assert.equal(
+ stackedObserver(),
+ undefined,
+ "a modal that is still up must not keep the subtree observer alive for nobody",
+ );
+ assert.equal(bodyObserver(), undefined);
+});
+
+test("a listener arriving while a modal is up gets the observer back", () => {
+ reset();
+ const first = subscribeModalLayer(() => undefined);
+ openModal();
+ first();
+ assert.equal(stackedObserver(), undefined);
+
+ // Dropping the observers must not cost the next reader its answer: the modal is still up, so
+ // this subscriber has to be told and stacking watched again.
+ let notified = 0;
+ const second = subscribeModalLayer(() => {
+ notified += 1;
+ });
+ assert.equal(getModalLayer(), true, "the body still says a modal is up");
+ assert.ok(stackedObserver(), "stacking must be watched again");
+ assert.equal(notified, 1, "the arriving listener is told the layer is up");
+ second();
+ body.style.pointerEvents = "";
+});
+
+test("an animated inline style notifies nobody and serialises nothing", () => {
+ reset();
+ let notified = 0;
+ const unsubscribe = subscribeModalLayer(() => {
+ notified += 1;
+ });
+ openModal();
+ notified = 0;
+ attributeReads = 0;
+
+ // What an animation frame, a popper reposition and a resize drag look like here.
+ const animated = fakeElement();
+ stackedObserver()?.deliver([
+ { target: animated, oldValue: "transform: translate3d(0px, 0px, 0px)" },
+ { target: animated, oldValue: "transform: translate3d(1px, 0px, 0px)" },
+ { target: animated, oldValue: "opacity: 0.4" },
+ { target: animated, oldValue: null },
+ ]);
+
+ assert.equal(notified, 0);
+ assert.equal(
+ attributeReads,
+ 0,
+ "the live property answers, no getAttribute needed",
+ );
+ closeModal();
+ unsubscribe();
+});
+
+test("a layer losing pointer-events auto notifies", () => {
+ reset();
+ let notified = 0;
+ const unsubscribe = subscribeModalLayer(() => {
+ notified += 1;
+ });
+ openModal();
+ notified = 0;
+
+ // A second dialog opens over the first: the layer beneath flips auto to none.
+ stackedObserver()?.deliver([
+ { target: fakeElement("none"), oldValue: "pointer-events: auto" },
+ ]);
+ assert.equal(notified, 1);
+
+ // And back, when it closes.
+ stackedObserver()?.deliver([
+ { target: fakeElement("auto"), oldValue: "pointer-events: none" },
+ ]);
+ assert.equal(notified, 2);
+ closeModal();
+ unsubscribe();
+});
+
+test("a style that only drops pointer-events still notifies", () => {
+ reset();
+ let notified = 0;
+ const unsubscribe = subscribeModalLayer(() => {
+ notified += 1;
+ });
+ openModal();
+ notified = 0;
+
+ // The layer stops writing the property at all, which is how Radix ends the modal state.
+ stackedObserver()?.deliver([
+ { target: fakeElement(""), oldValue: "pointer-events: auto" },
+ ]);
+ assert.equal(notified, 1);
+ closeModal();
+ unsubscribe();
+});
+
+test("two subscribers sharing a callback survive one of them leaving", () => {
+ reset();
+ let notifications = 0;
+ const listener = () => {
+ notifications += 1;
+ };
+ const first = subscribeModalLayer(listener);
+ const second = subscribeModalLayer(listener);
+ first();
+ // The Set stores identities, so without a per-subscription wrapper both entries collapse into
+ // one and the first cleanup disconnects the observers under a subscriber still reading.
+ notifications = 0;
+ openModal();
+ assert.equal(getModalLayer(), true);
+ assert.ok(notifications > 0, "the surviving subscriber stopped being notified");
+ second();
+ closeModal();
+});
diff --git a/tests/studio/playwright_chat_autoscroll.py b/tests/studio/playwright_chat_autoscroll.py
new file mode 100644
index 00000000000..19754045c01
--- /dev/null
+++ b/tests/studio/playwright_chat_autoscroll.py
@@ -0,0 +1,303 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-frame cost and intent correctness of the main chat viewport's autoscroll (#8483).
+
+The chat viewport follows the bottom through a 600ms window that every mutation re-arms, so a
+streaming message keeps the window open for its whole duration. What that window costs depends
+on whether the frame chain re-arms unconditionally or only while layout is still moving, which
+is the change PR #8525 made to the research activity panel's equivalent loop.
+
+Four phases, and the third is the one that decides whether the port is worth making:
+
+ stream - tokens and blocks at a realistic cadence; how many frames does the loop run.
+ idle - the loop must stop when the content goes quiet.
+ silent - content grows via an inline style, which the MutationObserver deliberately
+ excludes and a border-box ResizeObserver cannot see. Only a frame that reads
+ layout notices. This models a decoding image, a font-display: swap webfont and a
+ late KaTeX pass. Measures how long the view stays off the bottom.
+ intent - scrolling up detaches and stays detached through further streaming; scrolling
+ back re-attaches. A cheaper loop must not cost any of this.
+
+requestAnimationFrame is pumped on a fixed 16ms timer: Chromium here produces only a couple of
+real frames a second, which would flatten a runaway per-frame loop into a passing number. The
+counts are therefore a property of the code, not of this machine's compositor. Chromium is also
+not the WebKitGTK webview the desktop app embeds, so what transfers is the work, not the
+absolute timings.
+
+Run:
+ cd studio/frontend && npx vite --port 5193 &
+ SMOKE_BASE_URL=http://127.0.0.1:5193 python tests/studio/playwright_chat_autoscroll.py
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import chromium_launch_args # noqa: E402
+
+BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:5193")
+LABEL = os.environ.get("SMOKE_LABEL", "tree")
+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-chat-autoscroll"))
+OUT.mkdir(parents = True, exist_ok = True)
+
+# A token every 250ms for 8s: the deep research synthesis cadence, and the one the loop is
+# wasteful at. A faster cadence (SMOKE_TOKEN_GAP_MS=40) is the one case where a frame per token is
+# justified, so measuring only there hides the effect.
+TOKEN_COUNT = int(os.environ.get("SMOKE_TOKEN_COUNT", "32"))
+TOKEN_GAP_MS = int(os.environ.get("SMOKE_TOKEN_GAP_MS", "250"))
+# One frame per token at this cadence is 4/s; the old loop ran at the pump's ceiling, around 62/s.
+# 25/s leaves room for React's own frames and still fails loudly on a return to the ceiling.
+MAX_STREAM_RAF_PER_SECOND = float(os.environ.get("SMOKE_MAX_RAF_PER_S", "25"))
+# The follow window in the hook. Silent growth is measured against it.
+FOLLOW_SETTLE_MS = 600
+# What the settle check trades away: unobservable growth is followed on a timer, not the next
+# frame. Generous against 115ms measured, tight enough to catch a regression.
+SILENT_GROWTH_REPIN_BUDGET_MS = int(os.environ.get("SMOKE_REPIN_BUDGET_MS", "250"))
+
+PUMP_INIT = """
+(() => {
+ window.__longTasks = [];
+ try {
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ window.__longTasks.push({ start: entry.startTime, duration: entry.duration });
+ }
+ }).observe({ type: "longtask", buffered: true });
+ } catch (e) { /* longtask unsupported: the CDP metrics still apply */ }
+ window.__rafCount = 0;
+ let nextHandle = 1;
+ const pending = new Map();
+ window.requestAnimationFrame = (cb) => {
+ const handle = nextHandle++;
+ pending.set(
+ handle,
+ setTimeout(() => {
+ pending.delete(handle);
+ window.__rafCount += 1;
+ cb(performance.now());
+ }, 16),
+ );
+ return handle;
+ };
+ window.cancelAnimationFrame = (handle) => {
+ const timer = pending.get(handle);
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ pending.delete(handle);
+ }
+ };
+})();
+"""
+
+
+def info(message: str) -> None:
+ print(f"[chat-autoscroll] {message}", flush = True)
+
+
+def metrics(cdp) -> dict[str, float]:
+ got = cdp.send("Performance.getMetrics")
+ return {m["name"]: m["value"] for m in got["metrics"]}
+
+
+def delta(before: dict[str, float], after: dict[str, float], name: str) -> float:
+ return round(after.get(name, 0.0) - before.get(name, 0.0), 4)
+
+
+def run() -> dict:
+ results: dict = {"label": LABEL, "base": BASE}
+ with sync_playwright() as p:
+ browser = p.chromium.launch(
+ headless = os.environ.get("SMOKE_HEADLESS", "1") == "1",
+ args = chromium_launch_args(),
+ )
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ context.add_init_script(PUMP_INIT)
+ context.add_init_script(
+ "localStorage.setItem('unsloth_auth_token', 'chat-autoscroll-smoke');"
+ )
+ context.route(
+ re.compile(rf"^{re.escape(BASE)}/api/"),
+ lambda route: route.fulfill(status = 200, content_type = "application/json", body = "{}"),
+ )
+ page = context.new_page()
+ page.goto(f"{BASE}/smoke-autoscroll.html", wait_until = "domcontentloaded")
+ page.wait_for_function("() => Boolean(window.__autoscroll)", timeout = 30_000)
+ cdp = context.new_cdp_session(page)
+ cdp.send("Performance.enable")
+
+ page.evaluate("window.__autoscroll.seed(40)")
+ page.wait_for_timeout(800)
+ results["seeded"] = page.evaluate("window.__autoscroll.metrics()")
+
+ # 1. Streaming.
+ before = metrics(cdp)
+ page.evaluate(
+ """async ([count, gap]) => {
+ window.__longTasks.length = 0;
+ window.__rafCount = 0;
+ for (let i = 0; i < count; i += 1) {
+ window.__autoscroll.token("token " + i + " ");
+ // A finished message every 20 tokens, so childList mutations are in the mix
+ // alongside the characterData ones.
+ if (i > 0 && i % 20 === 0) window.__autoscroll.block();
+ await new Promise((r) => setTimeout(r, gap));
+ }
+ }""",
+ [TOKEN_COUNT, TOKEN_GAP_MS],
+ )
+ page.wait_for_timeout(1200)
+ after = metrics(cdp)
+ long_tasks = page.evaluate("window.__longTasks")
+ results["stream"] = {
+ "tokens": TOKEN_COUNT,
+ "wall_ms": TOKEN_COUNT * TOKEN_GAP_MS,
+ "raf_callbacks": page.evaluate("window.__rafCount"),
+ "long_tasks": len(long_tasks),
+ "worst_long_task_ms": round(max((t["duration"] for t in long_tasks), default = 0.0), 1),
+ "layout_count": delta(before, after, "LayoutCount"),
+ "recalc_style_count": delta(before, after, "RecalcStyleCount"),
+ "layout_ms": round(delta(before, after, "LayoutDuration") * 1000, 1),
+ "recalc_style_ms": round(delta(before, after, "RecalcStyleDuration") * 1000, 1),
+ "task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),
+ "pinned_after_stream": page.evaluate("window.__autoscroll.distanceFromBottom()"),
+ "is_at_bottom": page.evaluate("window.__autoscroll.isAtBottom()"),
+ }
+
+ # 2. Idle: the loop must stop.
+ page.evaluate("window.__rafCount = 0")
+ page.wait_for_timeout(2000)
+ results["idle_raf_per_2s"] = page.evaluate("window.__rafCount")
+
+ # 3. Silent growth. A token first to open a fresh follow window, then growth as an inline
+ # style, which reaches neither observer.
+ page.evaluate("window.__autoscroll.resetGrowth()")
+ page.wait_for_timeout(900)
+ settled = page.evaluate(
+ """async ([followMs]) => {
+ window.__autoscroll.token("x ");
+ // 100ms in: inside the follow window, which is where a decoding image lands.
+ await new Promise((r) => setTimeout(r, 100));
+ const start = performance.now();
+ window.__autoscroll.growSilently(240);
+ let repinnedAfterMs = null;
+ // Watch past the window's end plus a margin, so a settle check at the deadline
+ // is still counted rather than reported as a permanent failure to follow.
+ while (performance.now() - start < followMs + 600) {
+ if (window.__autoscroll.distanceFromBottom() <= 2) {
+ repinnedAfterMs = performance.now() - start;
+ break;
+ }
+ await new Promise((r) => setTimeout(r, 8));
+ }
+ return {
+ repinnedAfterMs,
+ distanceAtEnd: window.__autoscroll.distanceFromBottom(),
+ isAtBottom: window.__autoscroll.isAtBottom(),
+ };
+ }""",
+ [FOLLOW_SETTLE_MS],
+ )
+ results["silent_growth"] = settled
+
+ # 4. Intent. Scrolling up must detach and survive further streaming.
+ page.evaluate("window.__autoscroll.resetGrowth()")
+ page.evaluate("window.__autoscroll.scrollToBottom()")
+ page.wait_for_timeout(900)
+ intent = page.evaluate(
+ """async () => {
+ window.__autoscroll.scrollUpBy(400);
+ await new Promise((r) => setTimeout(r, 200));
+ const detached = !window.__autoscroll.isAtBottom();
+ const distanceAfterDetach = window.__autoscroll.distanceFromBottom();
+ for (let i = 0; i < 12; i += 1) {
+ window.__autoscroll.token("more " + i + " ");
+ await new Promise((r) => setTimeout(r, 40));
+ }
+ await new Promise((r) => setTimeout(r, 900));
+ const stillDetached = !window.__autoscroll.isAtBottom();
+ const grewWhileDetached =
+ window.__autoscroll.distanceFromBottom() > distanceAfterDetach;
+ // Scroll back to within the re-attach threshold.
+ const before = window.__autoscroll.distanceFromBottom();
+ window.__autoscroll.scrollDownBy(before);
+ await new Promise((r) => setTimeout(r, 400));
+ return {
+ detached,
+ stillDetached,
+ grewWhileDetached,
+ reattached: window.__autoscroll.isAtBottom(),
+ };
+ }"""
+ )
+ results["intent"] = intent
+
+ context.close()
+ browser.close()
+ return results
+
+
+def main() -> int:
+ results = run()
+ stream_seconds = max(0.001, results["stream"]["wall_ms"] / 1000)
+ raf_rate = results["stream"]["raf_callbacks"] / stream_seconds
+ results["stream"]["raf_per_second"] = round(raf_rate, 1)
+ out = OUT / f"{LABEL}.json"
+ out.write_text(json.dumps(results, indent = 2), encoding = "utf-8")
+ info(json.dumps(results, indent = 2))
+ info(f"wrote {out}")
+
+ failures: list[str] = []
+ if results["seeded"]["scrollHeight"] <= results["seeded"]["clientHeight"]:
+ failures.append("the seeded viewport does not overflow; nothing was measured")
+ if results["stream"]["pinned_after_stream"] > 2:
+ failures.append("the viewport did not stay pinned through the stream")
+ if not results["stream"]["is_at_bottom"]:
+ failures.append("isAtBottom went false while following")
+ # Recording the count without asserting on it was false-green: the unconditional loop ran 503
+ # callbacks over this stream and the script still exited 0.
+ if raf_rate > MAX_STREAM_RAF_PER_SECOND:
+ failures.append(
+ f"the follow loop ran at {raf_rate:.1f} rAF/s during the stream, over the "
+ f"{MAX_STREAM_RAF_PER_SECOND} rAF/s budget"
+ )
+ if results["idle_raf_per_2s"] > 8:
+ failures.append(
+ f"the loop still runs when idle ({results['idle_raf_per_2s']} frames in 2s)"
+ )
+ intent = results["intent"]
+ if not intent["detached"]:
+ failures.append("scrolling up did not detach")
+ # Without this the check above is vacuous: if the tokens streamed while detached add no
+ # height, "streaming re-pinned a detached reader" passes on a tree where following is broken
+ # in either direction. Recorded and unread was false-green; assert it.
+ if not intent["grewWhileDetached"]:
+ failures.append("the content did not grow while detached; the re-pin check proved nothing")
+ if not intent["stillDetached"]:
+ failures.append("streaming re-pinned a detached reader")
+ if not intent["reattached"]:
+ failures.append("scrolling back to the bottom did not re-attach")
+ repinned_after_ms = results["silent_growth"]["repinnedAfterMs"]
+ if repinned_after_ms is None:
+ failures.append("silent growth was never followed inside the window")
+ # The settle timer is 100ms plus the frame it schedules, measured at 115ms. Bounding it is the
+ # point: "eventually" would stay green if the re-check slowed to half a second.
+ elif repinned_after_ms > SILENT_GROWTH_REPIN_BUDGET_MS:
+ failures.append(
+ f"silent growth took {repinned_after_ms:.0f}ms to follow, over the "
+ f"{SILENT_GROWTH_REPIN_BUDGET_MS}ms budget"
+ )
+ for problem in failures:
+ info(f"FAIL {problem}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/playwright_research_freeze.py b/tests/studio/playwright_research_freeze.py
new file mode 100644
index 00000000000..b0d99ee2bc4
--- /dev/null
+++ b/tests/studio/playwright_research_freeze.py
@@ -0,0 +1,387 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Main-thread cost of a streaming deep research run (#8483).
+
+The report: on Ubuntu 26.04 under Wayland the desktop app froze on "Writing the report" and
+again while closing the research detail pane -- spinner stopped, nothing clickable, force quit.
+
+What this measures, and what it cannot: Chromium is not the WebKitGTK webview the desktop app
+embeds on Linux, and `studio/src-tauri/src/linux_webkit.rs` forces that webview onto the SHM
+software renderer on Wayland, where the frame budget is far tighter than anything measured here.
+So an absolute pass here does not prove the reporter's machine is fixed. What transfers is the
+*work*: long tasks, forced layouts and style recalcs during the stream, and whether the window
+still takes clicks afterwards. Those are the quantities the fixes move.
+
+It drives smoke-research.html, which mounts the real ResearchActivityPanel and the real
+MarkdownPreview against the real store, so nothing here is a mock of the code under test. Runs
+against a vite dev server; no backend, no auth, no GPU.
+
+Run:
+ cd studio/frontend && npx vite --port 5183 &
+ SMOKE_BASE_URL=http://127.0.0.1:5183 python tests/studio/playwright_research_freeze.py
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import chromium_launch_args # noqa: E402
+
+BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:5183")
+LABEL = os.environ.get("SMOKE_LABEL", "tree")
+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-research-freeze"))
+OUT.mkdir(parents = True, exist_ok = True)
+
+# ~12.5 events/s is what the store's 80ms coalescing window admits during synthesis; 240 of them
+# is a ~20s run, long enough for a follow loop to show and short enough to repeat.
+DELTA_COUNT = int(os.environ.get("SMOKE_DELTA_COUNT", "240"))
+DELTA_GAP_MS = int(os.environ.get("SMOKE_DELTA_GAP_MS", "80"))
+
+# The budget that makes this file a regression test rather than a report. All measured on this
+# harness: the frame pump below runs at 62 callbacks/s, and a self-chaining rAF loop (the bug's
+# shape) sits exactly on that ceiling (310 callbacks in 5s). The fixed tree spends 29/s over three
+# repeats (592, 597, 597 in a 20.4s window) because chaining is conditional. 45/s is the midpoint:
+# above the fixed cost, well below anything that re-arms every frame.
+MAX_STREAM_RAF_PER_SECOND = float(os.environ.get("SMOKE_MAX_RAF_PER_S", "45"))
+# Idle measures 0 across the same repeats: a quiet list has nothing to follow. A couple of frames
+# of slack covers a settle check landing just inside the window; more means a loop that never let
+# go, which is what left the reporter's window unresponsive.
+MAX_IDLE_RAF_PER_2S = int(os.environ.get("SMOKE_MAX_IDLE_RAF", "4"))
+
+# A real deep research run's size, with the three costliest things to render: fenced code (shiki),
+# a table, and display math (KaTeX).
+REPORT_SECTION = """
+## Section {n}
+
+British cultural exports carry {n} distinct threads, and the reception of each varies by
+audience, decade and medium. The paragraph below exists to give the renderer real prose to
+lay out, with **emphasis**, `inline code`, and a [link](https://example.invalid/{n}).
+
+| Aspect | Reception | Note |
+| --- | --- | --- |
+| Broadcasting | Mixed | Public service model |
+| Music | Positive | Export driven |
+
+```python
+def section_{n}(values):
+ return sum(value * {n} for value in values)
+```
+"""
+
+
+def info(message: str) -> None:
+ print(f"[research-freeze] {message}", flush = True)
+
+
+def build_report(sections: int) -> str:
+ body = "\n".join(REPORT_SECTION.format(n = n) for n in range(1, sections + 1))
+ return f"# Deep research report\n\n{body}\n\n$$\\sum_{{i=1}}^{{n}} x_i^2$$\n"
+
+
+LONGTASK_INIT = """
+(() => {
+ window.__longTasks = [];
+ try {
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ window.__longTasks.push({ start: entry.startTime, duration: entry.duration });
+ }
+ }).observe({ type: "longtask", buffered: true });
+ } catch (e) { /* longtask unsupported: the CDP metrics below still apply */ }
+ // A timer-driven frame pump replaces requestAnimationFrame. Chromium in a container produces
+ // only a couple of real frames a second (software rendering, offscreen), which flattens a
+ // per-frame loop into nothing and would let a runaway one pass. Pumping at a fixed 16ms makes
+ // the count a property of the code under test rather than of this machine's compositor.
+ window.__rafCount = 0;
+ let nextHandle = 1;
+ const pending = new Map();
+ window.requestAnimationFrame = (cb) => {
+ const handle = nextHandle++;
+ pending.set(
+ handle,
+ setTimeout(() => {
+ pending.delete(handle);
+ window.__rafCount += 1;
+ cb(performance.now());
+ }, 16),
+ );
+ return handle;
+ };
+ window.cancelAnimationFrame = (handle) => {
+ const timer = pending.get(handle);
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ pending.delete(handle);
+ }
+ };
+})();
+"""
+
+
+SCROLLER = '[aria-label="Research activity timeline"]'
+DISTANCE_FROM_BOTTOM = (
+ f"() => {{ const el = document.querySelector('{SCROLLER}');"
+ " return Math.round(el.scrollHeight - el.scrollTop - el.clientHeight); }"
+)
+LATEST_BUTTON_VISIBLE = (
+ "() => [...document.querySelectorAll('button')]"
+ ".some((button) => button.textContent.trim() === 'Latest')"
+)
+
+
+def metrics(cdp) -> dict[str, float]:
+ got = cdp.send("Performance.getMetrics")
+ return {m["name"]: m["value"] for m in got["metrics"]}
+
+
+def delta(before: dict[str, float], after: dict[str, float], name: str) -> float:
+ return round(after.get(name, 0.0) - before.get(name, 0.0), 4)
+
+
+def run() -> dict:
+ results: dict = {"label": LABEL, "base": BASE}
+ with sync_playwright() as p:
+ # Headed under Xvfb by default (SMOKE_HEADLESS=1 to override): with no compositor,
+ # headless Chromium throttles rAF to a few callbacks a second, flattening the per-frame
+ # loop this file exists to measure.
+ headless = os.environ.get("SMOKE_HEADLESS", "0") == "1"
+ browser = p.chromium.launch(headless = headless, args = chromium_launch_args())
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ # Deliberately NOT installing the view-transition killer: it forces
+ # `body { pointer-events: auto !important }`, which is precisely the symptom under test.
+ context.add_init_script(LONGTASK_INIT)
+ # A token, and a 200 for every backend call: without them the auth guard sees a 401 and
+ # navigates to /login, throwing the harness away mid-run. The pattern is anchored on the
+ # origin so it cannot swallow vite's own module URLs under src/.../api/.
+ context.add_init_script(
+ "localStorage.setItem('unsloth_auth_token', 'research-freeze-smoke');"
+ )
+ context.route(
+ re.compile(rf"^{re.escape(BASE)}/api/"),
+ lambda route: route.fulfill(status = 200, content_type = "application/json", body = "{}"),
+ )
+ page = context.new_page()
+ page.goto(f"{BASE}/smoke-research.html", wait_until = "domcontentloaded")
+ page.wait_for_function("() => Boolean(window.__research)", timeout = 30_000)
+ cdp = context.new_cdp_session(page)
+ cdp.send("Performance.enable")
+
+ page.evaluate("window.__research.seed()")
+ page.wait_for_timeout(500)
+
+ # 1. The streaming phase.
+ before = metrics(cdp)
+ page.evaluate(
+ """async ([count, gap]) => {
+ window.__longTasks.length = 0;
+ window.__rafCount = 0;
+ for (let i = 0; i < count; i += 1) {
+ window.__research.delta("token " + i + " ");
+ if (i % 4 === 0) window.__research.reportDelta(i * 32);
+ // A new step every 8 deltas, so the list grows the way a real run's does
+ // rather than mutating one row in place.
+ if (i % 8 === 0) window.__research.step(i / 8);
+ await new Promise((r) => setTimeout(r, gap));
+ }
+ }""",
+ [DELTA_COUNT, DELTA_GAP_MS],
+ )
+ # The tail is part of the measurement: re-arming after the last event is the failure mode,
+ # so count those frames rather than stopping the clock.
+ page.wait_for_timeout(1200)
+ stream_window_ms = DELTA_COUNT * DELTA_GAP_MS + 1200
+ stream_raf = page.evaluate("window.__rafCount")
+ after = metrics(cdp)
+ long_tasks = page.evaluate("window.__longTasks")
+ results["stream"] = {
+ "events": DELTA_COUNT,
+ "wall_ms": stream_window_ms,
+ "raf_callbacks": stream_raf,
+ "raf_per_second": round(stream_raf / (stream_window_ms / 1000), 1),
+ "long_tasks": len(long_tasks),
+ "worst_long_task_ms": round(max((t["duration"] for t in long_tasks), default = 0.0), 1),
+ "layout_count": delta(before, after, "LayoutCount"),
+ "recalc_style_count": delta(before, after, "RecalcStyleCount"),
+ "layout_ms": round(delta(before, after, "LayoutDuration") * 1000, 1),
+ "recalc_style_ms": round(delta(before, after, "RecalcStyleDuration") * 1000, 1),
+ "task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),
+ "activities": page.evaluate("window.__research.state().activities"),
+ }
+
+ # 2. Idle after the stream: the follow loop must stop when the list goes quiet.
+ page.evaluate("window.__rafCount = 0")
+ page.wait_for_timeout(2000)
+ results["idle_raf_callbacks_per_2s"] = page.evaluate("window.__rafCount")
+
+ # 3. Publishing the finished report -- the commit the freeze was reported on.
+ report = build_report(int(os.environ.get("SMOKE_REPORT_SECTIONS", "40")))
+ before = metrics(cdp)
+ page.evaluate("window.__longTasks.length = 0")
+ page.evaluate("md => window.__research.publishReport(md)", report)
+ # A click during the parse: if the main thread is blocked this lands late but must land.
+ page.click('[data-smoke="click-probe"]')
+ page.wait_for_timeout(3000)
+ after = metrics(cdp)
+ long_tasks = page.evaluate("window.__longTasks")
+ results["report"] = {
+ "chars": len(report),
+ "long_tasks": len(long_tasks),
+ "worst_long_task_ms": round(max((t["duration"] for t in long_tasks), default = 0.0), 1),
+ "task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),
+ "clicks_registered": page.evaluate("window.__research.clicks()"),
+ "rendered": page.evaluate(
+ "() => Boolean(document.querySelector('[data-smoke=\\\"report\\\"] h1'))"
+ ),
+ }
+
+ # 4. Modal lifecycle: approval unmounts PlanReview's Dialog while open, and closing the
+ # pane unmounts the panel under it. Either one stranding `body { pointer-events: none }`
+ # leaves the whole window unclickable.
+ page.evaluate("window.__research.clearReport()")
+ page.evaluate("window.__research.awaitApproval()")
+ page.wait_for_timeout(600)
+ dialog_open = page.evaluate(
+ "() => Boolean(document.querySelector('[role=\\\"dialog\\\"]'))"
+ )
+ body_during = page.evaluate("() => document.body.style.pointerEvents")
+ page.evaluate("window.__research.approve()")
+ page.wait_for_timeout(600)
+ body_after_approve = page.evaluate("() => document.body.style.pointerEvents")
+ clicks_before = page.evaluate("window.__research.clicks()")
+ page.click('[data-smoke="click-probe"]', timeout = 5000)
+ clicks_after_approve = page.evaluate("window.__research.clicks()")
+
+ page.evaluate("window.__research.awaitApproval()")
+ page.wait_for_timeout(600)
+ page.evaluate("window.__research.closePanel()")
+ page.wait_for_timeout(600)
+ body_after_close = page.evaluate("() => document.body.style.pointerEvents")
+ page.click('[data-smoke="click-probe"]', timeout = 5000)
+ clicks_after_close = page.evaluate("window.__research.clicks()")
+
+ results["modal"] = {
+ "dialog_opened": dialog_open,
+ "body_pointer_events_while_open": body_during,
+ "body_pointer_events_after_approve": body_after_approve,
+ "body_pointer_events_after_close": body_after_close,
+ "click_after_approve": clicks_after_approve > clicks_before,
+ "click_after_close": clicks_after_close > clicks_after_approve,
+ }
+
+ # 5. Detaching from the bottom. The follow loop must keep the view pinned while the list
+ # grows and let go the moment the reader scrolls up, including a flick shorter than the
+ # bottom threshold: a still-pending follow step used to run anyway and reconcile
+ # isAtBottom back to true, so "Latest" never appeared and nothing corrected it.
+ page.evaluate("window.__research.openPanel()")
+ page.wait_for_timeout(300)
+ page.evaluate("() => { for (let i = 100; i < 130; i += 1) window.__research.step(i); }")
+ page.wait_for_timeout(1500)
+ overflowing = page.evaluate(
+ f"() => {{ const el = document.querySelector('{SCROLLER}'); return el.scrollHeight > el.clientHeight; }}"
+ )
+ followed_distance = page.evaluate(DISTANCE_FROM_BOTTOM)
+ latest_while_following = page.evaluate(LATEST_BUTTON_VISIBLE)
+ # A mutation, one macrotask so the observer has queued its follow step, then a small
+ # upward flick while that step is still pending.
+ page.evaluate(
+ f"""async () => {{
+ const el = document.querySelector('{SCROLLER}');
+ el.firstElementChild.setAttribute("aria-hidden", "false");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ el.dispatchEvent(new WheelEvent("wheel", {{ deltaY: -40, bubbles: true }}));
+ el.scrollTop = el.scrollHeight - el.clientHeight - 8;
+ el.dispatchEvent(new Event("scroll"));
+ }}"""
+ )
+ page.wait_for_timeout(600)
+ results["detach"] = {
+ "overflowing": overflowing,
+ "distance_while_following": followed_distance,
+ "latest_while_following": latest_while_following,
+ "distance_after_flick": page.evaluate(DISTANCE_FROM_BOTTOM),
+ "latest_after_flick": page.evaluate(LATEST_BUTTON_VISIBLE),
+ }
+
+ page.screenshot(path = str(OUT / f"{LABEL}.png"), full_page = False)
+ context.close()
+ browser.close()
+ return results
+
+
+def main() -> int:
+ results = run()
+ out = OUT / f"{LABEL}.json"
+ out.write_text(json.dumps(results, indent = 2), encoding = "utf-8")
+ info(json.dumps(results, indent = 2))
+ info(f"wrote {out}")
+
+ failures: list[str] = []
+ stream = results["stream"]
+ # A list that ingested nothing has nothing to follow, so it measures zero frames and clears
+ # both budgets below. Recorded and unread was false-green; assert it.
+ if stream["activities"] < 1:
+ failures.append(
+ "the run ingested no activities; the frame budgets below measured an empty list"
+ )
+ # Without these two the file records the per-frame cost and passes regardless, which is how
+ # the original loop shipped: the numbers were there, nothing read them.
+ if stream["raf_per_second"] > MAX_STREAM_RAF_PER_SECOND:
+ failures.append(
+ f"{stream['raf_per_second']} rAF/s during the stream, budget "
+ f"{MAX_STREAM_RAF_PER_SECOND} (a per-frame loop is running)"
+ )
+ if results["idle_raf_callbacks_per_2s"] > MAX_IDLE_RAF_PER_2S:
+ failures.append(
+ f"{results['idle_raf_callbacks_per_2s']} rAF in 2s with the list idle, budget "
+ f"{MAX_IDLE_RAF_PER_2S} (the follow loop never let go)"
+ )
+ modal = results["modal"]
+ if not modal["dialog_opened"]:
+ failures.append("plan review dialog never opened; the modal checks proved nothing")
+ # A dialog that never took the layer strands nothing, so every check below passes on a tree
+ # where the teardown is broken. Verified: with `modal={false}` on PlanReview's Dialog this
+ # reads "" and the whole phase went green. Recorded and unread was false-green; assert it.
+ if modal["body_pointer_events_while_open"] != "none":
+ failures.append(
+ "the plan review dialog never took the modal layer "
+ f"(body pointer-events was {modal['body_pointer_events_while_open']!r}, "
+ "expected 'none'); the stranding checks proved nothing"
+ )
+ if modal["body_pointer_events_after_approve"] == "none":
+ failures.append("body pointer-events stranded at none after approve")
+ if modal["body_pointer_events_after_close"] == "none":
+ failures.append("body pointer-events stranded at none after closing the pane")
+ if not modal["click_after_approve"] or not modal["click_after_close"]:
+ failures.append("a click did not reach its handler after a modal path")
+ if not results["report"]["rendered"]:
+ failures.append("the report never rendered")
+ # The modal checks below compare click counts against a baseline, so they still pass if this
+ # one was swallowed. Responsiveness during the report parse is the reported symptom; assert it.
+ if results["report"]["clicks_registered"] < 1:
+ failures.append("the click during the report parse never reached its handler")
+ detach = results["detach"]
+ if not detach["overflowing"]:
+ failures.append("the activity list never overflowed; the detach checks proved nothing")
+ if detach["distance_while_following"] > 2:
+ failures.append(
+ f"the view was {detach['distance_while_following']}px off the bottom while following"
+ )
+ if detach["latest_while_following"]:
+ failures.append("'Latest' was offered while the view was still following")
+ if not detach["latest_after_flick"]:
+ failures.append("'Latest' did not appear after a flick shorter than the bottom threshold")
+ for problem in failures:
+ info(f"FAIL {problem}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.py
new file mode 100644
index 00000000000..3120e1243c8
--- /dev/null
+++ b/tests/studio/test_autoscroll_harness_contract.py
@@ -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
+
+"""The two #8483 harnesses must read every guard they record.
+
+Both files measure in a browser and then decide pass/fail in `main()`. A metric that is recorded
+but never compared is how a harness goes false-green: it keeps reporting the number that would
+have caught the regression while exiting 0. Three shipped that way already (an unasserted rAF
+budget, an unasserted click count, and the two guards below), so the rule is pinned here rather
+than left to review.
+"""
+
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+STUDIO_TESTS = ROOT / "tests" / "studio"
+
+
+def source(name: str) -> str:
+ return (STUDIO_TESTS / name).read_text(encoding = "utf-8")
+
+
+def verdict(name: str) -> str:
+ """Everything from `def main()` on: the only place a metric turns into an exit code."""
+ text = source(name)
+ start = text.index("def main()")
+ return text[start:]
+
+
+def test_chat_autoscroll_asserts_the_detached_stream_actually_grew() -> None:
+ # `stillDetached` says streaming did not re-pin the reader. It says nothing at all if the
+ # streamed tokens added no height, which the harness measures as `grewWhileDetached`.
+ main = verdict("playwright_chat_autoscroll.py")
+ assert 'intent["stillDetached"]' in main
+ assert 'intent["grewWhileDetached"]' in main
+
+
+def test_research_freeze_asserts_the_dialog_took_the_modal_layer() -> None:
+ # The stranded-`pointer-events: none` checks are the reported symptom (an unclickable
+ # window). They only test anything if the dialog put the body on the modal layer first.
+ main = verdict("playwright_research_freeze.py")
+ assert 'modal["body_pointer_events_after_approve"]' in main
+ assert 'modal["body_pointer_events_while_open"]' in main
+
+
+def test_research_freeze_asserts_the_stream_had_something_to_follow() -> None:
+ # An empty activity list runs no follow loop, so it clears the frame budgets by measuring
+ # nothing.
+ main = verdict("playwright_research_freeze.py")
+ assert 'stream["raf_per_second"]' in main
+ assert 'stream["activities"]' in main