Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: CI gate that fails when typing in a long chat gets slower as the chat grows (#16801)
Daniel Han8f4206ce418f
diff --git a/.github/workflows/studio-composer-compatibility.yml b/.github/workflows/studio-composer-compatibility.ymlindex f5c15a2478a..8cb31311219 100644--- a/.github/workflows/studio-composer-compatibility.yml+++ b/.github/workflows/studio-composer-compatibility.yml@@ -24,6 +24,10 @@ on:- '.github/workflows/studio-composer-compatibility.yml'- 'scripts/lockfile_supply_chain_audit.py'- '.github/scripts/retry-with-apt-lock.sh'+ - 'tests/studio/playwright_long_thread_gate.py'+ - 'tests/studio/_css_culprit.py'+ - 'studio/frontend/smoke-thread-weight*'+ - 'studio/frontend/vite.long-thread.config.ts'workflow_dispatch:permissions:@@ -74,6 +78,28 @@ jobs:- name: Install frontend dependencies without lifecycle scriptsworking-directory: studio/frontendrun: npm ci --ignore-scripts --no-fund --no-audit+ # Runs first in every frontend lane, so a long-chat typing regression fails within minutes+ # instead of after the other suites. Ratio, not timing: Chromium's selector-matching time per+ # keystroke in a 200-turn chat over a 40-turn chat (production build, real app ancestors), plus+ # a :has() budget in the large one; a slow runner cannot fail it. A failure prints ms per key,+ # the selectors responsible and the CSS they probably come from.+ - name: Chromium for the long-chat typing gate+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 10+ env:+ APT_ACQUIRE_RETRIES: '0'+ run: |+ python -m pip install 'playwright>=1.45,<2'+ python -m playwright install chromium+ if [ "$RUNNER_OS" = Linux ] && ! python -c "from playwright.sync_api import sync_playwright as s; p = s().start(); p.chromium.launch().close(); p.stop()"; then+ bash .github/scripts/retry-with-apt-lock.sh python -m playwright install-deps chromium+ fi+ - name: Browser gate for long-chat typing cost+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 15+ run: python tests/studio/playwright_long_thread_gate.py- name: Create isolated test environmentrun: |# Chrome/Edge abort when their TMPDIR socket path exceeds 107 bytes; RUNNER_TEMP is short.diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 309b41c62a4..ce62ebdc48e 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -41,6 +41,9 @@ on:- 'tests/studio/playwright_user_message_time.py'- 'tests/studio/playwright_progressive_rows.py'- 'tests/studio/playwright_long_chat_renders.py'+ - 'tests/studio/playwright_long_thread_gate.py'+ - 'tests/studio/_css_culprit.py'+ - 'tests/studio/test_css_culprit.py'- 'tests/studio/playwright_model_picker_renders.py'- 'tests/studio/playwright_recipe_drag_renders.py'- 'tests/studio/playwright_gallery_strip_renders.py'@@ -90,6 +93,9 @@ on:- 'tests/studio/playwright_user_message_time.py'- 'tests/studio/playwright_progressive_rows.py'- 'tests/studio/playwright_long_chat_renders.py'+ - 'tests/studio/playwright_long_thread_gate.py'+ - 'tests/studio/_css_culprit.py'+ - 'tests/studio/test_css_culprit.py'- 'tests/studio/playwright_model_picker_renders.py'- 'tests/studio/playwright_recipe_drag_renders.py'- 'tests/studio/playwright_gallery_strip_renders.py'@@ -188,6 +194,30 @@ jobs:exit 1fi+ # Runs first in every frontend lane, so a long-chat typing regression fails within minutes+ # instead of after the other suites. Ratio, not timing: Chromium's selector-matching time per+ # keystroke in a 200-turn chat over a 40-turn chat (production build, real app ancestors), plus+ # a :has() budget in the large one; a slow runner cannot fail it. A failure prints ms per key,+ # the selectors responsible and the CSS they probably come from.+ - name: Chromium for the long-chat typing gate+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 10+ env:+ APT_ACQUIRE_RETRIES: '0'+ run: |+ python3 -m pip install 'playwright>=1.45,<2'+ python3 -m playwright install chromium+ if [ "$RUNNER_OS" = Linux ] && ! python3 -c "from playwright.sync_api import sync_playwright as s; p = s().start(); p.chromium.launch().close(); p.stop()"; then+ bash .github/scripts/retry-with-apt-lock.sh python3 -m playwright install-deps chromium+ fi++ - name: Browser gate for long-chat typing cost+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 15+ run: python3 tests/studio/playwright_long_thread_gate.py+# Fetch the base commit with an explicit refspec so origin/<base> exists.- name: Dependency removal safety checkif: github.event_name == 'pull_request'@@ -373,7 +403,8 @@ jobs:tests/studio/test_heavy_thread_harness_contract.py \tests/studio/test_heavy_thread_measurement_integrity.py \tests/studio/test_heavy_thread_gap_contract.py \- tests/studio/test_code_block_flicker_contract.py -q+ tests/studio/test_code_block_flicker_contract.py \+ tests/studio/test_css_culprit.py -q# Keep data settings separate from the shorter checks. Each group owns its cache.# The step bound is the smaller one, leaving the job 25 minutes for the steps before it: a@@ -662,6 +693,30 @@ jobs:# --ignore-scripts: a platform gate, so no install scripts run at all.- run: npm ci --ignore-scripts --no-fund --no-audit+ # Runs first in every frontend lane, so a long-chat typing regression fails within minutes+ # instead of after the other suites. Ratio, not timing: Chromium's selector-matching time per+ # keystroke in a 200-turn chat over a 40-turn chat (production build, real app ancestors), plus+ # a :has() budget in the large one; a slow runner cannot fail it. A failure prints ms per key,+ # the selectors responsible and the CSS they probably come from.+ - name: Chromium for the long-chat typing gate+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 10+ env:+ APT_ACQUIRE_RETRIES: '0'+ run: |+ python -m pip install 'playwright>=1.45,<2'+ python -m playwright install chromium+ if [ "$RUNNER_OS" = Linux ] && ! python -c "from playwright.sync_api import sync_playwright as s; p = s().start(); p.chromium.launch().close(); p.stop()"; then+ bash .github/scripts/retry-with-apt-lock.sh python -m playwright install-deps chromium+ fi++ - name: Browser gate for long-chat typing cost+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 15+ run: python tests/studio/playwright_long_thread_gate.py+- name: Unit testsrun: npm testdiff --git a/.github/workflows/studio-inline-images.yml b/.github/workflows/studio-inline-images.ymlindex ccf4376ead2..2a787e13bb6 100644--- a/.github/workflows/studio-inline-images.yml+++ b/.github/workflows/studio-inline-images.yml@@ -27,6 +27,10 @@ on:- '.github/scripts/retry-with-apt-lock.sh'- 'scripts/lockfile_supply_chain_audit.py'- '.github/workflows/studio-inline-images.yml'+ - 'tests/studio/playwright_long_thread_gate.py'+ - 'tests/studio/_css_culprit.py'+ - 'studio/frontend/smoke-thread-weight*'+ - 'studio/frontend/vite.long-thread.config.ts'workflow_dispatch:permissions:@@ -68,6 +72,28 @@ jobs:- name: Install frontend dependenciesworking-directory: studio/frontendrun: npm ci --ignore-scripts --no-fund --no-audit+ # Runs first in every frontend lane, so a long-chat typing regression fails within minutes+ # instead of after the other suites. Ratio, not timing: Chromium's selector-matching time per+ # keystroke in a 200-turn chat over a 40-turn chat (production build, real app ancestors), plus+ # a :has() budget in the large one; a slow runner cannot fail it. A failure prints ms per key,+ # the selectors responsible and the CSS they probably come from.+ - name: Chromium for the long-chat typing gate+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 10+ env:+ APT_ACQUIRE_RETRIES: '0'+ run: |+ python -m pip install 'playwright>=1.45,<2'+ python -m playwright install chromium+ if [ "$RUNNER_OS" = Linux ] && ! python -c "from playwright.sync_api import sync_playwright as s; p = s().start(); p.chromium.launch().close(); p.stop()"; then+ bash .github/scripts/retry-with-apt-lock.sh python -m playwright install-deps chromium+ fi+ - name: Browser gate for long-chat typing cost+ working-directory: ${{ github.workspace }}+ shell: bash+ timeout-minutes: 15+ run: python tests/studio/playwright_long_thread_gate.py- name: Create isolated test environmentrun: |python -m venv temp/inline-image-validation/venvdiff --git a/studio/frontend/smoke-thread-weight-main.tsx b/studio/frontend/smoke-thread-weight-main.tsxindex 25e2093f385..ba094e39b6c 100644--- a/studio/frontend/smoke-thread-weight-main.tsx+++ b/studio/frontend/smoke-thread-weight-main.tsx@@ -5,6 +5,7 @@// seeded via thread.import on a local runtime (only it backs export/import used by delete).import { Thread } from "@/components/assistant-ui/thread";+import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";import { TooltipProvider } from "@/components/ui/tooltip";import {AssistantRuntimeProvider,@@ -99,7 +100,7 @@ type SeedOptions = {* `rounds` x reasoning, tool call, answer per reply; truncation every `compactionEvery`th.* `sources` adds six URL source parts after every web_search call.*/- agent?: { rounds: number; compactionEvery?: number; sources?: boolean };+ agent?: { rounds: number; compactionEvery?: number; sources?: boolean; rich?: boolean };};const AGENT_TOOLS = ["web_search", "terminal", "python"] as const;@@ -114,7 +115,11 @@ function urlSources(tag: string) {}));}-function agentContent(index: number, rounds: number, sources = false) {+function table(tag: string): string {+ return ["| step | loss | lr |", "|---|---|---|", ...[0, 1, 2, 3].map((row) => `| ${tag}.${row} | 0.${row}4 | 2e-4 |`)].join("\n");+}++function agentContent(index: number, rounds: number, sources = false, rich = false) {const parts: Exclude<ThreadMessageLike["content"], string>[number][] = [];for (let round = 0; round < rounds; round++) {const tag = `${index}_${round}`;@@ -138,7 +143,9 @@ function agentContent(index: number, rounds: number, sources = false) {if (sources && toolName === "web_search") parts.push(...urlSources(tag));parts.push({type: "text" as const,- text: `Answer ${tag}. ${PROSE}\n\n- first item ${tag}\n- second item ${tag}`,+ text: rich+ ? [assistantMarkdown(index * 10 + round), table(tag), `- first item ${tag}\n- second item ${tag}`].join("\n\n")+ : `Answer ${tag}. ${PROSE}\n\n- first item ${tag}\n- second item ${tag}`,});}return parts;@@ -169,7 +176,7 @@ function buildMessages(const compacted = every > 0 && ordinal > 0 && ordinal % every === 0;return {role: "assistant" as const,- content: agentContent(index, agent.rounds, agent.sources),+ content: agentContent(index, agent.rounds, agent.sources, agent.rich),...(compacted? {metadata: {@@ -369,6 +376,29 @@ function ThreadWeightApi({return null;}+// `?shell=1`: the ancestors the app puts around the thread (root layout + chat page), so CSS+// anchored on them (e.g. a `:has()` on the wallpaper workspace) runs here as it does in Studio.+const SHELL = new URLSearchParams(window.location.search).get("shell") === "1";++function AppShell({ children }: { children: ReactElement }): ReactElement {+ if (!SHELL) return children;+ return (+ <SidebarProvider+ data-wallpaper-workspace=""+ data-wallpaper-route="chat"+ className="relative !min-h-0 h-[100dvh] overflow-hidden"+ >+ <SidebarInset className="overflow-hidden">+ <div className="relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">+ <div data-chat-content-root="" className="relative flex min-h-0 flex-1 flex-col">+ {children}+ </div>+ </div>+ </SidebarInset>+ </SidebarProvider>+ );+}+// `?remote=1`: the remote thread list + attachments adapter the app uses, for the same scopes.const REMOTE = new URLSearchParams(window.location.search).get("remote") === "1";@@ -423,12 +453,14 @@ function HarnessBody({<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>+ <AppShell>+ <div+ data-smoke="thread"+ style={{ display: "flex", flexDirection: "column", height: SHELL ? "100%" : "100vh" }}+ >+ {threadMounted ? <Thread hideWelcome={true} /> : null}+ </div>+ </AppShell></AssistantRuntimeProvider></TooltipProvider>);diff --git a/studio/frontend/vite.long-thread.config.ts b/studio/frontend/vite.long-thread.config.tsnew file mode 100644index 00000000000..0627ce6b22c--- /dev/null+++ b/studio/frontend/vite.long-thread.config.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Production build of the thread-weight fixture for tests/studio/playwright_long_thread_gate.py:+// the shipped CSS plugins and production React, since a dev build inflates the costs it gates.+import path from "node:path";+import { mergeConfig } from "vite";+import base from "./vite.config";++export default mergeConfig(base, {+ build: {+ emptyOutDir: true,+ outDir: path.resolve(__dirname, "../../.playwright-cli/long-thread-production"),+ rollupOptions: {+ input: path.resolve(__dirname, "smoke-thread-weight.html"),+ },+ },+});diff --git a/tests/studio/_css_culprit.py b/tests/studio/_css_culprit.pynew file mode 100644index 00000000000..9fc656f9bc2--- /dev/null+++ b/tests/studio/_css_culprit.py@@ -0,0 +1,345 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Best-effort pointer from a slow selector (as Chromium's selector statistics name it) to the+source that probably wrote it. Text matching only: a guess to start diagnosis from, not proof.++ locate(selector) -> [(path, line, source text, how it matched)] for CSS rules under src/+ has_descendant(sel) -> the :has() arguments that contain a descendant combinator+ anchor_sites(sel) -> where the attributes / classes a :has() is anchored on are set in TSX+ changed_in_branch(path, line) -> True / False / None (None: git could not tell)+"""++from __future__ import annotations++import os+import re+import subprocess+from functools import lru_cache+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+SRC = REPO / "studio" / "frontend" / "src"+# Elements that hold the whole thread: a :has() anchored on one walks every message.+THREAD_ANCESTORS = (+ "[data-wallpaper-workspace]",+ "[data-chat-content-root]",+ "[data-windows-wallpaper-page]",+ ".aui-thread-viewport",+ "[data-chat-page-root]",+ '[data-slot="sidebar-inset"]',+)+++def _strip_comments(text: str) -> str:+ # Keep newlines so line numbers survive.+ return re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags = re.S)+++def split_top(text: str, sep: str = ",") -> list[str]:+ """Split on `sep` outside (), [] and quotes."""+ out, depth, quote, cur = [], 0, "", []+ for ch in text:+ if quote:+ cur.append(ch)+ if ch == quote:+ quote = ""+ continue+ if ch in "\"'":+ quote = ch+ elif ch in "([":+ depth += 1+ elif ch in ")]":+ depth -= 1+ elif ch == sep and depth == 0:+ out.append("".join(cur))+ cur = []+ continue+ cur.append(ch)+ out.append("".join(cur))+ return [s.strip() for s in out if s.strip()]+++def norm(selector: str) -> str:+ s = selector.replace("'", '"')+ s = re.sub(r"\s+", " ", s).strip()+ s = re.sub(r"\s*([>+~,()])\s*", r"\1", s)+ s = re.sub(r"\[\s*([\w-]+)\s*([~|^$*]?=)\s*", r"[\1\2", s)+ s = re.sub(r"=([\w-]+)\]", r'="\1"]', s) # [a=b] -> [a="b"]+ return s+++@lru_cache(maxsize = 1)+def css_rules() -> tuple:+ rules = []+ for path in sorted(SRC.rglob("*.css")):+ text = _strip_comments(path.read_text(encoding = "utf-8", errors = "replace"))+ start = 0+ for i, ch in enumerate(text):+ if ch in "{};":+ if ch == "{":+ prelude = text[start:i]+ stripped = prelude.lstrip()+ if stripped and not stripped.startswith("@"):+ line = text.count("\n", 0, start + len(prelude) - len(stripped)) + 1+ for sel in split_top(stripped.strip()):+ rules.append((str(path.relative_to(REPO)), line, sel, norm(sel)))+ start = i + 1+ return tuple(rules)+++def _tokens(selector: str) -> set[str]:+ return set(re.findall(r"\.[\w-]+|\[[\w-]+|:[\w-]+\(", selector))+++def locate(selector: str, limit: int = 3) -> list[tuple[str, int, str, str]]:+ want = norm(selector)+ rules = css_rules()+ exact = [(p, ln, raw, "exact text match") for p, ln, raw, n in rules if n == want]+ if exact:+ return _dedupe(exact)[:limit]+ # Nested CSS (`&`) and serialization differences: rank by shared classes / attributes.+ toks = _tokens(selector)+ if not toks:+ return []+ scored = []+ for p, ln, raw, n in rules:+ common = toks & _tokens(raw)+ if common:+ scored.append((len(common) / len(toks | _tokens(raw)), p, ln, raw, len(common)))+ scored.sort(reverse = True)+ return _dedupe(+ [+ (p, ln, raw, f"partial match, {k} of {len(toks)} classes / attributes in common")+ for score, p, ln, raw, k in scored+ if score >= 0.4+ ]+ )[:limit]+++def _dedupe(rows: list) -> list:+ seen, out = set(), []+ for row in rows:+ if (row[0], row[1]) not in seen:+ seen.add((row[0], row[1]))+ out.append(row)+ return out+++def _has_args(selector: str) -> list[tuple[str, str]]:+ """(anchor compound, argument) for each :has( in the selector."""+ out = []+ for m in re.finditer(r":has\(", selector):+ depth, j = 1, m.end()+ while j < len(selector) and depth:+ depth += {"(": 1, ")": -1}.get(selector[j], 0)+ j += 1+ arg = selector[m.end() : j - 1]+ out.append((_compound_before(selector[: m.start()]), arg))+ return out+++def _compound_before(head: str) -> str:+ """The compound a pseudo-class at the end of `head` belongs to; climbs out of :not( / :is(."""+ depth, k = 0, len(head)+ while k > 0:+ c = head[k - 1]+ if c in ")]":+ depth += 1+ elif c in "([":+ if depth == 0:+ break+ depth -= 1+ elif depth == 0 and c in " >+~,":+ break+ k -= 1+ if head[k:] or k == 0 or head[k - 1] != "(":+ return head[k:]+ # inside :not( ... ): the anchor is the compound that :not() belongs to+ return _compound_before(re.sub(r":[\w-]+$", "", head[: k - 1]))+++def has_descendant(selector: str) -> list[tuple[str, str]]:+ """:has() arguments with a descendant combinator: Chromium then searches the anchor's subtree."""+ hits = []+ for anchor, arg in _has_args(selector):+ for part in split_top(arg):+ # No leading combinator means "a descendant anywhere": the whole subtree is searched.+ if part.strip()[:1] not in (">", "+", "~"):+ hits.append((anchor, part.strip()))+ break+ depth, quote = 0, ""+ p = re.sub(r"\s*([>+~])\s*", r"\1", part.strip())+ for i, c in enumerate(p):+ if quote:+ quote = "" if c == quote else quote+ elif c in "\"'":+ quote = c+ elif c in "([":+ depth += 1+ elif c in ")]":+ depth -= 1+ elif c == " " and depth == 0:+ hits.append((anchor, part.strip()))+ break+ else:+ continue+ break+ return hits+++def anchor_sites(anchor: str, limit: int = 3) -> list[tuple[str, int, str]]:+ names = re.findall(r"\[([\w-]+)", anchor) + [c[1:] for c in re.findall(r"\.[\w-]+", anchor)]+ out = []+ for name in names:+ pat = re.compile(re.escape(name) + r"(?![\w-])")+ for path in sorted(SRC.rglob("*.tsx")):+ for i, line in enumerate(+ path.read_text(encoding = "utf-8", errors = "replace").splitlines(), 1+ ):+ if pat.search(line) and not line.lstrip().startswith(("//", "*", "/*")):+ if "querySelector" in line or "closest(" in line:+ continue+ out.append((str(path.relative_to(REPO)), i, line.strip()[:140]))+ if len(out) >= limit:+ return out+ return out+++def utility_uses(selector: str, limit: int = 3) -> list[tuple[str, int, str]]:+ """TSX lines using the escaped class names (Tailwind utilities) in `selector`."""+ classes = [re.sub(r"\\(.)", r"\1", c) for c in re.findall(r"\.((?:\\.|[\w-])+)", selector)]+ classes = [+ c for c in classes if not c.replace("-", "").isalpha() or ":" in c or "[" in c+ ] or classes+ out = []+ for cls in classes:+ pat = re.compile(r"(?<![\w:-])" + re.escape(cls) + r"(?![\w-])")+ for path in sorted(SRC.rglob("*.tsx")):+ for i, line in enumerate(+ path.read_text(encoding = "utf-8", errors = "replace").splitlines(), 1+ ):+ if pat.search(line):+ out.append((str(path.relative_to(REPO)), i, line.strip()[:140]))+ if len(out) >= limit:+ return out+ return out+++def thread_anchor(anchor: str) -> str | None:+ n = norm(anchor)+ for a in THREAD_ANCESTORS:+ if norm(a) in n:+ return a+ return None+++@lru_cache(maxsize = 64)+def _changed_ranges(path: str) -> tuple | None:+ base = os.environ.get("GITHUB_BASE_REF") or "main"+ for ref in (f"origin/{base}...HEAD", "HEAD^1"):+ try:+ diff = subprocess.run(+ ["git", "-C", str(REPO), "diff", "--unified=0", ref, "--", path],+ capture_output = True,+ text = True,+ timeout = 30,+ )+ except Exception: # noqa: BLE001+ return None+ if diff.returncode != 0:+ continue+ return tuple(+ (int(m.group(1)), max(int(m.group(2) or 1), 1))+ for m in re.finditer(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", diff.stdout, re.M)+ )+ return None+++def changed_in_branch(path: str, line: int) -> bool | None:+ ranges = _changed_ranges(path)+ if ranges is None:+ return None+ return any(start <= line < start + count for start, count in ranges)+++STATE = re.compile(r":(?:hover|focus|focus-visible|focus-within|active|checked)\b|\[data-state")+++def suspect_rules(limit: int = 5) -> list[tuple[int, str, int, str, list[str]]]:+ """:has() rules ranked by how likely they are to restyle much of the page on each keystroke."""+ rows = []+ for path, line, raw, _ in css_rules():+ if ":has(" not in raw:+ continue+ reasons, score = [], 0+ for anchor, _arg in has_descendant(raw)[:1]:+ where = thread_anchor(anchor)+ if where:+ reasons.append(f"searches all descendants of {where}, which holds the thread")+ score += 3+ else:+ reasons.append(f"searches all descendants of `{anchor[:60]}`")+ score += 1+ if any(STATE.search(arg) for _, arg in _has_args(raw)):+ reasons.append(+ "its :has() argument depends on hover / focus / open state, which input flips"+ )+ score += 2+ tail = raw[raw.rfind(")") + 1 :].strip()+ if " " in tail or re.search(r":not\(|\[class\*=|\*", tail):+ reasons.append(+ "its subject is a broad descendant of the :has() element, so one change re-matches that subtree"+ )+ score += 1+ if changed_in_branch(path, line):+ reasons.insert(0, "changed on this branch")+ score += 4+ if score:+ rows.append((score, path, line, raw, reasons))+ rows.sort(key = lambda r: (-r[0], r[1], r[2]))+ return rows[:limit]+++def explain(selector: str, indent: str = " ") -> list[str]:+ """Human-readable guesses for one slow selector."""+ lines = []+ found = locate(selector)+ if found:+ lines.append(+ f"{indent}It is possible this section caused the issue, but we cannot be sure (a text match):"+ )+ for path, line, raw, how in found:+ changed = changed_in_branch(path, line)+ tag = {True: ", changed on this branch", False: ", unchanged on this branch", None: ""}[+ changed+ ]+ lines.append(f"{indent} {path}:{line} ({how}{tag})")+ lines.append(f"{indent} {raw[:220]}")+ else:+ uses = utility_uses(selector)+ if uses:+ lines.append(+ f"{indent}It is possible these class names caused the issue, but we cannot be sure "+ "(a Tailwind utility; text match on its class):"+ )+ lines += [f"{indent} {p}:{ln} {txt}" for p, ln, txt in uses]+ else:+ lines.append(+ f"{indent}No CSS rule or class under studio/frontend/src matched this selector's text; "+ "it may come from a dependency's stylesheet."+ )+ for anchor, arg in has_descendant(selector):+ where = thread_anchor(anchor)+ lines.append(+ f"{indent}Pattern: `:has({arg[:120]})` on `{anchor[:160]}` searches all descendants (no leading `>`, "+ "or a space inside), so Chromium re-walks everything under that element after each DOM change, "+ "whether or not anything matches."+ )+ if where:+ sites = anchor_sites(where)+ site = f" (first found in {sites[0][0]}:{sites[0][1]})" if sites else ""+ lines.append(+ f"{indent} `{where}`{site} holds the whole thread, so every keystroke walks every message."+ )+ return linesdiff --git a/tests/studio/playwright_long_thread_gate.py b/tests/studio/playwright_long_thread_gate.pynew file mode 100644index 00000000000..f3d8be9dd5f--- /dev/null+++ b/tests/studio/playwright_long_thread_gate.py@@ -0,0 +1,583 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Gate: typing in a long chat must not cost more as the chat grows.++The production build of smoke-thread-weight.html (vite.long-thread.config.ts) is seeded with an+agent-style history (open reasoning, tool cards, web sources, compaction markers, code, KaTeX,+tables) inside the app's own ancestors (`?shell=1`). While keys are typed, Chromium's selector+statistics give the time spent matching each selector. Two checks, both blind to how fast the+runner is:++ 1. `:has()` matching per keystroke in the large chat stays under MAX_HAS_MS. A descendant+ `:has()` on an element that holds the thread (#16603) walks every message on every key:+ 74-84 ms per key at 200 turns, against 0.2 ms once fixed.+ 2. Total selector matching per keystroke does not grow with the chat: large / small at most+ MAX_MATCH_RATIO for LARGE / SMALL times the turns (healthy: 1.00x).++Fails fast: the large chat is measured first and a blown `:has()` budget stops the run there; an+untraced pre-check shortens the traced window to 2 keys on a slow page; a second repeat runs only+when the ratio is close to its limit. A failure prints the measured numbers, how far over budget+they are, and the selectors responsible with their cost per key; selectors tried on most of the+DOM are marked as likely victims of a whole-page restyle. It then pins the trigger down by+removing :has() rules from the stylesheet before fresh page loads (a bisection, time-boxed) and+names the rule whose removal makes typing cheap, with the CSS file and line it probably comes from.+"""++from __future__ import annotations++import functools+import http.server+import json+import os+import statistics+import subprocess+import sys+import threading+import time+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _css_culprit import explain, has_descendant, thread_anchor # noqa: E402+from _playwright_robust import chromium_launch_args # noqa: E402++REPO = Path(__file__).resolve().parents[2]+FRONTEND = REPO / "studio" / "frontend"+DIST = Path(os.environ.get("LONG_THREAD_DIST", REPO / ".playwright-cli" / "long-thread-production"))+SMALL = int(os.environ.get("LONG_THREAD_SMALL", "40"))+LARGE = int(os.environ.get("LONG_THREAD_LARGE", "200"))+# Measured (40 -> 200 turns, per keystroke): with the #16603 rule, selector matching 79-80 ->+# 423-472 ms (5.3-6.0x) and :has() 74-84 ms; healthy, 0.7-0.9 -> 0.7-1.0 ms (1.00x) and 0.2 ms.+MAX_MATCH_RATIO = float(os.environ.get("LONG_THREAD_MAX_MATCH_RATIO", "2.0"))+MAX_HAS_MS = float(os.environ.get("LONG_THREAD_MAX_HAS_MS", "5.0"))+# A ratio inside this band gets a second interleaved repeat before the verdict; outside it, one+# measurement is decisive (healthy runs read 1.00x, the regression 5.3-6.0x).+RECHECK_BAND = (1.5, 3.0)+# Keeps sub-millisecond noise from becoming a large ratio.+MATCH_FLOOR_MS = 2.0+HEALTHY = "healthy reference: 0.7-1.0 ms/key selector matching, 1.00x, 0.2 ms/key :has()"+KEYS = "the quick "+PRECHECK_KEYS = "ab"+# Untraced style recalc per key above this on the large chat means a regressed build (healthy:+# 1-15 ms; #16603: 140-1000 ms); its traced window is then 2 keys, not 10. Above EXTREME the+# page is hundreds of times a healthy one and fails on the untraced number alone.+SLOW_STYLE_MS = 60.0+EXTREME_STYLE_MS = 300.0+# Rule bisection on a failure: a smaller chat, 3 keys per probe, a time budget.+PIN_TURNS = 60+PIN_KEYS = "abc"+PIN_BUDGET_S = 240.0+TOP = 5+SEED_OPTIONS = {"agent": {"rounds": 2, "compactionEvery": 10, "sources": True, "rich": True}}+HINT = (+ "Typical cause: a :has() whose argument has a descendant combinator (a space), anchored on an "+ "element that holds the thread ([data-wallpaper-workspace], [data-chat-content-root], "+ "[data-windows-wallpaper-page], .aui-thread-viewport). Chromium walks every message on each "+ "keystroke even when nothing matches. Use a child-only path (`:has(> a > b)`) or a flag on "+ "<html> set from a layout effect (see useMarkChatWelcome in features/chat-background)."+)+++def build() -> None:+ if os.environ.get("LONG_THREAD_DIST"):+ return+ # npx is npx.cmd on Windows, which CreateProcess only finds through the shell.+ subprocess.run(+ ["npx", "vite", "build", "--config", "vite.long-thread.config.ts"],+ cwd = FRONTEND,+ check = True,+ shell = os.name == "nt",+ )+++def serve(root: Path) -> tuple[http.server.ThreadingHTTPServer, str]:+ handler = functools.partial(_QuietHandler, directory = str(root))+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)+ threading.Thread(target = server.serve_forever, daemon = True).start()+ return server, f"http://127.0.0.1:{server.server_address[1]}"+++class _QuietHandler(http.server.SimpleHTTPRequestHandler):+ def log_message(self, *args) -> None: # noqa: D401+ pass+++def metrics(cdp) -> dict:+ return {m["name"]: m["value"] for m in cdp.send("Performance.getMetrics")["metrics"]}+++# The stylesheet is edited as text before the page loads: rules switched off in a page that has+# already rendered leave Chromium's :has() flags on its elements, so the cost stays (measured).+SHEET_RULES_JS = """(text) => {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(text);+ const out = [];+ const walk = (list, path) => {+ for (let i = 0; i < list.length; i++) {+ const r = list[i];+ const p = path.concat(i);+ if (typeof r.selectorText === 'string' && r.selectorText.includes(':has(')) out.push({p, s: r.selectorText});+ if (r.cssRules && r.cssRules.length) walk(r.cssRules, p);+ }+ };+ walk(sheet.cssRules, []);+ return out;+}"""+SHEET_WITHOUT_JS = """([text, paths]) => {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(text);+ for (const p of paths) {+ let list = sheet.cssRules, rule = null;+ for (const i of p) { rule = list[i]; list = rule.cssRules; }+ if (rule) rule.selectorText = '.__long_chat_gate_disabled__';+ }+ return [...sheet.cssRules].map((r) => r.cssText).join('\\n');+}"""+++def main_stylesheet(dist: Path) -> tuple[str, str] | None:+ """(URL path, text) of the built stylesheet that carries the :has() rules."""+ best = None+ for css in (dist / "assets").glob("*.css"):+ text = css.read_text(encoding = "utf-8", errors = "replace")+ if ":has(" in text and (best is None or len(text) > len(best[1])):+ best = (f"/assets/{css.name}", text)+ return best+++def open_thread(+ browser,+ base: str,+ turns: int,+ css: tuple[str, str] | None = None,+):+ ctx = browser.new_context(viewport = {"width": 1440, "height": 900})+ if css is not None:+ path, body = css+ ctx.route(+ f"{base}{path}",+ lambda route: route.fulfill(status = 200, body = body, content_type = "text/css"),+ )+ page = ctx.new_page()+ page.goto(f"{base}/smoke-thread-weight.html?shell=1", wait_until = "load")+ page.wait_for_function("() => !!window.__threadWeight", timeout = 60_000)+ count = turns * 2+ page.evaluate("([n, o]) => window.__threadWeight.seed(n, o)", [count, SEED_OPTIONS])+ page.wait_for_function(+ "(n) => window.__threadWeight.messageCount() >= n", arg = count, timeout = 120_000+ )+ page.wait_for_timeout(1500 if css is not None else 2500)+ cdp = ctx.new_cdp_session(page)+ cdp.send("Performance.enable")+ box = page.locator(".aui-composer-input").first+ box.click()+ # Focusing the composer restyles focus-dependent rules once, across the thread; that one-off+ # is not a per-keystroke cost, so let it and a warm-up key land before the window opens.+ page.wait_for_timeout(800)+ page.keyboard.press("x")+ page.keyboard.press("Backspace")+ page.wait_for_timeout(400)+ return ctx, page, cdp+++def style_per_key(cdp, page, keys: str) -> float:+ m0 = metrics(cdp)+ for ch in keys:+ page.keyboard.press("Space" if ch == " " else ch)+ page.wait_for_timeout(60)+ page.wait_for_timeout(200)+ return 1000 * (metrics(cdp)["RecalcStyleDuration"] - m0["RecalcStyleDuration"]) / len(keys)+++def measure(browser, base: str, turns: int) -> dict:+ ctx, page, cdp = open_thread(browser, base, turns)+ shape = page.evaluate("""() => ({+ messages: document.querySelectorAll('[data-role]').length,+ nodes: document.getElementsByTagName('*').length,+ sources: document.querySelectorAll('[data-role="assistant"] a[href^="https://example"]').length,+ reasoning: document.querySelectorAll('.aui-reasoning-root, [data-reasoning]').length,+ code: document.querySelectorAll('pre').length,+ katex: document.querySelectorAll('.katex').length,+ tables: document.querySelectorAll('table').length,+ workspace: !!document.querySelector('[data-wallpaper-workspace] .thread-bottom-fade'),+ })""")+ # Untraced pre-check: selector statistics slow a regressed build ~50x, so a slow page gets a+ # short traced window; the verdict still comes from the traced numbers.+ pre = style_per_key(cdp, page, PRECHECK_KEYS)+ if pre >= EXTREME_STYLE_MS:+ # Hundreds of times a healthy keystroke: one traced key would take minutes and could not+ # change the verdict, so skip tracing and let the pin-down find the rule.+ typed_ok = page.evaluate("() => window.__threadWeight.composerText()") == PRECHECK_KEYS+ ctx.close()+ return {+ "turns": turns,+ "shape": shape,+ "typed_ok": typed_ok,+ "keys": 0,+ "extreme": True,+ "precheck_style_ms": round(pre, 1),+ "typing_s": 0.0,+ "match_ms": None,+ "has_ms": None,+ "style_ms": None,+ "selectors": {},+ }+ keys = KEYS if pre < SLOW_STYLE_MS else KEYS[:2]+ events: list = []+ done: list = []+ cdp.on("Tracing.dataCollected", lambda d: events.extend(d["value"]))+ cdp.on("Tracing.tracingComplete", lambda d: done.append(True))+ m0 = metrics(cdp)+ t0 = time.perf_counter()+ cdp.send(+ "Tracing.start",+ {+ "traceConfig": {+ "includedCategories": ["devtools.timeline", "disabled-by-default-blink.debug"]+ },+ "transferMode": "ReportEvents",+ },+ )+ for ch in keys:+ page.keyboard.press("Space" if ch == " " else ch)+ page.wait_for_timeout(60)+ page.wait_for_timeout(300)+ cdp.send("Tracing.end")+ while not done:+ page.wait_for_timeout(50)+ typing_s = time.perf_counter() - t0+ m1 = metrics(cdp)+ typed_ok = page.evaluate("() => window.__threadWeight.composerText()") == PRECHECK_KEYS + keys+ ctx.close()+ n = len(keys)+ selectors: dict[str, dict] = {}+ for event in events:+ stats = (event.get("args") or {}).get("selector_stats")+ for timing in (stats or {}).get("selector_timings", []):+ row = selectors.setdefault(timing["selector"], {"ms": 0.0, "attempts": 0, "matches": 0})+ row["ms"] += timing.get("elapsed (us)", 0) / 1000 / n+ row["attempts"] += timing.get("match_attempts", 0) / n+ row["matches"] += timing.get("match_count", 0) / n+ return {+ "turns": turns,+ "shape": shape,+ "typed_ok": typed_ok,+ "keys": n,+ "precheck_style_ms": round(pre, 1),+ "typing_s": round(typing_s, 1),+ "match_ms": sum(r["ms"] for r in selectors.values()),+ "has_ms": sum(r["ms"] for s, r in selectors.items() if ":has(" in s),+ "style_ms": 1000 * (m1["RecalcStyleDuration"] - m0["RecalcStyleDuration"]) / n,+ "selectors": selectors,+ }+++def pin_down(+ browser,+ base: str,+ budget_s: float = PIN_BUDGET_S,+) -> list[str]:+ """Find the :has() rules whose removal makes the keystroke cheap, one fresh page per probe.++ Untraced style recalc per key with every :has() rule on (E) and off (F). The cost is often not+ additive: one rule makes the browser restyle a whole subtree and the other rules then pay for+ it. So the search removes rules: bisect for a set whose removal brings the page back near F,+ narrowed to single rules. For each rule found it reports the page without that rule and the+ rule on its own. Up to three rules, time-boxed. Measurements, not a guess.+ """+ started = time.time()+ sheet = main_stylesheet(DIST)+ if sheet is None:+ return [" pin-down: the built stylesheet has no :has() rules to test"]+ css_path, css_text = sheet+ scratch = browser.new_context()+ page = scratch.new_page()+ rules = page.evaluate(SHEET_RULES_JS, css_text)+ paths = [r["p"] for r in rules]+ every = list(range(len(paths)))+ probes = [0]++ def cost(enabled) -> float:+ on = set(enabled)+ probes[0] += 1+ body = page.evaluate(+ SHEET_WITHOUT_JS, [css_text, [p for i, p in enumerate(paths) if i not in on]]+ )+ c, pg, cd = open_thread(browser, base, PIN_TURNS, (css_path, body))+ try:+ return style_per_key(cd, pg, PIN_KEYS)+ finally:+ c.close()++ def without(removed) -> float:+ gone = set(removed)+ return cost([i for i in every if i not in gone])++ try:+ e_all, f_none = cost(every), cost([])+ out = [+ f" pin-down at {PIN_TURNS} turns, untraced style recalc per keystroke: {e_all:.1f} ms with all "+ f"{len(paths)} :has() rules, {f_none:.1f} ms with none of them"+ ]+ if e_all < max(2 * f_none, f_none + 10):+ out.append(+ " switching every :has() rule off does not remove the cost, so the cause is probably "+ "not a :has() rule; see the selectors above"+ )+ return out+ fixed = lambda ms: ms <= max(2 * f_none, f_none + 0.15 * (e_all - f_none)) # noqa: E731+ found: list[int] = []++ def search(cands: list[int], also_removed: list[int]) -> int | None:+ """One rule in `cands` whose removal (with `also_removed`) fixes the page."""+ extra = list(also_removed)+ while len(cands) > 1:+ if time.time() - started > budget_s:+ return None+ first, second = cands[: len(cands) // 2], cands[len(cands) // 2 :]+ if fixed(without(found + extra + first)):+ cands = first+ elif fixed(without(found + extra + second)):+ cands = second+ else:+ # needs something from both halves: keep the second out, find the first's part+ extra += second+ cands = first+ return cands[0] if cands else None++ # Rules that search all descendants of an element holding the thread go first: when+ # removing them fixes the page, the bisection only has to look among them.+ likely = [+ i+ for i, r in enumerate(rules)+ if any(thread_anchor(a) for a, _ in has_descendant(r["s"]))+ ]+ while len(found) < 3 and time.time() - started < budget_s:+ rest = [i for i in every if i not in found]+ if found and fixed(without(found)):+ break+ group = [i for i in likely if i in rest]+ if group and fixed(without(found + group)):+ i = search(group, [])+ else:+ i = search(rest, [])+ if i is None:+ break+ found.append(i)+ for i in found:+ minus, alone = without([i]), cost([i])+ out.append(+ f" Measured: removing only this rule takes the keystroke from {e_all:.1f} to {minus:.1f} ms "+ f"(no :has() rules: {f_none:.1f} ms); this rule on its own costs {alone:.1f} ms:"+ )+ out.append(f" {short(rules[i]['s'], 240)}")+ out += suspects_for(rules[i]["s"])+ if len(found) > 1:+ out.append(+ f" removing all {len(found)} together: {without(found):.1f} ms per keystroke"+ )+ if not found:+ out.append(f" no rule found within the {budget_s:.0f} s budget")+ out.append(f" (pin-down: {probes[0]} probes, {time.time() - started:.0f} s)")+ return out+ finally:+ scratch.close()+++def shape_problems(result: dict) -> list[str]:+ shape, turns = result["shape"], result["turns"]+ out = []+ missing = [k for k in ("reasoning", "sources", "code", "katex", "tables") if not shape[k]]+ if shape["messages"] < turns * 2 or not shape["workspace"] or missing:+ out.append(+ f"fixture did not render what the gate measures at {turns} turns: {shape['messages']} of "+ f"{turns * 2} messages, workspace fade {'present' if shape['workspace'] else 'MISSING'}, "+ f"missing content: {', '.join(missing) or 'none'}"+ )+ if not result["typed_ok"]:+ out.append(f"typed text was lost at {turns} turns")+ return out+++def short(selector: str, width: int = 170) -> str:+ return selector if len(selector) <= width else selector[: width - 3] + "..."+++def top_selectors(result: dict, only_has: bool = False) -> list[str]:+ nodes = max(1, result["shape"]["nodes"])+ rows = [(s, r) for s, r in result["selectors"].items() if not only_has or ":has(" in s]+ rows.sort(key = lambda x: x[1]["ms"], reverse = True)+ out = []+ for s, r in rows[:TOP]:+ share = r["attempts"] / nodes+ tag = (+ f" [tried on {share:.0%} of the DOM: likely restyled because of another rule]"+ if share >= 0.5+ else ""+ )+ out.append(+ f" {r['ms']:8.2f} ms/key {r['attempts']:>10,.0f} match attempts/key {short(s)}{tag}"+ )+ wide = sum(1 for r in result["selectors"].values() if r["attempts"] >= 0.5 * nodes)+ if wide >= 3:+ out.append(+ f" {wide} selectors were tried against at least half of the {nodes:,} elements on every "+ "keystroke: the whole page is being restyled, so the slowest selectors above are probably "+ "victims rather than the cause. The pin-down below switches rules off to find the trigger."+ )+ return out+ return out + suspects([s for s, r in rows[:2] if r["ms"] > 1.0 and r["attempts"] < 0.5 * nodes])+++def suspects_for(selector: str) -> list[str]:+ try:+ return explain(selector, indent = " ")+ except Exception as exc: # noqa: BLE001 - diagnosis must never hide the failure itself+ return [f" (source lookup failed: {exc!r})"]+++def suspects(selectors: list[str]) -> list[str]:+ """Where the slowest selectors probably come from: a text match, so a hint, never a verdict."""+ out = []+ for s in selectors:+ out.append(f" where `{short(s, 120)}` may come from:")+ out += suspects_for(s)+ return out+++def growth(small: dict, large: dict) -> list[str]:+ names = set(small["selectors"]) | set(large["selectors"])+ rows = []+ for s in names:+ a = small["selectors"].get(s, {"ms": 0.0, "attempts": 0})+ b = large["selectors"].get(s, {"ms": 0.0, "attempts": 0})+ rows.append((b["ms"] - a["ms"], s, a, b))+ rows.sort(reverse = True)+ out = [+ f" +{d:7.2f} ms/key {a['ms']:.2f} -> {b['ms']:.2f} ms/key, "+ f"{a['attempts']:,.0f} -> {b['attempts']:,.0f} attempts/key {short(s)}"+ for d, s, a, b in rows[:TOP]+ if d > 0+ ]+ return out + suspects([s for d, s, a, b in rows[:2] if d > 1.0])+++def report(+ runs: dict[int, list[dict]], failures: list[str], details: list[str], started: float+) -> int:+ def med(turns: int, key: str):+ vals = [r[key] for r in runs.get(turns, [])]+ return statistics.median(vals) if vals else None++ lines = [f"long-chat typing gate ({time.time() - started:.0f} s)"]+ for turns in (SMALL, LARGE):+ if runs.get(turns) and runs[turns][-1].get("extreme"):+ r = runs[turns][-1]+ lines.append(+ f" {turns:>3} turns: style recalc {r['precheck_style_ms']:.1f} ms/key untraced, "+ f"{r['shape']['nodes']:,} DOM nodes (tracing skipped)"+ )+ elif runs.get(turns):+ lines.append(+ f" {turns:>3} turns: selector matching {med(turns, 'match_ms'):.2f} ms/key, :has() "+ f"{med(turns, 'has_ms'):.2f} ms/key, style recalc {med(turns, 'style_ms'):.1f} ms/key "+ f"(tracing on; {runs[turns][-1]['precheck_style_ms']:.1f} ms/key untraced), "+ f"{runs[turns][0]['shape']['nodes']:,} DOM nodes, {runs[turns][-1]['keys']} keys traced "+ f"in {runs[turns][-1]['typing_s']} s"+ )+ print("\n".join(lines))+ if failures:+ for f in failures:+ print(f"FAIL: {f}")+ for d in details:+ print(d)+ print(f" {HEALTHY}")+ return 1+ print("PASS: selector work per keystroke does not grow with the chat")+ return 0+++def main() -> int:+ started = time.time()+ build()+ if not (DIST / "smoke-thread-weight.html").exists():+ print(f"FAIL: no production build at {DIST}")+ return 1+ server, base = serve(DIST)+ runs: dict[int, list[dict]] = {SMALL: [], LARGE: []}+ failures: list[str] = []+ details: list[str] = []+ try:+ with sync_playwright() as p:+ browser = p.chromium.launch(args = chromium_launch_args())+ # Large first: a blown :has() budget is decisive on its own and stops the run here.+ large = measure(browser, base, LARGE)+ runs[LARGE].append(large)+ failures += shape_problems(large)+ if large.get("extreme"):+ pre = large["precheck_style_ms"]+ failures.append(+ f"a keystroke costs {pre:.0f} ms of style recalc at {LARGE} turns (untraced); healthy "+ f"builds measure 1-15 ms, so this is at least {pre / 15:.0f}x over. Selector tracing "+ "was skipped: one traced key would take minutes"+ )+ print(f"FAIL (diagnosis follows): {failures[-1]}", flush = True)+ details += pin_down(browser, base)+ details.append(" " + HINT)+ elif large["has_ms"] > MAX_HAS_MS:+ print(+ f"FAIL (diagnosis follows): :has() matching costs {large['has_ms']:.1f} ms per keystroke",+ flush = True,+ )+ failures.append(+ f":has() matching costs {large['has_ms']:.1f} ms per keystroke at {LARGE} turns, "+ f"budget {MAX_HAS_MS:.1f} ms ({large['has_ms'] / MAX_HAS_MS:.1f}x over); "+ f"total selector matching {large['match_ms']:.1f} ms/key"+ )+ details.append(f" most expensive :has() selectors at {LARGE} turns:")+ details += top_selectors(large, only_has = True)+ details += pin_down(browser, base)+ details.append(" " + HINT)+ if not failures:+ small = measure(browser, base, SMALL)+ runs[SMALL].append(small)+ failures += shape_problems(small)+ if not failures:++ def ratio() -> float:+ a = statistics.median(r["match_ms"] for r in runs[SMALL])+ b = statistics.median(r["match_ms"] for r in runs[LARGE])+ return max(b, MATCH_FLOOR_MS) / max(a, MATCH_FLOOR_MS)++ if RECHECK_BAND[0] <= ratio() <= RECHECK_BAND[1]:+ print(+ f"ratio {ratio():.2f}x is near the {MAX_MATCH_RATIO}x limit; repeating",+ flush = True,+ )+ runs[SMALL].append(measure(browser, base, SMALL))+ runs[LARGE].append(measure(browser, base, LARGE))+ r = ratio()+ if r > MAX_MATCH_RATIO:+ a = statistics.median(x["match_ms"] for x in runs[SMALL])+ b = statistics.median(x["match_ms"] for x in runs[LARGE])+ failures.append(+ f"selector matching per keystroke grows with the chat: {a:.2f} ms/key at "+ f"{SMALL} turns -> {b:.2f} ms/key at {LARGE} turns = {r:.2f}x for "+ f"{LARGE / SMALL:.0f}x the turns (limit {MAX_MATCH_RATIO}x, +{b - a:.1f} ms/key)"+ )+ details.append(+ f" selectors whose cost grew most from {SMALL} to {LARGE} turns:"+ )+ details += growth(runs[SMALL][-1], runs[LARGE][-1])+ details += pin_down(browser, base)+ details.append(" " + HINT)+ browser.close()+ finally:+ server.shutdown()+ return report(runs, failures, details, started)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_css_culprit.py b/tests/studio/test_css_culprit.pynew file mode 100644index 00000000000..c3ef066d212--- /dev/null+++ b/tests/studio/test_css_culprit.py@@ -0,0 +1,75 @@+# 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 long-chat gate's source hints: selector text -> CSS rule, and the :has() shape check."""++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++import _css_culprit as culprit # noqa: E402++# Chromium's serialization of the #16603 rule, as its selector statistics report it.+REPORTED = (+ ":is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready] "+ '.chat-wallpaper-image[data-fade="false"]) .thread-bottom-fade'+)+SOURCE = """\+/* a comment { with braces } */+.unrelated { color: red; }++:is([data-wallpaper-workspace],[data-chat-content-root]):has(>.chat-wallpaper[data-ready] .chat-wallpaper-image[data-fade=false]) .thread-bottom-fade,+.other { display: none; }+@media (min-width: 1px) {+ .aui-thread-viewport:has(.aui-thread-welcome-center) { gap: 0; }+}+"""+++def _use(tmp_path, monkeypatch):+ src = tmp_path / "studio" / "frontend" / "src"+ src.mkdir(parents = True)+ (src / "index.css").write_text(SOURCE)+ (src / "root.tsx").write_text('<SidebarProvider data-wallpaper-workspace="" />\n')+ monkeypatch.setattr(culprit, "REPO", tmp_path)+ monkeypatch.setattr(culprit, "SRC", src)+ culprit.css_rules.cache_clear()+++def test_reported_selector_maps_to_its_source_line(tmp_path, monkeypatch):+ _use(tmp_path, monkeypatch)+ [(path, line, raw, how)] = culprit.locate(REPORTED)+ assert path.endswith("index.css") and line == 4 and how == "exact text match"+ assert raw.startswith(":is([data-wallpaper-workspace]")+ text = "\n".join(culprit.explain(REPORTED))+ assert "It is possible this section caused the issue, but we cannot be sure" in text+ assert "index.css:4" in text and "root.tsx:1" in text and "holds the whole thread" in text+++def test_nested_rule_is_found_and_classified(tmp_path, monkeypatch):+ _use(tmp_path, monkeypatch)+ [(path, line, _, _)] = culprit.locate(".aui-thread-viewport:has(.aui-thread-welcome-center)")+ assert line == 7+++def test_descendant_shapes():+ walks = [+ ".a:has(.b)",+ ".a:has(> .b .c)",+ ".a:has(> .b, .c .d)",+ ":is([x]):not(:has(.welcome)) > .w",+ ]+ bounded = [".a:has(> .b)", ".a:has(> .b > .c)", ".a:has(+ .b)", ".a:has(~ .b)", ".a:not(.b)"]+ for sel in walks:+ assert culprit.has_descendant(sel), sel+ for sel in bounded:+ assert not culprit.has_descendant(sel), sel+ [(anchor, _)] = culprit.has_descendant(":is([x]):not(:has(.welcome)) > .w")+ assert anchor == ":is([x])"+++def test_no_match_says_so(tmp_path, monkeypatch):+ _use(tmp_path, monkeypatch)+ text = "\n".join(culprit.explain(".nothing-like-this"))+ assert "No CSS rule or class under studio/frontend/src matched" in text