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: mount only the messages near the reader in long chats (#17504)
Wasim Yousef Saidd6841bbe96f1
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 50277d50570..5e7d21c9dc2 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -41,6 +41,7 @@ on:- 'tests/studio/playwright_user_message_time.py'- 'tests/studio/playwright_progressive_rows.py'- 'tests/studio/playwright_long_chat_renders.py'+ - 'tests/studio/playwright_thread_window.py'- 'tests/studio/playwright_long_thread_gate.py'- 'tests/studio/_css_culprit.py'- 'tests/studio/test_css_culprit.py'@@ -106,6 +107,7 @@ on:- 'tests/studio/playwright_user_message_time.py'- 'tests/studio/playwright_progressive_rows.py'- 'tests/studio/playwright_long_chat_renders.py'+ - 'tests/studio/playwright_thread_window.py'- 'tests/studio/playwright_long_thread_gate.py'- 'tests/studio/_css_culprit.py'- 'tests/studio/test_css_culprit.py'@@ -611,6 +613,13 @@ jobs:timeout-minutes: 5run: python3 tests/studio/playwright_long_chat_renders.py+ # Structure, not timings: a long thread mounts only the rows near the reader, and scrolling,+ # jumping, copying and a streamed reply must not show it.+ - name: Browser check for the windowed thread+ working-directory: ${{ github.workspace }}+ timeout-minutes: 10+ run: python3 tests/studio/playwright_thread_window.py+# Render counts, not timings: a search keystroke or a quant probe answer in the model# picker's On Device tab must not re-render every row, and the rows must still navigate.- name: Browser check for model picker re-rendersdiff --git a/.github/workflows/studiobench-ci.yml b/.github/workflows/studiobench-ci.ymlindex d939c9bd1dc..a1c6c04ee12 100644--- a/.github/workflows/studiobench-ci.yml+++ b/.github/workflows/studiobench-ci.yml@@ -225,12 +225,14 @@ jobs:# Pass the bootstrap password explicitly: an attached studiobench cannot find the home.# 100K is the smallest rung where every action except image_upload runs.+ # --windowed-arm: the thread mounts only the rows near the reader (thread-window.ts).- name: Run a real-path sessionrun: |python -m tests.studio.studiobench \--tier fast --rungs 100K --reps 1 \--attach "http://127.0.0.1:${STUDIO_PORT}" \--password "$(cat ~/.unsloth/studio/auth/.bootstrap_password)" \+ --windowed-arm base \--engine chromium \--out outputs/studiobench-cidiff --git a/.github/workflows/studiobench-ui-parity.yml b/.github/workflows/studiobench-ui-parity.ymlindex 73b9811a13b..c3eeca8f8d7 100644--- a/.github/workflows/studiobench-ui-parity.yml+++ b/.github/workflows/studiobench-ui-parity.yml@@ -301,7 +301,8 @@ jobs:PY# --reps 2 is load-bearing: derive_unstable needs 2 observations, else the measured set is- # empty and scoring silently falls back to the declared list.+ # empty and scoring silently falls back to the declared list. --windowed-arm on both sides:+ # a thread may mount only the rows near the reader; a fully mounted side is unaffected.- name: Drive both sides through one sessiontimeout-minutes: 9run: |@@ -314,6 +315,7 @@ jobs:--ab "${{ steps.refs.outputs.side_b }}" \--password "$PASSWORD_a" \--password-b "$PASSWORD_b" \+ --windowed-arm base,treatment \--engine chromium \--parity-shots "$SHOT_DIR" \--out "$OUT_DIR"diff --git a/studio/frontend/smoke-heavy-thread-main.tsx b/studio/frontend/smoke-heavy-thread-main.tsxindex 5abbd4890c6..ebf80cf5def 100644--- a/studio/frontend/smoke-heavy-thread-main.tsx+++ b/studio/frontend/smoke-heavy-thread-main.tsx@@ -4,6 +4,7 @@// Harness for tests/studio/playwright_heavy_thread.py: real Thread with a heavy thread built in// whole cycles of mixed content; local runtime since delete uses thread.export/import.+import { holdProgressiveMounts } from "@/components/assistant-ui/progressive-messages";import { Thread } from "@/components/assistant-ui/thread";import { TooltipProvider } from "@/components/ui/tooltip";import {@@ -24,6 +25,10 @@ import { type ReactElement, useEffect, useRef, useState } from "react";import { createRoot } from "react-dom/client";import "./src/index.css";+// This page takes a census of the whole thread and times actions against all of it, so every row+// stays mounted: the state an open find bar or a print puts the app in.+holdProgressiveMounts();+// Explicit allowlist, never a blanket `/api/` match: unlisted requests must trip the stray counter.const STUBBED_API: ReadonlyArray<readonly [RegExp, string]> = [// Fork-count badges, one GET per thread; answer with the real `{"counts":{}}` shape.diff --git a/studio/frontend/smoke-thread-weight-main.tsx b/studio/frontend/smoke-thread-weight-main.tsxindex 7b7077e7f37..b5fe7f9688d 100644--- a/studio/frontend/smoke-thread-weight-main.tsx+++ b/studio/frontend/smoke-thread-weight-main.tsx@@ -4,6 +4,10 @@// Harness for tests/studio/playwright_thread_weight.py: the real Thread and real markdown bodies,// seeded via thread.import on a local runtime (only it backs export/import used by delete).+import {+ hasPendingProgressiveMounts,+ holdProgressiveMounts,+} from "@/components/assistant-ui/progressive-messages";import { Thread } from "@/components/assistant-ui/thread";import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";import { TooltipProvider } from "@/components/ui/tooltip";@@ -32,9 +36,13 @@ import { watchModalPointerLock } from "./src/lib/modal-pointer-lock";// Answer ForkCountBadge GETs in-page: a Playwright-side answer would add a CDP round trip per// assistant message inside the timed region.const realFetch = window.fetch.bind(window);+const apiWrites: { url: string; body: string | null }[] = [];window.fetch = (input, init) => {const url = typeof input === "string" ? input : (input as Request).url ?? String(input);if (url.includes("/api/")) {+ if (init?.method && init.method !== "GET") {+ apiWrites.push({ url, body: typeof init.body === "string" ? init.body : null });+ }return Promise.resolve(new Response("{}", {status: 200,@@ -102,6 +110,9 @@ type SeedOptions = {* `sources` adds six URL source parts after every web_search call.*/agent?: { rounds: number; compactionEvery?: number; sources?: boolean; rich?: boolean };+ /** Each default reply also carries a numbered equation, which KaTeX counts page-wide, and+ * the same environments as code. */+ numbered?: boolean;};const AGENT_TOOLS = ["web_search", "terminal", "python"] as const;@@ -168,7 +179,15 @@ function buildMessages(if (index % 2 === 0) {return {role: "user" as const,- content: [{ type: "text" as const, text: userMarkdown(index) }],+ content: [+ {+ type: "text" as const,+ // A prompt shows math source as text, so these take no number.+ text:+ userMarkdown(index) ++ (options?.numbered ? "\n\n$$\\begin{equation}p=1\\end{equation}$$" : ""),+ },+ ],};}if (agent) {@@ -200,7 +219,13 @@ function buildMessages(type: "text" as const,text: isPlain((index - 1) / 2, options)? plainAssistantMarkdown(index)- : assistantMarkdown(index),+ : assistantMarkdown(index) ++ (options?.numbered+ ? `\n\n$$\n\\begin{equation}E_{${index}} = mc^2\\end{equation}\n$$` ++ "\n\n$$\n\\begin{align}f &= \\begin{cases}1\\\\0\\end{cases}\\\\ g &= 2\\end{align}\n$$" ++ // Examples, not math: they render verbatim and take no number.+ "\n\n```latex\n\\begin{equation}x\\end{equation}\n```\n\nInline `\\begin{align}a\\end{align}` too."+ : ""),},],};@@ -290,6 +315,24 @@ function ThreadWeightApi({messageCount(): number {return document.querySelectorAll("[data-role]").length;},+ /** Opens the last user prompt's editor; returns its message id. */+ editLastPrompt(): string | null {+ const messages = aui.thread().getState().messages;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ if (messages[index].role !== "user") continue;+ aui.thread().message({ index }).composer().beginEdit();+ return messages[index].id;+ }+ return null;+ },+ /** The conversation's length, where messageCount() is how much of it is mounted. */+ threadLength(): number {+ return aui.thread().getState().messages.length;+ },+ /** What the turn rail waits on before it renders: a full mount still under way. */+ pendingMounts(): boolean {+ return hasPendingProgressiveMounts();+ },counts(): {messages: number;assistantMessages: number;@@ -333,6 +376,10 @@ function ThreadWeightApi({viewport(): HTMLElement | null {return document.querySelector<HTMLElement>(".aui-thread-viewport");},+ /** Non-GET /api/ calls the stub above answered. */+ apiWrites(): { url: string; body: string | null }[] {+ return apiWrites;+ },composer(): HTMLTextAreaElement | null {return document.querySelector<HTMLTextAreaElement>(".aui-composer-input",@@ -377,6 +424,13 @@ function ThreadWeightApi({return null;}+// The checks on this page measure what a whole thread costs in the DOM (the state an open find bar+// or a print puts the app in), so every row stays mounted. `?window=1` leaves the thread as the+// app opens it: only the rows near the reader are mounted.+if (new URLSearchParams(window.location.search).get("window") !== "1") {+ holdProgressiveMounts();+}+// `?shell=1`: the ancestors the app puts around the thread (root layout + chat page), so CSS// anchored on them (e.g. a `:has()` on the wallpaper workspace) runs here as it does in Studio.const SHELL = new URLSearchParams(window.location.search).get("shell") === "1";diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 15a2ddbf0e2..3326d90e37c 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -88,7 +88,7 @@ import { AnimatePresence, motion } from "motion/react";import {type ComponentType,lazy,-+ memo,type ReactNode,Suspense,useCallback,@@ -228,6 +228,24 @@ function ChatPage(props: ChatPageProps) {);}+// The layout re-renders on its own state (the Settings flag gating every route shortcut, a route+// change): without these, each of those re-rendered the sidebar, the navbar and the whole chat+// page with it. A component that takes no props is one element, made once: React skips a subtree+// whose element is the one it rendered last. Neither form adds a fiber level, so the useId paths+// the reload snapshot relies on are unchanged.+const appSidebar = <AppSidebar />;+const navbar = <Navbar />;+const commandPalette = <CommandPalette />;+const hfTokenWarningDialog = <HfTokenWarningDialog />;+const remoteCodeConsentDialog = <RemoteCodeConsentDialog />;+const downloadApprovalDialog = <DownloadApprovalDialog />;+const transformersUpgradeDialog = <TransformersUpgradeDialog />;+const managedEngineOfferDialog = <ManagedEngineOfferDialog />;+const llmCompressorConsentDialog = <LlmCompressorConsentDialog />;+const stopRunningChatsDialog = <StopRunningChatsDialog />;+const imageViewer = <ImageViewer />;+const ChatPageSlot = memo(ChatPage);+const ImagesPage = lazy(() =>import("@/features/images").then((m) => ({ default: m.ImagesPage })),);@@ -702,15 +720,15 @@ function RootLayout() {{!isAuthFlowRoute && <ChatSettingsHydrationMount />}{!isAuthFlowRoute && <LowDiskNoticeMount />}{!isAuthFlowRoute && <ApiMonitorOverlay />}- <HfTokenWarningDialog />- <RemoteCodeConsentDialog />- <DownloadApprovalDialog />- <TransformersUpgradeDialog />- <ManagedEngineOfferDialog />- <LlmCompressorConsentDialog />- <StopRunningChatsDialog />- <ImageViewer />- {!hideNavbar && <CommandPalette />}+ {hfTokenWarningDialog}+ {remoteCodeConsentDialog}+ {downloadApprovalDialog}+ {transformersUpgradeDialog}+ {managedEngineOfferDialog}+ {llmCompressorConsentDialog}+ {stopRunningChatsDialog}+ {imageViewer}+ {!hideNavbar && commandPalette}{hideNavbar ? (<main className="h-dvh flex-1 overflow-y-auto pt-[var(--studio-hidden-route-top-inset,0px)] [--studio-titlebar-height:var(--studio-hidden-route-top-inset,0px)]"><RouteBoundary readyWhenCommitted={!routeOwnsReloadReadiness}>@@ -729,7 +747,7 @@ function RootLayout() {className="relative !min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden"><ChatBackground route={isChatRoute ? "chat" : "page"} backdrop />- <AppSidebar />+ {appSidebar}<SidebarEdgeTrigger />{windowsWallpaperPage && (<div@@ -749,7 +767,7 @@ function RootLayout() {: "mt-[var(--studio-non-chat-scroller-top,0px)] overflow-y-auto"}>- <Navbar />+ {navbar}<divref={findScopeRef}{...{ [FIND_SCOPE_ATTRIBUTE]: "" }}@@ -766,7 +784,7 @@ function RootLayout() {}inert={!isChatRoute || undefined}>- <ChatPage search={chatSearch} active={isChatRoute} />+ <ChatPageSlot search={chatSearch} active={isChatRoute} /></div>)}{shouldMountImages && (diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 3ab87483647..4ae0b91b930 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -700,6 +700,19 @@ function MermaidCopyButton({ source }: { source: string }) {);}+/** A block's own wrap and expand choices, by language and code: the thread window remounts rows+ * it scrolls back to, and the choices would otherwise reset with the component. */+const blockViews = new Map<string, { wrapped?: boolean; expanded?: boolean }>();+const BLOCK_VIEWS_MAX = 500;++function rememberBlockView(key: string | null, view: { wrapped?: boolean; expanded?: boolean }) {+ if (key === null) return;+ const next = { ...blockViews.get(key), ...view };+ blockViews.delete(key);+ blockViews.set(key, next);+ if (blockViews.size > BLOCK_VIEWS_MAX) blockViews.delete(blockViews.keys().next().value as string);+}+export function CodeBlockActions({disabled,language,@@ -714,12 +727,23 @@ export function CodeBlockActions({}) {const { copied, showCopied } = useCopiedState();const actionsRef = useRef<HTMLDivElement>(null);+ const viewKey = wrappable && typeof source === "string" ? `${language ?? ""}\n${source}` : null;+ const remembered = viewKey === null ? undefined : blockViews.get(viewKey);// Starts from Appearance > Code > Word wrap; the toggle overrides it for this block only.const [wrapped, setWrapped] = useState(- () => typeof document !== "undefined" && document.documentElement.hasAttribute("data-code-wrap"),+ () =>+ remembered?.wrapped ??+ (typeof document !== "undefined" && document.documentElement.hasAttribute("data-code-wrap")),);const wrapLabel = wrapped ? "Disable word wrap" : "Enable word wrap";- const [expanded, setExpanded] = useState(false);+ const [expanded, setExpanded] = useState(() => remembered?.expanded ?? false);+ // biome-ignore lint/correctness/useExhaustiveDependencies: restores a remembered view once, on mount+ useLayoutEffect(() => {+ const wrapper = actionsRef.current?.parentElement;+ if (!wrapper || !remembered) return;+ if (remembered.wrapped !== undefined) wrapper.setAttribute("data-wrap", remembered.wrapped ? "on" : "off");+ if (remembered.expanded) wrapper.toggleAttribute("data-code-expanded", true);+ }, []);const [overflowing, setOverflowing] = useState(false);useEffect(() => {const wrapper = actionsRef.current?.parentElement;@@ -759,6 +783,7 @@ export function CodeBlockActions({const next = !wrapped;// The block is this bar's sibling; index.css keys the per-block wrap on the shared wrapper.actionsRef.current?.parentElement?.setAttribute("data-wrap", next ? "on" : "off");+ rememberBlockView(viewKey, { wrapped: next });setWrapped(next);}}>@@ -773,6 +798,7 @@ export function CodeBlockActions({onClick={() => {const next = !expanded;actionsRef.current?.parentElement?.toggleAttribute("data-code-expanded", next);+ rememberBlockView(viewKey, { expanded: next });setExpanded(next);}}>diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsxindex 5339af81449..1f94bb8ea08 100644--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx@@ -1,8 +1,8 @@// 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 glue; see progressive-mount-controller.ts. One shared propless slot-// element lets React skip unchanged rows; a components object would re-render every row.+// Thread window glue (maths in thread-window.ts). One shared propless slot element lets React+// skip unchanged rows; a components object would re-render every row.import { AuiProvider, useAui, useAuiState } from "@assistant-ui/react";import {@@ -13,6 +13,7 @@ import {startTransition,useCallback,useEffect,+ useInsertionEffect,useLayoutEffect,useMemo,useRef,@@ -24,36 +25,89 @@ import { createRowNotificationGate } from "@/components/assistant-ui/row-notificimport { MessageByIndexProvider } from "@/components/assistant-ui/stale-safe-scopes";import {type AnchorSample,- type MountWindow,CHUNK_MESSAGES,anchorCorrection,- alignAnchorCorrection,- initialWindow,nextMountChunk,watchProgressiveScroll,- widen,} from "@/components/assistant-ui/progressive-mount-controller";+import {+ type Expanded,+ type MountedRow,+ type RowMeta,+ type RowWindow,+ RowHeights,+ WINDOW_REACH_PX,+ absorbShift,+ followCount,+ holdTailTurn,+ initialRowWindow,+ numberedEquations,+ messageWeight,+ planEngage,+ planFill,+ planSlide,+ sameWindow,+ spacerHeights,+ spacerRows,+ threadSlots,+ withPins,+} from "@/components/assistant-ui/thread-window";import {type ThreadMessageRole,rendersAsRow,} from "@/components/assistant-ui/thread-message-slot";import { useAdjustForContentInsertedAbove } from "@/components/assistant-ui/use-intent-aware-autoscroll";-import { REACH as WINDOW_REACH } from "@/components/assistant-ui/message-window-controller";+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";import { inputPointerHeld } from "@/lib/input-pointer-state";import { isWebKitGTK } from "@/components/ui/theme-view-transition";const WEBKIT_GTK = typeof navigator !== "undefined"&& isWebKitGTK(navigator.platform, navigator.userAgent);-const MOUNT_CHUNK = WEBKIT_GTK ? 2 : CHUNK_MESSAGES;-const ANCHOR_PRECISION = WEBKIT_GTK ? 1 / 64 : 1;+/** WebKitGTK commits inside the frame, so it takes fewer rows per step. */+const SLIDE_STEP = WEBKIT_GTK ? 2 : 8;+const FILL_CHUNK = WEBKIT_GTK ? 2 : CHUNK_MESSAGES;+/** Sub-pixel shifts are real here: the spacer takes them, where scrollTop would round them. */+const ANCHOR_PRECISION = 1 / 64;+const FILL_RELEASE_MS = 3000;+const SETTLE_RETRY_MS = 350;+const HOLD_RECHECK_MS = 1000;+const FIND_FLAG = "data-find-bar-open";+// Not `[data-role]`: a prompt being edited renders as an EditComposer, which has no role.+const ROW_SELECTOR = "[data-message-id]";+const SPACER_ATTRIBUTE = "data-thread-spacer";+// An iframe (an inline MCP app) holds state and a bridge port a remount would lose.+const PINNED_CONTENT = "textarea, [contenteditable=true], iframe";/** Module-level: consumers are imperative DOM readers, and a thread can mount twice (Compare). */-interface ActiveCompleter {- complete: () => Promise<void>;+interface ActiveWindow {+ complete: (signal?: AbortSignal) => Promise<void>;+ reveal: (messageId: string) => boolean;+ withholding: () => boolean;+ filling: () => boolean;+ wake: () => void;viewportRef: RefObject<HTMLElement | null>;}-const activeCompleters = new Set<ActiveCompleter>();+const activeWindows = new Set<ActiveWindow>();+const rowListeners = new Set<() => void>();+const fullMountHolds = new Set<symbol>();++/** Keeps every row mounted until released, for a reader of the whole DOM over time. */+export function holdProgressiveMounts(): () => void {+ const hold = Symbol("full mount");+ fullMountHolds.add(hold);+ for (const entry of activeWindows) entry.wake();+ return () => {+ if (fullMountHolds.delete(hold)) for (const entry of activeWindows) entry.wake();+ };+}++export function subscribeMountedRows(listener: () => void): () => void {+ rowListeners.add(listener);+ return () => {+ rowListeners.delete(listener);+ };+}/** DOM readers (not store readers) must await this, or they see a short conversation. */export const PROGRESSIVE_MOUNT_SEARCH_MS = 400;@@ -61,33 +115,47 @@ export const PROGRESSIVE_MOUNT_SEARCH_MS = 400;export async function completeProgressiveMounts(/** Viewports to force; find-in-page passes one to skip inert off-route workspaces. */wants?: (viewport: HTMLElement | null) => boolean,+ /** A reader that stops waiting (Find closed) lets the window slide again at once. */+ signal?: AbortSignal,): Promise<void> {const wanted = () =>- wants === undefined- ? [...activeCompleters]- : [...activeCompleters].filter((entry) => wants(entry.viewportRef.current));- // An empty completer set is only believed after SEARCH_MS: a thread still loading history also- // looks empty. A set that was non-empty and drained is believed immediately.+ [...activeWindows].filter((entry) =>+ wants === undefined || wants(entry.viewportRef.current));+ // An empty set is only believed after SEARCH_MS: a thread still loading history also looks+ // empty. A set that was non-empty and drained is believed immediately.const deadline = Date.now() + PROGRESSIVE_MOUNT_SEARCH_MS;let observed = false;for (;;) {+ if (signal?.aborted) return;const pending = wanted();if (pending.length > 0) {observed = true;- await Promise.all(pending.map((entry) => entry.complete()));+ await Promise.all(pending.map((entry) => entry.complete(signal)));}await new Promise<void>((resolve) =>requestAnimationFrame(() => requestAnimationFrame(() => resolve())),);- // Filtered set: an unwanted completer would otherwise hold the loop open forever.- if (wanted().length === 0 && (observed || Date.now() >= deadline)) {+ // Filtered set: an unwanted window would otherwise hold the loop open forever.+ if (+ !wanted().some((entry) => entry.withholding()) &&+ (observed || Date.now() >= deadline)+ ) {return;}}}+/** A settled window or a hidden thread withholds rows without being pending. */export function hasPendingProgressiveMounts(): boolean {- return activeCompleters.size > 0;+ for (const entry of activeWindows) if (entry.filling()) return true;+ return false;+}++export function revealProgressiveRow(viewport: HTMLElement, messageId: string): boolean {+ for (const entry of activeWindows) {+ if (entry.viewportRef.current === viewport) return entry.reveal(messageId);+ }+ return false;}/** Clears only an empty inline declaration so the viewport carries no stray `style=""`. */@@ -176,312 +244,822 @@ type HeldAnchor = {rowSample: AnchorSample | null;};-/** Px from the viewport top up to the first mounted row's top; prepends land above it. */-function frontierAbove(viewport: HTMLElement | null): number | null {- const first = viewport?.querySelector("[data-role][data-message-id]");- if (!viewport || !first) return null;- return viewport.getBoundingClientRect().top - first.getBoundingClientRect().top;+type ThreadMessage = {+ id?: string;+ role?: ThreadMessageRole;+ content?: readonly { type?: string; text?: string }[];+ composer?: { isEditing?: boolean };+};++type Metas = {+ metas: RowMeta[];+ index: Map<string, number>;+ tailTurn: number;+};++const metaCache = new WeakMap<object, { expanded: Expanded; meta: RowMeta }>();++function metaOf(message: ThreadMessage, index: number, expanded: Expanded): RowMeta {+ const cached = metaCache.get(message);+ if (cached?.expanded === expanded) return cached.meta;+ const role = message.role ?? "assistant";+ // Unknown shapes count as rendering: room for a row that turns out empty costs nothing.+ const renders =+ message.role == null || rendersAsRow(message.role, message.composer?.isEditing === true);+ const meta: RowMeta = {+ id: message.id ?? `#${index}`,+ role,+ weight: messageWeight(message.content, expanded),+ // Only replies render markdown math: a prompt shows its source as text.+ equations: renders && role === "assistant" ? numberedEquations(message.content, expanded) : 0,+ renders,+ revision: message.content,+ };+ metaCache.set(message, { expanded, meta });+ return meta;}-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;+const metasCache = new WeakMap<readonly ThreadMessage[], { expanded: Expanded; derived: Metas }>();++function metasOf(messages: readonly ThreadMessage[], expanded: Expanded): Metas {+ const cached = metasCache.get(messages);+ if (cached?.expanded === expanded) return cached.derived;+ const metas = messages.map((message, at) => metaOf(message, at, expanded));+ const index = new Map<string, number>();+ let tailTurn = -1;+ metas.forEach((meta, at) => {+ index.set(meta.id, at);+ if (meta.role === "user" && meta.renders) tailTurn = at;+ });+ const derived = { metas, index, tailTurn };+ metasCache.set(messages, { expanded, derived });+ return derived;+}++const threadHeights = new Map<string, RowHeights>();+const REMEMBERED_THREADS = 8;++function heightsFor(key: string | undefined): RowHeights {+ if (key === undefined) return new RowHeights();+ let heights = threadHeights.get(key);+ if (heights) threadHeights.delete(key);+ else heights = new RowHeights();+ threadHeights.set(key, heights);+ if (threadHeights.size > REMEMBERED_THREADS) {+ const oldest = threadHeights.keys().next().value;+ if (oldest !== undefined) threadHeights.delete(oldest);+ }+ return heights;+}++type Measured = {+ rows: MountedRow[];+ threadTop: number;+};++function rowIndex(child: Element, lookup: Metas): number | undefined {+ if (!child.matches(ROW_SELECTOR)) return undefined;+ return lookup.index.get(child.getAttribute("data-message-id") ?? "");+}++/** Height = top to the top of what follows, so the margins between rows are counted. */+function measureRows(viewport: HTMLElement, lookup: Metas, heights: RowHeights): Measured {+ const origin = viewport.getBoundingClientRect().top;+ const rows: MountedRow[] = [];+ let threadTop: number | null = null;+ let open: MountedRow | null = null;+ let openRow: Element | null = null;+ const close = (height: number) => {+ if (!open || !openRow) return;+ const meta = lookup.metas[open.index];+ // A re-render that changed the row's equations changed its height too.+ if (heights.measure(meta, Math.max(0, height))) {+ heights.countEquations(meta, {+ html: openRow.querySelectorAll(".eqn-num").length,+ mathml: openRow.querySelectorAll(".mml-eqn-num").length,+ });+ }+ };+ for (const child of viewport.children) {+ const index = rowIndex(child, lookup);+ if (index === undefined && !child.hasAttribute(SPACER_ATTRIBUTE)) continue;+ const box = child.getBoundingClientRect();+ const top = box.top - origin;+ threadTop ??= top;+ if (open) close(top - open.top);+ open = null;+ if (index === undefined) continue;+ open = { index, top, bottom: box.bottom - origin };+ openRow = child;+ rows.push(open);+ }+ if (open) close(open.bottom - open.top);+ return { rows, threadTop: threadTop ?? 0 };+}++// A dialog opened from a row (an attachment viewer) is portaled out of it, so its focus and+// media are invisible to isPinned: while one is open, no mounted row is let go.+const OPEN_DIALOG = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]';++const EDITABLE = "input, textarea, [contenteditable=true]";++/** Every range: Firefox selects several at once with Ctrl-drag. */+function heldSelection(viewport: HTMLElement): Range[] | null {+ const selection = document.getSelection();+ if (selection === null || selection.isCollapsed) return null;+ const ranges: Range[] = [];+ for (let at = 0; at < selection.rangeCount; at += 1) {+ const range = selection.getRangeAt(at);+ if (range.intersectsNode(viewport)) ranges.push(range);+ }+ return ranges.length > 0 ? ranges : null;+}++function isPinned(row: Element, selection: Range[] | null): boolean {+ if (row.contains(document.activeElement)) return true;+ if (row.querySelector(PINNED_CONTENT) !== null) return true;+ if (selection?.some((range) => range.intersectsNode(row))) return true;+ for (const media of row.querySelectorAll<HTMLMediaElement>("video, audio")) {+ if (!media.paused) return true;+ }+ return false;+}++/** Appearance flags on the root that re-wrap rows without moving any root typography value. */+const LAYOUT_FLAGS = [+ "data-chat-font",+ "data-ui-font",+ "data-ui-font-size",+ "data-code-font-size",+ "data-code-wrap",+ "data-code-line-numbers",+ "data-code-no-ligatures",+];++/** What a row's wrapping depends on. The column, not the viewport: Chat width moves only the+ * column, and the appearance settings change no width at all. */+function rowLayout(row: HTMLElement): string {+ const style = getComputedStyle(row);+ const root = document.documentElement;+ return [+ row.clientWidth,+ style.fontFamily,+ style.fontSize,+ style.letterSpacing,+ style.getPropertyValue("--custom-code-font"),+ style.getPropertyValue("--custom-code-font-size"),+ LAYOUT_FLAGS.map((name) => (root.hasAttribute(name) ? "1" : "0")).join(""),+ ].join("\n");+}++/** Rows the reader is working in stay mounted where they are, apart from the window, so a jump+ * keeps an unsaved edit without mounting what lies between. `tail` is a reply being streamed. */+function keepPinned(+ viewport: HTMLElement,+ lookup: Metas,+ next: RowWindow,+ tail: number | null,+): RowWindow {+ const selection = heldSelection(viewport);+ const dialog = document.querySelector(OPEN_DIALOG) !== null;+ const pins: number[] = [];+ for (const child of viewport.children) {+ const index = rowIndex(child, lookup);+ if (index === undefined || (index >= next.start && index < next.end)) continue;+ if (dialog || index === tail || isPinned(child, selection)) pins.push(index);+ }+ return withPins(next, pins, lookup.metas.length);+}++/** WAI-ARIA ordinals for a windowed list. Written here, not by the rows: the total changes on+ * every append, and a row must not re-render for it. */+function publishOrdinals(viewport: HTMLElement, lookup: Metas, windowed: boolean): void {+ const total = String(lookup.metas.length);+ for (const child of viewport.children) {+ if (!child.matches(ROW_SELECTOR)) continue;+ const index = windowed+ ? lookup.index.get(child.getAttribute("data-message-id") ?? "")+ : undefined;+ if (index === undefined) {+ child.removeAttribute("aria-posinset");+ child.removeAttribute("aria-setsize");+ if (child.getAttribute("role") === "article") child.removeAttribute("role");+ continue;+ }+ // Ordinals need a role that supports them: a focusable message in a feed is an article.+ if (!child.hasAttribute("role")) child.setAttribute("role", "article");+ const position = String(index + 1);+ if (child.getAttribute("aria-posinset") !== position) {+ child.setAttribute("aria-posinset", position);+ }+ if (child.getAttribute("aria-setsize") !== total) child.setAttribute("aria-setsize", total);+ }}-function useProgressiveMountWindow(+function useThreadWindow(count: number,resetKey: string | undefined,viewportRef: RefObject<HTMLElement | null>,- alignmentRef: RefObject<HTMLDivElement | null>,-): MountWindow {+ topRef: RefObject<HTMLDivElement | null>,+ bottomRef: RefObject<HTMLDivElement | null>,+): {+ win: RowWindow | null;+ gapHeight: (from: number, to: number) => number;+ counterIncrement: (from: number, to: number) => string | undefined;+} {const aui = useAui();const adjustScroll = useAdjustForContentInsertedAbove();- const adjustForContentInsertedAbove = useCallback((shift: number) => {- const spacer = alignmentRef.current;- if (spacer) {- // WebKit rounds scrollTop. Align the inserted height instead of moving text- // between two fractional positions on every background prepend.- const aligned = alignAnchorCorrection(shift, Number.parseFloat(spacer.style.height) || 0);- spacer.style.height = `${aligned.inset}px`;- return adjustScroll(aligned.scroll);- }- return adjustScroll(shift);- }, [adjustScroll, alignmentRef]);- // Imperative, so run start/stop does not re-render and rebuild the row array.- const isRunningNow = useCallback(- () => aui.thread().getState().isRunning === true,- [aui],+ // Read imperatively: a useAuiState selector on messages would walk the thread every keystroke.+ const thinking = useChatPreferencesStore((state) => state.thinkingVisibility);+ const tools = useChatPreferencesStore((state) => state.toolVisibility);+ // One object per setting pair: the meta caches compare it by identity.+ const expanded = useMemo(+ (): Expanded => ({ reasoning: thinking === "expanded", tools: tools === "expanded" }),+ [thinking, tools],+ );+ const readMetas = useCallback(+ (): Metas =>+ metasOf(aui.thread().getState().messages as unknown as readonly ThreadMessage[], expanded),+ [aui, expanded],);- // Read imperatively: a useAuiState selector on messages would walk the thread every keystroke.- const renderableAt = useCallback(() => {- const messages = aui.thread().getState().messages as ReadonlyArray<{- role?: ThreadMessageRole;- composer?: { isEditing?: boolean };- }>;- return (index: number) => {- const message = messages[index];- // Unknown shapes count as renderable, degrading to the count-based window rather than none.- if (message?.role == null) return true;- return rendersAsRow(message.role, message.composer?.isEditing === true);- };- }, [aui]);+ const heights = useMemo(() => heightsFor(resetKey), [resetKey]);- const [mountWindow, setMountWindow] = useState<MountWindow>(() =>- initialWindow(count, isRunningNow(), renderableAt()),- );+ const open = useCallback((): RowWindow | null => {+ const { metas, tailTurn } = readMetas();+ const view = typeof window === "undefined" ? 900 : window.innerHeight;+ const opened = initialRowWindow(+ metas.length,+ (index) => heights.heightOf(metas[index]),+ view + WINDOW_REACH_PX,+ );+ return holdTailTurn(opened, metas.length, tailTurn);+ }, [readMetas, heights]);++ const [win, setWin] = useState<RowWindow | null>(open);+ const winRef = useRef(win);+ /** "fill" mounts every row for a DOM reader (find, print, select all). */+ const modeRef = useRef<"slide" | "fill">("slide");+ const slackRef = useRef(0);+ const releaseAtRef = useRef(0);+ const printingRef = useRef(false);+ const anchorRef = useRef<HeldAnchor | null>(null);+ /** A commit is in flight; its layout effect owns the correction. */+ const pendingRef = useRef(false);+ const frameRef = useRef(0);+ const chunkRef = useRef(0);+ const waitersRef = useRef<Array<() => void>>([]);+ const scrollActivity = useRef<ReturnType<typeof watchProgressiveScroll> | null>(null);+ const stepRef = useRef<() => void>(() => undefined);+ const settleTimerRef = useRef(0);+ const ordinalsRef = useRef(false);// Re-arm per thread during render. Unexercised while an ancestor key remounts on switch, but// needed if that key is removed.const [previousKey, setPreviousKey] = useState(resetKey);if (previousKey !== resetKey) {setPreviousKey(resetKey);- setMountWindow(initialWindow(count, isRunningNow(), renderableAt()));+ setWin(open());}- // Arm on the commit that first brings rows into an empty tree: history arrives after mount, and- // gating on the threshold instead would window a thread the reader is in the middle of.const [previousCount, setPreviousCount] = useState(count);if (previousCount !== count) {setPreviousCount(count);if (previousCount === 0 && count > 0) {- setMountWindow(initialWindow(count, isRunningNow(), renderableAt()));+ setWin(open());+ } else if (win != null) {+ const followed = followCount(win, previousCount, count);+ if (followed !== win) setWin(followed);}}- // Reconcile a thread that shrank past the window here, or a later widen unmounts rows.- if (mountWindow != null && mountWindow.start >= count) {- setMountWindow(null);- }+ const { metas } = readMetas();+ const spacers = useMemo(() => spacerHeights(heights, metas, win), [heights, metas, win]);- // A run starting mid-widening drops the window: streaming and widening write the same scrollTop.- const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);- useEffect(() => {- if (threadIsRunning && mountWindow != null) setMountWindow(null);- }, [threadIsRunning, mountWindow]);-- // Captured against the scroll container; the correction assumes native anchoring is off.- const anchorRef = useRef<- | ({- element: Element;- row: Element | null;- rowSample: AnchorSample | null;- } & AnchorSample)- | null- >(null);- const idleRef = useRef<HeldAnchor | null>(null);- const chunkRef = useRef(0);- const scrollActivity = useRef<ReturnType<typeof watchProgressiveScroll> | null>(null);+ const schedule = useCallback(() => {+ if (frameRef.current) return;+ frameRef.current = requestAnimationFrame(() => {+ frameRef.current = 0;+ stepRef.current();+ });+ }, []);- useEffect(() => {- const viewport = viewportRef.current;- if (!viewport) return;- const activity = watchProgressiveScroll(viewport);- scrollActivity.current = activity;- return () => {- activity.dispose();- scrollActivity.current = null;- };- }, [viewportRef]);+ const commit = useCallback(+ (next: RowWindow | null, sync: boolean) => {+ const viewport = viewportRef.current;+ if (viewport) {+ // Off before the capture: native anchoring would correct the same shift a second time.+ viewport.style.setProperty("overflow-anchor", "none");+ const element = pickAnchorRow(viewport);+ anchorRef.current = element ? holdAnchor(viewport, element) : null;+ }+ pendingRef.current = true;+ const apply = () => setWin(next);+ // Keep the commit and its correction inside the same WebKit rendering frame.+ if (sync) flushSync(apply);+ else startTransition(apply);+ },+ [viewportRef],+ );- const captureAnchor = useCallback(() => {- const viewport = viewportRef.current;- // Disarm native anchoring right before the capture. A layout effect is too early: as a descendant,- // this runs before the viewport ref callback on the mounting commit.- if (viewport) viewport.style.setProperty("overflow-anchor", "none");- // Preserve the last compensated position, including reflows between widening frames.- const held = idleRef.current;- if (viewport && held?.element.isConnected && isAnchorVisible(viewport, held.element)) {- anchorRef.current = {- element: held.element,- ...held.sample,- row: held.row,- rowSample: held.rowSample,- };- return;- }- const anchor = viewport ? pickAnchorRow(viewport) : null;- // Fall back to the row: the anchor is often a `<pre>` replaced when Shiki finishes.- const row = anchor?.closest("[data-role]") ?? null;- anchorRef.current =- viewport && anchor- ? {- element: anchor,- ...sampleAnchor(viewport, anchor),- row,- rowSample: row ? sampleAnchor(viewport, row) : null,- }- : null;- }, [viewportRef]);+ const flushWaiters = useCallback(() => {+ const waiters = waitersRef.current;+ waitersRef.current = [];+ for (const resolve of waiters) resolve();+ }, []);- useEffect(() => {- if (mountWindow == null) return;- let frame = 0;- const advance = () => {- // Re-check: a run can start between the commit and this frame.- if (isRunningNow()) {- setMountWindow(null);+ const ordinals = useCallback(+ (viewport: HTMLElement, lookup: Metas) => {+ const windowed = winRef.current != null;+ if (!windowed && !ordinalsRef.current) return;+ publishOrdinals(viewport, lookup, windowed);+ ordinalsRef.current = windowed;+ },+ [],+ );++ /** Once input is quiet, folds the leading spacer's slack into scrollTop, anchor held. */+ const settle = useCallback(+ (viewport: HTMLElement, current: RowWindow, lookup: Metas) => {+ const top = topRef.current;+ window.clearTimeout(settleTimerRef.current);+ if (!top || current.start <= spacerRows(current, lookup.metas.length).topFrom) {+ restoreScrollAnchoring(viewport);+ return;+ }+ const wanted = spacerHeights(heights, lookup.metas, current).top;+ const now = Number.parseFloat(top.style.height) || 0;+ if (Math.abs(now - wanted) < 1) {+ slackRef.current = now - wanted;+ restoreScrollAnchoring(viewport);return;}- // A prepend's instant anchor correction also interrupts native wheel momentum.if (scrollActivity.current?.blocked(inputPointerHeld())) {- frame = requestAnimationFrame(advance);+ settleTimerRef.current = window.setTimeout(schedule, SETTLE_RETRY_MS);return;}- captureAnchor();- // Read after the capture's layout reads, so this forces no extra layout.- const chunk = WEBKIT_GTK- ? (chunkRef.current = nextMountChunk(- chunkRef.current, frontierAbove(viewportRef.current), MOUNT_CHUNK, WINDOW_REACH))- : MOUNT_CHUNK;- const commit = () => {- setMountWindow((current) => widen(current, count, chunk));- };- // Keep the prepend and its scroll correction inside the same WebKit rendering frame.- if (WEBKIT_GTK) flushSync(commit);- else startTransition(commit);- };- frame = requestAnimationFrame(advance);- return () => cancelAnimationFrame(frame);- }, [mountWindow, count, captureAnchor, isRunningNow, viewportRef]);+ viewport.style.setProperty("overflow-anchor", "none");+ const element = pickAnchorRow(viewport);+ const held = element ? holdAnchor(viewport, element) : null;+ top.style.height = `${wanted}px`;+ slackRef.current = 0;+ const shift = held+ ? anchorCorrection(held.sample, sampleAnchor(viewport, held.element), ANCHOR_PRECISION)+ : null;+ adjustScroll(shift ?? 0);+ restoreScrollAnchoring(viewport);+ },+ [adjustScroll, heights, schedule, topRef],+ );- // mountWindow is a trigger: this must run in the commit that widened the window, before paint.- // biome-ignore lint/correctness/useExhaustiveDependencies: mountWindow is a trigger, see above- useLayoutEffect(() => {- const captured = anchorRef.current;- anchorRef.current = null;+ const step = useCallback(() => {const viewport = viewportRef.current;- if (!viewport) return;- if (!captured) {- // The initial tail has no earlier anchor. Pin it before its first paint,- // just as later prepends are corrected in this commit.- adjustForContentInsertedAbove(0);+ if (!viewport || pendingRef.current) return;+ // Hidden behind another route: every row measures zero (the resize observer steps on show),+ // and a waiter would wait for as long as it hides.+ if (viewport.clientHeight === 0) {+ flushWaiters();return;}- const [element, baseline] = captured.element.isConnected- ? [captured.element, captured as AnchorSample]- : captured.row?.isConnected && captured.rowSample- ? [captured.row, captured.rowSample]- : [null, null];- if (!element || !baseline) return;- const shift = anchorCorrection(baseline, sampleAnchor(viewport, element), ANCHOR_PRECISION);- // Call even with zero shift: it resyncs the hook's scroll bookkeeping.- adjustForContentInsertedAbove(shift ?? 0);- // Keep a post-correction baseline; nulling it folds an in-between reflow into the next one.- idleRef.current = holdAnchor(viewport, element);- }, [mountWindow, adjustForContentInsertedAbove, viewportRef]);-- // Compensate reflows between prepends while native anchoring is off.- useEffect(() => {- if (mountWindow == null) {- idleRef.current = null;- // The next thread's first steps start small again.- chunkRef.current = 0;- return;+ const lookup = readMetas();+ const total = lookup.metas.length;+ const current = winRef.current;+ const column = viewport.querySelector<HTMLElement>(ROW_SELECTOR);+ // Opening every trace or card moves every row too.+ const relaid =+ column != null && heights.relayout(`${rowLayout(column)}\n${thinking}\n${tools}`);+ const measured = measureRows(viewport, lookup, heights);+ // Also here: a row can replace its root (an edit opening) without the window committing.+ ordinals(viewport, lookup);++ const readerHolds =+ printingRef.current ||+ fullMountHolds.size > 0 ||+ document.documentElement.hasAttribute(FIND_FLAG);+ if (readerHolds) modeRef.current = "fill";+ else if (+ modeRef.current === "fill" &&+ // A full mount still under way is dropped too once nobody is waiting for it (find closed).+ (current == null || waitersRef.current.length === 0) &&+ performance.now() >= releaseAtRef.current+ ) {+ modeRef.current = "slide";}- let frame = 0;- const tick = () => {- frame = requestAnimationFrame(tick);- const viewport = viewportRef.current;- // A pending widening capture owns the correction; stepping in would correct twice.- if (!viewport || anchorRef.current) return;- if (scrollActivity.current?.blocked(inputPointerHeld())) {- idleRef.current = null;- return;+ // The reply being written keeps its row: its effects run the stream.+ const tail = aui.thread().getState().isRunning === true ? total - 1 : null;++ if (current == null) {+ if (waitersRef.current.length > 0) {+ releaseAtRef.current = performance.now() + FILL_RELEASE_MS;+ requestAnimationFrame(flushWaiters);}- const held = idleRef.current;- if (!held) {- const element = pickAnchorRow(viewport);- idleRef.current = element ? holdAnchor(viewport, element) : null;+ const next = holdTailTurn(+ planEngage(measured.rows, total, viewport.clientHeight),+ total,+ lookup.tailTurn,+ );+ const held =+ modeRef.current === "fill" || heldSelection(viewport) !== null || inputPointerHeld();+ if (next == null || held) {+ restoreScrollAnchoring(viewport);+ // Only a reader's hold wakes the window when it ends; the others end silently.+ if (next != null && !readerHolds) {+ window.clearTimeout(settleTimerRef.current);+ settleTimerRef.current = window.setTimeout(schedule, HOLD_RECHECK_MS);+ }return;}- // Fall back to the row if replaced; re-picking would re-base after the replacement's 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;+ commit(keepPinned(viewport, lookup, next, tail), true);+ return;+ }++ const inWindow = measured.rows.filter(+ (row) => row.index >= current.start && row.index < current.end,+ );+ const heightOf = (index: number) => heights.heightOf(lookup.metas[index]);+ let next: RowWindow | null;+ let trim = true;+ if (modeRef.current === "fill") {+ // A commit also interrupts native wheel momentum, so a full mount waits for a quiet moment.+ if (scrollActivity.current?.blocked(inputPointerHeld())) {+ schedule();return;}- // Tested by the row's box, not its top: a tall row just off screen can keep its top near the fold.- if (!isAnchorVisible(viewport, element)) {- // Re-pick in this frame; a baseline-free frame folds a reflow into the next baseline.- const replacement = pickAnchorRow(viewport);- idleRef.current = replacement- ? holdAnchor(viewport, replacement)- : null;+ // Px from the viewport top up to the window's first row; prepends land above it.+ const frontier = inWindow.length > 0 ? -inWindow[0].top : null;+ const chunk = WEBKIT_GTK+ ? (chunkRef.current = nextMountChunk(+ chunkRef.current, frontier, FILL_CHUNK, WINDOW_REACH_PX))+ : FILL_CHUNK;+ next = planFill(current, total, chunk, heightOf);+ } else {+ chunkRef.current = 0;+ next = planSlide({+ win: current,+ count: total,+ rows: inWindow,+ viewHeight: viewport.clientHeight,+ threadTop: measured.threadTop,+ slack: slackRef.current,+ heightOf,+ maxStep: SLIDE_STEP,+ trim: (trim =+ heldSelection(viewport) === null &&+ !inputPointerHeld() &&+ document.querySelector(OPEN_DIALOG) === null),+ });+ next = holdTailTurn(next, total, lookup.tailTurn);+ }+ if (next != null) next = keepPinned(viewport, lookup, next, tail);+ if (sameWindow(next, current)) {+ // Every height moved: the trailing spacer and gaps are sized only by a render.+ if (relaid) {+ commit({ ...current }, true);return;}- const shift = anchorCorrection(baseline, sampleAnchor(viewport, element), ANCHOR_PRECISION);- if (shift !== null) adjustForContentInsertedAbove(shift);- // Re-base every frame: anchorCorrection's clamp term reads the baseline scrollTop.- idleRef.current = holdAnchor(viewport, element);- };- frame = requestAnimationFrame(tick);- return () => cancelAnimationFrame(frame);- }, [mountWindow, adjustForContentInsertedAbove, viewportRef]);-- // Restore native anchoring when the window closes or on unmount; it is turned off at capture.+ settle(viewport, current, lookup);+ if (!trim) {+ window.clearTimeout(settleTimerRef.current);+ settleTimerRef.current = window.setTimeout(schedule, HOLD_RECHECK_MS);+ }+ return;+ }+ const trimOnly = next != null && next.start >= current.start && next.end <= current.end;+ // A spacer in view is blank screen: not behind an interruptible transition.+ const first = inWindow[0];+ const last = inWindow[inWindow.length - 1];+ const exposed =+ !first ||+ (current.start > 0 && first.top > 0) ||+ (current.end < total && last.bottom < viewport.clientHeight);+ commit(next, WEBKIT_GTK || trimOnly || exposed);+ }, [aui, commit, flushWaiters, heights, ordinals, readMetas, schedule, settle, thinking, tools, viewportRef]);useLayoutEffect(() => {- if (mountWindow != null) return;- restoreScrollAnchoring(viewportRef.current);- }, [mountWindow, viewportRef]);+ stepRef.current = step;+ }, [step]);- // biome-ignore lint/correctness/useExhaustiveDependencies: unmount-only cleanup+ // Declared before the commit effect below, which reads what this resets.+ // biome-ignore lint/correctness/useExhaustiveDependencies: resetKey is the thread these belong touseLayoutEffect(() => {+ modeRef.current = "slide";+ slackRef.current = 0;+ }, [resetKey]);++ // The leading spacer stands for no rows: the window starts at the first row, or at a pin.+ const atFirstRow = win == null || win.start <= spacerRows(win, count).topFrom;++ // Spacers are sized before any layout effect: a new spacer node has no height yet, and a row+ // reading layout in its own effect would let the browser clamp scrollTop to a short thread.+ useInsertionEffect(() => {const viewport = viewportRef.current;- return () => {- restoreScrollAnchoring(viewport);- };- }, [viewportRef]);+ if (!viewport) return;+ const spacer = (name: string) =>+ viewport.querySelector<HTMLElement>(`:scope > [${SPACER_ATTRIBUTE}="${name}"]`);+ const leading = atFirstRow ? 0 : Math.max(0, spacers.top + slackRef.current);+ spacer("top")?.style.setProperty("height", `${leading}px`);+ spacer("bottom")?.style.setProperty("height", `${spacers.bottom}px`);+ }, [atFirstRow, spacers, viewportRef]);- // Registered only while rows are withheld, so completeProgressiveMounts is free when settled.- const isWithholding = mountWindow != null;- const completionWaiters = useRef<Array<() => void>>([]);useLayoutEffect(() => {- if (!isWithholding) return;- const complete = () =>+ winRef.current = win;+ const captured = anchorRef.current;+ anchorRef.current = null;+ const committed = pendingRef.current;+ pendingRef.current = false;+ const viewport = viewportRef.current;+ const top = topRef.current;+ const bottom = bottomRef.current;+ if (!viewport || !top || !bottom) return;+ let spacer = atFirstRow ? 0 : Math.max(0, spacers.top + slackRef.current);+ top.style.height = `${spacer}px`;+ bottom.style.height = `${spacers.bottom}px`;+ let scroll = 0;+ if (captured) {+ const [element, baseline] = captured.element.isConnected+ ? [captured.element, captured.sample]+ : captured.row?.isConnected && captured.rowSample+ ? [captured.row, captured.rowSample]+ : [null, null];+ const shift =+ element && baseline+ ? anchorCorrection(baseline, sampleAnchor(viewport, element), ANCHOR_PRECISION)+ : null;+ if (shift !== null) {+ // The spacer takes the shift, so wheel momentum or a held thumb is left alone.+ const taken = absorbShift(spacer, shift, atFirstRow);+ spacer = taken.spacer;+ scroll = taken.scroll;+ top.style.height = `${spacer}px`;+ }+ }+ slackRef.current = atFirstRow ? 0 : spacer - spacers.top;+ // Called with zero too: the hook owns scrollTop and resyncs its bookkeeping on every commit.+ adjustScroll(scroll);+ ordinals(viewport, readMetas());+ if (committed) for (const listener of rowListeners) listener();+ schedule();+ }, [win, atFirstRow, spacers, adjustScroll, ordinals, readMetas, schedule, viewportRef, topRef, bottomRef]);++ /** Behind another route: no boxes, so no step runs and a full mount cannot make progress. */+ const hidden = useCallback(() => viewportRef.current?.clientHeight === 0, [viewportRef]);++ const complete = useCallback(+ (signal?: AbortSignal) =>new Promise<void>((resolve) => {- completionWaiters.current.push(resolve);- setMountWindow(null);+ if (signal?.aborted) {+ resolve();+ return;+ }+ // Nothing can read a hidden thread's rows, and a waiter here would never be resolved.+ if (hidden()) {+ resolve();+ return;+ }+ modeRef.current = "fill";+ releaseAtRef.current = performance.now() + FILL_RELEASE_MS;+ if (winRef.current == null) {+ resolve();+ return;+ }+ waitersRef.current.push(resolve);+ signal?.addEventListener(+ "abort",+ () => {+ waitersRef.current = waitersRef.current.filter((waiter) => waiter !== resolve);+ // Nobody else waiting: the release deadline is all that holds the full mount now.+ if (waitersRef.current.length === 0) releaseAtRef.current = performance.now();+ resolve();+ schedule();+ },+ { once: true },+ );+ schedule();+ }),+ [hidden, schedule],+ );++ const reveal = useCallback(+ (messageId: string): boolean => {+ const lookup = readMetas();+ const index = lookup.index.get(messageId);+ if (index === undefined) return false;+ const current = winRef.current;+ const viewport = viewportRef.current;+ if (+ current == null ||+ !viewport ||+ (index >= current.start && index < current.end) ||+ current.pins?.includes(index)+ ) {+ return true;+ }+ const total = lookup.metas.length;+ const tail = aui.thread().getState().isRunning === true ? total - 1 : null;+ const next = keepPinned(+ viewport,+ lookup,+ { start: index, end: Math.min(total, index + SLIDE_STEP) },+ tail,+ );+ // No anchor: the caller scrolls to the row, so there is no reading position to keep.+ viewport.style.setProperty("overflow-anchor", "none");+ anchorRef.current = null;+ pendingRef.current = true;+ flushSync(() => {+ setWin(next);});- const entry: ActiveCompleter = { complete, viewportRef };- activeCompleters.add(entry);+ return true;+ },+ [aui, readMetas, viewportRef],+ );++ useLayoutEffect(() => {+ const entry: ActiveWindow = {+ complete,+ reveal,+ // A hidden thread is neither: a reader waiting on it would wait for as long as it hides.+ withholding: () => winRef.current != null && !hidden(),+ filling: () => modeRef.current === "fill" && winRef.current != null && !hidden(),+ wake: schedule,+ viewportRef,+ };+ activeWindows.add(entry);return () => {- activeCompleters.delete(entry);+ activeWindows.delete(entry);};- }, [isWithholding, viewportRef]);-- // Resolve after the commit that dropped the window, then a paint; a bare timer raced the commit.- const flushCompletionWaiters = useCallback(() => {- const waiters = completionWaiters.current;- completionWaiters.current = [];- for (const resolve of waiters) resolve();- }, []);+ }, [complete, hidden, reveal, schedule, viewportRef]);useEffect(() => {- if (mountWindow != null || completionWaiters.current.length === 0) return;- // Waiters are emptied only when the frame fires, so a cancelled frame keeps them.- const frame = requestAnimationFrame(() =>- requestAnimationFrame(flushCompletionWaiters),- );- return () => cancelAnimationFrame(frame);- }, [mountWindow, flushCompletionWaiters]);+ const viewport = viewportRef.current;+ if (!viewport) return;+ const activity = watchProgressiveScroll(viewport);+ scrollActivity.current = activity;+ const flags = new MutationObserver(schedule);+ flags.observe(document.documentElement, {+ attributes: true,+ attributeFilter: [FIND_FLAG, ...LAYOUT_FLAGS],+ });+ const resize = new ResizeObserver(schedule);+ resize.observe(viewport);+ // A row that shrinks (a block collapsed) or re-wraps can bare a spacer with no scroll to wake+ // the window. Not a growth: a streamed reply grows on every chunk.+ const rowSizes = new WeakMap<Element, { width: number; height: number }>();+ const rowResize = new ResizeObserver((entries) => {+ let wake = false;+ for (const entry of entries) {+ const { width, height } = entry.contentRect;+ const before = rowSizes.get(entry.target);+ rowSizes.set(entry.target, { width, height });+ if (before && (height < before.height - 1 || Math.abs(width - before.width) > 1)) {+ wake = true;+ }+ }+ if (wake) schedule();+ });+ const watchRows = (nodes: Iterable<Node>) => {+ for (const node of nodes) {+ if (node instanceof Element && node.matches(ROW_SELECTOR)) rowResize.observe(node);+ }+ };+ const rowsChanged = new MutationObserver((records) => {+ for (const record of records) {+ for (const node of record.removedNodes) {+ if (node instanceof Element) rowResize.unobserve(node);+ }+ watchRows(record.addedNodes);+ }+ });+ rowsChanged.observe(viewport, { childList: true });+ watchRows(viewport.children);+ const media = window.matchMedia("print");+ const beforePrint = () => {+ printingRef.current = true;+ modeRef.current = "fill";+ // Print lays out only what is mounted, even over a commit in flight. A hidden thread is not+ // printed, and its step would not rewindow it until shown.+ if (winRef.current != null && viewport.clientHeight > 0) commit(null, true);+ };+ const afterPrint = () => {+ printingRef.current = media.matches;+ releaseAtRef.current = performance.now();+ schedule();+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "a") return;+ const target = event.target as Element | null;+ if (target?.closest?.(EDITABLE)) return;+ if (viewport.clientHeight === 0 || viewport.closest("[inert]")) return;+ void complete();+ };+ const onCopy = (event: ClipboardEvent) => {+ // A selection across a spacer would copy a short conversation: mount before it is read.+ if (winRef.current == null) return;+ // A field copies its own text; a page selection left behind is not what is copied.+ const target = event.target as Element | null;+ if (target?.closest?.(EDITABLE)) return;+ const selection = document.getSelection();+ if (!selection || selection.isCollapsed) return;+ const top = topRef.current;+ const bottom = bottomRef.current;+ const standsIn = (spacer: HTMLElement | null) =>+ spacer !== null && spacer.offsetHeight > 0 && selection.containsNode(spacer, true);+ const fromTop = standsIn(top);+ const toBottom = standsIn(bottom);+ const acrossGap = [+ ...viewport.querySelectorAll<HTMLElement>(`:scope > [${SPACER_ATTRIBUTE}="gap"]`),+ ].some(standsIn);+ if (!fromTop && !toBottom && !acrossGap) return;+ const lookup = readMetas();+ const { topFrom, bottomTo } = spacerRows(winRef.current, lookup.metas.length);+ modeRef.current = "fill";+ releaseAtRef.current = performance.now() + FILL_RELEASE_MS;+ commit(null, true);+ // WebKit serialises the selection resolved before the mount, so set it again, with an end+ // it moved off a spacer put on the first (or last) row that spacer stood for. Rows, not the+ // spacers: a spacer keyed by a pin is replaced by the mount.+ if (selection.rangeCount !== 1) return;+ const rowAt = (from: number, step: 1 | -1): Element | null => {+ for (let index = from; index >= 0 && index < lookup.metas.length; index += step) {+ const id = lookup.metas[index].id;+ const row = viewport.querySelector(`:scope > [data-message-id="${CSS.escape(id)}"]`);+ if (row) return row;+ }+ return null;+ };+ const range = selection.getRangeAt(0).cloneRange();+ const edge = document.createRange();+ const first = fromTop ? rowAt(topFrom, 1) : null;+ if (first) {+ edge.setStartBefore(first);+ edge.collapse(true);+ if (range.compareBoundaryPoints(Range.START_TO_START, edge) > 0) range.setStartBefore(first);+ }+ const last = toBottom ? rowAt(bottomTo - 1, -1) : null;+ if (last) {+ edge.setStartAfter(last);+ edge.collapse(true);+ if (range.compareBoundaryPoints(Range.END_TO_END, edge) < 0) range.setEndAfter(last);+ }+ selection.removeAllRanges();+ selection.addRange(range);+ };+ viewport.addEventListener("scroll", schedule, { passive: true });+ // A pinned row is let go once the reader has left it.+ viewport.addEventListener("focusout", schedule);+ document.addEventListener("copy", onCopy, true);+ document.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("beforeprint", beforePrint);+ window.addEventListener("afterprint", afterPrint);+ schedule();+ return () => {+ activity.dispose();+ scrollActivity.current = null;+ flags.disconnect();+ resize.disconnect();+ rowResize.disconnect();+ rowsChanged.disconnect();+ viewport.removeEventListener("scroll", schedule);+ viewport.removeEventListener("focusout", schedule);+ document.removeEventListener("copy", onCopy, true);+ document.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("beforeprint", beforePrint);+ window.removeEventListener("afterprint", afterPrint);+ cancelAnimationFrame(frameRef.current);+ frameRef.current = 0;+ window.clearTimeout(settleTimerRef.current);+ restoreScrollAnchoring(viewport);+ };+ }, [viewportRef, topRef, bottomRef, schedule, commit, complete, readMetas]);// Settle waiters on unmount, or a DOM capture racing a thread switch waits forever.- useEffect(() => flushCompletionWaiters, [flushCompletionWaiters]);+ useEffect(() => flushWaiters, [flushWaiters]);++ /** Estimated height of rows `[from, to)`, for a spacer between pinned rows. */+ const gapHeight = useCallback(+ (from: number, to: number): number => {+ const { metas: rows } = readMetas();+ let height = 0;+ for (let index = from; index < Math.min(to, rows.length); index += 1) {+ height += heights.heightOf(rows[index]);+ }+ return height;+ },+ [readMetas, heights],+ );- return mountWindow;+ const counterIncrement = useCallback(+ (from: number, to: number): string | undefined => {+ const { html, mathml } = heights.equationsIn(readMetas().metas, from, to);+ return html || mathml ? `katexEqnNo ${html} mmlEqnNo ${mathml}` : undefined;+ },+ [readMetas, heights],+ );++ return { win, gapHeight, counterIncrement };}-/** Drop-in for `ThreadPrimitive.Messages` that bounds a long thread's first commit to the tail. */+/** Drop-in for `ThreadPrimitive.Messages` that mounts only the rows near the reader. */export const ProgressiveMessages: FC<{renderMessage: () => ReactElement;resetKey: string | undefined;@@ -489,32 +1067,55 @@ export const ProgressiveMessages: FC<{}> = memo(({ renderMessage, resetKey, viewportRef }) => {const count = useAuiState(({ thread }) => thread.messages.length);- const alignmentRef = useRef<HTMLDivElement>(null);- const mountWindow = useProgressiveMountWindow(count, resetKey, viewportRef, alignmentRef);+ const topRef = useRef<HTMLDivElement>(null);+ const bottomRef = useRef<HTMLDivElement>(null);+ const { win, gapHeight, counterIncrement } = useThreadWindow(+ count,+ resetKey,+ viewportRef,+ topRef,+ bottomRef,+ );const aui = useAui();const gate = useMemo(() => createRowNotificationGate(aui), [aui]);return useMemo(() => {if (count === 0) return null;- // A thread that shrank under a live window: drop the restriction now; clamping would emit nothing.- const first =- mountWindow == null || mountWindow.start >= count- ? 0- : Math.max(mountWindow.start, 0);const message = renderMessage();- const rows: ReactElement[] = [];- for (let index = first; index < count; index += 1) {- rows.push(- <AuiProvider key={index} value={gate.row(index)}>- <MessageByIndexProvider index={index}>{message}</MessageByIndexProvider>- </AuiProvider>,+ // A spacer is keyed by where it sits among the rows, so no commit ever has to move a row+ // past one: moving a row's node would take its focus and stop its media.+ return threadSlots(win, count).map((slot) => {+ if (slot.kind === "row") {+ const index = slot.index;+ return (+ <AuiProvider key={index} value={gate.row(index)}>+ <MessageByIndexProvider index={index}>{message}</MessageByIndexProvider>+ </AuiProvider>+ );+ }+ // Heights are written in the layout effect, never by React: a re-render must not undo them.+ if (slot.name === "top") {+ const key = slot.from === 0 ? "top" : `top:${slot.from}`;+ return <div key={key} ref={topRef} data-thread-spacer="top" aria-hidden="true" style={{ flexShrink: 0, counterIncrement: counterIncrement(slot.from, slot.to) }} />;+ }+ if (slot.name === "bottom") {+ const key = slot.to === count ? "bottom" : `bottom:${slot.to}`;+ return <div key={key} ref={bottomRef} data-thread-spacer="bottom" aria-hidden="true" style={{ flexShrink: 0, counterIncrement: counterIncrement(slot.from, slot.to) }} />;+ }+ return (+ <div+ key={`gap:${slot.from}`}+ data-thread-spacer="gap"+ aria-hidden="true"+ style={{+ flexShrink: 0,+ height: gapHeight(slot.from, slot.to),+ counterIncrement: counterIncrement(slot.from, slot.to),+ }}+ />);- }- return <>- {WEBKIT_GTK && <div ref={alignmentRef} aria-hidden="true" style={{ height: 0, flexShrink: 0 }} />}- {rows}- </>;- }, [count, mountWindow, renderMessage, gate]);+ });+ }, [count, win, renderMessage, gate, gapHeight, counterIncrement]);},(prev, next) =>prev.resetKey === next.resetKey &&diff --git a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.tsindex 9fae807a2b0..6ed9b114524 100644--- a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts+++ b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts@@ -1,40 +1,38 @@// 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. Not a virtualizer: unmounting breaks find-in-page, selection, copy,-// screen readers, print and export. The window only grows; nothing is ever unmounted.+// Pacing and anchor arithmetic for the thread's mount window (progressive-messages.tsx). Which+// rows are mounted is decided in thread-window.ts.-/** Indices `[start, count)` may mount; `null` means no restriction (settled or short thread). */-export type MountWindow = { start: number } | null;--/** Below this many messages the whole thread mounts in one commit. */-export const MIN_PROGRESSIVE_MESSAGES = 40;--/** Even, and sized so 16 of the shortest rows fill a clientHeight up to about 1890px. */-export const INITIAL_MESSAGES = 16;--/** Messages added per widening frame; trades build-in height against length, not total work. */+/** Messages added per frame while every row is being mounted for a DOM reader (find, print). */export const CHUNK_MESSAGES = 32;/** Leave native scrolling and its momentum alone before changing the scroll range. */+/** How long scrolling may run on after the reader's last input (touch momentum lasts seconds). */+const MOMENTUM_MS = 3000;+export function watchProgressiveScroll(viewport: EventTarget,now: () => number = () => performance.now(),) {// Let the initial tail paint before starting background work.let resumeAt = now() + 300;+ let inputAt = Number.NEGATIVE_INFINITY;const pause = () => { resumeAt = now() + 300; };- const onScroll = () => { if (now() < resumeAt) pause(); };+ const onInput = () => { inputAt = now(); pause(); };+ // A scroll extends a pause only near the reader's input (momentum runs on after a fling);+ // the autoscroll following a stream would otherwise hold a full mount off until it ends.+ const onScroll = () => { if (now() < resumeAt && now() - inputAt < MOMENTUM_MS) pause(); };const onKey = (event: Event) => {const key = event as KeyboardEvent;if (key.defaultPrevented || !["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(key.key)) return;const target = key.target as HTMLElement | null;if (target?.isContentEditable || target?.closest?.("input, textarea, select")) return;- pause();+ onInput();};- const listeners = { wheel: pause, touchmove: pause, keydown: onKey, scroll: onScroll };+ const listeners = { wheel: onInput, touchmove: onInput, keydown: onKey, scroll: onScroll };const inputTarget = (viewport as HTMLElement).ownerDocument ?? viewport;- inputTarget.addEventListener("pointerdown", pause, { capture: true, passive: true });+ inputTarget.addEventListener("pointerdown", onInput, { capture: true, passive: true });inputTarget.addEventListener("beforeinput", pause, { capture: true, passive: true });inputTarget.addEventListener("compositionupdate", pause, { capture: true, passive: true });for (const [type, listener] of Object.entries(listeners)) {@@ -46,7 +44,7 @@ export function watchProgressiveScroll(return now() < resumeAt;},dispose() {- inputTarget.removeEventListener("pointerdown", pause, { capture: true });+ inputTarget.removeEventListener("pointerdown", onInput, { capture: true });inputTarget.removeEventListener("beforeinput", pause, { capture: true });inputTarget.removeEventListener("compositionupdate", pause, { capture: true });for (const [type, listener] of Object.entries(listeners)) {@@ -56,44 +54,6 @@ export function watchProgressiveScroll(};}-/** Caps the tail walk so a tail of non-rendering messages cannot mount the whole thread. */-export const MAX_INITIAL_SPAN = INITIAL_MESSAGES * 4;--/** A running thread opens unrestricted: widening and streaming write the same scroll position. */-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 (system messages paint nothing); without isRenderable, count-based.- if (!isRenderable) return { start: Math.max(0, count - INITIAL_MESSAGES) };- // Never walk past MAX_INITIAL_SPAN, or a tail dense with non-rendering rows mounts everything.- 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 };- }- if (floor > 0) return { start: floor };- return null;-}--export function isCovered(current: MountWindow): boolean {- return current == null || current.start <= 0;-}--/** Returns null once it would cover the thread, so the restriction drops in the same commit. */-export function widen(current: MountWindow, count: number, chunk = CHUNK_MESSAGES): MountWindow {- if (current == null) return null;- // A start past the end withholds nothing; clamping then subtracting would unmount rows.- if (current.start >= count) return null;- const start = Math.max(0, current.start - chunk);- if (start <= 0) return null;- return { start };-}-/*** Largest WebKitGTK step for parked history. 32 restored the pre-windowing load time but made single* frames up to ~1.4 s on CPU-painted WebKit; 16 keeps the worst frame at the 2-per-step level.@@ -101,10 +61,10 @@ export function widen(current: MountWindow, count: number, chunk = CHUNK_MESSAGEexport const FAR_MOUNT_CHUNK = 16;/**- * WebKitGTK step size. Rows prepended within `reach` px above the viewport top stay unparked and can- * move what the reader sees, so they mount `near` at a time; past that they are parked as they land,- * so the step grows fourfold per frame up to `max` (each commit has a fixed cost there). `previous`- * is 0 before the first step, which stays `near` so it does not delay the tail's first paint.+ * WebKitGTK step size for a full mount. Rows prepended within `reach` px above the viewport top+ * stay unparked and can move what the reader sees, so they mount `near` at a time; past that they+ * are parked as they land, so the step grows fourfold per frame up to `max` (each commit has a+ * fixed cost there). `previous` is 0 before the first step, which stays `near`.*/export function nextMountChunk(previous: number,@@ -117,11 +77,6 @@ export function nextMountChunk(return Math.max(near, Math.min(max, previous * 4));}-/** Out-of-window indices are not rendered at all: hiding would not avoid the mount cost. */-export function admits(current: MountWindow, index: number): boolean {- return current == null || index >= current.start;-}-export type AnchorSample = {/** Offset from the scroll container top, not the window, so container moves are not corrected. */viewportOffset: number;@@ -150,22 +105,3 @@ export function anchorCorrection(clamped;return Math.abs(shift) >= minShift ? shift : null;}--/** Keep the scroll correction integral; a subpixel leading inset absorbs the remainder. */-export function alignAnchorCorrection(shift: number, inset: number) {- const scroll = Math.ceil(shift - inset) || 0;- return { scroll, inset: inset + scroll - shift };-}--/** Tests assert on this so the constants cannot drift into a thread that never converges. */-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-window.ts b/studio/frontend/src/components/assistant-ui/thread-window.tsnew file mode 100644index 00000000000..be09aab4b53--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/thread-window.ts@@ -0,0 +1,555 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Sliding mount window maths; the DOM and React glue is progressive-messages.tsx.++import { findCodeBlockRegions } from "../../lib/latex.ts";++/** `pins` (ascending): rows outside `[start, end)` the reader is working in, kept where they are. */+export type RowWindow = { start: number; end: number; pins?: readonly number[] };++export const WINDOW_REACH_PX = 2000;+/** Unmount distance; the gap to REACH is hysteresis. */+export const WINDOW_KEEP_PX = 4000;+export const WINDOW_INITIAL_ROWS = 16;+/** By height, not count: an agent chat is often a few turns of very long replies. */+export const WINDOW_MIN_TOTAL_PX = 40_000;+export const WINDOW_MIN_ROWS = 8;++export const worthWindowing = (count: number, totalPx: number): boolean =>+ count >= WINDOW_MIN_ROWS && totalPx >= WINDOW_MIN_TOTAL_PX;++export type RowMeta = {+ id: string;+ role: string;+ /** Expected rendered lines; only its proportion to height matters. */+ weight: number;+ renders: boolean;+ equations?: number;+ /** The content measured: an edit (another tab, a reload) voids what was read off the page. */+ revision?: unknown;+};++/** Padding, action bar and gap: a row's height before its first line. */+const BASE_PX: Record<string, number> = { user: 96, assistant: 72 };+const DEFAULT_BASE_PX = 72;+const PRIOR_PX_PER_LINE = 24;+const PRIOR_LINES = 8;+const MIN_ROW_PX = 24;+const CHARS_PER_LINE = 90;+/** Tool calls and reasoning render collapsed. */+const COLLAPSED_PART_LINES = 2;+const MEDIA_PART_LINES = 12;++type Part = { type?: string; text?: string; argsText?: string; result?: unknown };++/** Thinking and tool cards the "Always expanded" settings open on every message. */+export type Expanded = { reasoning: boolean; tools: boolean };+const COLLAPSED: Expanded = { reasoning: false, tools: false };++/** Lines, not characters: code (many short lines) must not be estimated as a paragraph. */+function textLines(text: string): number {+ let lines = 0;+ let from = 0;+ for (;;) {+ const at = text.indexOf("\n", from);+ const length = (at === -1 ? text.length : at) - from;+ lines += 1 + Math.floor(length / CHARS_PER_LINE);+ if (at === -1) return lines;+ from = at + 1;+ }+}++export function messageWeight(+ content: readonly Part[] | undefined,+ expanded: Expanded = COLLAPSED,+): number {+ if (!content) return 0;+ let weight = 0;+ for (const part of content) {+ if (part.type === "text") weight += part.text ? textLines(part.text) : 0;+ else if (part.type === "image" || part.type === "file") weight += MEDIA_PART_LINES;+ else if (part.type === "source") continue;+ else {+ weight += COLLAPSED_PART_LINES;+ if (part.type === "reasoning" && expanded.reasoning && part.text) {+ weight += textLines(part.text);+ } else if (part.type === "tool-call" && expanded.tools) {+ if (part.argsText) weight += textLines(part.argsText);+ if (typeof part.result === "string") weight += textLines(part.result);+ }+ }+ }+ return weight;+}++const NUMBERED_ENV = /\\begin\{(equation|multline|align|gather|alignat|flalign|eqnarray)\}([\s\S]*?)\\end\{\1\}/g;+/** Display math only: KaTeX refuses these environments inline. */+const DISPLAY_MATH = /\$\$([\s\S]*?)\$\$|\\\[([\s\S]*?)\\\]/g;++/** Code renders verbatim, so an environment in it is an example, not math. The markdown+ * pipeline's own regions: fenced (in containers too), indented and inline. */+function withoutCode(text: string): string {+ let prose = "";+ let cursor = 0;+ for (const [start, end] of findCodeBlockRegions(text)) {+ prose += `${text.slice(cursor, start)}\n`;+ cursor = end;+ }+ return prose + text.slice(cursor);+}++const TEX_COMMENT = /(?<!\\)%[^\n]*/g;+const UNNUMBERED = /\\(?:notag|nonumber|tag)\b/;+const ENV_EDGE = /\\(begin|end)\{[^}]*\}/y;++/** Split on `\\` at the environment's own level: a nested cases or matrix row takes no number. */+function topLevelRows(body: string): string[] {+ const rows: string[] = [];+ let depth = 0;+ let from = 0;+ for (let at = 0; at < body.length; at += 1) {+ const char = body[at];+ if (char === "{") depth += 1;+ else if (char === "}") depth -= 1;+ else if (char === "\\") {+ ENV_EDGE.lastIndex = at;+ const edge = ENV_EDGE.exec(body);+ if (edge) {+ depth += edge[1] === "begin" ? 1 : -1;+ at = ENV_EDGE.lastIndex - 1;+ } else if (body[at + 1] === "\\" && depth === 0) {+ rows.push(body.slice(from, at));+ from = at + 2;+ at += 1;+ } else {+ at += 1;+ }+ }+ }+ rows.push(body.slice(from));+ return rows;+}++/**+ * KaTeX numbers these on page-wide CSS counters, so a row left out of the DOM must still count+ * them: one per environment, one per top-level row of the multi-line ones, less tagged rows.+ */+export function numberedEquations(+ content: readonly Part[] | undefined,+ expanded: Expanded = COLLAPSED,+): number {+ let total = 0;+ for (const part of content ?? []) {+ // A trace renders markdown too, but is on the page only while open.+ const shown = part.type === "text" || (part.type === "reasoning" && expanded.reasoning);+ if (!shown || !part.text?.includes("\\begin{")) continue;+ const prose = withoutCode(part.text);+ for (const [, dollars, brackets] of prose.matchAll(DISPLAY_MATH)) {+ for (const [, env, source] of (dollars ?? brackets).matchAll(NUMBERED_ENV)) {+ // KaTeX drops a comment to the end of its line, `\notag` in it included.+ const body = source.replace(TEX_COMMENT, "");+ const rows = env === "equation" || env === "multline" ? [body] : topLevelRows(body);+ total += rows.filter((row) => row.trim() !== "" && !UNNUMBERED.test(row)).length;+ }+ }+ }+ return total;+}++export type Equations = { html: number; mathml: number };++type Density = { lines: number; px: number };++/**+ * Measured heights by message id; an unmeasured row is estimated from px per line seen so far per+ * role. A ratio of sums, not a fitted line: the first rows measured are alike, so a fit is undefined.+ */+export class RowHeights {+ private measured = new Map<string, { height: number; revision: unknown }>();+ private densities = new Map<string, Density>();+ private counted = new Map<string, { role: string; lines: number; px: number }>();+ private layout: string | null = null;++ /** A new width or typography re-wraps every row: forget every height. True when it did. */+ relayout(layout: string): boolean {+ if (layout === this.layout) return false;+ const was = this.layout;+ this.layout = layout;+ if (was === null) return false;+ this.measured.clear();+ this.densities.clear();+ this.counted.clear();+ // Opening or closing every trace adds or drops its equations too.+ this.equations.clear();+ return true;+ }++ private equations = new Map<string, { counted: Equations; revision: unknown }>();++ /** True when the height changed. */+ measure(meta: RowMeta, height: number): boolean {+ if (!(height >= 0)) return false;+ const prior = this.measured.get(meta.id);+ if (prior !== undefined && prior.height === height && prior.revision === meta.revision) {+ return false;+ }+ this.measured.set(meta.id, { height, revision: meta.revision });+ let density = this.densities.get(meta.role);+ if (!density) {+ density = { lines: PRIOR_LINES, px: PRIOR_LINES * PRIOR_PX_PER_LINE };+ this.densities.set(meta.role, density);+ }+ const before = this.counted.get(meta.id);+ if (before && before.role === meta.role) {+ density.lines -= before.lines;+ density.px -= before.px;+ }+ const px = Math.max(0, height - (BASE_PX[meta.role] ?? DEFAULT_BASE_PX));+ density.lines += meta.weight;+ density.px += px;+ this.counted.set(meta.id, { role: meta.role, lines: meta.weight, px });+ return true;+ }++ countEquations(meta: RowMeta, counted: Equations): void {+ this.equations.set(meta.id, { counted, revision: meta.revision });+ }++ /** Counter increments rows `[from, to)` would have made, for the spacer standing in for them. */+ equationsIn(metas: readonly RowMeta[], from: number, to: number): Equations {+ const sum = { html: 0, mathml: 0 };+ for (let index = from; index < Math.min(to, metas.length); index += 1) {+ const meta = metas[index];+ const entry = this.equations.get(meta.id);+ const known = entry !== undefined && entry.revision === meta.revision ? entry.counted : null;+ sum.html += known ? known.html : (meta.equations ?? 0);+ sum.mathml += known ? known.mathml : (meta.equations ?? 0);+ }+ return sum;+ }++ has(id: string): boolean {+ return this.measured.has(id);+ }++ heightOf(meta: RowMeta): number {+ if (!meta.renders) return 0;+ const known = this.measured.get(meta.id);+ if (known !== undefined && known.revision === meta.revision) return known.height;+ const density = this.densities.get(meta.role);+ const perLine = density ? density.px / density.lines : PRIOR_PX_PER_LINE;+ const base = BASE_PX[meta.role] ?? DEFAULT_BASE_PX;+ return Math.max(MIN_ROW_PX, Math.round(base + perLine * meta.weight));+ }+}++export function withPins(win: RowWindow, pins: readonly number[], count: number): RowWindow {+ const kept = pins.filter(+ (index) => index >= 0 && index < count && (index < win.start || index >= win.end),+ );+ return kept.length > 0+ ? { start: win.start, end: win.end, pins: kept }+ : { start: win.start, end: win.end };+}++/** A mounted row, or a spacer for rows `[from, to)`; a `gap` spacer separates pinned rows. */+export type ThreadSlot =+ | { kind: "row"; index: number }+ | { kind: "spacer"; name: "top" | "bottom" | "gap"; from: number; to: number };++/** Document order. A full mount still has its two (empty) spacers. */+export function threadSlots(win: RowWindow | null, count: number): ThreadSlot[] {+ const start = win == null ? 0 : Math.max(0, Math.min(win.start, count));+ const end = win == null ? count : Math.max(start, Math.min(win.end, count));+ const pins = (win?.pins ?? []).filter((index) => index >= 0 && index < count);+ const slots: ThreadSlot[] = [];+ let at = 0;+ let from = 0;+ for (; at < pins.length && pins[at] < start; at += 1) {+ slots.push({ kind: "spacer", name: "gap", from, to: pins[at] });+ slots.push({ kind: "row", index: pins[at] });+ from = pins[at] + 1;+ }+ slots.push({ kind: "spacer", name: "top", from, to: start });+ for (let index = start; index < end; index += 1) slots.push({ kind: "row", index });+ while (at < pins.length && pins[at] < end) at += 1;+ slots.push({ kind: "spacer", name: "bottom", from: end, to: at < pins.length ? pins[at] : count });+ for (; at < pins.length; at += 1) {+ slots.push({ kind: "row", index: pins[at] });+ slots.push({+ kind: "spacer",+ name: "gap",+ from: pins[at] + 1,+ to: at + 1 < pins.length ? pins[at + 1] : count,+ });+ }+ return slots;+}++/** `[topFrom, start)` and `[end, bottomTo)`: up to the nearest pin on each side. */+export function spacerRows(win: RowWindow, count: number): { topFrom: number; bottomTo: number } {+ const start = Math.max(0, Math.min(win.start, count));+ const end = Math.max(start, Math.min(win.end, count));+ let topFrom = 0;+ let bottomTo = count;+ for (const pin of win.pins ?? []) {+ if (pin < start) topFrom = Math.max(topFrom, pin + 1);+ else if (pin >= end && pin < bottomTo) bottomTo = pin;+ }+ return { topFrom, bottomTo };+}++export function spacerHeights(+ heights: RowHeights,+ metas: readonly RowMeta[],+ win: RowWindow | null,+): { top: number; bottom: number } {+ if (win == null) return { top: 0, bottom: 0 };+ const { topFrom, bottomTo } = spacerRows(win, metas.length);+ let top = 0;+ let bottom = 0;+ const start = Math.min(win.start, metas.length);+ for (let index = topFrom; index < start; index += 1) top += heights.heightOf(metas[index]);+ for (let index = Math.max(win.end, start); index < bottomTo; index += 1) {+ bottom += heights.heightOf(metas[index]);+ }+ return { top, bottom };+}++/** A window at the tail follows it; one past a shorter thread is clamped (null if nothing is left). */+export function followCount(win: RowWindow, previous: number, count: number): RowWindow | null {+ if (win.start >= count) return null;+ const end = win.end >= previous || win.end > count ? count : win.end;+ const next = withPins({ start: win.start, end }, win.pins ?? [], count);+ return sameWindow(next, win) ? win : next;+}++export function initialRowWindow(+ count: number,+ heightOf: (index: number) => number,+ coverPx: number,+ maxRows = WINDOW_INITIAL_ROWS,+): RowWindow | null {+ let total = 0;+ for (let index = 0; index < count; index += 1) total += heightOf(index);+ if (!worthWindowing(count, total)) return null;+ let start = count;+ let covered = 0;+ let rows = 0;+ while (start > 0 && rows < maxRows && covered < coverPx) {+ start -= 1;+ const height = heightOf(start);+ if (height > 0) rows += 1;+ covered += height;+ }+ if (start <= 0) return null;+ return { start, end: count };+}++/** Px from the viewport's top edge. */+export type MountedRow = { index: number; top: number; bottom: number };++export type SlideInput = {+ win: RowWindow;+ count: number;+ /** Not its pins. */+ rows: readonly MountedRow[];+ viewHeight: number;+ threadTop: number;+ /** Px the leading spacer carries beyond its rows' heights. */+ slack: number;+ heightOf: (index: number) => number;+ maxStep: number;+ trim: boolean;+ reach?: number;+ keep?: number;+};++/** Extend toward an edge within reach, drop rows past keep, re-centre when the viewport is in a+ * spacer. Pins are the caller's. */+export function planSlide(input: SlideInput): RowWindow {+ const { win, count, rows, viewHeight, heightOf, maxStep } = input;+ const reach = input.reach ?? WINDOW_REACH_PX;+ const keep = input.keep ?? WINDOW_KEEP_PX;+ let start = Math.max(0, Math.min(win.start, count));+ let end = Math.max(start, Math.min(win.end, count));++ const first = rows[0];+ const last = rows[rows.length - 1];++ if (first && last) {+ // A jump outran the window: open a fresh one where the offset lands, walked by the heights+ // the spacers are sized from.+ const above = first.top - viewHeight;+ const below = -last.bottom;+ if (above > keep || below > keep) {+ let index = 0;+ let offset = -input.threadTop - input.slack;+ while (index < count - 1) {+ const height = heightOf(index);+ if (offset < height) break;+ offset -= height;+ index += 1;+ }+ let covered = -offset;+ let next = index;+ let mounted = 0;+ while (next < count && mounted < maxStep && covered < viewHeight + reach) {+ const height = heightOf(next);+ if (height > 0) mounted += 1;+ covered += height;+ next += 1;+ }+ return { start: index, end: Math.max(next, index + 1) };+ }+ }++ let extendedUp = false;+ let extendedDown = false;+ if (start > 0) {+ let gap = (first ? first.top : 0) + reach;+ let mounted = 0;+ while (gap > 0 && start > 0 && mounted < maxStep) {+ start -= 1;+ const height = heightOf(start);+ if (height > 0) mounted += 1;+ gap -= height;+ extendedUp = true;+ }+ }+ if (end < count) {+ let gap = viewHeight + reach - (last ? last.bottom : viewHeight);+ let mounted = 0;+ while (gap > 0 && end < count && mounted < maxStep) {+ const height = heightOf(end);+ if (height > 0) mounted += 1;+ gap -= height;+ end += 1;+ extendedDown = true;+ }+ }++ if (input.trim) {+ if (!extendedUp) {+ for (const row of rows) {+ if (row.bottom >= -keep) break;+ start = Math.max(start, row.index + 1);+ }+ }+ if (!extendedDown) {+ for (let at = rows.length - 1; at >= 0; at -= 1) {+ const row = rows[at];+ if (row.top <= viewHeight + keep) break;+ end = Math.min(end, row.index);+ }+ }+ }+ if (end <= start) end = Math.min(count, start + 1);+ return { start, end };+}++export const FILL_BUDGET_PX = 20_000;++/** Widen both ways by up to `chunk` rows each and `budgetPx` in all (one row at least), so a pass+ * over very long replies is not seconds of layout. Null once the window covers the thread. */+export function planFill(+ win: RowWindow,+ count: number,+ chunk: number,+ heightOf: (index: number) => number = () => 0,+ budgetPx = FILL_BUDGET_PX,+): RowWindow | null {+ let start = Math.max(0, Math.min(win.start, count));+ let end = Math.max(start, Math.min(win.end, count));+ let up = 0;+ let down = 0;+ let spent = 0;+ let mounted = 0;+ for (;;) {+ const canUp = start > 0 && up < chunk;+ const canDown = end < count && down < chunk;+ if (!canUp && !canDown) break;+ const goUp = canUp && (!canDown || up <= down);+ const height = heightOf(goUp ? start - 1 : end);+ if (mounted > 0 && spent + height > budgetPx) break;+ if (goUp) {+ start -= 1;+ up += 1;+ } else {+ end += 1;+ down += 1;+ }+ spent += height;+ if (height > 0) mounted += 1;+ }+ if (start <= 0 && end >= count) return null;+ return { start, end };+}++/** Null when the thread is short or too little would unmount to be worth a commit. */+export function planEngage(+ rows: readonly MountedRow[],+ count: number,+ viewHeight: number,+ keep = WINDOW_KEEP_PX,+): RowWindow | null {+ const first = rows[0];+ const last = rows[rows.length - 1];+ if (!first || !last || !worthWindowing(count, last.bottom - first.top)) return null;+ let start = 0;+ let end = count;+ let keptTop = first.top;+ let keptBottom = last.bottom;+ for (const row of rows) {+ if (row.bottom >= -keep) {+ keptTop = row.top;+ break;+ }+ start = row.index + 1;+ }+ for (let at = rows.length - 1; at >= 0; at -= 1) {+ const row = rows[at];+ if (row.top <= viewHeight + keep) {+ keptBottom = row.bottom;+ break;+ }+ end = row.index;+ }+ const freed = keptTop - first.top + (last.bottom - keptBottom);+ if (end <= start || freed < keep) return null;+ return { start, end };+}++function samePins(a: readonly number[] = [], b: readonly number[] = []): boolean {+ return a.length === b.length && a.every((pin, at) => pin === b[at]);+}++export const TAIL_TURN_MAX_ROWS = 4;++/** A tail window also holds the last prompt: a reply taller than the keep distance would drop it. */+export function holdTailTurn(+ win: RowWindow | null,+ count: number,+ tailTurn: number,+): RowWindow | null {+ if (win == null || win.end < count || tailTurn < 0 || win.start <= tailTurn) return win;+ if (win.start - tailTurn > TAIL_TURN_MAX_ROWS) return win;+ return withPins({ start: tailTurn, end: win.end }, win.pins ?? [], count);+}++export const sameWindow = (a: RowWindow | null, b: RowWindow | null): boolean =>+ a === b ||+ (a != null && b != null && a.start === b.start && a.end === b.end && samePins(a.pins, b.pins));++/** The leading spacer takes an anchor shift; only what it cannot take is left for scrollTop. */+export function absorbShift(+ spacerPx: number,+ shiftPx: number,+ atFirstRow: boolean,+): { spacer: number; scroll: number } {+ if (atFirstRow) return { spacer: 0, scroll: shiftPx - spacerPx };+ const wanted = spacerPx - shiftPx;+ if (wanted >= 0) return { spacer: wanted, scroll: 0 };+ return { spacer: 0, scroll: -wanted };+}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 992e905e53b..294ec73c444 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -2352,17 +2352,17 @@ export const Thread: FC<{<TurnNavigator viewportRef={viewportElRef} />- {/* 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. */}+ {/* Drop-in for ThreadPrimitive.Messages that mounts only the rows near the reader, with a+ spacer for the rows on either side, so a thread costs what is on screen and not its+ length. Readers of the whole document (find, print, select all) call+ completeProgressiveMounts. It takes the propless slot #9042 introduced: React's bail-out+ needs one shared element per row. See thread-window.ts. */}<ProgressiveMessagesrenderMessage={renderThreadMessage}resetKey={runtimeThreadId}viewportRef={viewportElRef}/>+ <ForkChatShortcut />{/* Bottom slack so the last message has room above the stickyscroll-to-bottom button (and floating composer in single mode),@@ -4085,15 +4085,16 @@ const Composer: FC<{const cancelAudioUpload = audioUpload.cancel;// Read at Send time so a send materializing after a project switch is filed where made.const projectScope = useChatProjectScope();- const promptQueueThreadIds = compactIds([- threadListItemId,- threadListItemRemoteId,- threadId,- ]);- const preStreamThreadIds = compactIds([- ...promptQueueThreadIds,- referenceThreadId,- ]);+ // One array per set of ids, not per render: the queue callbacks and the context they feed are+ // keyed on these, and the composer renders on every keystroke.+ const promptQueueThreadIds = useMemo(+ () => compactIds([threadListItemId, threadListItemRemoteId, threadId]),+ [threadListItemId, threadListItemRemoteId, threadId],+ );+ const preStreamThreadIds = useMemo(+ () => compactIds([...promptQueueThreadIds, referenceThreadId]),+ [promptQueueThreadIds, referenceThreadId],+ );const preStreamRunReservationRef = useRef<symbol | null>(null);// Wakes a parked attachment when a preflight releases without ever streaming.const preStreamRunActive = useSyncExternalStore(@@ -5943,20 +5944,84 @@ const Composer: FC<{[aui, startHydratedPromptQueue, threadIsRunning, disableQueue],);- const queueContextValue: PromptQueueCallbacks = { startQueue, stopQueue };+ const queueContextValue: PromptQueueCallbacks = useMemo(+ () => ({ startQueue, stopQueue }),+ [startQueue, stopQueue],+ );// Skills off sends no read_skill, so a mention would load nothing.const [skillsSwitchOn] = useSkillsSwitch();+ // The composer renders on every keystroke, since it owns the draft. Nothing in these controls+ // reads the text, so their elements are kept from one render to the next: React skips a subtree+ // whose element is the one it rendered last. Measured on a keystroke: 297 component renders+ // under the composer without this, 68 with it.+ const toolsMenu = useMemo(+ () => (+ <ComposerToolsMenu+ inputRef={inputRef}+ side={effectiveMenuSide}+ researchAvailable={!researchUsed}+ audioUploadBusy={audioUpload.busy}+ />+ ),+ [effectiveMenuSide, researchUsed, audioUpload.busy],+ );+ const pills = useMemo(+ () => (+ <>+ <PermissionModeComposerPill side={effectiveMenuSide} />+ {effectiveDeepResearchEnabled ? (+ <DeepResearchComposerButton+ onConfigure={() => setResearchWebsiteAccessOpen(true)}+ />+ ) : null}+ <WebSearchToggle />+ <CodeToolsToggle />+ <BrowserAgentPill glyph={(icon) => <PillGlyph>{icon}</PillGlyph>} />+ <ImagesToggle />+ <KnowledgeBaseComposerButton side={effectiveMenuSide} />+ {mcpEnabledForChat ? (+ <McpComposerButton side={effectiveMenuSide} />+ ) : null}+ <SkillsComposerButton side={effectiveMenuSide} />+ </>+ ),+ [effectiveMenuSide, effectiveDeepResearchEnabled, mcpEnabledForChat],+ );+ const attachments = useMemo(+ () => (+ <>+ <ComposerAttachments oneRowInChat={true} />+ <PendingAudioChip />+ </>+ ),+ [],+ );+ const toolStatus = useMemo(() => <ToolStatusDisplay />, []);+ const documentsBar = useMemo(+ () => (+ <ThreadDocumentsBar+ threadId={referenceThreadId}+ onIndexingChange={handleIndexingChange}+ />+ ),+ [referenceThreadId, handleIndexingChange],+ );+ const researchWebsiteAccessDialog = useMemo(+ () => (+ <DeepResearchWebsiteAccessDialog+ open={researchWebsiteAccessOpen && effectiveDeepResearchEnabled}+ onOpenChange={setResearchWebsiteAccessOpen}+ />+ ),+ [researchWebsiteAccessOpen, effectiveDeepResearchEnabled],+ );+const composerContent = (<>- {!isDictating ? (- <>- <ComposerAttachments oneRowInChat={true} />- <PendingAudioChip />- </>- ) : null}+ {!isDictating ? attachments : null}{!isDictating ? <ComposerDraftPreview text={composerText} /> : null}- {!isDictating ? <ToolStatusDisplay /> : null}+ {!isDictating ? toolStatus : null}<divclassName="unsloth-composer-line"// The permission pill is always visible, so stay two-row unless dictating.@@ -5968,31 +6033,8 @@ const Composer: FC<{className="unsloth-composer-left"data-pill-compact={pillCompact}>- <ComposerToolsMenu- inputRef={inputRef}- side={effectiveMenuSide}- researchAvailable={!researchUsed}- audioUploadBusy={audioUpload.busy}- />- {!isDictating ? (- <>- <PermissionModeComposerPill side={effectiveMenuSide} />- {effectiveDeepResearchEnabled ? (- <DeepResearchComposerButton- onConfigure={() => setResearchWebsiteAccessOpen(true)}- />- ) : null}- <WebSearchToggle />- <CodeToolsToggle />- <BrowserAgentPill glyph={(icon) => <PillGlyph>{icon}</PillGlyph>} />- <ImagesToggle />- <KnowledgeBaseComposerButton side={effectiveMenuSide} />- {mcpEnabledForChat ? (- <McpComposerButton side={effectiveMenuSide} />- ) : null}- <SkillsComposerButton side={effectiveMenuSide} />- </>- ) : null}+ {toolsMenu}+ {!isDictating ? pills : null}</div>{isDictating ? (<ChatDictationBar@@ -6110,10 +6152,7 @@ const Composer: FC<{</>)}</div>- <DeepResearchWebsiteAccessDialog- open={researchWebsiteAccessOpen && effectiveDeepResearchEnabled}- onOpenChange={setResearchWebsiteAccessOpen}- />+ {researchWebsiteAccessDialog}<ChatAudioUploadMount audioUpload={audioUpload} /></>);@@ -6162,10 +6201,7 @@ const Composer: FC<{<PromptQueueStack queueThreadIds={promptQueueThreadIds} />{/* Chat with files card. Stays mounted while dictating to keep indexing state. */}<div className={isDictating ? "hidden" : "contents"}>- <ThreadDocumentsBar- threadId={referenceThreadId}- onIndexingChange={handleIndexingChange}- />+ {documentsBar}</div>{youtubeOfferUrl && !isDictating && !disabled ? (// Keyed by URL so a second paste remounts and aborts the stale request.@@ -8612,10 +8648,6 @@ const AssistantMessage: FC = () => {<AssistantActionBar /></div></WindowedMessageBody>- {/* Renders nothing. `If last` keeps the hook off the other N-1. */}- <MessagePrimitive.If last={true}>- <ForkChatShortcut />- </MessagePrimitive.If>{/* Trailing stop so Shift+Tab enters the action bar; the root's onFocus mounts it. */}<span@@ -8667,10 +8699,9 @@ const ForkCountBadge: FC = () => {);};-const useForkMessageAction = () => {+const useForkMessageAction = (messageId: string | undefined) => {const aui = useAui();const navigate = useNavigate();- const messageId = useAuiState(({ message }) => message.id);const isRunning = useAuiState(({ thread }) => thread.isRunning);const pending = useForkInFlight((s) => s.forking);const setPending = useForkInFlight((s) => s.setForking);@@ -8678,6 +8709,7 @@ const useForkMessageAction = () => {const handleFork = async () => {// Read the store, not the render: two handlers can run in one tick.if (useForkInFlight.getState().forking) return;+ if (!messageId) return;const remoteId = aui.threadListItem().getState().remoteId;if (!remoteId) {toast.error("Cannot fork an unsaved chat");@@ -8722,9 +8754,11 @@ const useForkMessageAction = () => {};};-/** The fork chord's registration, mounted once under `If last`: autohidden action bars drop it. */+/** The fork chord's registration, mounted once per thread outside the rows: the window unmounts+ * the last row when the reader scrolls away, and autohidden action bars drop theirs. */const ForkChatShortcut: FC = () => {- const { forkMessage, forkDisabled } = useForkMessageAction();+ const lastId = useAuiState(({ thread }) => thread.messages.at(-1)?.id);+ const { forkMessage, forkDisabled } = useForkMessageAction(lastId);const chatActive = useChatActive();// Compare mounts a thread per pane and the chord goes to whichever registered first.const inComparePane = useInComparePane();@@ -8735,13 +8769,14 @@ const ForkChatShortcut: FC = () => {if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;void forkMessage();},- { enabled: chatActive && !inComparePane && !forkDisabled },+ { enabled: lastId !== undefined && chatActive && !inComparePane && !forkDisabled },);return null;};const ForkMessageButton: FC = () => {- const { forkMessage, forkDisabled } = useForkMessageAction();+ const messageId = useAuiState(({ message }) => message.id);+ const { forkMessage, forkDisabled } = useForkMessageAction(messageId);return (<TooltipIconButton@@ -9269,8 +9304,16 @@ const ScheduledTaskSource: FC = () => {);};+/** Prompts already shown: the thread window remounts rows, and a remount must not replay the arrival. */+const shownPrompts = new Set<string>();+const UserMessage: FC = () => {const focusReveal = useActionBarFocusReveal();+ const id = useAuiState(({ message }) => message.id);+ const [arriving] = useState(() => !shownPrompts.has(id));+ useEffect(() => {+ shownPrompts.add(id);+ }, [id]);const promptRef = focusReveal.ref;const adjustAbove = useAdjustForContentInsertedAbove();useEffect(() => {@@ -9282,7 +9325,10 @@ const UserMessage: FC = () => {);return (<MessagePrimitive.Root- className="aui-user-message-root fade-in slide-in-from-bottom-1 mx-auto flex w-full max-w-(--thread-content-max-width) animate-in flex-col items-end gap-y-2 pt-6 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em] duration-150"+ className={cn(+ "aui-user-message-root mx-auto flex w-full max-w-(--thread-content-max-width) flex-col items-end gap-y-2 pt-6 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]",+ arriving && "fade-in slide-in-from-bottom-1 animate-in duration-150",+ )}data-role="user"tabIndex={0}{...focusReveal}@@ -9306,9 +9352,6 @@ const UserMessage: FC = () => {</UserMessageFooter></div></WindowedMessageBody>- <MessagePrimitive.If last={true}>- <ForkChatShortcut />- </MessagePrimitive.If>{/* Reverse traversal reaches a trailing stop before the root. Focusing itmounts the autohidden controls, so the next Shift+Tab enters its controlsinstead of skipping the action bar and leaving the message. */}@@ -9349,7 +9392,8 @@ const UserActionBar: FC = () => {const UserMoreMenu: FC = () => {const triggerRef = useRef<HTMLButtonElement>(null);const collisionPadding = useWindowChromeCollisionPadding(undefined);- const { forkMessage, forkDisabled } = useForkMessageAction();+ const messageId = useAuiState(({ message }) => message.id);+ const { forkMessage, forkDisabled } = useForkMessageAction(messageId);return (// Non-modal: see AssistantActionBar.<ActionBarMorePrimitive.Root modal={false}>diff --git a/studio/frontend/src/components/assistant-ui/turn-navigation.tsx b/studio/frontend/src/components/assistant-ui/turn-navigation.tsxindex d49c449f3f4..8d6eb9f8628 100644--- a/studio/frontend/src/components/assistant-ui/turn-navigation.tsx+++ b/studio/frontend/src/components/assistant-ui/turn-navigation.tsx@@ -28,6 +28,8 @@ import { createPortal } from "react-dom";import {completeProgressiveMounts,hasPendingProgressiveMounts,+ revealProgressiveRow,+ subscribeMountedRows,} from "@/components/assistant-ui/progressive-messages";import {threadTurns,@@ -341,6 +343,10 @@ const TurnRail: FC<{ viewportRef: RefObject<HTMLElement | null> }> = ({}const selector = `[data-message-id="${CSS.escape(messageId)}"]`;let target = viewport.querySelector<HTMLElement>(selector);+ // The thread mounts only the rows near the reader; ask for this one rather than for all.+ if (!target && revealProgressiveRow(viewport, messageId)) {+ target = viewport.querySelector<HTMLElement>(selector);+ }if (!target) {await completeProgressiveMounts((candidate) => candidate === viewport);target = viewport.querySelector<HTMLElement>(selector);@@ -546,18 +552,30 @@ const TurnRail: FC<{ viewportRef: RefObject<HTMLElement | null> }> = ({},{ root: viewport },);- const messages = new Map<string, Element>();- for (const message of viewport.querySelectorAll("[data-message-id]")) {- messages.set(message.getAttribute("data-message-id") ?? "", message);- }- for (const marker of rail.querySelectorAll<HTMLElement>("button[data-turn-id]")) {- const message = messages.get(marker.dataset.turnId ?? "");- if (message) {- markerFor.set(message, marker);- observer.observe(message);+ // Rows mount and unmount as the reader moves, so the watched set follows them.+ const watch = () => {+ observer.disconnect();+ markerFor.clear();+ const messages = new Map<string, Element>();+ for (const message of viewport.querySelectorAll("[data-message-id]")) {+ messages.set(message.getAttribute("data-message-id") ?? "", message);}- }- return () => observer.disconnect();+ for (const marker of rail.querySelectorAll<HTMLElement>("button[data-turn-id]")) {+ const message = messages.get(marker.dataset.turnId ?? "");+ if (message) {+ markerFor.set(message, marker);+ observer.observe(message);+ } else {+ marker.removeAttribute("data-in-view");+ }+ }+ };+ watch();+ const unsubscribe = subscribeMountedRows(watch);+ return () => {+ unsubscribe();+ observer.disconnect();+ };}, [viewportRef, signature, turnCount]);const hidePreview = useCallback(() => {cancelHide();diff --git a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.tsindex 37491337ce6..303a70c2cce 100644--- a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts+++ b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts@@ -224,8 +224,10 @@ export function useFindInPage(// The thread mounts its tail first, so complete progressive mounts for this scope only.let live = true;- void completeProgressiveMounts((viewport) =>- indexReaches(scope, viewport),+ const fill = new AbortController();+ void completeProgressiveMounts(+ (viewport) => indexReaches(scope, viewport),+ fill.signal,).then(() => {if (!live) return;// Only re-anchor if completion actually renumbered, so a mid-run Enter is kept.@@ -314,6 +316,7 @@ export function useFindInPage(return () => {live = false;+ fill.abort();cancelRevealPasses();window.removeEventListener("resize", invalidate);window.removeEventListener("wheel", noteScroll, { capture: true });diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.tsindex 7b2acfbf94b..fed0b9509bf 100644--- a/studio/frontend/tests/find-in-page.test.ts+++ b/studio/frontend/tests/find-in-page.test.ts@@ -2492,14 +2492,17 @@ test("Escape closes the bar from the walk buttons, not just the field", async ()test("only threads this search can read are forced to finish mounting", async () => {assert.match(USE_FIND_IN_PAGE,- /completeProgressiveMounts\(\(viewport\) =>\s*\n?\s*indexReaches\(scope, viewport\)/,+ /completeProgressiveMounts\(\s*\(viewport\) =>\s*\n?\s*indexReaches\(scope, viewport\),\s*fill\.signal,/,);+ // Closing Find lets go of the full mount it asked for, so the window slides again at once.+ assert.match(USE_FIND_IN_PAGE, /live = false;\s*fill\.abort\(\);/);const progressive = await readSrcAsync("components/assistant-ui/progressive-messages.tsx",);+ // Re-read on every pass and filtered, so a thread this search cannot read never holds it open.assert.match(progressive,- /if \(wanted\(\)\.length === 0 && \(observed \|\| Date\.now\(\) >= deadline\)\)/,+ /!wanted\(\)\.some\(\(entry\) => entry\.withholding\(\)\) &&\s*\(observed \|\| Date\.now\(\) >= deadline\)/,);});diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.tsindex ddcb715860d..7ed623beb0b 100644--- a/studio/frontend/tests/keyboard-shortcuts.test.ts+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts@@ -1022,9 +1022,11 @@ test("the chords that need one target do not fire where there are two", async ()chatPage,/enabled: headerPickersShown,\n\s*claims: chatUncovered,\n\s*\}/,);- // Both panes mount the last message, and the chord would go to whichever- // registered its listener first. `If last` carries the other half.- assert.match(thread, /enabled: chatActive && !inComparePane && !forkDisabled/);+ // Both panes mount a thread, and the chord would go to whichever registered its listener first.+ assert.match(+ thread,+ /enabled: lastId !== undefined && chatActive && !inComparePane && !forkDisabled/,+ );assert.match(toolCard,/soleRequest &&\n\s*!selectionActive &&\n\s*showControls &&/,@@ -1137,18 +1139,14 @@ test("the fork chord is registered where it mounts, not from an action bar", asy"the per-instance flag is what let two forks run",);- const mounts = THREAD.match(- /<MessagePrimitive\.If last=\{true\}>\n\s*<ForkChatShortcut \/>\n\s*<\/MessagePrimitive\.If>/g,+ // Once per thread, beside the windowed rows: a row holding it unmounts when scrolled away.+ assert.ok(!THREAD.includes("<MessagePrimitive.If last={true}>\n <ForkChatShortcut />"));+ assert.equal(THREAD.match(/<ForkChatShortcut \/>/g)?.length, 1);+ assert.match(THREAD, /viewportRef=\{viewportElRef\}\n\s*\/>\n\s*<ForkChatShortcut \/>/);+ assert.match(+ block,+ /const lastId = useAuiState\(\(\{ thread \}\) => thread\.messages\.at\(-1\)\?\.id\);/,);- assert.equal(mounts?.length, 2);- for (const role of ["const AssistantMessage", "const UserMessage: FC"]) {- const at = THREAD.indexOf(role);- assert.notEqual(at, -1, `${role} moved`);- assert.ok(- THREAD.slice(at, THREAD.indexOf("\n};", at)).includes("<ForkChatShortcut />"),- `${role} does not mount the fork chord`,- );- }});// The tour's opener pins the picker and an effect unpins it when no tour runs.diff --git a/studio/frontend/tests/progressive-mount-controller.test.ts b/studio/frontend/tests/progressive-mount-controller.test.tsindex ea0e5e50add..9ba89bc0046 100644--- a/studio/frontend/tests/progressive-mount-controller.test.ts+++ b/studio/frontend/tests/progressive-mount-controller.test.ts@@ -1,29 +1,20 @@// 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 window only grows and always reaches null; shrinking would unmount a message.-// The .tsx glue is pinned in progressive-mount-glue.test.ts.+// Pacing of a full mount and the anchor arithmetic shared by every window commit. Which rows are+// mounted is tested in thread-window.test.ts; the .tsx glue in progressive-mount-glue.test.ts.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,- alignAnchorCorrection,- initialWindow,- isCovered,FAR_MOUNT_CHUNK,nextMountChunk,- stepsToCover,watchProgressiveScroll,- widen,} from "../src/components/assistant-ui/progressive-mount-controller.ts";+import { type RowWindow, planFill } from "../src/components/assistant-ui/thread-window.ts";test("mounting waits for wheel momentum and thumb release, without pausing on its own corrections", () => {const viewport = new EventTarget();@@ -83,129 +74,29 @@ test("scroll keys, touch momentum, and composer input outside the viewport pauseassert.equal(activity.blocked(false), false);});-test("a thread under the floor is never windowed", () => {- for (const count of [0, 1, 20, MIN_PROGRESSIVE_MESSAGES - 1]) {- assert.equal(- 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 paints 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("smaller renderer batches still converge without skipping messages", () => {- let current = initialWindow(600, false);- let previous = current!.start;- while (current !== null) {- current = widen(current, 600, 2);- const start = current?.start ?? 0;- assert.ok(start < previous && previous - start <= 2);- previous = start;+test("a stream's own autoscroll does not hold a full mount off, only the reader's momentum does", () => {+ const viewport = new EventTarget();+ let time = 1000;+ const activity = watchProgressiveScroll(viewport, () => time);+ const send = (type: string) => viewport.dispatchEvent(new Event(type));+ // Inside the opening pause, scrolls with no input behind them (the autoscroll) do not renew it.+ for (let at = 0; at < 10; at += 1) {+ time += 100;+ send("scroll");}-});--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`);+ assert.equal(activity.blocked(false), false);+ // A fling: momentum scrolls keep the pause going for as long as they run, input or not.+ send("touchmove");+ for (let at = 0; at < 20; at += 1) {+ time += 100;+ send("scroll");+ assert.equal(activity.blocked(false), true);}-});--test("the number of widening frames is bounded and small", () => {- // At 60Hz seven frames is under 120ms, the budget this 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", () => {- // {start: 0} renders the same as null, so leaving it wastes a full re-render frame.- 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 must not leave the window past the end.- 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 the first commit cannot quietly become one row or everything.- 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",- );+ // Past the momentum allowance, scrolling alone lets the full mount go on.+ time += 1100;+ send("scroll");+ time += 301;+ assert.equal(activity.blocked(false), false);});const sample = (viewportOffset: number, scrollTop: number, maxScrollTop = 1_000_000) => ({@@ -238,27 +129,6 @@ 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", () => {- // Clamping then subtracting a chunk would unmount rows the caller already rendered.- assert.equal(widen({ start: 204 }, 100), null);- assert.equal(widen({ start: 204 }, 0), null);- assert.equal(widen({ start: 100 }, 100), null);- assert.deepEqual(widen({ start: 99 }, 100), { start: 99 - CHUNK_MESSAGES });-});--test("widening is monotone in start for every reachable window and count", () => {- 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 clamps scrollTop on shrink; apply only the unabsorbed part.assert.equal(@@ -271,166 +141,6 @@ test("a shrink the browser already clamped is not corrected twice", () => {);});-// Roles with no component render null and have no height, so size the tail by renderable rows.--function tailIsUnrenderable(count: number, systemTail: number) {- return (index: number) => index < count - systemTail;-}--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);- assert.equal(visibleRows(w, count, renders), INITIAL_MESSAGES);- 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);- assert.ok(w != null && w.start >= 0 && w.start < count);- assert.equal(visibleRows(w, count, renders), INITIAL_MESSAGES);- 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", () => {- 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", () => {- 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", () => {- assert.deepEqual(initialWindow(220, false), {- start: 220 - INITIAL_MESSAGES,- });- assert.deepEqual(- initialWindow(220, false, () => true),- {- start: 220 - INITIAL_MESSAGES,- },- );-});--// The renderable-row walk must stay bounded, or a long non-rendering tail mounts everything.--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", () => {- 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", () => {- 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");- }-});--test("fractional prepends and reflows keep the visible anchor stationary with integer scrolling", () => {- let inset = 0;- let contentTop = 0;- let scrollTop = 0;- for (let index = 0; index < 600; index++) {- const delta = [4408.625, 4210.4375, -0.375, 0.1875, -12.5625][index % 5];- contentTop += delta;- const aligned = alignAnchorCorrection(delta, inset);- assert.equal(Number.isInteger(aligned.scroll), true);- assert.ok(aligned.inset >= 0 && aligned.inset < 1);- inset = aligned.inset;- scrollTop += aligned.scroll;- assert.equal(contentTop + inset - scrollTop, 0);- }-});--test("subpixel reflows can be absorbed without issuing fractional scroll writes", () => {- const before = sample(30, 12000);- const after = sample(30.375, 12000);- assert.equal(anchorCorrection(before, after), null);- assert.equal(anchorCorrection(before, after, 1 / 64), 0.375);- assert.equal(anchorCorrection(before, before, 1 / 64), null);- assert.deepEqual(alignAnchorCorrection(-0.375, 0), { scroll: 0, inset: 0.375 });-});-test("WebKitGTK steps stay small near the reader and ramp to FAR_MOUNT_CHUNK past the window reach", () => {const near = 2;const reach = 2000;@@ -457,13 +167,13 @@ test("WebKitGTK steps stay small near the reader and ramp to FAR_MOUNT_CHUNK pas// The near step already being the cap (other engines) never changes it.assert.equal(nextMountChunk(CHUNK_MESSAGES, 10_000, CHUNK_MESSAGES, reach), CHUNK_MESSAGES);assert.equal(nextMountChunk(CHUNK_MESSAGES, null, CHUNK_MESSAGES, reach), CHUNK_MESSAGES);- // A 300-message thread past the reach covers in about 20 commits instead of about 142.- let current: MountWindow = initialWindow(300, false);+ // A 300-message thread past the reach is fully mounted in about 20 commits instead of about 142.+ let current: RowWindow | null = { start: 298, end: 300 };let commits = 0;chunk = 0;while (current != null) {chunk = nextMountChunk(chunk, reach + 1, near, reach);- current = widen(current, 300, chunk);+ current = planFill(current, 300, chunk);commits += 1;}assert.ok(commits <= 24, `took ${commits} commits`);diff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.tsindex 78b1c197061..314cfb0daaf 100644--- a/studio/frontend/tests/progressive-mount-glue.test.ts+++ b/studio/frontend/tests/progressive-mount-glue.test.ts@@ -1,7 +1,8 @@// 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 progressive mount glue lives in .tsx, which node type stripping cannot import, so assert on source.+// The mount window glue lives in .tsx, which node type stripping cannot import, so assert on+// source. The window maths it calls is tested directly in thread-window.test.ts.import assert from "node:assert/strict";import test from "node:test";@@ -19,6 +20,7 @@ const HOOK = code(readText("../src/components/assistant-ui/use-intent-aware-autoscroll.tsx"),);const THREAD = code(readText("../src/components/assistant-ui/thread.tsx"));+const TURNS = code(readText("../src/components/assistant-ui/turn-navigation.tsx"));/** Both markers required: indexOf -1 or a moved end marker would silently widen the slice. */const section = (source: string, from: string, to: string): string => {@@ -33,13 +35,13 @@ const section = (source: string, from: string, to: string): string => {const GLUE_WINDOW = () =>section(GLUE,- "function useProgressiveMountWindow(",+ "function useThreadWindow(","ProgressiveMessages.displayName",);test("the thread renders rows through MessageByIndex, never ThreadPrimitive.Messages", () => {// Upstream renders MessageByIndexProvider, RenderChildrenWithAccessor, then children, while this- // row map skips the accessor; switching between them on convergence would remount every message.+ // row map skips the accessor; switching between them would remount every message.assert.match(GLUE,/<AuiProvider key=\{index\} value=\{gate\.row\(index\)\}>\s*<MessageByIndexProvider index=\{index\}>/,@@ -47,12 +49,12 @@ test("the thread renders rows through MessageByIndex, never ThreadPrimitive.Messassert.doesNotMatch(GLUE,/<ThreadPrimitive\.Messages\b/,- "the row map must not switch primitives on convergence",+ "the row map must not switch primitives",);assert.doesNotMatch(THREAD,/<ThreadPrimitive\.Messages\b/,- "Thread must render the progressive list, not the unbounded one",+ "Thread must render the windowed list, not the unbounded one",);assert.match(THREAD, /<ProgressiveMessages/);// React's bail-out needs one shared element per row; a `components` object reallocates props.@@ -71,79 +73,147 @@ test("rows outside the window are not rendered rather than rendered and hidden",assert.doesNotMatch(glue, /display:\s*["']?none/);assert.doesNotMatch(glue, /visibility:\s*["']?hidden/);assert.doesNotMatch(glue, /content-visibility/);+ // The only rows rendered are the ones the layout lists: the window's and the pinned ones.+ assert.match(glue, /return threadSlots\(win, count\)\.map\(\(slot\) => \{\s*if \(slot\.kind === "row"\) \{/);});-test("the window is only ever advanced through widen", () => {- // Any other setter could move `start` upward and unmount a message.- const calls = [...GLUE.matchAll(/setMountWindow\(([^;]*?)\)\s*[;,]/gs)].map(- (m) => m[1].trim(),- );- assert.ok(- calls.length >= 4,- `expected several setMountWindow calls, found ${calls.length}`,+test("the window is only ever set to what a planner returned", () => {+ // Any other setter could mount or unmount rows the reader's position did not ask for.+ const calls = [...GLUE.matchAll(/setWin\(([^;]*?)\)\s*[;,]/gs)].map((m) =>+ m[1].replace(/\s+/g, " ").trim(),);+ assert.ok(calls.length >= 5, `expected several setWin calls, found ${calls.length}`);+ const allowed = new Set(["open()", "next", "followed"]);for (const call of calls) {- const ok =- call === "null" ||- call.startsWith("initialWindow(") ||- call.includes("widen(current, count, chunk)");- assert.ok(- ok,- `setMountWindow(${call}) is not one of null / initialWindow / widen`,- );+ assert.ok(allowed.has(call), `setWin(${call}) is not an opening, a clamp, a reveal or a plan`);}+ assert.match(GLUE, /const followed = followCount\(win, previousCount, count\);\s*if \(followed !== win\) setWin\(followed\);/);+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(step, /next = planFill\(current, total, chunk, heightOf\);/);+ assert.match(step, /next = planSlide\(\{/);+ assert.match(step, /const next = holdTailTurn\(\s*planEngage\(/);+ // A window at the tail holds the last prompt too, from the first open on.+ assert.match(step, /next = holdTailTurn\(next, total, lookup\.tailTurn\);/);+ assert.match(GLUE, /return holdTailTurn\(opened, metas\.length, tailTurn\);/);+ assert.match(step, /if \(sameWindow\(next, current\)\)/);+ const reveal = section(GLUE, "const reveal = useCallback(", "[aui, readMetas, viewportRef],");+ assert.match(reveal, /const next = keepPinned\(\s*viewport,\s*lookup,\s*\{ start: index, end: Math\.min\(total, index \+ SLIDE_STEP\) \},\s*tail,\s*\);/);});-test("a run drops the window", () => {- // Two gates: reactive for later runs, in-frame re-check for runs between commit and rAF.- assert.match(GLUE, /thread\.isRunning/);- assert.match(+test("a run keeps the window, and the reply being written keeps its row", () => {+ // Agent chats run most of the time: dropping the window for a run would mount the whole thread.+ assert.doesNotMatch(GLUE, /threadIsRunning/);+ assert.doesNotMatch(GLUE,- /if \(threadIsRunning && mountWindow != null\) setMountWindow\(null\)/,+ /isRunning[^;]*\)\s*setWin\(null\)/,+ "a run must not drop the window",);- assert.match(GLUE, /if \(isRunningNow\(\)\) \{\s*setMountWindow\(null\);/);+ // The streaming row's effects run the stream; scrolling away must not unmount it.+ assert.match(GLUE, /const tail = aui\.thread\(\)\.getState\(\)\.isRunning === true \? total - 1 : null;/);+ assert.match(GLUE, /if \(dialog \|\| index === tail \|\| isPinned\(child, selection\)\) pins\.push\(index\);/);});-test("the widening step is deferred and WebKit commits inside the animation frame", () => {- assert.match(GLUE, /requestAnimationFrame\(/);- assert.match(GLUE, /startTransition\(/);- assert.match(GLUE, /if \(WEBKIT_GTK\) flushSync\(commit\);/);- assert.match(GLUE, /cancelAnimationFrame\(frame\)/);- // Scoped to the widening effect: a timer fires before paint and its handle cannot be- // cancelled as a frame.- const widening = section(- GLUE,- "if (mountWindow == null) return;",- "}, [mountWindow, count, captureAnchor, isRunningNow, viewportRef]);",- );+test("rows the reader is working in are not unmounted", () => {+ const pinned = section(GLUE, "function isPinned(", "\n}\n");+ assert.match(pinned, /row\.contains\(document\.activeElement\)/);+ assert.match(pinned, /row\.querySelector\(PINNED_CONTENT\)/);+ assert.match(pinned, /if \(!media\.paused\) return true;/);+ assert.match(GLUE, /const PINNED_CONTENT = "textarea, \[contenteditable=true\], iframe";/);+ assert.match(pinned, /if \(selection\?\.some\(\(range\) => range\.intersectsNode\(row\)\)\) return true;/);+ // A selection reaching into the thread, or a held pointer, holds every mounted row.+ assert.match(GLUE, /trim: \(trim =\s*heldSelection\(viewport\) === null &&\s*!inputPointerHeld\(\) &&\s*document\.querySelector\(OPEN_DIALOG\) === null\),/);+ // A dialog a row opened is portaled out of it; while one is open every mounted row stays.+ assert.match(GLUE, /const dialog = document\.querySelector\(OPEN_DIALOG\) !== null;/);assert.match(- widening,- /frame = requestAnimationFrame\(advance\)/,- "the widening step must be scheduled on a frame, not a timer",+ section(GLUE, "function heldSelection(", "\n}\n"),+ // Every range, not the first: Firefox's Ctrl-drag selects several messages apart.+ /for \(let at = 0; at < selection\.rangeCount; at \+= 1\) \{\s*const range = selection\.getRangeAt\(at\);\s*if \(range\.intersectsNode\(viewport\)\) ranges\.push\(range\);/,+ );+});++test("a pinned row survives every way the window can leave it behind", () => {+ // A scrollbar drag replaces the window outright, and so do a turn jump and re-opening after a+ // full mount. Each took a row with an unsaved edit in it (the reply editor is uncontrolled, so+ // the draft is gone when the row comes back). The row is held as a pin, apart from the window:+ // stretching the window to it would mount everything between the edit and the reader.+ const keep = section(GLUE, "function keepPinned(", "\n}\n");+ assert.match(keep, /if \(index === undefined \|\| \(index >= next\.start && index < next\.end\)\) continue;/);+ assert.match(keep, /return withPins\(next, pins, lookup\.metas\.length\);/);+ // Rows are the viewport's own children, read in document order, so the pins come out ascending.+ assert.match(keep, /for \(const child of viewport\.children\)/);+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ // Every plan, sliding or filling, goes through it before it is compared or committed.+ assert.match(step, /if \(next != null\) next = keepPinned\(viewport, lookup, next, tail\);\s*if \(sameWindow\(next, current\)\)/);+ assert.match(step, /commit\(keepPinned\(viewport, lookup, next, tail\), true\);/);+ // The planner sees the window's rows only: a pin far away must not read as the window's edge.+ assert.match(step, /const inWindow = measured\.rows\.filter\(\s*\(row\) => row\.index >= current\.start && row\.index < current\.end,\s*\);/);+ assert.match(step, /rows: inWindow,/);+ assert.doesNotMatch(step, /pinned:/, "the planner does not hold rows by stretching the window");+ // A pin is let go when the reader leaves the row, which nothing else would step for.+ assert.match(GLUE, /viewport\.addEventListener\("focusout", schedule\);/);+ assert.match(GLUE, /viewport\.removeEventListener\("focusout", schedule\);/);+});++test("a spacer is keyed by where it sits among the rows", () => {+ // React moves a node when a sibling that used to follow it now precedes it. A spacer keyed by+ // the rows it borders never changes sides of a row, so no row's node is ever moved: a move+ // would drop the focus a pinned row is pinned for.+ assert.match(GLUE, /const key = slot\.from === 0 \? "top" : `top:\$\{slot\.from\}`;/);+ assert.match(GLUE, /const key = slot\.to === count \? "bottom" : `bottom:\$\{slot\.to\}`;/);+ assert.match(GLUE, /key=\{`gap:\$\{slot\.from\}`\}/);+ // A gap between pins is sized by React from the same heights the other two are.+ assert.match(GLUE, /height: gapHeight\(slot\.from, slot\.to\),\s*counterIncrement: counterIncrement\(slot\.from, slot\.to\),/);+ // The leading spacer holds no slack where it stands for no rows: at the first row, or at a pin.+ assert.match(GLUE, /const atFirstRow = win == null \|\| win\.start <= spacerRows\(win, count\)\.topFrom;/);+ // A spacer node this commit created is sized before any row's layout effect can read layout,+ // or the browser clamps scrollTop to a thread that is a few rows long for that moment.+ const early = section(GLUE, "useInsertionEffect(() => {", "}, [atFirstRow, spacers, viewportRef]);");+ assert.match(early, /const leading = atFirstRow \? 0 : Math\.max\(0, spacers\.top \+ slackRef\.current\);/);+ assert.match(early, /spacer\("top"\)\?\.style\.setProperty\("height", `\$\{leading\}px`\);/);+ assert.match(early, /spacer\("bottom"\)\?\.style\.setProperty\("height", `\$\{spacers\.bottom\}px`\);/);+ assert.ok(+ GLUE.indexOf("useInsertionEffect(() => {") < GLUE.indexOf("useLayoutEffect(() => {\n winRef.current = win;"),);+ assert.match(GLUE, /if \(!top \|\| current\.start <= spacerRows\(current, lookup\.metas\.length\)\.topFrom\) \{/);+});++test("a step runs on a frame, and WebKit commits inside it", () => {+ const schedule = section(GLUE, "const schedule = useCallback(", "}, []);");+ assert.match(schedule, /if \(frameRef\.current\) return;/);+ assert.match(schedule, /frameRef\.current = requestAnimationFrame\(/);assert.doesNotMatch(- widening,+ schedule,/setTimeout|setInterval|queueMicrotask/,- "cancelAnimationFrame does not cancel a timer, so a closed window would still widen",- );- assert.match(widening, /if \(scrollActivity\.current\?\.blocked\(inputPointerHeld\(\)\)\) \{\s*frame = requestAnimationFrame\(advance\);\s*return;/);+ "cancelAnimationFrame does not cancel a timer, so an unmounted thread would still step",+ );+ assert.match(GLUE, /cancelAnimationFrame\(frameRef\.current\);/);+ const commit = section(GLUE, "const commit = useCallback(", "[viewportRef],");+ assert.match(commit, /if \(sync\) flushSync\(apply\);\s*else startTransition\(apply\);/);+ // A trim is cheap and must not lag the measurement it was planned from.+ assert.match(GLUE, /const trimOnly = next != null && next\.start >= current\.start && next\.end <= current\.end;/);+ assert.match(GLUE, /commit\(next, WEBKIT_GTK \|\| trimOnly \|\| exposed\);/);+ // One commit at a time: its layout effect owns the correction.+ assert.match(GLUE, /if \(!viewport \|\| pendingRef\.current\) return;/);});-test("only WebKitGTK sizes the step by the prepend frontier; other engines keep CHUNK_MESSAGES", () => {- assert.match(GLUE, /const MOUNT_CHUNK = WEBKIT_GTK \? 2 : CHUNK_MESSAGES;/);- const widening = section(- GLUE,- "if (mountWindow == null) return;",- "}, [mountWindow, count, captureAnchor, isRunningNow, viewportRef]);",- );+test("a full mount is paced like the old background mount, and waits for a quiet moment", () => {+ assert.match(GLUE, /const FILL_CHUNK = WEBKIT_GTK \? 2 : CHUNK_MESSAGES;/);+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(+ step,+ /const chunk = WEBKIT_GTK\s*\?\s*\(chunkRef\.current = nextMountChunk\(\s*chunkRef\.current, frontier, FILL_CHUNK, WINDOW_REACH_PX\)\)\s*: FILL_CHUNK;/,+ );+ // The frontier is the window's first row, not a pinned row far above it.+ assert.match(step, /const frontier = inWindow\.length > 0 \? -inWindow\[0\]\.top : null;/);+ // Rows alone do not bound a pass: 32 very long replies in one commit held input for seconds+ // after select all. The pass is given the heights so it can stop at its budget.+ assert.match(step, /const heightOf = \(index: number\) => heights\.heightOf\(lookup\.metas\[index\]\);/);+ assert.match(step, /next = planFill\(current, total, chunk, heightOf\);/);+ // A commit interrupts native wheel momentum; scrolling by row does not wait, a full mount does.assert.match(- widening,- /const chunk = WEBKIT_GTK\s*\?\s*\(chunkRef\.current = nextMountChunk\(\s*chunkRef\.current, frontierAbove\(viewportRef\.current\), MOUNT_CHUNK, WINDOW_REACH\)\)\s*: MOUNT_CHUNK;/,+ step,+ /if \(scrollActivity\.current\?\.blocked\(inputPointerHeld\(\)\)\) \{\s*schedule\(\);\s*return;/,);- // Measured after the anchor capture, whose layout reads it reuses.- assert.ok(widening.indexOf("captureAnchor();") < widening.indexOf("const chunk = "));- // The near/far boundary is the window controller's own reach, not a copy of it.- assert.match(GLUE, /import \{ REACH as WINDOW_REACH \} from "@\/components\/assistant-ui\/message-window-controller";/);});test("the anchor is measured against its scroll container, not against the window", () => {@@ -154,55 +224,33 @@ test("the anchor is measured against its scroll container, not against the windo"the container's own top must be subtracted at both ends",);assert.match(GLUE, /function sampleAnchor\(/);- assert.match(GLUE, /sampleAnchor\(viewport, anchor\)/);assert.match(GLUE, /anchorCorrection\(baseline, sampleAnchor\(viewport, element\), ANCHOR_PRECISION\)/);// The anchor is often a <pre> Streamdown replaces after Shiki, so fall back to the row.- assert.match(GLUE, /const row = anchor\?\.closest\("\[data-role\]"\) \?\? null;/);+ assert.match(GLUE, /const row = element\.closest\("\[data-role\]"\);/);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", () => {// Without an unmount path the pending promise hangs a DOM capture forever.- assert.match(- GLUE,- /useEffect\(\(\) => flushCompletionWaiters, \[flushCompletionWaiters\]\)/,- );- const scheduler = section(- GLUE,- "if (mountWindow != null || completionWaiters.current.length === 0) return;",- "useEffect(() => flushCompletionWaiters",- );- assert.doesNotMatch(scheduler, /completionWaiters\.current = \[\];/);+ assert.match(GLUE, /useEffect\(\(\) => flushWaiters, \[flushWaiters\]\)/);+ // Emptied only when flushed, so a cancelled frame keeps the waiters.+ const flush = section(GLUE, "const flushWaiters = useCallback(", "}, []);");+ assert.match(flush, /waitersRef\.current = \[\];\s*for \(const resolve of waiters\) resolve\(\);/);});-test("the window owns the viewport's scroll-anchoring mode while it is open", () => {- // Native anchoring moves scrollTop inconsistently across engines, breaking document-space math.- assert.match(GLUE, /setProperty\("overflow-anchor", "none"\)/);- // Set from the capture rAF: on mount the viewport ref is still null in layout effects.- const capture = section(- GLUE,- "const captureAnchor = useCallback(",- "}, [viewportRef]);",- );- assert.match(capture, /setProperty\("overflow-anchor", "none"\)/);- assert.match(GLUE, /removeProperty\("overflow-anchor"\)/);- // Scoped to the closing effect; the unmount cleanup's removeProperty would satisfy a file match.- 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",+test("native scroll anchoring is off for a commit and handed back when the window settles", () => {+ // Native anchoring would correct the same shift a second time.+ const commit = section(GLUE, "const commit = useCallback(", "[viewportRef],");+ assert.match(commit, /setProperty\("overflow-anchor", "none"\)/);+ assert.ok(+ commit.indexOf('setProperty("overflow-anchor", "none")') < commit.indexOf("pickAnchorRow(viewport)"),+ "anchoring goes off before the capture it would otherwise move",);+ // Between commits the browser compensates late reflows above the reader (images, fonts).+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(step, /if \(sameWindow\(next, current\)\) \{[\s\S]{0,200}?settle\(viewport, current, lookup\);/);+ assert.match(section(GLUE, "const settle = useCallback(", "[adjustScroll, heights, schedule, topRef],"), /restoreScrollAnchoring\(viewport\);/);// removeProperty alone leaves `style=""` behind.assert.match(section(GLUE, "function restoreScrollAnchoring(", "\n}"),@@ -223,7 +271,28 @@ test("the mount window never writes scrollTop itself", () => {assert.doesNotMatch(glue, /scrollTop\s*=[^=]/);assert.doesNotMatch(glue, /\.scrollTo\(/);assert.doesNotMatch(glue, /scrollIntoView\(/);- assert.match(glue, /adjustForContentInsertedAbove\(shift \?\? 0\)/);+ assert.match(glue, /adjustScroll\(scroll\);/);+});++test("the leading spacer takes a height surprise before scrollTop does", () => {+ // A scroll write interrupts wheel momentum and fights a held scrollbar thumb.+ const effect = section(GLUE, "useLayoutEffect(() => {\n winRef.current = win;", "}, [win, atFirstRow, spacers,");+ assert.match(effect, /const taken = absorbShift\(spacer, shift, atFirstRow\);/);+ assert.match(effect, /scroll = taken\.scroll;/);+ assert.match(effect, /slackRef\.current = atFirstRow \? 0 : spacer - spacers\.top;/);+ // React must not own the heights: a re-render would put the pre-correction value back.+ assert.match(effect, /top\.style\.height = `\$\{spacer\}px`;/);+ assert.match(effect, /bottom\.style\.height = `\$\{spacers\.bottom\}px`;/);+ // React owns only flexShrink and the equation counters on these two, never their heights.+ assert.match(GLUE, /data-thread-spacer="top" aria-hidden="true" style=\{\{ flexShrink: 0, counterIncrement: counterIncrement\(slot\.from, slot\.to\) \}\}/);+ assert.match(GLUE, /data-thread-spacer="bottom" aria-hidden="true" style=\{\{ flexShrink: 0, counterIncrement: counterIncrement\(slot\.from, slot\.to\) \}\}/);+ // What the spacer took on is folded into scrollTop only once input has gone quiet.+ const settle = section(GLUE, "const settle = useCallback(", "[adjustScroll, heights, schedule, topRef],");+ assert.match(settle, /if \(scrollActivity\.current\?\.blocked\(inputPointerHeld\(\)\)\) \{/);+ assert.ok(+ settle.indexOf("scrollActivity.current?.blocked") < settle.indexOf("top.style.height ="),+ "the quiet check comes before the write",+ );});test("the hook pins a follower during the prepend commit", () => {@@ -234,7 +303,7 @@ test("the hook pins a follower during the prepend commit", () => {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.+ // commit's write.assert.match(THREAD, /scroll-smooth/);const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");assert.match(body, /behavior: "instant"/);@@ -247,7 +316,7 @@ test("the correction advances the intent bookkeeping with its write", () => {assert.match(body, /lastDistanceFromBottom = distanceFromBottom\(\);/);});-test("the escape hatch exists, resolves after a paint, and is registered only while withholding", () => {+test("the escape hatch mounts every row and resolves after a paint", () => {// A single rAF resolves before the forced commit paints.assert.match(GLUE, /export async function completeProgressiveMounts\(/);assert.match(GLUE, /wants\?: \(viewport: HTMLElement \| null\) => boolean,/);@@ -255,14 +324,148 @@ test("the escape hatch exists, resolves after a paint, and is registered only whGLUE,/requestAnimationFrame\(\(\) => requestAnimationFrame\(\(\) => resolve\(\)\)\)/,);- assert.match(GLUE, /if \(!isWithholding\) return;/);- assert.match(GLUE, /activeCompleters\.delete\(entry\)/);+ const complete = section(GLUE, "const complete = useCallback(", "[hidden, schedule],");+ assert.match(complete, /modeRef\.current = "fill";/);+ assert.match(complete, /if \(winRef\.current == null\) \{\s*resolve\(\);\s*return;/);+ assert.match(GLUE, /activeWindows\.delete\(entry\)/);+});++test("the whole document is mounted for the readers that need it", () => {+ // Find highlights DOM ranges, print lays out what is mounted, select all means every row.+ assert.match(GLUE, /const FIND_FLAG = "data-find-bar-open";/);+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(+ step,+ /const readerHolds =\s*printingRef\.current \|\|\s*fullMountHolds\.size > 0 \|\|\s*document\.documentElement\.hasAttribute\(FIND_FLAG\);\s*if \(readerHolds\) modeRef\.current = "fill";/,+ );+ assert.match(GLUE, /attributeFilter: \[FIND_FLAG, \.\.\.LAYOUT_FLAGS\]/);+ const print = section(GLUE, "const beforePrint = () => {", "};");+ // Synchronous: the print dialog opens when this handler returns.+ assert.match(print, /commit\(null, true\);/);+ // Not for a hidden thread: it is not printed, and its step would leave it fully mounted.+ assert.match(print, /if \(winRef\.current != null && viewport\.clientHeight > 0\) commit\(null, true\);/);+ const key = section(GLUE, "const onKeyDown = (event: KeyboardEvent) => {", "};");+ assert.match(key, /event\.key\.toLowerCase\(\) !== "a"/);+ assert.match(key, /closest\?\.\(EDITABLE\)\) return;/);+ assert.match(key, /void complete\(\);/);+});++test("a hidden thread is left as it is", () => {+ // Off its route the chat page stays mounted with no boxes: rows measure zero, so a step would+ // record those heights and mount the whole thread two rows a frame (measured: 111 rows and+ // climbing while the Model hub was open).+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ const guard = step.indexOf("if (viewport.clientHeight === 0) {");+ assert.notEqual(guard, -1);+ // A reader already waiting on the thread when it was hidden is released, not left hanging.+ assert.match(step, /if \(viewport\.clientHeight === 0\) \{\s*flushWaiters\(\);\s*return;\s*\}/);+ assert.ok(guard < step.indexOf("measureRows("), "the guard must come before any row is measured");+ assert.match(GLUE, /const resize = new ResizeObserver\(schedule\);\s*resize\.observe\(viewport\);/);+});++test("a full mount that ends without a signal is looked at again", () => {+ // A selection cleared, a pointer lifted and the release time passing fire nothing the window+ // listens to, so without this a thread mounted whole for one copy stays whole.+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(+ step,+ /if \(next != null && !readerHolds\) \{\s*window\.clearTimeout\(settleTimerRef\.current\);\s*settleTimerRef\.current = window\.setTimeout\(schedule, HOLD_RECHECK_MS\);/,+ );+});++test("a copy that runs across a spacer mounts the rows it stands in for first", () => {+ // The clipboard takes DOM text, so a copy over unmounted rows would be a short conversation.+ const copy = section(GLUE, "const onCopy = (event: ClipboardEvent) => {", "\n };");+ assert.match(copy, /if \(winRef\.current == null\) return;/);+ assert.match(copy, /spacer\.offsetHeight > 0 && selection\.containsNode\(spacer, true\)/);+ // Synchronous: the browser reads the selection when this handler returns.+ assert.match(copy, /commit\(null, true\);/);+ // WebKit serialises the selection it resolved before the mount (measured: 19,434 characters+ // of a 1,985,002 character thread), so the selection is set again, ends back on the spacers.+ assert.match(copy, /range\.compareBoundaryPoints\(Range\.START_TO_START, edge\) > 0/);+ // Rows, read after the mount: a spacer keyed by a pin is replaced by it.+ assert.match(copy, /const \{ topFrom, bottomTo \} = spacerRows\(winRef\.current, lookup\.metas\.length\);\s*modeRef/);+ assert.match(copy, /range\.setStartBefore\(first\);/);+ assert.match(copy, /range\.setEndAfter\(last\);/);+ assert.match(copy, /selection\.removeAllRanges\(\);\s*selection\.addRange\(range\);/);+ // Capture, on the document: the thread's own copy handler must see the full mount.+ assert.match(GLUE, /document\.addEventListener\("copy", onCopy, true\);/);+ assert.match(GLUE, /document\.removeEventListener\("copy", onCopy, true\);/);+});++test("a windowed thread publishes its length and each row's place in it", () => {+ const publish = section(GLUE, "function publishOrdinals(", "\n}\n");+ assert.match(publish, /const total = String\(lookup\.metas\.length\);/);+ assert.match(publish, /const position = String\(index \+ 1\);/);+ assert.match(publish, /child\.setAttribute\("aria-posinset", position\);/);+ assert.match(publish, /child\.setAttribute\("aria-setsize", total\);/);+ // A full mount publishes nothing, and clears what a window left behind.+ assert.match(publish, /child\.removeAttribute\("aria-posinset"\);/);+ assert.match(GLUE, /if \(!windowed && !ordinalsRef\.current\) return;/);+});++test("a hold keeps every row mounted until its release", () => {+ const hold = section(GLUE, "export function holdProgressiveMounts(", "\n}\n");+ assert.match(hold, /fullMountHolds\.add\(hold\);/);+ assert.match(hold, /if \(fullMountHolds\.delete\(hold\)\) for \(const entry of activeWindows\) entry\.wake\(\);/);+ assert.match(GLUE, /wake: schedule,/);+});++test("a settled window withholds rows without counting as a pending mount", () => {+ // The turn rail waits for pending mounts; a window that never fills must not hold it off.+ assert.match(+ section(GLUE, "export function hasPendingProgressiveMounts(", "\n}\n"),+ /if \(entry\.filling\(\)\) return true;/,+ );+ assert.match(GLUE, /filling: \(\) => modeRef\.current === "fill" && winRef\.current != null && !hidden\(\),/);+ assert.match(GLUE, /withholding: \(\) => winRef\.current != null && !hidden\(\),/);+});++test("a hidden thread holds no reader up", () => {+ // Find opened in a chat and then Compare entered: the chat stays mounted with no boxes, its+ // step stops at the hidden guard, and its full mount never finishes. Counted as pending it+ // kept the turn rail of every Compare pane from rendering until Compare was closed.+ assert.match(GLUE, /const hidden = useCallback\(\(\) => viewportRef\.current\?\.clientHeight === 0, \[viewportRef\]\);/);+ // And a reader that asks a hidden thread for every row is answered at once: the waiter would+ // never be resolved, and the request must not turn into a full mount when the thread is shown.+ const complete = section(GLUE, "const complete = useCallback(", "[hidden, schedule],");+ const answered = complete.indexOf("if (hidden()) {");+ assert.notEqual(answered, -1);+ assert.ok(answered < complete.indexOf('modeRef.current = "fill";'));+ assert.ok(answered < complete.indexOf("waitersRef.current.push(resolve);"));+});++test("a full mount nobody is waiting for is dropped", () => {+ // Find closed half way through a long thread: the rest of the mount is seconds of work for+ // no reader. A waiter (select all, a capture) still gets every row.+ const step = section(GLUE, "const step = useCallback(", "stepRef.current = step;");+ assert.match(+ step,+ /modeRef\.current === "fill" &&\s*\(current == null \|\| waitersRef\.current\.length === 0\) &&\s*performance\.now\(\) >= releaseAtRef\.current/,+ );+});++test("a jump asks for its row instead of for the whole thread", () => {+ assert.match(GLUE, /export function revealProgressiveRow\(viewport: HTMLElement, messageId: string\): boolean/);+ const reveal = section(GLUE, "const reveal = useCallback(", "[aui, readMetas, viewportRef],");+ // Mounted already: in the window, or pinned outside it.+ assert.match(reveal, /\(index >= current\.start && index < current\.end\) \|\|\s*current\.pins\?\.includes\(index\)\s*\) \{\s*return true;/);+ // Synchronous, so the caller finds the row in the DOM when this returns.+ assert.match(reveal, /flushSync\(\(\) => \{\s*setWin\(next\);\s*\}\);/);+ const jump = section(TURNS, "const jumpToTurn = useCallback(", "[viewportRef, detachFromBottom],");+ assert.ok(+ jump.indexOf("revealProgressiveRow(viewport, messageId)") < jump.indexOf("completeProgressiveMounts("),+ "the turn rail reveals one row before falling back to a full mount",+ );+ // Rows come and go as the reader moves, so the rail's in-view markers follow them.+ assert.match(TURNS, /const unsubscribe = subscribeMountedRows\(watch\);/);});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/);+ // Open dialogs are the one document-wide read: they are portaled out of every thread.+ assert.doesNotMatch(GLUE, /document\.querySelector\((?!OPEN_DIALOG\))/);assert.match(GLUE, /viewportRef\.current/);});@@ -270,7 +473,7 @@ test("the row map is memoized on the slot identity", () => {// Messages skips re-render only while its children function keeps identity.assert.match(GLUE,- /useMemo\(\(\) => \{[\s\S]*?\}, \[count, mountWindow, renderMessage, gate\]\)/,+ /useMemo\(\(\) => \{[\s\S]*?\}, \[count, win, renderMessage, gate, gapHeight, counterIncrement\]\)/,);assert.match(GLUE,@@ -280,49 +483,39 @@ test("the row map is memoized on the slot identity", () => {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` emits no rows until a transition widen, painting an empty column.- assert.match(- GLUE,- /mountWindow == null \|\| mountWindow\.start >= count/,- "start >= count must drop the window, not clamp it to count",- );- // Reconcile state too, or the next widen unmounts 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("a window past a thread that shrank is dropped or clamped, never left to emit nothing", () => {+ // followCount drops or clamps it (thread-window.test.ts); null is the full mount.+ assert.match(GLUE, /\} else if \(win != null\) \{\s*const followed = followCount\(win, previousCount, count\);/);+ // The row map clamps too, in threadSlots: the state update above lands a render later.+ assert.match(GLUE, /return threadSlots\(win, count\)\.map\(/);});-test("the window re-arms on the commit that first fills an empty tree", () => {+test("a window at the tail follows new messages", () => {+ // Otherwise a sent prompt and its reply would land in the trailing spacer.+ // followCount again; it is given the count the window was planned against.+ assert.match(GLUE, /followCount\(win, previousCount, count\)/);+ assert.match(GLUE, /setPreviousCount\(count\);/);+});++test("the window opens on the commit that first fills an empty tree", () => {// The thread mounts at count 0 before history arrives; the cold open must still be windowed.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", () => {- // Completers register from an effect, so an empty set is not trusted straight away.+test("the escape hatch re-reads the window set instead of sampling it once", () => {+ // Windows register from an effect, so an empty set is not trusted straight away.assert.match(GLUE, /let observed = false;/);- // Must re-read the filtered set each call, or a declined completer holds the loop open.+ // Must re-read the filtered set each call, or a declined window holds the loop open.assert.match(GLUE,- /wanted\(\)\.length === 0 && \(observed \|\| Date\.now\(\) >= deadline\)/,+ /!wanted\(\)\.some\(\(entry\) => entry\.withholding\(\)\) &&\s*\(observed \|\| Date\.now\(\) >= deadline\)/,);- assert.match(GLUE, /const wanted = \(\) =>[\s\S]*?activeCompleters/);+ assert.match(GLUE, /const wanted = \(\) =>[\s\S]*?activeWindows/);// The deadline must be positive and outlast a cold history load (~160ms).assert.match(GLUE,/const deadline = Date\.now\(\) \+ PROGRESSIVE_MOUNT_SEARCH_MS;/,- "an empty completer set must only be believed after a search interval",+ "an empty set must only be believed after a search interval",);const searchMs = Number(/PROGRESSIVE_MOUNT_SEARCH_MS = (\d+)/.exec(GLUE)?.[1] ?? "0",@@ -333,9 +526,11 @@ test("the escape hatch re-reads the completer set instead of sampling it once",);});-test("the hook is told about every widening, including the ones with nothing to apply", () => {+test("the hook is told about every commit, including the ones with nothing to apply", () => {// Resync bookkeeping even with zero shift: anchoring scroll events would re-attach a parked reader.- assert.match(GLUE, /adjustForContentInsertedAbove\(shift \?\? 0\)/);+ const effect = section(GLUE, "useLayoutEffect(() => {\n winRef.current = win;", "}, [win, atFirstRow, spacers,");+ assert.match(effect, /let scroll = 0;/);+ assert.match(effect, /\n adjustScroll\(scroll\);/, "the call is not inside the captured-anchor branch");const body = section(HOOK, "adjustImplRef.current = (", "const onWheel = ");assert.doesNotMatch(body,@@ -352,25 +547,91 @@ test("the anchor is the first row the reader can see, not the first row in the l// A row can be taller than the viewport, so descend to the fold.assert.match(GLUE, /for \(const child of layoutChildren\(anchor\)\)/);assert.match(GLUE, /getComputedStyle\(child\)\.display === "contents"/);- assert.match(GLUE, /function isAnchorVisible\(/);- assert.match(GLUE, /return box\.bottom > fold && box\.top < fold \+ viewport\.clientHeight;/);- // Pass a post-correction baseline, or a reflow before the next frame is never corrected.- 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",);- assert.match(GLUE, /const anchor = viewport \? pickAnchorRow\(viewport\) : null;/);assert.match(GLUE, /const element = pickAnchorRow\(viewport\);/);+ assert.match(GLUE, /function holdAnchor\(viewport: HTMLElement, element: Element\): HeldAnchor/);});-test("the interval between widenings is compensated too, not just the widening commits", () => {- // Native anchoring is off for the whole window, so idle reflows need compensation too.- assert.match(GLUE, /idleRef/);- assert.match(GLUE, /if \(!viewport \|\| anchorRef\.current\) return;/);- assert.match(GLUE, /function holdAnchor\(viewport: HTMLElement, element: Element\): HeldAnchor/);- assert.match(GLUE, /held\.row\?\.isConnected && held\.rowSample/);- // Re-base every frame: anchorCorrection's clamp term reads the baseline scrollTop.- assert.match(GLUE, /if \(shift !== null\) adjustForContentInsertedAbove\(shift\);/);+test("a row's height is its top to the top of what follows it, read in one pass", () => {+ // Margins between rows belong to the spacers too, or every unmount would shift the reader.+ // What follows is a row or a spacer: a pinned row has a spacer on both sides.+ const measure = section(GLUE, "function measureRows(", "\n}\n");+ assert.match(measure, /if \(index === undefined && !child\.hasAttribute\(SPACER_ATTRIBUTE\)\) continue;/);+ assert.match(measure, /if \(open\) close\(top - open\.top\);/);+ assert.match(measure, /if \(heights\.measure\(meta, Math\.max\(0, height\)\)\) \{/);+ // Where the thread starts, for the planner to find the row a jump lands on.+ assert.match(measure, /threadTop \?\?= top;/);+ // Rows are the viewport's own children: a nested transcript's rows are not this thread's.+ assert.match(measure, /for \(const child of viewport\.children\)/);+});++test("the thread's messages are read imperatively, not through a selector", () => {+ // A useAuiState selector on messages would walk the thread on every keystroke.+ assert.doesNotMatch(GLUE, /useAuiState\(\(\{ thread \}\) => thread\.messages\)/);+ assert.match(GLUE, /aui\.thread\(\)\.getState\(\)\.messages/);+ assert.match(GLUE, /const count = useAuiState\(\(\{ thread \}\) => thread\.messages\.length\);/);+});++test("a mounted row that shrinks or re-wraps wakes the window, and growth does not", () => {+ assert.match(+ GLUE,+ /if \(before && \(height < before\.height - 1 \|\| Math\.abs\(width - before\.width\) > 1\)\) \{\s*wake = true;/,+ );+ assert.match(GLUE, /if \(wake\) schedule\(\);/);+ // Heights are keyed on a row's layout: Chat width moves the column, not the viewport, and the+ // chat font, text size and code font move no width.+ assert.match(+ GLUE,+ /const column = viewport\.querySelector<HTMLElement>\(ROW_SELECTOR\);[\s\S]{0,120}?column != null && heights\.relayout\(`\$\{rowLayout\(column\)\}/,+ );+ const layout = section(GLUE, "function rowLayout(row: HTMLElement): string {", "\n}");+ for (const part of ["row.clientWidth", "style.fontFamily", "style.fontSize", "style.letterSpacing", '"--custom-code-font"', '"--custom-code-font-size"']) {+ assert.ok(layout.includes(part), `the row layout key lost ${part}`);+ }+ assert.match(layout, /LAYOUT_FLAGS\.map\(\(name\) => \(root\.hasAttribute\(name\) \? "1" : "0"\)\)/);+ for (const flag of ["data-code-wrap", "data-code-line-numbers", "data-chat-font", "data-ui-font-size", "data-code-font-size"]) {+ assert.ok(section(GLUE, "const LAYOUT_FLAGS = [", "];").includes(`"${flag}"`), `${flag} left the layout key`);+ }+ // A flag flip wakes the window: an idle reader has no scroll to step it.+ assert.match(GLUE, /attributeFilter: \[FIND_FLAG, \.\.\.LAYOUT_FLAGS\]/);+ assert.doesNotMatch(GLUE, /heights\.re(?:size|layout)\(viewport\.clientWidth\)/);+ // Rows come and go: removed ones are let go, so the observer holds no detached row.+ assert.match(GLUE, /rowResize\.unobserve\(node\)/);+ assert.match(GLUE, /rowsChanged\.observe\(viewport, \{ childList: true \}\);/);+ assert.match(GLUE, /rowResize\.disconnect\(\);\s*rowsChanged\.disconnect\(\);/);+});++test("a reader that stops waiting for a full mount lets the window slide again", () => {+ const complete = section(GLUE, "const complete = useCallback(", "[hidden, schedule],");+ assert.match(complete, /if \(signal\?\.aborted\) \{\s*resolve\(\);/);+ assert.match(complete, /waitersRef\.current = waitersRef\.current\.filter\(\(waiter\) => waiter !== resolve\);/);+ assert.match(complete, /if \(waitersRef\.current\.length === 0\) releaseAtRef\.current = performance\.now\(\);/);+ assert.match(GLUE, /await Promise\.all\(pending\.map\(\(entry\) => entry\.complete\(signal\)\)\);/);+});++test("only a rendered reply's equations count toward the spacers", () => {+ assert.match(+ GLUE,+ /equations: renders && role === "assistant" \? numberedEquations\(message\.content, expanded\) : 0,/,+ );+});++test("a relayout re-renders every spacer even when the window holds", () => {+ assert.match(+ GLUE,+ /if \(relaid\) \{\s*commit\(\{ \.\.\.current \}, true\);\s*return;/,+ );+ // The expanded settings move every row and feed the estimate, so both key the caches.+ assert.match(GLUE, /heights\.relayout\(`\$\{rowLayout\(column\)\}\\n\$\{thinking\}\\n\$\{tools\}`\)/);+ assert.match(GLUE, /metasOf\(aui\.thread\(\)\.getState\(\)\.messages as unknown as readonly ThreadMessage\[\], expanded\)/);+});++test("a copy from a field leaves the window alone", () => {+ const copy = section(GLUE, "const onCopy = (event: ClipboardEvent) => {", "\n };");+ assert.match(copy, /const target = event\.target as Element \| null;\s*if \(target\?\.closest\?\.\(EDITABLE\)\) return;/);+ assert.match(GLUE, /const EDITABLE = "input, textarea, \[contenteditable=true\]";/);});diff --git a/studio/frontend/tests/thread-window.test.ts b/studio/frontend/tests/thread-window.test.tsnew file mode 100644index 00000000000..592e1d66521--- /dev/null+++ b/studio/frontend/tests/thread-window.test.ts@@ -0,0 +1,615 @@+// 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 sliding mount window: which rows a reader's position asks for, how tall the rows outside+// are taken to be, and how a height surprise is kept from moving what the reader sees.+// The .tsx glue is pinned in progressive-mount-glue.test.ts.++import assert from "node:assert/strict";+import test from "node:test";++import {+ type MountedRow,+ type RowMeta,+ type RowWindow,+ FILL_BUDGET_PX,+ RowHeights,+ WINDOW_KEEP_PX,+ WINDOW_MIN_ROWS,+ WINDOW_MIN_TOTAL_PX,+ WINDOW_REACH_PX,+ TAIL_TURN_MAX_ROWS,+ absorbShift,+ holdTailTurn,+ followCount,+ initialRowWindow,+ messageWeight,+ numberedEquations,+ planEngage,+ planFill,+ planSlide,+ sameWindow,+ spacerHeights,+ spacerRows,+ threadSlots,+ withPins,+} from "../src/components/assistant-ui/thread-window.ts";++const VIEW = 800;++const meta = (index: number, weight = 20, role = index % 2 ? "assistant" : "user"): RowMeta => ({+ id: `m${index}`,+ role,+ weight,+ renders: true,+});++/** Rows of one height stacked from `firstTop`, as the glue would measure them. */+function stack(win: RowWindow, firstTop: number, height: number): MountedRow[] {+ const rows: MountedRow[] = [];+ for (let index = win.start; index < win.end; index += 1) {+ const top = firstTop + (index - win.start) * height;+ rows.push({ index, top, bottom: top + height });+ }+ return rows;+}++function slide(+ win: RowWindow,+ rows: MountedRow[],+ overrides: Partial<Parameters<typeof planSlide>[0]> = {},+): RowWindow {+ return planSlide({+ win,+ count: 1000,+ rows,+ viewHeight: VIEW,+ threadTop: (rows[0]?.top ?? 0) - win.start * 500,+ slack: 0,+ heightOf: () => 500,+ maxStep: 4,+ trim: true,+ ...overrides,+ });+}++test("a part's weight is the lines it renders: text by line, collapsed parts by a fixed share", () => {+ assert.equal(messageWeight(undefined), 0);+ assert.equal(messageWeight([{ type: "text", text: "abcd" }]), 1);+ assert.equal(messageWeight([{ type: "text", text: "a\nb\nc" }]), 3);+ // A long line wraps; forty short lines of code are forty lines, not one paragraph.+ assert.equal(messageWeight([{ type: "text", text: "x".repeat(450) }]), 6);+ const code = Array.from({ length: 40 }, () => "let a = 1;").join("\n");+ assert.equal(messageWeight([{ type: "text", text: code }]), 40);+ const tool = messageWeight([{ type: "tool-call" }]);+ assert.ok(tool > 0);+ // A reasoning block renders collapsed however long it ran, so its text is not counted.+ assert.equal(messageWeight([{ type: "reasoning", text: "x".repeat(50_000) }]), tool);+ assert.ok(messageWeight([{ type: "image" }]) > tool);+ // Sources are inline badges on lines the text already counted.+ assert.equal(messageWeight([{ type: "source" }]), 0);+});++test("an unmeasured row is estimated from its lines, and a measured one is exact", () => {+ const heights = new RowHeights();+ const short = heights.heightOf(meta(1, 2));+ const long = heights.heightOf(meta(3, 400));+ assert.ok(long > short * 10, "a long reply must not be given a short reply's room");+ heights.measure(meta(3, 400), 1234.5);+ assert.equal(heights.heightOf(meta(3, 400)), 1234.5);+ assert.equal(heights.has("m3"), true);+ assert.equal(heights.has("m1"), false);+});++test("a message that renders no row takes no room", () => {+ const heights = new RowHeights();+ assert.equal(heights.heightOf({ ...meta(0), renders: false }), 0);+});++test("the estimate learns what a line takes in each role from the rows measured so far", () => {+ const heights = new RowHeights();+ // Replies here run 40px per line (code, tables), well off the prior.+ for (let index = 1; index < 41; index += 2) {+ const lines = 40 + index;+ heights.measure(meta(index, lines), 72 + lines * 40);+ }+ const guess = heights.heightOf(meta(999, 200));+ assert.ok(Math.abs(guess - (72 + 8000)) < 250, `expected about 8072, got ${guess}`);+ // Prompts were not measured, so they keep their own prior rather than the replies' density.+ const prompt = heights.heightOf(meta(998, 2, "user"));+ assert.ok(prompt < 300, `a short prompt was estimated at ${prompt}`);+});++test("three alike rows at the tail are enough to size the rest", () => {+ // What a thread opens with: the last few rows measured, every other row a guess.+ const heights = new RowHeights();+ for (const index of [395, 397, 399]) heights.measure(meta(index, 60), 1700);+ const guess = heights.heightOf(meta(1, 60));+ assert.ok(Math.abs(guess - 1700) < 1700 * 0.1, `expected within 10% of 1700, got ${guess}`);+});++test("rows of one length converge on their measured height, whatever the prior said", () => {+ const heights = new RowHeights();+ for (let index = 0; index < 60; index += 2) heights.measure(meta(index, 4, "user"), 213);+ const guess = heights.heightOf(meta(500, 4, "user"));+ assert.ok(Math.abs(guess - 213) < 15, `expected about 213, got ${guess}`);+});++test("measuring a row again replaces what it taught the estimate", () => {+ const once = new RowHeights();+ once.measure(meta(1, 80), 2000);+ const twice = new RowHeights();+ // A row is measured while it is still rendering, then again at its settled height.+ twice.measure(meta(1, 80), 90);+ twice.measure(meta(1, 80), 2000);+ assert.equal(twice.heightOf(meta(7, 180)), once.heightOf(meta(7, 180)));+});++test("the spacers are the heights of the rows on either side of the window", () => {+ const heights = new RowHeights();+ const metas = Array.from({ length: 10 }, (_, index) => meta(index));+ metas.forEach((row, index) => heights.measure(row, 100 + index));+ assert.deepEqual(spacerHeights(heights, metas, null), { top: 0, bottom: 0 });+ assert.deepEqual(spacerHeights(heights, metas, { start: 2, end: 7 }), {+ top: 100 + 101,+ bottom: 107 + 108 + 109,+ });+ assert.deepEqual(spacerHeights(heights, metas, { start: 0, end: 10 }), { top: 0, bottom: 0 });+ // A window past a thread that shrank counts nothing twice.+ assert.deepEqual(spacerHeights(heights, metas.slice(0, 3), { start: 5, end: 9 }), {+ top: 100 + 101 + 102,+ bottom: 0,+ });+});++test("a thread opens on the tail, sized by height and capped in rows", () => {+ const cover = VIEW + WINDOW_REACH_PX;+ // Tall replies: two rows already cover the reach.+ assert.deepEqual(initialRowWindow(600, () => 2000, cover), { start: 598, end: 600 });+ // Short rows: the row cap bounds the first commit.+ assert.deepEqual(initialRowWindow(6000, () => 20, cover), { start: 5984, end: 6000 });+});++test("a thread is windowed by its height, not its message count", () => {+ const cover = VIEW + WINDOW_REACH_PX;+ // A few turns of very long replies (an agent run) is exactly the thread that needs it.+ assert.deepEqual(initialRowWindow(10, () => 12_000, cover), { start: 9, end: 10 });+ // Many short messages are cheap to mount whole.+ assert.equal(initialRowWindow(200, () => 100, cover), null);+ const rows = Math.ceil(WINDOW_MIN_TOTAL_PX / 500);+ assert.equal(initialRowWindow(rows - 1, () => 500, cover), null, "just under the height floor");+ assert.notEqual(initialRowWindow(rows, () => 500, cover), null, "at the height floor");+ // Too few messages to leave any out, however tall.+ assert.equal(initialRowWindow(WINDOW_MIN_ROWS - 1, () => 50_000, cover), null);+ // The tail that fits reaches the first row: nothing would be withheld.+ assert.equal(initialRowWindow(WINDOW_MIN_ROWS, () => 5000, 1_000_000, 64), null);+});++test("messages that render nothing do not use up the opening rows", () => {+ const cover = VIEW + WINDOW_REACH_PX;+ const win = initialRowWindow(6000, (index) => (index % 2 ? 0 : 20), cover, 16);+ assert.deepEqual(win, { start: 6000 - 32, end: 6000 });+});++test("a reader at rest inside the reach keeps the window as it is", () => {+ // Fourteen 500px rows from 2500px above the viewport to 4500px below its top.+ const win = { start: 100, end: 114 };+ const rows = stack(win, -WINDOW_REACH_PX - 500, 500);+ assert.ok(sameWindow(slide(win, rows), win));+});++test("scrolling up mounts rows above, a step at a time, and never past the first", () => {+ const win = { start: 100, end: 110 };+ // The first mounted row starts 300px above the viewport: 1700px of the reach are uncovered.+ const next = slide(win, stack(win, -300, 500));+ assert.equal(next.start, 96, "four 500px rows cover the 1700px gap");+ assert.equal(next.end, 110);+ const capped = slide(win, stack(win, -300, 500), { maxStep: 2 });+ assert.equal(capped.start, 98, "a commit mounts maxStep rows at most");+ const atHead = slide({ start: 1, end: 10 }, stack({ start: 1, end: 10 }, 0, 500));+ assert.equal(atHead.start, 0);+});++test("scrolling down mounts rows below, up to the end of the thread", () => {+ const win = { start: 100, end: 107 };+ // Seven rows from above the upper reach end 1000px below the viewport top: 1800px of the+ // lower reach are uncovered.+ const next = slide(win, stack(win, -2500, 500));+ assert.equal(next.start, 100);+ assert.equal(next.end, 111);+ const tail = { start: 992, end: 999 };+ assert.equal(slide(tail, stack(tail, -2500, 500)).end, 1000);+});++test("rows past the keep distance unmount; rows between reach and keep stay", () => {+ const win = { start: 100, end: 140 };+ // Row 100 ends at -9500; row 119 starts at 0.+ const rows = stack(win, -10_000, 500);+ const next = slide(win, rows);+ const firstKept = rows.find((row) => row.bottom >= -WINDOW_KEEP_PX);+ const lastKept = [...rows].reverse().find((row) => row.top <= VIEW + WINDOW_KEEP_PX);+ assert.equal(next.start, firstKept?.index);+ assert.equal(next.end, (lastKept?.index ?? 0) + 1);+ assert.ok(next.start > win.start && next.end < win.end);+ // Hysteresis: a row just past the reach is not dropped the moment it leaves it.+ const near = { start: 100, end: 112 };+ assert.ok(sameWindow(slide(near, stack(near, -WINDOW_REACH_PX - 700, 500)), near));+});++test("nothing unmounts while trimming is held", () => {+ const win = { start: 100, end: 140 };+ const next = slide(win, stack(win, -10_000, 500), { trim: false });+ assert.ok(sameWindow(next, win), "a selection or a held pointer keeps every mounted row");+});++test("a pinned row is held apart from the window, not by stretching the window to it", () => {+ // Rows the next window leaves out but the reader is working in: before it, inside it, after it.+ const win = withPins({ start: 300, end: 310 }, [104, 305, 599, 600], 600);+ assert.deepEqual(win, { start: 300, end: 310, pins: [104, 599] });+ // No pin leaves a plain window, so it compares equal to one that never had any.+ assert.deepEqual(withPins({ start: 300, end: 310, pins: [104] }, [], 600), { start: 300, end: 310 });+ assert.ok(!sameWindow(win, { start: 300, end: 310 }));+ assert.ok(!sameWindow(win, { start: 300, end: 310, pins: [104, 598] }));+ assert.ok(sameWindow(win, { start: 300, end: 310, pins: [104, 599] }));+});++test("the thread is laid out as rows and the spacers standing in for the rest", () => {+ const names = (win: RowWindow | null, count: number) =>+ threadSlots(win, count).map((slot) =>+ slot.kind === "row" ? slot.index : `${slot.name}[${slot.from},${slot.to})`,+ );+ assert.deepEqual(names({ start: 3, end: 5 }, 8), ["top[0,3)", 3, 4, "bottom[5,8)"]);+ // A full mount keeps its two spacers, so the nodes survive the window closing and re-opening.+ assert.deepEqual(names(null, 3), ["top[0,0)", 0, 1, 2, "bottom[3,3)"]);+ // Pins on both sides: each is a row of its own, and the spacers against the window stop at+ // the nearest one.+ assert.deepEqual(names({ start: 10, end: 12, pins: [2, 6, 15, 19] }, 20), [+ "gap[0,2)", 2, "gap[3,6)", 6, "top[7,10)", 10, 11, "bottom[12,15)", 15, "gap[16,19)", 19,+ "gap[20,20)",+ ]);+ // Every row of the thread is in exactly one slot, in order.+ const covered: number[] = [];+ for (const slot of threadSlots({ start: 10, end: 12, pins: [2, 6, 15, 19] }, 20)) {+ if (slot.kind === "row") covered.push(slot.index);+ else for (let index = slot.from; index < slot.to; index += 1) covered.push(index);+ }+ assert.deepEqual(covered, Array.from({ length: 20 }, (_, index) => index));+ // A window clamped to a thread that shrank, and a pin past its end.+ assert.deepEqual(names({ start: 2, end: 9, pins: [7] }, 4), ["top[0,2)", 2, 3, "bottom[4,4)"]);+});++test("the spacers against the window stop at a pinned row", () => {+ const heights = new RowHeights();+ const metas = Array.from({ length: 20 }, (_, index) => meta(index));+ metas.forEach((row, index) => heights.measure(row, 100 + index));+ const win = { start: 10, end: 12, pins: [2, 6, 15, 19] };+ assert.deepEqual(spacerRows(win, 20), { topFrom: 7, bottomTo: 15 });+ assert.deepEqual(spacerHeights(heights, metas, win), {+ top: 107 + 108 + 109,+ bottom: 112 + 113 + 114,+ });+ assert.deepEqual(spacerRows({ start: 10, end: 12 }, 20), { topFrom: 0, bottomTo: 20 });+ // A window that starts right after a pin has a leading spacer standing for no rows.+ assert.deepEqual(spacerRows({ start: 7, end: 12, pins: [6] }, 20), { topFrom: 7, bottomTo: 20 });+});++test("a window follows a thread that grows at its tail and is clamped to one that shrinks", () => {+ const tail = { start: 590, end: 600 };+ assert.deepEqual(followCount(tail, 600, 602), { start: 590, end: 602 });+ // A reader further up is left where they are, on the same object.+ const middle = { start: 300, end: 310 };+ assert.equal(followCount(middle, 600, 602), middle);+ assert.deepEqual(followCount(tail, 600, 595), { start: 590, end: 595 });+ assert.equal(followCount(tail, 600, 590), null);+ // Pins come along: one the tail grew over is the window's now, one past the end is gone.+ assert.deepEqual(followCount({ start: 300, end: 310, pins: [100, 599] }, 600, 598), {+ start: 300,+ end: 310,+ pins: [100],+ });+ assert.deepEqual(followCount({ start: 590, end: 600, pins: [100] }, 600, 601), {+ start: 590,+ end: 601,+ pins: [100],+ });+});++test("a jump above the window re-opens it on the row the offset lands on", () => {+ const win = { start: 500, end: 510 };+ // The viewport now sits 20 rows (10,000px) above the first mounted row.+ const firstTop = 10_000 + VIEW;+ const rows = stack(win, firstTop, 500);+ const next = slide(win, rows, { threadTop: firstTop - 500 * 500 });+ // Offset into the spacer: (500 rows * 500px) - 10,800px = row 478.4.+ assert.equal(next.start, 478);+ assert.ok(next.end > next.start && next.end <= next.start + 5);+ assert.ok(next.end <= win.start, "the old rows are dropped, not kept across the gap");+});++test("a jump below the window walks the rows after it", () => {+ const win = { start: 100, end: 110 };+ const rows = stack(win, -5000 - 20_000, 500);+ const next = slide(win, rows);+ // The viewport top is 20,000px into the trailing spacer: 40 rows on.+ assert.equal(next.start, 150);+});++test("a jump drops every row of the old window: holding one is the caller's pin, not a stretch", () => {+ const win = { start: 100, end: 110, pins: [40] };+ const next = slide(win, stack(win, -5000 - 20_000, 500));+ assert.equal(next.start, 150);+ assert.ok(next.end <= 150 + 5, "the window does not reach back for the rows it left");+ assert.equal(next.pins, undefined);+});++test("a jump accounts for what the leading spacer carries beyond its rows", () => {+ const win = { start: 500, end: 510 };+ const firstTop = 10_000 + VIEW;+ const plain = slide(win, stack(win, firstTop, 500), { threadTop: firstTop - 500 * 500 });+ // 1000px of slack: the same viewport offset is two rows earlier in the thread.+ const slack = slide(win, stack(win, firstTop, 500), {+ threadTop: firstTop - 500 * 500 - 1000,+ slack: 1000,+ });+ assert.equal(slack.start, plain.start);+});++test("a short hop past the mounted rows extends the window instead of dropping it", () => {+ const win = { start: 100, end: 110 };+ // The viewport is 1000px above the first row: inside the keep distance.+ const next = slide(win, stack(win, 1000 + VIEW, 500));+ assert.ok(next.start < win.start);+ assert.ok(next.end > next.start);+ assert.ok(next.end >= 100, "rows the reader just left are still within the keep distance");+});++test("a window with nothing mounted yet still makes progress", () => {+ const next = slide({ start: 100, end: 101 }, [], { heightOf: () => 0 });+ assert.ok(next.end > next.start);+ const grown = slide({ start: 100, end: 100 }, []);+ assert.ok(grown.end > grown.start, "an empty window never stays empty");+});++test("a window past a thread that shrank is clamped before it is planned", () => {+ const next = slide({ start: 100, end: 400 }, stack({ start: 100, end: 110 }, 0, 500), { count: 105 });+ assert.ok(next.end <= 105);+ assert.ok(next.start < next.end);+});++test("sliding converges: the planned window is a fixed point once the reach is covered", () => {+ let win: RowWindow = { start: 500, end: 501 };+ for (let step = 0; step < 50; step += 1) {+ // The reader holds row 500's top at the viewport top; rows are 500px.+ const next = slide(win, stack(win, (win.start - 500) * 500, 500));+ if (sameWindow(next, win)) {+ assert.ok(win.start <= 496, "the upper reach is covered");+ assert.ok(win.end >= 506, "the lower reach is covered");+ return;+ }+ win = next;+ }+ assert.fail("the window never settled");+});++test("a full mount widens both ways and ends unrestricted", () => {+ assert.deepEqual(planFill({ start: 100, end: 110 }, 1000, 32), { start: 68, end: 142 });+ assert.deepEqual(planFill({ start: 10, end: 990 }, 1000, 32), null);+ assert.deepEqual(planFill({ start: 0, end: 500 }, 1000, 32), { start: 0, end: 532 });+ let win: RowWindow | null = { start: 598, end: 600 };+ let steps = 0;+ while (win != null) {+ const next: RowWindow | null = planFill(win, 600, 16);+ assert.ok(next == null || (next.start <= win.start && next.end >= win.end), "never narrows");+ win = next;+ steps += 1;+ assert.ok(steps < 100, "a full mount must finish");+ }+});++test("a full mount pass is bounded by estimated height, not only by rows", () => {+ const win = { start: 100, end: 110 };+ // Short messages: the row cap is what bounds the pass, as before.+ assert.deepEqual(planFill(win, 1000, 32, () => 200), { start: 68, end: 142 });+ // Very long replies: the budget stops the pass after a few rows, split between both sides.+ const tall = planFill(win, 1000, 32, () => 6000);+ assert.deepEqual(tall, { start: 98, end: 111 });+ assert.ok((win.start - 98 + (111 - win.end)) * 6000 <= FILL_BUDGET_PX);+ // A row taller than the whole budget still mounts, one a pass: a full mount must finish.+ assert.deepEqual(planFill(win, 1000, 32, () => FILL_BUDGET_PX * 3), { start: 99, end: 110 });+ // Messages that render nothing cost nothing and do not count as the row a pass must add.+ const sparse = planFill(win, 1000, 32, (index) => (index % 2 ? 0 : FILL_BUDGET_PX * 3));+ assert.deepEqual(sparse, { start: 99, end: 111 }, "row 99 renders nothing; row 110 is the pass");+ // One side exhausted: the other takes the whole budget.+ assert.deepEqual(planFill({ start: 0, end: 10 }, 1000, 32, () => 5000), { start: 0, end: 14 });+ let current: RowWindow | null = { start: 598, end: 600 };+ let passes = 0;+ while (current != null) {+ const before: RowWindow = current;+ current = planFill(before, 600, 32, (index) => 500 + (index % 7) * 4000);+ if (current != null) {+ let added = 0;+ for (let index = current.start; index < before.start; index += 1) added += 500 + (index % 7) * 4000;+ for (let index = before.end; index < current.end; index += 1) added += 500 + (index % 7) * 4000;+ const rows = before.start - current.start + (current.end - before.end);+ assert.ok(rows >= 1, "every pass adds a row");+ assert.ok(added <= FILL_BUDGET_PX || rows === 1, `a pass added ${added}px over ${rows} rows`);+ }+ passes += 1;+ assert.ok(passes < 1000, "a full mount must finish");+ }+});++test("a fully mounted thread re-opens its window only when enough would unmount", () => {+ const all = { start: 0, end: 600 };+ // The reader is at row 300; every row is 500px.+ const rows = stack(all, -300 * 500, 500);+ const win = planEngage(rows, 600, VIEW);+ assert.ok(win != null);+ assert.ok(win.start > 280 && win.start < 300);+ assert.ok(win.end > 300 && win.end < 320);+ // Short thread: under the height floor, so it stays whole.+ const small = { start: 0, end: 40 };+ assert.equal(planEngage(stack(small, -2000, 200), 40, VIEW), null);+ // Tall enough, but it is one long reply the reader is in: the few rows after it are not worth+ // a commit.+ const giant: MountedRow[] = [{ index: 0, top: -20_000, bottom: 22_000 }];+ for (let index = 1; index < 9; index += 1) {+ giant.push({ index, top: 22_000 + (index - 1) * 300, bottom: 22_000 + index * 300 });+ }+ assert.equal(planEngage(giant, 9, VIEW), null);+ assert.equal(planEngage([], 600, VIEW), null);+});++test("re-opening counts the rows on both sides of the reader", () => {+ const all = { start: 0, end: 200 };+ // The reader is at the top: everything to unmount is below.+ const below = planEngage(stack(all, 0, 500), 200, VIEW);+ assert.deepEqual(below?.start, 0);+ assert.ok(below != null && below.end < 20);+ // At the tail: everything to unmount is above.+ const above = planEngage(stack(all, -199 * 500, 500), 200, VIEW);+ assert.ok(above != null && above.start > 180);+ assert.equal(above?.end, 200);+});++test("the leading spacer takes a height surprise, so the reader's row does not move", () => {+ // Rows mounted above came out 120px taller than estimated: the spacer gives that back.+ assert.deepEqual(absorbShift(5000, 120, false), { spacer: 4880, scroll: 0 });+ // Shorter than estimated: the spacer grows.+ assert.deepEqual(absorbShift(5000, -80, false), { spacer: 5080, scroll: 0 });+});++test("only what the spacer cannot take is left for a scroll correction", () => {+ // The spacer runs out: the rest is a scroll write.+ assert.deepEqual(absorbShift(100, 250, false), { spacer: 0, scroll: 150 });+ // At the first row there is no spacer; whatever it still held is corrected by scrolling.+ assert.deepEqual(absorbShift(0, 40, true), { spacer: 0, scroll: 40 });+ assert.deepEqual(absorbShift(300, 40, true), { spacer: 0, scroll: -260 });+});++test("the reach and keep distances leave hysteresis between mounting and unmounting", () => {+ assert.ok(WINDOW_KEEP_PX >= WINDOW_REACH_PX * 1.5);+});++test("a window holding the tail also holds the prompt its reply answers", () => {+ assert.deepEqual(holdTailTurn({ start: 9, end: 10 }, 10, 8), { start: 8, end: 10 });+ assert.deepEqual(holdTailTurn({ start: 5, end: 10 }, 10, 8), { start: 5, end: 10 });+ assert.deepEqual(holdTailTurn({ start: 9, end: 10 }, 10, -1), { start: 9, end: 10 });+ // A window away from the tail is the reader's, not the tail's.+ assert.deepEqual(holdTailTurn({ start: 2, end: 6 }, 10, 1), { start: 2, end: 6 });+ assert.equal(holdTailTurn(null, 10, 8), null);+ // A prompt many rows up (a long agent turn) is not worth mounting everything between.+ const far = { start: 50, end: 60 };+ assert.deepEqual(holdTailTurn(far, 60, 50 - TAIL_TURN_MAX_ROWS - 1), far);+ assert.deepEqual(holdTailTurn(far, 60, 50 - TAIL_TURN_MAX_ROWS), {+ start: 50 - TAIL_TURN_MAX_ROWS,+ end: 60,+ });+ // A pin the widened window now covers is no longer a pin.+ assert.deepEqual(holdTailTurn({ start: 9, end: 10, pins: [2, 8] }, 10, 7), {+ start: 7,+ end: 10,+ pins: [2],+ });+ const held = holdTailTurn({ start: 9, end: 10 }, 10, 8);+ assert.deepEqual(holdTailTurn(held, 10, 8), held);+});++test("a new row layout forgets every height, since every row re-wraps", () => {+ const heights = new RowHeights();+ const row = meta(1);+ assert.equal(heights.relayout("800 Inter 15px"), false, "the first layout forgets nothing");+ heights.measure(row, 900);+ assert.equal(heights.relayout("800 Inter 15px"), false);+ assert.equal(heights.heightOf(row), 900, "the same layout keeps them");+ assert.equal(heights.relayout("800 Inter 18px"), true);+ assert.equal(heights.has(row.id), false);+ assert.notEqual(heights.heightOf(row), 900);+});++test("numbered equations are counted where KaTeX's page-wide counters would count them", () => {+ const text = (value: string) => [{ type: "text", text: value }];+ assert.equal(numberedEquations(text("$$x$$ and \\begin{equation*}y\\end{equation*}")), 0);+ assert.equal(numberedEquations(text("$$\\begin{equation}a=b\\end{equation}$$")), 1);+ assert.equal(numberedEquations(text("\\[\\begin{align}a\\\\b \\notag\\\\c\\end{align}\\]")), 2);+ assert.equal(numberedEquations(text("$$\\begin{equation}a\\tag{*}\\end{equation}$$")), 0);+ // A comment is not a tag: KaTeX drops it to the end of the line.+ assert.equal(numberedEquations(text("$$\\begin{equation}a % \\notag\n\\end{equation}$$")), 1);+ assert.equal(numberedEquations(text("$$\\begin{equation}a = 5\\%\\notag\\end{equation}$$")), 0);+ // A nested environment's or a group's rows are not the outer one's.+ assert.equal(+ numberedEquations(text("$$\\begin{align}f &= \\begin{cases}1\\\\0\\end{cases}\\\\ g &= 2\\end{align}$$")),+ 2,+ );+ assert.equal(numberedEquations(text("$$\\begin{gather}\\substack{a\\\\b}\\\\c\\end{gather}$$")), 2);+ // Only display math renders them: bare, inline-coded or fenced, they are text.+ assert.equal(numberedEquations(text("\\begin{equation}a=b\\end{equation}")), 0);+ assert.equal(numberedEquations(text("Use `$$\\begin{equation}a\\end{equation}$$` here")), 0);+ assert.equal(+ numberedEquations(+ text("```latex\n$$\\begin{equation}a\\end{equation}$$\n```\n\n$$\\begin{equation}b\\end{equation}$$"),+ ),+ 1,+ );+ assert.equal(numberedEquations(text("~~~\n$$\\begin{equation}a\\end{equation}$$")), 0);+ assert.equal(numberedEquations(text("Example:\n\n $$\\begin{equation}a\\end{equation}$$\n")), 0);+ assert.equal(numberedEquations(text("> ~~~\n> $$\\begin{equation}a\\end{equation}$$\n> ~~~")), 0);+ assert.equal(numberedEquations([{ type: "reasoning", text: "\\begin{equation}a\\end{equation}" }]), 0);+});++test("a spacer carries the equation counts of the rows it stands for", () => {+ const heights = new RowHeights();+ const metas = [0, 1, 2].map((index) => ({ ...meta(index), equations: index }));+ // Estimated from the text until a row is counted in the DOM.+ assert.deepEqual(heights.equationsIn(metas, 0, 3), { html: 3, mathml: 3 });+ heights.countEquations(metas[2], { html: 5, mathml: 0 });+ assert.deepEqual(heights.equationsIn(metas, 1, 3), { html: 6, mathml: 1 });+ assert.deepEqual(heights.equationsIn(metas, 2, 2), { html: 0, mathml: 0 });+ assert.equal(heights.measure(metas[0], 100), true);+ assert.equal(heights.measure(metas[0], 100), false, "an unchanged height is not a change");+});++test("always expanded thinking and tool cards count their text", () => {+ const trace = "step\n".repeat(40);+ const content = [+ { type: "reasoning", text: trace },+ { type: "tool-call", argsText: '{"q": 1}', result: "row\n".repeat(20) },+ { type: "text", text: "answer" },+ ];+ const collapsed = messageWeight(content);+ assert.equal(collapsed, messageWeight(content, { reasoning: false, tools: false }));+ assert.ok(messageWeight(content, { reasoning: true, tools: false }) >= collapsed + 40);+ assert.ok(messageWeight(content, { reasoning: false, tools: true }) >= collapsed + 20);+});++test("an open trace's equations count, a closed one's do not", () => {+ const content = [+ { type: "reasoning", text: "$$\\begin{equation}a\\end{equation}$$" },+ { type: "text", text: "done" },+ ];+ assert.equal(numberedEquations(content), 0);+ assert.equal(numberedEquations(content, { reasoning: true, tools: false }), 1);+});++test("a relayout forgets the equation counts read off the page", () => {+ const heights = new RowHeights();+ const row = { ...meta(1), equations: 0 };+ heights.relayout("thinking expanded");+ heights.countEquations(row, { html: 2, mathml: 2 });+ assert.deepEqual(heights.equationsIn([row], 0, 1), { html: 2, mathml: 2 });+ heights.relayout("thinking collapsed");+ assert.deepEqual(heights.equationsIn([row], 0, 1), { html: 0, mathml: 0 });+});++test("an edited message's page readings no longer stand for it", () => {+ const heights = new RowHeights();+ const before = { ...meta(1), equations: 0, revision: ["old"] };+ heights.measure(before, 300);+ heights.countEquations(before, { html: 2, mathml: 2 });+ assert.equal(heights.heightOf(before), 300);+ const after = { ...before, weight: 200, equations: 1, revision: ["new"] };+ assert.notEqual(heights.heightOf(after), 300, "the old height stood for new content");+ assert.deepEqual(heights.equationsIn([after], 0, 1), { html: 1, mathml: 1 });+ assert.equal(heights.measure(after, 300), true, "a new revision is a new reading at any height");+ assert.equal(heights.heightOf(after), 300);+});diff --git a/tests/studio/_area_matrix.py b/tests/studio/_area_matrix.pyindex 3f42012a4e2..2487de871b3 100644--- a/tests/studio/_area_matrix.py+++ b/tests/studio/_area_matrix.py@@ -277,6 +277,15 @@ STREAMED = """(end) => {}"""# Answers /v1/chat/completions from the page with STREAM's frames, one per STREAM_MS.+# The thread mounts only the rows near the reader, so "loaded" is the length its rows publish+# (aria-setsize); a thread short enough to mount whole publishes none and is counted instead.+THREAD_LOADED = """(n) => {+ const rows = document.querySelectorAll('[data-role]');+ if (rows.length >= n) return true;+ const last = rows[rows.length - 1];+ return !!last && Number(last.getAttribute('aria-setsize')) >= n;+}"""+STREAM_SHIM = """(([frames, ms]) => {const realFetch = window.fetch.bind(window);window.__gateStreams = 0;@@ -1056,7 +1065,7 @@ class Page:f"{base}/chat?thread={self.api.rec['id']}", wait_until = "load", timeout = 120_000)page.wait_for_function(- "(n) => document.querySelectorAll('[data-role]').length >= n",+ THREAD_LOADED,arg = 2 * turns,timeout = 120_000,)diff --git a/tests/studio/_webkit_leg.py b/tests/studio/_webkit_leg.pyindex 6afbd621288..e571f11e129 100644--- a/tests/studio/_webkit_leg.py+++ b/tests/studio/_webkit_leg.py@@ -263,7 +263,7 @@ class WebKitPage(am.Page):self.attr_before, self.focusins_before, self.hovered = None, 0, Falsepage.goto(f"{base}/chat?thread={self.api.rec['id']}", wait_until = "load", timeout = 180_000)page.wait_for_function(- "(n) => document.querySelectorAll('[data-role]').length >= n",+ am.THREAD_LOADED,arg = 2 * turns,timeout = 180_000,)diff --git a/tests/studio/playwright_long_chat_renders.py b/tests/studio/playwright_long_chat_renders.pyindex 946158111fa..0ebef7477bc 100644--- a/tests/studio/playwright_long_chat_renders.py+++ b/tests/studio/playwright_long_chat_renders.py@@ -28,7 +28,7 @@ from _playwright_robust import ( # noqa: E402PORT = int(os.environ.get("SMOKE_PORT", "5217"))_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"-# Under MIN_PROGRESSIVE_MESSAGES (40), so the whole history mounts in one commit.+# The harness page holds every row mounted, so the whole history is in the DOM.MESSAGES = 30CHUNKS = 60diff --git a/tests/studio/playwright_thread_window.py b/tests/studio/playwright_thread_window.pynew file mode 100644index 00000000000..9c0df36ab2d--- /dev/null+++ b/tests/studio/playwright_thread_window.py@@ -0,0 +1,731 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A long thread mounts only the rows near the reader, and nothing the reader can do shows it.++smoke-thread-weight.html?window=1 is the thread as the app opens it (without the flag the page+holds every row mounted). Structure only, never a timing:++ 1. The DOM does not grow with the chat: a 400-message thread mounts about what an 80-message+ one does, and its rows publish the thread's length and their place (aria-setsize,+ aria-posinset), so assistive technology does not count only what is mounted.+ 2. The scroll range is the fully mounted thread's, within EXTENT_TOLERANCE, before a single row+ above the fold has rendered.+ 3. Wheeling to the top, the window catches up with the reader after every step, passes every+ message once, and ends on the first one.+ 4. A reader at rest is not moved by the window settling behind them.+ 5. A jump (a dragged scrollbar) lands on mounted rows.+ 6. A row the reader is working in stays mounted, with its focus, wherever they jump to, apart+ from the window and without the rows between; it is let go once they leave it.+ 7. Copying a selection that runs over unmounted rows carries the whole conversation, the same+ text the fully mounted thread selects, and the window comes back once the selection is gone.+ 8. A thread hidden behind another route mounts nothing while it has no boxes to measure, and a+ full mount it was in the middle of does not count as pending for the threads on screen.+ 9. A reply streamed into the windowed thread lands at the tail with the reader following it.+ 10. Mounting everything (select all) goes in passes bounded by height, so very long replies do+ not land thirty-two to a commit.+ 11. The window at the tail holds the last prompt too, and a prompt being edited (a row with no+ `data-role`) keeps its editor, focus and draft across jumps to both ends.+ 12. The leading spacer carries the KaTeX equation numbers of the rows it stands for, so the+ page-wide numbering of the mounted rows is the fully mounted thread's.+ 13. A code block's own word wrap survives its row being unmounted and mounted again.+"""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++from playwright.sync_api import TimeoutError as PlaywrightTimeoutError+from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5219"))+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+ENGINES = [e for e in os.environ.get("SMOKE_ENGINES", "chromium").split(",") if e]+SMALL = 80+LARGE = 400+STREAM_CHUNKS = 20+DRAFT = "unsaved draft for the windowed thread"+SEED = {"agent": {"rounds": 2, "compactionEvery": 10, "sources": True, "rich": True}}+# Same allowance studiobench gives a windowed arm (analysis/behaviour.py).+EXTENT_TOLERANCE = 0.10+# Rows the larger thread may mount beyond the smaller one: a row of slack either side.+ROW_SLACK = 4+WHEEL_PX = 700+WHEEL_GAP_MS = 40+# Rows are separated by gaps, so a covered viewport is not rows from edge to edge.+MIN_COVERAGE = 0.5+# How long the window may take to catch up with one wheel step before it counts as lost. Not a+# pace: a shared CI runner serving unminified modules takes whole frames for a commit.+CATCH_UP_MS = 30_000+# Very long replies, for the full mount: a few thousand px each.+TALL_MESSAGES = 60+TALL_SEED = {"agent": {"rounds": 12, "compactionEvery": 10, "sources": True, "rich": True}}+# thread-window.ts FILL_BUDGET_PX and progressive-mount-controller.ts CHUNK_MESSAGES. The budget+# is spent on estimated heights, so a pass may come out somewhat over it once rendered.+FILL_BUDGET_PX = 20_000+FILL_BUDGET_SLACK = 1.5+FILL_CHUNK_ROWS = 32++STATE = """() => {+ const api = window.__threadWeight;+ const viewport = api.viewport();+ const rows = [...document.querySelectorAll('[data-role]')];+ return {+ length: api.threadLength(),+ mounted: rows.length,+ positions: rows.map((row) => Number(row.getAttribute('aria-posinset'))),+ sizes: [...new Set(rows.map((row) => row.getAttribute('aria-setsize')))],+ scrollTop: viewport.scrollTop,+ scrollHeight: viewport.scrollHeight,+ clientHeight: viewport.clientHeight,+ topSpacer: document.querySelector('[data-thread-spacer="top"]')?.offsetHeight ?? null,+ nodes: document.getElementsByTagName('*').length,+ };+}"""++# One sample per frame: how much of the viewport rows cover, and which messages are mounted.+RECORD = """() => {+ const viewport = window.__threadWeight.viewport();+ const record = { frames: 0, minCoverage: 1, seen: new Set(), live: true };+ window.__windowRecord = record;+ const tick = () => {+ if (!record.live) return;+ const box = viewport.getBoundingClientRect();+ let covered = 0;+ for (const row of document.querySelectorAll('[data-role]')) {+ const at = row.getBoundingClientRect();+ covered += Math.max(0, Math.min(at.bottom, box.bottom) - Math.max(at.top, box.top));+ record.seen.add(Number(row.getAttribute('aria-posinset')));+ }+ record.frames += 1;+ record.minCoverage = Math.min(record.minCoverage, covered / box.height);+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+}"""++# Rows over at least `min` of the viewport: the window is where the reader is.+COVERED = """(min) => {+ const box = window.__threadWeight.viewport().getBoundingClientRect();+ let covered = 0;+ for (const row of document.querySelectorAll('[data-role]')) {+ const at = row.getBoundingClientRect();+ covered += Math.max(0, Math.min(at.bottom, box.bottom) - Math.max(at.top, box.top));+ }+ return covered / box.height >= min;+}"""++STOP_RECORD = """() => {+ const record = window.__windowRecord;+ record.live = false;+ return { frames: record.frames, minCoverage: record.minCoverage, seen: [...record.seen] };+}"""++# The first row the reader can see, and where it sits, over a run of frames.+REST = """async (frames) => {+ const viewport = window.__threadWeight.viewport();+ const fold = viewport.getBoundingClientRect().top;+ const row = [...document.querySelectorAll('[data-role]')].find(+ (candidate) => candidate.getBoundingClientRect().bottom > fold + 1,+ );+ if (!row) return null;+ const id = row.getAttribute('data-message-id');+ const offsets = [];+ for (let frame = 0; frame < frames; frame += 1) {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ const now = document.querySelector(`[data-message-id="${CSS.escape(id)}"]`);+ offsets.push(now ? now.getBoundingClientRect().top - fold : null);+ }+ return offsets;+}"""++# Focus a control in the first row the reader can see, and mark its node: a row that was unmounted+# and mounted again has a new node, which the mark is not on.+PIN = """() => {+ const viewport = window.__threadWeight.viewport();+ const fold = viewport.getBoundingClientRect().top;+ for (const row of document.querySelectorAll('[data-role]')) {+ if (row.getBoundingClientRect().bottom <= fold + 1) continue;+ const control = row.querySelector('button, [tabindex]');+ if (!control) continue;+ control.focus({ preventScroll: true });+ if (document.activeElement !== control) continue;+ control.setAttribute('data-pin-probe', '');+ return { position: Number(row.getAttribute('aria-posinset')), scrollTop: viewport.scrollTop };+ }+ return null;+}"""++PINNED = """() => {+ const probe = document.querySelector('[data-pin-probe]');+ const row = probe?.closest('[data-role]') ?? null;+ return {+ mounted: probe !== null,+ focused: probe !== null && document.activeElement === probe,+ position: row ? Number(row.getAttribute('aria-posinset')) : null,+ gaps: document.querySelectorAll('[data-thread-spacer="gap"]').length,+ };+}"""++# The first mounted row's ordinal and the counter increments of the spacer standing in for the rest.+SPACER_EQUATIONS = """() => ({+ first: Number(document.querySelector('[data-role][aria-posinset]').getAttribute('aria-posinset')),+ increment: document.querySelector('[data-thread-spacer="top"]').style.counterIncrement,+})"""++EQUATIONS_BEFORE = """(first) => [...document.querySelectorAll('[data-role]')]+ .slice(0, first - 1)+ .reduce((sum, row) => sum + row.querySelectorAll('.eqn-num').length, 0)"""++JUMP = """(top) => {+ const viewport = window.__threadWeight.viewport();+ viewport.scrollTo({ top: top < 0 ? viewport.scrollHeight : top, behavior: 'instant' });+}"""++# One entry per commit that added rows: how many, and how tall they came out.+WATCH_PASSES = """() => {+ const viewport = window.__threadWeight.viewport();+ const passes = [];+ window.__fillPasses = passes;+ new MutationObserver((records) => {+ let rows = 0;+ let px = 0;+ for (const record of records) {+ for (const node of record.addedNodes) {+ if (node.nodeType !== 1 || !node.matches('[data-role]')) continue;+ rows += 1;+ px += node.getBoundingClientRect().height;+ }+ }+ if (rows > 0) passes.push({ rows, px: Math.round(px) });+ }).observe(viewport, { childList: true });+}"""++SELECT_ALL = """() => {+ document.body.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'a', ctrlKey: true, bubbles: true, cancelable: true }),+ );+}"""++SELECT_THREAD = """() => {+ const viewport = window.__threadWeight.viewport();+ const selection = window.getSelection();+ selection.removeAllRanges();+ const range = document.createRange();+ range.selectNodeContents(viewport);+ selection.addRange(range);+}"""++# A dispatched event runs the app's copy handlers in every engine; a key press does not copy in+# WebKit. What the selection holds once they return is what the clipboard would take.+COPY = """() => {+ window.__threadWeight.viewport().dispatchEvent(+ new ClipboardEvent('copy', { bubbles: true, cancelable: true }),+ );+ return {+ chars: window.__selectedChars(),+ mounted: document.querySelectorAll('[data-role]').length,+ };+}"""++# Without whitespace: a code fence serialises its line breaks differently once it has been+# highlighted (Firefox), and which fences have been is a matter of where each page has scrolled.+SELECTED_CHARS = """+window.__selectedChars = () => window.getSelection().toString().replace(/\\s+/g, '').length;+"""+++def info(message: str) -> None:+ print(f"[thread-window] {message}", flush = True)+++def open_thread(+ context,+ messages: int,+ *,+ windowed: bool,+ stream: bool = False,+ seed: dict = SEED,+):+ page = context.new_page()+ errors: list[str] = []+ page.on("pageerror", lambda error: errors.append(str(error)))+ query = (+ "shell=1"+ + ("&window=1" if windowed else "")+ + (f"&stream={STREAM_CHUNKS}" if stream else "")+ )+ page.goto(f"{BASE}/smoke-thread-weight.html?{query}", wait_until = "load")+ page.wait_for_function("() => window.__threadWeight !== undefined", timeout = 120_000)+ page.evaluate("([n, o]) => window.__threadWeight.seed(n, o)", [messages, seed])+ page.wait_for_function(+ "(n) => window.__threadWeight.threadLength() >= n", arg = messages, timeout = 120_000+ )+ if not windowed:+ page.wait_for_function(+ "(n) => window.__threadWeight.messageCount() >= n", arg = messages, timeout = 180_000+ )+ settle(page)+ return page, errors+++def settle(page) -> dict:+ """Waits until the mounted rows and the scroll range have held for half a second."""+ last, stable = None, 0+ for _ in range(300):+ state = page.evaluate(STATE)+ key = (state["mounted"], state["scrollHeight"], round(state["scrollTop"]))+ stable = stable + 1 if key == last else 0+ if stable >= 5:+ return state+ last = key+ page.wait_for_timeout(100)+ raise AssertionError(f"the thread never settled: {last}")+++def check_ordinals(+ state: dict,+ label: str,+ pinned: int | None = None,+) -> None:+ """The mounted rows are one run of consecutive messages, plus `pinned` when it is outside it."""+ positions = state["positions"]+ assert state["sizes"] == [str(state["length"])], (+ f"{label}: rows must all publish the thread's length {state['length']} as aria-setsize, "+ f"got {state['sizes']}"+ )+ assert positions == sorted(positions), f"{label}: rows are out of order: {positions}"+ if pinned is not None:+ assert pinned in positions, f"{label}: the pinned row {pinned} is not mounted: {positions}"+ run = [position for position in positions if position != pinned]+ if run and (pinned == run[0] - 1 or pinned == run[-1] + 1):+ run = positions+ else:+ run = positions+ assert run == list(+ range(run[0], run[0] + len(run))+ ), f"{label}: mounted rows are not consecutive messages: {positions}"+++def check_engine(playwright, engine: str) -> None:+ launcher = getattr(playwright, engine)+ browser = launcher.launch(+ headless = True, args = chromium_launch_args() if engine == "chromium" else []+ )+ try:+ context = browser.new_context(viewport = {"width": 1440, "height": 900})+ context.add_init_script(SELECTED_CHARS)++ # 1. The DOM does not grow with the chat.+ page, errors = open_thread(context, SMALL, windowed = True)+ small = page.evaluate(STATE)+ page.close()+ page, errors = open_thread(context, LARGE, windowed = True)+ opened = page.evaluate(STATE)+ info(+ f"{engine}: {SMALL} messages mount {small['mounted']} rows ({small['nodes']} elements), "+ f"{LARGE} mount {opened['mounted']} ({opened['nodes']})"+ )+ assert opened["length"] == LARGE, opened["length"]+ assert opened["mounted"] <= small["mounted"] + ROW_SLACK, (+ f"a {LARGE}-message thread mounts {opened['mounted']} rows against {small['mounted']} "+ f"for {SMALL}: the mounted rows grow with the chat"+ )+ check_ordinals(opened, "on open")+ assert (+ opened["positions"][-1] == LARGE+ ), f"the thread did not open on its last message: {opened['positions']}"+ bottom = opened["scrollHeight"] - opened["clientHeight"] - opened["scrollTop"]+ assert abs(bottom) <= 2, f"the thread opened {bottom}px above its end"++ # 2. The scroll range is the fully mounted thread's.+ full_page, full_errors = open_thread(context, LARGE, windowed = False)+ full = full_page.evaluate(STATE)+ full_page.evaluate(SELECT_THREAD)+ full_chars = full_page.evaluate("() => window.__selectedChars()")+ full_page.close()+ assert full["mounted"] == LARGE and not full_errors, (full["mounted"], full_errors)+ drift = abs(opened["scrollHeight"] - full["scrollHeight"]) / full["scrollHeight"]+ info(+ f"{engine}: scroll range {opened['scrollHeight']} windowed, {full['scrollHeight']} "+ f"mounted ({drift:.1%} apart)"+ )+ assert drift <= EXTENT_TOLERANCE, (+ f"the windowed thread is {opened['scrollHeight']}px tall and the mounted one "+ f"{full['scrollHeight']}px: {drift:.1%} apart, {EXTENT_TOLERANCE:.0%} allowed"+ )++ # 3. Wheeling to the top, the window keeps up and passes every message.+ box = page.locator(".aui-thread-viewport").bounding_box()+ page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+ page.evaluate(RECORD)+ rest_checked = False+ for step in range(6_000):+ page.mouse.wheel(0, -WHEEL_PX)+ page.wait_for_timeout(WHEEL_GAP_MS)+ try:+ page.wait_for_function(COVERED, arg = MIN_COVERAGE, timeout = CATCH_UP_MS)+ except PlaywrightTimeoutError:+ raise AssertionError(+ f"rows cover under {MIN_COVERAGE:.0%} of the viewport {CATCH_UP_MS}ms after "+ f"wheel step {step}: the window lost the reader"+ ) from None+ if step == 60 and not rest_checked:+ # 4. A reader at rest is not moved by the window settling behind them.+ rest_checked = True+ page.wait_for_timeout(700)+ offsets = page.evaluate(REST, 40)+ assert (+ offsets and None not in offsets+ ), f"the reader's row unmounted at rest: {offsets}"+ moved = max(offsets) - min(offsets)+ assert moved <= 1, f"a reader at rest moved {moved}px while the window settled"+ if (+ step % 10 == 9+ and page.evaluate("() => window.__threadWeight.viewport().scrollTop") <= 0+ ):+ break+ page.wait_for_timeout(600)+ record = page.evaluate(STOP_RECORD)+ top = page.evaluate(STATE)+ # The least coverage on any one frame is how far the window fell behind in passing. It+ # is reported and not asserted: it is this machine's speed, not the window's structure.+ info(+ f"{engine}: wheel to top, {record['frames']} frames, least coverage on a frame "+ f"{record['minCoverage']:.0%}, {len(record['seen'])} of {LARGE} messages passed"+ )+ missing = sorted(set(range(1, LARGE + 1)) - set(record["seen"]))+ assert not missing, f"messages never mounted on the way up: {missing[:20]}"+ check_ordinals(top, "at the top")+ assert top["positions"][0] == 1 and top["scrollTop"] <= 0 and top["topSpacer"] == 0, (+ f"the top of the thread is not its first message: {top['positions'][:3]}, "+ f"scrollTop {top['scrollTop']}, spacer {top['topSpacer']}"+ )+ assert (+ top["mounted"] <= small["mounted"] + 2 * ROW_SLACK+ ), f"{top['mounted']} rows are still mounted after the sweep: rows are not unmounting"++ # 5. A jump lands on mounted rows.+ page.evaluate(RECORD)+ page.evaluate(+ "() => { const v = window.__threadWeight.viewport();"+ " v.scrollTo({ top: v.scrollHeight / 2, behavior: 'instant' }); }"+ )+ settle(page)+ middle = page.evaluate(STATE)+ record = page.evaluate(STOP_RECORD)+ check_ordinals(middle, "after a jump")+ landed = page.evaluate(REST, 1)+ assert landed and landed[0] is not None, "a jump to the middle left the viewport empty"+ assert 1 < middle["positions"][0] and middle["positions"][-1] < LARGE, middle["positions"]++ # 6. A row the reader is working in survives every jump, apart from the window.+ pin = page.evaluate(PIN)+ assert pin, "no mounted row has a control to focus"+ bound = small["mounted"] + 2 * ROW_SLACK + 1+ for label, target in (("the top", 0), ("the end", -1)):+ page.evaluate(JUMP, target)+ state = settle(page)+ held = page.evaluate(PINNED)+ assert held["mounted"] and held["focused"], (+ f"a jump to {label} unmounted the row the reader had focus in "+ f"(message {pin['position']}): {held}, rows {state['positions']}"+ )+ check_ordinals(state, f"pinned, at {label}", pinned = pin["position"])+ assert held["gaps"] >= 1, f"the pinned row has no spacer of its own at {label}: {held}"+ assert state["mounted"] <= bound, (+ f"{state['mounted']} rows mounted at {label} with one pinned: the window "+ f"stretched to the pinned row instead of leaving it where it is"+ )+ drift = abs(state["scrollHeight"] - full["scrollHeight"]) / full["scrollHeight"]+ assert drift <= EXTENT_TOLERANCE, (+ f"the scroll range is {drift:.1%} off the mounted thread at {label}: the "+ f"spacers around the pinned row do not stand in for the rows left out"+ )+ info(+ f"{engine}: message {pin['position']} kept its focus across jumps to both ends, "+ f"{state['mounted']} rows mounted"+ )+ # Back onto it: the window takes the row in, without moving its node.+ page.evaluate(JUMP, pin["scrollTop"])+ state = settle(page)+ held = page.evaluate(PINNED)+ assert (+ held["mounted"] and held["focused"] and held["gaps"] == 0+ ), f"coming back to the pinned row lost it: {held}, rows {state['positions']}"+ check_ordinals(state, "back on the pinned row")+ # Let go: the row unmounts once the reader is elsewhere and no longer in it.+ page.evaluate(JUMP, 0)+ settle(page)+ page.evaluate("() => document.activeElement?.blur()")+ page.wait_for_function(+ "() => document.querySelector('[data-pin-probe]') === null", timeout = 30_000+ )+ check_ordinals(settle(page), "after the pin is let go")+ page.evaluate(JUMP, pin["scrollTop"])+ settle(page)++ # 7. A copy over unmounted rows carries the whole conversation.+ page.evaluate(SELECT_THREAD)+ copied = page.evaluate(COPY)+ info(+ f"{engine}: copy holds {copied['chars']} characters with {copied['mounted']} rows "+ f"mounted; the mounted thread selects {full_chars}"+ )+ assert (+ copied["mounted"] == LARGE+ ), f"a copy over the whole thread ran with {copied['mounted']} of {LARGE} rows mounted"+ assert copied["chars"] == full_chars, (+ f"the copy holds {copied['chars']} characters and the mounted thread {full_chars}: "+ f"text was lost or added"+ )+ page.evaluate("() => window.getSelection().removeAllRanges()")+ page.wait_for_function(+ "(n) => document.querySelectorAll('[data-role]').length <= n",+ arg = small["mounted"] + 2 * ROW_SLACK,+ timeout = 30_000,+ )+ check_ordinals(settle(page), "after the copy")+ assert not errors, errors+ page.close()++ # 8. A hidden thread stays as it is, and holds nothing else up.+ page, errors = open_thread(context, LARGE, windowed = True)+ shown = page.evaluate(STATE)+ page.evaluate(+ "() => { document.querySelector('[data-smoke=\"thread\"]').style.display = 'none'; }"+ )+ page.wait_for_timeout(1_500)+ hidden = page.evaluate("() => document.querySelectorAll('[data-role]').length")+ assert hidden == shown["mounted"], (+ f"{hidden} rows mounted while the thread was hidden, {shown['mounted']} before: "+ f"a thread with no boxes is walking itself"+ )+ page.evaluate(+ "() => { document.querySelector('[data-smoke=\"thread\"]').style.display = 'flex'; }"+ )+ back = settle(page)+ check_ordinals(back, "shown again")+ drift = abs(back["scrollHeight"] - shown["scrollHeight"]) / shown["scrollHeight"]+ assert back["positions"][-1] == LARGE and drift <= 0.01, (+ f"the thread came back changed: rows {back['positions']}, scroll range "+ f"{shown['scrollHeight']} -> {back['scrollHeight']}"+ )+ # A reader asks for every row (the find bar), and the thread is hidden part way through.+ page.evaluate("() => document.documentElement.setAttribute('data-find-bar-open', '')")+ page.wait_for_function(+ "(n) => document.querySelectorAll('[data-role]').length > n",+ arg = back["mounted"],+ timeout = 30_000,+ )+ assert page.evaluate(+ "() => window.__threadWeight.pendingMounts()"+ ), "a full mount under way on a visible thread must count as pending"+ page.evaluate(+ "() => { document.querySelector('[data-smoke=\"thread\"]').style.display = 'none'; }"+ )+ page.wait_for_timeout(500)+ part = page.evaluate("() => document.querySelectorAll('[data-role]').length")+ assert part < LARGE, f"the full mount finished before the thread was hidden ({part} rows)"+ assert not page.evaluate("() => window.__threadWeight.pendingMounts()"), (+ f"a hidden thread stopped {part} rows into a full mount still counts as pending: "+ f"the turn rail of every visible thread waits on it"+ )+ page.evaluate("() => document.documentElement.removeAttribute('data-find-bar-open')")+ page.evaluate(+ "() => { document.querySelector('[data-smoke=\"thread\"]').style.display = 'flex'; }"+ )+ # Nobody is waiting for the rest of it any more, so the window comes back.+ page.wait_for_function(+ "(n) => document.querySelectorAll('[data-role]').length <= n",+ arg = small["mounted"] + 2 * ROW_SLACK,+ timeout = 30_000,+ )+ check_ordinals(settle(page), "after the abandoned full mount")+ assert not errors, errors+ page.close()++ # 9. A streamed reply lands at the tail with the reader following it.+ page, errors = open_thread(context, LARGE, windowed = True, stream = True)+ page.evaluate("() => window.__threadWeight.send('go')")+ page.wait_for_function("() => window.__threadWeight.isRunning()", timeout = 60_000)+ page.wait_for_function(+ "() => !window.__threadWeight.isRunning()", timeout = 120_000, polling = 100+ )+ sent = settle(page)+ check_ordinals(sent, "after a reply")+ text = page.evaluate("() => window.__threadWeight.lastAssistantMessage()?.innerText ?? ''")+ assert (+ sent["length"] == LARGE + 2 and sent["positions"][-1] == LARGE + 2+ ), f"the reply is not the mounted tail: {sent['length']} messages, {sent['positions']}"+ assert f"word{STREAM_CHUNKS - 1}" in text, "the stream did not finish in the mounted row"+ assert (+ sent["mounted"] <= small["mounted"] + 2 * ROW_SLACK+ ), f"{sent['mounted']} rows mounted after a reply"+ assert not errors, errors+ page.close()++ # 10. A full mount goes in passes bounded by height.+ page, errors = open_thread(context, TALL_MESSAGES, windowed = True, seed = TALL_SEED)+ tall = page.evaluate(STATE)+ assert (+ tall["mounted"] < TALL_MESSAGES+ ), f"the tall thread is not windowed: {tall['mounted']}"+ page.evaluate(WATCH_PASSES)+ page.evaluate(SELECT_ALL)+ page.wait_for_function(+ "(n) => document.querySelectorAll('[data-role]').length >= n",+ arg = TALL_MESSAGES,+ timeout = 120_000,+ )+ passes = page.evaluate("() => window.__fillPasses")+ tallest = max(passes, key = lambda entry: entry["px"])+ info(+ f"{engine}: select all mounted {TALL_MESSAGES} long replies in {len(passes)} passes, "+ f"the largest {tallest['rows']} rows and {tallest['px']}px"+ )+ for entry in passes:+ assert entry["rows"] <= 2 * FILL_CHUNK_ROWS, f"a pass mounted {entry['rows']} rows"+ assert entry["rows"] == 1 or entry["px"] <= FILL_BUDGET_PX * FILL_BUDGET_SLACK, (+ f"one pass of the full mount added {entry['rows']} rows, {entry['px']}px of them: "+ f"the height budget ({FILL_BUDGET_PX}px) is not bounding it"+ )+ assert not errors, errors+ page.close()++ # 11. The last prompt is mounted with its reply, and an open prompt editor keeps its draft.+ page, errors = open_thread(context, LARGE, windowed = True)+ last_user = page.evaluate(+ "() => [...document.querySelectorAll('[data-role]')].filter("+ "(row) => row.dataset.role === 'user').length"+ )+ assert last_user >= 1, "the window at the tail left out the prompt its reply answers"+ edited = page.evaluate("() => window.__threadWeight.editLastPrompt()")+ editor = page.locator(f'[data-message-id="{edited}"] textarea')+ editor.fill(DRAFT)+ # Wheeled, not scrolled by script: a programmatic scroll is not the reader leaving the tail.+ box = page.locator(".aui-thread-viewport").bounding_box()+ page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+ for _ in range(20):+ page.mouse.wheel(0, -WHEEL_PX)+ page.wait_for_timeout(WHEEL_GAP_MS)+ away = settle(page)+ assert editor.count() == 1 and editor.evaluate("(e) => e === document.activeElement"), (+ f"a prompt being edited lost its editor or focus {away['scrollHeight'] - away['scrollTop']}"+ f"px up the thread"+ )+ assert editor.input_value() == DRAFT, "a prompt being edited lost its draft"+ assert not errors, errors+ page.close()++ # 12. Equation numbers continue across the rows the leading spacer stands for.+ numbered = {"numbered": True}+ page, errors = open_thread(context, LARGE, windowed = True, seed = numbered)+ spacer = page.evaluate(SPACER_EQUATIONS)+ page.close()+ page, errors = open_thread(context, LARGE, windowed = False, seed = numbered)+ expected = page.evaluate(EQUATIONS_BEFORE, spacer["first"])+ page.close()+ info(+ f"{engine}: the leading spacer counts {spacer['increment']!r}, rows above hold {expected}"+ )+ assert spacer["first"] > 1 and expected > 0, spacer+ assert spacer["increment"] == f"katexEqnNo {expected} mmlEqnNo {expected}", (+ f"the leading spacer counts {spacer['increment']!r} for rows that render {expected} "+ f"numbered equations: equation numbers below it shift with the window"+ )++ # 13. A block's wrap choice outlives its row.+ page, errors = open_thread(context, LARGE, windowed = True, seed = numbered)+ row = page.evaluate(+ "() => window.__threadWeight.lastAssistantMessage().getAttribute('data-message-id')"+ )+ wrap = f'[data-message-id="{row}"] button[aria-label="Enable word wrap"], [data-message-id="{row}"] button[aria-label="Disable word wrap"]'+ before = page.locator(wrap).first.get_attribute("aria-pressed")+ page.locator(wrap).first.click()+ page.evaluate("() => window.__threadWeight.composer()?.focus()")+ # A loaded host can hold the window still for a settle; the row must leave within a few.+ for _ in range(5):+ page.evaluate(JUMP, 0)+ settle(page)+ if page.locator(f'[data-message-id="{row}"]').count() == 0:+ break+ else:+ raise AssertionError("the row never left")+ page.evaluate(JUMP, -1)+ settle(page)+ after = page.locator(wrap).first.get_attribute("aria-pressed")+ assert before != after, f"a block's word wrap reset to {after} when its row came back"+ assert not errors, errors+ page.close()++ # 14. A bound Fork Chat chord still forks at the tip once the last row has left.+ context.add_init_script(+ "localStorage.setItem('unsloth_keyboard_shortcuts', "+ "JSON.stringify({forkChat: {primary: 'Mod+Alt+Shift+KeyY'}}))"+ )+ page, errors = open_thread(context, LARGE, windowed = True)+ last = page.evaluate(+ "() => window.__threadWeight.lastAssistantMessage().getAttribute('data-message-id')"+ )+ box = page.locator(".aui-thread-viewport").bounding_box()+ page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+ for _ in range(400):+ page.mouse.wheel(0, -WHEEL_PX)+ page.wait_for_timeout(30)+ if page.evaluate("() => document.querySelector('.aui-thread-viewport').scrollTop <= 0"):+ break+ settle(page)+ assert page.locator(f'[data-message-id="{last}"]').count() == 0, "the last row never left"+ page.keyboard.press("ControlOrMeta+Alt+Shift+KeyY")+ page.wait_for_timeout(1000)+ forks = [+ json.loads(write["body"] or "{}")+ for write in page.evaluate("() => window.__threadWeight.apiWrites()")+ if write["url"].endswith("/fork")+ ]+ info(f"{engine}: the fork chord at the top posts {forks!r}")+ assert [fork.get("messageId") for fork in forks] == [+ last+ ], f"the fork chord posted {forks!r} with the last row unmounted, not one fork of {last}"+ page.close()+ info(f"{engine}: ok " + json.dumps({"small": small["mounted"], "large": opened["mounted"]}))+ finally:+ browser.close()+++def main() -> int:+ proc = None+ try:+ if not _EXTERNAL:+ proc = start_vite(PORT)+ wait_for_smoke_page(+ f"{BASE}/smoke-thread-weight.html",+ "smoke-thread-weight-main.tsx",+ proc = proc,+ info = info,+ )+ with sync_playwright() as playwright:+ for engine in ENGINES:+ check_engine(playwright, engine)+ info("ok")+ return 0+ finally:+ if proc is not None:+ stop_process(proc)+++if __name__ == "__main__":+ raise SystemExit(main())