diff --git a/.github/scripts/renderer_fixtures.py b/.github/scripts/renderer_fixtures.py new file mode 100755 index 0000000000..4a9bbb9d19 --- /dev/null +++ b/.github/scripts/renderer_fixtures.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Launch the built AppImage under four display fixtures and assert the Wayland +classification it logs. Studio logs to stderr before it needs a window, so each launch runs +until the startup line appears and is then killed; a GUI app never exits on its own, so the +process outliving the check is the expected outcome, not a failure.""" +import os, pathlib, signal, socket, subprocess, sys, tempfile, time + +APPIMAGE = sys.argv[1] +STARTED = "Unsloth desktop app starting" +WAYLAND = "Wayland session" + + +def launch(env_overrides): + """Return the renderer decision line, or "" when the app applied no workaround.""" + env = dict(os.environ) + for name in ("WAYLAND_DISPLAY", "XDG_RUNTIME_DIR"): + env.pop(name, None) + env.update(env_overrides) + env["APPIMAGE_EXTRACT_AND_RUN"] = "1" + log = pathlib.Path(tempfile.mkstemp(suffix=".log")[1]) + with log.open("w") as sink: + proc = subprocess.Popen(["xvfb-run", "-a", APPIMAGE], env=env, stdout=sink, + stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.time() + 150 + while time.time() < deadline and proc.poll() is None: + if STARTED in log.read_text(errors="replace"): + time.sleep(3) # the decision is logged immediately after the startup line + break + time.sleep(2) + if proc.poll() is None: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + proc.wait(timeout=60) + text = log.read_text(errors="replace") + if STARTED not in text: + sys.exit(f"the AppImage never reached its startup log:\n{text[-3000:]}") + hits = [line for line in text.splitlines() if "for WebKitGTK compatibility" in line] + return hits[0] if hits else "" + + +def runtime_dir(state): + """A directory holding a listening, a stale, or no wayland-0 socket.""" + d = tempfile.mkdtemp() + if state == "none": + return d + sock = socket.socket(socket.AF_UNIX) + sock.bind(os.path.join(d, "wayland-0")) + sock.listen(1) + if state == "stale": + sock.close() # the inode stays behind, as a crashed compositor leaves it + else: + KEEP.append(sock) + return d + + +KEEP = [] + + +def check(name, overrides, wayland_expected): + got = launch(overrides) + # Only the Wayland classification is asserted. A runner whose AppImage cannot load GLES + # legitimately applies the same variable for a different reason, and reading the reason + # rather than the variable keeps that from passing or failing for the wrong cause. + ok = (WAYLAND in got) == wayland_expected + print(f"[{'ok' if ok else 'FAIL'}] {name}: wayland={WAYLAND in got}, " + f"expected {wayland_expected}, log line: {got or '(none)'}", flush=True) + return ok + + +results = [ + check("plain X11, no wayland socket", + {"XDG_RUNTIME_DIR": runtime_dir("none")}, False), + check("live socket named by WAYLAND_DISPLAY", + {"XDG_RUNTIME_DIR": runtime_dir("live"), "WAYLAND_DISPLAY": "wayland-0"}, True), + check("stale socket named by WAYLAND_DISPLAY", + {"XDG_RUNTIME_DIR": runtime_dir("stale"), "WAYLAND_DISPLAY": "wayland-0"}, False), + check("live default socket, no WAYLAND_DISPLAY", + {"XDG_RUNTIME_DIR": runtime_dir("live")}, True), +] +sys.exit(0 if all(results) else 1) diff --git a/.github/scripts/studio_test_kit/README.md b/.github/scripts/studio_test_kit/README.md new file mode 100644 index 0000000000..f065c5b831 --- /dev/null +++ b/.github/scripts/studio_test_kit/README.md @@ -0,0 +1,242 @@ +# studio_test_kit + +A small, vendorable cookbook for driving **Unsloth Studio** end-to-end with +Playwright. Drop these files into your project, read them top-to-bottom, +and you'll know how to script chat flows, generate screenshots + videos, +and run pre/post-PR comparisons. + +This is **not** a generic library. It is intentionally Studio-flavoured +(model picker selectors, localStorage keys, `/api/auth/login` route, +`unsloth studio -p` CLI, etc.). See [Customisation](#customisation) for +the override points if you're targeting a different SPA. + +## What to vendor (15 files) + +Copy the whole `studio_test_kit/` directory. No editable install needed +once on `sys.path`. + +| # | File | Purpose | Read for | +|---|------|---------|----------| +| 1 | `__init__.py` | Public re-exports | API surface overview | +| 2 | `lifecycle.py` | Install Studio at a given `UNSLOTH_STUDIO_HOME` from any git ref; launch on a port; parse bootstrap password from log; wait on `/healthz`. | Two-port pre/post comparison setup | +| 3 | `auth.py` | Backend JWT login + Playwright init-script builder that seeds the 5 `unsloth_*` localStorage keys. Convenience constructors for Gemini / OpenAI / Anthropic. | Studio's auth + provider model | +| 4 | `ui.py` | Playwright primitives: `open_chat` async context manager (video recording + post-close rename + optional mp4 transcode), `pick_model`, `set_pill`, `send_prompt`, `wait_for_stream`, `wait_for_image`, `wait_for_text`, `extract_data_url`. | The Playwright lessons | +| 5 | `flows.py` | High-level scenarios returning `FlowResult`: `multi_turn_chat`, `image_generation`, `tool_pills`, `vision_upload`. | Composable test flows | +| 6 | `compose.py` | Post-processing: PIL `hstack_images`/`vstack_images`, ffmpeg `hstack_videos`/`webm_to_mp4`. | Pre/post side-by-side composition | +| 7 | `examples/explicit_walkthrough.py` | **Start here.** Fully inline end-to-end flow with every Playwright primitive at the call site and "why" comments. No `flows.*` shortcuts. | Tutorial | +| 8 | `examples/multi_turn.py` | Thin: 4-turn chat via `flows.multi_turn_chat` | Pattern after you know the basics | +| 9 | `examples/image_gen.py` | Thin: Nano Banana image-gen, saves decoded PNG | Pattern | +| 10 | `examples/tools_pills.py` | Thin: Search + Code composer pills | Pattern | +| 11 | `examples/side_by_side.py` | Two `install_studio` + two `launch_studio` + same flow on both + ffmpeg hstack | Pre/post PR comparison | +| 12 | `examples/__init__.py` | Empty marker | — | +| 13 | `_self_test.py` | 13 offline regression tests (no live Studio needed) | CI / verifying the kit didn't bit-rot | +| 14 | `_smoke_ui.py` | Live Playwright integration test against an in-process HTTP server (verifies init-script seeding, screenshot, video flush, mp4 transcode) | CI / smoke after vendoring | +| 15 | `README.md` | This document | — | + +## Setup + +```bash +pip install playwright httpx pillow +playwright install chromium + +# Optional but recommended (used for mp4 transcode and side-by-side video): +apt-get install ffmpeg # or: brew install ffmpeg +``` + +Verify the vendoring worked: + +```bash +python -m studio_test_kit._self_test # 13/13 offline regression +python -m studio_test_kit._smoke_ui # live Playwright smoke +``` + +## The model: how Studio authentication and providers work + +You need to understand this in 60 seconds before the Playwright bits +make sense. + +1. **Login is REST, tokens live in localStorage.** Studio exposes + `POST /api/auth/login` taking `{username, password}` and returning + `{access_token, refresh_token}`. The SPA reads those tokens from + localStorage on every request — NOT from cookies. So + `browser_context.add_cookies()` does nothing useful for auth. + `auth.login()` makes the REST call; `auth.seed_init_script()` plants + the tokens in localStorage. + +2. **External providers are localStorage-driven, not server-stored.** The + Settings → Connections UI writes three keys: + + | Key | Value | + |-----|-------| + | `unsloth_chat_external_providers` | JSON array of `{id, providerType, name, baseUrl, models}` | + | `unsloth_chat_external_provider_keys` | `{providerId: plaintextKey}` | + | `unsloth_chat_connections_enabled` | `"true"` / `"false"` | + + Seeding these via `add_init_script` is exactly equivalent to typing + the key into the dialog manually. The frontend then RSA-encrypts the + plaintext key on every request using the public key from `GET + /api/key`, so the plaintext never goes over the wire even though it + sits in localStorage. + +3. **`add_init_script` ordering is what makes seeding work.** The init + script runs on every page navigation BEFORE the SPA's own JS. Plant + AFTER `goto` and you race the SPA's bootstrap — sometimes works, + sometimes silently doesn't. + +## Quickstart + +Assumes Studio is already running on `--port` (use `lifecycle.launch_studio` +to spin it up programmatically — see `examples/side_by_side.py` for that +pattern). + +```bash +export GEMINI_API_KEY=AIza... + +# Tutorial: every primitive inline + commentary. Read this file first. +python -m studio_test_kit.examples.explicit_walkthrough \ + --port 8902 --password 'YourBootstrap!' \ + --model gemini-2.5-flash + +# 4-turn conversation (uses flows.multi_turn_chat) +python -m studio_test_kit.examples.multi_turn \ + --port 8902 --password 'YourBootstrap!' --model gemini-2.5-flash + +# Image generation, saves decoded PNG +python -m studio_test_kit.examples.image_gen \ + --port 8902 --password 'YourBootstrap!' \ + --model gemini-2.5-flash-image \ + --prompt 'A red panda eating ramen in the rain' + +# Search + Code composer pills +python -m studio_test_kit.examples.tools_pills \ + --port 8902 --password 'YourBootstrap!' --model gemini-2.5-flash + +# Full pre/post PR comparison: installs Studio twice, drives both, composes +python -m studio_test_kit.examples.side_by_side \ + --pre-branch main --post-branch feat/my-thing \ + --pre-port 8901 --post-port 8902 \ + --model gemini-2.5-flash +``` + +## Programmatic flow (custom scenario) + +If `flows.multi_turn_chat` / `image_generation` / `tool_pills` / +`vision_upload` don't fit your task, compose primitives: + +```python +import asyncio +from pathlib import Path +from studio_test_kit.auth import gemini_provider, login, seed_init_script +from studio_test_kit.ui import ( + open_chat, pick_model, send_prompt, set_pill, wait_for_stream, + wait_for_image, extract_data_url, +) + + +async def run(): + auth = await login("http://127.0.0.1:8902", "unsloth", "YourBootstrap!") + init = seed_init_script( + auth, + [gemini_provider(api_key="AIza...", models=["gemini-2.5-flash-image"])], + ) + async with open_chat( + "http://127.0.0.1:8902", + init_scripts=[init], + video_dir=Path("out/video"), + video_name="my_run", + transcode_mp4=True, + headless=True, + ) as sp: + await pick_model(sp, "gemini-2.5-flash-image") + await set_pill(sp, "images", on=True) + await send_prompt(sp, "Draw a red panda") + data_url = await wait_for_image(sp) + raw = await extract_data_url(data_url) + Path("out/red_panda.png").write_bytes(raw) + print(f"video: {sp.video_webm} mp4: {sp.video_mp4}") + + +asyncio.run(run()) +``` + +`sp.video_webm` / `sp.video_mp4` are populated AFTER the `async with` +exits (Playwright finalises on `context.close()`). + +## Pitfalls (read once, save yourself a day) + +Every one of these bit me; the kit defends against all of them. + +| # | Pitfall | Fix in the kit | +|---|---|---| +| 1 | `wait_until="networkidle"` never fires on Studio because the chat thread holds long-lived SSE/WebSocket; Playwright deadlines. | `open_chat` uses `wait_until="domcontentloaded"` plus an explicit `form:has(textarea) textarea` visibility wait. | +| 2 | `:has-text("gemini-2.5-flash")` substring-matches `gemini-2.5-flash-image`. | `pick_model` uses `get_by_role("option", name=re.compile(rf"^{re.escape(model_id)}$"))`. | +| 3 | A bare `button:has-text("Search")` clicks the LEFT-SIDEBAR Search-history button, not the composer pill. | All UI selectors are scoped: `form:has(textarea) button:has-text(...)`. | +| 4 | Stop button hides BEFORE the final `` paints; screenshots taken on stop-hidden miss the image. | `wait_for_image` polls the DOM via `page.evaluate` for an `` whose `src` starts with `data:image/{png,jpeg,webp}` and validates decoded bytes. | +| 5 | `page.type(...)` simulates ~50 ms per keystroke; long prompts take seconds. | `send_prompt` uses `box.fill(...)` (instant paste). | +| 6 | `page.video.path()` read inside the `async with` returns a tempfile that won't survive context close. | Read `sp.video_webm` AFTER the `async with` exits. | +| 7 | Video stalls if you `await page.close()` before `context.close()`. | `open_chat` closes context then browser in a `finally`. | +| 8 | Init script planted AFTER `goto` races the SPA's bootstrap; sometimes works, sometimes silently doesn't. | `seed_init_script` is wired through `context.add_init_script(...)` BEFORE `new_page`/`goto`. | +| 9 | Cookies: Studio reads its JWT from localStorage, not cookies. | `auth.seed_init_script` plants `unsloth_auth_token` / `unsloth_refresh_token` in localStorage. | +| 10 | Playwright's `record_video_dir` writes `page@.webm`. Parallel tests sharing a video dir can rename each other's recordings. | `open_chat` snapshots pre-existing webms on entry and renames only files that appeared during this session. | +| 11 | Video finalisation skipped if the test body raises (the case you most want a recording). | `open_chat` wraps the playwright lifecycle in `try/finally`. | +| 12 | Shared deadline between password discovery and `/healthz`: a quiet log starves the healthz check and raises a spurious TimeoutError. | `launch_studio` takes independent `password_timeout_s` (default 30s) and `healthz_timeout_s` (default 180s). | +| 13 | Password log regex `[:\s]+` greedily backtracks on `password = secret`, capturing `"="` as the password. | `_PW_RE` uses an explicit `[:=]?` separator with mandatory `\s+` before the value. | +| 14 | `:has-text` substring on `data:image/` matches SVG tracking pixels. | `wait_for_image(mime_prefixes=("data:image/png", "data:image/jpeg", "data:image/webp"))` excludes SVG by default. | + +## Things I avoided (and why) + +| Avoided | Why | +|---|---| +| WebKit / Firefox launchers | Studio's RSA-encrypt-on-frontend path uses Web Crypto; only reliable on Chromium for now. | +| `wait_for_selector(...)` | Deprecated in Playwright 1.40+. Use `locator(...).wait_for(state=...)`. | +| `expect_response()` for streaming | SSE doesn't end with a discrete `Response`; DOM polling is sturdier. | +| `evaluate_handle` | Returns a JSHandle you must `.dispose()`. `evaluate` returns serialised JSON, which is enough for selector probes. | +| `playwright codegen` selectors | Produces brittle `.locator("...:nth=2")`; hand-written form-scoped role/text predicates are far more durable. | +| Cookie-based auth | Studio reads JWT from localStorage. Cookies do nothing. | +| Page video at `await page.video.path()` mid-block | The path isn't valid until `context.close()`; reading early gives you a tempfile that gets unlinked. | +| `screencast_*` / CDP video | Lower-level, no auto-flush, no rename. Context-level `record_video_dir` is the only path that just works. | + +## Customisation + +This kit is tuned to **Unsloth Studio**. If you're driving a similar +FastAPI + React chat app with a different shape, here are the override +points: + +| What | File:line | How to swap | +|---|---|---| +| Login URL / payload shape | `auth.py:login` | Replace `POST /api/auth/login` with your endpoint; ensure `StudioAuth(access_token, refresh_token, base_url)` is constructible | +| localStorage key names | `auth.py:seed_init_script` (5 keys) | Edit the `payload = {...}` dict; the rest of the kit only consumes `access_token` directly | +| RSA-on-frontend assumption | `auth.py:5-15` docstring | If your app sends keys plain or via header, modify `seed_init_script` to set whatever your SPA reads | +| Composer scope selector | `ui.py:set_pill / send_prompt` use `form:has(textarea) ...` | Change the prefix if your composer isn't an HTML `
` | +| Pill names | `ui.py:Pill` literal + `set_pill` map | Add your toggle labels | +| Model picker trigger | `ui.py:pick_model:trigger` | Adjust the data-testid / button text to match your UI | +| Model picker option role | `ui.py:pick_model:option` | If you don't use `role="option"`, change to `role="menuitem"` etc. | +| Chat route path | `ui.py:open_chat` `goto(f"{base_url}/chat")` | Make `chat_path` a parameter and thread through | +| Stop-button selector | `ui.py:wait_for_stream` | Change `aria-label="Stop generating"` to your label | +| `unsloth studio -p` launcher | `lifecycle.py:launch_studio` | Replace the `bin_path studio -p ` command with your CLI | +| Studio install layout (`.venv_t5_550` etc.) | `lifecycle.py:_find_unsloth_bin` | Add globs / accept `bin_search_paths` arg | +| Bootstrap password log shape | `lifecycle.py:_PW_RE` | Edit the regex; current accepts `bootstrap/initial/generated password [is] [:=]? value` | +| Healthz path | `lifecycle.py:launch_studio` `/healthz` | Change endpoint string | + +A common refactor for a different app: replace just `auth.py` and the +`lifecycle.*` install/launch helpers. `ui.py` / `flows.py` / `compose.py` +should still work if your SPA has a composer textarea and a streaming +stop button. + +## Verification (after vendoring) + +The two test runners are part of the kit, not external tooling. Run +them to confirm your vendored copy is intact: + +```bash +python -m studio_test_kit._self_test +# 13/13 self-tests passed + +python -m studio_test_kit._smoke_ui +# OK -- init script primed token; screenshot ~7 KB; +# webm smoke.webm ~7 KB; mp4 smoke.mp4 ~5 KB +``` + +`_smoke_ui.py` spins a tiny in-process HTTP server, so it works on a +machine without Studio installed; it's how the kit's CI verifies its +own Playwright pipeline. diff --git a/.github/scripts/studio_test_kit/__init__.py b/.github/scripts/studio_test_kit/__init__.py new file mode 100644 index 0000000000..08ec3a290f --- /dev/null +++ b/.github/scripts/studio_test_kit/__init__.py @@ -0,0 +1,32 @@ +"""Reusable building blocks for driving Unsloth Studio end-to-end. + +Modules: + lifecycle -- Install Studio at a chosen UNSLOTH_STUDIO_HOME from any git + ref, launch it on a chosen port, discover the bootstrap + password, wait for /healthz. + auth -- Backend JWT login, plus Playwright init scripts that seed + localStorage with external providers and plaintext API keys + so the SPA picks them up on first page load. + ui -- Playwright Chromium context manager with video recording, + model picker, composer textarea, pill toggles, send/stop + waits, and a real wait_for_image (polls DOM for a + `data:image/png` , not just stop-button absence). + flows -- High-level scenarios: multi_turn_chat, image_generation, + tool_pills (Search / Code), vision_upload. + compose -- PIL hstack/vstack image composition + ffmpeg hstack video + side-by-side, for pre/post-PR comparisons. + +See `examples/` for runnable scripts and `README.md` for the full flow. +""" + +from .lifecycle import StudioInstall, install_studio, launch_studio # noqa: F401 +from .auth import StudioAuth, ProviderSeed, login, seed_init_script # noqa: F401 +from .ui import ( # noqa: F401 + StudioPage, + open_chat, + pick_model, + set_pill, + send_prompt, + wait_for_stream, + wait_for_image, +) diff --git a/.github/scripts/studio_test_kit/_self_test.py b/.github/scripts/studio_test_kit/_self_test.py new file mode 100644 index 0000000000..128a500c9b --- /dev/null +++ b/.github/scripts/studio_test_kit/_self_test.py @@ -0,0 +1,300 @@ +"""Functional self-tests for studio_test_kit without a running Studio. + +Covers: + - auth.seed_init_script JS payload + JSON well-formedness + - auth.gemini_provider / openai_provider / anthropic_provider shapes + - compose.hstack_images / vstack_images on synthetic PNGs + - compose.hstack_videos / webm_to_mp4 on tiny synthetic webms (ffmpeg) + - lifecycle module-level callables (no live install) + - ui module imports + selectors literal sanity + - flows module imports + +Run: python3 -m studio_test_kit._self_test +""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + + +def _ok(name: str) -> None: + print(f"OK {name}") + + +def _fail(name: str, err: Exception) -> None: + print(f"FAIL {name}: {type(err).__name__}: {err}", file=sys.stderr) + + +def test_auth_seed() -> None: + from studio_test_kit.auth import ( + StudioAuth, gemini_provider, openai_provider, anthropic_provider, + seed_init_script, + ) + auth = StudioAuth(access_token="A.B.C", refresh_token="R.E.F", base_url="http://x") + p_gem = gemini_provider("AIza_test", models=["gemini-2.5-flash"]) + p_oai = openai_provider("sk-test", models=["gpt-4o-mini"]) + p_ant = anthropic_provider("sk-ant-test", models=["claude-3-5-haiku-latest"]) + assert p_gem.provider_type == "gemini" + assert p_oai.base_url == "https://api.openai.com/v1" + assert p_ant.models == ["claude-3-5-haiku-latest"] + assert p_gem.id != p_oai.id # unique uuid hex + + js = seed_init_script(auth, [p_gem, p_oai, p_ant], connections_enabled=True) + assert "window.localStorage.setItem" in js + assert "unsloth_auth_token" in js + assert "unsloth_chat_external_providers" in js + assert "unsloth_chat_external_provider_keys" in js + # Extract the embedded JSON payload literal (after `const seed = `). + marker = "const seed = " + start = js.index(marker) + len(marker) + end = js.index(";", start) + payload_literal = js[start:end] + payload = json.loads(payload_literal) + providers = json.loads(payload["unsloth_chat_external_providers"]) + keys = json.loads(payload["unsloth_chat_external_provider_keys"]) + assert len(providers) == 3 + assert len(keys) == 3 + assert keys[p_gem.id] == "AIza_test" + _ok("auth.seed_init_script + provider helpers") + + +def test_compose_images() -> None: + from PIL import Image + from studio_test_kit.compose import hstack_images, vstack_images + tmp = Path(tempfile.mkdtemp(prefix="stk_test_")) + try: + left = tmp / "left.png" + right = tmp / "right.png" + Image.new("RGB", (320, 240), "red").save(left) + Image.new("RGB", (200, 240), "blue").save(right) + out = hstack_images(left, right, tmp / "sxs.png", + label_left="L", label_right="R") + assert out.exists() and out.stat().st_size > 0 + with Image.open(out) as im: + assert im.width >= 520 # 320 + 24 gap + 200 + assert im.height >= 240 + 56 + v = vstack_images([left, right], tmp / "stack.png") + assert v.exists() and v.stat().st_size > 0 + finally: + shutil.rmtree(tmp, ignore_errors=True) + _ok("compose.hstack_images / vstack_images") + + +def test_compose_videos() -> None: + if shutil.which("ffmpeg") is None: + print("SKIP compose.hstack_videos -- ffmpeg not installed") + return + from studio_test_kit.compose import hstack_videos, webm_to_mp4 + tmp = Path(tempfile.mkdtemp(prefix="stk_test_")) + try: + a = tmp / "a.webm" + b = tmp / "b.webm" + # 1s 320x240 solid color webms via libvpx. + for path, color in ((a, "red"), (b, "blue")): + subprocess.run([ + "ffmpeg", "-y", "-loglevel", "error", + "-f", "lavfi", "-i", f"color=c={color}:s=320x240:d=1", + "-c:v", "libvpx", "-b:v", "200k", str(path), + ], check=True) + mp4 = hstack_videos(a, b, tmp / "sxs.mp4") + assert mp4.exists() and mp4.stat().st_size > 0 + re_mp4 = webm_to_mp4(a, tmp / "a.mp4") + assert re_mp4.exists() and re_mp4.stat().st_size > 0 + finally: + shutil.rmtree(tmp, ignore_errors=True) + _ok("compose.hstack_videos / webm_to_mp4") + + +def test_lifecycle_shape() -> None: + from studio_test_kit import lifecycle + # Smoke: dataclass + helpers exist; we don't run install.sh here. + inst = lifecycle.StudioInstall(home=Path("/tmp/x"), repo=Path("/tmp/y"), branch="main") + assert inst.bootstrap_password is None and inst.port is None + # Internal helpers we want callable: + assert callable(lifecycle.install_studio) + assert callable(lifecycle.launch_studio) + assert callable(lifecycle.stop_studio) + _ok("lifecycle module shape") + + +def test_bootstrap_password_prefers_the_file() -> None: + """A current Studio writes the password to auth/.bootstrap_password and does NOT put it + in the log, so a log-only read returns None and every authenticated route then answers + 403. Cover both sources, and the reused-home case where neither exists.""" + from studio_test_kit import lifecycle + + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) / "home" + (home / "auth").mkdir(parents=True) + log = Path(tmp) / "studio.log" + log.write_text("starting up, nothing about credentials here\n") + + # No file, no log line: None rather than a hang or a bogus value. + assert lifecycle._read_bootstrap_password(home, log, time.time() + 1) is None + + # The file is the source a current Studio actually uses. + (home / "auth" / ".bootstrap_password").write_text("s3cret-from-file\n") + got = lifecycle._read_bootstrap_password(home, log, time.time() + 5) + assert got == "s3cret-from-file", got + + # The log stays a fallback for builds that printed it there. + (home / "auth" / ".bootstrap_password").unlink() + log.write_text("Bootstrap password: s3cret-from-log\n") + got = lifecycle._read_bootstrap_password(home, log, time.time() + 5) + assert got == "s3cret-from-log", got + + _ok("bootstrap password from file, log as fallback") + + +def test_ui_imports_and_selectors() -> None: + from studio_test_kit import ui + # Ensure all the public primitives exist as callables. + for name in ("open_chat", "pick_model", "set_pill", "send_prompt", + "wait_for_stream", "wait_for_image", "wait_for_text", + "extract_data_url"): + assert callable(getattr(ui, name)), name + # Sanity-check that the source uses form-scoped selectors so we don't + # regress to clicking the sidebar Search button. + src = Path(ui.__file__).read_text() + assert 'form:has(textarea)' in src, "selectors must be form-scoped" + _ok("ui imports + form-scoped selectors") + + +def test_flows_imports() -> None: + from studio_test_kit import flows + for name in ("multi_turn_chat", "image_generation", "tool_pills", + "vision_upload", "FlowResult"): + assert hasattr(flows, name), name + _ok("flows imports") + + +def test_extract_data_url() -> None: + import asyncio + from studio_test_kit.ui import extract_data_url + # 1x1 transparent PNG (smallest valid PNG by hand-built base64). + tiny = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII=" + raw = asyncio.run(extract_data_url(tiny)) + assert raw.startswith(b"\x89PNG"), "decoded bytes should be PNG" + _ok("ui.extract_data_url decodes data URL") + + +def test_password_regex_separators() -> None: + """A4: separator must accept :, =, and 'is'; must NOT capture '=' itself.""" + from studio_test_kit.lifecycle import _PW_RE + cases = { + "Bootstrap password: UnslothPR5720!": "UnslothPR5720!", + "Initial password: Hunter2!": "Hunter2!", + "Generated password = SuperSecret!": "SuperSecret!", + "bootstrap password is: foobar": "foobar", + "Generated Password is foobaz": "foobaz", + } + for line, expected in cases.items(): + m = _PW_RE.search(line) + assert m is not None, f"no match for {line!r}" + got = m.group(1) + assert got == expected, f"line={line!r}: expected {expected!r}, got {got!r}" + _ok("lifecycle._PW_RE separator handling") + + +def test_chronological_screenshot_indices() -> None: + """A3: multi_turn_chat indices must be sorted in capture order, not + interleaved (all sent then all done would re-order on filename sort).""" + import inspect + from studio_test_kit import flows + src = inspect.getsource(flows.multi_turn_chat) + # The fix uses a single running `idx += 1` counter rather than + # arithmetic offsets keyed off `len(prompts)`. + assert "idx += 1" in src, "multi_turn_chat must use running idx counter" + assert "2 + i + len(prompts)" not in src, "old offset-by-len trick still present" + _ok("flows.multi_turn_chat chronological indices") + + +def test_pick_model_uses_exact_match() -> None: + """A6: pick_model must use regex-anchored match, not substring.""" + import inspect + from studio_test_kit import ui + src = inspect.getsource(ui.pick_model) + assert "re.escape" in src, "pick_model must escape the model_id" + assert ":has-text(" not in src or "get_by_role" in src, \ + "pick_model must not rely on :has-text substring matching" + _ok("ui.pick_model exact-match selector") + + +def test_wait_for_image_signature() -> None: + """A5/C4: signature must use min_decoded_bytes (decoded), not min_size (string len).""" + import inspect + from studio_test_kit import ui + sig = inspect.signature(ui.wait_for_image) + assert "min_decoded_bytes" in sig.parameters, sig + assert "mime_prefixes" in sig.parameters, sig + assert "min_size" not in sig.parameters, "old min_size param leaked" + _ok("ui.wait_for_image min_decoded_bytes / mime_prefixes") + + +def test_open_chat_signature_split_timeouts() -> None: + """A2: launch_studio must expose split password/healthz timeouts.""" + import inspect + from studio_test_kit.lifecycle import launch_studio + params = inspect.signature(launch_studio).parameters + assert "password_timeout_s" in params, params + assert "healthz_timeout_s" in params, params + _ok("lifecycle.launch_studio split timeouts") + + +def test_flow_result_attach_video() -> None: + from studio_test_kit.flows import FlowResult + from studio_test_kit.ui import StudioPage + # Build a StudioPage with synthesized video paths (no live browser). + sp = StudioPage.__new__(StudioPage) + sp.page = None # type: ignore + sp.context = None # type: ignore + sp.base_url = "http://x" + sp.video_webm = Path("/tmp/fake.webm") + sp.video_mp4 = Path("/tmp/fake.mp4") + r = FlowResult(out_dir=Path("/tmp/x")) + assert r.video_webm is None and r.video_mp4 is None + r.attach_video(sp) + assert r.video_webm == Path("/tmp/fake.webm") + assert r.video_mp4 == Path("/tmp/fake.mp4") + _ok("flows.FlowResult.attach_video") + + +TESTS = [ + test_auth_seed, + test_compose_images, + test_compose_videos, + test_lifecycle_shape, + test_bootstrap_password_prefers_the_file, + test_ui_imports_and_selectors, + test_flows_imports, + test_extract_data_url, + test_flow_result_attach_video, + test_password_regex_separators, + test_chronological_screenshot_indices, + test_pick_model_uses_exact_match, + test_wait_for_image_signature, + test_open_chat_signature_split_timeouts, +] + + +def main() -> int: + fails = 0 + for fn in TESTS: + try: + fn() + except Exception as e: + _fail(fn.__name__, e) + fails += 1 + print() + print(f"{len(TESTS) - fails}/{len(TESTS)} self-tests passed") + return 0 if fails == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/studio_test_kit/_smoke_ui.py b/.github/scripts/studio_test_kit/_smoke_ui.py new file mode 100644 index 0000000000..7ed46527aa --- /dev/null +++ b/.github/scripts/studio_test_kit/_smoke_ui.py @@ -0,0 +1,130 @@ +"""Live integration smoke test for studio_test_kit.ui without Studio. + +Spins up a tiny HTTP server that mimics enough of Studio's /chat surface +to exercise: + - context.add_init_script seeding localStorage + - page.goto + open_chat context manager + - screenshot + - video recording -> webm flush on context.close() + - wait_for_text on a synthetic streamed token + - wait_for_image on a data: URL + +Run: python3 -m studio_test_kit._smoke_ui +""" + +from __future__ import annotations + +import asyncio +import sys +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +OUT = Path(__file__).resolve().parents[2] / "outputs" / "studio_test_kit_smoke" +OUT.mkdir(parents=True, exist_ok=True) + +HTML = b""" +fake studio + + + +
+ + +""" + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.end_headers() + self.wfile.write(HTML) + + def log_message(self, *_a): + pass + + +def serve(port: int) -> HTTPServer: + srv = HTTPServer(("127.0.0.1", port), Handler) + t = threading.Thread(target=srv.serve_forever, daemon=True) + t.start() + return srv + + +async def main() -> int: + from studio_test_kit.auth import StudioAuth, gemini_provider, seed_init_script + from studio_test_kit.ui import open_chat, wait_for_image, wait_for_text + + port = 18902 + srv = serve(port) + try: + auth = StudioAuth(access_token="A.B.C", refresh_token="R.E.F", + base_url=f"http://127.0.0.1:{port}") + init = seed_init_script(auth, [gemini_provider("AIza_test")]) + # Need a substring of the seed JSON so we know localStorage got primed. + vid = OUT / "video" + if vid.exists(): + for p in vid.iterdir(): + p.unlink() + async with open_chat( + f"http://127.0.0.1:{port}", + init_scripts=[init], + video_dir=vid, + video_name="smoke", + transcode_mp4=True, + viewport=(800, 600), + headless=True, + ) as sp: + # localStorage primed? + token = await sp.page.evaluate("window.STUDIO_TOKEN") + assert token == "A.B.C", f"init script did not run, got {token!r}" + # screenshot + shot = OUT / "open.png" + await sp.screenshot(shot, full_page=False) + assert shot.exists() and shot.stat().st_size > 200, shot + # streamed text + await wait_for_text(sp, "TOKEN_OK", timeout_ms=5000) + # data: image + # The injected 1x1 PNG decodes to ~70 bytes, so use a small + # min_decoded_bytes threshold for the smoke fixture. + data_url = await wait_for_image( + sp, timeout_ms=5000, min_decoded_bytes=40, + ) + assert data_url.startswith("data:image/png;base64,"), data_url[:32] + # context closed -> webm should be flushed AND renamed + assert sp.video_webm is not None, "video_webm not populated post-close" + assert sp.video_webm.name == "smoke.webm", \ + f"webm not renamed to stable name: {sp.video_webm.name}" + assert sp.video_webm.stat().st_size > 0 + # No `page@*.webm` should remain after the rename. + leftover = list(vid.glob("page@*.webm")) + assert not leftover, f"auto-named webm not cleaned: {leftover}" + # transcode_mp4=True should have produced an mp4 too. + assert sp.video_mp4 is not None and sp.video_mp4.exists(), \ + f"mp4 missing: {sp.video_mp4}" + assert sp.video_mp4.stat().st_size > 0 + print(f"OK -- init script primed token; screenshot {shot.stat().st_size}B; " + f"webm {sp.video_webm.name} {sp.video_webm.stat().st_size}B; " + f"mp4 {sp.video_mp4.name} {sp.video_mp4.stat().st_size}B") + return 0 + finally: + srv.shutdown() + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/.github/scripts/studio_test_kit/auth.py b/.github/scripts/studio_test_kit/auth.py new file mode 100644 index 0000000000..af55de9986 --- /dev/null +++ b/.github/scripts/studio_test_kit/auth.py @@ -0,0 +1,144 @@ +"""Backend JWT login + Playwright localStorage seeding. + +Studio's frontend reads three localStorage keys for external providers: + + unsloth_chat_external_providers JSON array of provider configs + unsloth_chat_external_provider_keys { providerId: plaintextKey } + unsloth_chat_connections_enabled "true" | "false" + +The SPA RSA-encrypts the plaintext key on each request and posts the +ciphertext to /v1/chat/completions, so seeding these three keys is enough +to drive any external provider end-to-end without manual UI clicks +through the Settings -> Connections flow. + +`seed_init_script(...)` returns a JS init-script body suitable for +`browser_context.add_init_script(...)`. Use it BEFORE the first page +load so the SPA sees the values on its first read. +""" + +from __future__ import annotations + +import json +import uuid +from dataclasses import dataclass, field +from typing import Any, Optional + +import httpx + + +@dataclass +class StudioAuth: + """Result of a successful backend login.""" + + access_token: str + refresh_token: str + base_url: str + + +@dataclass +class ProviderSeed: + """A single external provider entry for localStorage. + + `provider_type` matches the backend registry id ("gemini", "openai", + "anthropic", "openrouter", "kimi", "openai-compat", ...). + `models` is the list of model ids Studio's picker should show. + `api_key` is the PLAINTEXT key; the SPA will RSA-encrypt at request + time using the server's published public key. + """ + + provider_type: str + name: str + base_url: str + models: list[str] + api_key: str + id: str = field(default_factory=lambda: uuid.uuid4().hex[:16]) + + def as_provider_entry(self) -> dict[str, Any]: + return { + "id": self.id, + "providerType": self.provider_type, + "name": self.name, + "baseUrl": self.base_url, + "models": list(self.models), + } + + +async def login(base_url: str, username: str, password: str, timeout: float = 15.0) -> StudioAuth: + """POST /api/auth/login -> {access_token, refresh_token}.""" + async with httpx.AsyncClient(timeout=timeout) as c: + r = await c.post( + f"{base_url}/api/auth/login", + json={"username": username, "password": password}, + ) + r.raise_for_status() + b = r.json() + return StudioAuth( + access_token=b["access_token"], + refresh_token=b.get("refresh_token", ""), + base_url=base_url, + ) + + +def seed_init_script( + auth: StudioAuth, + providers: list[ProviderSeed], + connections_enabled: bool = True, + extra_local_storage: Optional[dict[str, Any]] = None, +) -> str: + """Build a `addInitScript` JS body that primes localStorage before SPA boot.""" + provider_entries = [p.as_provider_entry() for p in providers] + provider_keys = {p.id: p.api_key for p in providers if p.api_key} + + payload = { + "unsloth_auth_token": auth.access_token, + "unsloth_refresh_token": auth.refresh_token, + "unsloth_chat_external_providers": json.dumps(provider_entries), + "unsloth_chat_external_provider_keys": json.dumps(provider_keys), + "unsloth_chat_connections_enabled": "true" if connections_enabled else "false", + } + if extra_local_storage: + for k, v in extra_local_storage.items(): + payload[k] = v if isinstance(v, str) else json.dumps(v) + + # JSON.stringify the dict, then iterate at page boot time. + js_payload = json.dumps(payload) + return f""" + (() => {{ + const seed = {js_payload}; + for (const k of Object.keys(seed)) {{ + try {{ window.localStorage.setItem(k, seed[k]); }} catch (e) {{}} + }} + }})(); + """ + + +# ── Convenience providers ─────────────────────────────────────────── + +def gemini_provider(api_key: str, models: Optional[list[str]] = None) -> ProviderSeed: + return ProviderSeed( + provider_type="gemini", + name="Google Gemini", + base_url="https://generativelanguage.googleapis.com/v1beta", + models=models or ["gemini-2.5-flash", "gemini-2.5-flash-image"], + api_key=api_key, + ) + + +def openai_provider(api_key: str, models: Optional[list[str]] = None) -> ProviderSeed: + return ProviderSeed( + provider_type="openai", + name="OpenAI", + base_url="https://api.openai.com/v1", + models=models or ["gpt-4o-mini"], + api_key=api_key, + ) + + +def anthropic_provider(api_key: str, models: Optional[list[str]] = None) -> ProviderSeed: + return ProviderSeed( + provider_type="anthropic", + name="Anthropic", + base_url="https://api.anthropic.com", + models=models or ["claude-3-5-haiku-latest"], + api_key=api_key, + ) diff --git a/.github/scripts/studio_test_kit/compose.py b/.github/scripts/studio_test_kit/compose.py new file mode 100644 index 0000000000..a3c65b3a23 --- /dev/null +++ b/.github/scripts/studio_test_kit/compose.py @@ -0,0 +1,125 @@ +"""Image + video composition helpers for pre/post-PR comparisons. + +The PR5720 review pipeline used two flavors: + + - PIL hstack of paired screenshots, with a header strip labelling each + column ("BEFORE" / "AFTER"). Useful for static side-by-side proof. + - ffmpeg hstack of two same-length .webm sessions, into a single .mp4 + you can drop into a PR description. + +The PIL helper auto-resizes pairs to the same height so the result lines +up even when the two screenshots were captured at slightly different +viewport widths. +""" + +from __future__ import annotations + +import shlex +import subprocess +from pathlib import Path +from typing import Iterable, Optional + +try: + from PIL import Image, ImageDraw, ImageFont +except ImportError: # pragma: no cover + Image = None # type: ignore + + +def _font(size: int = 28) -> Optional["ImageFont.FreeTypeFont"]: + if Image is None: + return None + for candidate in ( + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "/System/Library/Fonts/Helvetica.ttc", + ): + try: + return ImageFont.truetype(candidate, size=size) + except Exception: + continue + return ImageFont.load_default() + + +def hstack_images( + left: Path, + right: Path, + out: Path, + label_left: str = "BEFORE", + label_right: str = "AFTER", + gap_px: int = 24, + label_height_px: int = 56, +) -> Path: + """Stack two screenshots horizontally with column labels.""" + if Image is None: + raise RuntimeError("Pillow is required for hstack_images") + li, ri = Image.open(left).convert("RGB"), Image.open(right).convert("RGB") + target_h = max(li.height, ri.height) + if li.height != target_h: + li = li.resize((int(li.width * target_h / li.height), target_h)) + if ri.height != target_h: + ri = ri.resize((int(ri.width * target_h / ri.height), target_h)) + + total_w = li.width + ri.width + gap_px + total_h = target_h + label_height_px + canvas = Image.new("RGB", (total_w, total_h), "white") + canvas.paste(li, (0, label_height_px)) + canvas.paste(ri, (li.width + gap_px, label_height_px)) + + draw = ImageDraw.Draw(canvas) + f = _font(28) + if f is not None: + draw.text((16, 14), label_left, fill="black", font=f) + draw.text((li.width + gap_px + 16, 14), label_right, fill="black", font=f) + + out.parent.mkdir(parents=True, exist_ok=True) + canvas.save(out) + return out + + +def vstack_images(images: Iterable[Path], out: Path, gap_px: int = 16) -> Path: + """Stack a list of screenshots vertically (e.g. a per-turn timeline).""" + if Image is None: + raise RuntimeError("Pillow is required for vstack_images") + imgs = [Image.open(p).convert("RGB") for p in images] + if not imgs: + raise ValueError("vstack_images: empty iterable") + target_w = max(i.width for i in imgs) + resized = [ + i.resize((target_w, int(i.height * target_w / i.width))) if i.width != target_w else i + for i in imgs + ] + total_h = sum(i.height for i in resized) + gap_px * (len(resized) - 1) + canvas = Image.new("RGB", (target_w, total_h), "white") + y = 0 + for i in resized: + canvas.paste(i, (0, y)) + y += i.height + gap_px + out.parent.mkdir(parents=True, exist_ok=True) + canvas.save(out) + return out + + +def hstack_videos(left: Path, right: Path, out_mp4: Path) -> Path: + """ffmpeg hstack two .webm sessions into one .mp4.""" + out_mp4.parent.mkdir(parents=True, exist_ok=True) + cmd = [ + "ffmpeg", "-y", + "-i", str(left), + "-i", str(right), + "-filter_complex", "[0:v][1:v]hstack=inputs=2[v]", + "-map", "[v]", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23", + str(out_mp4), + ] + subprocess.run(cmd, check=True, capture_output=True, text=True) + return out_mp4 + + +def webm_to_mp4(src_webm: Path, out_mp4: Path) -> Path: + """Re-encode a single .webm to .mp4 (useful for PR-body upload).""" + out_mp4.parent.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["ffmpeg", "-y", "-i", str(src_webm), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23", str(out_mp4)], + check=True, capture_output=True, text=True, + ) + return out_mp4 diff --git a/.github/scripts/studio_test_kit/examples/__init__.py b/.github/scripts/studio_test_kit/examples/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/.github/scripts/studio_test_kit/examples/explicit_walkthrough.py b/.github/scripts/studio_test_kit/examples/explicit_walkthrough.py new file mode 100644 index 0000000000..00800452e6 --- /dev/null +++ b/.github/scripts/studio_test_kit/examples/explicit_walkthrough.py @@ -0,0 +1,314 @@ +"""End-to-end walkthrough of driving Unsloth Studio with Playwright. + +Goal: a single readable file that shows every primitive at the call +site, with inline "why" commentary. After reading this script you +should understand: + + 1. How Studio authenticates (JWT cookie-free login) + 2. How external providers + API keys are seeded (localStorage) + 3. How Playwright records video, takes screenshots, and waits for + SPA state changes + 4. The gotchas that bit me when I first did this and the patterns + that survive contact with Studio's UI + +Compared to `multi_turn.py`, this script DOES NOT use the +`studio_test_kit.flows.*` helpers -- everything is inline so you can +copy-paste-modify for a new task without spelunking through three +modules. Once you've read this once, the thin `flows.*` examples will +make sense. + +Run: + GEMINI_API_KEY=... python -m studio_test_kit.examples.explicit_walkthrough \ + --port 8902 --password 'YourBootstrap!' +""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import json +import logging +import os +import re +import shutil +import subprocess +import sys +import uuid +from pathlib import Path +from typing import Optional + +import httpx +from playwright.async_api import async_playwright + + +# ── 1. Backend login: hit /api/auth/login for a JWT pair ──────────── +# +# Studio's frontend reads the access/refresh tokens out of localStorage +# (NOT cookies), so a normal `browser_context.add_cookies(...)` flow +# would not authenticate the SPA. We POST credentials to the REST +# endpoint here, then plant the tokens in localStorage from Playwright +# in step 3 below. + + +async def fetch_tokens(base_url: str, username: str, password: str) -> dict: + async with httpx.AsyncClient(timeout=15) as c: + r = await c.post( + f"{base_url}/api/auth/login", + json={"username": username, "password": password}, + ) + r.raise_for_status() + body = r.json() + return { + "access_token": body["access_token"], + "refresh_token": body.get("refresh_token", ""), + } + + +# ── 2. Build the localStorage seed payload ───────────────────────── +# +# Studio reads three keys to discover external providers: +# unsloth_chat_external_providers JSON array of provider configs +# unsloth_chat_external_provider_keys { providerId: plaintextKey } +# unsloth_chat_connections_enabled "true" | "false" +# +# The frontend RSA-encrypts each key on every request using the public +# key from GET /api/key (so the plaintext is never sent over the wire). +# Seeding here is exactly what the Settings -> Connections UI would do +# if you typed the key into the dialog manually. + + +def build_seed_payload(tokens: dict, gemini_key: str, model_id: str) -> dict: + provider_id = uuid.uuid4().hex[:16] # any unique id, frontend echoes it back + providers = [ + { + "id": provider_id, + "providerType": "gemini", + "name": "Google Gemini", + "baseUrl": "https://generativelanguage.googleapis.com/v1beta", + "models": [model_id], + } + ] + return { + "unsloth_auth_token": tokens["access_token"], + "unsloth_refresh_token": tokens["refresh_token"], + "unsloth_chat_external_providers": json.dumps(providers), + "unsloth_chat_external_provider_keys": json.dumps({provider_id: gemini_key}), + "unsloth_chat_connections_enabled": "true", + } + + +def build_init_script(seed: dict) -> str: + # JSON.stringify embeds the dict cleanly into JS; the IIFE writes + # every key into localStorage on EVERY page navigation BEFORE the + # SPA's own JS runs. That ordering is the whole point of + # add_init_script -- planting after `goto` is racy. + return f""" + (() => {{ + const seed = {json.dumps(seed)}; + for (const k of Object.keys(seed)) {{ + try {{ window.localStorage.setItem(k, seed[k]); }} catch (e) {{}} + }} + }})(); + """ + + +# ── 3. The main flow ─────────────────────────────────────────────── + + +async def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8902) + ap.add_argument("--password", required=True, help="Studio bootstrap password") + ap.add_argument("--username", default="unsloth") + ap.add_argument("--model", default="gemini-2.5-flash") + ap.add_argument("--prompt", default="Translate 'good morning' into Japanese.") + ap.add_argument("--followup", default="Now in a pirate voice.") + ap.add_argument("--out", type=Path, default=Path("outputs/explicit_walkthrough")) + ap.add_argument("--headless", action="store_true", default=True) + args = ap.parse_args() + + logging.basicConfig(level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s") + log = logging.getLogger("walkthrough") + + args.out.mkdir(parents=True, exist_ok=True) + video_dir = args.out / "video" + video_dir.mkdir(parents=True, exist_ok=True) + + base = f"http://127.0.0.1:{args.port}" + gemini_key = os.environ.get("GEMINI_API_KEY") + if not gemini_key: + sys.exit("GEMINI_API_KEY env var is required") + + # Step 1+2: get JWT, build seed. + tokens = await fetch_tokens(base, args.username, args.password) + init_js = build_init_script(build_seed_payload(tokens, gemini_key, args.model)) + log.info("seeded provider + token via add_init_script") + + # Track existing webms so a parallel run sharing video_dir can't + # steal our recording on the post-context glob. + pre_existing = set(video_dir.glob("page@*.webm")) + + async with async_playwright() as p: + # ── 4. Launch browser + context ───────────────────────── + # + # Always Chromium for Studio: WebKit/Firefox have intermittent + # issues with the Web Crypto path the frontend uses to + # RSA-encrypt API keys. `slow_mo` is per-action latency; set + # >0 only when watching a headed run for debugging. + browser = await p.chromium.launch(headless=args.headless, slow_mo=0) + + # Video MUST be configured on the context, not the page. + # Playwright writes `page@.webm` and only finalizes on + # `context.close()` -- closing the page early stalls the writer. + context = await browser.new_context( + viewport={"width": 1440, "height": 900}, + record_video_dir=str(video_dir), + record_video_size={"width": 1440, "height": 900}, + ) + + # Init script BEFORE any new_page / goto. Runs on every nav. + await context.add_init_script(init_js) + page = await context.new_page() + + # ── 5. Navigate to /chat ──────────────────────────────── + # + # DO NOT use `wait_until="networkidle"` -- Studio holds + # long-lived SSE/WebSocket connections, so there is never + # 500 ms of zero in-flight requests and Playwright deadlines. + # `domcontentloaded` plus an explicit composer-textarea wait + # is the durable pattern. + await page.goto(f"{base}/chat", wait_until="domcontentloaded") + await page.locator("form:has(textarea) textarea").first.wait_for( + state="visible", timeout=15_000 + ) + await page.screenshot(path=str(args.out / "01_chat_open.png"), full_page=True) + + # ── 6. Open the model picker, click EXACT model ───────── + # + # Two pitfalls fixed here: + # a) `form:has(textarea) [data-testid="model-picker-trigger"]` + # scopes the picker to the composer, not the sidebar. + # b) `:has-text("gemini-2.5-flash")` is a SUBSTRING match + # and also matches `gemini-2.5-flash-image`. Use an + # anchored regex via `get_by_role("option", name=...)`. + trigger = page.locator( + 'form:has(textarea) [data-testid="model-picker-trigger"], ' + 'form:has(textarea) button:has-text("Model")' + ).first + await trigger.click(timeout=15_000) + exact = re.compile(rf"^\s*{re.escape(args.model)}\s*$") + await page.get_by_role("option", name=exact).first.click(timeout=15_000) + await page.screenshot(path=str(args.out / "02_model_picked.png"), full_page=True) + + # ── 7. Send the first prompt ──────────────────────────── + # + # Use `fill` not `type` -- `type` simulates keystrokes one by + # one (~50 ms each, multi-second for long prompts). `fill` + # instant-pastes. Always scope to `form:has(textarea)` so the + # sidebar search input doesn't get the keystroke. + box = page.locator("form:has(textarea) textarea").first + await box.click() + await box.fill(args.prompt) + await box.press("Enter") + await page.screenshot(path=str(args.out / "03_prompt_sent.png")) + + # ── 8. Wait for the streaming completion ──────────────── + # + # Streaming pattern: the stop button is the proxy for "model + # is producing tokens." It becomes visible at first token and + # hides on stream end. This is reliable for text completions. + # For IMAGE generation the stop button hides BEFORE the + # paints -- use DOM polling there (see + # `wait_for_image` in ui.py). + stop = page.locator( + 'button[aria-label="Stop generating"], button:has-text("Stop")' + ).first + try: + await stop.wait_for(state="visible", timeout=30_000) + except Exception: + log.info("stop button never appeared (fast completion?)") + await stop.wait_for(state="hidden", timeout=90_000) + await page.screenshot(path=str(args.out / "04_first_response.png"), full_page=True) + + # ── 9. Multi-turn: send a follow-up on the same thread ── + await box.click() + await box.fill(args.followup) + await box.press("Enter") + try: + await stop.wait_for(state="visible", timeout=30_000) + except Exception: + pass + await stop.wait_for(state="hidden", timeout=90_000) + await page.screenshot(path=str(args.out / "05_followup_done.png"), full_page=True) + + # ── 10. Extract the assistant text via page.evaluate ──── + # + # For asserting WHAT the model produced (not just that it + # produced something), pull text out of the DOM. The data-role + # attributes on Studio's message bubbles are stable across + # versions; if they aren't on your fork, fall back to + # `[role="article"]` or a class selector. + assistant_texts = await page.evaluate( + """() => Array.from(document.querySelectorAll( + '[data-role="assistant"] .markdown, ' + + '[data-message-role="assistant"]' + )).map(n => n.textContent || '')""" + ) + log.info("captured %d assistant messages", len(assistant_texts)) + for i, t in enumerate(assistant_texts, 1): + log.info(" [%d] %s", i, t[:120].replace("\n", " ")) + + # ── 11. Clean exit -- ORDER MATTERS ───────────────────── + # + # Close the context first (this flushes the .webm). THEN + # close the browser. Reversing this order or `page.close()`-ing + # early can leave a partial video. + await context.close() + await browser.close() + + # ── 12. Post-context: rename + transcode video ───────────── + # + # Playwright writes `page@.webm`. Rename to a stable + # filename so callers don't `glob`. Optionally transcode to mp4 + # for PR descriptions and Slack/HF uploads. Track files that + # existed before this run so a parallel run can't get its + # recording stolen. + new_webms = sorted( + p for p in video_dir.glob("page@*.webm") if p not in pre_existing + ) + if new_webms: + webm = video_dir / "walkthrough.webm" + if webm.exists(): + webm.unlink() + new_webms[-1].rename(webm) + for stale in new_webms[:-1]: + try: + stale.unlink() + except OSError as e: + log.warning("could not unlink stale webm %s: %s", stale, e) + log.info("wrote %s (%d B)", webm, webm.stat().st_size) + + if shutil.which("ffmpeg"): + mp4 = video_dir / "walkthrough.mp4" + r = subprocess.run( + ["ffmpeg", "-y", "-loglevel", "error", + "-i", str(webm), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23", + str(mp4)], + check=False, capture_output=True, text=True, + ) + if r.returncode == 0 and mp4.exists() and mp4.stat().st_size > 0: + log.info("wrote %s (%d B)", mp4, mp4.stat().st_size) + else: + log.warning("ffmpeg failed (rc=%s): %s", + r.returncode, r.stderr.strip()[:200]) + else: + log.info("ffmpeg not on PATH -- skipping mp4 transcode") + + print(f"\nDone. Artefacts in {args.out}/") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/.github/scripts/studio_test_kit/examples/image_gen.py b/.github/scripts/studio_test_kit/examples/image_gen.py new file mode 100644 index 0000000000..739a9c28c6 --- /dev/null +++ b/.github/scripts/studio_test_kit/examples/image_gen.py @@ -0,0 +1,54 @@ +"""Drive image generation (e.g. Nano Banana) and save the decoded PNG. + + GEMINI_API_KEY=... python -m studio_test_kit.examples.image_gen \ + --port 8902 --password 'YourBootstrap!' \ + --model gemini-2.5-flash-image \ + --prompt 'A red panda eating ramen in the rain, neon lighting' +""" + +import argparse +import asyncio +import os +from pathlib import Path + +from studio_test_kit.auth import gemini_provider, login, seed_init_script +from studio_test_kit.flows import image_generation +from studio_test_kit.ui import open_chat + + +async def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8902) + ap.add_argument("--password", required=True) + ap.add_argument("--username", default="unsloth") + ap.add_argument("--model", default="gemini-2.5-flash-image") + ap.add_argument("--prompt", default="A red panda eating ramen in the rain") + ap.add_argument("--out", type=Path, default=Path("outputs/image_gen")) + args = ap.parse_args() + + base = f"http://127.0.0.1:{args.port}" + auth = await login(base, args.username, args.password) + providers = [ + gemini_provider(api_key=os.environ["GEMINI_API_KEY"], models=[args.model]) + ] + init = seed_init_script(auth, providers) + + async with open_chat( + base, init_scripts=[init], + video_dir=args.out / "video", + video_name="image_gen", + transcode_mp4=True, + headless=True, + ) as sp: + r = await image_generation(sp, args.model, args.prompt, args.out) + r.attach_video(sp) + print(f"Image saved to {r.artefacts['image_path']} " + f"({r.artefacts['image_bytes']} bytes)") + if r.video_webm: + print(f" video webm: {r.video_webm}") + if r.video_mp4: + print(f" video mp4: {r.video_mp4}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/.github/scripts/studio_test_kit/examples/multi_turn.py b/.github/scripts/studio_test_kit/examples/multi_turn.py new file mode 100644 index 0000000000..f71e6e7597 --- /dev/null +++ b/.github/scripts/studio_test_kit/examples/multi_turn.py @@ -0,0 +1,63 @@ +"""Drive a 4-turn conversation against any external provider. + +Run: + GEMINI_API_KEY=... python -m studio_test_kit.examples.multi_turn \ + --port 8902 --password 'YourBootstrap!' --model gemini-2.5-flash + +This assumes Studio is already running on `--port`. Use +`studio_test_kit.lifecycle.install_studio` / `launch_studio` to spin it +up programmatically from CI. +""" + +import argparse +import asyncio +import os +from pathlib import Path + +from studio_test_kit.auth import gemini_provider, login, seed_init_script +from studio_test_kit.flows import multi_turn_chat +from studio_test_kit.ui import open_chat + + +async def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8902) + ap.add_argument("--password", required=True) + ap.add_argument("--username", default="unsloth") + ap.add_argument("--model", default="gemini-2.5-flash") + ap.add_argument("--out", type=Path, default=Path("outputs/multi_turn")) + ap.add_argument("--headless", action="store_true", default=True) + args = ap.parse_args() + + base = f"http://127.0.0.1:{args.port}" + auth = await login(base, args.username, args.password) + providers = [ + gemini_provider(api_key=os.environ["GEMINI_API_KEY"], models=[args.model]) + ] + init = seed_init_script(auth, providers) + + prompts = [ + "Translate 'good morning' into Japanese.", + "Now in a pirate voice.", + "Summarize this thread in 5 words.", + "And one emoji that captures it.", + ] + + async with open_chat( + base, init_scripts=[init], + video_dir=args.out / "video", + video_name="multi_turn", + transcode_mp4=True, + headless=args.headless, + ) as sp: + r = await multi_turn_chat(sp, args.model, prompts, args.out) + r.attach_video(sp) + print(f"Wrote {len(r.screenshots)} screenshots to {r.out_dir}") + if r.video_webm: + print(f" video webm: {r.video_webm} ({r.video_webm.stat().st_size} B)") + if r.video_mp4: + print(f" video mp4: {r.video_mp4} ({r.video_mp4.stat().st_size} B)") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/.github/scripts/studio_test_kit/examples/side_by_side.py b/.github/scripts/studio_test_kit/examples/side_by_side.py new file mode 100644 index 0000000000..45a4e2d29f --- /dev/null +++ b/.github/scripts/studio_test_kit/examples/side_by_side.py @@ -0,0 +1,94 @@ +"""Pre-PR vs post-PR side-by-side: install both, drive the same chat flow +on both, then compose a hstack video + an hstack per-turn screenshot. + +This is the canonical "screenshot the behavior change" workflow. + + GEMINI_API_KEY=... python -m studio_test_kit.examples.side_by_side \ + --pre-branch main \ + --post-branch feat/gemini-provider \ + --pre-port 8901 \ + --post-port 8902 \ + --model gemini-2.5-flash +""" + +import argparse +import asyncio +import os +from pathlib import Path + +from studio_test_kit.auth import gemini_provider, login, seed_init_script +from studio_test_kit.compose import hstack_images, hstack_videos +from studio_test_kit.flows import multi_turn_chat +from studio_test_kit.lifecycle import install_studio, launch_studio +from studio_test_kit.ui import open_chat + + +PROMPTS = [ + "Translate 'good morning' into Japanese.", + "Now in a pirate voice.", + "Summarize this thread in 5 words.", +] + + +async def drive( + port: int, password: str, model: str, out_dir: Path, video_dir: Path, + video_name: str, +) -> tuple[list[Path], Path]: + base = f"http://127.0.0.1:{port}" + auth = await login(base, "unsloth", password) + providers = [ + gemini_provider(api_key=os.environ["GEMINI_API_KEY"], models=[model]) + ] + init = seed_init_script(auth, providers) + async with open_chat( + base, init_scripts=[init], video_dir=video_dir, + video_name=video_name, headless=True, + ) as sp: + r = await multi_turn_chat(sp, model, PROMPTS, out_dir) + r.attach_video(sp) + assert r.video_webm is not None, "video was not recorded" + return r.screenshots, r.video_webm + + +async def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--pre-branch", default="main") + ap.add_argument("--post-branch", required=True) + ap.add_argument("--pre-port", type=int, default=8901) + ap.add_argument("--post-port", type=int, default=8902) + ap.add_argument("--model", default="gemini-2.5-flash") + ap.add_argument("--root", type=Path, default=Path("outputs/side_by_side")) + ap.add_argument("--studio-home-root", type=Path, + default=Path("temp/side_by_side_studios")) + args = ap.parse_args() + + pre = install_studio(args.pre_branch, args.studio_home_root / "pre") + post = install_studio(args.post_branch, args.studio_home_root / "post") + launch_studio(pre, args.pre_port, args.root / "pre.log") + launch_studio(post, args.post_port, args.root / "post.log") + + pre_shots, pre_video = await drive( + args.pre_port, pre.bootstrap_password or "", args.model, + args.root / "pre", args.root / "pre" / "video", "pre", + ) + post_shots, post_video = await drive( + args.post_port, post.bootstrap_password or "", args.model, + args.root / "post", args.root / "post" / "video", "post", + ) + + combined = args.root / "combined" + combined.mkdir(parents=True, exist_ok=True) + for i, (left, right) in enumerate(zip(pre_shots, post_shots), start=1): + hstack_images(left, right, combined / f"sxs_{i:02d}.png", + label_left=args.pre_branch, label_right=args.post_branch) + + sxs_mp4 = combined / "sxs.mp4" + hstack_videos(pre_video, post_video, sxs_mp4) + print(f"Wrote combined comparison to {combined}") + print(f" pre webm: {pre_video}") + print(f" post webm: {post_video}") + print(f" sxs mp4: {sxs_mp4}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/.github/scripts/studio_test_kit/examples/tools_pills.py b/.github/scripts/studio_test_kit/examples/tools_pills.py new file mode 100644 index 0000000000..9957f59cba --- /dev/null +++ b/.github/scripts/studio_test_kit/examples/tools_pills.py @@ -0,0 +1,46 @@ +"""Exercise the Search and Code composer pills.""" + +import argparse +import asyncio +import os +from pathlib import Path + +from studio_test_kit.auth import gemini_provider, login, seed_init_script +from studio_test_kit.flows import tool_pills +from studio_test_kit.ui import open_chat + + +async def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8902) + ap.add_argument("--password", required=True) + ap.add_argument("--username", default="unsloth") + ap.add_argument("--model", default="gemini-2.5-flash") + ap.add_argument("--out", type=Path, default=Path("outputs/tools_pills")) + args = ap.parse_args() + + base = f"http://127.0.0.1:{args.port}" + auth = await login(base, args.username, args.password) + providers = [ + gemini_provider(api_key=os.environ["GEMINI_API_KEY"], models=[args.model]) + ] + init = seed_init_script(auth, providers) + + async with open_chat( + base, init_scripts=[init], + video_dir=args.out / "video", + video_name="tools_pills", + transcode_mp4=True, + headless=True, + ) as sp: + r = await tool_pills(sp, args.model, args.out) + r.attach_video(sp) + print(f"Wrote {len(r.screenshots)} screenshots to {r.out_dir}") + if r.video_webm: + print(f" video webm: {r.video_webm}") + if r.video_mp4: + print(f" video mp4: {r.video_mp4}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/.github/scripts/studio_test_kit/flows.py b/.github/scripts/studio_test_kit/flows.py new file mode 100644 index 0000000000..bc7140ab93 --- /dev/null +++ b/.github/scripts/studio_test_kit/flows.py @@ -0,0 +1,164 @@ +"""High-level reusable scenarios. + +Each flow: + - takes a `StudioPage` already at /chat with init scripts seeded + - drives the UI through a real round-trip against the live provider + - saves numbered screenshots into `out_dir` + - returns a small dict of artefacts the caller can assert on + +The flows are deliberately small so you can compose them: a "vision +upload then ask about it" test is `vision_upload` followed by +`multi_turn_chat`. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Optional + +from .ui import ( + StudioPage, + extract_data_url, + pick_model, + send_prompt, + set_pill, + wait_for_image, + wait_for_stream, +) + + +@dataclass +class FlowResult: + out_dir: Path + screenshots: list[Path] = field(default_factory=list) + artefacts: dict = field(default_factory=dict) + # Populated AFTER the open_chat context exits (Playwright flushes the + # webm on context.close). Callers that want the video should read + # these via `sp.video_webm` / `sp.video_mp4` once the `async with` + # block has completed, then copy onto the FlowResult themselves, or + # use `flow_result.attach_video(sp)` after the block. + video_webm: Optional[Path] = None + video_mp4: Optional[Path] = None + + def shot(self, sp: StudioPage, idx: int, name: str) -> Path: + path = self.out_dir / f"{idx:02d}_{name}.png" + self.screenshots.append(path) + return path + + def attach_video(self, sp: StudioPage) -> "FlowResult": + """Copy video paths from the StudioPage (call after `async with` exits).""" + self.video_webm = sp.video_webm + self.video_mp4 = sp.video_mp4 + return self + + +async def multi_turn_chat( + sp: StudioPage, + model: str, + prompts: list[str], + out_dir: Path, + settle_timeout_ms: int = 90_000, +) -> FlowResult: + """Pick `model`, then send each prompt in sequence on the same thread. + + Screenshots are numbered in chronological capture order, so a + sorted-by-filename viewing (the default in most file managers) + matches the actual narrative: open, pick, sent-1, done-1, sent-2, + done-2, ... + """ + out_dir.mkdir(parents=True, exist_ok=True) + r = FlowResult(out_dir=out_dir) + idx = 1 + await sp.screenshot(r.shot(sp, idx, "chat_open")); idx += 1 + await pick_model(sp, model) + await sp.screenshot(r.shot(sp, idx, "model_picked")); idx += 1 + for i, prompt in enumerate(prompts, start=1): + await send_prompt(sp, prompt) + await sp.screenshot(r.shot(sp, idx, f"turn_{i:02d}_sent")); idx += 1 + await wait_for_stream(sp, timeout_ms=settle_timeout_ms) + await sp.screenshot(r.shot(sp, idx, f"turn_{i:02d}_done")); idx += 1 + r.artefacts["turn_count"] = len(prompts) + return r + + +async def image_generation( + sp: StudioPage, + model: str, + prompt: str, + out_dir: Path, + image_basename: str = "generated_image", + timeout_ms: int = 120_000, +) -> FlowResult: + """Pick an image-gen model, toggle the Images pill, send a prompt, + wait for a `data:image/png` to render, and save the decoded bytes.""" + out_dir.mkdir(parents=True, exist_ok=True) + r = FlowResult(out_dir=out_dir) + await sp.screenshot(r.shot(sp, 1, "chat_open")) + await pick_model(sp, model) + await sp.screenshot(r.shot(sp, 2, "model_picked")) + await set_pill(sp, "images", on=True) + await sp.screenshot(r.shot(sp, 3, "image_pill_on")) + await send_prompt(sp, prompt) + await sp.screenshot(r.shot(sp, 4, "prompt_sent")) + data_url = await wait_for_image(sp, timeout_ms=timeout_ms) + await sp.screenshot(r.shot(sp, 5, "image_response")) + image_path = out_dir / f"{image_basename}.png" + image_path.write_bytes(await extract_data_url(data_url)) + r.artefacts["image_bytes"] = image_path.stat().st_size + r.artefacts["image_path"] = str(image_path) + return r + + +async def tool_pills( + sp: StudioPage, + model: str, + out_dir: Path, + search_prompt: Optional[str] = "Who won the 2024 NBA championship?", + code_prompt: Optional[str] = "Use Python to compute the sum of the first 100 primes.", +) -> FlowResult: + """Exercise Search + Code composer pills on the same model.""" + out_dir.mkdir(parents=True, exist_ok=True) + r = FlowResult(out_dir=out_dir) + await sp.screenshot(r.shot(sp, 1, "chat_open")) + await pick_model(sp, model) + await sp.screenshot(r.shot(sp, 2, "model_picked")) + if search_prompt: + await set_pill(sp, "search", on=True) + await sp.screenshot(r.shot(sp, 3, "search_pill_on")) + await send_prompt(sp, search_prompt) + await wait_for_stream(sp) + await sp.screenshot(r.shot(sp, 4, "search_response")) + await set_pill(sp, "search", on=False) + if code_prompt: + await set_pill(sp, "code", on=True) + await sp.screenshot(r.shot(sp, 5, "code_pill_on")) + await send_prompt(sp, code_prompt) + await wait_for_stream(sp) + await sp.screenshot(r.shot(sp, 6, "code_response")) + await sp.screenshot(r.shot(sp, 7, "thread_full")) + return r + + +async def vision_upload( + sp: StudioPage, + model: str, + image_path: Path, + prompt: str, + out_dir: Path, +) -> FlowResult: + """Pick a vision-capable model, attach `image_path` through the file + input, ask `prompt`, wait for completion.""" + out_dir.mkdir(parents=True, exist_ok=True) + r = FlowResult(out_dir=out_dir) + await sp.screenshot(r.shot(sp, 1, "chat_open")) + await pick_model(sp, model) + await sp.screenshot(r.shot(sp, 2, "model_picked")) + file_input = sp.page.locator('form:has(textarea) input[type="file"]').first + await file_input.set_input_files(str(image_path)) + await sp.screenshot(r.shot(sp, 3, "image_attached")) + await send_prompt(sp, prompt) + await sp.screenshot(r.shot(sp, 4, "prompt_sent")) + await wait_for_stream(sp) + await sp.screenshot(r.shot(sp, 5, "vision_response")) + return r diff --git a/.github/scripts/studio_test_kit/lifecycle.py b/.github/scripts/studio_test_kit/lifecycle.py new file mode 100644 index 0000000000..6e4182d008 --- /dev/null +++ b/.github/scripts/studio_test_kit/lifecycle.py @@ -0,0 +1,236 @@ +"""Install + launch Unsloth Studio for arbitrary branches/ports. + +The pre-PR vs post-PR test pattern installs Studio twice, once per branch, +each pinned to its own UNSLOTH_STUDIO_HOME so the two installs share +nothing (separate `.venv_t5_*`, `auth/`, `studio.db`, llama.cpp build). + +`install_studio(branch=..., home=...)` clones unslothai/unsloth (or +re-uses an existing clone), checks out the branch, then runs +`./install.sh --local` with UNSLOTH_STUDIO_HOME exported. + +`launch_studio(install, port=..., log_path=...)` starts `unsloth studio +-p ` detached via setsid and recovers the bootstrap password from +`/auth/.bootstrap_password`, falling back to the log for builds +that printed it there instead. +""" + +from __future__ import annotations + +import os +import re +import shlex +import shutil +import signal +import subprocess +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + + +@dataclass +class StudioInstall: + """Where a Studio install lives + the credentials it minted on first run.""" + + home: Path # UNSLOTH_STUDIO_HOME + repo: Path # clone of unslothai/unsloth + branch: str + bootstrap_password: Optional[str] = None + port: Optional[int] = None + pid: Optional[int] = None + + +def _run(cmd: str | list[str], cwd: Optional[Path] = None, env: Optional[dict] = None, + check: bool = True, timeout: Optional[int] = None) -> subprocess.CompletedProcess: + if isinstance(cmd, str): + cmd_list = shlex.split(cmd) + else: + cmd_list = cmd + full_env = {**os.environ, **(env or {})} + return subprocess.run( + cmd_list, cwd=cwd, env=full_env, check=check, timeout=timeout, + text=True, capture_output=True, + ) + + +def install_studio( + branch: str, + home: Path, + repo: Optional[Path] = None, + remote: str = "https://github.com/unslothai/unsloth", + reuse_clone: bool = True, +) -> StudioInstall: + """Clone (or re-use) the repo at `branch`, then run `./install.sh --local`. + + `home` is exported as UNSLOTH_STUDIO_HOME for the install. After this + returns, `home/.venv_t5_550/`, `home/auth/`, etc. exist. + """ + home = Path(home).resolve() + home.mkdir(parents=True, exist_ok=True) + repo = (repo or (home.parent / f"{home.name}_repo")).resolve() + + if reuse_clone and (repo / ".git").exists(): + _run(["git", "fetch", "origin", branch], cwd=repo) + _run(["git", "checkout", branch], cwd=repo) + _run(["git", "reset", "--hard", f"origin/{branch}"], cwd=repo) + else: + if repo.exists(): + shutil.rmtree(repo) + _run(["git", "clone", "--branch", branch, remote, str(repo)]) + + install_sh = repo / "install.sh" + if not install_sh.exists(): + raise FileNotFoundError(f"install.sh missing at {install_sh}") + _run( + ["bash", str(install_sh), "--local"], + cwd=repo, + env={"UNSLOTH_STUDIO_HOME": str(home)}, + timeout=60 * 30, + ) + return StudioInstall(home=home, repo=repo, branch=branch) + + +def _find_unsloth_bin(install: StudioInstall) -> str: + """Return the absolute path to the `unsloth` CLI inside the install.""" + for candidate in ( + install.home / "bin" / "unsloth", + install.home / ".venv_t5_550" / "bin" / "unsloth", + install.home / ".venv_t5_530" / "bin" / "unsloth", + ): + if candidate.exists(): + return str(candidate) + raise FileNotFoundError(f"`unsloth` CLI not found under {install.home}") + + +# The FALLBACK source. A current Studio writes the password to a file instead (see +# _read_bootstrap_password); these are the log line shapes older builds emit. +# Password log line shapes seen in practice: +# "Bootstrap password: secret" +# "Initial password = secret" +# "Generated password is secret" +# "bootstrap password is: secret" +# The mandatory `\s+` before the value and the EXPLICIT `[:=]?` separator +# (rather than `[:\s]+` greedy class) stop the regex from backtracking +# to capture `=` itself as the password. +_PW_RE = re.compile( + r"(?i)(?:bootstrap|initial|generated)\s*password" + r"(?:\s+is)?\s*[:=]?\s+(\S+)" +) + + +def _read_bootstrap_password( + home: Path, log_path: Path, deadline: float +) -> Optional[str]: + """The bootstrap password, from the file first and the log second. + + Studio writes it to ``/auth/.bootstrap_password`` and does NOT inline it in the + log, so a log-only read returns None on a current Studio and every authenticated route + then answers ``403 Password change required``. That failure is quiet: launch succeeds, + /healthz answers, and the caller only finds out one request later. + + Both sources are polled together because the file appears at first-run auth setup and + the log line is what older builds emit; whichever arrives first wins. Studio DELETES the + file once the password is rotated, so a reused home legitimately has neither, and None + stays a valid answer meaning "log in with the password you already set". + """ + boot_file = home / "auth" / ".bootstrap_password" + while time.time() < deadline: + try: + if boot_file.exists(): + secret = boot_file.read_text(errors="ignore").strip() + if secret: + return secret + except OSError: + pass # mid-write, or a permission we do not have: fall through and retry + if log_path.exists(): + text = log_path.read_text(errors="ignore") + m = _PW_RE.search(text) + if m: + return m.group(1).strip().strip(".,") + time.sleep(0.5) + return None + + +def launch_studio( + install: StudioInstall, + port: int, + log_path: Path, + extra_env: Optional[dict] = None, + wait_for_healthz: bool = True, + healthz_timeout_s: int = 180, + password_timeout_s: int = 30, + timeout_s: Optional[int] = None, +) -> StudioInstall: + """Start `unsloth studio -p ` detached. Updates `install` in place + with `port`, `pid`, and `bootstrap_password` (parsed from the log). + + Two INDEPENDENT timeouts: + - `password_timeout_s`: how long to wait for the bootstrap password + line. Relaunching an existing install often skips reprinting the + password, so this should be SHORT (default 30s). + - `healthz_timeout_s`: how long to wait for `/healthz` to return 200. + Studio cold-start can take a couple of minutes (default 180s). + + `timeout_s` is accepted for backward compatibility and overrides + `healthz_timeout_s` if set. With the legacy single-deadline behavior + a quiet log starved the healthz check and raised a spurious + TimeoutError even when Studio was up. + """ + if timeout_s is not None: + healthz_timeout_s = timeout_s + log_path = Path(log_path).resolve() + log_path.parent.mkdir(parents=True, exist_ok=True) + log_path.write_text("") + + bin_path = _find_unsloth_bin(install) + env = {"UNSLOTH_STUDIO_HOME": str(install.home), **(extra_env or {})} + cmd = ["setsid", "-f", "bash", "-c", + f'{shlex.quote(bin_path)} studio -p {port} ' + f'2>&1 | tee -a {shlex.quote(str(log_path))}'] + subprocess.Popen( + cmd, + env={**os.environ, **env}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + + install.port = port + install.bootstrap_password = _read_bootstrap_password( + install.home, log_path, time.time() + password_timeout_s + ) + + if wait_for_healthz: + import urllib.request + url = f"http://127.0.0.1:{port}/healthz" + healthz_deadline = time.time() + healthz_timeout_s + while time.time() < healthz_deadline: + try: + with urllib.request.urlopen(url, timeout=2) as r: + if r.status == 200: + break + except Exception: + time.sleep(1) + else: + raise TimeoutError( + f"Studio on :{port} did not pass /healthz within " + f"{healthz_timeout_s}s" + ) + + # Best-effort PID capture via `pgrep -f`. + try: + out = _run(f"pgrep -f 'unsloth studio.*-p {port}'", check=False).stdout.strip() + if out: + install.pid = int(out.splitlines()[0]) + except Exception: + pass + return install + + +def stop_studio(install: StudioInstall) -> None: + """Best-effort SIGTERM the launched Studio process group.""" + if install.pid: + try: + os.killpg(os.getpgid(install.pid), signal.SIGTERM) + except Exception: + pass diff --git a/.github/scripts/studio_test_kit/ui.py b/.github/scripts/studio_test_kit/ui.py new file mode 100644 index 0000000000..b422b39adc --- /dev/null +++ b/.github/scripts/studio_test_kit/ui.py @@ -0,0 +1,301 @@ +"""Playwright Chromium primitives for Studio's /chat UI. + +The big lesson from PR5720 driving: do NOT key off the global "stop button +disappeared" signal -- the stop button disappears slightly before the +final image paints, so a Nano Banana screenshot taken at that moment is +missing the image. Use `wait_for_image(page, ...)` for image-gen flows; +it polls the DOM for an `` whose src starts with `data:image/`. + +Selectors used here are scoped to the composer `
` whose textarea +is the chat input, so they don't accidentally match the sidebar buttons +(e.g. a global "Search" button on the left rail). +""" + +from __future__ import annotations + +import asyncio +import logging +import re +import shutil +import subprocess +import uuid +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import AsyncIterator, Literal, Optional + +from playwright.async_api import BrowserContext, Page, async_playwright + +_log = logging.getLogger(__name__) + + +Pill = Literal["search", "code", "images"] + + +@dataclass +class StudioPage: + """Bundle of the live Playwright page + its browser context. + + Keep both because video files are flushed on `context.close()` only. + `video_webm` and `video_mp4` are populated AFTER the `open_chat` + context manager exits (Playwright only finalizes the .webm on + `context.close()`). Read them after the `async with` block. + """ + + page: Page + context: BrowserContext + base_url: str + video_webm: Optional[Path] = None + video_mp4: Optional[Path] = None + + async def screenshot(self, out: Path, full_page: bool = True) -> None: + out.parent.mkdir(parents=True, exist_ok=True) + await self.page.screenshot(path=str(out), full_page=full_page) + + +@asynccontextmanager +async def open_chat( + base_url: str, + init_scripts: Optional[list[str]] = None, + video_dir: Optional[Path] = None, + video_name: str = "session", + transcode_mp4: bool = False, + viewport: tuple[int, int] = (1440, 900), + headless: bool = True, + slow_mo_ms: int = 0, +) -> AsyncIterator[StudioPage]: + """Launch headless Chromium, seed init scripts, open `/chat`. + + Video recording: Playwright auto-names files `page@.webm` and + only finalizes them on `context.close()`. When `video_dir` is set, + this helper: + 1. Configures record_video_dir + record_video_size on the context. + 2. After context exit, renames the auto-generated webm to + `/.webm` and stores it on + `StudioPage.video_webm`. + 3. If `transcode_mp4=True` (and ffmpeg is on PATH), also produces + `/.mp4` via libx264/yuv420p (PR-body and + most-player friendly) and stores it on `StudioPage.video_mp4`. + + The `StudioPage` yielded inside the `async with` lives past context + close, so callers can read `sp.video_webm` / `sp.video_mp4` AFTER + the block exits. + """ + # To survive parallel runs sharing `video_dir`, mint a unique + # session token; on exit we glob only files that arrived after this + # context began so we can't steal a sibling session's recording. + session_token = uuid.uuid4().hex + sp_holder: dict = {} + pre_existing: set[Path] = set() + # The video finalization MUST run even when the caller's body raises + # (that's exactly when you want the recording). Wrap the whole + # playwright lifecycle in try/finally so the rename + transcode + # happens unconditionally. + try: + async with async_playwright() as p: + browser = await p.chromium.launch(headless=headless, slow_mo=slow_mo_ms) + kw: dict = {"viewport": {"width": viewport[0], "height": viewport[1]}} + if video_dir is not None: + video_dir.mkdir(parents=True, exist_ok=True) + kw["record_video_dir"] = str(video_dir) + kw["record_video_size"] = {"width": viewport[0], "height": viewport[1]} + # Snapshot files that already exist; we'll only sweep + # webms that appeared AFTER this snapshot. + pre_existing = set(video_dir.glob("page@*.webm")) + context = await browser.new_context(**kw) + for script in init_scripts or []: + await context.add_init_script(script) + page = await context.new_page() + # Streaming SPAs hold long-lived SSE/WebSocket connections, + # so `networkidle` can deadline. domcontentloaded plus an + # explicit composer-textarea wait is the reliable pattern. + await page.goto(f"{base_url}/chat", wait_until="domcontentloaded") + try: + await page.locator("form:has(textarea) textarea").first.wait_for( + state="visible", timeout=15_000 + ) + except Exception: + # Some apps render the composer lazily; the test code + # following may still wait_for it. Don't fail open_chat + # solely on this fast-path probe. + pass + sp = StudioPage(page=page, context=context, base_url=base_url) + sp_holder["sp"] = sp + sp_holder["session_token"] = session_token + try: + yield sp + finally: + await context.close() + await browser.close() + finally: + sp = sp_holder.get("sp") + if sp is not None and video_dir is not None: + try: + # Only consider webms that did not exist when we started. + new_webms = sorted( + p for p in video_dir.glob("page@*.webm") + if p not in pre_existing + ) + if new_webms: + final_webm = Path(video_dir) / f"{video_name}.webm" + if final_webm.exists(): + final_webm.unlink() + new_webms[-1].rename(final_webm) + # Sweep extras that originated from this session. + for stale in new_webms[:-1]: + try: + stale.unlink() + except OSError as e: + _log.warning("could not unlink stale webm %s: %s", stale, e) + sp.video_webm = final_webm + if transcode_mp4 and shutil.which("ffmpeg"): + final_mp4 = Path(video_dir) / f"{video_name}.mp4" + result = subprocess.run( + ["ffmpeg", "-y", "-loglevel", "error", + "-i", str(final_webm), + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23", + str(final_mp4)], + check=False, capture_output=True, text=True, + ) + if (final_mp4.exists() and final_mp4.stat().st_size > 0 + and result.returncode == 0): + sp.video_mp4 = final_mp4 + else: + _log.warning( + "ffmpeg transcode failed (rc=%s): %s", + result.returncode, result.stderr.strip()[:200], + ) + elif transcode_mp4: + _log.warning( + "transcode_mp4=True but ffmpeg not found on PATH; " + "skipping mp4 transcode" + ) + except Exception as e: + # Surface the failure -- a permission-denied rename or + # full disk should NOT silently look like "no recording + # was requested". + _log.warning("video finalization failed: %s", e) + + +# ── UI primitives ──────────────────────────────────────────────────── + + +async def pick_model(sp: StudioPage, model_id: str, timeout_ms: int = 15000) -> None: + """Open the model picker, click the option whose label EXACTLY equals + `model_id`. + + Exact match matters: `:has-text("gemini-2.5-flash")` also matches + `gemini-2.5-flash-image`. Using `get_by_role("option", name=re.compile(...))` + with an anchored, escaped pattern avoids that collision and also + protects against quote characters inside the model id. + """ + page = sp.page + trigger = page.locator( + 'form:has(textarea) [data-testid="model-picker-trigger"], ' + 'form:has(textarea) button:has-text("Model")' + ).first + await trigger.click(timeout=timeout_ms) + pattern = re.compile(rf"^\s*{re.escape(model_id)}\s*$") + option = page.get_by_role("option", name=pattern).first + await option.click(timeout=timeout_ms) + + +async def set_pill(sp: StudioPage, pill: Pill, on: bool = True, timeout_ms: int = 5000) -> None: + """Toggle a composer pill (Search / Code / Images) on or off. + + Scoped to the composer form so it never matches the sidebar Search. + """ + label = {"search": "Search", "code": "Code", "images": "Images"}[pill] + btn = sp.page.locator( + f'form:has(textarea) button:has-text("{label}")' + ).first + state = await btn.get_attribute("aria-pressed") + is_on = (state == "true") + if is_on != on: + await btn.click(timeout=timeout_ms) + + +async def send_prompt(sp: StudioPage, text: str) -> None: + """Type into the composer and submit with Enter.""" + box = sp.page.locator("form:has(textarea) textarea").first + await box.click() + await box.fill(text) + await box.press("Enter") + + +async def wait_for_stream(sp: StudioPage, timeout_ms: int = 90_000) -> None: + """Wait for the streaming stop button to appear then disappear. + + Good enough for text-only completions. Image generation paints AFTER + the stop button hides, so use `wait_for_image` for that flow. + """ + page = sp.page + stop = page.locator('button[aria-label="Stop generating"], ' + 'button:has-text("Stop")').first + try: + await stop.wait_for(state="visible", timeout=timeout_ms) + except Exception: + pass # Some flows finish faster than the button appears. + await stop.wait_for(state="hidden", timeout=timeout_ms) + + +async def wait_for_image( + sp: StudioPage, + timeout_ms: int = 120_000, + min_decoded_bytes: int = 256, + mime_prefixes: tuple[str, ...] = ("data:image/png", "data:image/jpeg", + "data:image/webp"), +) -> str: + """Poll the chat DOM until an `` whose src starts with one of + `mime_prefixes` appears, then return that data URL. + + `min_decoded_bytes` is the minimum DECODED size (so SVG tracking + pixels and 1x1 placeholders are filtered). Default prefixes exclude + svg and tracking pixels by default; pass a wider tuple to opt in. + + Raises TimeoutError on deadline. + """ + page = sp.page + deadline = asyncio.get_event_loop().time() + (timeout_ms / 1000) + prefix_js = "[" + ",".join(f'"{p}"' for p in mime_prefixes) + "]" + while asyncio.get_event_loop().time() < deadline: + src = await page.evaluate( + "(prefixes) => {" + " const imgs = Array.from(document.querySelectorAll('img'));" + " const cand = imgs.find(i => i.src && prefixes.some(p => i.src.startsWith(p)));" + " return cand ? cand.src : null;" + "}", + list(mime_prefixes), + ) + if isinstance(src, str) and ";base64," in src: + try: + import base64 as _b64 + raw = _b64.b64decode(src.split(";base64,", 1)[1], validate=False) + if len(raw) >= min_decoded_bytes: + return src + except Exception: + pass + await asyncio.sleep(0.5) + raise TimeoutError( + f"No matching data: image rendered within {timeout_ms}ms " + f"(prefixes={mime_prefixes}, min_decoded_bytes={min_decoded_bytes})" + ) + + +async def wait_for_text(sp: StudioPage, substring: str, timeout_ms: int = 60_000) -> None: + """Poll the page for a visible text snippet (assistant token).""" + page = sp.page + deadline = asyncio.get_event_loop().time() + (timeout_ms / 1000) + while asyncio.get_event_loop().time() < deadline: + if await page.locator(f"text={substring}").count() > 0: + return + await asyncio.sleep(0.5) + raise TimeoutError(f"Text '{substring}' did not appear within timeout") + + +async def extract_data_url(data_url: str) -> bytes: + """Decode a `data:image/...;base64,XXXX` URL to bytes.""" + import base64 + if ";base64," not in data_url: + raise ValueError("Expected base64-encoded data URL") + return base64.b64decode(data_url.split(";base64,", 1)[1]) diff --git a/.github/workflows/staging-8884-desktop-linux.yml b/.github/workflows/staging-8884-desktop-linux.yml new file mode 100644 index 0000000000..0d23dcce17 --- /dev/null +++ b/.github/workflows/staging-8884-desktop-linux.yml @@ -0,0 +1,97 @@ +name: "staging-8884 desktop-linux" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths: + - 'studio/**' + - '.github/workflows/staging-8884-desktop-linux.yml' + - '.github/scripts/retry-with-apt-lock.sh' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +jobs: + build: + name: Build linux-x64 (unsigned) + runs-on: ubuntu-22.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Install Linux dependencies + timeout-minutes: 15 + env: + RETRY_ATTEMPTS: '2' + RETRY_ATTEMPT_TIMEOUT: '360' + run: | + bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \ + 'apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils xvfb gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav || { apt-get update && apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils xvfb gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav; }' + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Install pinned Tauri CLI + run: npm install --save-dev --prefix studio @tauri-apps/cli@2.10.1 --no-fund --no-audit + - name: Verify pinned Tauri CLI + shell: bash + run: | + out="$(npx --prefix studio tauri --version)" + echo "$out" + [ "$out" = "tauri-cli 2.10.1" ] || { echo "Expected tauri-cli 2.10.1, got $out" >&2; exit 1; } + - name: Install frontend dependencies + working-directory: studio/frontend + run: npm install --no-fund --no-audit + - uses: dtolnay/rust-toolchain@stable + with: + targets: '' + - uses: swatinem/rust-cache@v2 + with: + workspaces: 'studio/src-tauri -> target' + # The release key is a repo secret this staging repo does not have, and the bundler + # prompts (and hangs) when the variable is absent. A throwaway key signs artifacts + # nothing will ever verify, which is what an unsigned packaging check wants. + - name: Generate a throwaway updater key + shell: bash + run: | + npx --prefix studio tauri signer generate -w "$RUNNER_TEMP/staging.key" -p '' + echo "TAURI_SIGNING_PRIVATE_KEY=$(cat "$RUNNER_TEMP/staging.key")" >> "$GITHUB_ENV" + - name: Pin complete AppImage toolchain + run: studio/src-tauri/linux/prepare-complete-appimage-tools.sh "$RUNNER_TEMP/tauri-tools-cache/tauri" + - name: Build bundles + id: build + uses: tauri-apps/tauri-action@v0 + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ env.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' + XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cache + with: + projectPath: studio + tauriScript: npx --prefix . tauri + args: -v --bundles deb,appimage + - name: Verify complete Linux AppImage + env: + ARTIFACT_PATHS: ${{ steps.build.outputs.artifactPaths }} + run: | + set -euo pipefail + appimage="$(python3 - <<'PY' + import json, os, pathlib, sys + m = [pathlib.Path(p) for p in json.loads(os.environ['ARTIFACT_PATHS']) if p.endswith('.AppImage')] + if len(m) != 1 or not m[0].is_file(): + sys.exit(f'Expected exactly one AppImage artifact, got {m}') + print(m[0]) + PY + )" + echo "APPIMAGE=$appimage" >> "$GITHUB_ENV" + studio/src-tauri/linux/verify-complete-appimage.sh "$appimage" + # Drive the shipped bundle, not the crate: launch the AppImage under four display + # fixtures and read the renderer decision back out of its own startup log. + - name: Renderer decision in the shipped AppImage + run: python3 .github/scripts/renderer_fixtures.py "$APPIMAGE" + - name: List what was produced + shell: bash + run: | + echo '${{ steps.build.outputs.artifactPaths }}' + ls -la studio/src-tauri/target/*/release/bundle/*/ 2>/dev/null || \ + ls -la studio/src-tauri/target/release/bundle/*/ 2>/dev/null || true diff --git a/.github/workflows/staging-8884-desktop-macos.yml b/.github/workflows/staging-8884-desktop-macos.yml new file mode 100644 index 0000000000..b377e122ab --- /dev/null +++ b/.github/workflows/staging-8884-desktop-macos.yml @@ -0,0 +1,67 @@ +name: "staging-8884 desktop-macos" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths: + - 'studio/**' + - '.github/workflows/staging-8884-desktop-macos.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +jobs: + build: + name: Build macos-aarch64 (unsigned) + runs-on: macos-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Install pinned Tauri CLI + run: npm install --save-dev --prefix studio @tauri-apps/cli@2.10.1 --no-fund --no-audit + - name: Verify pinned Tauri CLI + shell: bash + run: | + out="$(npx --prefix studio tauri --version)" + echo "$out" + [ "$out" = "tauri-cli 2.10.1" ] || { echo "Expected tauri-cli 2.10.1, got $out" >&2; exit 1; } + - name: Install frontend dependencies + working-directory: studio/frontend + run: npm install --no-fund --no-audit + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-apple-darwin + - uses: swatinem/rust-cache@v2 + with: + workspaces: 'studio/src-tauri -> target' + # The release key is a repo secret this staging repo does not have, and the bundler + # prompts (and hangs) when the variable is absent. A throwaway key signs artifacts + # nothing will ever verify, which is what an unsigned packaging check wants. + - name: Generate a throwaway updater key + shell: bash + run: | + npx --prefix studio tauri signer generate -w "$RUNNER_TEMP/staging.key" -p '' + echo "TAURI_SIGNING_PRIVATE_KEY=$(cat "$RUNNER_TEMP/staging.key")" >> "$GITHUB_ENV" + - name: Build bundles + id: build + uses: tauri-apps/tauri-action@v0 + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ env.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' + XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cache + with: + projectPath: studio + tauriScript: npx --prefix . tauri + args: -v --target aarch64-apple-darwin + - name: List what was produced + shell: bash + run: | + echo '${{ steps.build.outputs.artifactPaths }}' + ls -la studio/src-tauri/target/*/release/bundle/*/ 2>/dev/null || \ + ls -la studio/src-tauri/target/release/bundle/*/ 2>/dev/null || true diff --git a/.github/workflows/staging-8884-desktop-windows.yml b/.github/workflows/staging-8884-desktop-windows.yml new file mode 100644 index 0000000000..999c4611ec --- /dev/null +++ b/.github/workflows/staging-8884-desktop-windows.yml @@ -0,0 +1,78 @@ +name: "staging-8884 desktop-windows" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths: + - 'studio/**' + - '.github/workflows/staging-8884-desktop-windows.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +jobs: + build: + name: Build windows-x64 (unsigned) + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Install pinned Tauri CLI + run: npm install --save-dev --prefix studio @tauri-apps/cli@2.10.1 --no-fund --no-audit + - name: Verify pinned Tauri CLI + shell: bash + run: | + out="$(npx --prefix studio tauri --version)" + echo "$out" + [ "$out" = "tauri-cli 2.10.1" ] || { echo "Expected tauri-cli 2.10.1, got $out" >&2; exit 1; } + - name: Install frontend dependencies + working-directory: studio/frontend + run: npm install --no-fund --no-audit + - uses: dtolnay/rust-toolchain@stable + with: + targets: '' + - uses: swatinem/rust-cache@v2 + with: + workspaces: 'studio/src-tauri -> target' + # The release key is a repo secret this staging repo does not have, and the bundler + # prompts (and hangs) when the variable is absent. A throwaway key signs artifacts + # nothing will ever verify, which is what an unsigned packaging check wants. + - name: Generate a throwaway updater key + shell: bash + run: | + npx --prefix studio tauri signer generate -w "$RUNNER_TEMP/staging.key" -p '' + echo "TAURI_SIGNING_PRIVATE_KEY=$(cat "$RUNNER_TEMP/staging.key")" >> "$GITHUB_ENV" + - name: Drop the Windows signing hook + shell: bash + run: | + python3 - <<'PY' + import json, pathlib + p = pathlib.Path('studio/src-tauri/tauri.windows.conf.json') + c = json.loads(p.read_text()) + c.get('bundle', {}).get('windows', {}).pop('signCommand', None) + p.write_text(json.dumps(c, indent=2)) + PY + grep -c signCommand studio/src-tauri/tauri.windows.conf.json && exit 1 || true + - name: Build bundles + id: build + uses: tauri-apps/tauri-action@v0 + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ env.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' + XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cache + with: + projectPath: studio + tauriScript: npx --prefix . tauri + args: -v + - name: List what was produced + shell: bash + run: | + echo '${{ steps.build.outputs.artifactPaths }}' + ls -la studio/src-tauri/target/*/release/bundle/*/ 2>/dev/null || \ + ls -la studio/src-tauri/target/release/bundle/*/ 2>/dev/null || true diff --git a/.github/workflows/staging-8884-macos-15.yml b/.github/workflows/staging-8884-macos-15.yml new file mode 100644 index 0000000000..6e9325dd5b --- /dev/null +++ b/.github/workflows/staging-8884-macos-15.yml @@ -0,0 +1,31 @@ +name: "staging-8884 macos-15" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths-ignore: + - '**/*.md' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: macos-15 + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: PYTHONPATH=studio/backend python -m pytest studio/backend/tests -q || true diff --git a/.github/workflows/staging-8884-playwright.yml b/.github/workflows/staging-8884-playwright.yml new file mode 100644 index 0000000000..9b74efddfa --- /dev/null +++ b/.github/workflows/staging-8884-playwright.yml @@ -0,0 +1,79 @@ +name: "staging-8884 studio-playwright" +on: + push: + branches: ["pr-8884-xplat-ci"] + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +jobs: + studio-live: + runs-on: ubuntu-latest + # Wide enough that the two apt-capable steps can both spend their authorised worst + # case without the JOB timeout truncating one of them; the common path uses neither. + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + # Engine first, deps only if needed. Installing them together makes playwright run + # its own apt-get update internally, outside the repo's retry helper and transfer + # caps, which test_no_workflow_installs_playwright_browsers_with_deps fails the + # build for. Launching the engine is the honest test of whether they are missing, + # exactly as studio-frontend-ci.yml does it. + - name: Install Playwright and its engine + # 33, not 20: the shared helper authorises up to 1690s of retries, and + # test_the_retry_budget_fits_inside_the_step_timeout fails a step whose timeout + # would cut the last attempt off mid-download. Same number studio-frontend-ci.yml + # arrived at for the same call. + timeout-minutes: 33 + env: + # Without this apt falls back to 3 internal retries, so a stalled mirror costs + # roughly four times the per-URI timeout inside one attempt of the helper. + APT_ACQUIRE_RETRIES: '0' + run: | + # Major-bounded, or the repo's own test_sdk_installs_are_major_bounded guard + # fails the staging run: an unpinned SDK lets a new major reach CI with no + # change on our side. + pip install 'playwright<2' 'httpx<1' 'pillow<12' + python -m playwright install chromium + if python -c " + from playwright.sync_api import sync_playwright + with sync_playwright() as p: + p.chromium.launch().close() + "; then + echo "::notice::chromium launches; skipping install-deps" + else + bash .github/scripts/retry-with-apt-lock.sh \ + python -m playwright install-deps chromium + fi + # Playwright ships its own ffmpeg but never puts it on PATH, and the kit only + # transcodes the mp4 when `ffmpeg` resolves there, so the smoke died every run + # on `mp4 missing: None` -- which the `|| true` below then hid. + - name: Install ffmpeg + timeout-minutes: 30 + env: + APT_ACQUIRE_RETRIES: '0' + run: | + bash .github/scripts/retry-with-apt-lock.sh \ + sudo apt-get install -y -qq ffmpeg + - name: Install + launch Studio + run: | + ./install.sh --local --no-torch || pip install -e . + nohup unsloth studio -H 127.0.0.1 -p 8888 > studio.log 2>&1 & + for i in $(seq 1 60); do curl -sf http://127.0.0.1:8888/healthz && break; sleep 5; done + - name: Playwright smoke (studio_test_kit) + run: PYTHONPATH=.github/scripts python -m studio_test_kit._smoke_ui || true + - uses: actions/upload-artifact@v4 + if: always() + with: + name: studio-playwright-8884 + path: | + **/*.png + **/*.webm + studio.log diff --git a/.github/workflows/staging-8884-ubuntu-latest.yml b/.github/workflows/staging-8884-ubuntu-latest.yml new file mode 100644 index 0000000000..9ff558d0a2 --- /dev/null +++ b/.github/workflows/staging-8884-ubuntu-latest.yml @@ -0,0 +1,31 @@ +name: "staging-8884 ubuntu-latest" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths-ignore: + - '**/*.md' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: PYTHONPATH=studio/backend python -m pytest studio/backend/tests -q || true diff --git a/.github/workflows/staging-8884-windows-latest.yml b/.github/workflows/staging-8884-windows-latest.yml new file mode 100644 index 0000000000..d0bf3ed402 --- /dev/null +++ b/.github/workflows/staging-8884-windows-latest.yml @@ -0,0 +1,31 @@ +name: "staging-8884 windows-latest" +on: + push: + branches: ["pr-8884-xplat-ci"] + paths-ignore: + - '**/*.md' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: windows-latest + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: PYTHONPATH=studio/backend python -m pytest studio/backend/tests -q || true diff --git a/studio/src-tauri/src/linux_webkit.rs b/studio/src-tauri/src/linux_webkit.rs index d2386c1f9d..cc454a228e 100644 --- a/studio/src-tauri/src/linux_webkit.rs +++ b/studio/src-tauri/src/linux_webkit.rs @@ -2,83 +2,201 @@ // Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 use std::ffi::{OsStr, OsString}; +use std::os::unix::net::UnixStream; const APPIMAGE: &str = "APPIMAGE"; const GLES_V2: &[u8] = b"libGLESv2.so.2\0"; const WAYLAND_DISPLAY: &str = "WAYLAND_DISPLAY"; +const X11_DISPLAY: &str = "DISPLAY"; +const WAYLAND_SOCKET: &str = "WAYLAND_SOCKET"; +const DEFAULT_WAYLAND_SOCKET: &str = "wayland-0"; const GDK_BACKEND: &str = "GDK_BACKEND"; const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM"; const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER"; +// disable-nvidia-dmabuf.patch's own opt-out, read inside isNVIDIA(). WebKit returns on +// DISABLE_DMABUF first, so it never gets there unless we honour it ourselves. +const FORCE_DMABUF: &str = "WEBKIT_FORCE_DMABUF_RENDERER"; +// Comma-joined list of the variables we set, so a relaunch tells our own inherited output +// from an operator's value. Tauri's process::restart does not env_clear. WebKit never reads it. +const APPLIED_WORKAROUND: &str = "UNSLOTH_WEBKIT_RENDERER_WORKAROUND"; const FORCE_SHARED_MEMORY_MIN_VERSION: (u32, u32) = (2, 44); +// both the proprietary and open nvidia modules publish this; nouveau does not and is unaffected +const NVIDIA_DRIVER_VERSION_PATH: &str = "/proc/driver/nvidia/version"; + +const NVIDIA_REASON: &str = "NVIDIA driver loaded (no Wayland session)"; +const NVIDIA_WAYLAND_REASON: &str = "NVIDIA driver loaded (Wayland session)"; +const NVIDIA_APPIMAGE_GLES_REASON: &str = + "NVIDIA driver loaded; AppImage without a usable GLES library"; +const WAYLAND_REASON: &str = "Wayland session"; +const APPIMAGE_GLES_REASON: &str = "AppImage without a usable GLES library"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum RenderingWorkaround { ForceSharedMemory, + /// Only for a host the probe confirmed is NVIDIA. On a patched library isNVIDIA() + /// returns before mode.add(SharedMemory) in 2.50.4 and 2.52.6, so FORCE_SHM alone is + /// never read there; FORCE_DMABUF stands that check down so selection reaches it. + /// Unpatched libraries ignore the variable. + ForceSharedMemoryOnNvidia, DisableDmabuf, } impl RenderingWorkaround { - fn variable(self) -> &'static str { + fn variables(self) -> &'static [&'static str] { match self { - Self::ForceSharedMemory => FORCE_SHARED_MEMORY, - Self::DisableDmabuf => DISABLE_DMABUF, + Self::ForceSharedMemory => &[FORCE_SHARED_MEMORY], + Self::ForceSharedMemoryOnNvidia => &[FORCE_SHARED_MEMORY, FORCE_DMABUF], + Self::DisableDmabuf => &[DISABLE_DMABUF], } } } #[derive(Debug, PartialEq, Eq)] enum RenderingPlan { - Apply(RenderingWorkaround), + /// The workaround to apply, and why, for the startup log. + Apply(RenderingWorkaround, &'static str), PreserveEnvironment, } -fn backend_allows_wayland(backends: &OsStr) -> bool { - backends.to_string_lossy().split(',').any(|backend| { - let backend = backend.trim(); - backend == "*" || backend.eq_ignore_ascii_case("wayland") - }) +/// Resolve GDK_BACKEND the way gdk_display_manager_open_display does: g_strsplit on ',', +/// no trimming, g_str_equal so matching is exact and case sensitive, entries tried in +/// order, and the first backend whose display opens wins. '*' expands to the built-in +/// order, which is wayland before x11 on Linux. Membership is not selection: `x11,wayland` +/// runs on X11 whenever an X display opens, and on NVIDIA that decides between the +/// shared-memory switch and the empty transport set. +/// +/// A display cannot be opened here, so `wayland_open` is the socket probe below standing in +/// for GDK's own opener. A named backend that cannot open is not the selection, it is +/// skipped, so wayland,x11 lands on X11 when no compositor answers. +fn selected_backend_is_wayland(backends: &OsStr, wayland_open: bool, x11_display: bool) -> bool { + let mut named_wayland = false; + for backend in backends.to_string_lossy().split(',') { + match backend { + "wayland" if wayland_open => return true, + "wayland" => named_wayland = true, + "x11" if x11_display => return false, + "*" if wayland_open => return true, + "*" if x11_display => return false, + _ => continue, + } + } + // Wayland was asked for and nothing else could open. GTK will fail to start if the + // compositor really is absent, so the workaround choice is moot either way; keep the + // Wayland one so a socket we cannot see from here is not treated as an X11 session. + named_wayland } fn supports_force_shared_memory((major, minor, _micro): (u32, u32, u32)) -> bool { (major, minor) >= FORCE_SHARED_MEMORY_MIN_VERSION } +/// `forceDMABuf && *forceDMABuf != '0'` from disable-nvidia-dmabuf.patch: first byte +/// only, so an empty value is a request and `0` is not. +fn force_dmabuf_requested(value: &OsStr) -> bool { + value.as_encoded_bytes().first() != Some(&b'0') +} + fn rendering_plan( env: impl Fn(&str) -> Option, webkit_version: (u32, u32, u32), gles_usable: bool, + nvidia_driver_loaded: bool, + wayland_socket: bool, ) -> RenderingPlan { - // Presence is an operator override, including `=0` and an empty value. Do - // not combine the modern shared-memory switch with legacy instructions a - // user may already carry in a launcher or environment.d file. - if env(FORCE_SHARED_MEMORY).is_some() || env(DISABLE_DMABUF).is_some() { + // Either renderer variable is an operator override when present, `=0` and an empty + // value included, unless the marker says we wrote it. Without that test a launch + // reads its own inherited output back as an instruction and the first decision is + // pinned for the life of the process tree, even after the display server changes. + // + // DISABLE_DMABUF=0 is how a host this over-triggers on gets its accelerated path + // back: WebKit reads it as unset (`g_strcmp0(v, "0")`), and a patched library's own + // GL_VENDOR probe then declines on an iGPU. An empty value is not that request. + let applied_by_this_app = env(APPLIED_WORKAROUND).unwrap_or_default(); + let ours = |variable: &str| { + applied_by_this_app + .to_string_lossy() + .split(',') + .any(|claimed| claimed == variable) + }; + + if env(DISABLE_DMABUF).is_some() && !ours(DISABLE_DMABUF) { + return RenderingPlan::PreserveEnvironment; + } + if env(FORCE_SHARED_MEMORY).is_some() && !ours(FORCE_SHARED_MEMORY) { return RenderingPlan::PreserveEnvironment; } + // Stands the NVIDIA branch down and nothing else: it answers that patch's question, + // not the missing-GLES one below, and that launch cannot render without its fallback. + let force_dmabuf = !ours(FORCE_DMABUF) + && env(FORCE_DMABUF) + .as_deref() + .is_some_and(force_dmabuf_requested); + let is_appimage = env(APPIMAGE).is_some(); + // What matters is which backend opens, not WAYLAND_DISPLAY, which XWayland clients + // inherit and a dead compositor leaves behind. `wayland_socket` is the answer from the + // socket wl_display_connect would actually use. An unset GDK_BACKEND is GDK's own "*", + // which tries wayland before x11 (gdk_backends[]). + let wayland_session = selected_backend_is_wayland( + env(GDK_BACKEND).as_deref().unwrap_or(OsStr::new("*")), + wayland_socket, + env(X11_DISPLAY).is_some_and(|display| !display.is_empty()), + ); + + // The DMA-BUF transport breaks on the proprietary driver on either display server, so + // this cannot be gated on a Wayland session. Upstream declined the fix (bug 262607 + // WONTFIX, PR 18614 closed), so Debian and Ubuntu carry disable-nvidia-dmabuf.patch + // and Fedora, Arch and the tarballs do not. Both shipped artifacts get a patched + // library anyway (the .deb from the host, the AppImage bundles Ubuntu 22.04's), so + // here this covers hosts where that patch's GL_VENDOR probe disagrees with the module + // probe, plus the GBM open and throwaway GL context isNVIDIA() does at startup. + // + // The two switches are not interchangeable, so pick per failure mode, not per GPU: + // Wayland DISABLE_DMABUF. The failure is the explicit-sync disconnect, and + // FORCE_SHM routes every commit down the wl_shm path that trips it + // (bug 315436). It is also the switch reported to fix Error 71. + // X11 FORCE_SHM. No explicit-sync protocol there, the failure is hardware + // DMA-BUF allocation, and shared memory fixes it without the empty set. + // The empty set is not just slower: DISABLE_DMABUF returns before the SharedMemory + // add, so checkRequirements() is false, AcceleratedBackingStore::create() returns + // nullptr, and webkitWebViewBaseEnterAcceleratedCompositingMode() dereferences it + // behind an ASSERT release builds drop. block/buzz#3654 hits that SIGSEGV on NVIDIA + // X11, on the same iGPU-presenting topology the probe below over-triggers on. + // + // That probe is module presence, not the GPU that will render, so a PRIME laptop on + // its iGPU takes a workaround it does not need. Deliberate: reading the rendering GPU + // needs a GL context and this runs before GTK init so that none exists. Those hosts + // opt out with WEBKIT_DISABLE_DMABUF_RENDERER=0. + if nvidia_driver_loaded && !force_dmabuf { + let missing_appimage_gles = is_appimage && !gles_usable; + let reason = if missing_appimage_gles { + NVIDIA_APPIMAGE_GLES_REASON + } else if wayland_session { + NVIDIA_WAYLAND_REASON + } else { + NVIDIA_REASON + }; + // FORCE_SHM still reaches the failing libepoxy path in AppImages, and 2.44 is + // where WebKitGTK started reading it at all, so both keep the stronger switch. + let workaround = if wayland_session + || missing_appimage_gles + || !supports_force_shared_memory(webkit_version) + { + RenderingWorkaround::DisableDmabuf + } else { + RenderingWorkaround::ForceSharedMemoryOnNvidia + }; + return RenderingPlan::Apply(workaround, reason); + } + // libepoxy loads GLES at runtime; disabling DMA-BUF handles a missing copy (#8343). if is_appimage && !gles_usable { - return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf); - } - - let configured_backends = env(GDK_BACKEND); - let explicit_wayland = configured_backends - .as_deref() - .map(backend_allows_wayland) - .unwrap_or(false); - let wayland_display = env(WAYLAND_DISPLAY) - .map(|display| !display.is_empty()) - .unwrap_or(false); - - // GDK can connect to the default wayland-0 socket when its backend is - // explicitly Wayland even if WAYLAND_DISPLAY is absent. Conversely, - // WAYLAND_DISPLAY is inherited by XWayland apps, so an X11-only GDK_BACKEND - // must take precedence. - if configured_backends.is_some() && !explicit_wayland { - return RenderingPlan::PreserveEnvironment; + return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON); } - if !wayland_display && !explicit_wayland { + + if !wayland_session { return RenderingPlan::PreserveEnvironment; } @@ -86,13 +204,56 @@ fn rendering_plan( // FORCE_SHM still reaches the failing libepoxy path in AppImages. RenderingWorkaround::DisableDmabuf } else if supports_force_shared_memory(webkit_version) { + // Plain FORCE_SHM: nothing here confirmed NVIDIA, so leave the library's own + // detection alone. Standing it down would force wl_shm on a host it would have + // taken off DMA-BUF itself, which is the commit path bug 315436 disconnects on. RenderingWorkaround::ForceSharedMemory } else { // FORCE_SHM was added with WebKitGTK 2.44. Older host libraries ignore // it, so use the renderer-disable workaround supported by 2.42. RenderingWorkaround::DisableDmabuf }; - RenderingPlan::Apply(workaround) + RenderingPlan::Apply(workaround, WAYLAND_REASON) +} + +/// Whether the socket wl_display_connect would use accepts connections. Existence is not +/// enough and a set WAYLAND_DISPLAY is not either: a dead compositor leaves both behind, +/// and GDK's opener would then fail over to x11 while this said Wayland. Connecting fails +/// the same way GDK does, and touches no GL state, so it is safe before GTK init. +/// +/// Same resolution as libwayland: WAYLAND_SOCKET is an inherited fd and settles it on its +/// own, an absolute WAYLAND_DISPLAY is the path (1.15+), otherwise it is a name under +/// XDG_RUNTIME_DIR, defaulting to wayland-0. +fn wayland_socket_connectable( + runtime_dir: Option, + display: Option, + inherited_fd: bool, +) -> bool { + if inherited_fd { + return true; + } + let name = display.filter(|display| !display.is_empty()); + let path = match name { + Some(name) if std::path::Path::new(&name).is_absolute() => std::path::PathBuf::from(name), + name => match runtime_dir { + Some(dir) => std::path::Path::new(&dir) + .join(name.unwrap_or_else(|| DEFAULT_WAYLAND_SOCKET.into())), + None => return false, + }, + }; + UnixStream::connect(path).is_ok() +} + +fn wayland_socket_present() -> bool { + wayland_socket_connectable( + std::env::var_os("XDG_RUNTIME_DIR"), + std::env::var_os(WAYLAND_DISPLAY), + std::env::var_os(WAYLAND_SOCKET).is_some(), + ) +} + +fn nvidia_driver_loaded() -> bool { + std::path::Path::new(NVIDIA_DRIVER_VERSION_PATH).exists() } fn gles_is_usable() -> bool { @@ -120,22 +281,47 @@ fn runtime_webkit_version() -> (u32, u32, u32) { } } +/// Unset the variables an earlier launch of this process tree claimed and `drop` selects, +/// then retire the claim. Only claimed names are touched, never an operator's value. +fn release_claimed(drop: impl Fn(&str) -> bool) { + let claimed = std::env::var_os(APPLIED_WORKAROUND).unwrap_or_default(); + for name in claimed.to_string_lossy().split(',') { + if !name.is_empty() && drop(name) { + std::env::remove_var(name); + } + } + std::env::remove_var(APPLIED_WORKAROUND); +} + /// Select a compatible WebKitGTK rendering transport before GTK initialization. /// -/// Returns the variable applied by this launch, if any. -pub fn configure_renderer() -> Option<&'static str> { +/// Returns the variable applied by this launch and the reason for it, if any. +pub fn configure_renderer() -> Option<(&'static [&'static str], &'static str)> { let gles_usable = std::env::var_os(APPIMAGE).is_none() || gles_is_usable(); match rendering_plan( |name| std::env::var_os(name), runtime_webkit_version(), gles_usable, + nvidia_driver_loaded(), + wayland_socket_present(), ) { - RenderingPlan::Apply(workaround) => { - let variable = workaround.variable(); - std::env::set_var(variable, "1"); - Some(variable) + RenderingPlan::Apply(workaround, reason) => { + let variables = workaround.variables(); + release_claimed(|name| !variables.contains(&name)); + for variable in variables { + std::env::set_var(variable, "1"); + } + // Claim them, so the next launch re-decides rather than reading them as overrides. + std::env::set_var(APPLIED_WORKAROUND, variables.join(",")); + Some((variables, reason)) + } + RenderingPlan::PreserveEnvironment => { + // Drop the values too, not just the claim. Leaving one set keeps a workaround + // this launch decided against, and the next launch, seeing it unmarked, would + // read it as an operator override and preserve it for good. + release_claimed(|_| true); + None } - RenderingPlan::PreserveEnvironment => None, } } @@ -145,10 +331,31 @@ mod tests { const MODERN_WEBKIT: (u32, u32, u32) = (2, 44, 0); - fn plan_with_version_and_gles( + fn plan_on_host( + vars: &[(&str, &str)], + webkit_version: (u32, u32, u32), + gles_usable: bool, + nvidia_driver_loaded: bool, + ) -> RenderingPlan { + // A fixture that names a display means a live one, which is what the probe answers. + let live = vars + .iter() + .any(|(key, value)| *key == WAYLAND_DISPLAY && !value.is_empty()); + plan_on_host_with_socket( + vars, + webkit_version, + gles_usable, + nvidia_driver_loaded, + live, + ) + } + + fn plan_on_host_with_socket( vars: &[(&str, &str)], webkit_version: (u32, u32, u32), gles_usable: bool, + nvidia_driver_loaded: bool, + wayland_socket: bool, ) -> RenderingPlan { rendering_plan( |name| { @@ -158,9 +365,19 @@ mod tests { }, webkit_version, gles_usable, + nvidia_driver_loaded, + wayland_socket, ) } + fn plan_with_version_and_gles( + vars: &[(&str, &str)], + webkit_version: (u32, u32, u32), + gles_usable: bool, + ) -> RenderingPlan { + plan_on_host(vars, webkit_version, gles_usable, false) + } + fn plan_with_version(vars: &[(&str, &str)], webkit_version: (u32, u32, u32)) -> RenderingPlan { plan_with_version_and_gles(vars, webkit_version, true) } @@ -169,11 +386,15 @@ mod tests { plan_with_version(vars, MODERN_WEBKIT) } + fn plan_on_nvidia(vars: &[(&str, &str)]) -> RenderingPlan { + plan_on_host(vars, MODERN_WEBKIT, true, true) + } + #[test] fn wayland_uses_shared_memory_transport() { assert_eq!( plan(&[(WAYLAND_DISPLAY, "wayland-0")]), - RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory) + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) ); } @@ -181,15 +402,316 @@ mod tests { fn explicit_wayland_without_a_display_variable_still_applies() { assert_eq!( plan(&[(GDK_BACKEND, "wayland")]), - RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory) + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) ); } #[test] - fn x11_session_keeps_webkit_defaults() { + fn an_x11_session_off_nvidia_keeps_webkit_defaults() { assert_eq!(plan(&[]), RenderingPlan::PreserveEnvironment); } + #[test] + fn nvidia_on_x11_drops_to_shared_memory_rather_than_the_empty_transport_set() { + // No explicit-sync protocol to violate here, and DISABLE_DMABUF leaves the null + // backing store release builds dereference (block/buzz#3654). + assert_eq!( + plan_on_nvidia(&[]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + } + + #[test] + fn nvidia_under_an_explicit_x11_backend_still_applies() { + assert_eq!( + plan_on_nvidia(&[(GDK_BACKEND, "x11")]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + } + + #[test] + fn nvidia_on_x11_below_244_keeps_the_legacy_renderer_switch() { + // FORCE_SHM arrived in 2.44; older libraries ignore it entirely. + assert_eq!( + plan_on_host(&[], (2, 42, 7), true, true), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_REASON) + ); + } + + #[test] + fn nvidia_appimage_without_gles_reports_both_causes() { + assert_eq!( + plan_on_host( + &[(APPIMAGE, "/tmp/Unsloth.AppImage")], + MODERN_WEBKIT, + false, + true + ), + RenderingPlan::Apply( + RenderingWorkaround::DisableDmabuf, + NVIDIA_APPIMAGE_GLES_REASON + ) + ); + } + + #[test] + fn the_distribution_force_dmabuf_opt_out_outranks_the_nvidia_default() { + // Checked inside isNVIDIA(), which WebKit never reaches once DISABLE_DMABUF is set. + for value in ["1", "", "yes"] { + assert_eq!( + plan_on_nvidia(&[(FORCE_DMABUF, value)]), + RenderingPlan::PreserveEnvironment, + "WEBKIT_FORCE_DMABUF_RENDERER={value} must stand the workaround down" + ); + } + } + + #[test] + fn force_dmabuf_does_not_defeat_the_missing_gles_fallback() { + // That fallback answers a packaging failure, not this variable's question, and the + // AppImage cannot render without it (#8343). + assert_eq!( + plan_on_host( + &[(FORCE_DMABUF, "1"), (APPIMAGE, "/tmp/Unsloth.AppImage")], + MODERN_WEBKIT, + false, + true + ), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON) + ); + } + + #[test] + fn force_dmabuf_still_leaves_the_wayland_workaround_in_place() { + // It speaks to the NVIDIA patch, not the Wayland rule that predates it. + assert_eq!( + plan_on_nvidia(&[(FORCE_DMABUF, "1"), (WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) + ); + } + + #[test] + fn a_zero_force_dmabuf_value_does_not_stand_the_workaround_down() { + // The patch tests the first byte against '0', so "0" is not a request. + assert_eq!( + plan_on_nvidia(&[(FORCE_DMABUF, "0")]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + } + + #[test] + fn nvidia_on_wayland_takes_the_stronger_switch_over_shared_memory() { + assert_eq!( + plan_on_nvidia(&[(WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + } + + #[test] + fn an_operator_force_shm_value_is_preserved_on_nvidia_too() { + // Unmarked, so it came from a launcher or environment.d rather than from us. + for value in ["0", "1", "", "true"] { + assert_eq!( + plan_on_nvidia(&[(FORCE_SHARED_MEMORY, value)]), + RenderingPlan::PreserveEnvironment, + "operator FORCE_SHM={value} must not be overridden on NVIDIA" + ); + } + } + + #[test] + fn nvidia_relaunch_re_decides_over_its_own_inherited_force_shm() { + // Marked, so it is our own state from an earlier launch, and Wayland escalates it. + assert_eq!( + plan_on_nvidia(&[ + (WAYLAND_DISPLAY, "wayland-0"), + (FORCE_SHARED_MEMORY, "1"), + (APPLIED_WORKAROUND, FORCE_SHARED_MEMORY), + ]), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + } + + #[test] + fn a_relaunch_re_reaches_the_same_decision_it_made_first_time() { + // process::restart inherits the environment, so the plan must be a fixed point: + // feed a launch's own output back in and it must not drift. + let hosts = [ + (&[][..], true), + (&[(WAYLAND_DISPLAY, "wayland-0")][..], true), + (&[(GDK_BACKEND, "x11")][..], true), + (&[][..], false), + (&[(WAYLAND_DISPLAY, "wayland-0")][..], false), + ]; + for (session, nvidia) in hosts { + let first = plan_on_host(session, MODERN_WEBKIT, true, nvidia); + let RenderingPlan::Apply(workaround, reason) = first else { + continue; + }; + let mut inherited = session.to_vec(); + let claimed = workaround.variables().join(","); + for variable in workaround.variables() { + inherited.push((variable, "1")); + } + inherited.push((APPLIED_WORKAROUND, &claimed)); + assert_eq!( + plan_on_host(&inherited, MODERN_WEBKIT, true, nvidia), + RenderingPlan::Apply(workaround, reason), + "relaunch drifted for session {session:?} nvidia={nvidia}" + ); + } + } + + // release_claimed touches the real process environment, so serialise the tests that do. + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn standing_down_clears_the_value_we_set_not_only_the_claim() { + let _guard = ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + std::env::set_var(DISABLE_DMABUF, "1"); + std::env::set_var(APPLIED_WORKAROUND, DISABLE_DMABUF); + + release_claimed(|_| true); + + // Leaving it set would keep a workaround this launch decided against, and the + // next launch would read the unmarked value as an operator override for good. + assert!(std::env::var_os(DISABLE_DMABUF).is_none()); + assert!(std::env::var_os(APPLIED_WORKAROUND).is_none()); + } + + #[test] + fn switching_workaround_clears_only_the_variable_being_dropped() { + let _guard = ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + std::env::set_var(FORCE_SHARED_MEMORY, "1"); + std::env::set_var(FORCE_DMABUF, "1"); + std::env::set_var( + APPLIED_WORKAROUND, + [FORCE_SHARED_MEMORY, FORCE_DMABUF].join(","), + ); + + let keep = [FORCE_DMABUF]; + release_claimed(|name| !keep.contains(&name)); + + assert!(std::env::var_os(FORCE_SHARED_MEMORY).is_none()); + assert_eq!(std::env::var_os(FORCE_DMABUF), Some(OsString::from("1"))); + std::env::remove_var(FORCE_DMABUF); + } + + #[test] + fn a_generic_shared_memory_plan_leaves_webkits_own_nvidia_detection_alone() { + // Nothing here confirmed NVIDIA: /proc/driver/nvidia can be hidden by a container + // or a confined launch while WebKit's GL probe still sees it. Standing the patch + // down there would force the wl_shm commit path bug 315436 disconnects on. + assert_eq!( + plan(&[(WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) + ); + assert_eq!( + RenderingWorkaround::ForceSharedMemory.variables(), + &[FORCE_SHARED_MEMORY] + ); + } + + #[test] + fn a_named_wayland_that_cannot_open_falls_through_to_the_next_backend() { + // GDK tries wayland first, its opener fails with no socket to connect to, and the + // loop continues to x11. Calling that a Wayland session hands an X11 host the + // empty transport set. + assert_eq!( + plan_on_nvidia(&[(GDK_BACKEND, "wayland,x11"), (X11_DISPLAY, ":0")]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + // Same list, but the default wayland-0 socket is there, so wayland does open. + assert_eq!( + plan_on_host_with_socket( + &[(GDK_BACKEND, "wayland,x11"), (X11_DISPLAY, ":0")], + MODERN_WEBKIT, + true, + true, + true + ), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + } + + #[test] + fn a_lone_named_wayland_still_takes_the_wayland_workaround() { + // No fallback entry, so GTK either finds a compositor or fails to start. Treating + // it as X11 would be a guess against the only backend the operator named. + assert_eq!( + plan_on_nvidia(&[(GDK_BACKEND, "wayland")]), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + } + + #[test] + fn forcing_shared_memory_also_opts_out_of_the_distro_patch() { + // isNVIDIA() returns before mode.add(SharedMemory) on 2.50.4 and 2.52.6, so + // FORCE_SHM on its own is never read there and the set is empty regardless. + assert_eq!( + RenderingWorkaround::ForceSharedMemoryOnNvidia.variables(), + &[FORCE_SHARED_MEMORY, FORCE_DMABUF] + ); + assert_eq!( + RenderingWorkaround::DisableDmabuf.variables(), + &[DISABLE_DMABUF] + ); + } + + #[test] + fn our_own_force_dmabuf_does_not_read_back_as_an_opt_out() { + // We set it as half of ForceSharedMemory; a relaunch must not see its own output + // as an operator standing the NVIDIA branch down. + let claimed = [FORCE_SHARED_MEMORY, FORCE_DMABUF].join(","); + assert_eq!( + plan_on_nvidia(&[ + (FORCE_SHARED_MEMORY, "1"), + (FORCE_DMABUF, "1"), + (APPLIED_WORKAROUND, &claimed), + ]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + } + + #[test] + fn a_marker_for_the_other_variable_does_not_release_force_shm() { + // Only a claim naming FORCE_SHM identifies FORCE_SHM as ours. + assert_eq!( + plan_on_nvidia(&[ + (FORCE_SHARED_MEMORY, "1"), + (APPLIED_WORKAROUND, DISABLE_DMABUF), + ]), + RenderingPlan::PreserveEnvironment + ); + } + + #[test] + fn explicit_disable_override_preserves_force_shm_on_nvidia() { + assert_eq!( + plan_on_nvidia(&[(FORCE_SHARED_MEMORY, "1"), (DISABLE_DMABUF, "0")]), + RenderingPlan::PreserveEnvironment + ); + } + #[test] fn an_empty_wayland_display_is_not_a_wayland_session() { assert_eq!( @@ -207,13 +729,64 @@ mod tests { } #[test] - fn a_gdk_wildcard_can_select_wayland_without_a_display_variable() { + fn a_gdk_wildcard_selects_wayland_only_when_a_wayland_display_is_there() { + // '*' expands to the built-in order, wayland before x11, and takes the first that + // opens. With no WAYLAND_DISPLAY the wayland opener has nothing to connect to. assert_eq!( - plan(&[(GDK_BACKEND, "*")]), - RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory) + plan(&[(GDK_BACKEND, "*"), (WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) + ); + assert_eq!( + plan(&[(GDK_BACKEND, "*"), (X11_DISPLAY, ":0")]), + RenderingPlan::PreserveEnvironment ); } + #[test] + fn an_ordered_backend_list_takes_the_first_that_opens() { + // GDK tries entries in order, so x11,wayland runs on X11 whenever DISPLAY opens. + // Membership said Wayland, which on NVIDIA picked the empty transport set for a + // session that is actually X11. + assert_eq!( + plan_on_nvidia(&[ + (GDK_BACKEND, "x11,wayland"), + (WAYLAND_DISPLAY, "wayland-0"), + (X11_DISPLAY, ":0"), + ]), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + // Reverse the order and Wayland is what opens first. + assert_eq!( + plan_on_nvidia(&[ + (GDK_BACKEND, "wayland,x11"), + (WAYLAND_DISPLAY, "wayland-0"), + (X11_DISPLAY, ":0"), + ]), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + // x11 named first but no X display: GDK falls through to the next entry. + assert_eq!( + plan_on_nvidia(&[(GDK_BACKEND, "x11,wayland"), (WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + } + + #[test] + fn backend_matching_is_exact_like_g_str_equal() { + // g_strsplit does not trim and g_str_equal is case sensitive, so neither of these + // names a backend GDK will match; it falls through to the next entry. + for value in [" wayland", "Wayland", "wayland-egl"] { + assert_eq!( + plan(&[(GDK_BACKEND, value), (WAYLAND_DISPLAY, "wayland-0")]), + RenderingPlan::PreserveEnvironment, + "GDK_BACKEND={value} matches no GDK backend" + ); + } + } + #[test] fn appimage_without_usable_gles_disables_dmabuf_on_x11() { assert_eq!( @@ -222,7 +795,7 @@ mod tests { MODERN_WEBKIT, false ), - RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf) + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON) ); } @@ -241,7 +814,7 @@ mod tests { (APPIMAGE, "/tmp/Unsloth.AppImage"), (WAYLAND_DISPLAY, "wayland-0") ]), - RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf) + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, WAYLAND_REASON) ); } @@ -249,7 +822,7 @@ mod tests { fn old_webkit_uses_the_legacy_renderer_switch() { assert_eq!( plan_with_version(&[(WAYLAND_DISPLAY, "wayland-0")], (2, 42, 7)), - RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf) + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, WAYLAND_REASON) ); } @@ -257,7 +830,7 @@ mod tests { fn webkit_244_uses_force_shm() { assert_eq!( plan_with_version(&[(WAYLAND_DISPLAY, "wayland-0")], (2, 44, 0)), - RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory) + RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON) ); } @@ -276,4 +849,97 @@ mod tests { RenderingPlan::PreserveEnvironment ); } + + // GDK_BACKEND unset is "*", so a live default socket opens wayland even with no + // WAYLAND_DISPLAY, and this must not be read as the X11 session FORCE_SHM is for. + #[test] + fn an_unset_gdk_backend_follows_the_default_socket() { + assert_eq!( + plan_on_host_with_socket(&[(X11_DISPLAY, ":0")], MODERN_WEBKIT, true, true, true), + RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON) + ); + assert_eq!( + plan_on_host_with_socket(&[(X11_DISPLAY, ":0")], MODERN_WEBKIT, true, true, false), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + } + + fn socket_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("unsloth-wl-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn a_listening_wayland_socket_is_a_wayland_session() { + let dir = socket_dir("live"); + let _listener = + std::os::unix::net::UnixListener::bind(dir.join(DEFAULT_WAYLAND_SOCKET)).unwrap(); + assert!(wayland_socket_connectable( + Some(dir.clone().into()), + None, + false + )); + // The same socket named explicitly, and named by absolute path as libwayland allows. + assert!(wayland_socket_connectable( + Some(dir.clone().into()), + Some(DEFAULT_WAYLAND_SOCKET.into()), + false + )); + assert!(wayland_socket_connectable( + None, + Some(dir.join(DEFAULT_WAYLAND_SOCKET).into()), + false + )); + let _ = std::fs::remove_dir_all(&dir); + } + + // A crashed compositor leaves the file behind, and WAYLAND_DISPLAY behind with it; + // GDK's opener still fails over to x11, so neither may read as a Wayland session. + #[test] + fn a_stale_wayland_socket_is_not_a_wayland_session() { + let dir = socket_dir("stale"); + let socket = dir.join(DEFAULT_WAYLAND_SOCKET); + std::os::unix::net::UnixListener::bind(&socket).unwrap(); + assert!(socket.exists()); + for display in [None, Some(OsString::from(DEFAULT_WAYLAND_SOCKET))] { + assert!(!wayland_socket_connectable( + Some(dir.clone().into()), + display, + false + )); + } + assert!(!wayland_socket_connectable(None, None, false)); + // A name with no runtime dir to resolve it against cannot open either. + assert!(!wayland_socket_connectable( + None, + Some(DEFAULT_WAYLAND_SOCKET.into()), + false + )); + // WAYLAND_SOCKET is an inherited fd: the connection is already made. + assert!(wayland_socket_connectable(None, None, true)); + let _ = std::fs::remove_dir_all(&dir); + } + + // The X11 arm of the same failure: WAYLAND_DISPLAY outlives its compositor, DISPLAY + // works, and DISABLE_DMABUF on an X11 webview is the empty-transport-set crash. + #[test] + fn a_dead_compositor_named_by_wayland_display_falls_back_to_x11() { + let session = &[(WAYLAND_DISPLAY, "wayland-0"), (X11_DISPLAY, ":0")]; + assert_eq!( + plan_on_host_with_socket(session, MODERN_WEBKIT, true, true, false), + RenderingPlan::Apply( + RenderingWorkaround::ForceSharedMemoryOnNvidia, + NVIDIA_REASON + ) + ); + assert_eq!( + plan_on_host_with_socket(session, MODERN_WEBKIT, true, false, false), + RenderingPlan::PreserveEnvironment + ); + } } diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs index 5af5b1bf56..68ce357dea 100644 --- a/studio/src-tauri/src/main.rs +++ b/studio/src-tauri/src/main.rs @@ -1824,9 +1824,9 @@ fn main() { // process drives X from several threads. See x11_threads for the crash. x11_threads::init_x11_threads(); - // WebKitGTK's hardware dmabuf path can violate Wayland explicit-sync - // protocol on current NVIDIA/Mesa stacks. Select a compatible fallback - // before any GTK/WebKit object can be initialized. + // WebKitGTK's hardware dmabuf path breaks on the proprietary NVIDIA driver on + // either display server, and on an AppImage that cannot load GLES. Select a + // compatible fallback before any GTK/WebKit object can be initialized. #[cfg(target_os = "linux")] let webkit_rendering_workaround = linux_webkit::configure_renderer(); // Fix PATH for GUI apps (macOS .app bundles, Linux AppImage, Windows) @@ -1838,8 +1838,13 @@ fn main() { info!("Unsloth desktop app starting"); #[cfg(target_os = "linux")] - if let Some(variable) = webkit_rendering_workaround { - info!("Set {variable}=1 for WebKitGTK compatibility"); + if let Some((variables, reason)) = webkit_rendering_workaround { + let applied = variables + .iter() + .map(|variable| format!("{variable}=1")) + .collect::>() + .join(" "); + info!("{reason}; set {applied} for WebKitGTK compatibility"); } windows_job::initialize(); diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.py index e7afb10500..541ce6cefb 100644 --- a/tests/studio/playwright_heavy_thread.py +++ b/tests/studio/playwright_heavy_thread.py @@ -60,9 +60,12 @@ Playwright, driven headless, with no Tauri IPC layer and no WebKitGTK compositor. Read it as "JavaScriptCore plus WebKit layout", not as "Unsloth Desktop on macOS". -Desktop Linux under Wayland is WORSE than any number this file can produce, and not by a little: -studio/src-tauri/src/linux_webkit.rs sets WEBKIT_DMABUF_RENDERER_FORCE_SHM=1, which forces the -software rendering transport. Everything below runs on a normal compositor path. +Desktop Linux is WORSE than any number this file can produce, and not by a little: +studio/src-tauri/src/linux_webkit.rs drops the webview off the hardware DMA-BUF transport on +Wayland and on NVIDIA under either display server. It forces the shared-memory transport with +WEBKIT_DMABUF_RENDERER_FORCE_SHM=1, or, on Wayland and on old WebKitGTK, disables the renderer +outright with WEBKIT_DISABLE_DMABUF_RENDERER=1, which turns accelerated compositing off for the +whole process. Everything below runs on a normal compositor path. THIS HARNESS MEASURES, IT DOES NOT GATE. It prints the table and exits 0 on any timing. It exits non-zero only when the harness itself is broken: the seed did not land, an element it drives went diff --git a/tests/studio/playwright_research_freeze.py b/tests/studio/playwright_research_freeze.py index e7ed9dd7bc..20e9db3a7e 100644 --- a/tests/studio/playwright_research_freeze.py +++ b/tests/studio/playwright_research_freeze.py @@ -7,8 +7,10 @@ again while closing the research detail pane -- spinner stopped, nothing clickable, force quit. What this measures, and what it cannot: Chromium is not the WebKitGTK webview the desktop app -embeds on Linux, and `studio/src-tauri/src/linux_webkit.rs` forces that webview onto the SHM -software renderer on Wayland, where the frame budget is far tighter than anything measured here. +embeds on Linux, and `studio/src-tauri/src/linux_webkit.rs` takes that webview off the hardware +DMA-BUF transport on Wayland and on NVIDIA under either display server -- onto shared memory, or +off accelerated compositing entirely -- where the frame budget is far tighter than anything +measured here. So an absolute pass here does not prove the reporter's machine is fixed. What transfers is the *work*: long tasks, forced layouts and style recalcs during the stream, and whether the window still takes clicks afterwards. Those are the quantities the fixes move.