Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: paint a long thread's newest messages immediately instead of rebuilding all of them first (#9058)
Daniel Hanfdeefc50e2a5
diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsxnew file mode 100644index 00000000000..d255b84c55a--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx@@ -0,0 +1,581 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// React glue for the widen-only mount window. The state machine, and why this is not a virtualizer,+// are in progressive-mount-controller.ts.+//+// This replaces `<ThreadPrimitive.Messages>{renderThreadMessage}</ThreadPrimitive.Messages>` with+// an equivalent map over a bounded index range: upstream renders `MessageByIndexProvider ->+// RenderChildrenWithAccessor -> children({ message })`, this renders `MessageByIndexProvider ->+// children`, dropping an accessor wrapper the thread's slot does not use and that emits no DOM.+//+// The replacement is permanent, not a mode the thread leaves once the window closes: swapping trees+// would change the element type at that position, so React would unmount and rebuild every message+// on the convergence commit, which is the cost being avoided.+//+// It takes the SAME propless slot #9042 gave `ThreadPrimitive.Messages`, for the same reason.+// `renderMessage()` returns one shared element object, so a commit that changes the row count hands+// React an identical element for every pre-existing row and React skips those subtrees. A+// `components` object would allocate fresh props per row per commit, so every delete would+// re-render every body, action bar and tooltip: the regression #9042 removed.++import {+ MessageByIndexProvider,+ useAui,+ useAuiState,+} from "@assistant-ui/react";+import {+ type FC,+ type ReactElement,+ type RefObject,+ memo,+ startTransition,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";++import {+ type AnchorSample,+ type MountWindow,+ anchorCorrection,+ initialWindow,+ widen,+} from "@/components/assistant-ui/progressive-mount-controller";+import {+ type ThreadMessageRole,+ rendersAsRow,+} from "@/components/assistant-ui/thread-message-slot";+import { useAdjustForContentInsertedAbove } from "@/components/assistant-ui/use-intent-aware-autoscroll";++/**+ * Every mount window currently withholding rows. Module-level rather than context: the consumers are+ * imperative DOM readers (screenshot capture, the #9016 harness census) not necessarily in the React+ * tree, and a thread can be mounted twice at once (the Compare panes).+ */+const activeCompleters = new Set<() => Promise<void>>();++/**+ * Force every in-flight progressive mount to completion, resolving once the commit has painted.+ *+ * Anything reading the thread out of the DOM rather than the runtime store must await this, or a+ * read during the few frames a long thread takes to converge silently sees a short conversation.+ * Store readers need nothing: the window gated rendering, never the store.+ */+export const PROGRESSIVE_MOUNT_SEARCH_MS = 400;++export async function completeProgressiveMounts(): Promise<void> {+ // Two waits, failing in opposite directions.+ //+ // Draining is easy: ask every completer that exists to finish. Reading the set ONCE is not enough,+ // since completers register from a layout effect and a caller in the same task as the thread+ // opening finds it empty (measured: returned in 0.1ms, 16 of 220 rows two frames later).+ //+ // The hard half is that "empty" is ambiguous: a settled thread and a thread still loading history+ // (about 160ms on a cold open) look alike, so returning at the first empty reading resolves before+ // any row exists. An empty set is therefore only believed after SEARCH_MS of looking; a set that+ // was non-empty and has drained is believed immediately.+ //+ // So a caller on a settled thread pays SEARCH_MS, the deliberate direction to be wrong in: the+ // alternative is a screenshot or export of a conversation that is not there yet.+ const deadline = Date.now() + PROGRESSIVE_MOUNT_SEARCH_MS;+ let observed = false;+ for (;;) {+ if (activeCompleters.size > 0) {+ observed = true;+ await Promise.all([...activeCompleters].map((complete) => complete()));+ }+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ if (activeCompleters.size === 0 && (observed || Date.now() >= deadline)) {+ return;+ }+ }+}++/** True while any thread is still widening. Exposed for tests and diagnostics. */+export function hasPendingProgressiveMounts(): boolean {+ return activeCompleters.size > 0;+}++/**+ * Hand native scroll anchoring back, leaving no trace of having taken it.+ *+ * `removeProperty` empties the inline declaration but keeps the attribute, so the settled viewport+ * carried `style=""` where the shipping one carries no `style` at all. That is inert, but it was the+ * ONLY difference a whole-document structural digest could find between this branch and its merge+ * base at 100K and 300K (45,014 lines, one changed line, on a null scoring exactly zero), and a+ * byte-identical converged document is a claim worth being able to make rather than footnote.+ *+ * Only an empty declaration is cleared, so any other inline style a caller has set survives.+ */+function restoreScrollAnchoring(viewport: HTMLElement | null): void {+ if (!viewport) return;+ viewport.style.removeProperty("overflow-anchor");+ if (viewport.getAttribute("style") === "") viewport.removeAttribute("style");+}++/**+ * The row to hold still: the first one the reader can actually SEE, not the first in the list.+ *+ * Widening prepends above everything, so for a widening any row will do. A RELAYOUT will not: a row+ * growing between the topmost row and the fold moves the reader while leaving the topmost row where+ * it was. Measured with a 600px height change injected into one row above a detached reader with the+ * window open: 600px of movement, reported as 0 by a topmost-row anchor.+ */+function pickAnchorRow(viewport: HTMLElement): Element | null {+ const fold = viewport.getBoundingClientRect().top;+ const rows = viewport.querySelectorAll("[data-role]");+ let anchor: Element | null = rows.item(rows.length - 1);+ for (const row of rows) {+ if (row.getBoundingClientRect().bottom > fold) {+ anchor = row;+ break;+ }+ }+ if (!anchor) return null;+ // Then descend to the fold. A row can be taller than the viewport (a long answer with images and+ // code usually is), so a reader partway through one has the row's top ABOVE them: a block earlier+ // in that message growing moves everything they see while the row's top stays put, and a whole-row+ // anchor reports zero. The first descendant reaching the fold does not. Bounded because that block+ // is a few levels down, and this runs once per re-pick, not per frame.+ //+ // Known residual: if the fold lands inside a tall LEAF block (a paragraph with no element+ // children) the descent stops with its top above the reader, so lines reflowing inside it move+ // what they see without moving the block. Closing that needs a caret point at the fold, spelled+ // differently on all three engines, costing a Range and a rect every frame, and not itself stable+ // across the reflow it would measure.+ 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) {+ if (child.getBoundingClientRect().bottom > fold) {+ next = child;+ break;+ }+ }+ if (!next) break;+ anchor = next;+ }+ return anchor;+}++function sampleAnchor(viewport: HTMLElement, element: Element): AnchorSample {+ return {+ viewportOffset:+ element.getBoundingClientRect().top -+ viewport.getBoundingClientRect().top,+ scrollTop: viewport.scrollTop,+ maxScrollTop: viewport.scrollHeight - viewport.clientHeight,+ };+}++/**+ * An anchor plus the row it sits in, sampled together. The row is the fallback: pickAnchorRow+ * descends to the fold, so the anchor is often the `<pre>` Streamdown replaces when Shiki finishes,+ * and a replaced node takes its baseline with it. A `[data-role]` row is never replaced in place.+ *+ * Being an ANCESTOR, the row does not move when the replacement changes height inside it, so that+ * height change goes uncorrected. That is the better of the two available errors: an anchor BELOW+ * the replaced block would also see it grow DOWNWARD past the fold, which moves nothing the reader+ * sees, trading an error in a rare case for one in the common case. Either way the residual is one+ * code block's height change, for a detached reader, while a window is open.+ */+function holdAnchor(viewport: HTMLElement, element: Element): HeldAnchor {+ const row = element.closest("[data-role]");+ return {+ element,+ sample: sampleAnchor(viewport, element),+ row,+ rowSample: row ? sampleAnchor(viewport, row) : null,+ };+}++type HeldAnchor = {+ element: Element;+ sample: AnchorSample;+ row: Element | null;+ rowSample: AnchorSample | null;+};++/** True while `element` still covers some of what the reader can see. */+function isAnchorVisible(viewport: HTMLElement, element: Element): boolean {+ const box = element.getBoundingClientRect();+ const fold = viewport.getBoundingClientRect().top;+ return box.bottom > fold && box.top < fold + viewport.clientHeight;+}++function useProgressiveMountWindow(+ count: number,+ resetKey: string | undefined,+ viewportRef: RefObject<HTMLElement | null>,+): MountWindow {+ const aui = useAui();+ const adjustForContentInsertedAbove = useAdjustForContentInsertedAbove();++ // Imperative rather than useAuiState: a reactive subscription would re-render this component,+ // and so rebuild the whole row array, on every run start and stop.+ const isRunningNow = useCallback(+ () => aui.thread().getState().isRunning === true,+ [aui],+ );++ // Which indices actually paint, read IMPERATIVELY off the store for the same reason isRunning is:+ // a `useAuiState` selector touching the messages array runs on every store write, and the+ // composer is controlled off store state, so that would walk the thread once per keystroke and+ // once per streamed token. This is called only where a window is armed -- mount, thread switch,+ // and the commit that first brings messages in -- so it costs one snapshot each time, not one+ // per render. See thread-research-presence.ts for the same hazard.+ const renderableAt = useCallback(() => {+ const messages = aui.thread().getState().messages as ReadonlyArray<{+ role?: ThreadMessageRole;+ composer?: { isEditing?: boolean };+ }>;+ return (index: number) => {+ const message = messages[index];+ // A shape this cannot read counts as renderable, which degrades to the count-based window+ // that shipped before. The opposite default would silently stop windowing altogether.+ if (message?.role == null) return true;+ return rendersAsRow(message.role, message.composer?.isEditing === true);+ };+ }, [aui]);++ const [mountWindow, setMountWindow] = useState<MountWindow>(() =>+ initialWindow(count, isRunningNow(), renderableAt()),+ );++ // Re-arm per thread, adjusting state during render as React documents, so the previous thread's+ // window can never gate the new one for a frame.+ //+ // UNEXERCISED today: `<GeneratedImageOverlayProvider key={runtimeThreadId}>` in thread.tsx wraps+ // this subtree, so a thread switch rebuilds this component and the useState initialiser above+ // re-arms instead (measured across in-app switches: zero arm records from this branch). Kept+ // because it is what makes this component correct on its own terms; remove that ancestor key and+ // it is the only thing between a thread switch and the previous window gating the next thread.+ const [previousKey, setPreviousKey] = useState(resetKey);+ if (previousKey !== resetKey) {+ setPreviousKey(resetKey);+ setMountWindow(initialWindow(count, isRunningNow(), renderableAt()));+ }++ // The commit that puts the FIRST rows into an empty tree.+ //+ // Mounting is not when the app learns the thread length. `threadListItem.id` flips as soon as+ // switchToThread resolves and that remounts this subtree, but the messages arrive only when the+ // history adapter settles, a Dexie read plus two HTTP calls later. So on a cold open the useState+ // above runs at `count === 0` and declines, and without this the whole thread lands in one+ // unbounded commit: the stall this file exists to remove. Measured opening a 220-message thread:+ // mount at count 0, count 220 about 160ms later, same resetKey, first paint carrying all 220.+ //+ // Gated on the PREVIOUS count being zero rather than on crossing MIN_PROGRESSIVE_MESSAGES: a tree+ // that never rendered a row has no scroll position to lose, so arming here cannot move a reader.+ // Appending a 40th message to a 39-message thread crosses the threshold too, and would window a+ // conversation the reader is in the middle of.+ const [previousCount, setPreviousCount] = useState(count);+ if (previousCount !== count) {+ setPreviousCount(count);+ // Same call as the mount path, so a run in flight suppresses the window here too.+ if (previousCount === 0 && count > 0) {+ setMountWindow(initialWindow(count, isRunningNow(), renderableAt()));+ }+ }++ // A thread that shrank at or past the live window's start is reconciled HERE, during render, not+ // at the next widening. Rendering every row (below) is only half: the STATE still says start 204,+ // and a widen against a 100-message thread would produce start 68 and unmount the 68 rows this+ // render just mounted. Before this existed the stale state painted an empty column for 2 to 8+ // frames.+ if (mountWindow != null && mountWindow.start >= count) {+ setMountWindow(null);+ }++ // A run starting mid-widening drops the window immediately: streaming writes the same scroll+ // position widening does, and a reply must never commit into a tree that has not reached it. The+ // remaining rows land in one commit, which is what happened before this change anyway.+ const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);+ useEffect(() => {+ if (threadIsRunning && mountWindow != null) setMountWindow(null);+ }, [threadIsRunning, mountWindow]);++ // The row held still across a widening commit, plus the scroll state it was held against, both+ // captured against the SCROLL CONTAINER rather than the window (see AnchorSample).+ // anchorCorrection turns the pair into a scrollTop delta in document space, assuming nothing else+ // moved scrollTop, which is what disarming native anchoring below is for.+ const anchorRef = useRef<+ | ({+ element: Element;+ row: Element | null;+ rowSample: AnchorSample | null;+ } & AnchorSample)+ | null+ >(null);+ /** The row the idle sampler below holds still, and where it last saw it. */+ const idleRef = useRef<HeldAnchor | null>(null);++ const captureAnchor = useCallback(() => {+ const viewport = viewportRef.current;+ // Disarm native scroll anchoring HERE, immediately before the capture it would invalidate. The+ // correction is document space and only holds while nothing else moves scrollTop, so the+ // browser must be out of the loop before the first sample, not merely soon.+ //+ // A layout effect is too early: this component is a DESCENDANT of the viewport, so on the+ // mounting commit React runs this subtree's layout effects before the viewport's ref callback,+ // `viewportRef.current` is null and the style is silently skipped. Measured on that version,+ // computed `overflow-anchor` stayed `auto` until the FIRST widening at +803ms, so that widening+ // applied the document-space correction on top of the browser's: a reader who scrolled 4000px+ // was left 776px short. This callback runs from a requestAnimationFrame, after a paint, so the+ // ref is populated.+ if (viewport) viewport.style.setProperty("overflow-anchor", "none");+ const anchor = viewport ? pickAnchorRow(viewport) : null;+ // The enclosing row is a fallback: the anchor is often the `<pre>` Streamdown replaces when+ // Shiki finishes. Without a fallback the correction is dropped, and with anchoring off a whole+ // chunk of prepended rows moves the reader permanently. A row is never replaced in place.+ const row = anchor?.closest("[data-role]") ?? null;+ anchorRef.current =+ viewport && anchor+ ? {+ element: anchor,+ ...sampleAnchor(viewport, anchor),+ row,+ rowSample: row ? sampleAnchor(viewport, row) : null,+ }+ : null;+ }, [viewportRef]);++ useEffect(() => {+ if (mountWindow == null) return;+ const frame = requestAnimationFrame(() => {+ // Re-check: a run can start between the commit and this frame.+ if (isRunningNow()) {+ setMountWindow(null);+ return;+ }+ captureAnchor();+ startTransition(() => {+ setMountWindow((current) => widen(current, count));+ });+ });+ return () => cancelAnimationFrame(frame);+ }, [mountWindow, count, captureAnchor, isRunningNow]);++ // mountWindow is the TRIGGER, not a value the body reads, which is why the rule cannot see it:+ // this effect must run in the commit that widened the window, before it paints.+ // biome-ignore lint/correctness/useExhaustiveDependencies: mountWindow is a trigger, see above+ useLayoutEffect(() => {+ const captured = anchorRef.current;+ anchorRef.current = null;+ const viewport = viewportRef.current;+ if (!captured || !viewport) return;+ // The anchor, or its row if the anchor has been replaced since the capture.+ 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));+ // Called on EVERY widening commit, including no-op ones: a zero correction still resyncs the+ // hook's scroll bookkeeping, or the scroll event native anchoring fires arrives as a downward+ // scroll the reader did not make. See adjustForContentInsertedAbove.+ adjustForContentInsertedAbove(shift ?? 0);+ // Hand the idle sampler a POST-correction baseline rather than nulling it. Nulling made the next+ // frame re-pick and re-base, so a block landing in between was folded into the new baseline and+ // never corrected: with anchoring off the reader kept the displacement.+ idleRef.current = holdAnchor(viewport, element);+ }, [mountWindow, adjustForContentInsertedAbove, viewportRef]);++ // Content above the reader also moves for reasons that are not a widening, and nothing else+ // watches for it while the window is open: Streamdown replaces a `<pre>` when Shiki finishes,+ // KaTeX resizes a formula, an image lands. Native anchoring absorbs those and is disabled for the+ // duration, so compensation has to cover the whole interval, not just widening commits. The+ // autoscroll hook's mutation path pins a FOLLOWING reader and leaves a detached one alone.+ //+ // Measured when written, injecting a 600px height change into one row above a detached reader with+ // the window open: without this the reader moved the full 600px, against 0px on the merge base.+ //+ // RE-MEASURED SINCE, AND IT NO LONGER REPRODUCES ITS OWN MEASUREMENT: ablating this whole effect+ // leaves grow 600, grow 3600 and shrink 1200 identical to head within noise. The cause is+ // declaration ORDER, not the logic: the widening capture effect above registers its rAF first, so+ // `anchorRef.current` is non-null on every frame the window is open and this body returns at its+ // first line. Instrumented, 0 of 1110 frames across chromium, firefox and webkit got past it, and+ // the widening layout effect absorbs the reflow instead. Confirmed causally by swapping only the+ // two effect declarations, after which this body runs about 5 times per repetition. Anyone+ // reordering these two effects is switching this on.+ //+ // Kept because the widening path it defers to has no visibility test, so this is the only thing+ // that would catch a reflow on a frame with no widening pending. The anchor is the first row the+ // reader can SEE, re-picked only when gone or scrolled out of view, so per frame this costs one+ // rect and one scrollTop read.+ useEffect(() => {+ if (mountWindow == null) {+ idleRef.current = null;+ return;+ }+ let frame = 0;+ const tick = () => {+ frame = requestAnimationFrame(tick);+ const viewport = viewportRef.current;+ // A pending widening capture owns the correction until its layout effect runs; stepping in+ // between would correct the same movement twice.+ if (!viewport || anchorRef.current) return;+ const held = idleRef.current;+ if (!held) {+ const element = pickAnchorRow(viewport);+ idleRef.current = element ? holdAnchor(viewport, element) : null;+ return;+ }+ // The anchor, or its row if replaced since the last frame. Re-picking instead would discard+ // the only pre-replacement sample and re-base AFTER the replacement's own reflow.+ const [element, baseline] = held.element.isConnected+ ? [held.element, held.sample]+ : held.row?.isConnected && held.rowSample+ ? [held.row, held.rowSample]+ : [null, null];+ if (!element || !baseline) {+ const replacement = pickAnchorRow(viewport);+ idleRef.current = replacement+ ? holdAnchor(viewport, replacement)+ : null;+ return;+ }+ // Scrolled past: hold something the reader can see instead. Tested by the row's box, not its+ // top offset, since a tall row just off screen can still have its top within a viewport of the+ // fold, and a reflow between it and the first visible row moves the reader while it stays put.+ if (!isAnchorVisible(viewport, element)) {+ // Re-pick in THIS frame rather than nulling and waiting: a baseline-free frame folds a+ // reflow above the newly visible content into the next baseline.+ const replacement = pickAnchorRow(viewport);+ idleRef.current = replacement+ ? holdAnchor(viewport, replacement)+ : null;+ return;+ }+ const shift = anchorCorrection(baseline, sampleAnchor(viewport, element));+ if (shift !== null) adjustForContentInsertedAbove(shift);+ // Re-based EVERY frame, no-ops included. Returning early on a no-op left the baseline's+ // scrollTop stale, and anchorCorrection's clamp term reads it, so a later shrink near the+ // bottom would subtract the wrong amount.+ idleRef.current = holdAnchor(viewport, element);+ };+ frame = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(frame);+ }, [mountWindow, adjustForContentInsertedAbove, viewportRef]);++ // Native scroll anchoring goes back on the moment the window closes, and on unmount, so a settled+ // thread is exactly the thread that shipped before this change. Turning it OFF happens at capture+ // time instead, for the ordering reason in captureAnchor.+ //+ // Why it must be off: left on, the browser moves scrollTop by the inserted height on some frames+ // and not others (never on any shipping Safari, and suppressed per frame elsewhere after a+ // programmatic scroll), and no in-frame measurement can tell which kind of frame it is in. Off,+ // scrollTop moves only when the reader or this code moves it, which anchorCorrection assumes.+ useLayoutEffect(() => {+ if (mountWindow != null) return;+ restoreScrollAnchoring(viewportRef.current);+ }, [mountWindow, viewportRef]);++ // biome-ignore lint/correctness/useExhaustiveDependencies: unmount-only cleanup+ useLayoutEffect(() => {+ const viewport = viewportRef.current;+ return () => {+ restoreScrollAnchoring(viewport);+ };+ }, [viewportRef]);++ // Registered only while rows are actually withheld, so completeProgressiveMounts is free on the+ // settled thread that is the common case. A layout effect runs one phase earlier, narrowing (not+ // closing) the window in which a caller sees an empty completer set while rows are withheld.+ const isWithholding = mountWindow != null;+ const completionWaiters = useRef<Array<() => void>>([]);+ useLayoutEffect(() => {+ if (!isWithholding) return;+ const complete = () =>+ new Promise<void>((resolve) => {+ completionWaiters.current.push(resolve);+ setMountWindow(null);+ });+ activeCompleters.add(complete);+ return () => {+ activeCompleters.delete(complete);+ };+ }, [isWithholding]);++ // Resolve on the commit that actually dropped the window, then after a paint. A bare two-frame+ // timer started at the call raced the commit it had just asked for: measured, it resolved with 16+ // of 220 rows still in the document on 4 of 5 WebKit and 2 of 5 Firefox runs.+ const flushCompletionWaiters = useCallback(() => {+ const waiters = completionWaiters.current;+ completionWaiters.current = [];+ for (const resolve of waiters) resolve();+ }, []);++ useEffect(() => {+ if (mountWindow != null || completionWaiters.current.length === 0) return;+ // The ref is emptied only when the frame fires, so a cancelled frame leaves the waiters for the+ // next commit or the unmount below rather than dropping them.+ const frame = requestAnimationFrame(() =>+ requestAnimationFrame(flushCompletionWaiters),+ );+ return () => cancelAnimationFrame(frame);+ }, [mountWindow, flushCompletionWaiters]);++ // A thread that goes away settles anything still waiting on it. Without this a DOM capture racing+ // a thread switch waited forever: the cleanup above removes the completer, but the promise it+ // already handed out is only resolved by the effect above, which no longer runs.+ useEffect(() => flushCompletionWaiters, [flushCompletionWaiters]);++ return mountWindow;+}++/**+ * The thread's message list. Drop-in for `ThreadPrimitive.Messages`, with a long thread's first+ * commit bounded to the tail and the rest arriving over the following frames. Memoized on component+ * identity exactly as upstream is, so a `Thread` re-render does not rebuild the row array.+ */+export const ProgressiveMessages: FC<{+ /** The thread's propless message slot. See thread-message-slot.ts. */+ renderMessage: () => ReactElement;+ /** Changing this re-arms the window. The runtime thread id. */+ resetKey: string | undefined;+ /** The scroll viewport these rows live in. Identity is stable, so it is not compared below. */+ viewportRef: RefObject<HTMLElement | null>;+}> = memo(+ ({ renderMessage, resetKey, viewportRef }) => {+ const count = useAuiState(({ thread }) => thread.messages.length);+ const mountWindow = useProgressiveMountWindow(count, resetKey, viewportRef);++ return useMemo(() => {+ if (count === 0) return null;+ // `start >= count` means the thread shrank under a live window (a bulk delete, or a switch to+ // a shorter thread), and clamping `start` to `count` would make this loop emit NOTHING.+ // Measured before this line: dropping a 220-message thread to 10 with the window at start=204+ // painted an empty column for 2 to 8 frames (37 to 146ms) on all three engines. `widen` heals+ // it a frame later but runs inside startTransition, so the blank persists. Drop the+ // restriction in the same commit: it can withhold nothing now.+ const first =+ mountWindow == null || mountWindow.start >= count+ ? 0+ : Math.max(mountWindow.start, 0);+ // One shared element for every row, which is what lets React skip unchanged rows. See header.+ const message = renderMessage();+ const rows: ReactElement[] = [];+ for (let index = first; index < count; index += 1) {+ rows.push(+ <MessageByIndexProvider key={index} index={index}>+ {message}+ </MessageByIndexProvider>,+ );+ }+ return <>{rows}</>;+ }, [count, mountWindow, renderMessage]);+ },+ (prev, next) =>+ prev.resetKey === next.resetKey &&+ prev.renderMessage === next.renderMessage,+);++ProgressiveMessages.displayName = "ProgressiveMessages";diff --git a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.tsnew file mode 100644index 00000000000..5e09525ff56--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts@@ -0,0 +1,261 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Widen-only mount window for the chat thread.+//+// Re-opening a 300K thread costs 3175ms on Chromium (#9016), nearly all of it mounting messages+// from nothing. Mounting only the last 20 of 220 re-opens in 438ms and is FLAT in thread length+// (441ms at 25K, 470ms at 100K, 438ms at 300K, medians of 8 paired rounds): cost follows mounted+// nodes, not thread length.+//+// Not a virtualizer: unmounting what scrolls away breaks find-in-page, cross-message selection,+// copy-all, screen readers, print and export. Open WebUI shipped that in 02690339 and reverted it+// ten days later in d56d74b3 as "catastrophic mount/destroy thrashing" (open-webui#23990).+//+// So the window only ever GROWS: first commit mounts the tail, each frame adds a chunk, and once it+// covers the thread the restriction is dropped for good. Nothing is ever unmounted, so the document+// converges to exactly the pre-change tree a few frames later; consumers that cannot wait have+// `completeProgressiveMounts` (see use-progressive-mount).+//+// The thread is always bottom-anchored, so the window is a single `start` index. That is the one+// simplification over LibreChat#14901, which also has to support a top anchor.++/**+ * Indices `[start, count)` may mount. `null` means no restriction: where a settled thread rests,+ * and the only state a short thread is ever in.+ */+export type MountWindow = { start: number } | null;++/**+ * Below this many messages the whole thread mounts in one commit, as before. Chunking a thread that+ * was never slow only adds frames: at 20 messages, 446ms against a 438ms floor.+ */+export const MIN_PROGRESSIVE_MESSAGES = 40;++/**+ * Messages in the first commit.+ *+ * A window that undershoots what the user can see paints a gap, so what matters is how tall 16 of+ * the SHORTEST rows this app can produce are. One-word rows alternate 126px (user) and 80px+ * (assistant) because the roles carry different padding; sixteen of them measure 1643px, and with+ * the viewport's 48px top inset and 165px bottom spacer that fills every clientHeight up to 1890px.+ * Quote the pair, not their 103px mean: the mean only reproduces the total for an EVEN row count,+ * drifting up to 23px otherwise, which is why INITIAL_MESSAGES is even.+ *+ * Measured, not derived, on a 144-message thread whose last 24 messages are one-word replies, three+ * rounds a point, Chromium 151 / Firefox / WebKit: at 900, 1080, 1440, 1800, 1840 and 1860px of+ * clientHeight the empty band below the last row on the first painted commit is exactly the band a+ * settled thread has, so 0px of it is this window's. First row on screen at 133 to 315ms by engine.+ *+ * Above 1890px it undershoots, left unfixed: 10px of band at 1900px, 110px at 2000px, 270px at+ * 2160px, closed by the first chunk and nothing unreachable meanwhile. Deriving the window from+ * clientHeight would have to guess how many rows fill it before mounting any, and the merge base it+ * is compared against paints NOTHING for 1318ms at 2160px and then the whole thread at once. 270px+ * of white for a third of a second, at a height needing a 4K panel in portrait, beats 1.3s of empty+ * screen at every height. 16 is also what LibreChat#14901 ships for the same job.+ *+ * Probe: tests/studio/probe_compact_tail_gap.py.+ */+export const INITIAL_MESSAGES = 16;++/**+ * Messages added per widening frame until the window covers the thread.+ *+ * Measured, not inherited. One build at three chunk sizes through #9016's 300K fixture, three+ * rounds of three repetitions each:+ *+ * | chunk | first row | converged | worst frame | frames over 33ms |+ * |---|---|---|---|---|+ * | 16 | 226ms | 3199ms | 240ms | 15 |+ * | 32 | 236ms | 3186ms | 437ms | 9 |+ * | 64 | 222ms | 3170ms | 703ms | 6 |+ *+ * Chunk size cannot affect the first commit (always INITIAL_MESSAGES wide) nor the total work; it+ * only trades build-in height against length. 32 is the midpoint and what LibreChat#14901 uses.+ * Changing it chooses a shape, not a speedup.+ */+export const CHUNK_MESSAGES = 32;++/**+ * The most messages the first commit may span, however few of them render.+ *+ * Sizing the tail on renderable rows means walking back across every non-rendering message in+ * between, and that walk is unbounded on its own: sixteen visible messages followed by two hundred+ * system entries walks to zero and the first commit rebuilds every provider in the thread, which is+ * the bound this file exists to create.+ *+ * Four tails. A thread has to be three quarters non-rendering across its whole tail before this+ * binds at all, which no thread the importers produce comes close to; below that it costs nothing+ * and the window is exactly the renderable-row one. When it does bind the first commit shows fewer+ * than INITIAL_MESSAGES rows, possibly none, and widening reaches the rest within a few frames --+ * bounded work either way, against the 1318ms of empty screen the merge base pays for the same+ * thread.+ */+export const MAX_INITIAL_SPAN = INITIAL_MESSAGES * 4;++/**+ * The window a thread opens with. A running thread opens unrestricted: widening and streaming write+ * the same scroll position, and a run starting under a short window would commit its reply into a+ * tree that has not reached it. A mid-run thread was mounted a moment ago anyway.+ */+export function initialWindow(+ count: number,+ isRunning: boolean,+ isRenderable?: (index: number) => boolean,+): MountWindow {+ if (isRunning || count < MIN_PROGRESSIVE_MESSAGES) return null;+ // Sized on rows that RENDER, not on messages. A message whose role the thread supplies no+ // component for paints nothing at all -- `threadMessageKind` returns "none" and `ThreadMessage`+ // returns null -- so it has no height. Counting those into the tail opens an imported+ // conversation ending in system messages on sixteen zero-height rows and no conversation, until+ // a later widening frame rescues it: the exact stall this window exists to remove. Both+ // importers preserve "system" (chat-import.ts, openwebui-import.ts).+ //+ // Optional so the arithmetic stays testable on its own and `stepsToCover` keeps a pure form; a+ // caller that cannot say what renders gets the old count-based window.+ if (!isRenderable) return { start: Math.max(0, count - INITIAL_MESSAGES) };+ // Walk back from the end until the window holds a full tail of renderable rows, but never past+ // MAX_INITIAL_SPAN messages: the walk crosses non-rendering messages too, and without the cap a+ // tail dense with them reaches index 0 and mounts the whole thread. Reaching further back only+ // ever mounts MORE, so this cannot shrink the window or unmount anything.+ const floor = Math.max(0, count - MAX_INITIAL_SPAN);+ let renderable = 0;+ for (let index = count - 1; index >= floor; index -= 1) {+ if (!isRenderable(index)) continue;+ renderable += 1;+ if (renderable >= INITIAL_MESSAGES) return { start: index };+ }+ // The cap bound before a full tail was found. Take the cap: the first commit shows whatever+ // renders inside it, which may be nothing, and widening reaches the rest within a few frames.+ // Bounded and converging beats both alternatives -- mounting the whole thread, and withholding+ // on a thread this short.+ if (floor > 0) return { start: floor };+ // The whole thread fits inside the cap and still holds fewer renderable rows than one tail:+ // there is nothing to withhold, and withholding anyway would hide part of the little there is.+ return null;+}++/** True once the window admits every message, which is when the restriction can be dropped. */+export function isCovered(current: MountWindow): boolean {+ return current == null || current.start <= 0;+}++/**+ * The next window. Returns `null` once it would cover the thread, so the restriction drops in the+ * same commit that mounts the last chunk rather than a frame later.+ *+ * `count` is re-read every step because messages arrive between frames. `start` only ever moves+ * down, so a thread growing under a live window cannot un-mount anything.+ */+export function widen(current: MountWindow, count: number): MountWindow {+ if (current == null) return null;+ // A start at or past the end withholds nothing. Clamping to `count` then subtracting a chunk+ // would move `start` BACKWARDS relative to the screen ({start: 204} on a thread that shrank to+ // 100 becomes {start: 68}, unmounting rows 0 to 67). Drop the window instead.+ if (current.start >= count) return null;+ const start = Math.max(0, current.start - CHUNK_MESSAGES);+ if (start <= 0) return null;+ return { start };+}++/**+ * Whether `index` may mount. Out-of-window indices are not rendered at all rather than hidden: the+ * cost avoided is mounting, so hiding would collect nothing.+ */+export function admits(current: MountWindow, index: number): boolean {+ return current == null || index >= current.start;+}++/** One end of a widening, as the correction below needs to see it. */+export type AnchorSample = {+ /**+ * The anchor row's offset from the top of the SCROLL CONTAINER, not of the window.+ *+ * `getBoundingClientRect().top` is window-relative, so it also moves when the container moves+ * for reasons unrelated to the thread: the composer grows a line, mobile chrome slides away, a+ * parent relayouts, the window resizes. Any of those landing between capture and the widening+ * commit would read as content inserted above and be corrected away, moving a detached reader+ * for nothing. Subtracting the container's own top at both ends removes it.+ */+ viewportOffset: number;+ /** The scroll container's scrollTop at the same instant. */+ scrollTop: number;+ /**+ * The largest scrollTop possible at the same instant (`scrollHeight - clientHeight`).+ *+ * Only for the one case where the browser moves scrollTop with anchoring off: content above a+ * reader near the bottom SHRINKING forces a clamp, since the old offset no longer exists. The+ * document-space delta reports the whole shrink anyway, so applying it on top of the clamp would+ * move the viewport twice by the clamped part. See anchorCorrection.+ */+ maxScrollTop: number;+};++/**+ * How far to move scrollTop so a widening commit leaves the reader looking at the same content,+ * or null for "do nothing". Pure, so it can be tested as arithmetic rather than as a substring.+ *+ * DOCUMENT space, correct only because the viewport turns CSS scroll anchoring OFF while the window+ * is open (see progressive-messages). With native anchoring live the browser moves scrollTop by the+ * inserted height and a document-space delta reports that insertion too, so applying it doubles the+ * browser's correction: that was v1, and it walked a parked reader's scrollTop 22,897 to 117,104.+ *+ * v2 kept anchoring on, measured the residual in viewport space, and dropped any frame the reader+ * scrolled through, since in viewport space a gesture and a layout shift are the same number. That+ * holds only while the browser compensates, and it is not in charge of whether it does. Measured at+ * 150K characters:+ *+ * - Every shipping Safari and iOS browser has no scroll anchoring at all today; WebKit implemented+ * it in February 2026 and Playwright's WebKit 26.5 has it, which hid this on this machine. With+ * `overflow-anchor: none` standing in for those builds, one dropped frame walked a parked reader+ * 19,259px and dropping every frame walked them 45,873px, on all three engines.+ * - Anchoring is also suppressed PER FRAME on engines that have it, including after a programmatic+ * scroll, which is what scrollbar drag, PageUp and middle-click autoscroll all become. Chromium+ * 151 with a reader scrolling that way through the build-in: 45,161px of drift.+ *+ * So the browser is taken out of the loop rather than trusted in it. With anchoring off scrollTop+ * moves only when the reader or this code moves it, and document space subtracts the reader's own+ * movement arithmetically: no frame skipped, nothing to feature-probe. Same fixture, same reader:+ * 12px.+ */+export function anchorCorrection(+ captured: AnchorSample,+ now: AnchorSample,+): number | null {+ // What the browser was forced to absorb. With anchoring off it moves scrollTop for exactly one+ // reason: the reader's offset stopped existing because the document got shorter above them. That+ // part already happened, so only the remainder is applied.+ //+ // The clamp is estimated from the captured scrollTop, so it is exact only for a reader who did+ // not scroll during the frame, and that bound cannot be closed here: the two orderings (clamp+ // then gesture, gesture then clamp) produce the SAME pair of samples while wanting different+ // answers, so gating on "scrollTop did not end at maxScrollTop" just moves the error to the other+ // ordering. This picks clamp-first and is wrong by at most `captured.scrollTop -+ // now.maxScrollTop`, the height of the shrink the reader was hanging over, never by their+ // gesture. It needs a DETACHED reader parked inside that overhang, content above them shrinking,+ // and a scroll in that one frame, with a window open. Everything else has this term at zero.+ const clamped = Math.max(0, captured.scrollTop - now.maxScrollTop);+ const shift =+ now.viewportOffset ++ 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;+}++/**+ * Widening frames a thread of `count` messages takes to converge. Tests assert on this so the+ * constants above cannot drift into a thread that never finishes.+ */+export function stepsToCover(count: number): number {+ let steps = 0;+ let current = initialWindow(count, false);+ while (current != null) {+ current = widen(current, count);+ steps += 1;+ // Bounded by construction; fails a test rather than hanging the browser if that ever changes.+ if (steps > count + 2) throw new Error("widen made no progress");+ }+ return steps;+}diff --git a/studio/frontend/src/components/assistant-ui/thread-message-slot.ts b/studio/frontend/src/components/assistant-ui/thread-message-slot.tsindex 9272a6102cd..9004412222d 100644--- a/studio/frontend/src/components/assistant-ui/thread-message-slot.ts+++ b/studio/frontend/src/components/assistant-ui/thread-message-slot.ts@@ -47,6 +47,22 @@ export function threadMessageKind(return "none";}+/**+ * Whether a message in this state paints anything.+ *+ * Derived from `threadMessageKind` rather than from its own list of roles: a second list would+ * drift from the renderer the first time a role is added, and the drift is silent in both+ * directions. Anything sizing itself on what the reader can SEE, rather than on how many messages+ * there are, has to ask this -- a "none" message occupies no height, so counting it as a row makes+ * a thread open on blanks. See progressive-mount-controller.ts.+ */+export function rendersAsRow(+ role: ThreadMessageRole,+ isEditing: boolean,+): boolean {+ return threadMessageKind(role, isEditing) !== "none";+}+/*** A render prop that always returns the SAME propless element for `Component`.*diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 9747c2abf5b..cb12af3fa84 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -21,6 +21,7 @@ import {MessageResponseDetailsSheet,MessageResponseModelBadge,} from "@/components/assistant-ui/message-response-details-sheet";+import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";import { MessageTiming } from "@/components/assistant-ui/message-timing";import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";@@ -1537,8 +1538,13 @@ export const Thread: FC<{// the spacer clamp math. State, not a ref: the keyed provider remounts the// viewport on thread switches and the scroll listener must re-attach.const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);+ // Same element in an identity-stable ref, so ProgressiveMessages can read the viewport without a+ // prop that would rebuild its row array on thread switch. A ref rather than a document-wide query+ // because the Compare panes each mount their own Thread.+ const viewportElRef = useRef<HTMLElement | null>(null);const composedViewportRef = useCallback((node: HTMLElement | null) => {+ viewportElRef.current = node;setViewportEl(node);viewportRef(node);},@@ -1762,9 +1768,17 @@ export const Thread: FC<{</AuiIf>)}- <ThreadPrimitive.Messages>- {renderThreadMessage}- </ThreadPrimitive.Messages>+ {/* Drop-in for ThreadPrimitive.Messages that bounds a long thread's first commit to+ the tail and mounts the rest over the following frames. Nothing unmounts and the+ document converges to the tree this rendered before; consumers that cannot wait call+ completeProgressiveMounts. It takes the propless slot #9042 introduced, for the same+ reason: React's bail-out needs one shared element per row. See+ progressive-mount-controller.ts. */}+ <ProgressiveMessages+ renderMessage={renderThreadMessage}+ resetKey={runtimeThreadId}+ viewportRef={viewportElRef}+ />{/* Bottom slack so the last message has room above the stickyscroll-to-bottom button (and floating composer in single mode),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.tsxindex 73eaaded13a..be09f01bde6 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@@ -76,6 +76,15 @@ type AutoScrollContextValue = {* re-attaches; explicit pins (run start, button) still work.*/detachFromBottom: () => void;+ /**+ * `deltaPx` of content was inserted ABOVE the viewport; shift by it so the+ * user keeps looking at the same thing. Progressive mounting (see+ * progressive-mount-controller) is the only caller and calls on EVERY+ * widening commit, zero included, since a zero correction still resyncs the+ * intent bookkeeping below. A method rather than a scrollTop write at the+ * inserting commit because this hook owns scrollTop.+ */+ adjustForContentInsertedAbove: (deltaPx: number) => void;};const noopContext: AutoScrollContextValue = {@@ -89,6 +98,9 @@ const noopContext: AutoScrollContextValue = {detachFromBottom: () => {/* no viewport mounted */},+ adjustForContentInsertedAbove: () => {+ /* no viewport mounted */+ },};const AutoScrollContext = createContext<AutoScrollContextValue>(noopContext);@@ -111,6 +123,11 @@ export function useScrollThreadToBottom(): ScrollToBottom {return useContext(AutoScrollContext).scrollToBottom;}+/** See AutoScrollContextValue.adjustForContentInsertedAbove. */+export function useAdjustForContentInsertedAbove(): (deltaPx: number) => void {+ return useContext(AutoScrollContext).adjustForContentInsertedAbove;+}+export function useIsThreadAtBottom(): boolean {const ctx = useContext(AutoScrollContext);return useSyncExternalStore(ctx.subscribe, ctx.getIsAtBottom, () => true);@@ -134,6 +151,9 @@ export function useIntentAwareAutoScroll(): {const detachImplRef = useRef<() => void>(() => {/* no viewport mounted */});+ const adjustImplRef = useRef<(deltaPx: number) => void>(() => {+ /* no viewport mounted */+ });const getIsAtBottom = useCallback(() => isAtBottomRef.current, []);@@ -162,6 +182,10 @@ export function useIntentAwareAutoScroll(): {detachImplRef.current();}, []);+ const adjustForContentInsertedAbove = useCallback((deltaPx: number) => {+ adjustImplRef.current(deltaPx);+ }, []);+const attach = useCallback((el: HTMLElement, isRebind: boolean) => {let rafId: number | null = null;@@ -335,6 +359,50 @@ 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 runs onLayoutChange -> pinIfFollowing 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.+ adjustImplRef.current = (deltaPx: number) => {+ if (!userDetachedRef.current) {+ return;+ }+ if (deltaPx !== 0) {+ el.scrollTo({ top: el.scrollTop + deltaPx, behavior: "instant" });+ }+ // Advance the intent bookkeeping whether or not anything was written.+ //+ // With a write, this stops the scroll event it provokes from reading as+ // reader movement: the `delta > 0` branch below would re-attach a user+ // parked near the bottom and the next widening frame would yank them+ // down.+ //+ // WITHOUT a write it matters just as much. When native scroll anchoring+ // absorbs a widening in full the correction is zero, but the browser+ // still moved scrollTop by the whole inserted height and still fires a+ // scroll event for it (measured on Chromium 151, WebKit 26.5, Firefox+ // 153). Returning early left lastScrollTop a whole insertion behind, so+ // that event arrived as a large downward scroll nobody made. Layout+ // effects run before it is dispatched, so resyncing here reads as zero.+ lastScrollTop = el.scrollTop;+ lastDistanceFromBottom = distanceFromBottom();+ };+const onWheel = (e: WheelEvent) => {if (e.deltaY < 0 &&@@ -463,10 +531,7 @@ export function useIntentAwareAutoScroll(): {const needed = Math.max(0, shrink);if (needed !== stabilizerPx) {stabilizerPx = needed;- el.style.setProperty(- "--aui-scroll-stabilizer",- `${stabilizerPx}px`,- );+ el.style.setProperty("--aui-scroll-stabilizer", `${stabilizerPx}px`);}return currentContent + stabilizerPx;};@@ -571,6 +636,9 @@ export function useIntentAwareAutoScroll(): {detachImplRef.current = () => {/* no viewport mounted */};+ adjustImplRef.current = () => {+ /* no viewport mounted */+ };};},[setIsAtBottom],@@ -608,8 +676,20 @@ export function useIntentAwareAutoScroll(): {);const context = useMemo<AutoScrollContextValue>(- () => ({ scrollToBottom, getIsAtBottom, subscribe, detachFromBottom }),- [scrollToBottom, getIsAtBottom, subscribe, detachFromBottom],+ () => ({+ scrollToBottom,+ getIsAtBottom,+ subscribe,+ detachFromBottom,+ adjustForContentInsertedAbove,+ }),+ [+ scrollToBottom,+ getIsAtBottom,+ subscribe,+ detachFromBottom,+ adjustForContentInsertedAbove,+ ],);return { ref, context };diff --git a/studio/frontend/tests/progressive-mount-controller.test.ts b/studio/frontend/tests/progressive-mount-controller.test.tsnew file mode 100644index 00000000000..6a9babb3976--- /dev/null+++ b/studio/frontend/tests/progressive-mount-controller.test.ts@@ -0,0 +1,385 @@+// 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 widen-only mount window, tested where it is pure. The React glue is a .tsx and node's type+// stripping cannot import one, so its invariants are pinned by source assertion in+// progressive-mount-glue.test.ts instead.+//+// The property all of these protect: the window only ever grows, and it always reaches null. A+// window that shrank would unmount a message, the failure mode this change exists to avoid.++import assert from "node:assert/strict";+import test from "node:test";++import {+ CHUNK_MESSAGES,+ INITIAL_MESSAGES,+ MAX_INITIAL_SPAN,+ MIN_PROGRESSIVE_MESSAGES,+ type MountWindow,+ admits,+ anchorCorrection,+ initialWindow,+ isCovered,+ stepsToCover,+ widen,+} from "../src/components/assistant-ui/progressive-mount-controller.ts";++test("a thread under the floor is never windowed", () => {+ for (const count of [0, 1, 20, MIN_PROGRESSIVE_MESSAGES - 1]) {+ assert.equal(+ initialWindow(count, false),+ null,+ `${count} messages should mount at once`,+ );+ }+});++test("a thread at the floor is windowed", () => {+ const w = initialWindow(MIN_PROGRESSIVE_MESSAGES, false);+ assert.notEqual(w, null);+ assert.equal(w?.start, MIN_PROGRESSIVE_MESSAGES - INITIAL_MESSAGES);+});++test("the first commit mounts the tail, not the head", () => {+ // The thread is bottom-anchored, so a head-anchored window would mount 16 messages nobody can+ // see and still paint an empty viewport.+ const w = initialWindow(220, false);+ assert.equal(w?.start, 220 - INITIAL_MESSAGES);+ assert.equal(admits(w, 219), true);+ assert.equal(admits(w, 220 - INITIAL_MESSAGES), true);+ assert.equal(admits(w, 220 - INITIAL_MESSAGES - 1), false);+ assert.equal(admits(w, 0), false);+});++test("a running thread opens unrestricted", () => {+ // Widening and streaming both write scrollTop, and a reply must never commit into a tree that+ // has not reached it.+ assert.equal(initialWindow(220, true), null);+});++test("a null window admits every index", () => {+ assert.equal(admits(null, 0), true);+ assert.equal(admits(null, 10_000), true);+ assert.equal(isCovered(null), true);+});++test("widening only ever moves start down", () => {+ let current = initialWindow(220, false);+ let previous = Number.POSITIVE_INFINITY;+ while (current != null) {+ assert.ok(+ current.start < previous,+ `start went ${previous} -> ${current.start}`,+ );+ previous = current.start;+ current = widen(current, 220);+ }+});++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`);+ }+});++test("the number of widening frames is bounded and small", () => {+ // One frame per chunk after the first commit. 220 messages is #9016's largest fixture, and at+ // 60Hz seven frames is under 120ms, the budget this whole change rests on.+ assert.equal(+ stepsToCover(220),+ Math.ceil((220 - INITIAL_MESSAGES) / CHUNK_MESSAGES),+ );+ assert.equal(stepsToCover(220), 7);+ assert.ok(+ stepsToCover(5000) < 160,+ "a 5000-message thread must still converge in seconds",+ );+});++test("widen returns null in the same commit that mounts the last chunk", () => {+ // Not a frame later: {start: 0} renders the same as null, so leaving one spends an extra frame+ // re-rendering the whole thread into a byte-identical tree.+ const nearlyDone: MountWindow = { start: CHUNK_MESSAGES };+ assert.equal(widen(nearlyDone, 220), null);+ const exactlyOneChunkLeft: MountWindow = { start: CHUNK_MESSAGES - 1 };+ assert.equal(widen(exactlyOneChunkLeft, 220), null);+});++test("widen never returns a start above the message count", () => {+ // A thread that SHRANK under a live window (a delete or a branch switch) must not leave it+ // pointing past the end, which would admit nothing and paint an empty thread.+ const stale: MountWindow = { start: 200 };+ const next = widen(stale, 10);+ assert.equal(+ next,+ null,+ "a window past the end of a shrunken thread must be dropped",+ );+});++test("widen on a null window is a no-op", () => {+ assert.equal(widen(null, 220), null);+});++test("isCovered is true exactly when nothing is being withheld", () => {+ assert.equal(isCovered({ start: 0 }), true);+ assert.equal(isCovered({ start: 1 }), false);+});++test("the constants stay inside the range they were measured over", () => {+ // Bounds, not equalities, so a future edit cannot quietly turn the first commit into one row or+ // the floor into every thread and stay green.+ assert.ok(+ INITIAL_MESSAGES >= 8 && INITIAL_MESSAGES <= 64,+ `INITIAL_MESSAGES ${INITIAL_MESSAGES} is outside the measured range`,+ );+ assert.ok(+ CHUNK_MESSAGES >= 8 && CHUNK_MESSAGES <= 128,+ `CHUNK_MESSAGES ${CHUNK_MESSAGES} is outside the measured range`,+ );+ assert.ok(+ MIN_PROGRESSIVE_MESSAGES >= INITIAL_MESSAGES * 2,+ "the floor must leave room for at least one widening, or the window is pointless",+ );+});++// anchorCorrection, extracted. It used to live inside the .tsx where nothing could test it, and its+// one bug so far was found by a browser probe rather than a test.++const sample = (viewportOffset: number, scrollTop: number, maxScrollTop = 1_000_000) => ({+ viewportOffset,+ scrollTop,+ maxScrollTop,+});++test("the correction is the height inserted above, in document space", () => {+ // scrollTop did not move, so the anchor moved down by everything inserted above it.+ assert.equal(anchorCorrection(sample(-500, 20000), sample(11500, 20000)), 12000);+});++test("the reader's own scroll is subtracted, not skipped", () => {+ // 12000px inserted above in the frame the reader scrolled down 3000px; document space nets those+ // to the 12000px to apply. The version that skipped such frames left the reader 19,259px out.+ assert.equal(anchorCorrection(sample(-500, 20000), sample(8500, 23000)), 12000);+ // A frame holding only the reader's own scroll is a no-op, with no gesture bookkeeping needed.+ assert.equal(anchorCorrection(sample(-500, 20000), sample(-3500, 23000)), null);+});++test("a frame that inserted nothing is a no-op whatever the reader did", () => {+ for (const scrolled of [0, -900, 4000]) {+ assert.equal(+ anchorCorrection(sample(-500, 20000), sample(-500 - scrolled, 20000 + scrolled)),+ null,+ `no insertion should mean no correction (reader moved ${scrolled}px)`,+ );+ }+});++test("sub-pixel movement is never acted on", () => {+ assert.equal(anchorCorrection(sample(-500.0, 20000), sample(-499.4, 20000)), null);+});++test("a window past the end of a shrunken thread is dropped, never narrowed", () => {+ // The failure this rules out: {start: 204} against a thread that shrank to 100. Clamping to count+ // then subtracting a chunk gives {start: 68}, and the caller already rendered all 100 rows, so+ // rows 0 to 67 would be unmounted.+ assert.equal(widen({ start: 204 }, 100), null);+ assert.equal(widen({ start: 204 }, 0), null);+ assert.equal(widen({ start: 100 }, 100), null);+ // One below the end still widens normally.+ assert.deepEqual(widen({ start: 99 }, 100), { start: 99 - CHUNK_MESSAGES });+});++test("widening is monotone in start for every reachable window and count", () => {+ // The general property behind the case above: the next window never withholds more than this+ // one does.+ for (let count = 0; count <= 300; count += 7) {+ for (let start = 0; start <= 300; start += 5) {+ const next = widen({ start }, count);+ if (next == null) continue;+ assert.ok(+ next.start < start,+ `widen({start:${start}}, ${count}) returned {start:${next.start}}, which withholds more`,+ );+ }+ }+});++test("a shrink the browser already clamped is not corrected twice", () => {+ // With anchoring off the browser moves scrollTop for exactly one reason: content shrinks above a+ // reader near the bottom, their offset stops existing, and it clamps to the new maximum. The+ // document-space delta reports the whole shrink anyway, so applying it on top of the clamp would+ // move the viewport twice by the clamped part.+ //+ // 500px removed above a reader at scrollTop 9000, maximum dropping to 8600: the browser absorbed+ // 400, so 100 is left to apply.+ assert.equal(+ anchorCorrection(sample(200, 9000, 9100), sample(100, 8600, 8600)),+ -100,+ );+ // The same shrink with room to spare is corrected in full: nothing was clamped.+ assert.equal(+ anchorCorrection(sample(200, 9000, 50_000), sample(-300, 9000, 49_500)),+ -500,+ );+});++// A row that does not render is not a row. `threadMessageKind` returns "none" for any role the+// thread supplies no component for, and `ThreadMessage` renders null for it, so the message+// occupies no height. Sizing the tail by message COUNT therefore lets a thread open on sixteen+// invisible rows and paint no conversation at all, which is the stall this window exists to+// remove rather than cause. Imports keep the roles that do this: chat-import.ts and+// openwebui-import.ts both preserve "system".++/** Renderable everywhere except a tail of `systemTail` messages. */+function tailIsUnrenderable(count: number, systemTail: number) {+ return (index: number) => index < count - systemTail;+}++/** How many rows the first commit would actually paint. */+function visibleRows(+ window: MountWindow,+ count: number,+ renders: (index: number) => boolean,+): number {+ let visible = 0;+ for (+ let index = window == null ? 0 : window.start;+ index < count;+ index += 1+ ) {+ if (renders(index)) visible += 1;+ }+ return visible;+}++test("the initial tail is sized on rows that render, not on message count", () => {+ const count = 220;+ const renders = tailIsUnrenderable(count, INITIAL_MESSAGES);+ const w = initialWindow(count, false, renders);+ // The whole point: the first commit paints a full tail of CONVERSATION, not sixteen blanks.+ assert.equal(visibleRows(w, count, renders), INITIAL_MESSAGES);+ // And it got there by reaching further back, never by mounting less.+ assert.ok(w != null && w.start < count - INITIAL_MESSAGES);+});++test("a tail of unrenderable rows still only ever widens", () => {+ const count = 220;+ const renders = tailIsUnrenderable(count, 40);+ const w = initialWindow(count, false, renders);+ // Reaching back for renderable rows must not push `start` past the end or below zero, or widen+ // would unmount what this just mounted.+ assert.ok(w != null && w.start >= 0 && w.start < count);+ assert.equal(visibleRows(w, count, renders), INITIAL_MESSAGES);+ // Still converges.+ let current: MountWindow = w;+ let steps = 0;+ while (current != null) {+ const next = widen(current, count);+ assert.ok(+ next == null || next.start < current.start,+ "start must only fall",+ );+ current = next;+ steps += 1;+ assert.ok(steps <= count + 2, "widen made no progress");+ }+});++test("a short thread with too few renderable rows is not windowed at all", () => {+ // Short enough to sit inside the cap, so there is no bound to enforce and nothing to withhold:+ // withholding here would hide part of the little there is to see.+ const count = MAX_INITIAL_SPAN;+ assert.equal(+ initialWindow(count, false, () => false),+ null,+ );+ assert.equal(+ initialWindow(+ count,+ false,+ (index) => index >= count - (INITIAL_MESSAGES - 1),+ ),+ null,+ );+});++test("a long thread with too few renderable rows is bounded, not mounted whole", () => {+ // Past the cap the bound is what matters. There is nothing to see either way, so mounting the+ // whole thread in order to show nothing is the one option with no argument for it.+ const count = 220;+ const shapes = [+ () => false,+ (index: number) => index >= count - (INITIAL_MESSAGES - 1),+ ];+ for (const renders of shapes) {+ const w = initialWindow(count, false, renders);+ assert.notEqual(w, null);+ assert.equal(w?.start, count - MAX_INITIAL_SPAN);+ }+});++test("omitting the predicate keeps the count-based window", () => {+ // Callers that cannot say what renders (the tests above, stepsToCover) must behave as before.+ assert.deepEqual(initialWindow(220, false), {+ start: 220 - INITIAL_MESSAGES,+ });+ assert.deepEqual(+ initialWindow(220, false, () => true),+ {+ start: 220 - INITIAL_MESSAGES,+ },+ );+});++// Sizing the tail on renderable rows has to stay BOUNDED. Walking back for sixteen rows that+// render will cross every non-rendering message in between, and an imported thread of sixteen+// visible messages followed by two hundred system entries walked all the way to zero: the first+// commit then rebuilt every provider in the thread, which is the bound this window exists to+// create. Both ends matter, so both are asserted here.++test("the first commit's raw span is bounded even when the tail does not render", () => {+ const count = 220;+ const renders = (index: number) => index < INITIAL_MESSAGES;+ const w = initialWindow(count, false, renders);+ const first = w == null ? 0 : w.start;+ assert.ok(+ count - first <= MAX_INITIAL_SPAN,+ `first commit mounted ${count - first} providers, over the ${MAX_INITIAL_SPAN} cap`,+ );+});++test("the cap does not cost visible rows when they are reachable inside it", () => {+ // The realistic shape: a system entry every few messages. The walk crosses them and still+ // returns a full tail of conversation, well inside the cap.+ const count = 220;+ const renders = (index: number) => index % 3 !== 0;+ const w = initialWindow(count, false, renders);+ assert.notEqual(w, null);+ const first = w == null ? 0 : w.start;+ assert.ok(count - first <= MAX_INITIAL_SPAN);+ assert.equal(visibleRows(w, count, renders), INITIAL_MESSAGES);+});++test("an all-renderable thread is unchanged by the cap", () => {+ // The common case must not move: the cap is a bound, not a policy.+ assert.deepEqual(initialWindow(220, false, () => true), {+ start: 220 - INITIAL_MESSAGES,+ });+});++test("a capped window still only widens, and still converges", () => {+ const count = 220;+ const renders = (index: number) => index < INITIAL_MESSAGES;+ let current = initialWindow(count, false, renders);+ assert.ok(current != null && current.start >= 0 && current.start < count);+ let steps = 0;+ while (current != null) {+ const next = widen(current, count);+ assert.ok(next == null || next.start < current.start, "start must only fall");+ current = next;+ steps += 1;+ assert.ok(steps <= count + 2, "widen made no progress");+ }+});diff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.tsnew file mode 100644index 00000000000..a7f038e9712--- /dev/null+++ b/studio/frontend/tests/progressive-mount-glue.test.ts@@ -0,0 +1,440 @@+// 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 impure parts of the progressive mount, pinned by source assertion because they live in .tsx+// files and node's type stripping cannot import one (same shape as+// chat-autoscroll-frame-budget.test.ts). Each is a real invariant with a real failure behind it.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const read = (path: string): string =>+ readFileSync(new URL(path, import.meta.url), "utf8");++/**+ * Source with comments removed. The "must not appear" assertions run against this: these files+ * explain at length what they deliberately do NOT do, and a prose mention of a banned construct+ * must not fail its own test.+ */+const code = (source: string): string =>+ source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, "");++const GLUE = code(+ read("../src/components/assistant-ui/progressive-messages.tsx"),+);+const HOOK = code(+ read("../src/components/assistant-ui/use-intent-aware-autoscroll.tsx"),+);+const THREAD = code(read("../src/components/assistant-ui/thread.tsx"));++/**+ * The region of `source` between two markers, with BOTH required. A bare+ * `source.slice(source.indexOf(marker))` is the sharpest edge in a file of source assertions: a+ * renamed marker gives -1 and `slice(-1)` is the file's last character, or a moved end marker+ * widens to the rest of the file and PASSES for the wrong reason.+ */+const section = (source: string, from: string, to: string): string => {+ const start = source.indexOf(from);+ assert.notEqual(start, -1, `source assertion anchor is gone: ${from}`);+ const end = source.indexOf(to, start + from.length);+ assert.notEqual(end, -1, `source assertion anchor is gone: ${to}`);+ return source.slice(start, end);+};++/**+ * The mount window and the row map only. The "must never appear" assertions are about what the+ * WINDOW does to the thread's viewport, and anything above it may legitimately hide, scroll or+ * insert into elements of its own that are never in the thread.+ */+const GLUE_WINDOW = () =>+ section(+ GLUE,+ "function useProgressiveMountWindow(",+ "ProgressiveMessages.displayName",+ );++test("the thread renders rows through MessageByIndex, never ThreadPrimitive.Messages", () => {+ // Upstream renders MessageByIndexProvider -> RenderChildrenWithAccessor -> children; this row map+ // renders MessageByIndexProvider -> children. Switching between the two on convergence would+ // change the element type at that position, so React would unmount and rebuild every message.+ assert.match(GLUE, /<MessageByIndexProvider key=\{index\} index=\{index\}>/);+ assert.doesNotMatch(+ GLUE,+ /<ThreadPrimitive\.Messages\b/,+ "the row map must not switch primitives on convergence",+ );+ assert.doesNotMatch(+ THREAD,+ /<ThreadPrimitive\.Messages\b/,+ "Thread must render the progressive list, not the unbounded one",+ );+ assert.match(THREAD, /<ProgressiveMessages/);+ // And it takes the propless slot #9042 gave ThreadPrimitive.Messages: React's bail-out needs one+ // shared element per row, whereas a `components` object allocates fresh props per row per commit+ // and every delete re-renders every body, action bar and tooltip.+ assert.match(THREAD, /renderMessage=\{renderThreadMessage\}/);+ assert.match(GLUE, /const message = renderMessage\(\);/);+ assert.doesNotMatch(+ GLUE,+ /components=\{components\}/,+ "the row map must not go back to the components form",+ );+});++test("rows outside the window are not rendered rather than rendered and hidden", () => {+ // The cost avoided is mounting. A display:none row costs the same to mount, so a rewrite to+ // hiding would stay green and collect nothing.+ const glue = GLUE_WINDOW();+ assert.doesNotMatch(glue, /display:\s*["']?none/);+ assert.doesNotMatch(glue, /visibility:\s*["']?hidden/);+ assert.doesNotMatch(glue, /content-visibility/);+});++test("the window is only ever advanced through widen", () => {+ // setMountWindow may set the initial window, clear it (null), or call widen. Anything else could+ // move `start` upward and unmount a mounted message, the failure mode this design rules out.+ const calls = [...GLUE.matchAll(/setMountWindow\(([^;]*?)\)\s*[;,]/gs)].map(+ (m) => m[1].trim(),+ );+ assert.ok(+ calls.length >= 4,+ `expected several setMountWindow calls, found ${calls.length}`,+ );+ for (const call of calls) {+ const ok =+ call === "null" ||+ call.startsWith("initialWindow(") ||+ call.includes("widen(current, count)");+ assert.ok(+ ok,+ `setMountWindow(${call}) is not one of null / initialWindow / widen`,+ );+ }+});++test("a run drops the window", () => {+ // Streaming and widening both move the scroll position, and a reply must never commit into a+ // tree that has not reached it. Two gates: reactive, for a run starting after the window opened,+ // and an in-frame re-check for one starting between commit and rAF.+ assert.match(GLUE, /thread\.isRunning/);+ assert.match(+ GLUE,+ /if \(threadIsRunning && mountWindow != null\) setMountWindow\(null\)/,+ );+ assert.match(GLUE, /if \(isRunningNow\(\)\) \{\s*setMountWindow\(null\);/);+});++test("the widening step is deferred and transition-wrapped", () => {+ // Without rAF the chunks collapse into one commit and the first paint is no earlier than before.+ // Without startTransition the widening blocks input.+ assert.match(GLUE, /requestAnimationFrame\(/);+ assert.match(GLUE, /startTransition\(/);+ assert.match(GLUE, /cancelAnimationFrame\(frame\)/);+ // Scoped to the widening effect, because the file schedules frames in three other places and a+ // whole-file match stays green while this one is retimed to a timer. Two failures behind it. A+ // timer fires before the commit it follows has painted, so captureAnchor samples rects from the+ // previous layout, and the same early run is why the disarm has to happen here rather than in a+ // layout effect (the viewport ref is populated by the paint). And the cleanup below cancels a+ // FRAME: hand it a timer handle and a window closed between the commit and the callback widens+ // anyway, which is a widening into a tree a run may already have taken over.+ const widening = section(+ GLUE,+ "if (mountWindow == null) return;",+ "}, [mountWindow, count, captureAnchor, isRunningNow]);",+ );+ assert.match(+ widening,+ /const frame = requestAnimationFrame\(/,+ "the widening step must be scheduled on a frame, not a timer",+ );+ assert.doesNotMatch(+ widening,+ /setTimeout|setInterval|queueMicrotask/,+ "cancelAnimationFrame does not cancel a timer, so a closed window would still widen",+ );+});++test("the anchor is measured against its scroll container, not against the window", () => {+ // getBoundingClientRect().top is WINDOW-relative, so it also moves when the scroll container does+ // (the composer grows a line, mobile chrome slides away, a parent relayouts). Any of those between+ // capture and the widening commit would read as content inserted above and move a reader.+ assert.match(+ GLUE,+ /element\.getBoundingClientRect\(\)\.top -\s*viewport\.getBoundingClientRect\(\)\.top/,+ "the container's own top must be subtracted at both ends",+ );+ // Both ends go through the same function, so they cannot drift apart.+ assert.match(GLUE, /function sampleAnchor\(/);+ assert.match(GLUE, /sampleAnchor\(viewport, anchor\)/);+ assert.match(GLUE, /anchorCorrection\(baseline, sampleAnchor\(viewport, element\)\)/);+ // The enclosing row is a fallback: pickAnchorRow descends to the fold, so the anchor is often the+ // <pre> Streamdown replaces when Shiki finishes, and dropping the correction then would move a+ // detached reader by a whole chunk with anchoring off.+ assert.match(GLUE, /const row = anchor\?\.closest\("\[data-role\]"\) \?\? null;/);+ assert.match(GLUE, /captured\.row\?\.isConnected && captured\.rowSample/);+ assert.match(GLUE, /scrollTop: viewport\.scrollTop,/);+ assert.match(+ GLUE,+ /anchorCorrection\(/,+ "the correction must go through the tested pure function",+ );+});++test("a completion waiter is settled when its thread goes away", () => {+ // completeProgressiveMounts awaits a promise this component resolves. Without an unmount path the+ // cleanup removed the completer but left the promise pending forever, hanging a DOM capture.+ assert.match(+ GLUE,+ /useEffect\(\(\) => flushCompletionWaiters, \[flushCompletionWaiters\]\)/,+ );+ // A cancelled frame must not drop them either, so the flush empties the ref, not the scheduler.+ const scheduler = section(+ GLUE,+ "if (mountWindow != null || completionWaiters.current.length === 0) return;",+ "useEffect(() => flushCompletionWaiters",+ );+ assert.doesNotMatch(scheduler, /completionWaiters\.current = \[\];/);+});++test("the window owns the viewport's scroll-anchoring mode while it is open", () => {+ // The correction is document-space arithmetic, correct only if nothing else moves scrollTop.+ // Native anchoring moves it on some frames and not others (never on any shipping Safari, and+ // suppressed per frame elsewhere after a programmatic scroll), and no in-frame measurement tells+ // the two apart. Measured with it left on: 19,259px of drift on a parked reader where the engine+ // did not compensate, 45,161px on Chromium where it did but was suppressed.+ assert.match(GLUE, /setProperty\("overflow-anchor", "none"\)/);+ // Set from the anchor-capture rAF, NOT a layout effect: this component is a descendant of the+ // viewport, so on the mounting commit React runs this subtree's layout effects before the+ // viewport's ref callback and the ref is still null. Measured on that version, computed+ // overflow-anchor stayed `auto` until the first widening at +803ms, which then applied the+ // document-space correction on top of the browser's and left a reader 776px short.+ const capture = section(+ GLUE,+ "const captureAnchor = useCallback(",+ "}, [viewportRef]);",+ );+ assert.match(capture, /setProperty\("overflow-anchor", "none"\)/);+ // And back on when the window closes, or a settled thread is not the pre-change thread.+ assert.match(GLUE, /removeProperty\("overflow-anchor"\)/);+ // Scoped to the effect that runs on the CLOSING commit, because there is a second removeProperty+ // in the unmount cleanup and a whole-file match is satisfied by that one alone. Losing the close+ // path is not a transient: the thread the reader keeps scrolling for the rest of the session has+ // native anchoring off with nothing left compensating for it, since the idle sampler and the+ // widening correction both stop with the window. Every later image, Shiki swap or KaTeX resize+ // above the fold then moves the reader by its own height.+ const closing = section(+ GLUE,+ "if (mountWindow != null) return;",+ "}, [mountWindow, viewportRef]);",+ );+ assert.match(+ closing,+ /restoreScrollAnchoring\(viewportRef\.current\)/,+ "the closing commit must hand scroll anchoring back to the browser",+ );+ // Both hand-backs go through the one helper, which also drops the emptied `style` attribute.+ // removeProperty alone leaves `style=""` behind, and that attribute was the only difference a+ // whole-document digest could find between this branch and its merge base at 100K and 300K.+ assert.match(+ section(GLUE, "function restoreScrollAnchoring(", "\n}"),+ /if \(viewport\.getAttribute\("style"\) === ""\) viewport\.removeAttribute\("style"\);/,+ );+ assert.doesNotMatch(+ GLUE.replace(section(GLUE, "function restoreScrollAnchoring(", "\n}"), ""),+ /removeProperty\("overflow-anchor"\)/,+ "every hand-back must go through restoreScrollAnchoring, or one path leaks style=''",+ );+ // No feature probe and no gesture bookkeeping: both decided which behaviour the browser was+ // giving us, and the browser is no longer in that loop.+ assert.doesNotMatch(GLUE, /getUserGestureSeq/);+ assert.doesNotMatch(HOOK, /userGestureSeqRef/);+});++test("the mount window never writes scrollTop itself", () => {+ // The autoscroll hook owns scrollTop. Two writers per widening frame double the forced layouts+ // and can re-attach a deliberately detached user through onScroll.+ const glue = GLUE_WINDOW();+ assert.doesNotMatch(glue, /scrollTop\s*=[^=]/);+ assert.doesNotMatch(glue, /\.scrollTo\(/);+ assert.doesNotMatch(glue, /scrollIntoView\(/);+ assert.match(glue, /adjustForContentInsertedAbove\(shift \?\? 0\)/);+});++test("the hook's correction stands down while the user is following", () => {+ // While following, the hook's MutationObserver path pins to the bottom in the same frame, and+ // since widening only prepends that is the same pixel. Correcting too is a second writer.+ const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");+ assert.match(body, /if \(!userDetachedRef\.current\) \{\s*return;/);+});++test("the hook's correction is instant, because the viewport is scroll-smooth", () => {+ // With scroll-smooth on the viewport, an animated write would still be in flight at the next+ // widening frame's write.+ assert.match(THREAD, /scroll-smooth/);+ const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");+ assert.match(body, /behavior: "instant"/);+});++test("the correction advances the intent bookkeeping with its write", () => {+ // Otherwise onScroll sees a downward scroll nobody made, and a user detached within+ // RE_ATTACH_THRESHOLD_PX of the bottom is re-attached by their own correction and yanked to the+ // bottom on the next widening frame.+ const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");+ assert.match(body, /lastScrollTop = el\.scrollTop;/);+ assert.match(body, /lastDistanceFromBottom = distanceFromBottom\(\);/);+});++test("the escape hatch exists, resolves after a paint, and is registered only while withholding", () => {+ // A DOM read during the few frames a long thread takes to converge would silently see a short+ // conversation, and a single rAF resolves before the commit it forced has painted.+ assert.match(+ GLUE,+ /export async function completeProgressiveMounts\(\): Promise<void>/,+ );+ assert.match(+ GLUE,+ /requestAnimationFrame\(\(\) => requestAnimationFrame\(\(\) => resolve\(\)\)\)/,+ );+ assert.match(GLUE, /if \(!isWithholding\) return;/);+ assert.match(GLUE, /activeCompleters\.delete\(complete\)/);+});++test("the viewport comes from a ref, not a document-wide query", () => {+ // The Compare panes each mount their own Thread, so a document-wide query finds whichever+ // viewport comes first rather than the one these rows are in.+ assert.doesNotMatch(GLUE, /document\.querySelector/);+ assert.match(GLUE, /viewportRef\.current/);+});++test("the row map is memoized on the slot identity", () => {+ // ThreadPrimitive.Messages skipped re-rendering entirely while its children function kept its+ // identity; rebuilding 220 elements per Thread re-render hands back what the windowing collects.+ assert.match(+ GLUE,+ /useMemo\(\(\) => \{[\s\S]*?\}, \[count, mountWindow, renderMessage\]\)/,+ );+ assert.match(GLUE, /prev\.renderMessage === next\.renderMessage/);+ assert.match(THREAD, /const renderThreadMessage = proplessSlot\(/);+});++test("a thread that shrank under a live window drops the restriction, it does not clamp", () => {+ // Clamping `start` to `count` makes the row loop emit NOTHING, and the widen that would heal it is+ // inside startTransition. Measured on the clamping version: dropping a 220-message thread to 10+ // with the window at start=204 painted an empty column for 2 to 8 frames on all three engines. A+ // source assertion because the failure is a React commit rather than a value.+ assert.match(+ GLUE,+ /mountWindow == null \|\| mountWindow\.start >= count/,+ "start >= count must drop the window, not clamp it to count",+ );+ // And the STATE is reconciled, not just the local `first`: leaving the window at start 204+ // against a 100-message thread lets the next widen produce start 68 and unmount 68 mounted rows.+ assert.match(+ GLUE,+ /if \(mountWindow != null && mountWindow\.start >= count\) \{\s*setMountWindow\(null\);/,+ );+ assert.doesNotMatch(+ GLUE,+ /Math\.min\(Math\.max\(mountWindow\.start, 0\), count\)/,+ "clamping start to count emits zero rows",+ );+});++test("the window re-arms on the commit that first fills an empty tree", () => {+ // The app mounts this before the history adapter delivers anything, so without this the cold+ // open, the one users complain about, was never windowed at all. Measured in the app: mount at+ // count 0, count 220 about 160ms later, same resetKey.+ assert.match(GLUE, /previousCount === 0 && count > 0/);+ assert.doesNotMatch(+ GLUE,+ /previousCount < MIN_PROGRESSIVE_MESSAGES/,+ "a threshold-crossing rule would window a thread the reader is already in the middle of",+ );+});++test("the escape hatch re-reads the completer set instead of sampling it once", () => {+ // The completers register from an effect, so a caller in the same task as the thread opening finds+ // the set empty (measured: returned in 0.1ms, 16 of 220 rows two frames later). Nor is an empty+ // set believed straight away, since a settled thread and one still loading history look alike.+ assert.match(GLUE, /let observed = false;/);+ assert.match(+ GLUE,+ /activeCompleters\.size === 0 && \(observed \|\| Date\.now\(\) >= deadline\)/,+ );+ // The re-read is only worth anything if the deadline is in the FUTURE. A deadline of `Date.now()`+ // keeps both lines above and still returns on the first pass, because a caller in the same task+ // as the thread opening reaches the check before any completer has registered: the read-once+ // failure again, spelled as a zero search interval. So the interval is a positive constant, and+ // it has to outlast a cold open's history load, measured at about 160ms.+ assert.match(+ GLUE,+ /const deadline = Date\.now\(\) \+ PROGRESSIVE_MOUNT_SEARCH_MS;/,+ "an empty completer set must only be believed after a search interval",+ );+ const searchMs = Number(+ /PROGRESSIVE_MOUNT_SEARCH_MS = (\d+)/.exec(GLUE)?.[1] ?? "0",+ );+ assert.ok(+ searchMs >= 200,+ `the search interval must outlast a cold open's history load, got ${searchMs}ms`,+ );+});++test("the hook is told about every widening, including the ones with nothing to apply", () => {+ // A widening with nothing to apply still resyncs the hook's bookkeeping, since something else may+ // have moved scrollTop in the same frame. Measured on the early-return version: a scroll-anchoring+ // adjustment fires one scroll event carrying the new offset (Chromium 151, WebKit 26.5, Firefox+ // 153), lastScrollTop stayed an insertion behind, and that event re-attached a parked reader.+ assert.match(GLUE, /adjustForContentInsertedAbove\(shift \?\? 0\)/);+ const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");+ assert.doesNotMatch(+ body,+ /deltaPx === 0\) \{\s*return;/,+ "a zero correction must still resync the bookkeeping",+ );+ assert.match(body, /lastScrollTop = el\.scrollTop;/);+});++test("the anchor is the first row the reader can see, not the first row in the list", () => {+ // Widening prepends above everything, so any row will do for it. A RELAYOUT will not: a row+ // growing between the topmost row and the fold moves the reader while leaving the topmost row+ // still. Measured with a 600px height change injected above a detached reader with the window+ // open: 600px of movement, reported as 0 by a topmost-row anchor.+ assert.match(GLUE, /function pickAnchorRow\(viewport: HTMLElement\)/);+ assert.match(GLUE, /if \(row\.getBoundingClientRect\(\)\.bottom > fold\) \{/);+ // Then down to the fold, because a row can be taller than the viewport: a reader partway through a+ // long answer has the row's top ABOVE them, so a block earlier in that message moves everything+ // they see while the row's top stays put.+ assert.match(GLUE, /for \(const child of anchor\.children\)/);+ // Visibility is tested by the row's box, not its top offset: a tall row just off screen can+ // still have its top within a viewport of the fold.+ assert.match(GLUE, /function isAnchorVisible\(/);+ assert.match(GLUE, /return box\.bottom > fold && box\.top < fold \+ viewport\.clientHeight;/);+ // A widening hands the sampler a post-correction baseline rather than nulling it, or a reflow+ // landing before the next frame is folded into the new baseline and never corrected.+ assert.doesNotMatch(GLUE, /idleRef\.current = null;\s*\}, \[mountWindow/);+ assert.doesNotMatch(+ GLUE,+ /querySelector\("\[data-role\]"\)/,+ "the first row in the list is not the row the reader is looking at",+ );+ // Both the widening capture and the between-widenings sampler use it.+ assert.match(GLUE, /const anchor = viewport \? pickAnchorRow\(viewport\) : null;/);+ assert.match(GLUE, /const element = pickAnchorRow\(viewport\);/);+});++test("the interval between widenings is compensated too, not just the widening commits", () => {+ // Native anchoring normally absorbs a <pre> swapping in Shiki output or a KaTeX resize, and it is+ // off for the whole mount window, so compensation has to cover the whole interval. The autoscroll+ // hook does not help: it pins a FOLLOWING reader and leaves a detached one alone.+ assert.match(GLUE, /idleRef/);+ assert.match(GLUE, /if \(!viewport \|\| anchorRef\.current\) return;/);+ // The idle path carries the same fallback as the widening path, because the anchor is often the+ // pre Streamdown replaces, and re-picking would re-base AFTER that replacement's own reflow.+ assert.match(GLUE, /function holdAnchor\(viewport: HTMLElement, element: Element\): HeldAnchor/);+ assert.match(GLUE, /held\.row\?\.isConnected && held\.rowSample/);+ // And it re-bases every frame, no-ops included: returning early left the baseline's scrollTop+ // stale, and anchorCorrection's clamp term reads it.+ assert.match(GLUE, /if \(shift !== null\) adjustForContentInsertedAbove\(shift\);/);+});diff --git a/studio/frontend/tests/thread-delete-render-budget.test.ts b/studio/frontend/tests/thread-delete-render-budget.test.tsindex 34e76dc53ef..13c56713eae 100644--- a/studio/frontend/tests/thread-delete-render-budget.test.ts+++ b/studio/frontend/tests/thread-delete-render-budget.test.ts@@ -32,11 +32,13 @@ test("the message list is rendered through a render prop, not a components map",// assistant-ui only skips a message subtree when the render prop's element has no props, and// the map form returns <ThreadMessageComponent components={...} />, whose props object is// freshly allocated per render.- assert.match(- thread,- /<ThreadPrimitive\.Messages>\s*\{renderThreadMessage\}\s*<\/ThreadPrimitive\.Messages>/,- );- assert.doesNotMatch(thread, /<ThreadPrimitive\.Messages[^>]*\scomponents=/s);+ //+ // The list is ProgressiveMessages, not ThreadPrimitive.Messages (#9058), so what is pinned here+ // is that the slot still reaches the row map. That list renders this same propless element in+ // each MessageByIndexProvider, so the bail-out is unchanged.+ assert.match(thread, /renderMessage=\{renderThreadMessage\}/);+ assert.doesNotMatch(thread, /<ThreadPrimitive\.Messages\b/);+ assert.doesNotMatch(thread, /<ProgressiveMessages[^>]*\scomponents=/s);});test("the render prop is built once, at module scope", () => {diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.pyindex a0e5e0d434f..550b9fed311 100644--- a/tests/studio/playwright_heavy_thread.py+++ b/tests/studio/playwright_heavy_thread.py@@ -657,12 +657,14 @@ async ([timeoutMs, settleMs, graceMs, probeEveryMs]) => {const started = performance.now();api.closeThread();// Unmount first, or "already back" is indistinguishable from "never left".- // Counted, not assumed. `growth()` subtracts one paint floor per double-rAF wait a metric is- // clocked across, and that count was hand-declared per axis in GROWTH_AXES. Reopening is- // driven by a React state update, so the count check immediately after openThread() always- // still sees the unmounted tree and the loop always pays at least one __nextPaint() before it- // can observe the rebuilt messages -- the same floor already subtracted from jump and delete.- // Reporting it lets the harness check its own declared constant instead of trusting it.+ // `paintWaits` below is REPORTED, not subtracted. Reopening is driven by a React state update,+ // so the count check immediately after openThread() always still sees the unmounted tree and+ // the loop always pays at least one __nextPaint() before it can observe the rebuilt messages.+ // That one wait is the observation floor GROWTH_AXES removes (REOPEN_OBSERVATION_FLOOR), the+ // same floor already subtracted from jump and delete. Any wait beyond it is a frame the+ // APPLICATION spent committing rows, so it stays in the number. Reporting the count lets the+ // harness verify it paid at least the floor it removes, and puts the progressive mount's frame+ // count in the table as a diagnostic in its own right.let closedMs = null;let closePaintWaits = 0;while (performance.now() - started < timeoutMs) {@@ -1306,6 +1308,42 @@ def print_table(results: dict) -> None:info(name.ljust(label_width) + "".join(cell.rjust(cell_width) for cell in cells))+# The double-rAF waits inside `reopen ms` that are OBSERVATION rather than latency.+#+# Exactly one. Reopening is driven by a React state update, so the count check immediately after+# openThread() always still sees the unmounted tree, and the loop always pays one __nextPaint()+# before a completed reopen can be seen at all. That wait is the instrument, not the application,+# and it comes out of the number.+#+# Every FURTHER wait the loop pays is not overhead. The poll runs in the same rAF queue as the+# application's own commits, so on a build that brings a long thread back over several animation+# frames those waits ARE the application mounting rows, and the time inside them is real+# convergence latency that a reader waits through.+#+# This is why the count is a constant and not `_floor_from("reopen", "paintWaits")`. The measured+# count is 1 on a build that rebuilds in one commit and rises with thread size on one that mounts+# progressively (1 at 25K, 8 at 100K, 24 at 300K on a 220-message fixture), so subtracting all of+# them removed ~33ms from one arm's 300K cell and ~800ms from the other's. That is asymmetric+# between the two arms of a comparison AND grows with the axis being varied: it reported a reopen+# curve that rises faster than the single-commit build's (7.60x against 7.08x from 25K to 300K) as+# one that rises slower (5.07x), which is the opposite sign. A floor exists to remove a CONSTANT+# the instrument adds, and the moment it tracks the thing being measured it is no longer a floor.+REOPEN_OBSERVATION_FLOOR = 1+# `<action> wall ms` spans the whole recorder window and normally takes the window's measured+# `paint_waits`, because for every other action those waits are harness-imposed idle time between+# driven steps. Reopen is the exception for the reason above: its window holds the close loop and+# the reopen loop, and on a progressive-mount build the reopen loop's waits are the application's+# commit frames. The observation floors in that window are the two terminal waits, one per loop.+WALL_FLOOR_OVERRIDES = {"reopen": 1 + REOPEN_OBSERVATION_FLOOR}+++def _wall_floor(action: str):+ """The floor for `<action> wall ms`: the measured window count, unless the action overrides it+ because part of that count is application work rather than instrument idle."""+ override = WALL_FLOOR_OVERRIDES.get(action)+ return _floor_from(action, "paint_waits") if override is None else override++# Growth axes: the whole point of the harness is that these rise with content. The third field is# HOW MANY double-rAF waits the metric is clocked across; each one carries its own ~33ms vsync# floor, and left in, that floor compresses every ratio towards 1 and lets a real regression sit@@ -1320,8 +1358,10 @@ GROWTH_AXES = tuple(# roughly `paint_waits * paint_floor_ms` of constant baseline in both ends of the ratio.# MENU_JS is the clearest case: it opens the recorder before opening the menu and closes it# after closing it, so it crosses the same two waits `menu open+close ms` correctly declares,- # and `menu wall ms` was declaring none of them.- + [(f"{a} wall ms", _action(a, "wall_ms"), _floor_from(a, "paint_waits")) for a in ACTIONS]+ # and `menu wall ms` was declaring none of them. The one exception is in WALL_FLOOR_OVERRIDES:+ # reading the row is only right while the waits in the window are the harness idling between+ # driven steps, and reopen's are not.+ + [(f"{a} wall ms", _action(a, "wall_ms"), _wall_floor(a)) for a in ACTIONS]+ [# The rule for the entries below: an axis measured from `__hv.startedAt` spans the WHOLE# recorder window, so it carries every double-rAF wait in it and takes the measured@@ -1350,10 +1390,12 @@ GROWTH_AXES = tuple(# close. The window count is zero here and would remove a floor that is really there.("menu open+close ms", _action("menu", "open_close_ms"), 2),("delete ms", _action("delete", "ms"), 1),- # 1, not 0: see paintWaits in REOPEN_JS. Leaving it at 0 left a full ~33ms vsync floor- # of constant baseline in both ends of the ratio, which compresses it towards 1 and can- # report a real reopen curve as flat when the smallest fixture rebuilds near the floor.- ("reopen ms", _action("reopen", "ms"), 1),+ # The OBSERVATION floor only, and deliberately a constant rather than the measured+ # `paintWaits`: see REOPEN_OBSERVATION_FLOOR above. Leaving it at 0 is still wrong, that+ # left a full ~33ms vsync floor of constant baseline in both ends; subtracting all the+ # waits was worse, because the count tracks the progressive mount and so removes the+ # thing the axis exists to measure.+ ("reopen ms", _action("reopen", "ms"), REOPEN_OBSERVATION_FLOOR),])# A ratio at or below this from the smallest size to the largest means the axis did not respond@@ -1562,10 +1604,14 @@ def print_growth(results: dict, report: dict) -> None:# The declared double-rAF count for each axis whose action reports how many it actually paid.-# GROWTH_AXES holds the declaration; the action holds the observation; a harness that declares a-# floor it does not pay, or pays one it does not declare, subtracts the wrong constant from both-# ends of every ratio it publishes. Only reopen reports its waits today, so only reopen is-# checkable here; the entry exists so adding a counter to another action wires it in by name.+# GROWTH_AXES holds the declaration; the action holds the observation; a harness that subtracts a+# floor the metric never waited out invents time it never spent. Only reopen reports its waits+# today, so only reopen is checkable here; the entry exists so adding a counter to another action+# wires it in by name.+#+# The check is a LOWER BOUND, not equality. Paying more waits than are subtracted is the normal+# state of a progressive mount and is not a fault: those extra waits are the application+# committing rows, and REOPEN_OBSERVATION_FLOOR keeps them in the number on purpose.# axis name in GROWTH_AXES -> (action, the field on that action reporting its own wait count)FLOOR_COUNTERS = {"reopen ms": ("reopen", "paintWaits")}@@ -1584,7 +1630,7 @@ def declared_floor(axis_name: str) -> int | None:def floor_declaration_problems(results: dict) -> list[str]:- """Axes whose subtracted paint floor does not match the waits the action actually paid."""+ """Axes that subtract more double-rAF floors than the action actually waited out."""problems: list[str] = []for engine in results["engines"]:for size in results["sizes"]:@@ -1605,13 +1651,18 @@ def floor_declaration_problems(results: dict) -> list[str]:f"paint floor subtracted from '{axis_name}' is unverified")continue- declared = declared_floor(axis_name)- if declared == observed:+ # Resolved against THIS row, so an axis whose floor is read from the row (see+ # `_floor_from`) is verified as what it will actually subtract rather than+ # compared as a callable and reported wrong every time. A hand-declared literal+ # resolves to itself, so it is still caught the moment it exceeds the waits the+ # action paid, which is the whole point of this check.+ declared = resolve_floor(declared_floor(axis_name), row)+ if observed >= declared:continueproblems.append(f"{engine} at {size} chars paid {observed} paint wait(s) in {action} but "- f"GROWTH_AXES subtracts {declared} from '{axis_name}'; the ratio is computed "- "after removing the wrong constant from both ends"+ f"GROWTH_AXES subtracts {declared} from '{axis_name}'; a metric cannot be "+ "credited with a floor it never waited out")return problemsdiff --git a/tests/studio/probe_compact_tail_gap.py b/tests/studio/probe_compact_tail_gap.pynew file mode 100644index 00000000000..de55546a359--- /dev/null+++ b/tests/studio/probe_compact_tail_gap.py@@ -0,0 +1,218 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does a long thread whose LAST messages are compact paint an empty region on the first commit?++The mount window opens on INITIAL_MESSAGES rows. If those rows plus the viewport's bottom spacer+are shorter than clientHeight -- a compact tail in a tall viewport -- the first painted commit+cannot fill the screen, and this measures how big the empty band is and how long it lasts.++Measured on a 144-message thread whose last 24 messages are one-word replies: at 900, 1080, 1440,+1800, 1840 and 1860px of clientHeight there is no band the settled thread does not also have,+because 16 one-word rows are 1639px and the viewport's own inset and spacer carry that to 1890px.+Above 1890px there is one -- 10px at 1900, 110px at 2000, 270px at 2160 -- for 287 to 499ms until+the first widening chunk closes it. See INITIAL_MESSAGES.++Prints and exits 0 on any measurement. Not a gate.++ PM_PORT=5731 PM_ENGINE=chromium PM_HEIGHTS=900,1080,1440 \+ python3 tests/studio/probe_compact_tail_gap.py++Needs #9016's heavy-thread harness, plus two methods on it: `seedCompactTail(chars, tailMessages)`+and `gapMetrics()`.+"""++from __future__ import annotations+import json, os, sys, time+from pathlib import Path+from playwright.sync_api import sync_playwright++TREE = Path(os.environ.get("PM_TREE", Path(__file__).resolve().parents[2])).resolve()+sys.path.insert(0, str(TREE / "tests" / "studio"))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("PM_PORT", "5731"))+PAGE = f"http://127.0.0.1:{PORT}/smoke-heavy-thread.html"+CHARS = int(os.environ.get("PM_CHARS", "150000"))+TAIL = int(os.environ.get("PM_TAIL", "24"))+HEIGHTS = [int(h) for h in os.environ.get("PM_HEIGHTS", "900,1080,1440").split(",")]+ENGINES = os.environ.get("PM_ENGINE", "chromium").split(",")+REPEATS = int(os.environ.get("PM_REPEATS", "3"))+LABEL = os.environ.get("PM_LABEL", "tree")+OUT = Path(os.environ.get("PW_ART_DIR", str(TREE / "logs" / "pm_gap")))+OUT.mkdir(parents = True, exist_ok = True)++NEXT_PAINT = """+window.__nextPaint = () => new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+"""++# Re-open and sample the viewport every frame from the first painted row until the thread stops+# growing, so the gap is a timeline rather than a single reading.+RUN_JS = """+async ([total, settleFrames]) => {+ const api = window.__heavyThread;+ api.closeThread();+ while (api.messageCount() !== 0) await window.__nextPaint();+ const samples = [];+ const t0 = performance.now();+ api.openThread();+ let stable = 0;+ let last = -1;+ const deadline = performance.now() + 30000;+ while (performance.now() < deadline) {+ await new Promise((r) => requestAnimationFrame(r));+ const rows = api.messageCount();+ if (rows > 0) {+ const m = api.gapMetrics();+ m.t = Math.round(performance.now() - t0);+ samples.push(m);+ }+ if (rows === last && rows >= total) { stable += 1; } else { stable = 0; }+ last = rows;+ if (stable >= settleFrames) break;+ }+ return { total, samples };+}+"""+++def info(m: str) -> None:+ print(f"[pm-gap] {m}", flush = True)+++def run_engine(pw, engine: str) -> dict:+ browser_type = getattr(pw, engine)+ launch = {"args": chromium_launch_args()} if engine == "chromium" else {}+ browser = browser_type.launch(headless = True, **launch)+ out: dict = {}+ for height in HEIGHTS:+ rounds = []+ context = browser.new_context(viewport = {"width": 1280, "height": height})+ context.add_init_script(NEXT_PAINT)+ page = context.new_page()+ page.goto(PAGE, wait_until = "load", timeout = 180000)+ page.wait_for_function("() => !!window.__heavyThread", timeout = 120000)+ # Named here rather than surfacing as a bare `seedCompactTail is not a function` JS error.+ missing = page.evaluate(+ """() => ["seedCompactTail", "gapMetrics"].filter(+ (k) => typeof window.__heavyThread[k] !== "function")"""+ )+ if missing:+ raise SystemExit(+ "the heavy-thread harness on this tree is missing "+ + ", ".join(missing)+ + "; see the module docstring."+ )+ plan = page.evaluate(+ "([c, t]) => window.__heavyThread.seedCompactTail(c, t)", [CHARS, TAIL]+ )+ page.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = plan["messages"],+ timeout = 180000,+ )+ page.wait_for_timeout(3000)+ for r in range(REPEATS):+ result = page.evaluate(RUN_JS, [plan["messages"], 6])+ samples = result["samples"]+ first = samples[0]+ # Empty band below the last mounted row, measured against the SETTLED value of the same+ # quantity, not zero: the bottom spacer and sticky footer leave a band either way.+ baseline = samples[-1]["gapBottom"]++ def netgap(s):+ return max(0, s["gapBottom"] - baseline)++ gap0 = netgap(first)+ # Time on screen, measured to the frame that CLOSES the gap rather than the last one+ # showing it, so a single-frame gap reads as that frame's duration and not 0ms.+ lingering = [s for s in samples if netgap(s) > 8]+ if lingering:+ closed = next(+ (s["t"] for s in samples if s["t"] > lingering[-1]["t"] and netgap(s) <= 8),+ samples[-1]["t"],+ )+ gap_ms = closed - lingering[0]["t"]+ else:+ gap_ms = 0+ rounds.append(+ {+ "firstPaintMs": first["t"],+ "firstRows": first["mountedRows"],+ "clientHeight": first["clientHeight"],+ "mountedHeight": first["mountedHeight"],+ "spacerHeight": first["spacerHeight"],+ "gapTop0": first["gapTop"],+ "gapBottom0": first["gapBottom"],+ "netGap0": gap0,+ "maxNetGap": max(netgap(s) for s in samples),+ "gapPersistMs": gap_ms,+ "gapFrames": len(lingering),+ "framesToConverge": len(samples),+ "convergedMs": samples[-1]["t"],+ "finalRows": samples[-1]["mountedRows"],+ "finalNetGap": netgap(samples[-1]),+ }+ )+ if r == 0:+ (OUT / f"{LABEL}-{engine}-{height}-timeline.json").write_text(+ json.dumps(samples, indent = 1), encoding = "utf-8"+ )+ # First commit, on its own re-open so nothing is settled.+ page.evaluate(+ """async () => {+ const api = window.__heavyThread;+ api.closeThread();+ while (api.messageCount() !== 0) await window.__nextPaint();+ api.openThread();+ while (api.messageCount() === 0) await new Promise(r => requestAnimationFrame(r));+ }"""+ )+ page.screenshot(path = str(OUT / f"{LABEL}-{engine}-{height}-firstcommit.png"))+ out[height] = rounds+ # After every height, not once at the end: a browser dying on the tallest viewport used to+ # take every earlier measurement with it.+ (OUT / f"{LABEL}-{engine}-rounds.json").write_text(+ json.dumps(out, indent = 1), encoding = "utf-8"+ )+ context.close()+ browser.close()+ return out+++def main() -> int:+ vite = start_vite(PORT)+ try:+ wait_for_smoke_page(PAGE, "smoke-heavy-thread-main.tsx", proc = vite, info = info)+ results = {}+ with sync_playwright() as pw:+ for engine in ENGINES:+ info(f"engine {engine}")+ results[engine] = run_engine(pw, engine)+ path = OUT / f"{LABEL}-results.json"+ path.write_text(json.dumps(results, indent = 1), encoding = "utf-8")+ info(f"wrote {path}")+ for engine, byh in results.items():+ for height, rounds in byh.items():+ med = lambda k: sorted(r[k] for r in rounds)[len(rounds) // 2]+ info(+ f"{LABEL} {engine} h={height}: rows={med('firstRows')} "+ f"mounted={med('mountedHeight')}px client={med('clientHeight')}px "+ f"spacer={med('spacerHeight')}px netGap0={med('netGap0')}px "+ f"maxNetGap={med('maxNetGap')}px persist={med('gapPersistMs')}ms "+ f"frames={med('gapFrames')} converged={med('convergedMs')}ms "+ f"finalRows={med('finalRows')}"+ )+ finally:+ stop_process(vite)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/probe_progressive_anchor.py b/tests/studio/probe_progressive_anchor.pynew file mode 100644index 00000000000..a44cde74274--- /dev/null+++ b/tests/studio/probe_progressive_anchor.py@@ -0,0 +1,273 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does the page move under a reader who scrolls up while a long thread is still widening?++The #9016 re-open action leaves the viewport pinned to the bottom, so it exercises only the branch+where the autoscroll hook already owns the correction. The branch with no other actor is the+DETACHED one: the user scrolls up the instant the thread opens and the widening keeps inserting+messages ABOVE them. If the correction there is wrong, or missing, what they are reading slides+down the page every widening frame: the regression Open WebUI shipped and reverted+(open-webui#23990).++The probe re-opens the thread, scrolls up hard on the frame the first row appears, then samples the+document-space top of a chosen visible message every frame until the thread has converged. A+correct build holds it still; a broken one shows it walking.++Not a gate. Prints and exits 0 on any measurement; exits non-zero only when the fixture did not+land, which would mean the numbers describe nothing.++It needs #9016's heavy-thread harness, which is not merged, so on this branch it exits with a+message naming the three files it is missing rather than running. That is the same dependency+every measurement in this PR has.++ SMOKE_PORT=5480 python tests/studio/probe_progressive_anchor.py+"""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+try:+ from playwright_heavy_thread import RECORDER_INIT # noqa: E402+except ModuleNotFoundError as exc: # pragma: no cover - the message IS the behaviour+ # #9016 is not merged, so its fixture files are absent and this import is where that becomes+ # visible. Say so instead of raising a bare ModuleNotFoundError, and do not vendor a copy: these+ # numbers are only comparable to #9016's while there is exactly one harness.+ raise SystemExit(+ "probe_progressive_anchor needs #9016's heavy-thread harness, which is not on this "+ "branch yet: tests/studio/playwright_heavy_thread.py plus "+ "studio/frontend/smoke-heavy-thread.{html,tsx}. Check out that branch, or copy those "+ "three files in, and run this again."+ ) from exc+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5480"))+BASE = f"http://127.0.0.1:{PORT}"+PAGE = f"{BASE}/smoke-heavy-thread.html"+CHARS = int(os.environ.get("SMOKE_HEAVY_CHARS", "300000"))+REPEATS = int(os.environ.get("SMOKE_ANCHOR_REPEATS", "3"))+LABEL = os.environ.get("SMOKE_LABEL", "tree")+OUT = Path(os.environ.get("PW_ART_DIR", "logs/progressive-anchor"))+OUT.mkdir(parents = True, exist_ok = True)++# How far up to scroll on the frame the thread comes back. Two viewports puts the reader clear of+# the bottom, so the hook's follow window is disarmed rather than merely expired.+SCROLL_UP_PX = int(os.environ.get("SMOKE_ANCHOR_SCROLL_PX", "4000"))+SETTLE_MS = int(os.environ.get("SMOKE_ANCHOR_SETTLE_MS", "8000"))+++def info(message: str) -> None:+ print(f"[anchor] {message}", flush = True)+++# Stage 1, in the page: unmount and re-open, returning as soon as the first row paints so the caller+# can scroll up while the widening is still in flight.+REOPEN_JS = """+async () => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ const before = api.messageCount();+ if (!before || !viewport) return null;+ api.closeThread();+ while (api.messageCount() !== 0) await window.__nextPaint();+ api.openThread();+ while (api.messageCount() === 0) await window.__nextPaint();+ const mountedAtFirstPaint = api.messageCount();++ // Wait for the FIRST widening to land before handing control back to scroll up.+ //+ // Re-opening a thread pins it to the bottom, and that pin arrives a beat after the first row+ // paints: the viewport element is new, so the hook's fresh-attach path scrolls to the bottom and+ // opens a follow window, and thread.initialize pins again on top of that. A wheel issued before+ // those land is simply undone by them, and the probe then measures the pinned branch while+ // believing it measured the detached one. The first two versions of this probe did exactly that+ // and its own end-of-run guard is what caught it.+ const deadline = performance.now() + 4000;+ while (api.messageCount() <= mountedAtFirstPaint && performance.now() < deadline) {+ await window.__nextPaint();+ }+ return {+ before,+ mountedAtFirstPaint,+ mountedBeforeScroll: api.messageCount(),+ widenedBeforeScroll: api.messageCount() > mountedAtFirstPaint,+ };+}+"""++# Stage 3, in the page: pick an on-screen message and sample its position every frame until the+# thread converges. Document space (viewport offset plus scrollTop) is recorded alongside viewport+# space to isolate movement caused by rows inserted above.+SAMPLE_JS = """+async ([before, settleMs]) => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ if (!viewport) return null;+ const rows = () => Array.from(viewport.querySelectorAll("[data-role]"));+ const anchor = rows().find((el) => {+ const box = el.getBoundingClientRect();+ return box.bottom > 0 && box.top < viewport.clientHeight;+ }) || rows()[0];+ if (!anchor) return null;++ // THE headline is viewport space, because "did the page move under the reader" is a question+ // about where the message is on their screen. Document space is recorded alongside it as+ // context and MUST move: rows inserted above an element move it down the document by exactly+ // their height, whether or not the viewport was corrected. Reading document space as the+ // headline is the mistake the first version of this probe made, and it reported a 110,625px+ // drift on a build that had not moved anything on screen at all.+ const screenTop = () => anchor.getBoundingClientRect().top;+ const docTop = () => anchor.getBoundingClientRect().top + viewport.scrollTop;+ const samples = [];+ const docSamples = [];+ const mounted = [];+ const start = performance.now();+ const first = screenTop();+ const firstDoc = docTop();+ let previous = first;+ let worstStep = 0;+ const mountedAtSampleStart = api.messageCount();+ while (performance.now() - start < settleMs) {+ await window.__nextPaint();+ const now = screenTop();+ const step = Math.abs(now - previous);+ if (step > worstStep) worstStep = step;+ samples.push(Math.round(now - first));+ docSamples.push(Math.round(docTop() - firstDoc));+ mounted.push(api.messageCount());+ previous = now;+ if (api.messageCount() >= before && performance.now() - start > 600) break;+ }++ return {+ before,+ mountedAtSampleStart,+ mountedAtEnd: api.messageCount(),+ totalDriftPx: Math.round(previous - first),+ worstFramePx: Math.round(worstStep),+ documentShiftPx: Math.round(docTop() - firstDoc),+ // Did the sampling window actually contain a widening? If the thread was already whole before+ // the first sample there was nothing to hold still and the repetition proves nothing.+ caughtWidening: mountedAtSampleStart < before,+ scrollTopAtEnd: Math.round(viewport.scrollTop),+ distanceFromBottom: Math.round(+ viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight),+ frames: samples.length,+ trace: samples.slice(0, 40),+ docTrace: docSamples.slice(0, 40),+ mountedTrace: mounted.slice(0, 40),+ };+}+"""+++def main() -> int:+ info(f"starting vite dev server on port {PORT}")+ vite = start_vite(PORT)+ results: list[dict] = []+ try:+ wait_for_smoke_page(PAGE, "smoke-heavy-thread-main.tsx", proc = vite, info = info)+ with sync_playwright() as p:+ browser = p.chromium.launch(headless = True, args = chromium_launch_args())+ context = browser.new_context(viewport = {"width": 1280, "height": 900})+ # Reuse #9016's instrumentation: __nextPaint is the double-rAF this samples on, and it+ # must be the SAME clock the re-open column uses or the numbers are not comparable.+ context.add_init_script(RECORDER_INIT)+ page = context.new_page()+ page.goto(PAGE, wait_until = "domcontentloaded")+ page.wait_for_function("() => Boolean(window.__heavyThread)", timeout = 60_000)+ plan = page.evaluate("(n) => window.__heavyThread.seed(n)", CHARS)+ page.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = plan["messages"],+ timeout = 300_000,+ )+ page.evaluate("() => window.__heavyThread.expandTools()")+ for repetition in range(1, REPEATS + 1):+ info(f"repetition {repetition}/{REPEATS}")+ opened = page.evaluate(REOPEN_JS)+ if opened is None:+ info("fixture did not land")+ return 1+ # A REAL wheel from the input pipeline, over a message rather than the scroll+ # container. A synthetic dispatchEvent on the viewport does not detach: the hook+ # asks innerScrollWillConsumeUpward(e.target) whether something nested will consume+ # the gesture, and an event dispatched ON the viewport answers about the viewport+ # itself. The first version did that and its own guard caught it.+ if not opened["widenedBeforeScroll"]:+ info("no widening landed before the scroll; the fixture is not long enough")+ return 1+ page.mouse.move(640, 450)+ page.mouse.wheel(0, -SCROLL_UP_PX)+ # The viewport is scroll-smooth, so the wheel animates. Let it finish or the first+ # samples record the probe's own gesture as drift.+ page.wait_for_function(+ """() => {+ const el = window.__heavyThread.viewport();+ const settled = window.__anchorTop === el.scrollTop;+ window.__anchorTop = el.scrollTop;+ return settled;+ }""",+ timeout = 10_000,+ )+ out = page.evaluate(SAMPLE_JS, [opened["before"], SETTLE_MS])+ if out is None:+ info("fixture did not land")+ return 1+ out["mountedAtFirstPaint"] = opened["mountedAtFirstPaint"]+ out["mountedBeforeScroll"] = opened["mountedBeforeScroll"]+ results.append(out)+ browser.close()+ finally:+ stop_process(vite)+ info("vite stopped")++ payload = {"label": LABEL, "chars": CHARS, "repetitions": results}+ (OUT / f"{LABEL}.json").write_text(json.dumps(payload, indent = 2), encoding = "utf-8")++ print()+ print(+ f"{'rep':>4} {'caught':>7} {'mounted@1st':>13} {'ON SCREEN drift':>16} "+ f"{'worst frame':>12} {'document shift':>15} {'dist from bottom':>17}"+ )+ for i, r in enumerate(results, 1):+ print(+ f"{i:>4} {str(r['caughtWidening']):>7} "+ f"{r['mountedAtFirstPaint']:>5} of {r['before']:<5} "+ f"{r['totalDriftPx']:>16} {r['worstFramePx']:>12} "+ f"{r['documentShiftPx']:>15} {r['distanceFromBottom']:>17}"+ )+ print()+ info(f"wrote {OUT / f'{LABEL}.json'}")++ # The only failure asserted: it must have caught what it claims to measure.+ if not any(r["caughtWidening"] for r in results):+ info(+ "PROBE-BROKEN the thread was already whole at the first paint in every repetition, so "+ "nothing was held still and these numbers describe nothing"+ )+ return 1+ if any(r["distanceFromBottom"] < 200 for r in results):+ info(+ "PROBE-BROKEN a repetition ended within 200px of the bottom, so the reader was not "+ "detached and this measured the pinned branch instead"+ )+ return 1+ info("measurement only: no budgets are asserted here, so this exits 0 on any drift.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/probe_progressive_reflow.py b/tests/studio/probe_progressive_reflow.pynew file mode 100644index 00000000000..ca6450b4a1e--- /dev/null+++ b/tests/studio/probe_progressive_reflow.py@@ -0,0 +1,176 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does content above a detached reader move when it relayouts for a reason that is NOT a widening?++While the mount window is open the viewport has native scroll anchoring disabled, so nothing in+the browser absorbs a `<pre>` swapping in Shiki output, a KaTeX resize or an image landing. This+injects one such reflow of a known size and measures whether the reader moves.++Measured with it: 600px injected above a detached reader mid-build-in moved them the full 600px+before the between-widenings compensation existed, and 0px after, against 0px on the merge base.+Its own first two versions measured nothing, once by sampling before the probe's own smooth-scroll+had finished (4332px of "drift" on both arms) and once by anchoring on the topmost row rather than+a visible one, so read the guards as load-bearing.++Not a gate. Prints and exits 0 on any measurement.++ SMOKE_PORT=5719 python3 tests/studio/probe_progressive_reflow.py++Needs #9016's heavy-thread harness, the same dependency probe_progressive_anchor.py has.+"""++from __future__ import annotations+import json, os, sys+from pathlib import Path+from playwright.sync_api import sync_playwright++TREE = Path(os.environ.get("PM_TREE", Path(__file__).resolve().parents[2])).resolve()+sys.path.insert(0, str(TREE / "tests" / "studio"))+try:+ from playwright_heavy_thread import RECORDER_INIT # noqa: E402+except ModuleNotFoundError as exc: # pragma: no cover - the message IS the behaviour+ raise SystemExit(+ "probe_progressive_reflow needs #9016's heavy-thread harness, which is not on this "+ "branch yet: tests/studio/playwright_heavy_thread.py plus "+ "studio/frontend/smoke-heavy-thread.{html,tsx}."+ ) from exc+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5719"))+PAGE = f"http://127.0.0.1:{PORT}/smoke-heavy-thread.html"+CHARS = int(os.environ.get("SMOKE_HEAVY_CHARS", "300000"))+REPEATS = int(os.environ.get("PM_REPEATS", "3"))+LABEL = os.environ.get("PM_LABEL", "reflow")+GROW_PX = int(os.environ.get("PM_GROW_PX", "600"))+OUT = Path(os.environ.get("PW_ART_DIR", "logs/pm_probe"))+OUT.mkdir(parents = True, exist_ok = True)+++def info(m: str) -> None:+ print(f"[pm-reflow] {m}", flush = True)+++# Re-open, scroll the reader up, grow one row ABOVE them by a known amount while the window is+# still open, and watch the row they are looking at.+RUN_JS = """+async ([growPx, settleMs]) => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ const before = api.messageCount();+ if (!before || !viewport) return null;+ api.closeThread();+ while (api.messageCount() !== 0) await window.__nextPaint();+ api.openThread();+ while (api.messageCount() === 0) await window.__nextPaint();+ const mountedAtFirstPaint = api.messageCount();+ // Let one widening land so the window is demonstrably open and mid-build.+ const deadline = performance.now() + 6000;+ while (api.messageCount() <= mountedAtFirstPaint && performance.now() < deadline) {+ await window.__nextPaint();+ }+ return { before, mountedAtFirstPaint, mounted: api.messageCount() };+}+"""++GROW_JS = """+async ([growPx, settleMs, before]) => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ const rows = () => Array.from(viewport.querySelectorAll("[data-role]"));+ const onScreen = rows().find((el) => {+ const b = el.getBoundingClientRect();+ return b.bottom > 0 && b.top < viewport.clientHeight;+ });+ if (!onScreen) return null;+ const above = rows().filter((el) => el.getBoundingClientRect().bottom <= 0);+ const target = above[above.length - 1];+ if (!target) return { skipped: "no row above the fold" };+ const screenTop = () => onScreen.getBoundingClientRect().top;+ const first = screenTop();+ const startedMounted = api.messageCount();+ // The reflow: one row above the reader gets taller, exactly as a <pre> does when Shiki's+ // highlighted output replaces the plain one.+ target.style.paddingTop = `${growPx}px`;+ await window.__nextPaint();+ await window.__nextPaint();+ const afterTwoFrames = screenTop() - first;+ const t0 = performance.now();+ while (performance.now() - t0 < settleMs) await window.__nextPaint();+ return {+ before,+ startedMounted,+ endedMounted: api.messageCount(),+ windowWasOpen: startedMounted < before,+ growPx,+ driftAfterTwoFrames: Math.round(afterTwoFrames),+ driftAtEnd: Math.round(screenTop() - first),+ distanceFromBottom: Math.round(+ viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight),+ };+}+"""+++def main() -> int:+ vite = start_vite(PORT)+ out = {"label": LABEL, "tree": str(TREE), "growPx": GROW_PX, "reps": []}+ try:+ wait_for_smoke_page(PAGE, "smoke-heavy-thread-main.tsx", proc = vite, info = info)+ with sync_playwright() as p:+ b = p.chromium.launch(headless = True, args = chromium_launch_args())+ ctx = b.new_context(viewport = {"width": 1280, "height": 900})+ ctx.add_init_script(RECORDER_INIT)+ pg = ctx.new_page()+ pg.goto(PAGE, wait_until = "domcontentloaded")+ pg.wait_for_function("() => Boolean(window.__heavyThread)", timeout = 120_000)+ plan = pg.evaluate("(n) => window.__heavyThread.seed(n)", CHARS)+ pg.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = plan["messages"],+ timeout = 300_000,+ )+ pg.evaluate("() => window.__heavyThread.expandTools()")+ for i in range(REPEATS):+ info(f"repetition {i+1}/{REPEATS}")+ opened = pg.evaluate(RUN_JS, [GROW_PX, 2000])+ pg.mouse.move(640, 450)+ pg.mouse.wheel(0, -4000)+ # The viewport is scroll-smooth, so the wheel animates. Let it finish or the probe+ # measures its own gesture: the first version reported 4332px on BOTH arms.+ pg.wait_for_function(+ """() => { const el = window.__heavyThread.viewport();+ const settled = window.__rfTop === el.scrollTop;+ window.__rfTop = el.scrollTop; return settled; }""",+ timeout = 15_000,+ )+ r = pg.evaluate(GROW_JS, [GROW_PX, 2500, opened["before"]])+ r["mountedAtFirstPaint"] = opened["mountedAtFirstPaint"]+ out["reps"].append(r)+ b.close()+ finally:+ stop_process(vite)+ info("vite stopped")+ (OUT / f"{LABEL}.json").write_text(json.dumps(out, indent = 2), encoding = "utf-8")+ print()+ print(+ f"{'rep':>4} {'windowOpen':>11} {'mounted':>16} {'grewBy':>7} {'drift 2f':>9} {'drift end':>10} {'distBottom':>11}"+ )+ for i, r in enumerate(out["reps"], 1):+ if not r or "skipped" in r:+ print(f"{i:>4} {r}")+ continue+ print(+ f"{i:>4} {str(r['windowWasOpen']):>11} {r['startedMounted']:>6} of {r['before']:<6} "+ f"{r['growPx']:>7} {r['driftAfterTwoFrames']:>9} {r['driftAtEnd']:>10} {r['distanceFromBottom']:>11}"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_heavy_thread_measurement_integrity.py b/tests/studio/test_heavy_thread_measurement_integrity.pyindex e4feb78bbb9..aa35990a639 100644--- a/tests/studio/test_heavy_thread_measurement_integrity.py+++ b/tests/studio/test_heavy_thread_measurement_integrity.py@@ -811,10 +811,19 @@ def floor_row(}-def test_reopen_declares_the_one_paint_floor_it_pays() -> None:- """Reopen is driven by a React state update, so the count check straight after openThread()- always still sees the unmounted tree and the loop always waits at least one paint."""- assert HARNESS.declared_floor("reopen ms") == 1+def test_reopen_subtracts_only_the_observation_floor() -> None:+ """A CONSTANT, and one. Reopen is driven by a React state update, so the count check straight+ after openThread() always still sees the unmounted tree and the loop always waits out one+ paint before a finished reopen can be observed at all. That wait is the instrument.++ Every further wait is not. The poll shares the rAF queue with the application's own commits,+ so on a progressive-mount build those waits are the application mounting rows and the time in+ them is real convergence latency. Reading the measured `paintWaits` here subtracted all of+ them, which is a subtraction that grows with thread size and differs between the two arms of+ a comparison -- it removed ~800ms from one arm's 300K cell and ~33ms from the other's."""+ floored = HARNESS.declared_floor("reopen ms")+ assert not callable(floored), "reopen ms reads its floor from the row again"+ assert floored == 1 == HARNESS.REOPEN_OBSERVATION_FLOOR, flooreddef test_a_matching_floor_declaration_is_accepted() -> None:@@ -822,14 +831,44 @@ def test_a_matching_floor_declaration_is_accepted() -> None:assert HARNESS.floor_declaration_problems(floor_row(1)) == []-def test_a_floor_declared_below_the_waits_paid_is_rejected() -> None:- problems = HARNESS.floor_declaration_problems(floor_row(2))- assert len(problems) == 1 and "subtracts 1" in problems[0], problems+def test_a_multi_commit_reopen_is_not_a_mis_declared_floor() -> None:+ """The progressive mount window mounts a long thread over several frames, so `ms` -- which+ runs until messageCount() reaches `before` -- spans one paint wait per widening commit. Ten is+ an ordinary reading at 100K, not a harness fault, and reporting it as one stops the run after+ every measurement has already been taken."""+ assert HARNESS.floor_declaration_problems(floor_row(10)) == []-def test_a_floor_declared_above_the_waits_paid_is_rejected() -> None:+def test_subtracting_a_floor_the_reopen_never_paid_is_a_failure() -> None:+ """The other side of the lower bound. Equality is no longer required, so the check has to+ still catch the direction that invents time: a cell whose reopen resolved without waiting a+ paint at all, while the axis removes one."""problems = HARNESS.floor_declaration_problems(floor_row(0))- assert len(problems) == 1 and "paid 0 paint wait" in problems[0], problems+ assert len(problems) == 1 and "never waited out" in problems[0], problems+++def test_the_progressive_mount_frames_stay_in_the_reopen_number() -> None:+ """End to end, and the regression this file exists to hold.++ Two arms of one comparison at the same size: a single-commit build that pays one wait and a+ progressive-mount build that pays twenty-four for the same 220 messages. Subtracting the+ measured count made the slower arm read as the faster one. Only the shared observation floor+ comes out, so the arms stay ordered the way the clock ordered them."""+ pick = next(p for name, p, _f in HARNESS.GROWTH_AXES if name == "reopen ms")+ floored = HARNESS.declared_floor("reopen ms")++ def cell(ms: float, waits: int) -> dict:+ return {"paint_floor_ms": 33.3, "actions": {"reopen": {"ms": ms, "paintWaits": waits}}}++ def value(ms: float, waits: int) -> float:+ row = cell(ms, waits)+ return round(pick(row) - HARNESS.resolve_floor(floored, row) * row["paint_floor_ms"], 1)++ single_commit = value(2184.1, 1)+ progressive = value(2329.7, 24)+ assert single_commit == 2150.8, single_commit+ assert progressive == 2296.4, progressive+ assert progressive > single_commit, (progressive, single_commit)def test_an_unreported_wait_count_is_a_failure_not_a_skip() -> None:@@ -1284,7 +1323,31 @@ def test_whole_window_axes_use_the_measured_floor(name) -> None:assert floored({"actions": {action: {"paint_waits": 20}}}) == 20[email protected]("name", ("jump painted ms", "menu open+close ms", "reopen ms"))+def test_reopen_is_a_partial_window_axis_with_a_constant_floor() -> None:+ """Reopen is the third kind, and it is neither of the two below.++ `ms` is measured from `reopenStarted`, so it does not span the recorder window and cannot take+ the window's `paint_waits`. It cannot take its own `paintWaits` either, because that count is+ a property of how many frames the APPLICATION took to mount, which is the thing the axis is+ measuring. What it carries is one observation wait, always, on every build.+ """+ floored = axis_floor("reopen ms")+ assert not callable(floored), "reopen ms reads a per-row wait count again"+ assert floored == HARNESS.REOPEN_OBSERVATION_FLOOR == 1, floored+++def test_the_reopen_wall_axis_does_not_take_the_window_count_either() -> None:+ """`reopen wall ms` spans the close loop and the reopen loop, so the window's `paint_waits`+ carries the progressive mount's commit frames for the same reason `reopen ms` does. Its+ honest floor is the two terminal observation waits, one per loop. Every other action keeps+ the measured window count, where those waits really are harness idle between driven steps."""+ floored = axis_floor("reopen wall ms")+ assert not callable(floored), "reopen wall ms reads the window count again"+ assert floored == 2, floored+ assert callable(axis_floor("scroll wall ms")), "the other wall axes lost their measured floor"++[email protected]("name", ("jump painted ms", "menu open+close ms"))def test_partial_window_axes_keep_their_declared_floor(name) -> None:"""The other half of the rule, and it is not symmetry for its own sake.