Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Let the AppImage E2E use the Retry the failed quant row offers (#10032)
Daniel Han5f82b87200a3
diff --git a/tests/studio/appimage_model_download_webdriver.py b/tests/studio/appimage_model_download_webdriver.pyindex 9ba6b7845b7..46e775e0b14 100644--- a/tests/studio/appimage_model_download_webdriver.py+++ b/tests/studio/appimage_model_download_webdriver.py@@ -96,6 +96,68 @@ def _wait_for(raise AssertionError(f"Timed out waiting for {description}; last result: {last!r}")+# The quant list is fetched once per expanded row, by an effect keyed on+# [repoId, localSource, refreshKey, hfToken]. Its .catch() calls setError and stops:+# there is no automatic retry, by design, and the row offers a Retry button instead.+# So one transient transport blip at the moment the row expands leaves the row showing+# an error for the rest of the run, and waiting longer cannot help -- nothing is still+# in flight. Observed as "Unsloth isn't running -- please relaunch it." rendered inside+# the FLUX.2-klein-4B row while /api/health kept answering for another 49 seconds, on a+# job that fails on roughly three runs in four across unrelated branches.+#+# Clicking Retry is what a user does and what the row is built for. Bounded, and the+# listing error is reported if the retries run out, so a backend that is genuinely+# unreachable still fails the run rather than looping.+_VARIANT_RETRY_ATTEMPTS = 3+_VARIANT_ERROR_TEXT = (+ "const box=[...document.querySelectorAll('div')].find("+ "(d)=>d.className.includes('text-destructive') && "+ "[...d.querySelectorAll('button')].some((b)=>(b.innerText||'').trim()==='Retry'));"+ "return box ? (box.innerText||'').trim() : '';"+)+_VARIANT_RETRY_CLICK = (+ "const box=[...document.querySelectorAll('div')].find("+ "(d)=>d.className.includes('text-destructive') && "+ "[...d.querySelectorAll('button')].some((b)=>(b.innerText||'').trim()==='Retry'));"+ "const b=box && [...box.querySelectorAll('button')].find("+ "(e)=>(e.innerText||'').trim()==='Retry'); if(b)b.click(); return !!b;"+)+++def _wait_for_quantization(+ base: str,+ session_id: str,+ script: str,+ description: str,+ *,+ timeout: float = 15,+) -> Any:+ """_wait_for, plus the row's own Retry button when the listing failed outright."""+ last_error = ""+ for attempt in range(1, _VARIANT_RETRY_ATTEMPTS + 1):+ try:+ return _wait_for(base, session_id, script, description, timeout = timeout)+ except AssertionError:+ error_text = _execute(base, session_id, _VARIANT_ERROR_TEXT) or ""+ if not error_text:+ raise # No listing error on screen, so retrying would prove nothing.+ last_error = error_text+ print(+ f"[appimage-e2e] quant listing failed (attempt {attempt}/"+ f"{_VARIANT_RETRY_ATTEMPTS}): {error_text!r}",+ flush = True,+ )+ if attempt == _VARIANT_RETRY_ATTEMPTS:+ break+ if not _execute(base, session_id, _VARIANT_RETRY_CLICK):+ break # The button went away; let the assertion below carry the text.+ time.sleep(1.0)+ raise AssertionError(+ f"Timed out waiting for {description} after {_VARIANT_RETRY_ATTEMPTS} listing "+ f"attempts. The row reported: {last_error!r}"+ )++def _write_backend_fixture(home: Path, request_log: Path) -> None:fixture_dir = ART_DIR / "fixture"fixture_dir.mkdir(parents = True, exist_ok = True)@@ -156,9 +218,20 @@ def _write_backend_fixture(home: Path, request_log: Path) -> None:self.wfile.write(raw)def do_OPTIONS(self):+ # Recorded like GET and POST. A preflight the browser rejects means the+ # real request is never sent, so without this the request log shows+ # nothing and the failure looks like the frontend never tried.+ record("OPTIONS", urlparse(self.path).path)self.send_response(204)self.send_header("Access-Control-Allow-Origin", "tauri://localhost")- self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-HF-Token")+ # Echo what was asked for. studio/backend/main.py runs CORSMiddleware+ # with allow_headers = ["*"], so a fixed list here is not the product's+ # behaviour but a second copy of it, and it drifted: #8879 began sending+ # two X-Unsloth timezone headers on every authFetch, this list still+ # named three headers, and every authed request in this test has failed+ # its preflight since. Echoing cannot drift again.+ requested = self.headers.get("Access-Control-Request-Headers")+ self.send_header("Access-Control-Allow-Headers", requested or "*")self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")self.end_headers()@@ -638,7 +711,7 @@ def main() -> None:session_id,"const b=[...document.querySelectorAll('button')].find((e)=>(e.innerText||'').trim()==='GGUF'); if(b)b.click(); return !!b;",)- _wait_for(+ _wait_for_quantization(base,session_id,"return [...document.querySelectorAll('button')].some((b)=>(b.innerText||'').includes('Q4_K_M'))",diff --git a/tests/studio/test_appimage_fixture_cors.py b/tests/studio/test_appimage_fixture_cors.pynew file mode 100644index 00000000000..84827dac9da--- /dev/null+++ b/tests/studio/test_appimage_fixture_cors.py@@ -0,0 +1,135 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The AppImage E2E's fake backend has to admit the headers the real one admits.++`AppImage model download E2E` stands up a fixture backend for the webview to talk to.+Its CORS preflight used to answer with a hand-written list of three header names. The+real backend does not: studio/backend/main.py runs CORSMiddleware with+`allow_headers = ["*"]`. A fixed list is therefore a second copy of the product's+policy, and on 2026-08-28 it drifted -- #8879 began sending X-Unsloth-Timezone and+X-Unsloth-Timezone-Offset-Minutes on every authFetch, the list still named three+headers, and the browser rejected the preflight for every authed request in the test.++The visible symptom was nothing like the cause: the row for the model under test+rendered "Unsloth isn't running -- please relaunch it." (a fetch TypeError, tagged by+asTransportFailure), the request log showed no such request because it was never sent,+and the run failed as "Timed out waiting for the Q4_K_M quantization" while+/api/health kept answering. Roughly three runs in four, as a hard gate on every PR.++So these tests read the header names out of the frontend source rather than restating+them, and assert the fixture would admit them.+"""++from __future__ import annotations++import re+import threading+import urllib.request+from http.server import BaseHTTPRequestHandler, HTTPServer+from pathlib import Path++import pytest++REPO = Path(__file__).resolve().parents[2]+AUTH_API = REPO / "studio" / "frontend" / "src" / "features" / "auth" / "api.ts"+FIXTURE = REPO / "tests" / "studio" / "appimage_model_download_webdriver.py"+BACKEND_MAIN = REPO / "studio" / "backend" / "main.py"+++def frontend_request_headers() -> list[str]:+ """Every X-Unsloth-* header the auth layer attaches to an authed request."""+ names = re.findall(r'"(X-Unsloth-[A-Za-z0-9-]+)"', AUTH_API.read_text(encoding = "utf-8"))+ assert names, f"no X-Unsloth-* header constants found in {AUTH_API}; did they move?"+ return sorted(set(names))+++def _preflight(allow_headers_for) -> str:+ """Run one real OPTIONS through http.server and return its Allow-Headers."""+ sent = ",".join(frontend_request_headers() + ["Authorization"])++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_OPTIONS(self):+ self.send_response(204)+ self.send_header("Access-Control-Allow-Origin", "tauri://localhost")+ self.send_header(+ "Access-Control-Allow-Headers",+ allow_headers_for(self.headers.get("Access-Control-Request-Headers")),+ )+ self.end_headers()++ server = HTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = server.serve_forever, daemon = True).start()+ try:+ request = urllib.request.Request(+ f"http://127.0.0.1:{server.server_address[1]}/api/models/gguf-variants",+ method = "OPTIONS",+ )+ request.add_header("Origin", "tauri://localhost")+ request.add_header("Access-Control-Request-Method", "GET")+ request.add_header("Access-Control-Request-Headers", sent)+ with urllib.request.urlopen(request, timeout = 10) as response:+ return (response.headers.get("Access-Control-Allow-Headers") or "").lower()+ finally:+ server.shutdown()+++def blocked_headers(allowed: str) -> list[str]:+ """What a browser would refuse to send, given this Allow-Headers."""+ permitted = {h.strip() for h in allowed.split(",") if h.strip()}+ if "*" in permitted:+ return []+ return [h for h in frontend_request_headers() if h.lower() not in permitted]+++def test_echoing_the_requested_headers_admits_everything_the_frontend_sends():+ allowed = _preflight(lambda requested: requested or "*")+ assert not blocked_headers(allowed), allowed+++def test_the_list_that_broke_it_is_still_detected_as_broken():+ """The bug reproduced, so this file fails if the check stops being able to see it."""+ allowed = _preflight(lambda _requested: "Authorization, Content-Type, X-HF-Token")+ assert blocked_headers(allowed) == [+ "X-Unsloth-Timezone",+ "X-Unsloth-Timezone-Offset-Minutes",+ ], allowed+++def test_the_fixture_echoes_rather_than_naming_headers():+ """A fixed list cannot track `allow_headers = ["*"]`, so the fixture must not carry one."""+ source = FIXTURE.read_text(encoding = "utf-8")+ options = source.split("def do_OPTIONS", 1)+ assert len(options) == 2, "the fixture no longer answers preflights"+ body = options[1].split("def do_GET", 1)[0]+ assert "Access-Control-Request-Headers" in body, (+ "the fixture's preflight no longer echoes the requested headers, so it has gone "+ "back to a hand-written list that will drift from the backend again"+ )+ # Comments stripped first: the block deliberately names the two headers when+ # explaining what drifted, and that history is worth keeping. Only code counts.+ code = "\n".join(line.split("#", 1)[0] for line in body.splitlines())+ for name in frontend_request_headers():+ assert name not in code, (+ f"{name} is hard-coded into the fixture's preflight. Echo "+ f"Access-Control-Request-Headers instead; naming headers is what broke this."+ )+++def test_the_real_backend_still_allows_any_header():+ """The premise. If the product ever narrows this, echoing stops being faithful."""+ source = BACKEND_MAIN.read_text(encoding = "utf-8")+ assert re.search(r"allow_headers\s*=\s*\[\s*\"\*\"\s*\]", source), (+ "studio/backend/main.py no longer allows every request header, so the fixture "+ "echoing the request is no longer a faithful stand-in for it"+ )++[email protected]("name", frontend_request_headers())+def test_each_frontend_header_is_lowercase_safe(name):+ """CORS matching is case-insensitive; the echo path must not depend on casing."""+ allowed = _preflight(lambda requested: (requested or "").upper())+ assert name.lower() in allowed.lower() or "*" in allowed, (name, allowed)