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: enforce the research browser regression harnesses (#8736)
alkinun7bf8ade2db75
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex aa2161cddc7..87be60fbf3c 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -19,6 +19,12 @@ on:- 'tests/studio/test_frontend_dep_removal.py'- 'tests/studio/playwright_strip_ansi_smoke.py'+ - 'tests/studio/playwright_chat_autoscroll.py'+ - 'tests/studio/playwright_research_freeze.py'+ # Shared lifecycle helpers, and the contract test that keeps verdicts from going unread.+ - 'tests/studio/_playwright_robust.py'+ - 'tests/studio/test_autoscroll_harness_contract.py'+ - 'tests/studio/test_playwright_server_lifecycle.py'- 'scripts/sync_allow_scripts_pins.py'- 'tests/studio/test_sync_allow_scripts_pins.py'- '.github/workflows/studio-frontend-ci.yml'@@ -40,7 +46,8 @@ jobs:build:name: Frontend build + bundle sanityruns-on: ubuntu-latest- timeout-minutes: 10+ # Two browser smokes (~50s) plus the Chromium install now sit inside this.+ timeout-minutes: 20defaults:run:working-directory: studio/frontend@@ -149,18 +156,36 @@ jobs:run: npm test- - name: Install Chromium for tool-output smoke+ - name: Install Chromium for browser smokesworking-directory: ${{ github.workspace }}run: |- python3 -m pip install 'playwright>=1.45,<2'+ python3 -m pip install 'playwright>=1.45,<2' pytestpython3 -m playwright install --with-deps chromium+ # Cheap and browserless, but it imports the harnesses, which import playwright, so it has+ # to sit after the install. Covers the Windows teardown branch no runner here executes.+ - name: Dev-server lifecycle tests+ working-directory: ${{ github.workspace }}+ run: |+ python3 -m pytest tests/studio/test_playwright_server_lifecycle.py \+ tests/studio/test_autoscroll_harness_contract.py -q+- name: Browser smoke for ANSI tool outputworking-directory: ${{ github.workspace }}env:PW_BROWSER: chromiumrun: python3 tests/studio/playwright_strip_ansi_smoke.py+ # Each harness owns its vite dev server, like the ANSI smoke above. Starting one here+ # would background npm, so $! is the wrapper and killing it orphans the node child.+ - name: Browser smoke for chat autoscroll+ working-directory: ${{ github.workspace }}+ run: python3 tests/studio/playwright_chat_autoscroll.py++ - name: Browser smoke for research freeze+ working-directory: ${{ github.workspace }}+ run: python3 tests/studio/playwright_research_freeze.py+- name: Buildrun: npm run builddiff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex ee3952ed0bc..beb31bd09d9 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -28,5 +28,10 @@"@/*": ["./src/*"]}},- "include": ["src"]+ "include": [+ "src",+ "smoke-ansi-main.tsx",+ "smoke-autoscroll-main.tsx",+ "smoke-research-main.tsx"+ ]}diff --git a/tests/studio/_playwright_robust.py b/tests/studio/_playwright_robust.pyindex 356fd9b714f..6380609f18d 100644--- a/tests/studio/_playwright_robust.py+++ b/tests/studio/_playwright_robust.py@@ -8,16 +8,26 @@ directly by the standalone scripts; does NOT depend on pytest.from __future__ import annotations+import atexitimport jsonimport os+import shutil+import signal+import socket+import subprocessimport sysimport threadingimport timeimport urllib.errorimport urllib.request+from collections import dequefrom pathlib import Pathfrom typing import Any, Callable+FRONTEND = Path(__file__).resolve().parents[2] / "studio" / "frontend"+_LIVE_SERVERS: list[subprocess.Popen[str]] = []+_PREV_HANDLERS: dict[int, Any] = {}+# Chromium launch args.# Throttling flags stop Chromium deprioritising CPU/timers when it thinks the# headless window is backgrounded (run 25586583024 stalled inference + render).@@ -102,6 +112,169 @@ def install_view_transition_killer(ctx: Any) -> None:# 60s change-password timeout.+# The smoke pages are dev-server-only, so each harness owns its server. A backgrounded+# `npm run dev &` puts the npm WRAPPER in $!, and killing that orphans the node child+# holding the port and stdout. Hence the process group, stdout drain and SIGKILL escalation.+++def drain_process_output(proc: subprocess.Popen[str], sink: deque[str] | None = None) -> None:+ """Consume vite's output so its pipe cannot fill and wedge; keep the tail for errors."""+ if proc.stdout is not None:+ for line in proc.stdout:+ if sink is not None:+ sink.append(line.rstrip())+++def _port_is_taken(port: int, host: str) -> bool:+ with socket.socket() as probe:+ probe.settimeout(1.0)+ return probe.connect_ex((host, port)) == 0+++def _stop_live_servers() -> None:+ while _LIVE_SERVERS:+ stop_process(_LIVE_SERVERS.pop())+++def _handle_fatal_signal(signum, frame) -> None:+ _stop_live_servers()+ previous = _PREV_HANDLERS.get(signum, signal.SIG_DFL)+ if callable(previous):+ previous(signum, frame)+ return+ signal.signal(signum, signal.SIG_DFL)+ os.kill(os.getpid(), signum)+++def _arm_teardown_signals() -> None:+ """`finally` covers exceptions and SIGINT but not SIGTERM, and a CI cancel sends SIGTERM.+ Without this the server outlives the harness, which is the whole thing being fixed."""+ if _PREV_HANDLERS or os.name == "nt":+ return+ for signum in (signal.SIGTERM, signal.SIGHUP):+ try:+ _PREV_HANDLERS[signum] = signal.signal(signum, _handle_fatal_signal)+ except (ValueError, OSError):+ _PREV_HANDLERS.clear() # not the main thread; leave signals alone+ return+++def start_vite(port: int, *, host: str = "127.0.0.1") -> subprocess.Popen[str]:+ """Start `vite dev` on `port` in its own process group, with stdout drained.++ Refuses an occupied port. --strictPort would make vite exit anyway, and then the+ readiness poll would be talking to whatever else is listening, not to us.+ """+ if _port_is_taken(port, host):+ raise RuntimeError(+ f"{host}:{port} is already serving. Stop it, or move this harness with SMOKE_PORT."+ )+ process_group = (+ {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}+ if os.name == "nt"+ else {"start_new_session": True}+ )+ # shutil.which honours PATHEXT, so this resolves npm.cmd on Windows. CreateProcess cannot+ # run a .cmd directly, so a bare "npm" is a FileNotFoundError there.+ npm = shutil.which("npm") or "npm"+ proc = subprocess.Popen(+ [npm, "run", "dev", "--", "--host", host, "--port", str(port), "--strictPort"],+ cwd = FRONTEND,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ **process_group,+ )+ tail: deque[str] = deque(maxlen = 20)+ proc.vite_tail = tail # type: ignore[attr-defined]+ threading.Thread(target = drain_process_output, args = (proc, tail), daemon = True).start()+ _LIVE_SERVERS.append(proc)+ _arm_teardown_signals()+ atexit.register(_stop_live_servers)+ return proc+++def stop_process(proc: subprocess.Popen[str]) -> None:+ """SIGTERM the process group, escalating to SIGKILL if it does not go."""+ if proc in _LIVE_SERVERS:+ _LIVE_SERVERS.remove(proc)+ if proc.poll() is not None:+ return++ if os.name == "nt":+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T"],+ check = False,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ )+ else:+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except ProcessLookupError:+ return++ try:+ proc.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ if os.name == "nt":+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],+ check = False,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ )+ else:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ # Called from a `finally`: never raise over the failure that sent us here.+ try:+ proc.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ pass+++def wait_for_smoke_page(+ url: str,+ entry: str,+ *,+ proc: subprocess.Popen[str] | None = None,+ timeout_s: float = 120.0,+ info: Callable[[str], None] | None = None,+) -> None:+ """Block until `url` serves a page that really references `entry`.++ Vite's SPA fallback answers 200 with index.html for any path it cannot resolve, so a+ deleted smoke page still looks healthy. Match the module specifier, not the status.+ """+ deadline = time.monotonic() + timeout_s+ last = "no response"+ while time.monotonic() < deadline:+ # Ours died (busy port, missing node_modules): stop instead of polling out the timeout.+ if proc is not None and proc.poll() is not None:+ tail = "\n".join(getattr(proc, "vite_tail", []))+ raise RuntimeError(+ f"vite exited with code {proc.returncode} before serving {url}\n{tail}"+ )+ try:+ with urllib.request.urlopen(url, timeout = 3.0) as r:+ body = r.read().decode("utf-8", errors = "replace")+ if r.status == 200 and entry in body:+ if info is not None:+ info(f"{url} ready (serves {entry})")+ return+ last = (+ f"status={r.status}, {entry} "+ f"{'present' if entry in body else 'MISSING (SPA fallback?)'}"+ )+ except Exception as exc:+ last = f"{type(exc).__name__}: {exc}"+ time.sleep(0.5)+ raise RuntimeError(f"vite did not serve {url} referencing {entry} within {timeout_s}s ({last})")++def _http_get_status_and_body(url: str, timeout: float) -> tuple[int, dict | None]:try:with urllib.request.urlopen(url, timeout = timeout) as r:diff --git a/tests/studio/playwright_chat_autoscroll.py b/tests/studio/playwright_chat_autoscroll.pyindex 19754045c01..c47c28ad50a 100644--- a/tests/studio/playwright_chat_autoscroll.py+++ b/tests/studio/playwright_chat_autoscroll.py@@ -26,8 +26,10 @@ not the WebKitGTK webview the desktop app embeds, so what transfers is the work,absolute timings.Run:- cd studio/frontend && npx vite --port 5193 &- SMOKE_BASE_URL=http://127.0.0.1:5193 python tests/studio/playwright_chat_autoscroll.py+ python tests/studio/playwright_chat_autoscroll.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@@ -41,9 +43,19 @@ from pathlib import Pathfrom playwright.sync_api import sync_playwrightsys.path.insert(0, str(Path(__file__).resolve().parent))-from _playwright_robust import chromium_launch_args # noqa: E402--BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:5193")+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5193"))+# 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.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip()+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNALLABEL = os.environ.get("SMOKE_LABEL", "tree")OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-chat-autoscroll"))OUT.mkdir(parents = True, exist_ok = True)@@ -137,12 +149,14 @@ def run() -> dict:page.wait_for_timeout(800)results["seeded"] = page.evaluate("window.__autoscroll.metrics()")- # 1. Streaming.+ # 1. Streaming. Clock and counter start and stop together inside the page, so they+ # bracket one interval; split across round trips they do not, and the rate drifts.before = metrics(cdp)- page.evaluate(- """async ([count, gap]) => {+ streamed = page.evaluate(+ """async ([count, gap, tailMs]) => {window.__longTasks.length = 0;window.__rafCount = 0;+ const started = performance.now();for (let i = 0; i < count; i += 1) {window.__autoscroll.token("token " + i + " ");// A finished message every 20 tokens, so childList mutations are in the mix@@ -150,16 +164,19 @@ def run() -> dict:if (i > 0 && i % 20 === 0) window.__autoscroll.block();await new Promise((r) => setTimeout(r, gap));}+ // The tail is part of the measurement: re-arming after the last token is the+ // failure mode, so count those frames rather than stopping the clock early.+ await new Promise((r) => setTimeout(r, tailMs));+ return { wallMs: performance.now() - started, rafCallbacks: window.__rafCount };}""",- [TOKEN_COUNT, TOKEN_GAP_MS],+ [TOKEN_COUNT, TOKEN_GAP_MS, 1200],)- page.wait_for_timeout(1200)after = metrics(cdp)long_tasks = page.evaluate("window.__longTasks")results["stream"] = {"tokens": TOKEN_COUNT,- "wall_ms": TOKEN_COUNT * TOKEN_GAP_MS,- "raf_callbacks": page.evaluate("window.__rafCount"),+ "wall_ms": round(streamed["wallMs"], 1),+ "raf_callbacks": streamed["rafCallbacks"],"long_tasks": len(long_tasks),"worst_long_task_ms": round(max((t["duration"] for t in long_tasks), default = 0.0), 1),"layout_count": delta(before, after, "LayoutCount"),@@ -245,7 +262,19 @@ def run() -> dict:def main() -> int:- results = run()+ 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-autoscroll.html", "smoke-autoscroll-main.tsx", proc = vite, info = info+ )+ results = run()+ finally:+ if vite is not None:+ stop_process(vite)+ info("vite stopped")stream_seconds = max(0.001, results["stream"]["wall_ms"] / 1000)raf_rate = results["stream"]["raf_callbacks"] / stream_secondsresults["stream"]["raf_per_second"] = round(raf_rate, 1)diff --git a/tests/studio/playwright_research_freeze.py b/tests/studio/playwright_research_freeze.pyindex b0d99ee2bc4..a7108a6323d 100644--- a/tests/studio/playwright_research_freeze.py+++ b/tests/studio/playwright_research_freeze.py@@ -18,8 +18,10 @@ MarkdownPreview against the real store, so nothing here is a mock of the code unagainst a vite dev server; no backend, no auth, no GPU.Run:- cd studio/frontend && npx vite --port 5183 &- SMOKE_BASE_URL=http://127.0.0.1:5183 python tests/studio/playwright_research_freeze.py+ python tests/studio/playwright_research_freeze.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@@ -33,9 +35,19 @@ from pathlib import Pathfrom playwright.sync_api import sync_playwrightsys.path.insert(0, str(Path(__file__).resolve().parent))-from _playwright_robust import chromium_launch_args # noqa: E402+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)-BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:5183")+PORT = int(os.environ.get("SMOKE_PORT", "5183"))+# 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.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip()+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNALLABEL = os.environ.get("SMOKE_LABEL", "tree")OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-research-freeze"))OUT.mkdir(parents = True, exist_ok = True)@@ -55,6 +67,11 @@ MAX_STREAM_RAF_PER_SECOND = float(os.environ.get("SMOKE_MAX_RAF_PER_S", "45"))# of slack covers a settle check landing just inside the window; more means a loop that never let# go, which is what left the reporter's window unresponsive.MAX_IDLE_RAF_PER_2S = int(os.environ.get("SMOKE_MAX_IDLE_RAF", "4"))+# Longest the report work keeps the main thread from servicing a timer. A stall detector,+# not Event Timing input delay: nothing here reads an input timestamp. Measured 131.9ms on+# one box and 342-416ms on a loaded one, so 500 left just 1.2x; 1000 keeps ~2.4x and still+# fails ten times the report size (1518ms at SMOKE_REPORT_SECTIONS=400).+MAIN_THREAD_STALL_BUDGET_MS = int(os.environ.get("SMOKE_REPORT_STALL_BUDGET_MS", "1000"))# A real deep research run's size, with the three costliest things to render: fenced code (shiki),# a table, and display math (KaTeX).@@ -149,10 +166,8 @@ def delta(before: dict[str, float], after: dict[str, float], name: str) -> floatdef run() -> dict:results: dict = {"label": LABEL, "base": BASE}with sync_playwright() as p:- # Headed under Xvfb by default (SMOKE_HEADLESS=1 to override): with no compositor,- # headless Chromium throttles rAF to a few callbacks a second, flattening the per-frame- # loop this file exists to measure.- headless = os.environ.get("SMOKE_HEADLESS", "0") == "1"+ # The timer-driven frame pump above makes headless runs deterministic without Xvfb.+ headless = os.environ.get("SMOKE_HEADLESS", "1") == "1"browser = p.chromium.launch(headless = headless, args = chromium_launch_args())context = browser.new_context(viewport = {"width": 1440, "height": 900})# Deliberately NOT installing the view-transition killer: it forces@@ -176,6 +191,7 @@ def run() -> dict:page.evaluate("window.__research.seed()")page.wait_for_timeout(500)+ activities_before_stream = page.evaluate("window.__research.state().activities")# 1. The streaming phase.before = metrics(cdp)@@ -214,6 +230,7 @@ def run() -> dict:"recalc_style_ms": round(delta(before, after, "RecalcStyleDuration") * 1000, 1),"task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),"activities": page.evaluate("window.__research.state().activities"),+ "activities_before": activities_before_stream,}# 2. Idle after the stream: the follow loop must stop when the list goes quiet.@@ -225,10 +242,43 @@ def run() -> dict:report = build_report(int(os.environ.get("SMOKE_REPORT_SECTIONS", "40")))before = metrics(cdp)page.evaluate("window.__longTasks.length = 0")- page.evaluate("md => window.__research.publishReport(md)", report)- # A click during the parse: if the main thread is blocked this lands late but must land.- page.click('[data-smoke="click-probe"]')+ clicks_before_report = page.evaluate("window.__research.clicks()")+ # The probe does not click: a synthetic element.click() skips hit testing, so it lands+ # even with `body { pointer-events: none }` stranded, the freeze under test.+ page.evaluate(+ """md => {+ window.__reportStallMs = 0;+ let previous = performance.now();+ const probe = () => {+ const now = performance.now();+ window.__reportStallMs = Math.max(+ window.__reportStallMs,+ now - previous,+ );+ previous = now;+ window.__reportStallProbe = setTimeout(probe, 16);+ };+ window.__reportStallProbe = setTimeout(probe, 16);+ window.__research.publishReport(md);+ }""",+ report,+ )+ # A real, hit-tested input event: lands late under a blocked thread, but it must land.+ # Record a blocked click as a verdict; raising would lose every other measurement.+ try:+ page.click('[data-smoke="click-probe"]', timeout = 10_000)+ report_click_landed = True+ except Exception as exc:+ report_click_landed = False+ info(f"the click during the report parse never became actionable: {exc!r}")page.wait_for_timeout(3000)+ # Disarm only after the window closes, so a stall at its very end is still sampled.+ page.evaluate(+ """() => {+ clearTimeout(window.__reportStallProbe);+ window.__reportStallMs = Math.max(window.__reportStallMs, 0);+ }"""+ )after = metrics(cdp)long_tasks = page.evaluate("window.__longTasks")results["report"] = {@@ -236,7 +286,9 @@ def run() -> dict:"long_tasks": len(long_tasks),"worst_long_task_ms": round(max((t["duration"] for t in long_tasks), default = 0.0), 1),"task_ms": round(delta(before, after, "TaskDuration") * 1000, 1),- "clicks_registered": page.evaluate("window.__research.clicks()"),+ "main_thread_stall_ms": round(page.evaluate("window.__reportStallMs"), 1),+ "clicks_registered": page.evaluate("window.__research.clicks()") - clicks_before_report,+ "click_landed": report_click_landed,"rendered": page.evaluate("() => Boolean(document.querySelector('[data-smoke=\\\"report\\\"] h1'))"),@@ -317,7 +369,19 @@ def run() -> dict:def main() -> int:- results = run()+ 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-research.html", "smoke-research-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")info(json.dumps(results, indent = 2))@@ -327,9 +391,9 @@ def main() -> int:stream = results["stream"]# A list that ingested nothing has nothing to follow, so it measures zero frames and clears# both budgets below. Recorded and unread was false-green; assert it.- if stream["activities"] < 1:+ if stream["activities"] <= stream["activities_before"]:failures.append(- "the run ingested no activities; the frame budgets below measured an empty list"+ "the stream added no activities; the frame budgets below measured no workload")# Without these two the file records the per-frame cost and passes regardless, which is how# the original loop shipped: the numbers were there, nothing read them.@@ -365,8 +429,24 @@ def main() -> int:failures.append("the report never rendered")# The modal checks below compare click counts against a baseline, so they still pass if this# one was swallowed. Responsiveness during the report parse is the reported symptom; assert it.+ # Hit-tested, so a stranded `body { pointer-events: none }` fails here; a synthetic+ # element.click() would land straight on the handler and pass on that same tree.+ if not results["report"]["click_landed"]:+ failures.append(+ "a real click during the report parse never became actionable; the window was "+ "not taking input"+ )if results["report"]["clicks_registered"] < 1:failures.append("the click during the report parse never reached its handler")+ if results["report"]["main_thread_stall_ms"] > MAIN_THREAD_STALL_BUDGET_MS:+ failures.append(+ f"report rendering stalled the main thread for "+ f"{results['report']['main_thread_stall_ms']}ms, over the "+ f"{MAIN_THREAD_STALL_BUDGET_MS}ms budget"+ )+ # Zero means the probe never took a second sample: the budget above measured nothing.+ if results["report"]["main_thread_stall_ms"] <= 0:+ failures.append("the stall probe recorded no samples; the budget above measured nothing")detach = results["detach"]if not detach["overflowing"]:failures.append("the activity list never overflowed; the detach checks proved nothing")diff --git a/tests/studio/playwright_strip_ansi_smoke.py b/tests/studio/playwright_strip_ansi_smoke.pyindex 5871f02c1dc..9c9a51698ab 100644--- a/tests/studio/playwright_strip_ansi_smoke.py+++ b/tests/studio/playwright_strip_ansi_smoke.py@@ -7,22 +7,25 @@ from __future__ import annotationsimport os-import signal-import subprocessimport sys-import threading-import time-import urllib.error-import urllib.requestfrom pathlib import Pathfrom playwright.sync_api import expect, sync_playwrightsys.path.insert(0, str(Path(__file__).resolve().parent))-from _playwright_robust import chromium_launch_args # noqa: E402+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)-FRONTEND = Path(__file__).resolve().parents[2] / "studio" / "frontend"-BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:8000")+# 8000 collides with whatever else is on a shared box; sit by chat (5193) and research (5183).+PORT = int(os.environ.get("SMOKE_PORT", "5203"))+# Unset: start and stop our own server. Set: drive that one and leave it running.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip()+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNALART = Path(os.environ.get("PW_ART_DIR", "logs/playwright-ansi-smoke"))SECTIONS = ("tool-result-output",@@ -38,86 +41,15 @@ def info(msg: str) -> None:print(f"[ansi-smoke] {msg}", flush = True)-def wait_for_vite(timeout_s: float = 120.0) -> None:- url = f"{BASE}/smoke-ansi.html"- deadline = time.time() + timeout_s- while time.time() < deadline:- try:- with urllib.request.urlopen(url, timeout = 2) as response:- if response.status == 200:- return- except (urllib.error.URLError, TimeoutError):- pass- time.sleep(0.5)- raise RuntimeError(f"vite dev server did not become ready at {url}")---def drain_process_output(proc: subprocess.Popen[str]) -> None:- if proc.stdout is not None:- for _ in proc.stdout:- pass---def start_vite() -> subprocess.Popen[str]:- process_group = (- {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}- if os.name == "nt"- else {"start_new_session": True}- )- proc = subprocess.Popen(- ["npm", "run", "dev", "--", "--host", "127.0.0.1", "--port", "8000", "--strictPort"],- cwd = FRONTEND,- stdout = subprocess.PIPE,- stderr = subprocess.STDOUT,- text = True,- **process_group,- )- threading.Thread(target = drain_process_output, args = (proc,), daemon = True).start()- return proc---def stop_process(proc: subprocess.Popen[str]) -> None:- if proc.poll() is not None:- return-- if os.name == "nt":- subprocess.run(- ["taskkill", "/PID", str(proc.pid), "/T"],- check = False,- stdout = subprocess.DEVNULL,- stderr = subprocess.DEVNULL,- )- else:- try:- os.killpg(proc.pid, signal.SIGTERM)- except ProcessLookupError:- return-- try:- proc.wait(timeout = 10)- except subprocess.TimeoutExpired:- if os.name == "nt":- subprocess.run(- ["taskkill", "/PID", str(proc.pid), "/T", "/F"],- check = False,- stdout = subprocess.DEVNULL,- stderr = subprocess.DEVNULL,- )- else:- try:- os.killpg(proc.pid, signal.SIGKILL)- except ProcessLookupError:- pass- proc.wait(timeout = 10)--def main() -> None:ART.mkdir(parents = True, exist_ok = True)- info(f"starting vite dev server in {FRONTEND}")- vite = start_vite()+ if OWNS_SERVER:+ info(f"starting vite dev server on port {PORT}")+ vite = start_vite(PORT) if OWNS_SERVER else Nonetry:- wait_for_vite()- info(f"vite ready at {BASE}")+ wait_for_smoke_page(+ f"{BASE}/smoke-ansi.html", "smoke-ansi-main.tsx", proc = vite, info = info+ )with sync_playwright() as playwright:browser_name = os.environ.get("PW_BROWSER", "chromium").lower()@@ -142,7 +74,8 @@ def main() -> None:info("all production panes rendered clean text (no ANSI escapes)")browser.close()finally:- stop_process(vite)+ if vite is not None:+ stop_process(vite)if __name__ == "__main__":diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.pyindex 3120e1243c8..96637b980a0 100644--- a/tests/studio/test_autoscroll_harness_contract.py+++ b/tests/studio/test_autoscroll_harness_contract.py@@ -46,7 +46,42 @@ def test_research_freeze_asserts_the_dialog_took_the_modal_layer() -> None:def test_research_freeze_asserts_the_stream_had_something_to_follow() -> None:# An empty activity list runs no follow loop, so it clears the frame budgets by measuring- # nothing.+ # nothing. `seed()` leaves activities behind, so the count has to be compared against the+ # pre-stream baseline rather than against zero.main = verdict("playwright_research_freeze.py")assert 'stream["raf_per_second"]' in mainassert 'stream["activities"]' in main+ assert 'stream["activities_before"]' in main+++def test_research_freeze_asserts_the_report_stall_and_its_own_probe() -> None:+ # The stall budget is only a budget if a stall of zero fails too: no second sample means+ # the probe measured nothing and the comparison below it passes on any tree.+ main = verdict("playwright_research_freeze.py")+ assert 'results["report"]["main_thread_stall_ms"] > MAIN_THREAD_STALL_BUDGET_MS' in main+ assert 'results["report"]["main_thread_stall_ms"] <= 0' in main+++def test_research_freeze_keeps_a_hit_tested_click_in_the_report_phase() -> None:+ # A synthetic element.click() skips hit testing and passes on a stranded+ # `pointer-events: none` tree, so the verdict must read actionability, not just the counter.+ source_text = source("playwright_research_freeze.py")+ assert "page.click('[data-smoke=\"click-probe\"]'" in source_text+ main = verdict("playwright_research_freeze.py")+ assert 'results["report"]["click_landed"]' in main+ assert 'results["report"]["clicks_registered"]' in main+++def test_harnesses_own_their_dev_server() -> None:+ # A server started beside the harness leaves the node child alive when the wrapper is+ # killed, stranding the port and the step's stdout. Each harness owns its own instead.+ for name in (+ "playwright_chat_autoscroll.py",+ "playwright_research_freeze.py",+ "playwright_strip_ansi_smoke.py",+ ):+ text = source(name)+ assert "start_vite" in text, f"{name} does not start its own server"+ 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"diff --git a/tests/studio/test_playwright_server_lifecycle.py b/tests/studio/test_playwright_server_lifecycle.pynew file mode 100644index 00000000000..5af4cfc2fc3--- /dev/null+++ b/tests/studio/test_playwright_server_lifecycle.py@@ -0,0 +1,196 @@+# 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 dev-server lifecycle the browser smokes share.++Linux CI exercises the POSIX path only, and the Windows path is the one nobody runs until it+is broken on someone's machine. These drive both by injecting `os.name`, so the branch that+picks CREATE_NEW_PROCESS_GROUP and taskkill is checked on every run.++Everything here is monkeypatched: no npm, no browser, no sockets bound.+"""++from __future__ import annotations++import signal+import subprocess+import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parent))+import _playwright_robust as robust # noqa: E402++# Unix-only, so a Windows interpreter cannot name it even to drive the POSIX branch.+SIGKILL = getattr(signal, "SIGKILL", 9)++HARNESSES = (+ "playwright_chat_autoscroll",+ "playwright_research_freeze",+ "playwright_strip_ansi_smoke",+)+++class _FakeProc:+ """A child that never dies, so both escalation steps are reachable."""++ def __init__(self) -> None:+ self.pid = 4242+ self.stdout = None+ self.returncode = None++ def poll(self):+ return None++ def wait(self, timeout = None):+ raise subprocess.TimeoutExpired("vite", timeout or 0)+++def no_signals(monkeypatch):+ monkeypatch.setattr(robust, "_arm_teardown_signals", lambda: None)+ monkeypatch.setattr(robust, "_LIVE_SERVERS", [])+++def posix_branch(monkeypatch, no_signals):+ """Drive the POSIX teardown from any host: os.killpg and signal.SIGKILL are Unix-only."""+ monkeypatch.setattr(robust.os, "name", "posix")+ monkeypatch.setattr(robust.signal, "SIGKILL", SIGKILL, raising = False)++[email protected]("osname", ["posix", "nt"])+def test_start_vite_picks_the_platform_process_group(monkeypatch, no_signals, osname) -> None:+ captured: dict = {}+ monkeypatch.setattr(robust.os, "name", osname)+ monkeypatch.setattr(robust, "_port_is_taken", lambda port, host: False)+ monkeypatch.setattr(+ robust.threading, "Thread", lambda **kw: type("T", (), {"start": lambda self: None})()+ )+ monkeypatch.setattr(+ robust.subprocess, "Popen", lambda cmd, **kw: captured.update(cmd = cmd, kw = kw) or _FakeProc()+ )+ if osname == "nt":+ monkeypatch.setattr(robust.subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200, raising = False)++ robust.start_vite(5199)++ assert "--strictPort" in captured["cmd"], "a drifting port must fail, not pick another"+ if osname == "nt":+ assert captured["kw"]["creationflags"] == 0x200+ assert "start_new_session" not in captured["kw"]+ else:+ # Without its own session, killing the npm wrapper orphans the node child.+ assert captured["kw"]["start_new_session"] is True+ assert "creationflags" not in captured["kw"]+++def test_posix_teardown_signals_the_group_and_escalates(monkeypatch, posix_branch) -> None:+ sent = []+ monkeypatch.setattr(+ robust.os, "killpg", lambda pid, sig: sent.append((pid, sig)), raising = False+ )+ robust.stop_process(_FakeProc())+ assert sent == [(4242, signal.SIGTERM), (4242, SIGKILL)]+++def test_windows_teardown_kills_the_tree_and_escalates(monkeypatch, no_signals) -> None:+ calls = []+ monkeypatch.setattr(robust.os, "name", "nt")+ monkeypatch.setattr(robust.subprocess, "run", lambda cmd, **kw: calls.append(cmd))+ robust.stop_process(_FakeProc())+ assert calls == [+ ["taskkill", "/PID", "4242", "/T"],+ ["taskkill", "/PID", "4242", "/T", "/F"],+ ]+++def test_teardown_never_raises_over_the_failure_that_called_it(monkeypatch, posix_branch) -> None:+ """stop_process runs from a `finally`. A child that outlives SIGKILL must not replace the+ harness's real error with a TimeoutExpired."""+ monkeypatch.setattr(robust.os, "killpg", lambda pid, sig: None, raising = False)+ robust.stop_process(_FakeProc())+++def test_teardown_tolerates_a_process_that_already_vanished(monkeypatch, posix_branch) -> None:+ def gone(pid, sig):+ raise ProcessLookupError++ monkeypatch.setattr(robust.os, "killpg", gone, raising = False)+ robust.stop_process(_FakeProc())+++def test_an_occupied_port_is_refused_rather_than_measured(monkeypatch, no_signals) -> None:+ """--strictPort makes our vite exit, and the readiness poll would then be reading whatever+ else holds the port. Refuse up front instead."""+ monkeypatch.setattr(robust, "_port_is_taken", lambda port, host: True)+ with pytest.raises(RuntimeError, match = "already serving"):+ robust.start_vite(5199)+++def test_readiness_gives_up_as_soon_as_our_server_dies(monkeypatch, no_signals) -> None:+ """Otherwise a dead server costs the full timeout, three times over, per CI run."""++ class Dead:+ returncode = 1+ vite_tail = ["Port 5199 is already in use"]++ def poll(self):+ return 1++ with pytest.raises(RuntimeError, match = "vite exited with code 1") as caught:+ robust.wait_for_smoke_page(+ "http://127.0.0.1:5199/x.html", "x.tsx", proc = Dead(), timeout_s = 30.0+ )+ assert "already in use" in str(caught.value), "vite's own reason should be surfaced"++[email protected]("harness", HARNESSES)+def test_ports_do_not_collide_and_are_overridable(harness) -> None:+ import re+ src = (Path(__file__).resolve().parent / f"{harness}.py").read_text()+ assert re.search(r'SMOKE_PORT",\s*"\d+"', src), f"{harness} has no SMOKE_PORT default"+++def test_every_harness_picks_a_different_default_port() -> None:+ import re++ ports = {}+ for harness in HARNESSES:+ src = (Path(__file__).resolve().parent / f"{harness}.py").read_text()+ ports[harness] = re.search(r'SMOKE_PORT",\s*"(\d+)"', src).group(1)+ assert len(set(ports.values())) == len(HARNESSES), f"default ports collide: {ports}"++[email protected]("harness", HARNESSES)+def test_an_empty_smoke_base_url_means_unset(harness, monkeypatch) -> None:+ """Exported-but-empty is common in shell wrappers. `in os.environ` would call it external+ and then drive "" as the base URL."""+ pytest.importorskip("playwright") # importing a harness pulls in playwright.sync_api+ import importlib++ monkeypatch.setenv("SMOKE_BASE_URL", "")+ module = importlib.reload(importlib.import_module(harness))+ try:+ assert module.BASE.startswith("http://"), f"empty SMOKE_BASE_URL gave BASE={module.BASE!r}"+ finally:+ monkeypatch.delenv("SMOKE_BASE_URL", raising = False)+ importlib.reload(module)++[email protected]("harness", ("playwright_chat_autoscroll", "playwright_research_freeze"))+def test_an_external_smoke_base_url_is_still_honoured(harness, monkeypatch) -> None:+ """The documented pre-existing invocation. A harness that started its own server anyway+ would fail on the busy-port check."""+ pytest.importorskip("playwright")+ import importlib++ monkeypatch.setenv("SMOKE_BASE_URL", "http://127.0.0.1:9999")+ module = importlib.reload(importlib.import_module(harness))+ try:+ assert module.BASE == "http://127.0.0.1:9999"+ assert module.OWNS_SERVER is False+ finally:+ monkeypatch.delenv("SMOKE_BASE_URL", raising = False)+ importlib.reload(module)