Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make the chat thread stop getting slower as it fills (#8992)

Daniel Hanb0843382d285
diff --git a/.gitignore b/.gitignore
index 41e821e11d4..2560323fcb7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -247,3 +247,8 @@ logs/
# Audio fixture downloaded by tests/saving/text_to_speech_models at import time.
Speech_12dB_s16.flac
+
+# Generated at test time by tests/studio/install/test_selection_logic.py, which points
+# storage_roots.studio_root at it. It is a mutable SQLite runtime database, not a fixture,
+# so a test run or a Studio start rewrites it and dirties the checkout.
+.studio-test-root/
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index cf4eba4fd87..11d326a1222 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -36,6 +36,7 @@ from storage.studio_db import (
delete_chat_threads,
ensure_chat_project_workspace,
fork_chat_thread,
+ fork_counts_for_thread,
get_chat_attachment,
get_chat_project,
get_chat_thread,
@@ -1354,6 +1355,10 @@ class ChatForkCountResponse(BaseModel):
count: int
+class ChatThreadForkCountsResponse(BaseModel):
+ counts: dict[str, int]
+
+
@router.post("/threads/{thread_id}/fork", response_model = ChatForkResponse)
def fork_thread(
thread_id: str,
@@ -1422,6 +1427,15 @@ def get_fork_count(
return ChatForkCountResponse(count = count_forks_for_message(thread_id, message_id))
+ "/threads/{thread_id}/forks",
+ response_model = ChatThreadForkCountsResponse,
+)
+def get_thread_fork_counts(thread_id: str, current_subject: str = Depends(get_current_subject)):
+ """Every fork count of a thread in one read, so a rendered thread costs one request."""
+ return ChatThreadForkCountsResponse(counts = fork_counts_for_thread(thread_id))
+
+
@router.get("/export", response_model = ChatExportResponse)
def export_history(current_subject: str = Depends(get_current_subject)):
from datetime import datetime, timezone
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 5381fb421d4..a373dc35fd1 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3350,6 +3350,23 @@ def count_forks_for_message(thread_id: str, message_id: str) -> int:
conn.close()
+def fork_counts_for_thread(thread_id: str) -> dict[str, int]:
+ """Fork counts for every message of one thread, keyed by message id."""
+ conn = get_connection()
+ try:
+ rows = conn.execute(
+ """
+ SELECT forked_from_message_id, COUNT(*) FROM chat_threads
+ WHERE forked_from_thread_id = ? AND forked_from_message_id IS NOT NULL
+ GROUP BY forked_from_message_id
+ """,
+ (thread_id,),
+ ).fetchall()
+ return {str(row[0]): int(row[1]) for row in rows}
+ finally:
+ conn.close()
+
+
def list_chat_messages(thread_id: str) -> list[dict]:
conn = get_connection()
try:
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 0398f41e9c1..1a4f333dc6b 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -653,3 +653,12 @@ def test_get_fork_count(monkeypatch):
current_subject = "test-user",
)
assert response.count == 3
+
+
+def test_get_thread_fork_counts(monkeypatch):
+ monkeypatch.setattr(chat_history, "fork_counts_for_thread", lambda _t: {"m1": 2, "m2": 1})
+ response = chat_history.get_thread_fork_counts(
+ thread_id = "t",
+ current_subject = "test-user",
+ )
+ assert response.counts == {"m1": 2, "m2": 1}
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index 5092198ce5e..0f333823580 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -848,6 +848,40 @@ def test_count_forks_for_message(tmp_path, monkeypatch):
assert studio_db.count_forks_for_message("src", "m1") == 2
+def test_fork_counts_for_thread(tmp_path, monkeypatch):
+ """One read for the whole thread, so a rendered thread costs one request, not one per message."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ studio_db.upsert_chat_thread(_thread("src"))
+ studio_db.sync_chat_messages(
+ "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]
+ )
+ assert studio_db.fork_counts_for_thread("src") == {}
+
+ counter = {"i": 0}
+
+ def id_factory():
+ counter["i"] += 1
+ return f"id-{counter['i']}"
+
+ for index, (branch, new_id) in enumerate([("m1", "f1"), ("m1", "f2"), ("m2", "f3")]):
+ studio_db.fork_chat_thread(
+ source_thread_id = "src",
+ branch_message_id = branch,
+ new_thread_id = new_id,
+ new_title = new_id,
+ created_at = 10 + index,
+ id_factory = id_factory,
+ )
+
+ counts = studio_db.fork_counts_for_thread("src")
+ assert counts == {"m1": 2, "m2": 1}
+ # Same answer as the per-message read it replaces, message for message.
+ for message_id in ["m1", "m2", "m3"]:
+ assert counts.get(message_id, 0) == studio_db.count_forks_for_message("src", message_id)
+ # Another thread's forks never leak in.
+ assert studio_db.fork_counts_for_thread("f1") == {}
+
+
def _research_thread(
tmp_path,
monkeypatch,
diff --git a/studio/frontend/smoke-thread-weight-main.tsx b/studio/frontend/smoke-thread-weight-main.tsx
new file mode 100644
index 00000000000..f487d8a2646
--- /dev/null
+++ b/studio/frontend/smoke-thread-weight-main.tsx
@@ -0,0 +1,338 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for tests/studio/playwright_thread_weight.py: the real Thread at N messages, so the
+// measured cost of a keystroke, a scroll, a menu and a delete is the app's own and grows with the
+// thread the way a user's does (#8977).
+// Same shape as smoke-autoscroll.html and smoke-research.html: a vite entry, no backend, no auth.
+//
+// Two things are real on purpose and cannot be mocked away without deleting the measurement:
+// - Thread itself, from src/components/assistant-ui/thread.tsx, with its per-message action
+// bars, tooltips and markdown blocks.
+// - The message bodies, which carry prose plus one code fence plus one KaTeX block each, so
+// Streamdown, Shiki and KaTeX all pay their per-message price.
+// The runtime is synthetic: a local runtime whose model adapter never runs, seeded through
+// `thread.import`.
+//
+// useLocalRuntime rather than useExternalStoreRuntime: the delete path under measurement is
+// `thread.export()` -> MessageRepository -> `thread.import()`, which only the local runtime backs.
+
+import { Thread } from "@/components/assistant-ui/thread";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import {
+ AssistantRuntimeProvider,
+ type ChatModelAdapter,
+ ExportedMessageRepository,
+ type ThreadMessageLike,
+ useAui,
+ useLocalRuntime,
+} from "@assistant-ui/react";
+import {
+ RouterProvider,
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+} from "@tanstack/react-router";
+import { type ReactElement, useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+import "./src/index.css";
+
+// The local runtime's thread list item reports a synthetic `__LOCALID_...` remoteId, which is
+// truthy, so ForkCountBadge really does fire one GET per assistant message. Measured: seeding 20
+// messages issues 10 requests. Answering them here, before anything mounts, keeps that off the
+// wire entirely. Answering them from the Playwright side instead would put a CDP round trip to
+// another process inside a region this harness is timing, once per assistant message.
+const realFetch = window.fetch.bind(window);
+window.fetch = (input, init) => {
+ const url = typeof input === "string" ? input : (input as Request).url ?? String(input);
+ if (url.includes("/api/")) {
+ return Promise.resolve(
+ new Response("{}", {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }
+ return realFetch(input, init);
+};
+
+const PROSE =
+ "The reception of a long thread is decided by what the renderer does on every " +
+ "interaction, not by what it did once at load. This paragraph exists to give each " +
+ "message real prose to lay out, to wrap over several lines at a chat column's width, " +
+ "and to make the message tall enough that a seeded thread overflows the viewport.";
+
+const CLOSING =
+ "A second paragraph, so each message has more than one block-level child and the " +
+ "layout pass inside it is not trivially small.";
+
+function codeFence(index: number): string {
+ return [
+ "```python",
+ `def step_${index}(rows):`,
+ ' """One fence per message, so every message pays a highlighter pass."""',
+ " total = 0",
+ " for row in rows:",
+ " total += row.weight * row.count",
+ " return total",
+ "```",
+ ].join("\n");
+}
+
+function katexBlock(index: number): string {
+ return `$$\n\\sum_{k=1}^{${index + 1}} \\frac{1}{k^2} \\le \\frac{\\pi^2}{6}\n$$`;
+}
+
+function assistantMarkdown(index: number): string {
+ return [
+ `Reply ${index}. ${PROSE}`,
+ codeFence(index),
+ katexBlock(index),
+ CLOSING,
+ ].join("\n\n");
+}
+
+/**
+ * A reply that is prose and nothing else: no fence, no math, no link, no image.
+ *
+ * The default body above carries a code fence, and Streamdown gives every fence its own Copy
+ * button, so every assistant message in the default fixture happens to hold a focusable control
+ * whether or not its action bar is mounted. Most real replies are not like that. This variant
+ * exists so the harness can seed a reply whose focusable count is ZERO and a keyboard walk has
+ * nothing to land on (#8992, review item on unreachable plain-text replies).
+ */
+function plainAssistantMarkdown(index: number): string {
+ return [`Reply ${index}. ${PROSE}`, CLOSING].join("\n\n");
+}
+
+function userMarkdown(index: number): string {
+ return `Prompt ${index}. ${PROSE}`;
+}
+
+/**
+ * Which assistant replies are plain prose, by their ordinal among assistant messages.
+ * `"all"` makes every reply plain; omitting it keeps the default fenced body everywhere, so
+ * the existing weight measurements are untouched.
+ */
+type SeedOptions = { plainAssistants?: readonly number[] | "all" };
+
+function isPlain(assistantOrdinal: number, options: SeedOptions | undefined): boolean {
+ const plain = options?.plainAssistants;
+ if (!plain) return false;
+ if (plain === "all") return true;
+ return plain.includes(assistantOrdinal);
+}
+
+/** Alternating prompts and replies, oldest first, as a loaded thread arrives. */
+function buildMessages(
+ count: number,
+ options?: SeedOptions,
+): ThreadMessageLike[] {
+ return Array.from({ length: count }, (_, index) =>
+ index % 2 === 0
+ ? {
+ role: "user" as const,
+ content: [{ type: "text" as const, text: userMarkdown(index) }],
+ }
+ : {
+ role: "assistant" as const,
+ content: [
+ {
+ type: "text" as const,
+ text: isPlain((index - 1) / 2, options)
+ ? plainAssistantMarkdown(index)
+ : assistantMarkdown(index),
+ },
+ ],
+ },
+ );
+}
+
+// A run would need a backend. Seeding goes through `thread.import`, which does not use this.
+const NEVER_RUNS: ChatModelAdapter = {
+ run: () => {
+ throw new Error("smoke-thread-weight does not run the model");
+ },
+};
+
+function ThreadWeightApi({
+ setThreadMounted,
+}: {
+ setThreadMounted: (mounted: boolean) => void;
+}): null {
+ const aui = useAui();
+
+ useEffect(() => {
+ const api = {
+ /** Replace the thread with `count` messages, oldest first. */
+ seed(count: number, options?: SeedOptions): void {
+ aui
+ .thread()
+ .import(
+ ExportedMessageRepository.fromArray(buildMessages(count, options)),
+ );
+ },
+ /**
+ * Unmount or remount the Thread while the RUNTIME stays alive, which is what a sidebar
+ * thread switch does to a message's React subtree. The per-message `isHovering` flag
+ * lives in the runtime's message client, not in React, so it outlives this.
+ */
+ setThreadMounted(mounted: boolean): void {
+ setThreadMounted(mounted);
+ },
+ /**
+ * The runtime's own `isHovering` per message, oldest first. Reading the flag rather than
+ * counting mounted bars is what makes a leak test able to see a flag that is set while
+ * nothing is rendered.
+ */
+ hoverFlags(): { id: string; isHovering: boolean }[] {
+ return aui
+ .thread()
+ .getState()
+ .messages.map((message) => ({
+ id: message.id,
+ isHovering: Boolean(message.isHovering),
+ }));
+ },
+ /**
+ * One selector pass. Polling for a deletion has to read this, not counts(): counts() is
+ * eight document-wide queries including a walk of every element, so at 500 messages a
+ * poll loop built on it would spend more time measuring than the delete itself takes.
+ */
+ messageCount(): number {
+ return document.querySelectorAll("[data-role]").length;
+ },
+ /**
+ * Everything a caller might use to prove the seed landed. A harness that seeds 500 and
+ * silently renders 0 measures nothing, so the Python side prints every one of these.
+ */
+ counts(): {
+ messages: number;
+ assistantMessages: number;
+ userMessages: number;
+ domNodes: number;
+ codeBlocks: number;
+ katexNodes: number;
+ actionBars: number;
+ tooltipTriggers: number;
+ } {
+ return {
+ messages: document.querySelectorAll("[data-role]").length,
+ assistantMessages: document.querySelectorAll('[data-role="assistant"]')
+ .length,
+ userMessages: document.querySelectorAll('[data-role="user"]').length,
+ domNodes: document.getElementsByTagName("*").length,
+ codeBlocks: document.querySelectorAll("pre").length,
+ katexNodes: document.querySelectorAll(".katex").length,
+ actionBars: document.querySelectorAll(".aui-assistant-action-bar-root")
+ .length,
+ tooltipTriggers: document.querySelectorAll(
+ '[data-slot="tooltip-trigger"]',
+ ).length,
+ };
+ },
+ viewportMetrics(): {
+ scrollHeight: number;
+ scrollTop: number;
+ clientHeight: number;
+ } {
+ const element = api.viewport();
+ if (!element) {
+ return { scrollHeight: -1, scrollTop: -1, clientHeight: -1 };
+ }
+ return {
+ scrollHeight: element.scrollHeight,
+ scrollTop: element.scrollTop,
+ clientHeight: element.clientHeight,
+ };
+ },
+ viewport(): HTMLElement | null {
+ return document.querySelector<HTMLElement>(".aui-thread-viewport");
+ },
+ composer(): HTMLTextAreaElement | null {
+ return document.querySelector<HTMLTextAreaElement>(
+ ".aui-composer-input",
+ );
+ },
+ /**
+ * What the RUNTIME thinks the composer holds. Reading the textarea back instead would
+ * only echo the value the caller just wrote, so a keystroke that never reached React
+ * would still look like it landed.
+ */
+ composerText(): string {
+ return aui.composer().getState().text;
+ },
+ /** One selector pass, for the seed gate; counts() is far too heavy to poll. */
+ katexCount(): number {
+ return document.querySelectorAll(".katex").length;
+ },
+ /** Highlighted tokens. Shiki runs after the <pre> exists, so counting <pre> gates nothing. */
+ highlightedTokenCount(): number {
+ return document.querySelectorAll("pre code span").length;
+ },
+ /** Items in the open action menu. An empty popover satisfies "the menu opened". */
+ openMenuItemCount(): number {
+ return document.querySelectorAll(".aui-action-bar-more-item").length;
+ },
+ lastAssistantMessage(): HTMLElement | null {
+ const messages = document.querySelectorAll<HTMLElement>(
+ '[data-role="assistant"]',
+ );
+ return messages[messages.length - 1] ?? null;
+ },
+ /**
+ * The last assistant message's action-bar button with accessible name `label`.
+ * TooltipIconButton puts that name in an `sr-only` span rather than an aria-label, so
+ * this matches on text and stays correct if the styling classes are renamed.
+ */
+ actionButton(label: string): HTMLButtonElement | null {
+ const last = api.lastAssistantMessage();
+ if (!last) return null;
+ const buttons = Array.from(last.querySelectorAll("button"));
+ return (
+ buttons.find(
+ (button) => (button.textContent ?? "").trim() === label,
+ ) ?? null
+ );
+ },
+ };
+ (window as unknown as { __threadWeight: typeof api }).__threadWeight = api;
+ }, [aui, setThreadMounted]);
+
+ return null;
+}
+
+function Harness(): ReactElement {
+ const runtime = useLocalRuntime(NEVER_RUNS);
+ const [threadMounted, setThreadMounted] = useState(true);
+ return (
+ <TooltipProvider>
+ <AssistantRuntimeProvider runtime={runtime}>
+ <ThreadWeightApi setThreadMounted={setThreadMounted} />
+ {/* Thread is flex-1 basis-0 min-h-0, so it needs a bounded flex parent to scroll. */}
+ <div
+ data-smoke="thread"
+ style={{ display: "flex", flexDirection: "column", height: "100vh" }}
+ >
+ {threadMounted ? <Thread hideWelcome={true} /> : null}
+ </div>
+ </AssistantRuntimeProvider>
+ </TooltipProvider>
+ );
+}
+
+// Thread reaches useNavigate (the fork action, the composer tools menu). Without a router in
+// context tanstack's useRouter still works, but console.warns on every render of every action
+// bar: measured at 12 warnings for 10 assistant messages, which scales with N and is serialised
+// over CDP. A memory router with one route removes that without pulling in the app shell.
+const rootRoute = createRootRoute({ component: Harness });
+const router = createRouter({
+ routeTree: rootRoute,
+ history: createMemoryHistory({ initialEntries: ["/"] }),
+});
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("missing #root");
+}
+createRoot(root).render(<RouterProvider router={router as unknown as never} />);
diff --git a/studio/frontend/smoke-thread-weight.html b/studio/frontend/smoke-thread-weight.html
new file mode 100644
index 00000000000..3c33e87e000
--- /dev/null
+++ b/studio/frontend/smoke-thread-weight.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>thread weight smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-thread-weight-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 4d4a53af86f..2309852a00d 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -79,11 +79,7 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import {
- CHAT_HISTORY_UPDATED_EVENT,
- forkChatThread,
- getForkCount,
-} from "@/features/chat/api/chat-api";
+import { forkChatThread } from "@/features/chat/api/chat-api";
import {
findLatestUserAudioBase64,
resolveProjectId,
@@ -184,6 +180,8 @@ import {
type PromptQueueUIItemStatus,
type PromptQueueUIState,
usePromptQueueUI,
+ forkCountFor,
+ subscribeForkCounts,
type PlusMenuItemId,
usePlusMenuPrefsStore,
writeComposerDraft,
@@ -287,6 +285,7 @@ import {
type FC,
type KeyboardEvent,
type DragEvent as ReactDragEvent,
+ type FocusEvent as ReactFocusEvent,
type ReactNode,
type RefObject,
Fragment,
@@ -298,6 +297,7 @@ import {
useLayoutEffect,
useRef,
useState,
+ useSyncExternalStore,
} from "react";
import { extractTaggedText, updateThreadMessage } from "@/features/chat/utils/update-thread-message";
import { useComposerPillFit } from "@/hooks/use-composer-pill-fit";
@@ -1512,6 +1512,7 @@ export const Thread: FC<{
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const threadId = targetThreadId ?? activeThreadId ?? null;
const aui = useAui();
+ useThreadForkCounts();
// Measured height of the floating composer dock (null until measured).
// Drives the bottom spacer and the scroll-to-bottom footer offset.
@@ -6452,6 +6453,152 @@ const DiffusionCanvas: FC = () => {
);
};
+/**
+ * Mounts an autohidden action bar while focus is inside the message, the way hovering it does.
+ *
+ * `autohide="not-last"` UNMOUNTS every bar but the newest reply's, so Copy, Edit, Refresh,
+ * Delete, Read aloud and More leave the tab order on older messages and a keyboard or screen
+ * reader user has no way back: `:focus-within` in CSS cannot help, there is nothing to style.
+ * The reveal has to be JS, and it drives `message.setIsHovering`, the same flag the library's
+ * own `mouseenter`/`mouseleave` (MessagePrimitive.Root) writes and the only input to
+ * `useActionBarFloatStatus` besides the More menu's interaction lock. Reusing it rather than
+ * layering a second visibility source is what keeps the two from disagreeing.
+ *
+ * One flag, two writers, so the two clobber each other unless this hook covers both crossings:
+ * - pointer leaves while focus is inside (a Tab that scrolls the message under a parked
+ * cursor does exactly this): the library clears the flag, which would unmount the element
+ * that currently has focus. `reassert` below sets it back inside the same event.
+ * - focus leaves while the pointer is still over the message: clearing would unmount a bar
+ * the user is pointing at, and no second `mouseenter` is coming. The `:hover` test defers
+ * to the library's own `mouseleave` instead.
+ */
+function useActionBarFocusReveal() {
+ const aui = useAui();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const focusWithinRef = useRef(false);
+ const clearFrameRef = useRef<number | null>(null);
+
+ // The More menu is portaled OUTSIDE the message, so focus entering it looks like a blur.
+ // Its own interaction lock keeps the bar mounted meanwhile, but the trigger this hook has to
+ // hand focus back to lives in that bar, so a popup this message owns counts as engaged.
+ // Scoped to the action bar, NOT to every expanded descendant. Reasoning and tool cards are
+ // Radix CollapsibleTriggers and render aria-expanded="true" while open, which is the resting
+ // state of a message whose tool output the reader has expanded. An unscoped lookup treated
+ // those as an open popup, so `decide` rescheduled itself every frame for as long as the
+ // disclosure stayed open, held focusWithinRef and the synthetic hover set, and left the bar
+ // mounted: a per-frame DOM query per such message, which is the slowdown this branch removes.
+ const openPopupTrigger = useCallback(
+ () =>
+ rootRef.current?.querySelector(
+ '.aui-assistant-action-bar-root [aria-expanded="true"]',
+ ) ?? null,
+ [],
+ );
+
+ const isEngaged = useCallback(() => {
+ const el = rootRef.current;
+ if (!el) return false;
+ const active = document.activeElement;
+ if (active && el.contains(active)) return true;
+ return openPopupTrigger() !== null;
+ }, [openPopupTrigger]);
+
+ const cancelPendingClear = useCallback(() => {
+ if (clearFrameRef.current !== null) {
+ cancelAnimationFrame(clearFrameRef.current);
+ clearFrameRef.current = null;
+ }
+ }, []);
+
+ /**
+ * Decide, a frame from now, whether focus has really left, and keep asking until it has.
+ *
+ * Deferred rather than read off `relatedTarget`: that is null both for focus going to the
+ * browser chrome and for focus entering a portal, and it says nothing at all when the
+ * focused element is REMOVED, which is how a menu closes and which Chrome reports with no
+ * focusout event whatsoever. Reading `document.activeElement` a frame later answers all of
+ * them. Clearing late costs a frame of a mounted bar; clearing early destroys the element
+ * the user is on, so late is the safe direction.
+ */
+ const scheduleClear = useCallback(
+ (restart: boolean) => {
+ if (clearFrameRef.current !== null) {
+ if (!restart) return;
+ cancelAnimationFrame(clearFrameRef.current);
+ }
+ const decide = () => {
+ clearFrameRef.current = null;
+ const el = rootRef.current;
+ if (!el || !focusWithinRef.current) return;
+ const active = document.activeElement;
+ if (active && el.contains(active)) return;
+ if (openPopupTrigger()) {
+ // Focus is in this message's own portaled menu, whose interaction lock is holding
+ // the bar open anyway. Deciding now would be wrong and deciding never would pin the
+ // bar open for good, so ask again next frame; the loop lasts only as long as the
+ // menu is open on this one message.
+ clearFrameRef.current = requestAnimationFrame(decide);
+ return;
+ }
+ focusWithinRef.current = false;
+ if (!el.matches(":hover")) {
+ aui.message().setIsHovering(false);
+ }
+ };
+ clearFrameRef.current = requestAnimationFrame(decide);
+ },
+ [aui, openPopupTrigger],
+ );
+
+ // onFocus/onBlur on a container are focusin/focusout in React, so they give focus-within.
+ const handleFocus = useCallback(
+ (event: ReactFocusEvent<HTMLDivElement>) => {
+ const el = rootRef.current;
+ const target = event.target as Node | null;
+ if (el && target && !el.contains(target)) {
+ // React bubbles focus events out of PORTALS along the React tree, so this is this
+ // message's own menu, rendered into document.body. Focus is not in the subtree, so do
+ // not cancel the watchdog -- the menu will take focus with it when it unmounts, and
+ // that removal fires no focusout to wake us up again.
+ scheduleClear(false);
+ return;
+ }
+ cancelPendingClear();
+ if (focusWithinRef.current) return;
+ focusWithinRef.current = true;
+ aui.message().setIsHovering(true);
+ },
+ [aui, cancelPendingClear, scheduleClear],
+ );
+
+ const handleBlur = useCallback(() => {
+ if (!focusWithinRef.current) return;
+ scheduleClear(true);
+ }, [scheduleClear]);
+
+ useEffect(() => {
+ const el = rootRef.current;
+ if (!el) return;
+ // From an effect on purpose: MessagePrimitive.Root binds its own mouseleave from a ref
+ // callback, which commits before effects run, so this listener is registered second and
+ // runs second on the same element. Both writes land in one dispatch, the store settles on
+ // `true`, and React never renders the intermediate `false` -- so the bar does not unmount
+ // and the focused control is not destroyed under the user.
+ const reassert = () => {
+ if (focusWithinRef.current && isEngaged()) {
+ aui.message().setIsHovering(true);
+ }
+ };
+ el.addEventListener("mouseleave", reassert);
+ return () => {
+ el.removeEventListener("mouseleave", reassert);
+ cancelPendingClear();
+ };
+ }, [aui, isEngaged, cancelPendingClear]);
+
+ return { ref: rootRef, onFocus: handleFocus, onBlur: handleBlur };
+}
+
/**
* AssistantMessage handles the display and inline-editing of AI responses.
*
@@ -6461,6 +6608,7 @@ const DiffusionCanvas: FC = () => {
*/
const AssistantMessage: FC = () => {
const aui = useAui();
+ const focusReveal = useActionBarFocusReveal();
const messageId = useAuiState(({ message }) => message.id);
const messageContent = useAuiState(({ message }) => message.content);
const researchRunId = useAuiState(({ message }) => {
@@ -6531,6 +6679,20 @@ const AssistantMessage: FC = () => {
<MessagePrimitive.Root
className="group/assistant-message aui-assistant-message-root relative mx-auto min-w-0 w-full max-w-(--thread-content-max-width) pt-0.5 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]"
data-role="assistant"
+ // The message itself is the tab stop that lets the reveal below fire. Without it, a reply
+ // whose body is plain prose -- no link, no image, no code fence and so not even
+ // Streamdown's per-fence Copy button -- contains nothing focusable once `autohide` has
+ // unmounted its action bar, and Tab has no way into the message at all: Copy, Edit,
+ // Delete and More are unreachable for the whole thread except its newest reply.
+ // A tabIndex rather than a visually hidden button on purpose: it adds no DOM node (this
+ // PR exists to cut per-message weight) and it draws nothing at rest. The app's own
+ // `:focus-visible` rule in index.css gives it the same soft 1px keyboard indicator every
+ // other focusable container gets, and `:focus-visible` means a mouse click on a reply
+ // still draws nothing.
+ tabIndex={0}
+ ref={focusReveal.ref}
+ onFocus={focusReveal.onFocus}
+ onBlur={focusReveal.onBlur}
>
<div className="aui-assistant-message-content wrap-break-word min-w-0 text-[#0d0d0d] dark:text-foreground leading-relaxed">
{isEditing ? (
@@ -6590,41 +6752,75 @@ const AssistantMessage: FC = () => {
<BranchPicker className="mr-0.5" />
<AssistantActionBar />
</div>
+
+ {/*
+ The same reveal, for the other traversal direction.
+
+ The tabIndex on the root above only works going FORWARD. A container is reached before its
+ own descendants, so Shift+Tab arriving from the message below lands on the last tabbable
+ thing in this message -- and with the bar unmounted that is the root, which sits BEFORE
+ the bar in DOM order. Focusing it mounts the controls and then the next Shift+Tab steps
+ past them to the previous message, so Copy, Edit, Delete and More are reachable going
+ forward and unreachable going backward.
+
+ A sentinel AFTER the bar is what makes the backward pass land inside the message: focus
+ stops here, the bar mounts, and the next Shift+Tab goes into the last control rather than
+ out of the message. Deliberately not a focus redirect to that control, which would trap
+ the forward pass in a loop between the last button and this element.
+
+ A span with no content rather than a visually hidden button: it is one node with no text,
+ which matters in a PR whose point is per-message weight, and it draws nothing at rest for
+ the same :focus-visible reason as the root.
+
+ No onFocus/onBlur of its own: React's onFocus is focusin and bubbles, so focus landing
+ here already reaches the root's handler and mounts the bar. Duplicating them would run
+ the same handler twice per focus change for no effect. No role either -- it performs no
+ action, so labelling it as a button would misdescribe it; the aria-label is what stops it
+ being an unannounced stop for a screen reader.
+ */}
+ <span
+ className="aui-assistant-reveal-sentinel"
+ tabIndex={0}
+ aria-label="Message actions"
+ />
</MessagePrimitive.Root>
);
};
const COPY_RESET_MS = 2000;
+/**
+ * One fork-count subscription for as long as the thread is on screen.
+ *
+ * The badges below sit inside action bars that autohide, so at rest at most the newest reply
+ * has one, and none at all while the thread is running or while its last message is a prompt.
+ * Left to them, the last badge leaving would drop the thread's counts and the next hover would
+ * fetch them all again -- one whole-thread request per message the pointer crosses, with the
+ * badge arriving a round trip after the bar it sits in.
+ */
+const useThreadForkCounts = (): void => {
+ const remoteId =
+ useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? null;
+ useEffect(() => {
+ if (!remoteId) return;
+ return subscribeForkCounts(remoteId, () => {});
+ }, [remoteId]);
+};
+
const ForkCountBadge: FC = () => {
- const aui = useAui();
+ const remoteId =
+ useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? null;
const messageId = useAuiState(({ message }) => message.id);
- const [count, setCount] = useState(0);
-
- useEffect(() => {
- let cancelled = false;
- const refresh = () => {
- const remoteId = aui.threadListItem().getState().remoteId;
- if (!remoteId) {
- if (!cancelled) setCount(0);
- return;
- }
- void getForkCount(remoteId, messageId)
- .then((n) => {
- if (!cancelled) setCount(n);
- })
- .catch(() => {
- /* swallow: badge is non-critical */
- });
- };
- refresh();
- const handler = () => refresh();
- window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, handler);
- return () => {
- cancelled = true;
- window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, handler);
- };
- }, [aui, messageId]);
+ const subscribe = useCallback(
+ (onChange: () => void) =>
+ remoteId ? subscribeForkCounts(remoteId, onChange) : () => {},
+ [remoteId],
+ );
+ const getSnapshot = useCallback(
+ () => (remoteId ? forkCountFor(remoteId, messageId) : 0),
+ [remoteId, messageId],
+ );
+ const count = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
if (count <= 0) return null;
return (
@@ -6936,6 +7132,21 @@ const AssistantActionBar: FC = () => {
<>
<ActionBarPrimitive.Root
hideWhenRunning={!speaking}
+ // Unmounts the bar on every message that is not hovered, as the user bar already does.
+ // Mounted, each one holds ~8 tooltips subscribed to the global modal-layer store, so
+ // every menu open fanned out across the whole thread.
+ //
+ // "not-last", not "always": an unmounted bar is out of the tab order too, and these are
+ // the only Copy, Refresh, Read aloud and More controls a message has. The newest reply
+ // keeps its bar, so a keyboard user still reaches the message they are acting on, and
+ // the other N-1 still go: 8 tooltip subscriptions on a 500-message thread instead of
+ // ~250. "never" while speaking because this bar carries the only Stop reading control,
+ // which neither hover nor a later reply must take away.
+ //
+ // The older N-1 are deferred, not lost: useActionBarFocusReveal on the message root
+ // remounts a bar when focus enters that message, so tabbing brings back what hovering
+ // brings back and the controls return to the accessibility tree with it.
+ autohide={speaking ? "never" : "not-last"}
className="aui-assistant-action-bar-root col-start-3 row-start-2 flex items-center gap-1 text-chat-icon-fg [&_button:not([data-slot=message-timing-trigger])]:size-8 [&_button]:!rounded-full [&_button:hover]:bg-chat-icon-bg-hover [&_button:hover]:text-chat-icon-fg-hover"
>
<CopyButton />
@@ -6971,7 +7182,10 @@ const AssistantActionBar: FC = () => {
</TooltipIconButton>
</ActionBarPrimitive.StopSpeaking>
</MessagePrimitive.If>
- <ActionBarMorePrimitive.Root>
+ {/* Non-modal: a modal Radix menu writes `pointer-events: none` on <body>, and
+ that is an INHERITED property, so every open invalidates style for the whole
+ document. On a long thread that recalc is the bulk of the open+close cost. */}
+ <ActionBarMorePrimitive.Root modal={false}>
<ActionBarMorePrimitive.Trigger asChild={true}>
<TooltipIconButton
tooltip="More"
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 23fc26bef67..58f4fd06cf2 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -903,16 +903,18 @@ export async function forkChatThread(
return data;
}
-export async function getForkCount(
+/** Fork counts for a whole thread, keyed by message id. One request per thread, not per message. */
+export async function getThreadForkCounts(
threadId: string,
- messageId: string,
-): Promise<number> {
+): Promise<ReadonlyMap<string, number>> {
const response = await authFetch(
- `/api/chat/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}/forks`,
+ `/api/chat/threads/${encodeURIComponent(threadId)}/forks`,
);
- if (response.status === 404) return 0;
- const data = await parseJsonOrThrow<{ count: number }>(response);
- return data.count;
+ if (response.status === 404) return new Map();
+ const data = await parseJsonOrThrow<{ counts?: Record<string, number> }>(
+ response,
+ );
+ return new Map(Object.entries(data.counts ?? {}));
}
/** Thread ids whose sandbox still holds files, for a caller that never asked. */
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 03c5d054693..70cf8522c5d 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -210,6 +210,10 @@ export {
removeChatThreadTombstones,
} from "./utils/chat-thread-tombstones";
export { emitChatAttachmentDeleted } from "./utils/chat-attachment-events";
+export {
+ forkCountFor,
+ subscribeForkCounts,
+} from "./utils/fork-count-store";
export { resolveReasoningGroupDuration } from "./utils/reasoning-duration";
export {
reasoningAutoOpensWhileStreaming,
diff --git a/studio/frontend/src/features/chat/utils/delete-thread-message.ts b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
index 008d1ec9d0e..89ffeac11de 100644
--- a/studio/frontend/src/features/chat/utils/delete-thread-message.ts
+++ b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
@@ -29,22 +29,25 @@ import {
reconcileServerManagedMessages,
} from "./research-message-sync";
-function cloneContent(
+// A copy of the list, not of what is in it. assistant-ui replaces parts and attachments
+// rather than mutating them, and the records built from these are serialized straight
+// into the PUT body, so a deep clone of the whole thread bought nothing and cost more
+// than the request that follows it.
+function snapshotContent(
content: ThreadMessage["content"],
): ThreadMessage["content"] {
if (typeof content === "string") {
return content;
}
- return Array.isArray(content) ? JSON.parse(JSON.stringify(content)) : [];
+ return Array.isArray(content)
+ ? ([...content] as ThreadMessage["content"])
+ : [];
}
-function cloneAttachments(
+function snapshotAttachments(
attachments: readonly CompleteAttachment[] | undefined,
): readonly CompleteAttachment[] {
- if (!Array.isArray(attachments)) {
- return [];
- }
- return JSON.parse(JSON.stringify(attachments));
+ return Array.isArray(attachments) ? [...attachments] : [];
}
export function exportedItemToRecord(
@@ -52,9 +55,9 @@ export function exportedItemToRecord(
parentId: string | null,
message: ThreadMessage,
): MessageRecord {
- const content = cloneContent(message.content);
+ const content = snapshotContent(message.content);
if (message.role === "user") {
- const attachments = cloneAttachments(message.attachments);
+ const attachments = snapshotAttachments(message.attachments);
const custom = message.metadata?.custom;
return {
id: message.id,
@@ -89,6 +92,8 @@ async function withStoredResearchMessages(
if (!records.some((record) => hasResearchMetadata(record.metadata))) {
return records;
}
+ // The read below wants the row in place, which is the only reason this path ensures it.
+ await ensureStoredChatThread(remoteId);
// The backend copy, not the legacy-merged one: only what it stored can be echoed back to it.
// Swallowing a failure here would send the unreconciled payload, which the server rejects
// wholesale, so the read failure has to surface as itself rather than as a later 409.
@@ -109,7 +114,8 @@ export async function syncExportedRepositoryToBackend(
exp: ExportedMessageRepository,
options: { pruneMissing?: boolean } = {},
): Promise<void> {
- await ensureStoredChatThread(remoteId);
+ // No ensureStoredChatThread here: syncStoredChatMessages ensures the row itself, and
+ // this used to make every save pay for the same GET /threads/{id} twice.
const records = exp.messages.map(({ message, parentId }) =>
exportedItemToRecord(remoteId, parentId, message),
);
diff --git a/studio/frontend/src/features/chat/utils/fork-count-store.ts b/studio/frontend/src/features/chat/utils/fork-count-store.ts
new file mode 100644
index 00000000000..847d3079b48
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/fork-count-store.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * One fork-count subscription per rendered thread, shared by every message badge.
+ *
+ * The badge used to own a `CHAT_HISTORY_UPDATED_EVENT` listener and a request per
+ * message, so a 200-message thread spent 200 requests on every history event, and
+ * streaming raises one of those per chunk.
+ */
+import { CHAT_HISTORY_UPDATED_EVENT, getThreadForkCounts } from "../api/chat-api";
+
+// Same reasoning as the sidebar's refresh: each quiet window costs one fetch.
+export const FORK_COUNT_REFRESH_DEBOUNCE_MS = 300;
+
+// The ceiling on how long a real fork change can sit unrendered. A trailing edge alone is a
+// starvation hazard, not merely a slow path: CHAT_HISTORY_UPDATED_EVENT fires once per streaming
+// chunk, so a reply running in a background thread resets the timer forever and a fork deleted
+// from the sidebar keeps its old badge for as long as that reply runs, which on a queued or long
+// generation is minutes. The event is a bare Event with no detail and six other consumers, so
+// telling fork changes apart from chunks would mean changing a contract well outside this store;
+// bounding the wait fixes the same problem inside it.
+//
+// 2000 rather than something tighter because the cost of the bound is one whole-thread fetch per
+// window for as long as a stream runs. At 300ms that is the per-chunk traffic this store exists
+// to remove; at 2000 it is under a sixth of it, and it is paid only while something is actually
+// streaming.
+export const FORK_COUNT_REFRESH_MAX_WAIT_MS = 2000;
+
+type Counts = ReadonlyMap<string, number>;
+
+const EMPTY_COUNTS: Counts = new Map();
+
+type Entry = {
+ counts: Counts;
+ subscribers: Set<() => void>;
+ /** Discards a response overtaken by a later refresh of the same thread. */
+ seq: number;
+};
+
+const entries = new Map<string, Entry>();
+let pendingRefresh: ReturnType<typeof setTimeout> | null = null;
+// Started by the first event of a burst and NOT restarted by the ones after it. That is what
+// makes it a ceiling rather than a second debounce.
+let maxWaitTimer: ReturnType<typeof setTimeout> | null = null;
+let listening = false;
+
+async function refresh(threadId: string): Promise<void> {
+ const entry = entries.get(threadId);
+ if (!entry) return;
+ const seq = ++entry.seq;
+ let counts: Counts;
+ try {
+ counts = await getThreadForkCounts(threadId);
+ } catch {
+ return; // the badge is non-critical
+ }
+ if (entries.get(threadId) !== entry || entry.seq !== seq) return;
+ entry.counts = counts;
+ for (const notify of [...entry.subscribers]) notify();
+}
+
+function cancelTimers(): void {
+ if (pendingRefresh) {
+ clearTimeout(pendingRefresh);
+ pendingRefresh = null;
+ }
+ if (maxWaitTimer) {
+ clearTimeout(maxWaitTimer);
+ maxWaitTimer = null;
+ }
+}
+
+function runRefresh(): void {
+ // Both timers race for this; whichever loses must not fire afterwards.
+ cancelTimers();
+ for (const threadId of entries.keys()) void refresh(threadId);
+}
+
+function onHistoryUpdated(): void {
+ // Clear and reschedule, as the sidebar refresh does. Returning while a timer exists would
+ // make this a leading-edge throttle: streaming fires this event per chunk, so the timer
+ // would expire mid-stream and the next chunk would start another window, costing one
+ // whole-thread fetch every FORK_COUNT_REFRESH_DEBOUNCE_MS for as long as the reply runs.
+ // Fork counts cannot change during generation, so every one of those is wasted.
+ if (pendingRefresh) clearTimeout(pendingRefresh);
+ pendingRefresh = setTimeout(runRefresh, FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ // The bound. Deliberately not restarted while it is already running, or a per-chunk event
+ // stream would push it out exactly the way it pushes out the trailing edge, and the ceiling
+ // would not be a ceiling. Implemented as a second timer rather than a Date.now() deadline so
+ // it is driven by the same clock as the debounce and can be tested without a fake Date.
+ if (!maxWaitTimer) {
+ maxWaitTimer = setTimeout(runRefresh, FORK_COUNT_REFRESH_MAX_WAIT_MS);
+ }
+}
+
+/** Register a badge. The first subscriber of a thread pays for the fetch; the rest are free. */
+export function subscribeForkCounts(
+ threadId: string,
+ onChange: () => void,
+): () => void {
+ let entry = entries.get(threadId);
+ if (!entry) {
+ entry = { counts: EMPTY_COUNTS, subscribers: new Set(), seq: 0 };
+ entries.set(threadId, entry);
+ void refresh(threadId);
+ }
+ const owner = entry;
+ owner.subscribers.add(onChange);
+ if (!listening && typeof window !== "undefined") {
+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);
+ listening = true;
+ }
+ return () => {
+ owner.subscribers.delete(onChange);
+ if (owner.subscribers.size > 0 || entries.get(threadId) !== owner) return;
+ entries.delete(threadId);
+ if (entries.size === 0 && listening) {
+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);
+ listening = false;
+ cancelTimers();
+ }
+ };
+}
+
+/** The snapshot a `useSyncExternalStore` badge reads: a number, so identity never churns. */
+export function forkCountFor(threadId: string, messageId: string): number {
+ return entries.get(threadId)?.counts.get(messageId) ?? 0;
+}
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 1327fcf84b2..5d34f34b829 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -1003,6 +1003,28 @@ html[data-chat-font] .aui-root {
outline-offset: -1px;
}
+ /* The backward-traversal reveal sentinel in thread.tsx is a real tab stop, so it needs a
+ real focus indicator. The rule above is scoped to :where(div, main, ...) and never
+ matched a span, so focus visibly disappeared for one stop before the next Shift+Tab
+ reached the action bar, which is a focus-visible failure rather than a cosmetic one.
+
+ The element stays 0x0 and the ring is drawn by outline-offset. Outlines do not take part
+ in layout, so the indicator appears without shifting the message the way giving the span
+ dimensions on focus would. Nothing is drawn at rest, and :focus-visible means a mouse
+ click never draws it either. */
+ .aui-assistant-reveal-sentinel {
+ display: inline-block;
+ width: 0;
+ height: 0;
+ vertical-align: middle;
+ }
+
+ .aui-assistant-reveal-sentinel:focus-visible {
+ outline: 1px solid var(--ring-soft);
+ outline-offset: 6px;
+ border-radius: 2px;
+ }
+
/* Number fields use the shared grey stepper instead of native spinners. */
input[type="number"] {
appearance: textfield;
@@ -2521,10 +2543,17 @@ html[data-chat-font] .aui-root {
* that gates content-visibility flips rendered height between the
* 200px placeholder and the actual code-block height as the block
* sits near the viewport edge during stream finalization. The
- * height jump is small but visible, and the rendering optimization
- * is unnecessary for chat content (thread length is bounded). We
- * force `visible` to keep the rendered height of code blocks fully
- * determined by their actual content at all times.
+ * height jump is small but visible. We force `visible` to keep the
+ * rendered height of code blocks fully determined by their actual
+ * content at all times.
+ *
+ * This used to be justified by "thread length is bounded", which
+ * #8977 disproves. It is kept for the flicker alone. Do not reach
+ * back for `content-visibility: auto` here: WebKit below Safari 26
+ * cannot find skipped content with find-in-page (webkit.org/b/283846)
+ * and Studio has no in-thread search to fall back on. Containment on
+ * the message roots was measured as no help either; what grows with
+ * thread length is inherited-property style recalc, not layout.
*
* 2. `[data-sd-animate]` (`sd-fadeIn`, 150ms). Streamdown wraps each
* streaming text segment in a span carrying this attribute. When
diff --git a/studio/frontend/tests/action-menu-modal-layer.test.ts b/studio/frontend/tests/action-menu-modal-layer.test.ts
new file mode 100644
index 00000000000..3f9ed628450
--- /dev/null
+++ b/studio/frontend/tests/action-menu-modal-layer.test.ts
@@ -0,0 +1,102 @@
+// 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 message action menu must stay non-modal.
+ *
+ * Radix writes `pointer-events: none` onto <body> for a modal menu. That is an
+ * INHERITED property, so the write invalidates style for every element in the
+ * document, and the menu re-renders the thread's tooltips on the way back out.
+ * Measured on a 500-message thread at 4x CPU throttle, one open plus close:
+ *
+ * modal non-modal
+ * windows 42462ms 506ms
+ * ubuntu 31651ms 356ms
+ * macos 16505ms 231ms
+ *
+ * The cost is also flat in thread length afterwards (1.5x from 10 to 500
+ * messages, against 24x to 32x before), which is the property worth keeping.
+ *
+ * `modal={false}` is one word and reads like a stray prop, so it is pinned here
+ * rather than left to survive the next tidy-up.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import ts from "typescript";
+
+const THREAD = new URL(
+ "../src/components/assistant-ui/thread.tsx",
+ import.meta.url,
+);
+const source = ts.createSourceFile(
+ "thread.tsx",
+ readFileSync(THREAD, "utf8"),
+ ts.ScriptTarget.ESNext,
+ true,
+ ts.ScriptKind.TSX,
+);
+
+/** Every `<ActionBarMorePrimitive.Root ...>` in the file, opening element only. */
+const menuRoots = (): ts.JsxOpeningLikeElement[] => {
+ const found: ts.JsxOpeningLikeElement[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
+ node.tagName.getText() === "ActionBarMorePrimitive.Root"
+ ) {
+ found.push(node);
+ }
+ ts.forEachChild(node, visit);
+ };
+ ts.forEachChild(source, visit);
+ return found;
+};
+
+test("every message action menu is non-modal", () => {
+ const roots = menuRoots();
+ assert.ok(roots.length > 0, "no ActionBarMorePrimitive.Root in thread.tsx");
+
+ for (const root of roots) {
+ const modal = root.attributes.properties.find(
+ (p): p is ts.JsxAttribute =>
+ ts.isJsxAttribute(p) && p.name.getText() === "modal",
+ );
+ assert.ok(
+ modal,
+ "ActionBarMorePrimitive.Root has no modal prop; it defaults to modal, " +
+ "which puts the whole document on the modal layer on every open",
+ );
+ const value = modal.initializer;
+ assert.ok(
+ value &&
+ ts.isJsxExpression(value) &&
+ value.expression?.kind === ts.SyntaxKind.FalseKeyword,
+ "modal must be exactly {false}",
+ );
+ }
+});
+
+test("the prop reaches Radix rather than being swallowed by the wrapper", () => {
+ // ActionBarMorePrimitive.Root spreads ...rest onto Radix's DropdownMenu.Root,
+ // which is the only reason a prop it does not name has any effect. If the
+ // pinned version stops doing that, modal={false} silently becomes a no-op and
+ // the test above keeps passing.
+ const wrapper = new URL(
+ "../node_modules/@assistant-ui/react/dist/primitives/actionBarMore/ActionBarMoreRoot.js",
+ import.meta.url,
+ );
+ const text = readFileSync(wrapper, "utf8");
+ assert.match(
+ text,
+ /DropdownMenuPrimitive\.Root,\s*\{[^}]*\.\.\.rest/,
+ "ActionBarMorePrimitive.Root no longer forwards unknown props to Radix",
+ );
+ assert.doesNotMatch(
+ text,
+ /\bmodal\b/,
+ "the wrapper now names modal itself; check it still forwards false",
+ );
+});
diff --git a/studio/frontend/tests/delete-thread-message-cost.test.ts b/studio/frontend/tests/delete-thread-message-cost.test.ts
new file mode 100644
index 00000000000..6872fe1bd95
--- /dev/null
+++ b/studio/frontend/tests/delete-thread-message-cost.test.ts
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// #8977: deleting a message deep-cloned the whole thread with JSON.parse(JSON.stringify)
+// on its way to a PUT that serializes it again, and ensured the thread row twice. The
+// records are the same bytes on the wire either way, which is what these tests pin,
+// alongside the delete semantics that must not move: last message, first message, a
+// branch point, and a user prompt's cascaded replies.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { MessageRepository } from "@assistant-ui/core/internal";
+import * as researchSync from "../src/features/chat/utils/research-message-sync.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Exported = {
+ headId: string | null;
+ messages: { parentId: string | null; message: Record<string, unknown> }[];
+};
+
+type Module = {
+ exportedItemToRecord: (
+ threadId: string,
+ parentId: string | null,
+ message: unknown,
+ ) => Record<string, unknown>;
+ deleteThreadMessage: (args: {
+ thread: { export: () => Exported; import: (data: Exported) => void };
+ messageId: string;
+ remoteId: string | undefined;
+ }) => Promise<void>;
+};
+
+type Harness = {
+ module: Module;
+ calls: string[];
+ synced: { records: Record<string, unknown>[]; pruneMissing?: boolean }[];
+ stored: Record<string, unknown>[];
+};
+
+function harness(): Harness {
+ const calls: string[] = [];
+ const synced: Harness["synced"] = [];
+ const stored: Record<string, unknown>[] = [];
+ const module = loadWithStubs<Module>(
+ new URL(
+ "../src/features/chat/utils/delete-thread-message.ts",
+ import.meta.url,
+ ),
+ {
+ "@assistant-ui/core/internal": { MessageRepository },
+ "../api/chat-api": {
+ listChatMessages: async () => {
+ calls.push("listChatMessages");
+ return stored;
+ },
+ },
+ "./chat-history-storage": {
+ ensureStoredChatThread: async () => {
+ calls.push("ensureStoredChatThread");
+ },
+ syncStoredChatMessages: async (
+ _threadId: string,
+ records: Record<string, unknown>[],
+ options: { pruneMissing?: boolean },
+ ) => {
+ calls.push("syncStoredChatMessages");
+ synced.push({ records, pruneMissing: options?.pruneMissing });
+ return records;
+ },
+ },
+ "./research-message-sync": researchSync,
+ },
+ );
+ return { module, calls, synced, stored };
+}
+
+function message(
+ id: string,
+ role: "user" | "assistant",
+ extra: Record<string, unknown> = {},
+): Record<string, unknown> {
+ return {
+ id,
+ role,
+ content: [{ type: "text", text: `text of ${id}` }],
+ createdAt: new Date(1000),
+ status: { type: "complete", reason: "stop" },
+ ...extra,
+ };
+}
+
+/** A linear thread `u0 -> a0 -> u1 -> a1 -> ...`. */
+function linear(pairs: number): Exported {
+ const messages: Exported["messages"] = [];
+ let parentId: string | null = null;
+ for (let i = 0; i < pairs; i++) {
+ messages.push({ parentId, message: message(`u${i}`, "user") });
+ messages.push({ parentId: `u${i}`, message: message(`a${i}`, "assistant") });
+ parentId = `a${i}`;
+ }
+ return { headId: `a${pairs - 1}`, messages };
+}
+
+const idsOf = (exported: Exported): string[] =>
+ exported.messages.map(({ message }) => String(message.id));
+
+async function deleteFrom(
+ h: Harness,
+ exported: Exported,
+ messageId: string,
+): Promise<Exported> {
+ let imported: Exported | null = null;
+ await h.module.deleteThreadMessage({
+ thread: { export: () => exported, import: (data) => (imported = data) },
+ messageId,
+ remoteId: "remote-1",
+ });
+ assert.notEqual(imported, null, "the thread was never re-imported");
+ return imported as unknown as Exported;
+}
+
+test("records share the message's parts instead of deep-cloning the thread", async () => {
+ const h = harness();
+ const source = message("u0", "user", {
+ attachments: [{ id: "att-1", type: "file", name: "a.txt" }],
+ metadata: { custom: { modelId: "m" } },
+ });
+ const record = h.module.exportedItemToRecord("t", null, source);
+
+ const parts = record.content as unknown[];
+ const sourceParts = source.content as unknown[];
+ assert.equal(parts[0], sourceParts[0], "the parts were copied, not shared");
+ assert.notEqual(parts, sourceParts, "the list itself is still a snapshot");
+ const attachments = record.attachments as unknown[];
+ const sourceAttachments = source.attachments as unknown[];
+ assert.equal(attachments[0], sourceAttachments[0]);
+ assert.notEqual(attachments, sourceAttachments);
+
+ // What matters on the wire: the same bytes the deep clone used to produce.
+ const deepCloned = h.module.exportedItemToRecord(
+ "t",
+ null,
+ JSON.parse(JSON.stringify(source)) as unknown,
+ );
+ assert.equal(
+ JSON.stringify(record),
+ JSON.stringify({ ...deepCloned, createdAt: record.createdAt }),
+ );
+});
+
+test("a delete ensures the thread row once, not twice", async () => {
+ const h = harness();
+ await deleteFrom(h, linear(3), "u1");
+ // ensureStoredChatThread belongs to syncStoredChatMessages, which does it for every
+ // caller; doing it here as well cost a second GET /threads/{id} on every save.
+ assert.deepEqual(h.calls, ["syncStoredChatMessages"]);
+ assert.equal(h.synced[0].pruneMissing, true);
+});
+
+test("a research thread still reads its stored copy after the row is ensured", async () => {
+ const h = harness();
+ const exported = linear(2);
+ exported.messages[3].message.metadata = { custom: { researchRunId: "r1" } };
+ h.stored.push({
+ id: "a1",
+ threadId: "remote-1",
+ parentId: "u1",
+ role: "assistant",
+ content: [{ type: "text", text: "stored report" }],
+ metadata: { researchRunId: "r1" },
+ createdAt: 1000,
+ });
+
+ await deleteFrom(h, exported, "u0");
+ assert.deepEqual(h.calls, [
+ "ensureStoredChatThread",
+ "listChatMessages",
+ "syncStoredChatMessages",
+ ]);
+ const report = h.synced[0].records.find((r) => r.id === "a1");
+ assert.deepEqual(report?.content, [{ type: "text", text: "stored report" }]);
+});
+
+test("deleting the last message keeps the rest and moves the head", async () => {
+ const h = harness();
+ const next = await deleteFrom(h, linear(3), "a2");
+ assert.deepEqual(idsOf(next), ["u0", "a0", "u1", "a1", "u2"]);
+ assert.equal(next.headId, "u2");
+ assert.deepEqual(
+ h.synced[0].records.map((r) => r.id),
+ idsOf(next),
+ );
+});
+
+test("deleting the first message relinks its children to the root", async () => {
+ const h = harness();
+ const next = await deleteFrom(h, linear(2), "u0");
+ // The prompt's own assistant reply cascades with it; the rest reparents to the root.
+ assert.deepEqual(idsOf(next), ["u1", "a1"]);
+ assert.equal(next.messages[0].parentId, null);
+ assert.equal(next.headId, "a1");
+});
+
+test("deleting an assistant message relinks the turn that followed it", async () => {
+ const h = harness();
+ const next = await deleteFrom(h, linear(3), "a1");
+ assert.deepEqual(idsOf(next), ["u0", "a0", "u1", "u2", "a2"]);
+ assert.equal(
+ next.messages.find(({ message }) => message.id === "u2")?.parentId,
+ "u1",
+ );
+ assert.equal(next.headId, "a2");
+});
+
+/** `u0 -> a0 -> u1 -> {a1 -> u2, a1b}`: a regenerated turn, so u1 has two replies. */
+function branched(): Exported {
+ return {
+ headId: "u2",
+ messages: [
+ { parentId: null, message: message("u0", "user") },
+ { parentId: "u0", message: message("a0", "assistant") },
+ { parentId: "a0", message: message("u1", "user") },
+ { parentId: "u1", message: message("a1", "assistant") },
+ { parentId: "u1", message: message("a1b", "assistant") },
+ { parentId: "a1", message: message("u2", "user") },
+ ],
+ };
+}
+
+test("deleting one branch relinks its children and leaves the sibling", async () => {
+ const h = harness();
+ const next = await deleteFrom(h, branched(), "a1");
+ assert.deepEqual(idsOf(next).sort(), ["a0", "a1b", "u0", "u1", "u2"]);
+ assert.equal(
+ next.messages.find(({ message }) => message.id === "u2")?.parentId,
+ "u1",
+ "the surviving turn hangs off the deleted reply's parent",
+ );
+});
+
+test("deleting a branch point takes every reply branch with it", async () => {
+ const h = harness();
+ const next = await deleteFrom(h, branched(), "u1");
+ // A prompt's assistant replies cascade, so both branches go and u2 reparents.
+ assert.deepEqual(idsOf(next).sort(), ["a0", "u0", "u2"]);
+ assert.equal(
+ next.messages.find(({ message }) => message.id === "u2")?.parentId,
+ "a0",
+ );
+ assert.deepEqual(
+ h.synced[0].records.map((r) => r.id).sort(),
+ ["a0", "u0", "u2"],
+ );
+});
+
+test("an unsaved thread deletes locally without a sync", async () => {
+ const h = harness();
+ let imported: Exported | null = null;
+ await h.module.deleteThreadMessage({
+ thread: { export: () => linear(2), import: (data) => (imported = data) },
+ messageId: "a0",
+ remoteId: undefined,
+ });
+ assert.deepEqual(h.calls, []);
+ assert.deepEqual(idsOf(imported as unknown as Exported), ["u0", "u1", "a1"]);
+});
diff --git a/studio/frontend/tests/fork-count-batching.test.ts b/studio/frontend/tests/fork-count-batching.test.ts
new file mode 100644
index 00000000000..4d7f0eef103
--- /dev/null
+++ b/studio/frontend/tests/fork-count-batching.test.ts
@@ -0,0 +1,337 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// #8977: the chat got slower as the thread filled. The fork badge owned a
+// CHAT_HISTORY_UPDATED_EVENT listener and a request per message, so a delete on a
+// 200-message thread spent 200 requests before anything could repaint, and streaming
+// raises that event once per chunk. One shared subscription, one request per thread.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test, { mock } from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
+
+type Store = {
+ FORK_COUNT_REFRESH_DEBOUNCE_MS: number;
+ FORK_COUNT_REFRESH_MAX_WAIT_MS: number;
+ subscribeForkCounts: (threadId: string, onChange: () => void) => () => void;
+ forkCountFor: (threadId: string, messageId: string) => number;
+};
+
+const listeners = new Map<string, Set<() => void>>();
+Object.assign(globalThis, {
+ window: {
+ addEventListener(type: string, fn: () => void) {
+ const set = listeners.get(type) ?? new Set<() => void>();
+ set.add(fn);
+ listeners.set(type, set);
+ },
+ removeEventListener(type: string, fn: () => void) {
+ listeners.get(type)?.delete(fn);
+ },
+ },
+});
+
+function historyListenerCount(): number {
+ return listeners.get(CHAT_HISTORY_UPDATED_EVENT)?.size ?? 0;
+}
+
+function fireHistoryUpdated(): void {
+ for (const fn of [...(listeners.get(CHAT_HISTORY_UPDATED_EVENT) ?? [])]) fn();
+}
+
+/** A fresh module instance plus the request log its fetches write to. */
+function freshStore(counts: Record<string, number> = {}): {
+ store: Store;
+ requests: string[];
+} {
+ const requests: string[] = [];
+ const store = loadWithStubs<Store>(
+ new URL("../src/features/chat/utils/fork-count-store.ts", import.meta.url),
+ {
+ "../api/chat-api": {
+ CHAT_HISTORY_UPDATED_EVENT,
+ getThreadForkCounts: async (threadId: string) => {
+ requests.push(threadId);
+ return new Map(Object.entries(counts));
+ },
+ },
+ },
+ );
+ return { store, requests };
+}
+
+/** Let the awaited fetch inside the store settle. */
+async function flush(): Promise<void> {
+ for (let i = 0; i < 5; i++) await Promise.resolve();
+}
+
+test("a 200-message thread costs one request, not one per message", async () => {
+ const { store, requests } = freshStore({ m7: 3 });
+ const seen = new Array<number>(200).fill(0);
+ const unsubscribes = seen.map((_, i) =>
+ store.subscribeForkCounts("thread-a", () => {
+ seen[i] = store.forkCountFor("thread-a", "m7");
+ }),
+ );
+ await flush();
+
+ assert.deepEqual(requests, ["thread-a"]);
+ assert.equal(historyListenerCount(), 1);
+ // Every badge sees the count the single request brought back.
+ assert.equal(seen.every((count) => count === 3), true);
+ assert.equal(store.forkCountFor("thread-a", "m7"), 3);
+ assert.equal(store.forkCountFor("thread-a", "m8"), 0);
+
+ for (const unsubscribe of unsubscribes) unsubscribe();
+ assert.equal(historyListenerCount(), 0);
+});
+
+test("a burst of history events collapses into one refresh", async (t) => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const unsubscribes = Array.from({ length: 200 }, () =>
+ store.subscribeForkCounts("thread-a", () => {}),
+ );
+ await flush();
+ assert.equal(requests.length, 1);
+
+ // What one delete looks like: the sync PUT and every follow-up notify.
+ for (let i = 0; i < 20; i++) fireHistoryUpdated();
+ assert.equal(requests.length, 1, "nothing fires before the debounce window");
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.equal(requests.length, 2);
+
+ fireHistoryUpdated();
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.equal(requests.length, 3, "a later window still refreshes");
+
+ for (const unsubscribe of unsubscribes) unsubscribe();
+ fireHistoryUpdated();
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.equal(requests.length, 3, "an unmounted thread stops fetching");
+});
+
+test("badges churning under the hover autohide do not refetch the thread", async () => {
+ const { store, requests } = freshStore({ m7: 3 });
+ // The thread subscribes for as long as it is on screen. Its badges live inside action bars
+ // that autohide, so they come and go with the pointer and at rest at most one is left.
+ const thread = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+ assert.deepEqual(requests, ["thread-a"]);
+
+ for (let i = 0; i < 10; i++) {
+ const badge = store.subscribeForkCounts("thread-a", () => {});
+ // Already there on the first render, so the badge does not arrive a round trip after the
+ // bar it sits in and shift the buttons beside it.
+ assert.equal(store.forkCountFor("thread-a", "m7"), 3);
+ badge();
+ }
+ await flush();
+ assert.equal(requests.length, 1, "hovering ten messages refetched the whole thread");
+
+ // Closing the thread is what drops the counts.
+ thread();
+ assert.equal(store.forkCountFor("thread-a", "m7"), 0);
+});
+
+test("two threads on screen cost one request each", async () => {
+ const { store, requests } = freshStore();
+ const a = store.subscribeForkCounts("thread-a", () => {});
+ const b = store.subscribeForkCounts("thread-b", () => {});
+ await flush();
+ assert.deepEqual(requests, ["thread-a", "thread-b"]);
+ a();
+ b();
+});
+
+test("the badge no longer owns a listener or a per-message request", () => {
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(thread, /getForkCount\(/);
+ assert.doesNotMatch(thread, /addEventListener\(CHAT_HISTORY_UPDATED_EVENT/);
+ assert.match(thread, /subscribeForkCounts\(remoteId, onChange\)/);
+ // The badges all unmount at rest, so the thread has to hold the subscription itself.
+ assert.match(thread, /const useThreadForkCounts[\s\S]*?subscribeForkCounts\(remoteId,/);
+ assert.match(thread, /^ {2}useThreadForkCounts\(\);$/m);
+});
+
+test("a continuous stream costs one refresh per ceiling, not one per debounce window", async (t) => {
+ // The burst case above fires every event inside a single window, where a leading-edge
+ // throttle and a trailing-edge debounce are indistinguishable. Streaming is the case that
+ // separates them: the event arrives per chunk, so chunks keep landing after the window has
+ // already expired. A throttle re-arms and fetches again, once per debounce window, for as long
+ // as the reply runs.
+ //
+ // This used to assert ZERO mid-stream fetches. That was the #8992 review finding: a pure
+ // trailing edge never expires under a stream, so a fork deleted from the sidebar kept a stale
+ // badge until the unrelated reply finished. FORK_COUNT_REFRESH_MAX_WAIT_MS bounds that, and
+ // the price of the bound is what this test now measures, so it is a number in the suite rather
+ // than a claim in a comment.
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const unsubscribe = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+ assert.equal(requests.length, 1, "the initial subscribe fetches once");
+
+ const gap = Math.floor(store.FORK_COUNT_REFRESH_DEBOUNCE_MS / 2);
+ const chunks = 20;
+ for (let chunk = 0; chunk < chunks; chunk++) {
+ fireHistoryUpdated();
+ mock.timers.tick(gap);
+ await flush();
+ }
+ const streamMs = chunks * gap;
+ const midStream = requests.length - 1;
+ const throttleWould = Math.floor(streamMs / store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ const ceilingAllows = Math.floor(streamMs / store.FORK_COUNT_REFRESH_MAX_WAIT_MS);
+ assert.equal(
+ midStream,
+ ceilingAllows,
+ `a ${chunks} chunk stream over ${streamMs}ms refetched ${midStream} time(s) mid-stream; ` +
+ `the ceiling allows ${ceilingAllows}`,
+ );
+ assert.ok(
+ midStream < throttleWould,
+ `the per-chunk traffic is back: ${midStream} fetches against the ${throttleWould} a ` +
+ "leading-edge throttle would have cost",
+ );
+
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.equal(
+ requests.length,
+ 2 + ceilingAllows,
+ "the quiet window after the stream refreshes exactly once",
+ );
+
+ unsubscribe();
+});
+
+// #8992 review: a trailing edge alone starves. CHAT_HISTORY_UPDATED_EVENT fires once per
+// streaming chunk, so a reply running in a background thread resets the debounce forever. A fork
+// deleted from the sidebar changes the badge on the thread the user is looking at, and without a
+// ceiling that badge stays wrong until the unrelated stream goes quiet, which on a long or queued
+// generation is minutes.
+
+test("a chunk every debounce window cannot postpone a refresh forever", async (t) => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const unsubscribe = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+ assert.equal(requests.length, 1, "the initial fetch");
+
+ // A stream chunking just inside the debounce window, which is what resets the trailing edge.
+ const step = store.FORK_COUNT_REFRESH_DEBOUNCE_MS - 1;
+ const ticks = Math.ceil(store.FORK_COUNT_REFRESH_MAX_WAIT_MS / step) + 1;
+ let firedAfter: number | null = null;
+ for (let i = 0; i < ticks; i++) {
+ fireHistoryUpdated();
+ mock.timers.tick(step);
+ await flush();
+ if (requests.length > 1) {
+ firedAfter = (i + 1) * step;
+ break;
+ }
+ }
+ assert.notEqual(
+ firedAfter,
+ null,
+ "the refresh never happened: a chunk per window postponed it indefinitely",
+ );
+ assert.ok(
+ (firedAfter as number) <= store.FORK_COUNT_REFRESH_MAX_WAIT_MS + step,
+ `the refresh waited ${firedAfter}ms, past the ${store.FORK_COUNT_REFRESH_MAX_WAIT_MS}ms bound`,
+ );
+ unsubscribe();
+});
+
+test("the ceiling does not fire while the burst is still inside the debounce window", async (t) => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const unsubscribe = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+ assert.equal(requests.length, 1);
+
+ // The ordinary case must still collapse to ONE refresh on the trailing edge. If the max-wait
+ // timer were left running after the debounce fired, this would fetch a second time later.
+ for (let i = 0; i < 20; i++) fireHistoryUpdated();
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.equal(requests.length, 2, "the trailing edge refreshes once");
+ mock.timers.tick(store.FORK_COUNT_REFRESH_MAX_WAIT_MS * 2);
+ await flush();
+ assert.equal(
+ requests.length,
+ 2,
+ "the max-wait timer fired again after the debounce had already refreshed",
+ );
+ unsubscribe();
+});
+
+test("the ceiling restarts for the next burst rather than firing once per lifetime", async (t) => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const unsubscribe = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+
+ for (let round = 0; round < 2; round++) {
+ const step = store.FORK_COUNT_REFRESH_DEBOUNCE_MS - 1;
+ const before = requests.length;
+ const ticks = Math.ceil(store.FORK_COUNT_REFRESH_MAX_WAIT_MS / step) + 1;
+ for (let i = 0; i < ticks && requests.length === before; i++) {
+ fireHistoryUpdated();
+ mock.timers.tick(step);
+ await flush();
+ }
+ assert.equal(
+ requests.length,
+ before + 1,
+ `round ${round + 1}: the bound did not apply, so it is a one-shot rather than a ceiling`,
+ );
+ }
+ unsubscribe();
+});
+
+test("unsubscribing cancels the ceiling as well as the trailing edge", async (t) => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore();
+ const first = store.subscribeForkCounts("thread-a", () => {});
+ await flush();
+ assert.equal(requests.length, 1);
+
+ // Unsubscribing with the ceiling armed. Asserting "no fetch happens" here would prove nothing:
+ // the entries map is empty by then, so a leaked timer fires runRefresh over nothing and the
+ // request log looks identical either way. The leak is only observable once a LATER thread is
+ // on screen for the stale timer to refresh, which is also the case that actually costs a user
+ // a request: open a thread, close it, open another inside the ceiling window.
+ fireHistoryUpdated();
+ first();
+
+ const second = store.subscribeForkCounts("thread-b", () => {});
+ await flush();
+ assert.deepEqual(requests, ["thread-a", "thread-b"], "the new thread fetches once on subscribe");
+
+ mock.timers.tick(store.FORK_COUNT_REFRESH_MAX_WAIT_MS * 2);
+ await flush();
+ assert.deepEqual(
+ requests,
+ ["thread-a", "thread-b"],
+ "a ceiling armed by the previous thread outlived it and refetched the new one",
+ );
+ second();
+});
diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.json
index b9521f0efe5..732dc02ef2b 100644
--- a/studio/frontend/tsconfig.app.json
+++ b/studio/frontend/tsconfig.app.json
@@ -34,6 +34,7 @@
"smoke-autoscroll-main.tsx",
"smoke-research-main.tsx",
"smoke-heavy-thread-main.tsx",
+ "smoke-thread-weight-main.tsx",
"smoke-settings-main.tsx",
"smoke-stream-pacing-main.tsx"
]
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index 5143827f98f..cee0d64f1cb 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -1267,6 +1267,32 @@ with sync_playwright() as p:
f"{state['intercepted']})"
)
+ # Settle before the five-turn sequence below: two bubbles, nothing streaming,
+ # nothing queued. That is the whole job of this wait. What the turns SAID is
+ # not checked here and never was; the queue behaviour this step exists to
+ # prove is `state.queueSeen` above.
+ #
+ # This used to also require every reply's innerText to be non-empty, which
+ # measured the action bar, not the reply. innerText of a message root spans
+ # the whole subtree, and the assistant action bar sits inside it, so the
+ # clause was satisfied by button labels ("Copy Edit response Refresh Delete
+ # message Read aloud More" plus the tok/s readout) whatever the model
+ # returned. Instrumented at this exact point on the CI runners, comparing the
+ # message content element against the message root, two passing runs read:
+ #
+ # content=[0, 0] innerText=[73, 73] -> clause held, both replies empty
+ # content=[0, 19] innerText=[73, 89] -> clause held, first reply empty
+ #
+ # gemma-3-270m-it answers "Reply with exactly: rapid-first" with an empty
+ # completion often enough to appear in 3 of 8 sampled runs, and the clause
+ # held anyway every time, so it never had the coverage its wording implies.
+ # A content-based replacement would be flakier than what it replaces, because
+ # an empty completion is the model's behaviour, not a defect in Studio.
+ #
+ # It matters now because the assistant action bar autohides on every reply but
+ # the newest, so for the older of the two this reads, the labels are no longer in
+ # the subtree and the clause finally started reporting what it was actually
+ # measuring: a hidden hover affordance.
page.wait_for_function(
"""(want) => {
const replies = Array.from(
@@ -1274,7 +1300,6 @@ with sync_playwright() as p:
).slice(-2);
return replies.length === 2 &&
document.querySelectorAll('[data-role="assistant"]').length >= want &&
- replies.every((reply) => (reply.innerText || '').trim().length > 0) &&
!document.querySelector('button[aria-label="Stop generating"]') &&
!document.querySelector('button[aria-label="Remove queued prompt 1"]');
}""",
diff --git a/tests/studio/playwright_thread_weight.py b/tests/studio/playwright_thread_weight.py
new file mode 100644
index 00000000000..9ba28dcb7e7
--- /dev/null
+++ b/tests/studio/playwright_thread_weight.py
@@ -0,0 +1,879 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""How the chat thread's interaction cost grows with the number of messages (#8977).
+
+Studio's chat UI is reported as sluggish on Windows 11 and worsening as the thread fills:
+opening menus, scrolling, deleting and typing all lag while token generation is unaffected.
+That shape says the cost is per-message renderer work, so the thing to measure is not a single
+absolute number but a curve: the same four interactions repeated at N in {10, 50, 200, 500}.
+
+Four scripted actions per N, under 6x CDP CPU throttling, against the real Thread mounted by
+studio/frontend/smoke-thread-weight.html:
+
+ keystroke - one character into the composer, measured to the frame that paints it.
+ scroll - one scroll gesture up through the thread; long-task ms is the lag a user feels.
+ menu - one message action menu opened and closed, the Radix modal-layer fan-out.
+ delete - one message deleted, the export / rebuild / import round trip.
+
+Each action is bracketed by CDP `Performance.getMetrics`, so LayoutCount, RecalcStyleCount,
+LayoutDuration, RecalcStyleDuration and TaskDuration separate the two families of cost: work
+that grows because layout is uncontained shows up in LayoutDuration and LayoutCount, while work
+that grows because a listener or an export is O(messages) shows up in TaskDuration alone.
+
+THIS HARNESS MEASURES, IT DOES NOT GATE. It prints the per-N table and exits 0 unless the
+harness itself broke -- the page failed to seed, an element it drives went missing, or every N
+produced the same number, which would mean it is measuring nothing. There are deliberately no
+performance budgets here. Budgets belong in a later change, set from real numbers taken on real
+hardware; a budget invented from one Linux CI run would either never fire or fire on noise.
+
+Chromium only for the numbers. `Emulation.setCPUThrottlingRate`, `Performance.getMetrics` and
+the `longtask` PerformanceObserver entry type are all Chromium features, so running this file
+under Firefox or WebKit would exercise the page as a correctness check and report no meaningful
+performance at all. The desktop app embeds WebKitGTK, not Chromium, so what transfers from these
+numbers is the shape of the curve, not the absolute milliseconds.
+
+Unlike playwright_chat_autoscroll.py this does NOT replace requestAnimationFrame with a fixed
+timer. That harness counts frames, where a deterministic pump is the point; this one measures
+time to paint, which a fake rAF would silently destroy. rAF is wrapped to count real callbacks
+and otherwise left alone; the harness's own waits use the unwrapped rAF, so __rafCount stays a
+count of the page's frames rather than of this file's.
+
+Read the timings against `paint_floor_ms`, which is printed per N. Anything clocked across a
+double rAF cannot resolve faster than two vsync intervals, measured at ~33ms here and unmoved by
+CPU throttling. An action that never happened therefore still reports ~33ms, which reads as a
+plausible measurement rather than as a failure, so the floor is subtracted before any growth
+ratio and the guards below reject a keystroke at or under it.
+
+Run:
+ python tests/studio/playwright_thread_weight.py
+ SMOKE_THREAD_SIZES=10,50 python tests/studio/playwright_thread_weight.py
+
+It starts and stops its own vite dev server. Point it at one you already have with
+SMOKE_BASE_URL, or move the port it picks with SMOKE_PORT.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+ wait_for_smoke_page,
+)
+
+PORT = int(os.environ.get("SMOKE_PORT", "5213"))
+# Unset: start and stop our own server. Set: drive that one and leave it running.
+# Exported-but-empty counts as unset, else we skip the server and drive "" as the URL.
+# rstrip("/"): a trailing slash would make the anchored /api/ route regex below never match,
+# silently turning the stubbed fork-count fan-out back into live HTTP.
+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")
+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"
+OWNS_SERVER = not _EXTERNAL
+LABEL = os.environ.get("SMOKE_LABEL", "tree")
+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-thread-weight"))
+OUT.mkdir(parents = True, exist_ok = True)
+
+# Sorted: the growth check reads the first and last entries as smallest and largest, so an
+# unsorted override would invert every ratio and report a good run as measuring nothing.
+SIZES = sorted(int(n) for n in os.environ.get("SMOKE_THREAD_SIZES", "10,50,200,500").split(","))
+# 6x is the Lighthouse mobile default and roughly the gap between this machine and the reported
+# one under load. Absolute ms are not comparable across machines; the curve is.
+CPU_THROTTLE_RATE = float(os.environ.get("SMOKE_CPU_THROTTLE", "6"))
+# Keystrokes are noisy at this timescale, so type several and report the median.
+KEYSTROKES = int(os.environ.get("SMOKE_KEYSTROKES", "5"))
+SCROLL_STEPS = int(os.environ.get("SMOKE_SCROLL_STEPS", "20"))
+SCROLL_STEP_PX = int(os.environ.get("SMOKE_SCROLL_STEP_PX", "400"))
+# 500 uncontained messages under 6x throttling are slow by construction; these bound a wedge,
+# not a regression.
+SEED_TIMEOUT_MS = int(os.environ.get("SMOKE_SEED_TIMEOUT_MS", "180000"))
+ACTION_TIMEOUT_MS = int(os.environ.get("SMOKE_ACTION_TIMEOUT_MS", "60000"))
+# How long an in-page action waits for the DOM to reach the state it asked for. This bounds an
+# action that never happened, and nothing else: it must stay well above the slowest honest
+# measurement or the harness reports "never opened" for what is really just a very slow open.
+# Measured on this tree, opening the action menu at N=500 under 6x takes around 25s.
+SETTLE_TIMEOUT_MS = int(os.environ.get("SMOKE_SETTLE_TIMEOUT_MS", "90000"))
+
+OBSERVER_INIT = """
+(() => {
+ window.__longTasks = [];
+ try {
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ window.__longTasks.push({ start: entry.startTime, duration: entry.duration });
+ }
+ }).observe({ type: "longtask", buffered: true });
+ } catch (e) { /* longtask is Chromium-only: the CDP metrics still apply */ }
+ // Counting wrapper, not a pump. Replacing rAF with a timer would flatten every
+ // time-to-paint number this harness exists to read.
+ window.__rafCount = 0;
+ const nativeRaf = window.requestAnimationFrame.bind(window);
+ window.requestAnimationFrame = (cb) =>
+ nativeRaf((t) => {
+ window.__rafCount += 1;
+ cb(t);
+ });
+ window.__nextPaint = () =>
+ new Promise((resolve) => nativeRaf(() => nativeRaf(() => resolve())));
+})();
+"""
+
+
+def info(message: str) -> None:
+ print(f"[thread-weight] {message}", flush = True)
+
+
+def metrics(cdp) -> dict[str, float]:
+ got = cdp.send("Performance.getMetrics")
+ return {m["name"]: m["value"] for m in got["metrics"]}
+
+
+def delta(before: dict[str, float], after: dict[str, float], name: str) -> float:
+ return round(after.get(name, 0.0) - before.get(name, 0.0), 4)
+
+
+def counters(before: dict[str, float], after: dict[str, float]) -> dict[str, float]:
+ return {
+ "layout_count": delta(before, after, "LayoutCount"),
+ "recalc_style_count": delta(before, after, "RecalcStyleCount"),
+ "layout_ms": round(delta(before, after, "LayoutDuration") * 1000, 1),
+ "recalc_style_ms": round(delta(before, after, "RecalcStyleDuration") * 1000, 1),
+ "task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),
+ }
+
+
+def long_task_summary(page) -> dict[str, float]:
+ # PerformanceObserver callbacks are delivered on a later task, so the entry for the long
+ # task at the tail of an action is not in the array yet. Yield once before reading, or the
+ # worst entry is silently dropped -- flakily, and most often at large N where that tail
+ # task is longest.
+ tasks = page.evaluate(
+ "async () => { await new Promise((r) => setTimeout(r, 0)); return window.__longTasks; }"
+ )
+ return {
+ "long_tasks": len(tasks),
+ "long_task_ms": round(sum(t["duration"] for t in tasks), 1),
+ "worst_long_task_ms": round(max((t["duration"] for t in tasks), default = 0.0), 1),
+ }
+
+
+# One character through the native value setter plus an input event: what the browser leaves
+# behind after a real keypress, and what React's controlled textarea and react-textarea-autosize
+# both react to. Resolved on the second rAF, which is the frame that has painted it.
+KEYSTROKE_JS = """
+async (count) => {
+ const api = window.__threadWeight;
+ const input = api.composer();
+ if (!input) return null;
+ input.focus();
+ const setValue = Object.getOwnPropertyDescriptor(
+ HTMLTextAreaElement.prototype, "value",
+ ).set;
+ const samples = [];
+ for (let i = 0; i < count; i += 1) {
+ await window.__nextPaint();
+ const started = performance.now();
+ setValue.call(input, input.value + "a");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await window.__nextPaint();
+ samples.push(performance.now() - started);
+ }
+ // domText is what the harness itself wrote; runtimeText is what the runtime received. Only
+ // the second can tell you the keystroke reached React rather than just the DOM node.
+ return {
+ samples,
+ domText: input.value,
+ runtimeText: api.composerText(),
+ };
+}
+"""
+
+SCROLL_JS = """
+async ([steps, stepPx]) => {
+ const api = window.__threadWeight;
+ const viewport = api.viewport();
+ if (!viewport) return null;
+ // The viewport carries `scroll-smooth`, so each scrollTop write starts an animation and the
+ // next read lands mid-flight. Stepping from a tracked target with an explicit instant
+ // behaviour is what a wheel gesture actually does, and it is the only way the gesture moves
+ // the distance it asks for.
+ const bottom = viewport.scrollHeight - viewport.clientHeight;
+ viewport.scrollTo({ top: bottom, behavior: "instant" });
+ await window.__nextPaint();
+ let target = viewport.scrollTop;
+ // Reverse at either end rather than stopping. A short thread runs out of travel long before
+ // a long one does, and a gesture that covers 2600px at N=10 and 8000px at N=500 is not the
+ // same gesture, so the two columns would not be comparable.
+ let direction = -1;
+ let travelled = 0;
+ let worstFrameMs = 0;
+ const started = performance.now();
+ for (let i = 0; i < steps; i += 1) {
+ if (direction < 0 && target <= 0) direction = 1;
+ else if (direction > 0 && target >= bottom) direction = -1;
+ const next = Math.min(bottom, Math.max(0, target + direction * stepPx));
+ const frameStarted = performance.now();
+ // The wheel event is what the app's own scroll listeners key off; the scrollTo is what
+ // moves the viewport in a headless run with no compositor input.
+ viewport.dispatchEvent(
+ new WheelEvent("wheel", {
+ deltaY: direction * stepPx, bubbles: true, cancelable: true,
+ }),
+ );
+ viewport.scrollTo({ top: next, behavior: "instant" });
+ await window.__nextPaint();
+ worstFrameMs = Math.max(worstFrameMs, performance.now() - frameStarted);
+ travelled += Math.abs(next - target);
+ target = next;
+ }
+ return {
+ wallMs: performance.now() - started,
+ scrolledPx: travelled,
+ worstFrameMs,
+ frames: steps,
+ };
+}
+"""
+
+# Radix portals the menu to document.body and puts the body on the modal layer, which is the
+# fan-out the issue blames. bodyPointerEvents proves the open really took that path.
+#
+# The trigger opens on `pointerdown`, not on `click`: an element.click() leaves the menu shut and
+# the whole measurement silently reads zero. Hence the pointer pair.
+MENU_JS = """
+async (timeoutMs) => {
+ const api = window.__threadWeight;
+ const trigger = api.actionButton("More");
+ if (!trigger) return null;
+ // A MutationObserver flag, not a querySelector per frame. The menu content is portaled to the
+ // end of document.body, so polling for it walks the whole message list and finds nothing for
+ // the entire open latency -- an O(messages) cost charged to the action, growing like the
+ // signal it is measuring.
+ let open = Boolean(document.querySelector(".aui-action-bar-more-content"));
+ const watcher = new MutationObserver(() => {
+ open = Boolean(document.querySelector(".aui-action-bar-more-content"));
+ });
+ watcher.observe(document.body, { childList: true, subtree: false });
+ const settle = async (want) => {
+ const started = performance.now();
+ while (performance.now() - started < timeoutMs) {
+ if (open === want) return performance.now() - started;
+ await window.__nextPaint();
+ }
+ return null;
+ };
+ const pointer = {
+ bubbles: true, cancelable: true, composed: true,
+ button: 0, pointerId: 1, pointerType: "mouse", isPrimary: true,
+ };
+ const openStarted = performance.now();
+ trigger.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, buttons: 1 }));
+ trigger.dispatchEvent(new PointerEvent("pointerup", { ...pointer, buttons: 0 }));
+ const opened = await settle(true);
+ const openMs = opened === null ? null : performance.now() - openStarted;
+ const bodyPointerEvents = getComputedStyle(document.body).pointerEvents;
+ const itemsWhileOpen = api.openMenuItemCount();
+ // Counted here, under the pointer, not in the resting-state census. An autohidden bar is
+ // absent at rest by design; one that never mounts at all is a broken page, and only a
+ // hovered count tells the two apart.
+ const triggersWhileHovered = document.querySelectorAll('[data-slot="tooltip-trigger"]').length;
+ // The clock starts BEFORE the dispatch. Radix dismisses synchronously inside it -- layer
+ // teardown, focus restore, the body coming off the modal layer and the re-render that
+ // follows -- which is the O(messages) fan-out being measured. Starting it after the dispatch
+ // excluded exactly the part worth timing.
+ const closeStarted = performance.now();
+ document.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),
+ );
+ const closed = await settle(false);
+ const result = {
+ openMs,
+ closeMs: closed === null ? null : performance.now() - closeStarted,
+ bodyPointerEvents,
+ bodyPointerEventsAfterClose: getComputedStyle(document.body).pointerEvents,
+ itemsWhileOpen,
+ triggersWhileHovered,
+ };
+ watcher.disconnect();
+ return result;
+}
+"""
+
+DELETE_JS = """
+async (timeoutMs) => {
+ const api = window.__threadWeight;
+ const button = api.actionButton("Delete message");
+ if (!button) return null;
+ // The last assistant message. That is the cheapest delete on the React side -- one subtree
+ // unmounts -- so this column under-measures reconciliation, though the export/rebuild/import
+ // half is O(messages) wherever the target sits.
+ const target = api.lastAssistantMessage();
+ const before = api.messageCount();
+ const started = performance.now();
+ button.click();
+ // isConnected on the captured node is O(1). Re-counting [data-role] every frame would put an
+ // O(messages) query inside the window being timed, growing like the signal.
+ while (performance.now() - started < timeoutMs) {
+ if (target === null || !target.isConnected) {
+ return { ms: performance.now() - started, before, after: api.messageCount() };
+ }
+ await window.__nextPaint();
+ }
+ return { ms: null, before, after: api.messageCount() };
+}
+"""
+
+# The floor under every timing here: two rAFs resolve no sooner than two vsync intervals.
+# Measured at 33.3ms on this machine and unmoved by CPU throttling, so an action that never
+# happened still reports ~33ms, which reads as a plausible number rather than as a failure.
+# Recorded per N and subtracted before any growth ratio is taken.
+PAINT_FLOOR_JS = """
+async (samples) => {
+ const values = [];
+ for (let i = 0; i < samples; i += 1) {
+ await window.__nextPaint();
+ const started = performance.now();
+ await window.__nextPaint();
+ values.push(performance.now() - started);
+ }
+ values.sort((a, b) => a - b);
+ return values[Math.floor(values.length / 2)];
+}
+"""
+
+
+def median(values: list[float]) -> float:
+ ordered = sorted(values)
+ middle = len(ordered) // 2
+ if not ordered:
+ return -1.0
+ if len(ordered) % 2:
+ return ordered[middle]
+ return (ordered[middle - 1] + ordered[middle]) / 2
+
+
+def reset_long_tasks(page) -> None:
+ page.evaluate("window.__longTasks.length = 0")
+
+
+def measure_one(context, cdp_throttle_rate: float, size: int) -> dict:
+ """Seed a fresh page to `size` messages and run the four actions on it."""
+ page = context.new_page()
+ result: dict = {"messages_requested": size}
+ # A request that escapes to the server, or a warning storm, is work this harness would be
+ # charging to the app, once per message. Both are cleared after seeding, so what is asserted
+ # on is the four measured actions rather than page load.
+ #
+ # startswith, not `"/api/" in url`: vite serves the app's own source modules from paths like
+ # /src/features/chat/api/chat-api.ts, and a substring match counts 45 of those as network
+ # calls. Same trap the API route regex below is anchored to avoid.
+ api_prefix = f"{BASE}/api/"
+ stray_requests: list[str] = []
+ console_warnings: list[str] = []
+ page.on(
+ "request",
+ lambda r: stray_requests.append(r.url) if r.url.startswith(api_prefix) else None,
+ )
+ page.on(
+ "console",
+ lambda m: console_warnings.append(m.text[:200]) if m.type in ("warning", "error") else None,
+ )
+ try:
+ page.goto(f"{BASE}/smoke-thread-weight.html", wait_until = "domcontentloaded")
+ page.wait_for_function("() => Boolean(window.__threadWeight)", timeout = 30_000)
+ cdp = context.new_cdp_session(page)
+ cdp.send("Performance.enable")
+
+ # Seeding unthrottled: this measures interaction cost at a thread size, not the cost of
+ # constructing the thread, and 500 messages at 6x would spend minutes here.
+ page.evaluate("(n) => window.__threadWeight.seed(n)", size)
+ # Single-selector gates. counts() walks every element in the document, so polling it
+ # per frame makes seeding superlinear in the thing being seeded.
+ page.wait_for_function(
+ "(n) => window.__threadWeight.messageCount() >= n",
+ arg = size,
+ timeout = SEED_TIMEOUT_MS,
+ )
+ page.wait_for_function(
+ "(n) => window.__threadWeight.katexCount() >= n",
+ arg = size // 2,
+ timeout = SEED_TIMEOUT_MS,
+ )
+ # Shiki is async and per block, and a <pre> exists before it is highlighted, so counting
+ # code blocks gates nothing. Wait for the token count to stop moving instead: unfinished
+ # highlighting would otherwise land in the keystroke window, the first action measured.
+ page.wait_for_function(
+ """() => {
+ const n = window.__threadWeight.highlightedTokenCount();
+ const settled = window.__twTokens === n;
+ window.__twTokens = n;
+ return settled && n > 0;
+ }""",
+ timeout = SEED_TIMEOUT_MS,
+ )
+ result["counts"] = page.evaluate("window.__threadWeight.counts()")
+ result["viewport"] = page.evaluate("window.__threadWeight.viewportMetrics()")
+ # Kept for the record, then cleared: load and seeding are not part of any timing.
+ result["seed_api_requests"] = len(stray_requests)
+ result["seed_console_warnings"] = len(console_warnings)
+ stray_requests.clear()
+ console_warnings.clear()
+
+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": cdp_throttle_rate})
+ result["cpu_throttle_rate"] = cdp_throttle_rate
+ # Under throttling, because that is the regime every timing below is taken in.
+ result["paint_floor_ms"] = round(page.evaluate(PAINT_FLOOR_JS, 9), 2)
+
+ # 1. Keystroke.
+ reset_long_tasks(page)
+ before = metrics(cdp)
+ typed = page.evaluate(KEYSTROKE_JS, KEYSTROKES)
+ after = metrics(cdp)
+ result["keystroke"] = {
+ "samples_ms": None if typed is None else [round(s, 2) for s in typed["samples"]],
+ "median_ms": None if typed is None else round(median(typed["samples"]), 2),
+ "worst_ms": None if typed is None else round(max(typed["samples"]), 2),
+ "dom_text": None if typed is None else typed["domText"],
+ "runtime_text": None if typed is None else typed["runtimeText"],
+ **counters(before, after),
+ **long_task_summary(page),
+ }
+
+ # 2. Scroll gesture.
+ reset_long_tasks(page)
+ before = metrics(cdp)
+ scrolled = page.evaluate(SCROLL_JS, [SCROLL_STEPS, SCROLL_STEP_PX])
+ after = metrics(cdp)
+ result["scroll"] = {
+ "wall_ms": None if scrolled is None else round(scrolled["wallMs"], 1),
+ "scrolled_px": None if scrolled is None else scrolled["scrolledPx"],
+ # Long tasks need a 50ms frame; a scroll can be visibly rough well under that, so the
+ # worst single frame is the jank number and long_task_ms is the severe-case one.
+ "worst_frame_ms": None if scrolled is None else round(scrolled["worstFrameMs"], 1),
+ "frames": None if scrolled is None else scrolled["frames"],
+ **counters(before, after),
+ **long_task_summary(page),
+ }
+
+ # 3. Menu open + close. The bar is hover-revealed once it is autohidden, so hover with a
+ # real pointer first; only the click-to-settled interval is timed.
+ # behavior: "instant". The viewport carries scroll-smooth, so the default animates, and
+ # at large N a fixed wait leaves that animation in flight inside the menu counters --
+ # the same trap SCROLL_JS documents.
+ page.evaluate(
+ """() => { const m = window.__threadWeight.lastAssistantMessage();
+ if (m) m.scrollIntoView({ block: "center", behavior: "instant" }); }"""
+ )
+ page.wait_for_function(
+ """() => {
+ const top = window.__threadWeight.viewportMetrics().scrollTop;
+ const settled = window.__twTop === top;
+ window.__twTop = top;
+ return settled;
+ }""",
+ timeout = ACTION_TIMEOUT_MS,
+ )
+ page.locator('[data-role="assistant"]').last.hover(timeout = ACTION_TIMEOUT_MS)
+ reset_long_tasks(page)
+ before = metrics(cdp)
+ menu = page.evaluate(MENU_JS, SETTLE_TIMEOUT_MS)
+ after = metrics(cdp)
+ result["menu"] = {
+ "open_ms": None if menu is None else _round_or_none(menu["openMs"]),
+ "close_ms": None if menu is None else _round_or_none(menu["closeMs"]),
+ "open_close_ms": None if menu is None else _sum_or_none(menu),
+ "body_pointer_events_while_open": None if menu is None else menu["bodyPointerEvents"],
+ "body_pointer_events_after_close": (
+ None if menu is None else menu["bodyPointerEventsAfterClose"]
+ ),
+ "items_while_open": None if menu is None else menu["itemsWhileOpen"],
+ "triggers_while_hovered": None if menu is None else menu["triggersWhileHovered"],
+ **counters(before, after),
+ **long_task_summary(page),
+ }
+
+ # 4. Delete.
+ page.locator('[data-role="assistant"]').last.hover(timeout = ACTION_TIMEOUT_MS)
+ reset_long_tasks(page)
+ before = metrics(cdp)
+ deleted = page.evaluate(DELETE_JS, SETTLE_TIMEOUT_MS)
+ after = metrics(cdp)
+ result["delete"] = {
+ "ms": None if deleted is None else _round_or_none(deleted["ms"]),
+ "messages_before": None if deleted is None else deleted["before"],
+ "messages_after": None if deleted is None else deleted["after"],
+ **counters(before, after),
+ **long_task_summary(page),
+ }
+
+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": 1})
+ # Cumulative over seeding and all four actions: a liveness check, not attributable to
+ # any one of them.
+ result["raf_callbacks"] = page.evaluate("window.__rafCount")
+ result["stray_api_requests"] = len(stray_requests)
+ result["console_warnings"] = len(console_warnings)
+ result["first_console_warning"] = console_warnings[0] if console_warnings else "-"
+ finally:
+ page.close()
+ return result
+
+
+def _round_or_none(value) -> float | None:
+ return None if value is None else round(value, 1)
+
+
+def _sum_or_none(menu: dict) -> float | None:
+ if menu["openMs"] is None or menu["closeMs"] is None:
+ return None
+ return round(menu["openMs"] + menu["closeMs"], 1)
+
+
+def run() -> dict:
+ results: dict = {
+ "label": LABEL,
+ "base": BASE,
+ "cpu_throttle_rate": CPU_THROTTLE_RATE,
+ "sizes": SIZES,
+ "by_size": {},
+ }
+ with sync_playwright() as p:
+ browser = p.chromium.launch(
+ headless = os.environ.get("SMOKE_HEADLESS", "1") == "1",
+ args = chromium_launch_args(),
+ )
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ context.add_init_script(OBSERVER_INIT)
+ # Anchored at the origin so it cannot swallow vite's own module URLs, which live under
+ # src/features/**/api/ and would otherwise match a bare "/api/" pattern.
+ context.route(
+ re.compile(rf"^{re.escape(BASE)}/api/"),
+ lambda route: route.fulfill(status = 200, content_type = "application/json", body = "{}"),
+ )
+ for size in SIZES:
+ info(f"measuring N={size}")
+ results["by_size"][str(size)] = measure_one(context, CPU_THROTTLE_RATE, size)
+ context.close()
+ browser.close()
+ return results
+
+
+# Every recorded metric appears here. That is the rule the harnesses in this directory are held
+# to: a metric that is recorded and never read is how one goes false-green, and
+# tests/studio/test_autoscroll_harness_contract.py fails if anything recorded below is missing.
+TABLE_ROWS = (
+ ("messages requested", lambda r: r["messages_requested"]),
+ ("cpu throttle rate", lambda r: r["cpu_throttle_rate"]),
+ ("paint floor ms", lambda r: r["paint_floor_ms"]),
+ ("seed api requests", lambda r: r["seed_api_requests"]),
+ ("seed console warnings", lambda r: r["seed_console_warnings"]),
+ ("action api requests", lambda r: r["stray_api_requests"]),
+ ("action console warnings", lambda r: r["console_warnings"]),
+ ("first console warning", lambda r: r["first_console_warning"]),
+ ("messages rendered", lambda r: r["counts"]["messages"]),
+ ("assistant messages", lambda r: r["counts"]["assistantMessages"]),
+ ("user messages", lambda r: r["counts"]["userMessages"]),
+ ("dom nodes", lambda r: r["counts"]["domNodes"]),
+ ("code blocks", lambda r: r["counts"]["codeBlocks"]),
+ ("katex nodes", lambda r: r["counts"]["katexNodes"]),
+ ("action bars", lambda r: r["counts"]["actionBars"]),
+ ("tooltip triggers", lambda r: r["counts"]["tooltipTriggers"]),
+ ("tooltip triggers hovered", lambda r: r["menu"]["triggers_while_hovered"]),
+ ("viewport scrollHeight", lambda r: r["viewport"]["scrollHeight"]),
+ ("viewport scrollTop", lambda r: r["viewport"]["scrollTop"]),
+ ("viewport clientHeight", lambda r: r["viewport"]["clientHeight"]),
+ ("keystroke median ms", lambda r: r["keystroke"]["median_ms"]),
+ ("keystroke worst ms", lambda r: r["keystroke"]["worst_ms"]),
+ # Compact so the column still lines up. Worth a row of its own: the first sample is always a
+ # cold outlier, which is why the headline number is the median rather than the mean.
+ (
+ "keystroke samples ms",
+ lambda r: "/".join(str(round(s)) for s in r["keystroke"]["samples_ms"]),
+ ),
+ ("keystroke dom text", lambda r: r["keystroke"]["dom_text"]),
+ ("keystroke runtime text", lambda r: r["keystroke"]["runtime_text"]),
+ ("keystroke layouts", lambda r: r["keystroke"]["layout_count"]),
+ ("keystroke layout ms", lambda r: r["keystroke"]["layout_ms"]),
+ ("keystroke recalcs", lambda r: r["keystroke"]["recalc_style_count"]),
+ ("keystroke recalc ms", lambda r: r["keystroke"]["recalc_style_ms"]),
+ ("keystroke task ms", lambda r: r["keystroke"]["task_ms"]),
+ ("keystroke longtasks", lambda r: r["keystroke"]["long_tasks"]),
+ ("keystroke longtask ms", lambda r: r["keystroke"]["long_task_ms"]),
+ ("keystroke worst longtask ms", lambda r: r["keystroke"]["worst_long_task_ms"]),
+ ("scroll wall ms", lambda r: r["scroll"]["wall_ms"]),
+ ("scroll worst frame ms", lambda r: r["scroll"]["worst_frame_ms"]),
+ ("scroll px", lambda r: r["scroll"]["scrolled_px"]),
+ ("scroll frames", lambda r: r["scroll"]["frames"]),
+ ("scroll layouts", lambda r: r["scroll"]["layout_count"]),
+ ("scroll layout ms", lambda r: r["scroll"]["layout_ms"]),
+ ("scroll recalcs", lambda r: r["scroll"]["recalc_style_count"]),
+ ("scroll recalc ms", lambda r: r["scroll"]["recalc_style_ms"]),
+ ("scroll task ms", lambda r: r["scroll"]["task_ms"]),
+ ("scroll longtasks", lambda r: r["scroll"]["long_tasks"]),
+ ("scroll longtask ms", lambda r: r["scroll"]["long_task_ms"]),
+ ("scroll worst longtask ms", lambda r: r["scroll"]["worst_long_task_ms"]),
+ ("menu open ms", lambda r: r["menu"]["open_ms"]),
+ ("menu close ms", lambda r: r["menu"]["close_ms"]),
+ ("menu open+close ms", lambda r: r["menu"]["open_close_ms"]),
+ ("menu body pe while open", lambda r: r["menu"]["body_pointer_events_while_open"]),
+ ("menu body pe after close", lambda r: r["menu"]["body_pointer_events_after_close"]),
+ ("menu items while open", lambda r: r["menu"]["items_while_open"]),
+ ("menu layouts", lambda r: r["menu"]["layout_count"]),
+ ("menu layout ms", lambda r: r["menu"]["layout_ms"]),
+ ("menu recalcs", lambda r: r["menu"]["recalc_style_count"]),
+ ("menu recalc ms", lambda r: r["menu"]["recalc_style_ms"]),
+ ("menu task ms", lambda r: r["menu"]["task_ms"]),
+ ("menu longtasks", lambda r: r["menu"]["long_tasks"]),
+ ("menu longtask ms", lambda r: r["menu"]["long_task_ms"]),
+ ("menu worst longtask ms", lambda r: r["menu"]["worst_long_task_ms"]),
+ ("delete ms", lambda r: r["delete"]["ms"]),
+ ("delete messages before", lambda r: r["delete"]["messages_before"]),
+ ("delete messages after", lambda r: r["delete"]["messages_after"]),
+ ("delete layouts", lambda r: r["delete"]["layout_count"]),
+ ("delete layout ms", lambda r: r["delete"]["layout_ms"]),
+ ("delete recalcs", lambda r: r["delete"]["recalc_style_count"]),
+ ("delete recalc ms", lambda r: r["delete"]["recalc_style_ms"]),
+ ("delete task ms", lambda r: r["delete"]["task_ms"]),
+ ("delete longtasks", lambda r: r["delete"]["long_tasks"]),
+ ("delete longtask ms", lambda r: r["delete"]["long_task_ms"]),
+ ("delete worst longtask ms", lambda r: r["delete"]["worst_long_task_ms"]),
+ ("rAF callbacks", lambda r: r["raf_callbacks"]),
+)
+
+
+def print_table(results: dict) -> None:
+ """Every recorded metric, printed. A metric that is recorded and never read is how these
+ harnesses go false-green; see tests/studio/test_autoscroll_harness_contract.py."""
+ sizes = [str(n) for n in results["sizes"]]
+ rows = []
+ for name, pick in TABLE_ROWS:
+ cells = []
+ for size in sizes:
+ try:
+ cells.append(str(pick(results["by_size"][size])))
+ except (KeyError, TypeError):
+ cells.append("-")
+ rows.append((name, cells))
+ label_width = max(len(name) for name, _ in rows) + 2
+ # From the widest cell, not a constant: a fixed width silently runs the columns together on
+ # the one row that overflows it, which is the row you were reading.
+ cell_width = max([len(cell) for _, cells in rows for cell in cells] + [8]) + 2
+ header = "".ljust(label_width) + "".join(f"N={n}".rjust(cell_width) for n in sizes)
+ info(header)
+ info("-" * len(header))
+ for name, cells in rows:
+ info(name.ljust(label_width) + "".join(cell.rjust(cell_width) for cell in cells))
+
+
+def growth(results: dict, pick, floored: bool) -> tuple[float | None, float | None]:
+ """The metric at the smallest and largest N, with the paint floor removed when it applies."""
+ sizes = [str(n) for n in results["sizes"]]
+ try:
+ rows = (results["by_size"][sizes[0]], results["by_size"][sizes[-1]])
+ values = []
+ for row in rows:
+ value = pick(row)
+ if floored:
+ value -= row["paint_floor_ms"]
+ values.append(round(value, 2))
+ return values[0], values[1]
+ except (KeyError, TypeError):
+ return None, None
+
+
+# Growth axes. The point of the harness is that at least one of these rises with N; if none
+# does, the page is not being driven and every later comparison would be vacuous.
+#
+# `floored` marks a metric whose clock is a double rAF, so it carries the ~33ms vsync floor
+# measured as paint_floor_ms. The floor is subtracted before the ratio: left in, it compresses
+# every ratio towards 1 and would let a real regression sit under the discrimination threshold.
+GROWTH_AXES = (
+ ("keystroke median ms", lambda r: r["keystroke"]["median_ms"], True),
+ ("scroll worst frame ms", lambda r: r["scroll"]["worst_frame_ms"], True),
+ ("scroll task ms", lambda r: r["scroll"]["task_ms"], False),
+ ("scroll longtask ms", lambda r: r["scroll"]["long_task_ms"], False),
+ ("scroll layout ms", lambda r: r["scroll"]["layout_ms"], False),
+ ("menu open+close ms", lambda r: r["menu"]["open_close_ms"], True),
+ ("menu recalc ms", lambda r: r["menu"]["recalc_style_ms"], False),
+ ("delete ms", lambda r: r["delete"]["ms"], True),
+ ("delete task ms", lambda r: r["delete"]["task_ms"], False),
+)
+
+
+def harness_failures(results: dict) -> list[str]:
+ """Only the ways this harness can be measuring nothing. No performance budgets: see the
+ module docstring."""
+ failures: list[str] = []
+ layers = set()
+ for size in results["sizes"]:
+ row = results["by_size"][str(size)]
+ counts = row["counts"]
+ # A request reaching the server is a CDP round trip to another process inside a region
+ # being timed, once per assistant message. A warning storm is the same cost via the
+ # console channel. Both scale with N, so both would forge the curve.
+ if row["stray_api_requests"]:
+ failures.append(
+ f"N={size} let {row['stray_api_requests']} /api/ requests reach the network "
+ "during the measured actions; the in-page stub is not covering them and the "
+ "timings include a round trip to another process for each"
+ )
+ if row["console_warnings"]:
+ failures.append(
+ f"N={size} logged {row['console_warnings']} console warnings during the "
+ f"measured actions, the first being "
+ f"{row['first_console_warning']!r}; each one is serialised over CDP and the "
+ "count grows with N"
+ )
+ if counts["messages"] < size:
+ failures.append(
+ f"N={size} rendered only {counts['messages']} messages; the seed did not land"
+ )
+ # A thread of plain paragraphs would be cheap for reasons the app is not.
+ if counts["codeBlocks"] <= 0 or counts["katexNodes"] <= 0:
+ failures.append(
+ f"N={size} rendered {counts['codeBlocks']} code blocks and "
+ f"{counts['katexNodes']} KaTeX nodes; the message bodies are not realistic"
+ )
+ # An autohidden bar is absent at rest ON PURPOSE, so the resting census cannot be the
+ # guard any more. What must still hold is that hovering produces one: a tree that
+ # mounts no bar under the pointer either is broken, and its menu column is measuring
+ # a page that has no menu.
+ hovered_triggers = row["menu"].get("triggers_while_hovered")
+ if counts["actionBars"] <= 0 and not hovered_triggers:
+ failures.append(
+ f"N={size} mounted no action bar at rest and none under the pointer either; "
+ "the per-message weight under investigation is absent"
+ )
+ viewport = row["viewport"]
+ if viewport["scrollHeight"] <= viewport["clientHeight"]:
+ failures.append(f"N={size} does not overflow its viewport; the scroll measures nothing")
+ keystroke = row["keystroke"]
+ if keystroke["median_ms"] is None:
+ failures.append(f"N={size} could not find the composer input")
+ # The DOM value is what the harness itself wrote, so it proves nothing on its own. Only
+ # the runtime's copy shows the keystroke reached React rather than just the textarea --
+ # and a keystroke that reached nothing still reports the ~33ms paint floor, which reads
+ # as a plausible timing.
+ elif keystroke["runtime_text"] != keystroke["dom_text"]:
+ failures.append(
+ f"N={size} typed {keystroke['dom_text']!r} into the DOM but the runtime holds "
+ f"{keystroke['runtime_text']!r}; the keystroke never reached the composer state"
+ )
+ elif len(keystroke["dom_text"]) < KEYSTROKES:
+ failures.append(
+ f"N={size} recorded {len(keystroke['dom_text'])} of {KEYSTROKES} keystrokes"
+ )
+ elif keystroke["median_ms"] <= row["paint_floor_ms"]:
+ failures.append(
+ f"N={size} reported a keystroke of {keystroke['median_ms']}ms at or under the "
+ f"{row['paint_floor_ms']}ms paint floor, so no work was measured"
+ )
+ if row["scroll"]["wall_ms"] is None:
+ failures.append(f"N={size} could not find the thread viewport")
+ # Equal travel at every N or the columns are not the same gesture. A short thread runs
+ # out of room, so the gesture reverses at the ends rather than stopping.
+ elif row["scroll"]["scrolled_px"] < SCROLL_STEPS * SCROLL_STEP_PX * 0.9:
+ failures.append(
+ f"N={size} travelled only {row['scroll']['scrolled_px']}px of the "
+ f"{SCROLL_STEPS * SCROLL_STEP_PX}px gesture, so its scroll column is not "
+ "comparable with the others"
+ )
+ menu = row["menu"]
+ if menu["open_ms"] is None:
+ failures.append(f"N={size} never opened the message action menu")
+ elif menu["close_ms"] is None:
+ failures.append(f"N={size} opened the action menu and it never closed")
+ elif menu["body_pointer_events_after_close"] == "none":
+ failures.append(f"N={size} left the body on the modal layer after closing the menu")
+ # An empty popover satisfies "the menu opened" and costs nothing to render.
+ elif not menu["items_while_open"]:
+ failures.append(f"N={size} opened an action menu with no items in it")
+ layers.add(menu["body_pointer_events_while_open"])
+ deleted = row["delete"]
+ if deleted["ms"] is None:
+ failures.append(f"N={size} never deleted a message")
+ elif deleted["messages_after"] >= deleted["messages_before"]:
+ failures.append(f"N={size} clicked delete and the message count did not drop")
+
+ # A modal menu puts the body on the modal layer and a non-modal one does not, and the two
+ # cost wildly different amounts. Either is a legitimate tree, but a run that mixes them
+ # across N is comparing columns measured on different mechanisms, which is the quiet way
+ # this table stops meaning anything. Collected in the loop above rather than in a second
+ # one over the same sizes: that loop shadowed `size` and `row`, and every check written
+ # under it silently measured only the last N.
+ if len(layers) > 1:
+ failures.append(
+ f"the menu put the body on {sorted(str(x) for x in layers)} across N; the columns "
+ "are not measuring the same mechanism"
+ )
+
+ # Discrimination. Not a budget: a harness where the biggest thread costs exactly what the
+ # smallest does is not reporting a flat curve, it is reporting that it never drove the page.
+ if len(results["sizes"]) >= 2:
+ rising = []
+ for name, pick, floored in GROWTH_AXES:
+ small, large = growth(results, pick, floored)
+ if small is None or large is None or small <= 0:
+ continue
+ ratio = large / small
+ suffix = " (paint floor removed)" if floored else ""
+ info(
+ f"growth {name}: N={results['sizes'][0]} {small} -> "
+ f"N={results['sizes'][-1]} {large} ({ratio:.2f}x){suffix}"
+ )
+ if ratio > 1.5:
+ rising.append(f"{name} {ratio:.2f}x")
+ if rising:
+ info(f"discriminating axes: {', '.join(rising)}")
+ else:
+ failures.append(
+ "no measured axis rose with N. Either the page was never driven or every "
+ "action is being measured somewhere it does not run; the numbers above cannot "
+ "size any change."
+ )
+ return failures
+
+
+def main() -> int:
+ vite = None
+ if OWNS_SERVER:
+ info(f"starting vite dev server on port {PORT}")
+ vite = start_vite(PORT)
+ try:
+ wait_for_smoke_page(
+ f"{BASE}/smoke-thread-weight.html",
+ "smoke-thread-weight-main.tsx",
+ proc = vite,
+ info = info,
+ )
+ results = run()
+ finally:
+ if vite is not None:
+ stop_process(vite)
+ info("vite stopped")
+
+ out = OUT / f"{LABEL}.json"
+ out.write_text(json.dumps(results, indent = 2), encoding = "utf-8")
+ print_table(results)
+ info(json.dumps(results, indent = 2))
+ info(f"wrote {out}")
+
+ failures = harness_failures(results)
+ for problem in failures:
+ info(f"HARNESS-BROKEN {problem}")
+ if failures:
+ return 1
+ info("measurement only: no budgets are asserted here, so this exits 0 on any timing.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.py
index ce970136663..8d966620056 100644
--- a/tests/studio/test_autoscroll_harness_contract.py
+++ b/tests/studio/test_autoscroll_harness_contract.py
@@ -10,6 +10,7 @@ budget, an unasserted click count, and the two guards below), so the rule is pin
than left to review.
"""
+import ast
import types
from pathlib import Path
@@ -171,6 +172,7 @@ def test_harnesses_own_their_dev_server() -> None:
"playwright_chat_autoscroll.py",
"playwright_research_freeze.py",
"playwright_strip_ansi_smoke.py",
+ "playwright_thread_weight.py",
"playwright_stream_pacing.py",
):
text = source(name)
@@ -178,3 +180,193 @@ def test_harnesses_own_their_dev_server() -> None:
assert "stop_process" in text, f"{name} never tears its server down"
# Vite's SPA fallback answers 200 with index.html for a page that no longer exists.
assert "wait_for_smoke_page" in text, f"{name} gates on status rather than on content"
+
+
+# The #8977 thread-weight harness deliberately asserts no timing budget: it exists to produce the
+# numbers a budget would later be set from. That removes the `main()` check the tests above rely
+# on, so the same rule is enforced one step earlier -- every metric it records has to reach the
+# printed table. An unprinted metric there is the same failure as an unasserted one here: the
+# number that would have shown the regression is collected and then thrown away.
+
+THREAD_WEIGHT = "playwright_thread_weight.py"
+
+
+def thread_weight_verdict() -> str:
+ """Everything from `def harness_failures(` on. Unlike the harnesses above, this one turns
+ metrics into an exit code there rather than in `main()`."""
+ text = source(THREAD_WEIGHT)
+ return text[text.index("def harness_failures(") :]
+
+
+def _dict_keys(node: ast.AST, helpers: dict[str, set[str]]) -> set[str]:
+ """String keys of a dict literal, following `**helper(...)` into the helper's return dict."""
+ keys: set[str] = set()
+ if not isinstance(node, ast.Dict):
+ return keys
+ for key, value in zip(node.keys, node.values):
+ if key is None: # **spread
+ call = value
+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name):
+ keys |= helpers.get(call.func.id, set())
+ continue
+ if isinstance(key, ast.Constant) and isinstance(key.value, str):
+ keys.add(key.value)
+ return keys
+
+
+def _thread_weight_recorded() -> dict[str, set[str]]:
+ """{action: recorded metric names} for every `result["action"] = {...}` in the harness."""
+ tree = ast.parse(source(THREAD_WEIGHT))
+ helpers: dict[str, set[str]] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef):
+ for statement in node.body:
+ if isinstance(statement, ast.Return):
+ found = _dict_keys(statement.value, {})
+ if found:
+ helpers[node.name] = found
+ recorded: dict[str, set[str]] = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign) or len(node.targets) != 1:
+ continue
+ target = node.targets[0]
+ if (
+ isinstance(target, ast.Subscript)
+ and isinstance(target.value, ast.Name)
+ and target.value.id == "result"
+ and isinstance(target.slice, ast.Constant)
+ and isinstance(target.slice.value, str)
+ ):
+ keys = _dict_keys(node.value, helpers)
+ if keys:
+ recorded[target.slice.value] = keys
+ return recorded
+
+
+def test_thread_weight_records_the_four_actions() -> None:
+ # Guards the parser above as much as the harness: an empty result set would make the
+ # coverage test below pass by finding nothing to check.
+ recorded = _thread_weight_recorded()
+ assert {"keystroke", "scroll", "menu", "delete"} <= set(recorded)
+ # Not `assert keys`: _thread_weight_recorded only stores an entry when it found keys, so
+ # that could never fail. Each action records its own timings plus the five CDP counters and
+ # the three long-task fields, so anything under ten means the parser lost a spread.
+ for action, keys in recorded.items():
+ assert len(keys) >= 10, f"{action} recorded only {len(keys)} metrics: {sorted(keys)}"
+
+
+def test_thread_weight_row_shapes_stay_distinct() -> None:
+ """TABLE_ROWS is (label, pick) and GROWTH_AXES is (label, pick, floored). They read almost
+ identically, so a bulk edit to one lands in the other and print_table dies at the end of a
+ forty-minute run, after every measurement is taken and before any of it is shown."""
+ import importlib
+ import sys
+
+ sys.path.insert(0, str(STUDIO_TESTS))
+ pytest = importlib.import_module("pytest")
+ pytest.importorskip("playwright")
+ module = importlib.import_module("playwright_thread_weight")
+ assert all(len(row) == 2 for row in module.TABLE_ROWS)
+ assert all(len(row) == 3 for row in module.GROWTH_AXES)
+
+
+def test_thread_weight_prints_every_metric_it_records() -> None:
+ text = source(THREAD_WEIGHT)
+ table = text[text.index("TABLE_ROWS = (") : text.index("def print_table")]
+ missing = [
+ f'{action}["{metric}"]'
+ for action, metrics in _thread_weight_recorded().items()
+ for metric in sorted(metrics)
+ if f'r["{action}"]["{metric}"]' not in table
+ ]
+ assert not missing, (
+ "recorded but never printed, so the harness would report a curve with these missing: "
+ + ", ".join(missing)
+ )
+
+
+def test_thread_weight_proves_it_discriminates_rather_than_gating_on_a_budget() -> None:
+ # The one thing this harness must fail on. Without it a run where nothing was ever clicked
+ # reports four identical columns and exits 0, which reads as "no regression".
+ # Not `in source(...)`: the verdict is a substring of the source, so an `or` against the
+ # whole file would make this unfailable.
+ # Asserted against the verdict region, not the whole file: a check that only ever appears
+ # in a comment or a table row would otherwise satisfy this.
+ main = thread_weight_verdict()
+ assert "GROWTH_AXES" in main
+ assert "no measured axis rose with N" in main
+ # The menu is opened non-modally now, so the body must NOT go onto the modal layer; what
+ # the verdict has to reject is a run that mixes the two across N, whose columns then price
+ # different mechanisms.
+ assert 'menu["body_pointer_events_while_open"]' in main
+ # An empty popover satisfies "the menu opened" and costs nothing to render.
+ assert 'menu["items_while_open"]' in main
+ # A delete that deleted nothing is a fast delete.
+ assert 'deleted["messages_after"]' in main
+ # A keystroke that never reached the runtime still reports the double-rAF paint floor, so
+ # the floor has to be compared rather than left implicit in the timings.
+ assert 'row["paint_floor_ms"]' in main
+ assert 'keystroke["runtime_text"] != keystroke["dom_text"]' in main
+ # Requests reaching the network and console warnings both cost a CDP round trip per
+ # message, so both would grow with N for reasons the app does not have.
+ assert 'row["stray_api_requests"]' in main
+ assert 'row["console_warnings"]' in main
+
+
+def _thread_weight_row(deleted: bool = True, layer: str = "auto") -> dict:
+ """One healthy column of the thread-weight table, optionally with a delete that did nothing."""
+ return {
+ "counts": {
+ "messages": 10_000,
+ "codeBlocks": 4,
+ "katexNodes": 4,
+ "actionBars": 3,
+ "tooltipTriggers": 8,
+ },
+ "stray_api_requests": 0,
+ "console_warnings": 0,
+ "first_console_warning": None,
+ "viewport": {"scrollHeight": 9000, "clientHeight": 800, "scrollTop": 0},
+ "paint_floor_ms": 33,
+ "keystroke": {"median_ms": 120, "runtime_text": "x" * 40, "dom_text": "x" * 40},
+ "scroll": {"wall_ms": 100, "scrolled_px": 10_000},
+ "menu": {
+ "open_ms": 10,
+ "close_ms": 10,
+ "body_pointer_events_after_close": "auto",
+ "body_pointer_events_while_open": layer,
+ "items_while_open": 5,
+ "triggers_while_hovered": 8,
+ },
+ "delete": {
+ "ms": 5 if deleted else None,
+ "messages_before": 10,
+ "messages_after": 9 if deleted else 10,
+ },
+ }
+
+
+def test_thread_weight_rejects_a_dead_delete_at_every_size() -> None:
+ """The delete checks once sat under the whole-run modal-layer `if`, so a table whose delete
+ never removed anything still passed while another axis grew. They belong to the per-size
+ loop: every measured column has to prove its own delete, not just the last one."""
+ import importlib
+ import sys
+
+ sys.path.insert(0, str(STUDIO_TESTS))
+ pytest = importlib.import_module("pytest")
+ pytest.importorskip("playwright")
+ module = importlib.import_module("playwright_thread_weight")
+
+ sizes = [10, 50]
+ for dead in sizes:
+ results = {
+ "sizes": sizes,
+ "by_size": {str(size): _thread_weight_row(deleted = size != dead) for size in sizes},
+ }
+ assert f"N={dead} never deleted a message" in module.harness_failures(results)
+ healthy = {
+ "sizes": sizes,
+ "by_size": {str(size): _thread_weight_row() for size in sizes},
+ }
+ assert not [f for f in module.harness_failures(healthy) if "delete" in f]
diff --git a/tests/studio/test_playwright_suites_run_in_ci.py b/tests/studio/test_playwright_suites_run_in_ci.py
index 53fb52063d6..4b607b97506 100644
--- a/tests/studio/test_playwright_suites_run_in_ci.py
+++ b/tests/studio/test_playwright_suites_run_in_ci.py
@@ -33,6 +33,13 @@ NOT_IN_CI = {
# through huggingface_hub; the UI workflows deliberately boot API-only with
# one 254 MiB GGUF and no network model resolution.
"playwright_train_pickers.py",
+ # A measurement harness rather than a gate: it prints the per-N cost table #8977
+ # was sized from and deliberately sets no budget, and the sizes that make the
+ # curve mean anything (to 500 messages under 6x CPU throttling) cost tens of
+ # minutes. Run by hand when that curve needs re-measuring. The part of it that
+ # can go wrong silently, the verdict in harness_failures, is driven without a
+ # browser by test_autoscroll_harness_contract.py, which CI does run.
+ "playwright_thread_weight.py",
}